예제 #1
0
        public Download(HtmlDocument document, string key, string url, string filename)
        {
            this.url = url;
            this.key = key;
            this.document = document;
            target = Path.Combine(Path.GetTempPath(), filename);
            if (File.Exists(target))
                status = DownloadStatus.DOWNLOADED;
            else
                status = DownloadStatus.AVAILABLE;

            downloadBGWorker = new BackgroundWorker()
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

            downloadBGWorker.DoWork += RunDownload;
            downloadBGWorker.ProgressChanged += UpdateProgress;
            downloadBGWorker.RunWorkerCompleted += DownloadFinished;

            extractBGWorker = new BackgroundWorker();

            extractBGWorker.DoWork += DoExtraction;
            extractBGWorker.RunWorkerCompleted += ExtractionFinished;
        }
        public DownloadItem Add(EpisodeWithDownloadSettings ep, string template, string downloadpath,DownloadStatus status=DownloadStatus.Queue)
        {
            DownloadItem dinfo = null;
            lock (_downloadslock)
            {
                dinfo = new DownloadItem(ep, template, downloadpath, this, status);
                dinfo.Index = cnt++;
                dinfo.OnProgress += ((a) =>
                {
                    if (OnProgress != null)
                        OnProgress(a);
                });

                dinfo.OnFinish += ((a) =>
                {
                    Save();
                    CheckForDownload();
                });
                lock (_downloadslock)
                {
                    _downloads.Add(dinfo);
                }
            }
            CheckForDownload();
            return dinfo;
        }
예제 #3
0
        public void NotifyStatusByAccountId(int accountId, DownloadStatus status, string message)
        {
            if (InvokeRequired)
            {
                this.Invoke(new Action(() => NotifyStatusByAccountId(accountId, status, message)));
                return;
            }
            if(status == DownloadStatus.CHECK_UNEXPECTED_PAGE)
            {
                CheckUnExpectedPage();
                return;
            }

            label_see_what_happen.Visible = downloadController.IsDownloadUnExpectedPage(account);
            string msg = DownloadStatusUtility.StatusToString(status);
            if (status == DownloadStatus.DONE)
            {
                label_status.Text = message; // num of downloaded
                if (uc_parent is UC_LocalContacts)
                {
                    ((UC_LocalContacts)uc_parent).NotifyNewContactAdded();
                }
            }
            else
            {
                label_status.Text = msg + message; // change status text
            }
        }
예제 #4
0
 public async void NotifyStatusByAccountId(int accountId, DownloadStatus status, object data)
 {
     await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         label_status.Text = status + " - " + data.ToString();
     });
 }
예제 #5
0
 public FileModel(string filename, string pathToDownload, string size, string serialName, IOneFileDownLoader oneFileDownLoader,DownloadStatus downloadStatus=DownloadStatus.NotStarted)
 {
     this.oneFileDownLoader = oneFileDownLoader;
     PathToDownload = pathToDownload;
     Size = size;
     SerialName = serialName;
     FileName = filename;
     DownloadStatus = downloadStatus;
 }
예제 #6
0
 public static string StatusToString(DownloadStatus status)
 {
     switch (status)
     {
         case DownloadStatus.INFORM:
             return string.Empty;
         case DownloadStatus.DONE:
             return resourceLoader.GetString("download_done");
         case DownloadStatus.PROCESSING:
             return resourceLoader.GetString("download_processing");
         case DownloadStatus.LOW_CONNECTION:
             return resourceLoader.GetString("connection_low");
         case DownloadStatus.LOST_CONNECTION:
             return resourceLoader.GetString("connection_lost");
         case DownloadStatus.UNEXPECTED_PAGE:
             return resourceLoader.GetString("unexpected_page");
         case DownloadStatus.ACCOUNT_SUSPENDED:
             return resourceLoader.GetString("account_suspended");
         case DownloadStatus.TWO_STEPS_VALIDATION:
         case DownloadStatus.TWO_STEPS_VALIDATION_MANUAL:
             return resourceLoader.GetString("two_steps_validation");
         case DownloadStatus.UNKNOWN_TYPE:
             return resourceLoader.GetString("unknown_type");
         case DownloadStatus.WRONG_USERNAME_OR_PASSWORD:
             return resourceLoader.GetString("wrong_username_or_password");
         case DownloadStatus.CONNECTION_TIME_OUT:
             return resourceLoader.GetString("connection_time_out");
         case DownloadStatus.DATABASE_ERROR:
             return resourceLoader.GetString("database_error");
         case DownloadStatus.EXCEED_MAXIMUM_LIMIT_CONTACT:
             return string.Format(resourceLoader.GetString("exceed_max_limit_contact"), ContactDB.MAX_LIMITATION);
         case DownloadStatus.EXCEED_CURRENT_LIMIT_CONTACT:
             return string.Format(resourceLoader.GetString("exceed_max_limit_contact"), ContactDB.MAX_LIMITATION);
         case DownloadStatus.USER_CANCEL:
             return resourceLoader.GetString("user_cancel");
         case DownloadStatus.ACCOUNT_BLOCKED:
             return resourceLoader.GetString("account_blocked");
         case DownloadStatus.CONTINUE_LOGIN:
             return resourceLoader.GetString("continue_login_manual");
         case DownloadStatus.ERROR_SENDING_REQUEST:
             return resourceLoader.GetString("error_sending_request");
         case DownloadStatus.ERROR_NETWORK:
             return resourceLoader.GetString("network_error");
         case DownloadStatus.ERROR_365:
             return resourceLoader.GetString("office365_error");
         case DownloadStatus.LOADING:
             return resourceLoader.GetString("page_loading");
         case DownloadStatus.WAIT_LOADING:
             return resourceLoader.GetString("wait_loading");
         case DownloadStatus.SERVICE_UNAVAILABLE:
             return resourceLoader.GetString("service_unavailable");
         case DownloadStatus.ACCOUNT_PROTECTED:
             return "Can't verify your account. Your account is protected.";
     }
     return string.Empty;
 }
