download method

Future<DownloadManagerResponse> download({
  1. required DownRequire req,
})

Implementation

Future<DownloadManagerResponse> download({required DownRequire req}) async {
  await _mutex.acquire();
  try {
    SelectDownload selectDow = checkDownload(req.tokenDownload);
    if (selectDow.exists)
      return DownloadManagerResponse(
        tokenDownload: req.tokenDownload,
        status: true,
      );

    bool freeIsolate = false;
    int tokenIsolate = 0;
    late TaskDownload selectTask;
    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,
      ),
    );
    return response;
  } finally {
    _mutex.release();
  }
}