download method

Future<DownloadManagerResponse> download({
  1. required DownRequire req,
  2. int tokenIsolate = 0,
})

Implementation

Future<DownloadManagerResponse> download({
  required DownRequire req,
  int tokenIsolate = 0,
}) async {
  await _mutex.acquire();
  try {
    SelectDownload selectDow = checkDownload(req.tokenDownload);
    if (selectDow.exists)
      return DownloadManagerResponse(
        tokenDownload: req.tokenDownload,
        status: true,
      );
    bool freeIsolate = false;
    late TaskDownload selectTask;
    if (tokenIsolate > 0) {
      if (!_task.containsKey(tokenIsolate))
        return DownloadManagerResponse(
          tokenDownload: req.tokenDownload,
          status: false,
        );
      selectTask = _task[tokenIsolate]!;
      if (selectTask.statusIsolate != StatusIsolateType.freeIsolate)
        return DownloadManagerResponse(
          tokenDownload: req.tokenDownload,
          status: false,
        );
      freeIsolate = true;
    } else {
      for (int isolate in _task.keys) {
        TaskDownload ts = _selectIsolate(isolate).task!;
        if (ts.statusIsolate == StatusIsolateType.freeIsolate) {
          freeIsolate = true;
          tokenIsolate = isolate;
          ts.statusIsolate = StatusIsolateType.waiting;
          selectTask = ts;
          break;
        }
      }
    }
    if (!freeIsolate)
      return DownloadManagerResponse(
        status: false,
        tokenDownload: req.tokenDownload,
        error: ErrorIsolate.limit,
      );

    if (req.tokenDownload == 0) {
      req.tokenDownload = ManSettings().token();
    }
    DownloadManagerResponse response = DownloadManagerResponse(
      tokenDownload: req.tokenDownload,
      status: true,
    );

    selectTask.sendPort.send(
      ManMessagePort(
        action: 'add',
        download: ManReques(
          setting: req.setting,
          url: req.url,
          fileName: req.fileName,
          extension: req.extension,
          tokenDownload: req.tokenDownload,
        ),
      ),
    );
    _downloadsTask.addAll({
      req.tokenDownload: TokenDownloadStatus(
        isolateToken: tokenIsolate,
        status: DownloadType.waiting,
      ),
    });
    _controller.sink.add(
      ControllerType(
        tokenIsolate: selectTask.status.tokenIsolate,
        status: IsolateType.busyIsolate,
        tokenDownload: req.tokenDownload,
      ),
    );
    return response;
  } finally {
    _mutex.release();
  }
}