예제 #7
0
파일: ISMRecorder.cs 프로젝트: TomoNag/Tomo
        public void ErrorMessage(string text, DownloadStatus status = DownloadStatus.Error)
        {
            downloadfile.DownloadStatus = status;
            this.InvokeOnUiThreadIfRequired(() => this.Close());

            if (showerror == true)
            {
                showerror = false;
                System.Windows.Forms.MessageBox.Show(new Form { TopMost = true }, text + "(" + downloadfile.Title + ")");
            }
        }
        public System.Threading.Tasks.Task Download()
        {
            return System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    Status = DownloadStatus.Loading;
                    OnChangedTaskStatus(new EventArgs());
                    var tmpFile = new System.IO.FileInfo(System.IO.Path.GetTempFileName());
                    try
                    {
                        var hashBuilder = new StringBuilder();
                        using (var fileStrm = tmpFile.Open(System.IO.FileMode.Open))
                        using (var imgStrm = ImageInfo.GetStream())
                        {
                            var buff = new byte[1024];
                            var buffLen = 0;
                            while ((buffLen = imgStrm.Read(buff, 0, buff.Length)) > 0)
                                fileStrm.Write(buff, 0, buffLen);

                            fileStrm.Seek(0, System.IO.SeekOrigin.Begin);
                            foreach (var chr in _hashMaker.ComputeHash(fileStrm))
                                hashBuilder.AppendFormat("{0:X2}", chr);
                        }

                        HashText = hashBuilder.ToString();
                        DownloadedTempImageFile = tmpFile;
                        var imgFile = new System.IO.FileInfo(_container.Setting.ImageSaveDirectory.FullName + "\\" + HashText + ".jpg");
                        if (_container.Setting.ImageHashList.Add(HashText) && !imgFile.Exists)
                        {
                            imgFile = tmpFile.CopyTo(imgFile.FullName);
                            Status = DownloadStatus.Loaded;
                            DownloadedImageFile = imgFile;
                            OnChangedTaskStatus(new EventArgs());
                        }
                        else
                        {
                            Status = imgFile.Exists ? DownloadStatus.Loaded : DownloadStatus.Deleted;
                            DownloadedImageFile = imgFile.Exists ? imgFile : null;
                            OnChangedTaskStatus(new EventArgs());
                        }
                    }
                    catch (Exception)
                    {
                        Status = DownloadStatus.Failed;
                        OnChangedTaskStatus(new EventArgs());
                    }
                    finally
                    {
                        if (tmpFile.Exists)
                            tmpFile.Delete();
                    }
                });
        }
예제 #9
0
        public static bool IsFinalState(DownloadStatus status)
        {
            switch (status)
            {
            case DownloadStatus.Finished:
            case DownloadStatus.Canceled:
            case DownloadStatus.Error:
                return(true);

            default:
                return(false);
            }
        }
 void StartEstimate()
 {
     estimationTotalSize = 0;
     estimationDownloads = 0;
     zoomLevel           = zoomLevelMin;
     for (int k = 0; k < downloads.Length; k++)
     {
         downloads [k].busy    = false;
         downloads [k].retries = 0;
     }
     progressTileCount = 0;
     status            = DownloadStatus.Estimating;
 }
        public DownloadableFile(string url, AsyncSaveHandler downloadType)
        {
            var videoId = string.Empty;

            if (!YoutubeClient.TryParseVideoId(url, out videoId) | !youtubeClient.CheckVideoExistsAsync(videoId).Result)
            {
                throw new SystemException("In order to download the file, it must come from YouTube");
            }

            this.videoId = videoId;
            DoAsyncSave  = downloadType;
            status       = DownloadStatus.Waiting;
        }
예제 #12
0
        public void ClearDownloads(DownloadStatus toClear = DownloadStatus.All)
        {
            for (int i = downloads.Count - 1; i >= 0; i--)
            {
                Download download = downloads[i];

                if (!toClear.HasFlag(download.Status))
                {
                    continue;
                }
                RemoveDownload(download);
            }
        }
예제 #13
0
        private void OnEnable()
        {
            elements       = new ElementData[0];
            downloadQueue  = new Queue <BundleData> ();
            assetBundles   = new Dictionary <uint, AssetBundle> ();
            assetPaths     = new Dictionary <uint, string> ();
            downloadStatus = DownloadStatus.Idle;

            // TODO: Move the following block of code into a lua bridge
            Database.OnItemFindRequest += FindItem;

            Instance = this;
        }
예제 #14
0
        public void ErrorMessage(string text, DownloadStatus status = DownloadStatus.Error)
        {
            downloadfile.DownloadStatus = status;
            this.InvokeOnUiThreadIfRequired(() => this.Close());

            if (showerror == true)
            {
                showerror = false;
                MessageBox.Show(new Form {
                    TopMost = true
                }, text + "(" + downloadfile.Title + ")");
            }
        }
