/// <summary> /// Get information about the video/playlist before downloading /// </summary> /// <param name="url"> /// Video/playlist to retrieve information about /// </param> /// <returns> /// Object representing the information of the video/playlist /// </returns> public async Task <DownloadInfo> GetDownloadInfoAsync(string url) { await this.semaphore.WaitAsync(); DownloadInfo info = await InfoService.GetDownloadInfoAsync(this, url); this.semaphore.Release(); return(info); }
private void ProcessDownload(DownloadInfo di) { ActiveDownloads.AddOrUpdate(di.Id, di, (o, n) => di); _downloader.Download(di.Id, di.File.ToSafePath(), di.Source, GetCookieDictionary(di.Cookies), di.DisableTracking, UpdateActiveDownload, ActiveDownloadCompleted ); }
/// <summary> /// Get information about the video/playlist before downloading /// </summary> /// <returns> /// Object representing the information of the video/playlist /// </returns> public async Task <DownloadInfo> GetDownloadInfoAsync() { await this.semaphore.WaitAsync(); DownloadInfo info = await InfoService.GetDownloadInfoAsync(this, downloadTokenSource.Token); this.semaphore.Release(); return(info); }
public override int WriteTo(byte[] Buffer, int StartIndex = 0) { int cursor = StartIndex; cursor += base.WriteTo(Buffer, cursor); cursor += DownloadInfo.WriteTo(Buffer, cursor); return(cursor - StartIndex); }
protected void CancelDownload(DownloadInfo info) { if (_cts.ContainsKey(info.ChannelId)) { _cts[info.ChannelId].Cancel(); _cts[info.ChannelId].Dispose(); } _cts.Remove(info.ChannelId); }
public void OnDownloadStart(DownloadInfo downloadInfo) { Msg = ""; FileSize = GetFileSize(downloadInfo.FileSize); if (string.IsNullOrEmpty(FileName)) { FileName = downloadInfo.Name; } }
public static string DownloadListInfoToXml(DownloadInfo fileListInfo, XmlDocument doc, XmlElement root) { if (fileListInfo == null) { return(""); } XmlElement newChild = doc.CreateElement("DownloadListInfo"); root.AppendChild(newChild); XmlElement element2 = doc.CreateElement("ClientName"); element2.InnerText = fileListInfo.SoftVer.ClientName; newChild.AppendChild(element2); element2 = doc.CreateElement("ClientIp"); element2.InnerText = fileListInfo.SoftVer.ClientIp; newChild.AppendChild(element2); element2 = doc.CreateElement("ClientPort"); element2.InnerText = fileListInfo.SoftVer.ClientPort.ToString(); newChild.AppendChild(element2); element2 = doc.CreateElement("SoftName"); element2.InnerText = fileListInfo.SoftVer.SoftName; newChild.AppendChild(element2); element2 = doc.CreateElement("Version"); element2.InnerText = fileListInfo.SoftVer.Version; newChild.AppendChild(element2); element2 = doc.CreateElement("Force"); element2.InnerText = fileListInfo.SoftVer.Force ? "1" : "0"; newChild.AppendChild(element2); element2 = doc.CreateElement("VerDesc"); element2.InnerText = fileListInfo.SoftVer.VerDesc; newChild.AppendChild(element2); element2 = doc.CreateElement("BserverStr"); element2.InnerText = fileListInfo.SoftVer.BserverStr; newChild.AppendChild(element2); element2 = doc.CreateElement("EnableStr"); element2.InnerText = fileListInfo.SoftVer.EnableStr; newChild.AppendChild(element2); element2 = doc.CreateElement("DisableStr"); element2.InnerText = fileListInfo.SoftVer.DisableStr; newChild.AppendChild(element2); element2 = doc.CreateElement("FilePath"); element2.InnerText = fileListInfo.SoftVer.FilePath; newChild.AppendChild(element2); element2 = doc.CreateElement("StartTime"); element2.InnerText = fileListInfo.SoftVer.StartTime.ToString("yyyyMMddHHmmss"); newChild.AppendChild(element2); element2 = doc.CreateElement("ExpireTime"); element2.InnerText = fileListInfo.SoftVer.ExpireTime.ToString("yyyyMMddHHmmss"); newChild.AppendChild(element2); element2 = doc.CreateElement("Xzbz"); element2.InnerText = fileListInfo.Xzbz.ToString(); newChild.AppendChild(element2); element2 = doc.CreateElement("UpdateFlag"); element2.InnerText = ""; newChild.AppendChild(element2); return(doc.InnerXml); }
public DownloadProgress GetNVSProgress(DownloadInfo info) { try { Log.Info("NVS", "GetNVSProgress->:" + info); if (info == null) { return(null); } DownloadProgress progress = new DownloadProgress(); progress.DId = info.DId; PlayBackForm form1 = NVSManage.Form; var downloader = form1.downloader; if (downloader == null) { progress.Progress = 0; progress.ProgressText = "downloader == null"; progress.IsFinished = false; } else { if (downloader.m_iDLTimeId != -1 && downloader.m_iDLTimeId != info.DId)//当前下载的文件不是客户端申请的,多个客户端下载文件的话。 { progress.Progress = 0; progress.ProgressText = "downloader.m_iDLTimeId != info.DId"; progress.IsFinished = false; } else { progress.Progress = downloader.Progress; progress.ProgressText = downloader.ProgressText; progress.IsFinished = downloader.IsFinished; if (progress.IsFinished) { progress.Url = downloader.GetUrl(NVSManage.RTMP_Host); if (!progress.Url.StartsWith("http")) { Log.Error("NVS", progress.Url); } else { Log.Info("NVS", "GetNVSProgress Finished !!!!!!!!:" + progress); } } } } Log.Info("NVS", "GetNVSProgress<-:" + progress); return(progress); } catch (Exception e) { Log.Error("LocationService.GetNVSProgress", e.ToString()); return(null); } }
/// <summary> /// 取消加载任务 by邓成 /// </summary> /// <param name="_shortURL"></param> public void CancelDownload(string _shortURL) { if (processingDownloads.ContainsKey(_shortURL)) { DownloadInfo info = processingDownloads[_shortURL]; info.onComplete = null; info.onProgressUpdate = null; } }
void openStreamAndDownloadPieces(DownloadInfo info) { if (File.Exists(downlodPath + "\\" + filename)) { File.Delete(downlodPath + "\\" + filename); } //Create file stram to start "making" the file from bits recived FileStream fileStream = File.Open(downlodPath + "\\" + filename, FileMode.Create); downloadBytes = new byte[fileSize]; //list of file pieces List <DownloadSourcePiece> pieces = new List <DownloadSourcePiece>(); //calculate every uploader piece size int pieceSize = fileSize / SourcesIps.Count; int downloadBytesRemaining = fileSize; //delgeate handling downloadEventSchedule(info, false); //start downloading pieces DownloadSourcePiece piece; for (int i = 0; i < SourcesIps.Count; i++) { int current = i; if (i == SourcesIps.Count - 1) { piece = new DownloadSourcePiece(SourcesIps[current], filename, fileSize, pieceSize * current, downloadBytesRemaining, port); //add piece to array pieces.Add(piece); //new thread for piece download piece.downloadTask.Start(); //last piece break; } piece = new DownloadSourcePiece(SourcesIps[current], filename, fileSize, pieceSize * current, pieceSize, port); downloadBytesRemaining -= pieceSize; //add piece to array pieces.Add(piece); //new thread for piece download piece.downloadTask.Start(); } // Wait for all pieces to be downloaded for (int i = 0; i < pieces.Count; i++) { Task.WaitAll(pieces[i].downloadTask); //joining all file pieces together fileStream.Write(pieces[i].pieceBytesArr, 0, pieces[i].pieceBytesArr.Length); } fileStream.Close(); }
private void MainCamera_DownloadReady(Camera sender, DownloadInfo Info) { try { string path = string.Empty; SavePathTextBox.Dispatcher.Invoke((Action) delegate { path = SavePathTextBox.Text; }); MainCamera.DownloadFile(Info, path); } catch (Exception ex) { ShowError(ex); } }
private PlexMovie GetObjectFromIndexWorker(int index) { PlexMovie obj = new PlexMovie(); DownloadInfo dlInfo = getContentDownloadInfo(index); obj.StreamInformation = dlInfo; obj.StreamIndex = index; return(obj); }
private void OnDelVideoDownload(DownloadInfo info) { int index = m_downloadList.FindIndex(item => item.SessionId == info.SessionId); if (index >= 0) { m_videoExport.DelExport(info.SessionId); m_downloadList.RemoveAt(index); } }
private async void MainCamera_DownloadReady(Camera sender, DownloadInfo Info) { try { string path = string.Empty; Invoke((MethodInvoker) delegate { path = SavePathTextBox.Text; }); await MainCamera.DownloadFile(Info, path); } catch (Exception ex) { ShowError(ex); } }
private bool NeedDownLoad(DownloadInfo downloadInfo) { if (File.Exists(downloadInfo.LocalFilePath) && GetFileSize(downloadInfo.LocalFilePath) == downloadInfo.FileSize && string.Equals(GetFileHash(downloadInfo.LocalFilePath), downloadInfo.FileHash, StringComparison.InvariantCultureIgnoreCase)) { return(false); } return(true); }
private void OnProgress(DownloadInfo info) { var mb = Math.Pow(1024, 2); var p = info.Progress.BytesDownloaded / (float)info.FileSize; var d = Math.Floor(info.Progress.BytesDownloaded / mb); var t = Math.Floor(info.FileSize / mb); var progress = $"{Math.Floor(p * 100)}%\t{d} of {t} MB\r"; Console.Write(progress); }
void frmMain_DownloadFileCompletedIndex(AsyncCompletedEventArgs e, int Index) { if (!e.Cancelled) { DownloadInfo diTmp = diDownloadQueue[Index]; diTmp.strStatus = "Done"; diDownloadQueue[Index] = diTmp; UpdateListView(Index); } }
public bool PromptToInstall(DownloadInfo download, ExternalComponent component, string promptText) { if (MessageBox.Show(promptText, MiscResources.DownloadNeeded, MessageBoxButtons.YesNo) == DialogResult.Yes) { var progressForm = formFactory.Create <FDownloadProgress>(); progressForm.QueueFile(download, component.Install); progressForm.ShowDialog(); } return(component.IsInstalled); }
private static void MainCamera_DownloadReady(Camera sender, DownloadInfo Info) { try { Console.WriteLine("Starting image download..."); sender.DownloadFile(Info, ImageSaveDirectory); } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); Error = true; } finally { WaitEvent.Set(); } }
private bool EnqueueDownload(DownloadInfo downloadInfo, bool forceDownload) { if (_queue.Any(x => x.Id == downloadInfo.Id) || ActiveDownloads.ContainsKey(downloadInfo.Id) && !forceDownload) { return(false); } _queue.Enqueue(downloadInfo); return(true); }
private void MainCamera_DownloadReady(Camera sender, DownloadInfo Info) { try { string dir = null; Invoke((Action) delegate { dir = strSavePathTextBox; }); sender.DownloadFile(Info, dir); } catch (Exception ex) { ReportError(ex.Message, false); } }
private static DownloadInfo BuildDownloadInfo(string id, string filePath, Uri url, CookieContainer cookieContainer = null, bool isQueued = true, bool disableTracking = false) { var di = new DownloadInfo(id, filePath, url, isQueued, disableTracking); if (cookieContainer != null) { di.Cookies = cookieContainer.GetCookies(url); } return(di); }
private void RemoveRow(DownloadInfo downloadInfo) { DataRow row = m_DTDownloadInfo.Rows.Find(downloadInfo.SessionId); if (row != null) { m_DTDownloadInfo.Rows.Remove(row); RecordCount = m_DTDownloadInfo.Rows.Count; } }
/// <summary> /// 下载文件 /// </summary> /// <param name="progressAction"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task DownloadFileAsync(Action <ProgressInfo> progressAction, CancellationToken cancellationToken = default) { if (IsDownloaded) { return; } SpeedCalculator speedCalculator = new SpeedCalculator(); ProgressInfo progressInfo = new ProgressInfo(); bool isCompleted = false; speedCalculator.Updated += async(h) => { progressInfo.AverageSpeed = speedCalculator.AverageSpeed; progressInfo.CurrentValue = speedCalculator.CurrentValue; progressInfo.Speed = speedCalculator.Speed; progressInfo.Percentage = DownloadInfo.Percentage; progressInfo.TargetValue = DownloadInfo?.Size; progressAction.Invoke(progressInfo); var count = DownloadInfo.Count(m => m.Size == 0); //Console.WriteLine("count " + count + " size " + DownloadInfo.Size + " read size " + DownloadInfo.TotalReadBytes); if (isCompleted) { speedCalculator.Stop(); } else { await SaveDownloadInfoAsync(); } }; foreach (var segment in DownloadInfo) { if (segment.TotalReadBytes != 0 && segment.TotalReadBytes >= segment.Size) { continue; } var task = DownloadSegmentFileAsync(segment, (r, percentage) => { speedCalculator.CurrentValue += r; }, cancellationToken); FileSegmentaionTasks.Add(task); } speedCalculator.Start(); await FileSegmentaionTasks.StartAndWaitAllThrottled(MaxThreadCount); var errorCount = await CheckDownloadInfoAsync(speedCalculator, cancellationToken); ///错误数量 if (errorCount == 0) { await ReconstructSegmentsAsync(); await CompleteAsync(true); } isCompleted = true; }
public bool ExportEditedVideo(string savePath) { //VideoStatusInfo videoStatusInfo = Framework.Container.Instance.VideoPlayService.GetPlayStatus(m_player.HWnd); //List<VideoSection> section = GetAllSection(); //if (section.Count > 0) //{ //DateTime start = StartTime; //DateTime end = new DateTime(0).AddMilliseconds(section[0].endTime); //string fileName = "";// Framework.Environment.VideoSavePath + @"\剪辑视频" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".h264"; //using (SaveFileDialog dlg = new SaveFileDialog()) //{ // dlg.InitialDirectory = Framework.Environment.VideoSavePath; // dlg.FileName = string.Format("导出视频_{0}_{1}", CurrFile.TaskUnitName.Replace('.', '_'), DateTime.Now.ToString("yyyyMMddHHmmss") + ".h264"); // dlg.Filter = "*.*|*.*"; // if (dlg.ShowDialog() != DialogResult.OK) // { // return false; // } // fileName = dlg.FileName; //} System.IO.FileInfo fi = new System.IO.FileInfo(savePath); if (fi.Extension.ToLower() != ".h264") { savePath += ".h264"; } DownloadInfo downloadInfo = new DownloadInfo() { VideoTaskUnitID = CurrFile.TaskUnitID, IsDownloadAllFile = false, LocalSaveFilePath = savePath, StartTime = StartTime, EndTime = EndTime, }; try { downloadInfo.SessionId = Framework.Container.Instance.VideoDownloadService.StartDownload(downloadInfo); if (downloadInfo.SessionId > 0) { //Framework.Container.Instance.EvtAggregator.GetEvent<NavigateEvent>().Publish(UIFuncItemInfo.SHOWDOWNLOADLIST); Framework.Container.Instance.EvtAggregator.GetEvent <AddVideoDownloadEvent>().Publish(downloadInfo); return(true); } } catch (SDKCallException ex) { SDKCallExceptionHandler.Handle(ex, "导出视频", true); } //} return(false); }
private void HandleDownload(BackgroundTransferRequest transferRequest, DownloadInfo info, bool isAddQueue) { transferRequest.TransferStatusChanged += (o, e) => { switch (e.Request.TransferStatus) { case TransferStatus.Completed: if (e.Request.StatusCode == 200 || e.Request.StatusCode == 206) { DownloadCompleted(info); BackgroundTransferService.Remove(e.Request); e.Request.Dispose(); } break; case TransferStatus.WaitingForWiFi: case TransferStatus.WaitingForNonVoiceBlockingNetwork: info.DownloadState = DownloadState.WaitingForWiFi; Utils.TileUtils.CreateBasicToast("需要在WiFi环境下才能下载"); break; case TransferStatus.WaitingForExternalPower: case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode: info.DownloadState = DownloadState.WaitingForExternalPower; Utils.TileUtils.CreateBasicToast("需要外接电源才能下载"); break; default: break; } }; transferRequest.TransferProgressChanged += (o, e) => { DownloadProgress(e.Request, info); }; if (isAddQueue) { transferRequest.Method = "GET"; info.RequestId = transferRequest.RequestId; try { if (BackgroundTransferService.Find(info.RequestId) == null) { BackgroundTransferService.Add(transferRequest); } } catch (Exception ex) { _isDownloading = false; DownloadFailture(info, ex.Message); } } }
private void UpdateList(bool silent) { DownloadExtensionIndex(); DownloadInfo dlg = new DownloadInfo(); dlg.silent = silent; dlg.ShowDialog(); FilterList(); _settings.LastUpdate = DateTime.Now; _settings.Save(); }
private void MainCamera_DownloadReady(Camera sender, DownloadInfo Info) { try { string dir = null; SavePathTextBox.Dispatcher.Invoke((Action) delegate { dir = SavePathTextBox.Text; }); sender.DownloadFile(Info, dir); MainProgressBar.Dispatcher.Invoke((Action) delegate { MainProgressBar.Value = 0; }); } catch (Exception ex) { ReportError(ex.Message, false); } }
/// <summary> /// Get information about the video/playlist before downloading /// </summary> /// <param name="url"> /// Video/playlist to retrieve information about /// </param> /// <returns> /// Object representing the information of the video/playlist /// </returns> public async Task <DownloadInfo> GetDownloadInfoAsync(string url) { await this.semaphore.WaitAsync(); await this.UpdateExecutable(); DownloadInfo info = await InfoService.GetDownloadInfoAsync(this, url, downloadTokenSource.Token); this.semaphore.Release(); return(info); }
/// <summary> /// 加载任务超时处理 by吴江 /// </summary> /// <param name="_info"></param> /// <param name="_www"></param> protected void DownloadTimeout(DownloadInfo _info, WWW _www) { Debug.LogError("加载 " + _info.shortURL + ", 超时."); if (_info.onComplete != null) { _info.onComplete(null, EResult.TimeOut); } processingDownloads.Remove(_info.shortURL); --downloadThreads; }
private void buttonDownload_Click(object sender, EventArgs e) { try { var downInfo = new DownloadInfo() { Url = textBoxUrl.Text, DestinationFileName = textBoxDestFile.Text }; downInfo.OnProgressDownloading += DownInfo_OnProgressDownloading; downInfo.OnInitProgressDownload += DownInfo_OnInitProgressDownload; new DownloadManager().Download(new List<DownloadInfo>() { downInfo }); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void btnDownload_Click(object sender, EventArgs e) { liDonwloadList.Add(strDownloadLinks[intCurrentSelectedDownloadLinks]); string filename = liDonwloadList[intDownloadListCount].strVideoTitle; string extension = liDonwloadList[intDownloadListCount].strVideoType.Replace("*", ""); SaveFileDialog sfdSave = new SaveFileDialog(); sfdSave.DefaultExt = liDonwloadList[intDownloadListCount].strVideoType; sfdSave.Filter = liDonwloadList[intDownloadListCount].strVideoType + "|" + liDonwloadList[intDownloadListCount].strVideoType; if (sfdSave.ShowDialog() == DialogResult.OK) { DownloadInfo diTmp = new DownloadInfo(); diTmp.intDownloadPercentage = 0; diTmp.strFilePath = sfdSave.FileName; diTmp.strTimeEplased = "00:00:00"; diTmp.strStatus = "Pending..."; diDownloadQueue.Add(new DownloadInfo()); diDownloadQueue[intDownloadListCount] = diTmp; DownloadQueue.Add(new clsDownloader(intDownloadListCount)); DownloadQueue[intDownloadListCount].DownloadFileCompletedIndex += new clsDownloader.OnDownloadFileCompletedIndexEventHandler(frmMain_DownloadFileCompletedIndex); DownloadQueue[intDownloadListCount].DownloadProgressChangedIndex += new clsDownloader.OnDownloadProgressChangedIndexEventHandler(frmMain_DownloadProgressChangedIndex); DownloadQueue[intDownloadListCount].DownloadFileAsync(new Uri(liDonwloadList[intDownloadListCount].strVideoLink), diTmp.strFilePath); ListViewItem lviDownload = new ListViewItem(filename + extension); lviDownload.SubItems.Add(liDonwloadList[intDownloadListCount].strVideoSize); lviDownload.SubItems.Add("0%"); lviDownload.SubItems.Add(diTmp.strTimeEplased); lviDownload.SubItems.Add(diTmp.strStatus); lviDownload.SubItems.Add(diTmp.strFilePath); lviDownload.SubItems.Add(liDonwloadList[intDownloadListCount].strQuality); intDownloadListCount++; lvwDonwloadList.Items.Add(lviDownload); } else { return; } tcMain.SelectedIndex = 1; //string newFilename = CheckForDupFileName(filename, extension); //LinkInfo liTmp = liDonwloadList[intDownloadListCount]; //liTmp.strVideoTitle = newFilename; //liDonwloadList[intDownloadListCount] = liTmp; }
/// <summary> /// Creates a list of DownloadInfos from a GitHub release /// </summary> /// <param name="modInfo">The mod to generate the list from</param> /// <returns>A list of one or more DownloadInfos for the most recent release of the selected repository</returns> private static List<DownloadInfo> GetDownloadInfo(ModInfo modInfo) { var htmlDoc = new HtmlWeb().Load(GetPathToReleases(modInfo.ModURL)); htmlDoc.OptionFixNestedTags = true; var releases = new List<DownloadInfo>(); var nodesrel = htmlDoc.DocumentNode.SelectNodes("//*[@class='release label-latest']/div[2]/ul/li/a"); var nodespre = htmlDoc.DocumentNode.SelectNodes("//*[@class='release label-prerelease'][1]/div[2]/ul/li/a"); if (nodesrel != null) { foreach (var s in nodesrel) { var url = "https://github.com" + s.Attributes["href"].Value; if (!url.Contains("releases")) continue; var dInfo = new DownloadInfo { DownloadURL = url, Filename = GetUrlParts(url).Last(), Name = Path.GetFileNameWithoutExtension(GetUrlParts(url).Last()) }; releases.Add(dInfo); } } if (nodespre != null) { foreach (var s in nodespre) { var url = "https://github.com" + s.Attributes["href"].Value; if (!url.Contains("releases")) continue; var versionNode = htmlDoc.DocumentNode.SelectSingleNode("//*[@class='release label-prerelease']/div[1]/ul/li[1]/a/span[2]").InnerText; var dInfo = new DownloadInfo { DownloadURL = url, Filename = GetUrlParts(url).Last(), Name = "Pre-release: " + versionNode + ": " + Path.GetFileNameWithoutExtension(GetUrlParts(url).Last()) }; releases.Add(dInfo); } } return releases; }
public Mpeg2DvrmsDownload() { DownloadInfo = new DownloadInfo(this); }
/// <summary> /// Saves the download status to the database. /// </summary> /// <param name = "downloadInfo"></param> /// <remarks> /// Will cancel the download if the download record disappears. /// </remarks> private static void SaveDownloadQueueStatus(DownloadInfo downloadInfo) { if (!_downloadDataChanged) return; if (downloadInfo == null || downloadInfo.Download == null) return; var download = downloadInfo.Download; using (var udm = UtilityDataModel.NewContext()) { try { udm.Attach(download); } catch (InvalidOperationException) { // download is gone... stop the presses! downloadInfo.Downloader.Cancel(); return; } download.LastDownloadUpdate = DateTime.Now; udm.SaveAndRefreshDataModel(udm.Downloads); _downloadDataChanged = false; udm.Detach(download); } }
public void Download(Package package, DownloadInfo downloadInfo) { Download(downloadInfo.id, downloadInfo.url, downloadInfo.key, package.title, package.publisher.label, package.category.label, null); }
public byte[] Download(string url, string parameters, DownloadProgressHandler progressCB) { // Ensure flag set correctly. allDone.Reset(); // Get the URI from the command line. Uri httpSite = new Uri(url); // Create the request object. WebRequest req = WebRequest.Create(httpSite); req.Method = "POST"; req.ContentType = @"application/x-www-form-urlencoded"; //byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters); //req.ContentLength = bytes.Length; // Create the state object. DownloadInfo info = new DownloadInfo(); // Put the request into the state object so it can be passed around. info.Request = req; // Assign the callbacks info.ProgressCallback += progressCB; // Issue the async request. IAsyncResult r = (IAsyncResult)req.BeginGetResponse(new AsyncCallback(ResponseCallback), info); // Wait until the ManualResetEvent is set so that the application // does not exit until after the callback is called. allDone.WaitOne(); // Pass back the downloaded information. if (info.useFastBuffers) return info.dataBufferFast; else { byte[] data = new byte[info.dataBufferSlow.Count]; for (int b = 0; b < info.dataBufferSlow.Count; b++) data[b] = (byte)info.dataBufferSlow[b]; return data; } }
public void LoadDownloadList() { var storageContainer = StorageManager.RequiredCurrentStorageContainer; if (!storageContainer.FileExists(downloadListPath)) return; using (var stream = storageContainer.OpenFile(downloadListPath, FileMode.Open)) { var definition = (DownloadListDefinition) downloadListSerializer.Deserialize(stream, null); if (ArrayHelper.IsNullOrEmpty(definition.Entries)) return; for (int i = 0; i < definition.Entries.Length; i++) { var downloadInfo = new DownloadInfo(definition.Entries[i].Uri) { LastModified = definition.Entries[i].LastModified }; downloadInfoCollection.Add(downloadInfo); } } }
DownloadInfo GetDownloadInfo(WebResource resource) { if (downloadInfoCollection.Contains(resource.AbsoluteUri)) { return downloadInfoCollection[resource.AbsoluteUri]; } else { var downloadInfo = new DownloadInfo(resource.AbsoluteUri); downloadInfoCollection.Add(downloadInfo); return downloadInfo; } }
public void UpdateStatus(DownloadInfo downloadInfo, DateTime utcNow) { BytesDownloaded = downloadInfo.BytesRead; UpdatedOn = utcNow; }
private bool CheckFile(object triggerMessage, FileTypes fileType, string fileName) { if (!string.IsNullOrEmpty(Path.GetDirectoryName(fileName))) throw new ArgumentException("FileName should be without path"); string fileTypeFolder = Path.Combine(this.main.FileStoragePath, fileType.ToString()); Directory.CreateDirectory(fileTypeFolder); string filePath = Path.Combine(fileTypeFolder, fileName); if (File.Exists(filePath)) return true; CleanUpDownloadInfo(); this.log.Info("Missing file {0} of type {1}", fileName, fileType); string downloadId; lock (this.downloadInfos) { if (this.downloadInfos.Any(x => x.Value.FileType == fileType && x.Value.FileName == fileName)) { // Already in the process to be downloaded this.log.Info("Already in the process of being downloaded"); return false; } var downloadInfo = new DownloadInfo(this.main.FileStoragePath, fileType) { TriggerMessage = triggerMessage, FileName = fileName, FinalFilePath = filePath }; this.downloadInfos.Add(downloadInfo.Id, downloadInfo); if (Directory.Exists(downloadInfo.TempFolder)) // Empty it Directory.Delete(downloadInfo.TempFolder, true); downloadId = downloadInfo.Id; } // Request the file SendMessage(new FileRequest { DownloadId = downloadId, Type = fileType, FileName = fileName }); return false; }