public void CheckMalware(DiarioFileAnalysis file) { if (file == null) { throw new ArgumentNullException(nameof(file)); } Task.Factory.StartNew(async() => await CheckFile(file), file.CancelToken, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler, this.currentScheduler); }
private async Task CheckFile(DiarioFileAnalysis file) { try { if (file.Retries > MaxRetries || file.CancelToken.IsCancellationRequested) { file.Error = file.Retries > MaxRetries ? "Too many retries. Try again later" : "Operation canceled"; file.Callback(file); } else { byte[] fileContent = null; if (String.IsNullOrWhiteSpace(file.Sha256Hash)) { using (SHA256Managed sha256 = new SHA256Managed()) { fileContent = File.ReadAllBytes(file.FilePath); file.Sha256Hash = BitConverter.ToString(sha256.ComputeHash(fileContent)).Replace("-", "").ToLowerInvariant(); } } BaseSDK.ApiResponse <dynamic> diarioResponse = this.sdk.Search(file.Sha256Hash); if (diarioResponse != null) { if (diarioResponse.Error != null) { if (diarioResponse.Error?.Code == FileNotFoundErrorCode) { diarioResponse = this.sdk.Upload(fileContent ?? File.ReadAllBytes(file.FilePath), Path.GetFileName(file.FilePath)); file.Retries++; await Task.Delay(DelayBetweenRetries); this.CheckMalware(file); } else { file.Error = diarioResponse.Error.Message; file.Callback(file); } } else if (diarioResponse.Data?["status"] == Analyzed) { file.Prediction = DiarioSDKNet.Diario.GetPredictonFromString(diarioResponse.Data["prediction"]); file.Completed = true; file.Callback(file); } else if (diarioResponse.Data?["status"] == Processing || diarioResponse.Data?["status"] == Queued) { file.Retries++; await Task.Delay(DelayBetweenRetries); this.CheckMalware(file); } else if (diarioResponse.Data?["status"] == Failed) { file.Error = "The analysis failed"; file.Prediction = DiarioSDKNet.Diario.Prediction.Unknown; file.Callback(file); } else { file.Error = "Unknown status"; file.Prediction = DiarioSDKNet.Diario.Prediction.Unknown; file.Callback(file); } } else { file.Error = "No response from DIARIO service"; file.Callback(file); } } } catch (Exception e) { file.Error = e.Message; file.Completed = false; file.Callback(file); } }