예제 #15
0
        private void downloadStatusCallback(string uri, int size, object obj)
        {
            var file_seg   = (EmiliaFileSegment)obj;
            var status_seg = new EmiliaFileStatusSegment
            {
                ArticleIndex = file_seg.ArticleIndex,
                DownloadSize = size,
                Index        = file_seg.Index
            };

            DownloadStatus?.Invoke(null, status_seg);
            dispatcher_dictionary[file_seg.SeriesIndex].DownloadStatus.Invoke(status_seg);
        }
 private void btnCancelDownload_Click(object sender, EventArgs e)
 {
     if (!cancellationSource.IsCancellationRequested)
     {
         var res = MessageBox.Show("Are you sure you want to cancel downloading the video",
                                   "Cancel Download?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
         if (res == DialogResult.Yes)
         {
             Status = DownloadStatus.Cancelled;
             cancellationSource.Cancel();
         }
     }
 }
예제 #17
0
        public static string ChooseIcon(DownloadStatus downloadStatus)
        {
            switch (downloadStatus)
            {
            case DownloadStatus.QUEUED:
                return(FontAwesome.Clock);

            case DownloadStatus.PAUSED:
                return(FontAwesome.Pause);

            case DownloadStatus.DOWNLOADING:
                return(FontAwesome.Download);

            case DownloadStatus.FETCHING:
                return(FontAwesome.LoadingSpinner);

            case DownloadStatus.PP_QUEUED:
                break;

            case DownloadStatus.LOADING_PARS:
                return(FontAwesome.LoadingSpinner);

            case DownloadStatus.VERIFYING_SOURCES:
                break;

            case DownloadStatus.REPAIRING:
                break;

            case DownloadStatus.VERIFYING_REPAIRED:
                break;

            case DownloadStatus.RENAMING:
                break;

            case DownloadStatus.UNPACKING:
                break;

            case DownloadStatus.MOVING:
                return(FontAwesome.ArrowRight);

            case DownloadStatus.EXECUTING_SCRIPT:
                break;

            case DownloadStatus.PP_FINISHED:
                break;

            default:
                throw new ArgumentOutOfRangeException("downloadStatus", downloadStatus, null);
            }
            return(FontAwesome.QuestionMark);
        }
예제 #18
0
            private async Task StartDownloadAsync()
            {
                Status = DownloadStatus.Downloading;
                MyLogger.Assert(fileStream != null && resumableUri != null);
                try
                {
                    if (!await CreateResumableDownloadAsync())
                    {
                        Status = DownloadStatus.ErrorNeedRestart; MessageAppended?.Invoke("Error create resumable download async"); return;
                    }
                    var fileSize = bytesReceivedSoFar + serverStreamLength;
                    MyLogger.Log($"File size = {fileSize}");
                    fileStream.Position = bytesReceivedSoFar;
                    int chunkSize = MinChunkSize;
                    for (; bytesReceivedSoFar != fileSize;)
                    {
                        DateTime startTime  = DateTime.Now;
                        var      bufferSize = (int)Math.Min(chunkSize, fileSize - bytesReceivedSoFar);
                        if (pauseRequest)
                        {
                            Status = DownloadStatus.Paused;
                            return;
                        }
                        var bytesRead = await DoResumableDownloadAsync(bufferSize);

                        if (Status == DownloadStatus.ErrorNeedResume)
                        {
                            MessageAppended?.Invoke($"Failed! Chunk range: {bytesReceivedSoFar}-{bytesReceivedSoFar + bufferSize - 1}");
                            return;
                        }
                        MyLogger.Assert(Status == DownloadStatus.Downloading && bytesRead != -1);
                        bytesReceivedSoFar += bytesRead;
                        if ((DateTime.Now - startTime).TotalSeconds < 0.2)
                        {
                            chunkSize = (int)Math.Min((long)chunkSize + chunkSize / 2, int.MaxValue);
                        }
                        else
                        {
                            chunkSize = Math.Max(MinChunkSize, chunkSize / 2);
                        }
                        OnProgressChanged(bytesReceivedSoFar, fileSize);
                    }
                    OnProgressChanged(fileSize, fileSize);
                    Status = DownloadStatus.Completed;
                }
                catch (Exception error)
                {
                    Status = DownloadStatus.ErrorNeedResume;
                    MessageAppended?.Invoke(error.ToString());
                }
            }
예제 #19
0
        public void StopDownload()
        {
            lock (this)
            {
                if (_downloadState == DownloadStatus.Downloading)
                {
                    // Update the calculation status.
                    _downloadState = DownloadStatus.NotDownloading;

                    // Fire a status changed event.
                    FireStatusChangedEvent(_downloadState);
                }
            }
        }
        public HttpDownloadClient(string url, long startPoint, long endPoint, int bufferSize, int cacheSize, int bufferCountPerNotification)
        {
            StartPoint   = startPoint;
            EndPoint     = endPoint;
            BufferSize   = bufferSize;
            MaxCacheSize = cacheSize;
            BufferCountPerNotification = bufferCountPerNotification;

            Url = new Uri(url, UriKind.Absolute);

            IsRangeSupported = true;

            status = DownloadStatus.Initialized;
        }
예제 #21
0
        public Task <DownloadInfo[]> GetDownloadInfos
        (
            string authenticationCookie,
            RemoteConnection server,
            string client,
            string patientID,
            string studyInstanceUID,
            string seriesInstanceUID,
            string sopInstanceUID,
            DownloadStatus status)
        {
            var userName = AuthHandler.Authorize(authenticationCookie, PermissionsTable.Instance.CanDownloadImages);

            return(null);
        }
 private void CheckIfFileIsDownloadedSuccesful()
 {
     if (FileUtil.CheckFileType(FileLocation))
     {
         Status          = DownloadStatus.Completed;
         DownloadPercent = 100;
         DownloadGroup.Refresh();
     }
     else
     {
         Status          = DownloadStatus.Preparing;
         DownloadPercent = 0;
         DownloadLink    = null;
     }
 }
예제 #23
0
 /// <summary>
 /// Validate the object.
 /// </summary>
 /// <exception cref="Rest.ValidationException">
 /// Thrown if validation fails
 /// </exception>
 public virtual void Validate()
 {
     if (UploadStatus != null)
     {
         UploadStatus.Validate();
     }
     if (DownloadStatus != null)
     {
         DownloadStatus.Validate();
     }
     if (CurrentProgress != null)
     {
         CurrentProgress.Validate();
     }
 }
예제 #24
0
        private void FinishDownloading(DownloadStatus status, Int64 id)
        {
            if (downloadCompleteFunction != null)
            {
                //downloadCompleteFunction.Invoke(status);
                downloadCompleteFunction(status, id, type);
                Debug.LogWarning("Invoking downloadcompleteFunction");
            }
            else
            {
                Debug.LogWarning("DownloadCompleteFunction is null");
            }

            working = false;
        }
예제 #25
0
        public Task <DownloadInfo[]> GetDownloadInfos
        (
            string authenticationCookie,
            RemoteConnection server,
            string client,
            string patientID,
            string studyInstanceUID,
            string seriesInstanceUID,
            string sopInstanceUID,
            DownloadStatus status)
        {
            var userName = AuthHandler.Authorize(authenticationCookie, PermissionsTable.Instance.CanDownloadImages);

            return(Task.Factory.StartNew(() => _addin.GetDownloadInfos(userName, server as PACSConnection, client, patientID, studyInstanceUID, seriesInstanceUID, sopInstanceUID, status)));
        }
 public DownloadInfoExpandPacket(Guid guid, IDownloadInfo info, string name, string quality, long size, bool isLocalDownload, TimePeriodPacket[] timePeriods, TimePeriodPacket[] timePeriodsCompleted, DownloadStatus status, string errorInfo, DateTime updatedLastestTime, long speed)
 {
     GuidCode             = guid;
     DownloadInfo         = info;
     Name                 = name;
     Quality              = quality;
     Size                 = size;
     IsLocalDownload      = isLocalDownload;
     TimePeriodsAll       = timePeriods;
     TimePeriodsCompleted = timePeriodsCompleted;
     DownloadStatus       = status;
     ErrorInfo            = errorInfo;
     UpdatedLastestTime   = updatedLastestTime;
     Speed                = speed;
 }
 static void statusCheck(StatusDelegate action, params DownloadStatus[] statusArray)
 {
     foreach (var obj in Enum.GetValues(typeof(DownloadStatus)))
     {
         DownloadStatus status = (DownloadStatus)obj;
         if (statusArray.Any(_ => _ == status))
         {
             Assert.IsTrue(action(status));
         }
         else
         {
             Assert.IsFalse(action(status));
         }
     }
 }
예제 #28
0
 public Downloader(IDownloadInfo info, DownloadStatus status, string errorInfo, string name)
 {
     DownloadInfo = info;
     ErrorInfom   = errorInfo;
     Path         = System.IO.Path.Combine(DownloadInfo.DownloadPath, name);
     load();
     if (DownloadingStatus == DownloadStatus.Waiting)
     {
         if (DownloadStatusManager.IsDownloadingOrWaiting(status))
         {
             status = DownloadStatus.Waiting;
         }
         onStatus(status);
         updateFromDownloadedStatus();
     }
 }
예제 #29
0
        private void onStatus()
        {
            DownloadStatus status = _downloader.DownloadingStatus;

            if (!DownloadStatusManager.IsDownloadingOrWaiting(status))
            {
                Pause();
            }
            if (status == DownloadStatus.Completed)
            {
                onChanged(nameof(UpdatedLastestTime));
            }
            onChanged(nameof(ErrorInfo));
            onChanged(nameof(DownloadStatus));
            updateDynamicInfo();
        }
예제 #30
0
        private void SetStatusIfNotSet(Uri uri, DownloadStatus downloadStatus)
        {
            bool setValue = true;

            downloadStatuses.AddOrUpdate(uri, downloadStatus, (key, oldValue) =>
            {
                setValue = false;

                return(oldValue);
            });

            if (setValue && downloadStatuses[uri] == DownloadStatus.NotStarted)
            {
                availableUrisToDownload.Release();
            }
        }
예제 #31
0
        /// <summary>
        /// Extract a file to a path
        /// </summary>
        /// <param name="path"></param>
        /// <param name="extractor"></param>
        /// <param name="status"></param>
        private void TryExtractMod(string path, SevenZipExtractor extractor, DownloadStatus status)
        {
            status.Label.Invoke(
                (MethodInvoker)(() =>
            {
                status.Label.Text = @"Extracting Files...";
                status.ProgressBar.Step = -100;
                status.ProgressBar.PerformStep();
            }));

            extractor.Extracting += (sender, e) => Extractor_Extracting(sender, e, status);
            Mod.ArchivePath       = path;
            var folderPath = App.FactorioLoader.Config.ReserveFolder + "\\" + Mod.FolderName;

            ModFileHelper.Extract(extractor, folderPath);
        }
예제 #32
0
        public Download(
            string url,
            string path,
            string filename,
            DownloadConfiguration configuration)
        {
            downloadService =
                configuration is not null ?
                new DownloadService(configuration) :
                new DownloadService();

            Url      = url;
            Folder   = path;
            Filename = filename;
            Status   = DownloadStatus.Created;
        }
        private static void BroadcastDownloadStatus(DownloadStatus status)
        {
            int message;

            switch (status)
            {
            case DownloadStatus.Started: message = WM_DL_START; break;

            case DownloadStatus.Succeeded: message = WM_DL_SUCCESS; break;

            case DownloadStatus.Failed: message = WM_DL_FAIL; break;

            default: return;
            }
            PostMessage((IntPtr)HWND_BROADCAST, message, IntPtr.Zero, IntPtr.Zero);
        }
예제 #34
0
 private void UpdateOnDownload(DownloadStatus status)
 {
     control.ShadowBoxText.Text = "";
     foreach (DownloadStatus d in statusOfDownloads)
     {
         int pos = d.File.LastIndexOf("\\") + 1;
         if (status.percent < 99.0)
         {
             control.ShadowBoxText.Text = control.ShadowBoxText.Text + "Downloading " + d.File.Substring(pos, d.File.Length - pos) + "  (" + d.percent.ToString("F2") + "%)\n";
         }
         else
         {
             d.active = false;
         }
     }
 }
예제 #35
0
        /// <summary>
        /// Download Progress Action
        /// </summary>
        /// <param name="info">
        /// The info.
        /// </param>
        private void DownloadProgress(DownloadStatus info)
        {
            if (info.TotalBytes == 0 || info.BytesRead == 0)
            {
                this.UpdateAvailable = false;
                this.UpdateMessage   = info.WasSuccessful ? Resources.OptionsViewModel_UpdateDownloaded : Resources.OptionsViewModel_UpdateServiceUnavailable;
                return;
            }

            long p = (info.BytesRead * 100) / info.TotalBytes;
            int  progress;

            int.TryParse(p.ToString(CultureInfo.InvariantCulture), out progress);
            this.DownloadProgressPercentage = progress;
            this.UpdateMessage = string.Format(
                "Downloading... {0}% - {1}k of {2}k", this.DownloadProgressPercentage, (info.BytesRead / 1024), (info.TotalBytes / 1024));
        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (!(value is DownloadStatus))
            {
                throw new ApplicationException("Value has to be of type '" + typeof(DownloadStatus).FullName + "'!");
            }

            if (!(parameter is DownloadStatus))
            {
                throw new ApplicationException("Parameter has to be of type '" + typeof(DownloadStatus).FullName + "'!");
            }

            DownloadStatus valueEnum     = (DownloadStatus)value;
            DownloadStatus parameterEnum = (DownloadStatus)parameter;

            return(valueEnum.Equals(parameterEnum) ? Visibility.Visible : Visibility.Collapsed);
        }
        private void AutoUpdaterForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && !isInDesignMode)
            {
                // cleanly cancell download if active
                if (webClient != null && webClient.IsBusy)
                {
                    webClient.CancelAsync();
                    webClient.Dispose();
                    webClient = null;
                }

                // always let AutoUpdater exit programatically
                dlStatus = DownloadStatus.CANCEL;
                e.Cancel = true;
            }
        }
예제 #38
0
            public HttpDownloadClient(string url, long startPoint,
                                      long endPoint, int bufferSize, int cacheSize, int bufferCountPerNotification)
            {
                this.StartPoint   = startPoint;
                this.EndPoint     = endPoint;
                this.BufferSize   = bufferSize;
                this.MaxCacheSize = cacheSize;
                this.BufferCountPerNotification = bufferCountPerNotification;

                this.Url = new Uri(url, UriKind.Absolute);

                // Set the default value of IsRangeSupported.
                this.IsRangeSupported = true;

                // Set the Initialized status.
                this.status = DownloadStatus.Initialized;
            }
예제 #39
0
        /// <summary>
        /// 下载结束时操作文件
        /// </summary>
        /// <param name="savePath">下载文件路径</param>
        /// <param name="configPath">配置文件路径</param>
        /// <param name="status">下载状态</param>
        public static void FileDownloadOver(string savePath, string configPath, DownloadStatus status)
        {
            //下载完,删除配置文件,并修改下载文件名
            if (status == DownloadStatus.ST_OVER_DOWNLOAD)
            {
                if (File.Exists(savePath))
                {
                    File.Move(savePath, savePath.Remove(savePath.LastIndexOf(CommonSymbol.SYMBOL_DOT))); //重命名
                }
                if (File.Exists(configPath))
                {
                    File.Delete(configPath);
                }
            }
            else if(status == DownloadStatus.ST_ERROR_DOWNLOAD) //如果下载错误,并且文件为0,则删除文件和配置文件
            {
                if (File.Exists(savePath))
                {
                    FileInfo file = new FileInfo(savePath);
                    if (file.Length == 0)
                    {
                        file.Delete();
                        if (File.Exists(configPath))
                        {
                            File.Delete(configPath);
                        }
                    }

                }

            }
            else if (status == DownloadStatus.ST_CANCEL_DOWNLOAD) //如果取消下载,删除文件和配置文件
            {
                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }
                if (File.Exists(configPath))
                {
                    File.Delete(configPath);
                }
            }
        }
예제 #40
0
 public static string StatusToString(DownloadStatus status)
 {
     switch (status)
     {
         case DownloadStatus.INFORM:
             return "";
         case DownloadStatus.DONE:
             return "Done.";
         case DownloadStatus.PROCESSING:
             return "Processing...";
         case DownloadStatus.LOW_CONNECTION:
             return "Low Connection.";
         case DownloadStatus.LOST_CONNECTION:
             return "The internet connection appears to be offline.";
         case DownloadStatus.UNEXPECTED_PAGE:
             return "Download Paused, Click \"See What Happens\" for more information.";
         case DownloadStatus.ACCOUNT_SUSPENDED:
             return "Your account is suspended.";
         case DownloadStatus.TWO_STEPS_VALIDATION:
             return "Your account needs 2 steps validation.";
         case DownloadStatus.UNKNOWN_TYPE:
             return "Unknow Type";
         case DownloadStatus.WRONG_USERNAME_OR_PASSWORD:
             return "The username or password is incorrect. Please try again.";
         case DownloadStatus.CONNECTION_TIME_OUT:
             return "Request time out.";
         case DownloadStatus.DATABASE_ERROR:
             return "Error in establishing a database connection.";
         case DownloadStatus.MAXIMUM_CONTACT_EXEED:
             return "Exceed Maximum Contacts.";
         case DownloadStatus.USER_CANCEL:
             return "Cancelled.";
         case DownloadStatus.ERROR_SENDING_REQUEST:
             return "An error occured while sending the request. Please try again.";
         case DownloadStatus.CAPTCHA:
             return "For security purpose please input captcha below.";
     }
     return "";
 }
예제 #41
0
 public static string ChooseIcon(DownloadStatus downloadStatus)
 {
     switch (downloadStatus)
     {
         case DownloadStatus.QUEUED:
             return FontAwesome.Clock;
         case DownloadStatus.PAUSED:
             return FontAwesome.Pause;
         case DownloadStatus.DOWNLOADING:
             return FontAwesome.Download;
         case DownloadStatus.FETCHING:
             return FontAwesome.LoadingSpinner;
         case DownloadStatus.PP_QUEUED:
             break;
         case DownloadStatus.LOADING_PARS:
             return FontAwesome.LoadingSpinner;
         case DownloadStatus.VERIFYING_SOURCES:
             break;
         case DownloadStatus.REPAIRING:
             break;
         case DownloadStatus.VERIFYING_REPAIRED:
             break;
         case DownloadStatus.RENAMING:
             break;
         case DownloadStatus.UNPACKING:
             break;
         case DownloadStatus.MOVING:
             return FontAwesome.ArrowRight;
         case DownloadStatus.EXECUTING_SCRIPT:
             break;
         case DownloadStatus.PP_FINISHED:
             break;
         default:
             throw new ArgumentOutOfRangeException("downloadStatus", downloadStatus, null);
     }
     return FontAwesome.QuestionMark;
 }
예제 #42
0
        public static string StatusToString(DownloadStatus status)
        {
            switch (status)
            {
                case DownloadStatus.INFORM:
                    return "";
                case DownloadStatus.DONE:
                    return "Done";
                case DownloadStatus.PROCESSING:
                    return "Processing...";
                case DownloadStatus.LOW_CONNECTION:
                    return "Low Connection";
                case DownloadStatus.LOST_CONNECTION:
                    return "Connection Lost";
                case DownloadStatus.UNEXPECTED_PAGE:
                    return "Download Paused, Click \"See What Happens\" for more information";
                case DownloadStatus.ACCOUNT_SUSPENDED:
                    return "Your account is suspended";
                case DownloadStatus.TWO_STEPS_VALIDATION:
                    return "Your account needs 2 steps validation";
                case DownloadStatus.UNKNOWN_TYPE:
                    return "Unknow Type";
                case DownloadStatus.WRONG_USERNAME_OR_PASSWORD:
                    return "Wrong username or password";
                case DownloadStatus.CONNECTION_TIME_OUT:
                    return "Request time out";
                case DownloadStatus.DATABASE_ERROR:
                    return "Database Error";
                case DownloadStatus.MAXIMUM_CONTACT_EXEED:
                    return "Exeed Maximum Contacts";
                case DownloadStatus.USER_CANCEL:
                    return "Cancelled";

            }
            return "";
        }
예제 #43
0
        public void NotifyStatusByUsername(string username, DownloadStatus status, object data)
        {

        }
예제 #44
0
        protected void NotifyDownloadStatus(DownloadStatus status, object message)
        {
            currentStatus = status;
            currentMessage = message;

            if (status == DownloadStatus.UNEXPECTED_PAGE || status == DownloadStatus.WRONG_USERNAME_OR_PASSWORD)
            {
                threadProcessingMode = THREAD_STOP;
                if (isThreadHangRunning)
                {
                    threadHangeMode = THREAD_RESTART;
                }
                else
                {
                    threadHangeMode = THREAD_START;
                    waitStatusHangThread = new Thread(WaitForHangStatus);
                    waitStatusHangThread.Start();
                }
            }
            else
            {
                threadHangeMode = THREAD_STOP;
                if (status == DownloadStatus.PROCESSING)
                {
                    if (isThreadProcessingRunning)
                    {
                        threadProcessingMode = THREAD_RESTART;
                    }
                    else
                    {
                        threadProcessingMode = THREAD_START;
                        waitStatusProcessingThread = new Thread(WaitForProcessingStatus);
                        waitStatusProcessingThread.Start();
                    }
                }
                else
                {
                    threadProcessingMode = THREAD_STOP;
                }
                DoNotifyStatus();
            }
        }
 private void RemoveFlagged(DownloadStatus status)
 {
     List<DownloadItem> dels = new List<DownloadItem>();
     foreach (DownloadItem s in objDownloads.Objects)
     {
         if (s.Status == status)
         {
             dels.Add(s);
         }
     }
     if (dels.Count > 0)
     {
         objDownloads.RemoveObjects(dels);
         foreach (DownloadItem d in dels)
             _manager.Delete(d.Id);
     }
 }
예제 #46
0
        protected void NotifyDownloadStatus(DownloadStatus status, object message)
        {
            currentStatus = status;
            currentMessage = message;

            if (status == DownloadStatus.UNEXPECTED_PAGE
                || status == DownloadStatus.ERROR_SENDING_REQUEST
                || status == DownloadStatus.WRONG_USERNAME_OR_PASSWORD
                || status == DownloadStatus.ACCOUNT_BLOCKED
                || status == DownloadStatus.SERVICE_UNAVAILABLE)
            {
                threadProcessingMode = THREAD_STOP;
                if (isThreadHangRunning)
                {
                    threadHangeMode = THREAD_RESTART;
                }
                else
                {
                    threadHangeMode = THREAD_START;
                    waitStatusHangThread = new System.Threading.Tasks.Task(WaitForHangStatus);
                    waitStatusHangThread.Start();
                }
            }
            else
            {
                threadHangeMode = THREAD_STOP;
                if (status == DownloadStatus.PROCESSING)
                {
                    if (isThreadProcessingRunning)
                    {
                        threadProcessingMode = THREAD_RESTART;
                    }
                    else
                    {
                        threadProcessingMode = THREAD_START;
                        waitStatusProcessingThread = new System.Threading.Tasks.Task(WaitForProcessingStatus);
                        waitStatusProcessingThread.Start();
                    }
                }
                else
                {
                    threadProcessingMode = THREAD_STOP;
                }
                DoNotifyStatus();
            }
        }
 private void OnDownloadStatusChanged(DownloadStatus status)
 {
     var handle = DownloadStatusChanged;
     handle?.Invoke(this, new DownloadStatusChangedArgs
     {
         Download = this,
         Status = status
     });
 }
예제 #48
0
 /// <summary>Constructs a new progress instance.</summary>
 /// <param name="status">The status of the download.</param>
 /// <param name="bytes">The number of bytes received so far.</param>
 public DownloadProgress(DownloadStatus status, long bytes)
 {
     Status = status;
     BytesDownloaded = bytes;
 }
예제 #49
0
 public DownloadEventArgs(DownloadStatus status)
 {
     this.Status = status;
 }
예제 #50
0
        private void Download()
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(_url);
            req.Method = "HEAD";
            try
            {
                HttpWebResponse resp = (HttpWebResponse)(req.GetResponse());
                long len = resp.ContentLength;
                _totalSize = len;
                Console.WriteLine("totalSize : " + _totalSize);

                req = (HttpWebRequest)WebRequest.Create(_url);
                req.AddRange(_downloadSize, _totalSize - 1);
                Console.Write("Resulting Request Headers: ");
                Console.WriteLine(req.Headers.ToString());

                // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)req.GetResponse();

                // Displays the headers in the response received
                Console.Write("Resulting Response Headers: ");
                Console.WriteLine(myHttpWebResponse.Headers.ToString());

                // Display the contents of the page to the console.
                Stream streamResponse = myHttpWebResponse.GetResponseStream();
                byte[] readBuffer = new byte[DOWNLOAD_BLOCK];
                int count = streamResponse.Read(readBuffer, 0, readBuffer.Length);
                using (Stream stream = new FileStream(_tempOutputFilename, FileMode.OpenOrCreate))
                {
                    stream.Seek(_downloadSize, SeekOrigin.Begin);
                    int p_progress = 0;
                    while (count > 0)
                    {
                        if (_downloadState == DownloadStatus.NotDownloading) break;
                        stream.Write(readBuffer, 0, count);

                        count = streamResponse.Read(readBuffer, 0, readBuffer.Length);
                        _downloadSize += count;
                        int progress = (int)(_downloadSize * 100 / _totalSize);
                        if (progress != p_progress)
                        {
                            p_progress = progress;
                            FireProgressChangedEvent(progress);
                        }
                    }
                    if (_downloadState == DownloadStatus.Downloading)
                    {
                        FireProgressChangedEvent(100);
                    }
                }
                // Release the response object resources.
                streamResponse.Close();
                myHttpWebResponse.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                _downloadState = DownloadStatus.Error;
                CleanUp();
            }
            if (_downloadState == DownloadStatus.Downloading)
            {
                File.Move(_tempOutputFilename, _outFilename);
                _downloadState = DownloadStatus.Completed;
            }
        }
예제 #51
0
 private void FireStatusChangedEvent(DownloadStatus status)
 {
     if (DownloadStatusChanged != null)
     {
         DownloadEventArgs args =
             new DownloadEventArgs(status);
         if (DownloadStatusChanged.Target is
                 System.Windows.Forms.Control)
         {
             System.Windows.Forms.Control targetForm = DownloadStatusChanged.Target
                     as System.Windows.Forms.Control;
             targetForm.Invoke(DownloadStatusChanged,
                     new object[] { this, args });
         }
         else
         {
             DownloadStatusChanged(this, args);
         }
     }
 }
예제 #52
0
        public void StartDownload()
        {
            lock (this)
            {
                if (_downloadState == DownloadStatus.NotDownloading)
                {
                    // Create a delegate to the calculation method.
                    DownloadDelegate download = new DownloadDelegate(Download);

                    // Start the calculation.
                    download.BeginInvoke(new AsyncCallback(EndDownload), download);

                    // Update the calculation status.
                    _downloadState = DownloadStatus.Downloading;

                    // Fire a status changed event.
                    FireStatusChangedEvent(_downloadState);
                }
            }
        }
예제 #53
0
        public void StopDownload()
        {
            lock (this)
            {
                if (_downloadState == DownloadStatus.Downloading)
                {
                    // Update the calculation status.
                    _downloadState = DownloadStatus.NotDownloading;

                    // Fire a status changed event.
                    FireStatusChangedEvent(_downloadState);
                }
            }
        }
예제 #54
0
        protected new void FetchData(SQLiteMonDataReader reader)
        {
            base.FetchData(reader);

            int filepathOrdinal = reader.GetOrdinal("filepath");

            this.Status = (DownloadStatus)reader.GetInt32(reader.GetOrdinal("status"));

            if (this.Status == DownloadStatus.Errored)
            {
                this.ErrorType = (ErrorType)reader.GetInt32(reader.GetOrdinal("errortype"));

                if (this.ErrorType != ErrorType.UnknownError)
                {
                    this.ErrorDetails = reader.GetString(reader.GetOrdinal("errordetails"));
                }
            }

            if (!reader.IsDBNull(filepathOrdinal))
            {
                this.DownloadPath = reader.GetString(filepathOrdinal);
            }

            this.PlayCount = reader.GetInt32(reader.GetOrdinal("playcount"));
        }
        public void Init4Loading()
        {
            Initialized = false;
            Initializing = false;
            initCdlStatus = DataInitStatus.NotStart;
            initRtdStatus = DataInitStatus.NotStart;
            cdlLoadingStatus = DownloadStatus.NotStart;
            rtdLoadingStatus = DownloadStatus.NotStart;

            //currentTInterval = AppSetting.INTEVALS[0];
            isUpdateCandle = false;
            isAddCandle = false;
            dataCache.InitLocalData();
            //List<BarData> datas = new List<BarData>();
            //if (dataCache.DataUnits.ContainsKey(currentTInterval))
            //{
            //    datas = dataCache.DataUnits[currentTInterval];
            //    Console.WriteLine(" datas   count  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  " + datas.Count);
            //    if (datas.Count > 0)
            //    {
            //        localLastCdlTime = datas[datas.Count - 1].DateTime;
            //        hasLocalLastCdlTime = true;
            //    }
            //}
            //else
            //{
            //    dataCache.DataUnits.Add(currentTInterval, datas);
            //}
        }
        //DateTime startTime;
        public void Init()
        {
            lock (this)
            {
                Console.WriteLine(" Start  Now   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  " + DateTime.Now.ToLongTimeString());
                Initialized = false;
                Initializing = false;
                initCdlStatus = DataInitStatus.NotStart;
                initRtdStatus = DataInitStatus.NotStart;
                cdlLoadingStatus = DownloadStatus.NotStart;
                rtdLoadingStatus = DownloadStatus.NotStart;

                //currentTInterval = AppSetting.INTEVALS[0];
                isUpdateCandle = false;
                isAddCandle = false;
                dataCache.InitLocalData();

                    handler = new ProviderHandler( this);
                    ProviderService.RegisterHandler(handler);
                    ProviderService.KickOff();
            }
            InitStart();
        }
예제 #57
0
 private void SetState(DownloadStatus value)
 {
     _status = value;
     OnStateChanged();
 }
예제 #58
0
 public DownloadEventArgs(int progress)
 {
     this.Progress = progress;
     this.Status = DownloadStatus.Downloading;
 }
        public void Reconnect()
        {
            lock (this)
            {
                timerAuto.Stop();

                Initialized = false;
                Initializing = false;
                initCdlStatus = DataInitStatus.NotStart;
                initRtdStatus = DataInitStatus.NotStart;
                cdlLoadingStatus = DownloadStatus.NotStart;
                rtdLoadingStatus = DownloadStatus.NotStart;

                //currentTInterval = AppSetting.INTEVALS[0];
                isUpdateCandle = false;
                isAddCandle = false;

                if (dataCache != null)
                    dataCache.CleanCache();
                else
                    dataCache = new DataCache(this);

                handler = new ProviderHandler(this);
                ProviderService.RegisterHandler(handler);

                dataCache.InitLocalData();
                if (dataCache.DataUnits.ContainsKey(currentTInterval))
                {
                    List<BarData> datas = dataCache.DataUnits[currentTInterval];
                    Console.WriteLine(" datas   count  ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;  " + datas.Count);
                    if (datas.Count > 0)
                    {
                        localLastCdlTime = datas[datas.Count - 1].DateTime;
                       hasLocalLastCdlTime = true;
                    }
                }
                else
                {
                    List<BarData> datas = new List<BarData>();
                    dataCache.DataUnits.Add(currentTInterval, datas);
                }
                ProviderService.KickOff();
            }
            timerInit.Start();
            //RaiseValuesUpdateEvent(UpdateType.NewBar, 1, 0);
        }
예제 #60
0
 public void NotifyDownloadCompleted(DownloadItem argDownloadItem, DownloadStatus dlStatus)
 {
     try {
     this.currentDownloads--;
     foreach (DownloaderTask task in this.downloadTasks) {
       if (task.downloadItem == argDownloadItem) {
     this.downloadTasks.Remove(task);
     break;
       }
     }
     bool flag = true;
     if (dlStatus == DownloadStatus.CompletedSuccessfully) {
       this.debugLogText.AddLine("Download Finish: " + argDownloadItem.itemUri.ToString());
       argDownloadItem.completed = true;
       this.lstDownloadItemList.Remove(argDownloadItem);
     } else {
       if (dlStatus == DownloadStatus.Failed_404) {
     this.debugLogText.AddLine("Download 404'd:  " + argDownloadItem.itemUri.ToString());
     argDownloadItem.completed = true;
     this.lstDownloadItemList.Remove(argDownloadItem);
     if (!Settings.Default.deleteFailedDownloads) {
       goto Label_01C3;
     }
     try {
       File.Delete(argDownloadItem.fullPath);
       goto Label_01C3;
     } catch {
       goto Label_01C3;
     }
       }
       if (dlStatus == DownloadStatus.Cancelled) {
     this.debugLogText.AddLine("Download Cancel: " + argDownloadItem.itemUri.ToString());
     argDownloadItem.completed = false;
     this.lstDownloadItemList.Remove(argDownloadItem);
     if (!Settings.Default.deleteFailedDownloads) {
       goto Label_01C3;
     }
     try {
       File.Delete(argDownloadItem.fullPath);
       goto Label_01C3;
     } catch {
       goto Label_01C3;
     }
       }
       this.debugLogText.AddLine("Download FAILED: " + argDownloadItem.itemUri.ToString());
       if (argDownloadItem.retries < (Settings.Default.maxRetries - 1)) {
     argDownloadItem.started = false;
     argDownloadItem.retries++;
     this.lstDownloadItemList.Remove(argDownloadItem);
     this.AddItemToDownloadList(ref argDownloadItem);
     flag = false;
       }
       if (Settings.Default.deleteFailedDownloads) {
     try {
       File.Delete(argDownloadItem.fullPath);
     } catch {
     }
       }
     }
     Label_01C3:
     if (flag) {
       argDownloadItem.watchThread.NotifyDownloadCompleted(argDownloadItem, dlStatus);
     }
       } catch (Exception exception) {
     MessageBox.Show("Error NotifyDownloadComplete.\r\n" + exception.Message);
       }
 }