Beispiel #1
0
 protected void btnSaveSettings_Click(object sender, EventArgs e)
 {
     List<DownloadType> types = new List<DownloadType>();
     foreach (GridViewRow row in spgvSettings.Rows)
     {
         bool flag = ((CheckBox)row.Cells[3].FindControl("chbDelete")).Checked;
         if (flag == false)
         {
             string ext = ((TextBox)row.Cells[0].FindControl("txtExtension")).Text;
             int size = Convert.ToInt32(((TextBox)row.Cells[1].FindControl("txtSize")).Text);
             bool active = ((CheckBox)row.Cells[2].FindControl("chbActive")).Checked;
             DownloadType file = new DownloadType(ext, size, active);
             if (!types.Contains(file))
                 types.Add(file);
         }
     }
     if (types != null)
     {
         ExtState state = DownloadManager.Instance.Save(types);
         switch (state)
         {
             case ExtState.Failed:
                 AddSPNotification(hdnFailed.Value);
                 break;
             case ExtState.Success:
                 AddSPNotification(hdnSuccess.Value);
                 Refresh();
                 break;
         }
     }
     Refresh();
 }
Beispiel #2
0
 void HandleCompletedDownload(object sender, DownloadStringCompletedEventArgs e, DownloadType type)
 {
     switch (type)
     {
         case DownloadType.RecentPlaylist:
             {
                 Parsers.ParseRecentPlaylist(e.Result);
                 break;
             }
         case DownloadType.MostPlayedPlaylist:
             {
                 Parsers.ParseMostPlayed(e.Result);
                 break;
             }
         case DownloadType.FavoritePlaylist:
             {
                 Parsers.ParseFavorites(e.Result);
                 break;
             }
         case DownloadType.BadgeList:
             {
                 Parsers.ParseBadges(e.Result);
                 break;
             }
         case DownloadType.FriendList:
             {
                 Parsers.ParseFriends(e.Result);
                 break;
             }
     }
 }
 public static async Task<ObservableCollection<DownloadModel>> GetDownload(DownloadType type)
 {
     var group= "";
     switch (type)
     {
         case DownloadType.song:
             group = "song";
             break;
         case DownloadType.mv:
             group = "mv";
             break;
         case DownloadType.other:
             group = "other";
             break;
         default:
             break;
     }
     var downs = await BackgroundDownloader.GetCurrentDownloadsForTransferGroupAsync(BackgroundTransferGroup.CreateGroup(group));
     var downlist = new ObservableCollection<DownloadModel>();
     if(downs.Count>0)
     {
         foreach (var down in downs)
         {
             var model = new DownloadModel();
             downlist.Add(model);
         }
     }
     return downlist;
 }
 /// <summary>
 ///     Initializes a new instance of this class.
 /// </summary>
 /// <param name="name">Name of file to download.</param>
 /// <param name="url">URL of file to download.</param>
 /// <param name="type">Type of file being downloaded.</param>
 /// <param name="description">Description of game being downloaded.</param>
 public DownloadItem(string name, string url, DownloadType type, GameDescription description)
 {
     _name = name;
     _gameDescription = description;
     _downloadType = type;
     _downloader = new FileDownloader(url);
     _downloader.Start();
 }
        public void Start(String url, String title, DownloadType type)
        {
            DownloadModel model = new DownloadModel(new Uri(url), String.Empty, title, type);
            Items.Add(model);
            this.downloadQueue.Enqueue(model);
            DownloadCount++;

            Download();
        }
Beispiel #6
0
        public DownloadModel(Uri url, String fileName, String title, DownloadType type)
        {
            DownloadProgress = 0;
            Url = url;
            FileName = fileName;
            Title = title;
            Type = type;

            CancelCommand = new DelegateCommand(() => RaiseEvent(ref CancelRequested));
        }
Beispiel #7
0
      internal DownloadInfo(string name, DownloadType type, Version version,
 string publisher, string architecture, long fileSize, Uri link)
      {
          Name = name;
             Type = type;
             Version = version;
             Publisher = publisher;
             Architecture = architecture;
             FileSize = fileSize;
             Link = link;
      }
 /// <summary>
 /// 要下载调用这个方法
 /// </summary>
 /// <param name="url">下载的文件网址的来源</param>
 /// <returns></returns>
 public static async Task Start(string filename,string url,DownloadType type,StorageFolder folder=null)
 {
     try
     {
         Uri uri = new Uri(Uri.EscapeUriString(url), UriKind.RelativeOrAbsolute);
         BackgroundDownloader downloader = new BackgroundDownloader();
         if (folder==null)
         {
             folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists);
             switch (type)
             {
                 case DownloadType.song:
                     folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("song");
                     break;
                 case DownloadType.mv:
                     folder = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("mv");
                     break;
                 case DownloadType.other:
                     folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists);
                     downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                     break;
                 default:
                     break;
             }
         }else
         {
             downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
         }
         //string name = uri.ToString().Substring(uri.ToString().LastIndexOf("/"), uri.ToString().Length);
         string name = filename;
         StorageFile file = await folder.CreateFileAsync(name, CreationCollisionOption.GenerateUniqueName);
         downloader.FailureToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Fa);
         downloader.SuccessToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Su);
         var download = downloader.CreateDownload(new Uri(url), file);
         TransferModel transfer = new TransferModel();
         transfer.DownloadOperation = download;
         transfer.Source = download.RequestedUri.ToString();
         transfer.Destination = download.ResultFile.Path;
         transfer.BytesReceived = download.Progress.BytesReceived;
         transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
         transfer.Progress = 0;
         transfers.Add(transfer);
         Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
         download.StartAsync().AsTask(cancelToken.Token, progressCallback);
     }
     catch
     {
         await new MessageDialog("链接已失效!").ShowAsync();
     }
 }
Beispiel #9
0
 public void Download(DownloadType type)
 {           
     switch (type)
     {
         case DownloadType.ProfilePicture:
             {
                 Profile.ProfileImage = new BitmapImage(new Uri(Profile.ProfileImageURL,UriKind.Absolute));
                 break;
             }
         case DownloadType.BackgroundPicture:
             {
                 Profile.BackgroundImage = new BitmapImage(new Uri(Profile.BackgroundImageURL, UriKind.Absolute));
                 break;
             }
         case DownloadType.RecentPlaylist:
            {
                WebClient client = new WebClient();
                client.DownloadStringCompleted += (s,e) => HandleCompletedDownload(s,e,type);
                client.DownloadStringAsync(new Uri(Profile.RecentPlaylistURL));
                break;
            }
         case DownloadType.MostPlayedPlaylist:
            {
                WebClient client = new WebClient();
                client.DownloadStringCompleted += (s, e) => HandleCompletedDownload(s, e, type);
                client.DownloadStringAsync(new Uri(Profile.MostPlayedPlaylistURL));
                break;
            }
         case DownloadType.FavoritePlaylist:
            {
                WebClient client = new WebClient();
                client.DownloadStringCompleted += (s, e) => HandleCompletedDownload(s, e, type);
                client.DownloadStringAsync(new Uri(Profile.FavortiesPlaylistURL));
                break;
            }
         case DownloadType.BadgeList:
            {
                WebClient client = new WebClient();
                client.DownloadStringCompleted += (s, e) => HandleCompletedDownload(s, e, type);
                client.DownloadStringAsync(new Uri(Profile.BadgeUrl));
                break;
            }
         case DownloadType.FriendList:
            {
                WebClient client = new WebClient();
                client.DownloadStringCompleted += (s, e) => HandleCompletedDownload(s, e, type);
                client.DownloadStringAsync(new Uri(Profile.FriendsUrl));
                break;
            }
     }
 }
Beispiel #10
0
        public Addon(String name, String dirName, String firstUploaded, String lastUpdated, String version, AddonType aType, DownloadType dlType, List<FAF> fafList)
        {
            Name = name;
            DirectoryName = dirName;
            FirstUploaded = firstUploaded;
            LastUpdated = lastUpdated;
            Version = version;
            AType = aType;
            DLType = dlType;
            FAFList = fafList;

            if("".Equals(name))
                throw new ArgumentException("Addon name is not allowed to be empty!");

            if(!DirectoryName.Equals("Serialized Directory Name") && !Regex.IsMatch(DirectoryName, @"^[a-z0-9_]*$"))
                throw new ArgumentException("Directory name has some invalid characters!");
        }
        public static void AddToQueue(Beatmap bm, DownloadType Type)
        {
            if (dqForm == null)
            {
                dqForm = new DownloadQueue();
                dqForm.Show();

                dqForm.Closed += (object sender, EventArgs e) =>
                {
                    dqForm = null;
                };
            }
            else if (dqForm.Visibility != Visibility.Visible)
                dqForm.Show();

            if (Type == DownloadType.Beatmap)
            {
                if (string.IsNullOrEmpty(Configuration.BeatmapDownloadLocation))
                {
                    MessageBox.Show("Please first select download locations in settings pannel at the bottom of the window.", "Welp", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
            }

            Queue.Add(bm);
            if (QueuedFile != null)
                QueuedFile(bm);

            if (DownloaderThread == null)
            {
                DownloaderThread = new Thread[4];

                DownloaderThread[0] = new Thread(new ThreadStart(DownloadQueue));
                DownloaderThread[0].Start();

                DownloaderThread[1] = new Thread(new ThreadStart(DownloadQueue));
                DownloaderThread[1].Start();

                DownloaderThread[2] = new Thread(new ThreadStart(DownloadQueue));
                DownloaderThread[2].Start();

                DownloaderThread[3] = new Thread(new ThreadStart(DownloadQueue));
                DownloaderThread[3].Start();
            }
        }
 public static async Task<bool> AddDownload(string filename, string url, DownloadType type, StorageFolder folder = null)
 {
     try
     {
         var down = new BackgroundDownloader();
         down.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
         if (folder == null)
         {
             folder = await KnownFolders.MusicLibrary.GetFolderAsync("kgdownload");
             switch (type)
             {
                 case DownloadType.song:
                     folder = await folder.GetFolderAsync("song");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("song");
                     break;
                 case DownloadType.mv:
                     folder = await folder.GetFolderAsync("mv");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("mv");
                     break;
                 case DownloadType.other:
                     folder = await folder.GetFolderAsync("other");
                     down.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                     break;
                 default:
                     break;
             }
         }
         var files= (await folder.GetFilesAsync()).ToList();
         foreach (var item in files)
         {
             await item.DeleteAsync();
         }
         var file = await folder.CreateFileAsync(filename);
         down.FailureToastNotification = DownloadToast(filename, DownloadResult.Failure);
         down.SuccessToastNotification = DownloadToast(filename, DownloadResult.Success);
         var opera= down.CreateDownload(new Uri(url), file);
         opera.CostPolicy = BackgroundTransferCostPolicy.Always;
         opera.StartAsync();
         return true;
     }
     catch (Exception)
     {
         return false;
     }
 }
Beispiel #13
0
 protected void btnAddDownload_Click(object sender, EventArgs e)
 {
     DownloadType type = new DownloadType(txtExtension.Text, Convert.ToInt32(txtSize.Text), chbActive.Checked);
     ExtState state = DownloadManager.Instance.Add(type);
     switch (state)
     {
         case ExtState.Failed:
             AddSPNotification(hdnFailed.Value);
             break;
         case ExtState.Success:
             AddSPNotification(hdnSuccess.Value);
             Refresh();
             break;
         case ExtState.IsExists:
             AddSPNotification(string.Format(hdnIsExists.Value, type.Extension));
             break;
     }
 }
Beispiel #14
0
        public void DownloadRealmData(string realm, string region, string appName, DownloadType downloadType = DownloadType.Array, string filePath = null)
        {
            string savePath = string.Empty;

            if (filePath == null)
            {
                savePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + $@"\{appName}\{region}\Region Auction Data.json";
            }
            else
            {
                savePath = filePath;
            }

            if (!Directory.Exists(savePath))
            {
                Directory.CreateDirectory(savePath);
            }

            string regionID = region.ToUpper();
            string realmID  = realm.Replace(" ", "-").ToLower();

            Request request = new Request(User_Agent);

            request.Get($"{API_URL}item/{regionID}/{realmID}?format=json&apiKey={API_Key}");

            switch (downloadType)
            {
            case DownloadType.Array:
                File.WriteAllText(savePath, request.Response);
                break;

            case DownloadType.Object:
                string firstPass  = request.Response.Replace("[", @"{ ""Auctions"": [");
                string secondPass = firstPass.Replace("]", "]}");
                File.WriteAllText(savePath, secondPass);
                break;
            }
        }
Beispiel #15
0
    void OnGUI()
    {
        UpdateType   updateStream = (UpdateType)Mathf.Min(EditorPrefs.GetInt(FuseSDKUpdater.AUTOUPDATE_KEY, 4) + 1, (int)UpdateType.Bugfixes);
        DownloadType autoDL       = (DownloadType)EditorPrefs.GetInt(FuseSDKUpdater.AUTODOWNLOAD_KEY, 1);

        UpdateType newStream = (UpdateType)EditorGUILayout.EnumPopup("Auto Update Checking", updateStream);

        if (updateStream != newStream)
        {
            EditorPrefs.SetInt(FuseSDKUpdater.AUTOUPDATE_KEY, ((int)newStream) - 1);
        }

        if (newStream != UpdateType.Never)
        {
            EditorGUILayout.Space();
            DownloadType newDL = (DownloadType)EditorGUILayout.EnumPopup("'Download now' action", autoDL);

            if (newDL != autoDL)
            {
                EditorPrefs.SetInt(FuseSDKUpdater.AUTODOWNLOAD_KEY, (int)newDL);
            }
        }
    }
Beispiel #16
0
        private void GetDownloadTypes()
        {
            List <DownloadType> types = new List <DownloadType>();

            Helper.RunElevated(SPContext.Current.Site.ID, SPContext.Current.Site.RootWeb.ID, delegate(SPWeb elevatedWeb)
            {
                try
                {
                    string[] fileTypes = elevatedWeb.Properties[Content.SPFileTypes].ToLower().Split(';');
                    string[] fileSizes = elevatedWeb.Properties[Content.SPFileSizes].ToLower().Split(';');
                    string[] actives   = elevatedWeb.Properties[Content.SPFileTypesActive].ToLower().Split(';');
                    if (fileSizes != null && fileTypes != null)
                    {
                        if (fileTypes.Length == fileSizes.Length)
                        {
                            for (int i = 0; i < fileTypes.Length - 1; i++)
                            {
                                DownloadType file = new DownloadType(fileTypes[i], Convert.ToInt32(fileSizes[i]), Convert.ToBoolean(actives[i]));
                                if (!types.Contains(file, new DownloadTypeEqualComparer()))
                                {
                                    types.Add(file);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            });
            if (types.Count > 0)
            {
                downloadTypes.Clear();
                downloadTypes.AddRange(types);
            }
        }
Beispiel #17
0
        public VPN_Downloader(MainWindow MW, DownloadType t)
        {
            m = MW;
            switch (t)
            {
            case DownloadType.ClinicDownloader:
                DOM_FOR_ACTUAL_DATA = "ContentPlaceHolder1_gvDownLoad";
                DOM_FOR_PAGECLICK   = "ContentPlaceHolder1_pgDownLoad";
                DOM_FOR_PAGENUMBERS = "ctl00$ContentPlaceHolder1$pgDownLoad_input";
                _td_parcer         += Clinic_TD_Parcer;
                break;

            case DownloadType.SpecialDownloader:
                DOM_FOR_ACTUAL_DATA = "cph_rptDownload";
                DOM_FOR_PAGECLICK   = "cph_pgDownLoad";
                DOM_FOR_PAGENUMBERS = "ctl00$cph$pgDownLoad_input";
                _td_parcer         += Special_TD_Parcer;
                break;

            default:
                Dispose();
                break;
            }
        }
Beispiel #18
0
        public DataShowF(DataSet p_dataSet, DownloadType p_downloadType, string p_caption)
        {
            InitializeComponent();

            _dataSet  = p_dataSet;
            this.Text = p_caption + p_dataSet.Tables[0].Rows[0]["Table"];
            switch (p_downloadType)
            {
            case DownloadType.CURRENCY_TABLE:
                _walutaTableUC = new WalutaTableUC(p_dataSet);
                _walutaTableUC.AutoSizeMode = AutoSizeMode.GrowAndShrink;
                _walutaTableUC.AutoSize     = true;
                _walutaTableUC.Dock         = DockStyle.Fill;
                UcViewFieldGB.Controls.Add(_walutaTableUC);
                UcViewFieldGB.Text = p_caption +
                                     p_dataSet.Tables[0].Rows[0]["Table"] +
                                     " numer " + p_dataSet.Tables[0].Rows[0]["No"] +
                                     " z dnia " + p_dataSet.Tables[0].Rows[0]["EffectiveDate"];
                break;

            default:
                break;
            }
        }
Beispiel #19
0
        protected void btnSaveSettings_Click(object sender, EventArgs e)
        {
            List <DownloadType> types = new List <DownloadType>();

            foreach (GridViewRow row in spgvSettings.Rows)
            {
                bool flag = ((CheckBox)row.Cells[3].FindControl("chbDelete")).Checked;
                if (flag == false)
                {
                    string       ext    = ((TextBox)row.Cells[0].FindControl("txtExtension")).Text;
                    int          size   = Convert.ToInt32(((TextBox)row.Cells[1].FindControl("txtSize")).Text);
                    bool         active = ((CheckBox)row.Cells[2].FindControl("chbActive")).Checked;
                    DownloadType file   = new DownloadType(ext, size, active);
                    if (!types.Contains(file))
                    {
                        types.Add(file);
                    }
                }
            }
            if (types != null)
            {
                ExtState state = DownloadManager.Instance.Save(types);
                switch (state)
                {
                case ExtState.Failed:
                    Helper.AddSPNotification(updSettings, hdnFailed.Value, false);
                    break;

                case ExtState.Success:
                    Helper.AddSPNotification(updSettings, hdnSuccess.Value, false);
                    Refresh();
                    break;
                }
            }
            Refresh();
        }
Beispiel #20
0
        public static IEnumerator Download(string url, DownloadType type, Action <UnityWebRequest> beforeSend, Action <UnityWebRequest> downloadCompleted, Action <UnityWebRequest> downloadFailed = null)
        {
            using (UnityWebRequest web = WebRequestForType(url, type))
            {
                if (web == null)
                {
                    yield break;
                }

                beforeSend?.Invoke(web);

                // Send the web request
                yield return(web.SendWebRequest());

                // Write the error if we encounter one
                if (web.isNetworkError || web.isHttpError)
                {
                    downloadFailed?.Invoke(web);
                    Plugin.Log($"Http error {web.responseCode} occurred during web request to url {url}. Error: {web.error}");
                    yield break;
                }
                downloadCompleted?.Invoke(web);
            }
        }
Beispiel #21
0
 string GetDestPath(DownloadType type, string fileName)
 {
     return
         (Utils.GetAlternativeFileName(Utils.MakePath(plasmaDownloader.SpringPaths.WritableDirectory, type == DownloadType.MAP?"maps":"games", fileName)));
 }
Beispiel #22
0
 /// <summary>
 /// The add new url.
 /// </summary>
 /// <param name="url">The download url.</param>
 /// <param name="type">The download type.</param>
 /// <param name="section">The download section.</param>
 /// <param name="threadId">The thread id.</param>
 /// <param name="ignoreCache">Ignore cache.</param>
 /// <param name="cookieContainer">The cookie container.</param>
 /// <returns>Return DownloadItem</returns>
 public static DownloadItem AddNewUrl(
     string url, 
     DownloadType type, 
     Section section, 
     int threadId, 
     bool ignoreCache, 
     CookieContainer cookieContainer = null)
 {
     return new DownloadItem
         {
             Url = url,
             Type = type,
             Section = section,
             CookieContainer = cookieContainer,
             IgnoreCache = ignoreCache
         };
 }
Beispiel #23
0
        /// <summary>
        /// 获取文件夹已经下载的文件信息
        /// </summary>
        /// <returns></returns>
        public static async Task <ResultData> GetList(DownloadType type)
        {
            try
            {
                IReadOnlyList <StorageFile> files = null;
                StorageFolder folder = null;
                folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists);

                switch (type)
                {
                case DownloadType.song:
                    folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists);

                    break;

                case DownloadType.mv:
                    folder = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists);

                    break;

                case DownloadType.other:
                    folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists);

                    break;

                default:
                    break;
                }
                files = await folder.GetFilesAsync();

                //DataConnect.transfersModel = transfers;//未下载成功的文件Item
                //DataConnect.filesModel = files;//下载成功的文件Item
                //await DiscoverActiveDownloadsAsync(type);
                var result = new ResultData();
                result.transfers = new ObservableCollection <TransferModel>();
                result.files     = files.ToList();
                if (transfers.Count > 0)
                {
                    foreach (var item in transfers)
                    {
                        string flag = "";
                        switch (type)
                        {
                        case DownloadType.song:
                            flag = "song";
                            break;

                        case DownloadType.mv:
                            flag = "mv";
                            break;

                        case DownloadType.other:
                            flag = "other";
                            break;

                        default:
                            break;
                        }
                        if (item.DownloadOperation.TransferGroup.Name == flag)
                        {
                            result.transfers.Add(item);
                        }
                    }
                }
                return(result);
            }
            catch { return(null); }
        }
Beispiel #24
0
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string url = txtInput.Text;

            this.Cursor = Cursors.WaitCursor;

            IPlugin selectedPlugin = null;

            //如果有可用插件
            if (supportedPlugins.Count > 0)
            {
                selectedPlugin = supportedPlugins[cboPlugins.SelectedIndex];

                //取得此url的hash
                string hash = selectedPlugin.GetHash(url);
                //检查是否有已经在进行的相同任务
                foreach (TaskInfo task in CoreManager.TaskManager.TaskInfos)
                {
                    if (hash.Equals(task.Hash, StringComparison.InvariantCultureIgnoreCase))
                    {
                        toolTip.Show("当前任务已经存在", txtInput, 4000);
                        this.Cursor = Cursors.Default;
                        return;
                    }
                }
                try
                {
                    //取得[代理设置]
                    WebProxy selectedProxy = null;
                    if (cboProxy.SelectedIndex == 0)                     //IE设置
                    //将WebProxy设置为null可以使用默认IE设置
                    //与WebRequest.DefaultWebProxy的区别在于设置为null时不会自动检测代理设置
                    //详情请见 http://msdn.microsoft.com/en-us/library/fze2ytx2.aspx
                    {
                        selectedProxy = null;
                    }
                    else if (cboProxy.SelectedIndex == 1)                     //直接连接
                    {
                        selectedProxy = new WebProxy();
                    }
                    else if (CoreManager.ConfigManager.Settings.Proxy_Settings != null)
                    {
                        foreach (AcDownProxy item in CoreManager.ConfigManager.Settings.Proxy_Settings)
                        {
                            if (item.Name == cboProxy.SelectedItem.ToString())
                            {
                                selectedProxy = item.ToWebProxy();
                                break;
                            }
                        }
                    }

                    //取得[AutoAnswer设置]
                    List <AutoAnswer> aa = new List <AutoAnswer>();
                    if (chkAutoAnswer.Checked)
                    {
                        if (selectedPlugin.Feature != null)
                        {
                            if (selectedPlugin.Feature.ContainsKey("AutoAnswer"))
                            {
                                aa = (List <AutoAnswer>)selectedPlugin.Feature["AutoAnswer"];
                                if (aa.Count > 0)
                                {
                                    FormAutoAnswer faa = new FormAutoAnswer(aa);
                                    faa.TopMost = this.TopMost;
                                    var result = faa.ShowDialog();
                                    if (result == System.Windows.Forms.DialogResult.Cancel)
                                    {
                                        this.Cursor = Cursors.Default;
                                        return;
                                    }
                                }
                            }
                        }
                    }

                    //添加任务
                    TaskInfo task = CoreManager.TaskManager.AddTask(selectedPlugin, url.Trim(), selectedProxy);
                    //设置[保存目录]
                    task.SaveDirectory = new DirectoryInfo(cboPath.Text);
                    //设置[下载类型]
                    DownloadType ds = DownloadType.None;
                    if (lstDownloadType.GetItemChecked(0))
                    {
                        ds = ds | DownloadType.Video;
                    }
                    if (lstDownloadType.GetItemChecked(1))
                    {
                        ds = ds | DownloadType.Audio;
                    }
                    if (lstDownloadType.GetItemChecked(2))
                    {
                        ds = ds | DownloadType.Picture;
                    }
                    if (lstDownloadType.GetItemChecked(3))
                    {
                        ds = ds | DownloadType.Text;
                    }
                    if (lstDownloadType.GetItemChecked(4))
                    {
                        ds = ds | DownloadType.Subtitle;
                    }
                    if (lstDownloadType.GetItemChecked(5))
                    {
                        ds = ds | DownloadType.Comment;
                    }
                    task.DownloadTypes = ds;
                    //设置[提取浏览器缓存]
                    task.ExtractCache = chkExtractCache.Checked;
                    //设置[解析关联视频]
                    task.ParseRelated = chkParseRelated.Checked;
                    //设置[自动应答]
                    task.AutoAnswer = aa;
                    //设置注释
                    task.Comment = txtComment.Text;


                    //开始下载
                    CoreManager.TaskManager.StartTask(task);


                    this.Cursor = Cursors.Default;
                    this.Close();
                }
                catch (Exception ex)
                {
                    Logging.Add(ex);
                    toolTip.Show("新建任务出现错误:\n" + ex.Message, btnAdd, 4000);
                }
            }
            else
            {
                toolTip.Show("您所输入的网络地址(URL)不符合规则。\n没有支持解析此网址的插件,请您检查后重新输入", txtInput, 3000);
                txtInput.SelectAll();
            }
            this.Cursor = Cursors.Default;
        }
Beispiel #25
0
 /// <summary>
 /// Download image of specified type to a file. (handles server errors for WMS type)
 /// </summary>
 public void DownloadFile(string destinationFile, DownloadType dlType)
 {
     DownloadType = dlType;
     DownloadFile(destinationFile);
 }
Beispiel #26
0
 /// <summary>
 /// Download image of specified type. (handles server errors for WMS type)
 /// </summary>
 /// <param name="dlType">Type of download.</param>
 public void BackgroundDownloadMemory(DownloadType dlType)
 {
     DownloadType = dlType;
     BackgroundDownloadMemory();
 }
        private Nullable <DownloadItem> getDownloadItem(TitleInfo item, DownloadType type)
        {
            TitleInfo info;

            lock (item)
            {
                info = item;
            }

            switch (type)
            {
            case DownloadType.Game:
                if (!info.isUpdate)
                {
                    try
                    {
                        bool madeTicket = false;
                        TMD  titleTMD   = AsyncHelpers.RunSync <TMD>(() => NUS.DownloadTMD(info.titleID));

                        if (info.ticket.Length == 0 && info.hasTicket)
                        {
                            info.ticket = AsyncHelpers.RunSync <byte[]>(() => HelperFunctions.DownloadTitleKeyWebsiteTicket(info.titleID));
                        }


                        if (!info.hasTicket && info.titleKey.Length > 0)
                        {
                            madeTicket  = true;
                            info.ticket = info.getGeneratedTitleTicket(titleTMD.TitleVersion);
                        }

                        return(new DownloadItem(
                                   info.displayName + (madeTicket ? " (FakeSign)" : ""),
                                   titleTMD,
                                   AsyncHelpers.RunSync <NUS.UrlFilenamePair[]>(() => NUS.GetTitleContentURLs(titleTMD, true)),
                                   info.ticket,
                                   null,
                                   null,
                                   madeTicket
                                   ));
                    }
                    catch { }
                }
                break;

            case DownloadType.DLC:
                try
                {
                    if (info.dlcKey.Length > 0)
                    {
                        TMD dlcTMD = AsyncHelpers.RunSync <TMD>(() => NUS.DownloadTMD(info.dlcID));

                        return(new DownloadItem(
                                   info.DisplayNameWithVersion(dlcTMD.TitleVersion, "DLC") + " (FakeSign)",
                                   dlcTMD,
                                   AsyncHelpers.RunSync <NUS.UrlFilenamePair[]>(() => NUS.GetTitleContentURLs(dlcTMD, true)),
                                   info.getDLCTicket(dlcTMD.TitleVersion),
                                   null,
                                   null,
                                   true
                                   ));
                    }
                }
                catch { }
                break;

            case DownloadType.Update:
                try
                {
                    TMD updateTMD = AsyncHelpers.RunSync <TMD>(() => NUS.DownloadTMD(info.updateID));
                    return(new DownloadItem(
                               info.DisplayNameWithVersion(updateTMD.TitleVersion, "Update"),
                               updateTMD,
                               AsyncHelpers.RunSync <NUS.UrlFilenamePair[]>(() => NUS.GetTitleContentURLs(updateTMD, true)),
                               AsyncHelpers.RunSync <byte[]>(() => NUS.DownloadTicket(info.updateID))
                               ));
                }
                catch { }
                break;
            }
            return(null);
        }
 public TaskQueueValues(TitleInfo info, DownloadType type)
 {
     this.info = info;
     this.type = type;
 }
Beispiel #29
0
        public Download GetResource(DownloadType type, string name)
        {
            if (name == "zk:dev" || name == "Zero-K $VERSION")
            {
                return(null);
            }
            lock (downloads)
            {
                downloads.RemoveAll(x => x.IsAborted || x.IsComplete != null); // remove already completed downloads from list}
                var existing = downloads.FirstOrDefault(x => x.Name == name || x.Alias == name);
                if (existing != null)
                {
                    return(existing);
                }
            }

            if (scanner?.HasResource(name) == true)
            {
                return(null);
            }
            if (SpringPaths.HasEngineVersion(name))
            {
                return(null);
            }


            // check rapid to determine type
            if (type == DownloadType.NOTKNOWN)
            {
                if (packageDownloader.GetByInternalName(name) != null || packageDownloader.GetByTag(name) != null)
                {
                    type = DownloadType.RAPID;
                }
                else
                {
                    packageDownloader.LoadMasterAndVersions().Wait();
                    if (packageDownloader.GetByInternalName(name) != null || packageDownloader.GetByTag(name) != null)
                    {
                        type = DownloadType.RAPID;
                    }
                    else
                    {
                        type = DownloadType.MAP;
                    }
                }
            }


            lock (downloads)
            {
                if (type == DownloadType.DEMO)
                {
                    var target     = new Uri(name);
                    var targetName = target.Segments.Last();
                    var filePath   = Utils.MakePath(SpringPaths.WritableDirectory, "demos", targetName);
                    if (File.Exists(filePath))
                    {
                        return(null);
                    }
                    var down = new WebFileDownload(name, filePath, null);
                    down.DownloadType = type;
                    downloads.Add(down);
                    DownloadAdded.RaiseAsyncEvent(this, new EventArgs <Download>(down)); //create dowload bar (handled by MainWindow.cs)
                    down.Start();
                    return(down);
                }


                if (type == DownloadType.MAP || type == DownloadType.MISSION)
                {
                    if (torrentDownloader == null)
                    {
                        torrentDownloader = new TorrentDownloader(this);                            //lazy initialization
                    }
                    var down = torrentDownloader.DownloadTorrent(name);
                    if (down != null)
                    {
                        down.DownloadType = type;
                        downloads.Add(down);
                        DownloadAdded.RaiseAsyncEvent(this, new EventArgs <Download>(down));
                        return(down);
                    }
                }

                if (type == DownloadType.RAPID)
                {
                    var down = packageDownloader.GetPackageDownload(name);
                    if (down != null)
                    {
                        down.DownloadType = type;
                        down.Alias        = name;
                        downloads.Add(down);
                        DownloadAdded.RaiseAsyncEvent(this, new EventArgs <Download>(down));
                        return(down);
                    }
                }



                if (type == DownloadType.ENGINE)
                {
                    var down = new EngineDownload(name, SpringPaths);
                    down.DownloadType = type;
                    downloads.Add(down);
                    DownloadAdded.RaiseAsyncEvent(this, new EventArgs <Download>(down));
                    down.Start();
                    return(down);
                }

                return(null);
            }
        }
Beispiel #30
0
 public DownloadItem(DownloadType type, string name)
 {
     DType    = type;
     ItemName = name;
 }
Beispiel #31
0
 public async Task <FileDownloadDto> GetDownloadAsync(int urn, DownloadType format, IPrincipal principal)
 => (await _httpClient.GetAsync <FileDownloadDto>($"establishment/{urn}/download?format={format.ToString().ToLower()}", principal)).GetResponse();
Beispiel #32
0
 /// <summary>
 /// Download image of specified type. (handles server errors for wms type)
 /// </summary>
 public void BackgroundDownloadFile(DownloadType dlType)
 {
     DownloadType = dlType;
     BackgroundDownloadFile();
 }
Beispiel #33
0
 /// <summary>
 /// Download image of specified type. (handles server errors for WMS type)
 /// </summary>
 public void DownloadMemory(DownloadType dlType)
 {
     DownloadType = dlType;
     DownloadMemory();
 }
        public async Task DownloadAsync(IProgress <ProgressReport> progress, CancellationToken cancellationToken)
        {
            using (WebClient client = new WebClient())
            {
                client.Encoding = Encoding.UTF8;
                client.Headers.Add("Accept", "application/vnd.twitchtv.v5+json; charset=UTF-8");
                client.Headers.Add("Client-Id", "kimne78kx3ncx6brgo4mv6wki5h1ko");

                DownloadType downloadType = downloadOptions.Id.All(x => Char.IsDigit(x)) ? DownloadType.Video : DownloadType.Clip;
                string       videoId      = "";

                JObject result   = new JObject();
                JObject video    = new JObject();
                JObject streamer = new JObject();
                JArray  comments = new JArray();

                double videoStart    = 0.0;
                double videoEnd      = 0.0;
                double videoDuration = 0.0;

                if (downloadType == DownloadType.Video)
                {
                    videoId = downloadOptions.Id;
                    JObject taskInfo = await TwitchHelper.GetVideoInfo(Int32.Parse(videoId));

                    streamer["name"] = taskInfo["channel"]["display_name"];
                    streamer["id"]   = taskInfo["channel"]["_id"];
                    videoStart       = downloadOptions.CropBeginning ? downloadOptions.CropBeginningTime : 0.0;
                    videoEnd         = downloadOptions.CropEnding ? downloadOptions.CropEndingTime : taskInfo["length"].ToObject <double>();
                }
                else
                {
                    JObject taskInfo = await TwitchHelper.GetClipInfo(downloadOptions.Id);

                    videoId = taskInfo["vod"]["id"].ToString();
                    downloadOptions.CropBeginning     = true;
                    downloadOptions.CropBeginningTime = taskInfo["vod"]["offset"].ToObject <int>();
                    downloadOptions.CropEnding        = true;
                    downloadOptions.CropEndingTime    = downloadOptions.CropBeginningTime + taskInfo["duration"].ToObject <double>();
                    streamer["name"] = taskInfo["broadcaster"]["display_name"];
                    streamer["id"]   = taskInfo["broadcaster"]["id"];
                    videoStart       = taskInfo["vod"]["offset"].ToObject <double>();
                    videoEnd         = taskInfo["vod"]["offset"].ToObject <double>() + taskInfo["duration"].ToObject <double>();
                }

                video["start"] = videoStart;
                video["end"]   = videoEnd;
                videoDuration  = videoEnd - videoStart;

                double latestMessage = videoStart - 1;
                bool   isFirst       = true;
                string cursor        = "";

                while (latestMessage < videoEnd)
                {
                    string response;
                    if (isFirst)
                    {
                        response = await client.DownloadStringTaskAsync(String.Format("https://api.twitch.tv/v5/videos/{0}/comments?content_offset_seconds={1}", videoId, videoStart));
                    }
                    else
                    {
                        response = await client.DownloadStringTaskAsync(String.Format("https://api.twitch.tv/v5/videos/{0}/comments?cursor={1}", videoId, cursor));
                    }

                    JObject res = JObject.Parse(response);

                    foreach (var comment in res["comments"])
                    {
                        if (latestMessage < videoEnd && comment["content_offset_seconds"].ToObject <double>() > videoStart)
                        {
                            comments.Add(comment);
                        }

                        latestMessage = comment["content_offset_seconds"].ToObject <double>();
                    }
                    if (res["_next"] == null)
                    {
                        break;
                    }
                    else
                    {
                        cursor = res["_next"].ToString();
                    }

                    int percent = (int)Math.Floor((latestMessage - videoStart) / videoDuration * 100);
                    progress.Report(new ProgressReport()
                    {
                        reportType = ReportType.Percent, data = percent
                    });
                    progress.Report(new ProgressReport()
                    {
                        reportType = ReportType.Message, data = $"Downloading {percent}%"
                    });

                    cancellationToken.ThrowIfCancellationRequested();

                    if (isFirst)
                    {
                        isFirst = false;
                    }
                }

                result["streamer"] = streamer;
                result["comments"] = comments;
                result["video"]    = video;

                if (downloadOptions.EmbedEmotes && downloadOptions.IsJson)
                {
                    progress.Report(new ProgressReport()
                    {
                        reportType = ReportType.Message, data = "Downloading + Embedding Emotes"
                    });
                    result["emotes"] = new JObject();
                    JArray firstParty = new JArray();
                    JArray thirdParty = new JArray();

                    string cacheFolder = Path.Combine(Path.GetTempPath(), "TwitchDownloader", "cache");
                    List <ThirdPartyEmote> thirdPartyEmotes = new List <ThirdPartyEmote>();
                    List <KeyValuePair <string, SKBitmap> > firstPartyEmotes = new List <KeyValuePair <string, SKBitmap> >();

                    await Task.Run(() => {
                        thirdPartyEmotes = TwitchHelper.GetThirdPartyEmotes(streamer["id"].ToObject <int>(), cacheFolder);
                        firstPartyEmotes = TwitchHelper.GetEmotes(result["comments"].ToObject <List <Comment> >(), cacheFolder).ToList();
                    });

                    foreach (ThirdPartyEmote emote in thirdPartyEmotes)
                    {
                        JObject newEmote = new JObject();
                        newEmote["id"]         = emote.id;
                        newEmote["imageScale"] = emote.imageScale;
                        newEmote["data"]       = emote.imageData;
                        newEmote["name"]       = emote.name;
                        thirdParty.Add(newEmote);
                    }
                    foreach (KeyValuePair <string, SKBitmap> emote in firstPartyEmotes)
                    {
                        JObject newEmote = new JObject();
                        newEmote["id"]         = emote.Key;
                        newEmote["imageScale"] = 1;
                        newEmote["data"]       = SKImage.FromBitmap(emote.Value).Encode(SKEncodedImageFormat.Png, 100).ToArray();
                        firstParty.Add(newEmote);
                    }

                    result["emotes"]["thirdParty"] = thirdParty;
                    result["emotes"]["firstParty"] = firstParty;
                }

                using (StreamWriter sw = new StreamWriter(downloadOptions.Filename))
                {
                    if (downloadOptions.IsJson)
                    {
                        sw.Write(result.ToString(Formatting.None));
                    }
                    else
                    {
                        foreach (var comment in result["comments"])
                        {
                            string username = comment["commenter"]["display_name"].ToString();
                            string message  = comment["message"]["body"].ToString();
                            if (downloadOptions.Timestamp)
                            {
                                string timestamp = comment["created_at"].ToObject <DateTime>().ToString("u").Replace("Z", " UTC");
                                sw.WriteLine(String.Format("[{0}] {1}: {2}", timestamp, username, message));
                            }
                            else
                            {
                                sw.WriteLine(String.Format("{0}: {1}", username, message));
                            }
                        }
                    }

                    sw.Flush();
                    sw.Close();
                    result = null;
                }
            }
        }
Beispiel #35
0
 /// <summary>
 /// Download image of specified type to a file. (handles server errors for WMS type)
 /// </summary>
 public void DownloadFile(string destinationFile, DownloadType dlType)
 {
     DownloadType = dlType;
     DownloadFile(destinationFile);
 }
        private void DownloadAsync (Uri uri, DownloadType type, object state)
        {
            this.uri = uri;
            this.type = type;
            this.userState = state;

            ImplDownloadAsync ();
        }
Beispiel #37
0
 /// <summary>
 /// Download image of specified type. (handles server errors for WMS type)
 /// </summary>
 public void DownloadMemory(DownloadType dlType)
 {
     DownloadType = dlType;
     DownloadMemory();
 }
 private void Reset ()
 {
     lock (cancelBusySync) {
         busy = false;
         cancelled = false;
         completed = false;
         error = null;
         fileName = String.Empty;
         ifModifiedSince = DateTime.MinValue;
         range = 0;
         type = DownloadType.None;
         uri = null;
         userState = null;
     }
 }
Beispiel #39
0
 public void CreateRequest(DownloadType Type, RequestCallback Callback, string URL, string Path = "")
 {
     switch (Type)
     {
         case DownloadType.API:
             APIRequests.Enqueue(new Request(Callback, URL, Path));
             break;
         case DownloadType.Wallpaper:
             WallpaperRequests.Enqueue(new Request(Callback, URL, Path));
             break;
         case DownloadType.Thumbnail:
             ThumbnailRequests.Enqueue(new Request(Callback, URL, Path));
             break;
     }
 }
Beispiel #40
0
    //资源有带前缀"ftp://"
    public DownloadData AddMultiResDownload(DownloadType dt, List <ServerIPData> serverList, List <DownResData> resList, object obj = null)
    {
        if (m_DownList.HasSpace() == false)
        {
            return(null);
        }
        MultiFileDownData mfdd = new MultiFileDownData();

        mfdd.CompletionList   = new MultiFileOK[resList.Count];
        mfdd.FTPIPList        = new List <ServerIPData>();
        mfdd.FileList         = new List <DownResData>();
        mfdd.OutsideRecvIndex = 0;
        mfdd.RecvCount        = 0;
        mfdd.CurrentRecvSize  = 0;
        mfdd.ExtraData        = obj;
        mfdd.RecvFileList     = new RecvFileDataFlag[resList.Count];
        List <ServerIPData> ipList1 = new List <ServerIPData>();
        List <ServerIPData> ipList2 = new List <ServerIPData>();

        for (int i = 0; i < serverList.Count; ++i)
        {
            if (serverList[i].ISP == ISP_TYPE || serverList[i].ISP == (byte)ISPType.ISP_YD || ISP_TYPE == (byte)ISPType.ISP_YD)
            {
                ipList1.Add(serverList[i]);
            }
            //else
            //  ipList2.Add(sip);
        }
        if (ipList1.Count == 0)
        {
            for (int i = 0; i < serverList.Count; ++i)
            {
                ipList1.Add(serverList[i]);
            }
        }
        for (int i = 0; i < resList.Count; ++i)
        {
            mfdd.RecvFileList[i] = new RecvFileDataFlag();
            DownResData drd = resList[i];
            string      url = drd.ResUrl.ToLower();
            int         idx = url.IndexOf("fishpublish");
            if (idx == -1)
            {
                return(null);
            }
            drd.ResUrl = url.Substring(idx, url.Length - idx);
            mfdd.FileList.Add(drd);
        }
        //将FTP排队
        for (int i = 0; i < ipList1.Count;)
        {
            int idx = Utility.Range(0, ipList1.Count);
            if (idx >= ipList1.Count)
            {
                idx = ipList1.Count - 1;
            }
            mfdd.FTPIPList.Add(ipList1[idx]);
            ipList1.RemoveAt(idx);
        }
        for (int i = 0; i < ipList2.Count;)
        {
            int idx = Utility.Range(0, ipList2.Count);
            if (idx >= ipList2.Count)
            {
                idx = ipList2.Count - 1;
            }
            mfdd.FTPIPList.Add(ipList2[idx]);
            ipList2.RemoveAt(idx);
        }
        DownloadData dd = new DownloadData(null, mfdd, dt);

        dd.DownState = DownloadState.DS_DOWNLOADING;
        m_DownList.AddItem(dd);
        return(dd);
    }
Beispiel #41
0
        private async void btnGetInfo_Click(object sender, RoutedEventArgs e)
        {
            string id = ValidateUrl(textUrl.Text);

            if (id != "")
            {
                btnGetInfo.IsEnabled = false;
                downloadId           = id;
                if (id.All(Char.IsDigit))
                {
                    downloadType = DownloadType.Video;
                }
                else
                {
                    downloadType = DownloadType.Clip;
                }

                try
                {
                    if (downloadType == DownloadType.Video)
                    {
                        Task <JObject> taskInfo = TwitchHelper.GetVideoInfo(Int32.Parse(downloadId));
                        await Task.WhenAll(taskInfo);

                        videoData = taskInfo.Result;
                        string             thumbUrl  = taskInfo.Result["preview"]["medium"].ToString();
                        Task <BitmapImage> taskThumb = InfoHelper.GetThumb(thumbUrl);

                        try
                        {
                            await taskThumb;
                        }
                        catch
                        {
                            AppendLog("ERROR: Unable to find thumbnail");
                        }
                        if (!taskThumb.IsFaulted)
                        {
                            imgThumbnail.Source = taskThumb.Result;
                        }
                        textTitle.Text     = taskInfo.Result["title"].ToString();
                        textStreamer.Text  = taskInfo.Result["channel"]["display_name"].ToString();
                        textCreatedAt.Text = taskInfo.Result["created_at"].ToString();
                        currentVideoTime   = taskInfo.Result["created_at"].ToObject <DateTime>().ToLocalTime();
                        streamerId         = taskInfo.Result["channel"]["_id"].ToObject <int>();
                        SetEnabled(true, false);
                    }
                    else if (downloadType == DownloadType.Clip)
                    {
                        string         clipId   = downloadId;
                        Task <JObject> taskInfo = TwitchHelper.GetClipInfo(clipId);
                        await Task.WhenAll(taskInfo);

                        JToken clipData = taskInfo.Result;
                        videoData = taskInfo.Result;
                        string             thumbUrl  = clipData["thumbnails"]["medium"].ToString();
                        Task <BitmapImage> taskThumb = InfoHelper.GetThumb(thumbUrl);
                        await Task.WhenAll(taskThumb);

                        imgThumbnail.Source = taskThumb.Result;
                        textStreamer.Text   = clipData["broadcaster"]["display_name"].ToString();
                        textCreatedAt.Text  = clipData["created_at"].ToString();
                        currentVideoTime    = clipData["created_at"].ToObject <DateTime>().ToLocalTime();
                        textTitle.Text      = clipData["title"].ToString();
                        streamerId          = clipData["broadcaster"]["id"].ToObject <int>();
                        SetEnabled(true, false);
                        SetEnabled(false, true);
                    }

                    btnGetInfo.IsEnabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Unable to get Clip/Video information. Please double check your link and try again", "Unable to get info", MessageBoxButton.OK, MessageBoxImage.Error);
                    AppendLog("ERROR: " + ex.Message);
                    btnGetInfo.IsEnabled = true;
                }
            }
            else
            {
                MessageBox.Show("Please double check the VOD/Clip link", "Unable to parse input", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        public Download GetResource(DownloadType type, string name)
        {
            if (name == "zk:dev" || name == "Zero-K $VERSION") return null;
            lock (downloads)
            {
                downloads.RemoveAll(x => x.IsAborted || x.IsComplete != null); // remove already completed downloads from list}
                var existing = downloads.FirstOrDefault(x => x.Name == name || x.Alias == name);
                if (existing != null) return existing;
            }

            if (scanner?.HasResource(name) == true) return null;
            if (SpringPaths.HasEngineVersion(name)) return null;


            // check rapid to determine type
            if (type == DownloadType.NOTKNOWN)
            {
                if (packageDownloader.GetByInternalName(name) != null || packageDownloader.GetByTag(name) != null) type = DownloadType.RAPID;
                else
                {
                    packageDownloader.LoadMasterAndVersions().Wait();
                    if (packageDownloader.GetByInternalName(name) != null || packageDownloader.GetByTag(name) != null) type = DownloadType.RAPID;
                    else type = DownloadType.MAP;
                } 
            }
            

            lock (downloads)
            {

                if (type == DownloadType.DEMO)
                {
                    var target = new Uri(name);
                    var targetName = target.Segments.Last();
                    var filePath = Utils.MakePath(SpringPaths.WritableDirectory, "demos", targetName);
                    if (File.Exists(filePath)) return null;
                    var down = new WebFileDownload(name, filePath, null);
                    down.DownloadType = type;
                    downloads.Add(down);
                    DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down)); //create dowload bar (handled by MainWindow.cs)
                    down.Start();
                    return down;
                }


                if (type == DownloadType.MAP || type == DownloadType.MISSION)
                {
                    if (torrentDownloader == null) torrentDownloader = new TorrentDownloader(this); //lazy initialization
                    var down = torrentDownloader.DownloadTorrent(name);
                    if (down != null)
                    {
                        down.DownloadType = type;
                        downloads.Add(down);
                        DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down));
                        return down;
                    }
                }

                if (type == DownloadType.RAPID)
                {
                    var down = packageDownloader.GetPackageDownload(name);
                    if (down != null)
                    {
                        down.DownloadType = type;
                        down.Alias = name;
                        downloads.Add(down);
                        DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down));
                        return down;
                    }
                }



                if (type == DownloadType.ENGINE)
                {
                    var down = new EngineDownload(name, SpringPaths);
                    down.DownloadType = type;
                    downloads.Add(down);
                    DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down));
                    down.Start();
                    return down;
                }

                return null;
            }
        }
Beispiel #43
0
        /// <summary>
        /// 要下载调用这个方法
        /// </summary>
        /// <param name="url">下载的文件网址的来源</param>
        /// <returns></returns>
        public static async Task Start(string filename, string url, DownloadType type, StorageFolder folder = null)
        {
            try
            {
                Uri uri = new Uri(Uri.EscapeUriString(url), UriKind.RelativeOrAbsolute);
                BackgroundDownloader downloader = new BackgroundDownloader();
                string extname = "";
                if (folder == null)
                {
                    folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists);

                    switch (type)
                    {
                    case DownloadType.song:
                        switch (KuGouUWP.Class.Setting.DownQu.GetType())
                        {
                        case KuGouUWP.Class.Setting.DownQu.Type.low:
                            extname = ".mp3";
                            break;

                        case KuGouUWP.Class.Setting.DownQu.Type.mid:
                            extname = ".mp3";
                            break;

                        case KuGouUWP.Class.Setting.DownQu.Type.high:
                            extname = ".flac";
                            break;

                        default:
                            break;
                        }
                        folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists);

                        downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("song");
                        break;

                    case DownloadType.mv:
                        extname = ".mp4";
                        folder  = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists);

                        downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("mv");
                        break;

                    case DownloadType.other:
                        folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists);

                        downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                        break;

                    default:
                        break;
                    }
                }
                else
                {
                    downloader.TransferGroup = BackgroundTransferGroup.CreateGroup("other");
                }
                //string name = uri.ToString().Substring(uri.ToString().LastIndexOf("/"), uri.ToString().Length);
                string      name = filename + extname;;
                StorageFile file = await folder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting);

                downloader.FailureToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Fa);
                downloader.SuccessToastNotification = DownloadedToast.Done(filename, DownloadedToast.DownResult.Su);
                var           download = downloader.CreateDownload(new Uri(url), file);
                TransferModel transfer = new TransferModel();
                transfer.DownloadOperation   = download;
                transfer.Source              = download.RequestedUri.ToString();
                transfer.Destination         = download.ResultFile.Path;
                transfer.BytesReceived       = download.Progress.BytesReceived;
                transfer.TotalBytesToReceive = download.Progress.TotalBytesToReceive;
                transfer.Progress            = 0;
                transfers.Add(transfer);
                Progress <DownloadOperation> progressCallback = new Progress <DownloadOperation>(DownloadProgress);
                download.StartAsync().AsTask(cancelToken.Token, progressCallback);
                if (type != DownloadType.song)
                {
                    await new MessageDialog(ResourceLoader.GetForCurrentView().GetString("AddDownSuccess")).ShowAsync();
                }
            }
            catch
            {
                await new MessageDialog(ResourceLoader.GetForCurrentView().GetString("AddDownFalied")).ShowAsync();
            }
        }
 public static Task <bool> DownloadFile(this PlasmaDownloader downloader, DownloadType type,
                                        string name,
                                        IChobbylaProgress progress) => DownloadFile(downloader, name, type, name, progress);
 private async Task<bool> DownloadFile(string desc, DownloadType type, string name)
 {
     Status = desc;
     Download = downloader.GetResource(type,  name);
     var dlTask = Download?.WaitHandle.AsTask(TimeSpan.FromMinutes(30));
     if (dlTask != null) await dlTask;
     if (Download?.IsComplete == false)
     {
         Status = $"Download of {Download.Name} has failed";
         return false;
     }
     return true;
 }
 /// <summary>
 ///     Starts a new download item and adds it to the downloads page.
 /// </summary>
 /// <param name="name">Name of the download.</param>
 /// <param name="url">URL of file to download.</param>
 /// <param name="type">Type of download.</param>
 /// <param name="description">Game description, used in the case of game downloads.</param>
 private void AddDownload(string name, string url, DownloadType type, GameDescription description)
 {
     DownloadItem download = new DownloadItem(name, url, type, description);
     download.ListViewItem = new ListViewItem(new string[] { "", download.Name, "Unknown", "Unknown", "Unknown" });
     download.ListViewItem.StateImageIndex = 0;
     downloadsListView.Items.Add(download.ListViewItem);
     _downloads.Add(download);
     SyncronizeWindow();
 }
Beispiel #47
0
 // Update is called once per frame
 void Update()
 {
     //查看http请求是否有返回了
     if (bIsBeginRequest)
     {
         //下载是否结束了
         if (_www.isDone)
         {
             if (_www.error != null)
             {
                 Debug.Log(_www.error);
                 //回调
                 if (this.errorHandlerDelegate != null)
                 {
                     this.errorHandlerDelegate.Invoke(_www.error);
                 }
             }
             else
             {
                 if (handlerDelegate != null)
                 {
                     if (downloadType == DownloadType.type_bytes ||
                         downloadType == DownloadType.type_assetBundle)
                     {
                         //二进制
                         handlerDelegate.Invoke(_www.bytes);
                     }
                     else if (downloadType == DownloadType.type_txt ||
                              downloadType == DownloadType.type_url)
                     {
                         //文本
                         handlerDelegate.Invoke(_www.text);
                     }
                 }
             }
             bIsDone         = true;
             bIsBeginRequest = false;
             handlerDelegate = null;
         }
     }
     else
     {
         //空闲时,开始下一个下载
         if (bIsDone)
         {
             if (downloadList.Count > 0)
             {
                 //取第一个下载项
                 DownloadItem downloadItem = downloadList[0];
                 downloadType    = downloadItem.downloadType;
                 url             = downloadItem.url;
                 handlerDelegate = downloadItem.callBack;
                 downloadList.RemoveAt(0);
                 if (downloadType == DownloadType.type_url)
                 {
                     byte[] requestParams = downloadItem.requestParams;
                     _www = new WWW(url, requestParams);//发送请求
                 }
                 else
                 {
                     _www = new WWW(url);
                 }
                 bIsBeginRequest = true;
                 bIsDone         = false;
             }
         }
     }
 }
Beispiel #48
0
 // Constructor
 public GenericObservable(DataFactory Factory, DownloadType type = DownloadType.Record, string OutputPath = "", string OutputName = "") : base(Factory, type, OutputPath, OutputPath)
 {
 }
Beispiel #49
0
 /// <summary>
 /// You can download an entire database in a single call using this method. Simply append /data to your database code, to get a zipped CSV file of the entire database.
 /// <a href="https://www.quandl.com/docs/api?csv#get-entire-database">Reference</a>
 /// </summary>
 /// <param name="code">Database code</param>
 /// <param name="downloadType">If “partial”, returns last day of data. If “complete”, returns entire database. Default is “complete”.</param>
 /// <param name="token">Cancellation token</param>
 /// <returns>Stream of zipped csv file (.zip)</returns>
 public async Task <Stream> GetZipAsync(DatabaseCode code, DownloadType downloadType = DownloadType.Complete, CancellationToken token = default(CancellationToken))
 => await GetZipAsync(code.ToEnumMemberValue(), downloadType, token);
Beispiel #50
0
 /// <summary>
 /// Download image of specified type. (handles server errors for wms type)
 /// </summary>
 public void BackgroundDownloadFile(DownloadType dlType)
 {
     DownloadType = dlType;
     BackgroundDownloadFile();
 }
Beispiel #51
0
 public DownloadStatusEventArgs(DownloadType downloadType, int completeCount, int totalCount)
 {
     DownloadType  = downloadType;
     CompleteCount = completeCount;
     TotalCount    = totalCount;
 }
Beispiel #52
0
 /// <summary>
 /// Download image of specified type. (handles server errors for WMS type)
 /// </summary>
 /// <param name="dlType">Type of download.</param>
 public void BackgroundDownloadMemory(DownloadType dlType)
 {
     DownloadType = dlType;
     BackgroundDownloadMemory();
 }
 /// <summary>
 /// 获取文件夹已经下载的文件信息
 /// </summary>
 /// <returns></returns>
 public static async Task<ResultData> GetList(DownloadType type)
 {
     try
     {
         IReadOnlyList<StorageFile> files = null;
         StorageFolder folder = null;
         folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists);
         switch (type)
         {
             case DownloadType.song:
                 folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists);
                 break;
             case DownloadType.mv:
                 folder = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists);
                 break;
             case DownloadType.other:
                 folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists);
                 break;
             default:
                 break;
         }
         files = await folder.GetFilesAsync();                
         //DataConnect.transfersModel = transfers;//未下载成功的文件Item
         //DataConnect.filesModel = files;//下载成功的文件Item
         //await DiscoverActiveDownloadsAsync(type);
         var result = new ResultData();
         result.transfers = new ObservableCollection<TransferModel>();
         result.files = files.ToList();
         if(transfers.Count>0)
         {
             foreach (var item in transfers)
             {
                 string flag = "";
                 switch (type)
                 {
                     case DownloadType.song:
                         flag = "song";
                         break;
                     case DownloadType.mv:
                         flag = "mv";
                         break;
                     case DownloadType.other:
                         flag = "other";
                         break;
                     default:
                         break;
                 }
                 if(item.DownloadOperation.TransferGroup.Name==flag)
                 {
                     result.transfers.Add(item);
                 }
             }
         }
         return result;
     }
     catch { return null; }
 }
 string GetDestPath(DownloadType type, string fileName)
 {
     return
         Utils.GetAlternativeFileName(Utils.MakePath(plasmaDownloader.SpringPaths.WritableDirectory , type== DownloadType.MAP?"maps":"games",fileName));
 }
        private bool validateArgs(Dictionary <string, string> cmdLineArgs)
        {
            //Get IP Address
            string ip = cmdLineArgs[reqArgs[0]]; //IP

            if (ip == null || !(IPAddress.TryParse(ip, out ipAddress)))
            {
                logger.Error("Parameter IP is not a valid IP Address");
                return(false);
            }

            filePath = cmdLineArgs[reqArgs[1]]; //FILE
            if (filePath == null || !(File.Exists(filePath)))
            {
                logger.Error("Sepcified File does not exist");
                return(false);
            }

            type = DownloadType.NONE;

            string downloadType = cmdLineArgs[reqArgs[2]]; //TYPE

            if (downloadType == null)
            {
                logger.Error("Invalid Download Type Specified");
                return(false);
            }

            switch (downloadType.ToUpper())
            {
            case "PARAM":
                type = DownloadType.PARAMETERS;
                logger.Debug("Downalod Parameer File");
                if (!Path.GetExtension(filePath).ToUpper().Equals(".PARFILE"))
                {
                    logger.Error("Download Type is Parameter File, but a parameter file was not passed.");
                    return(false);
                }
                break;

            case "MACRO":
                type = DownloadType.MACRO;
                logger.Debug("Downalod Macro File");
                if (!Path.GetExtension(filePath).ToUpper().Equals(".MACRO"))
                {
                    logger.Error("Download Type is Macro File, but a Macro file was not passed.");
                    return(false);
                }
                break;

            case  "ONBOARD":
                type = DownloadType.ONBOARD;
                logger.Debug("Downalod Onboard PLC File");
                if (!Path.GetExtension(filePath).ToUpper().Equals(".MACRO"))
                {
                    logger.Error("Download Type is Macro File, but a Macro file was not passed.");
                    return(false);
                }
                break;

            case  "FIRMWARE":
                type = DownloadType.FIRMWARE;
                logger.Debug("Downalod Firnware");

                if (!Path.GetExtension(filePath).ToUpper().Equals(".IMG"))
                {
                    logger.Error("Download Type is Firmware File, but a Firmware Image file was not passed.");
                    return(false);
                }

                //Not uspported yet
                logger.Error("Firmware download is not supported at this time");
                return(false);

            case  "MCI":
                type = DownloadType.MCI;
                logger.Debug("Downalod MCI PLC file");

                if (!Path.GetExtension(filePath).ToUpper().Equals(".UBA"))
                {
                    logger.Error("Download Type is MCI PLC Code File, but a Boot Application Image file was not passed.");
                    return(false);
                }

                // Not support
                logger.Error("MCI is not supported at this time");
                return(false);
            }
            return(true);
        }
 private void SetDownloadStatus(ThreadWatcher watcher, DownloadType downloadType, int completeCount, int totalCount)
 {
     string type;
     bool hideDetail = false;
     switch (downloadType) {
         case DownloadType.Page:
             type = totalCount == 1 ? "page" : "pages";
             hideDetail = totalCount == 1;
             break;
         case DownloadType.Image:
             type = "images";
             break;
         case DownloadType.Thumbnail:
             type = "thumbnails";
             break;
         default:
             return;
     }
     string status = hideDetail ? "Downloading " + type :
         String.Format("Downloading {0}: {1} of {2} completed", type, completeCount, totalCount);
     DisplayStatus(watcher, status);
 }
Beispiel #57
0
        private void DownloadPdf(Patent[] patents, DownloadType downloadType)
        {
            if (patents != null)
            {
                var queuePatents = new Queue <Patent>();


                pb_down.Maximum = patents.Length;
                pb_down.Value   = 0;
                if (downloadType == DownloadType.RegistrationCertificate)
                {
                    btn_down.Text = "取消";
                }
                if (downloadType == DownloadType.OffcActionOutgoing)
                {
                    btn_down2.Text = "取消";
                }


                Task.Run(async() =>
                {
                    var dir = $"{Directory.GetCurrentDirectory()}/download/{DateTime.Now.ToString("yyyyMMdd")}/{downloadType}";

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    foreach (var item in patents)
                    {
                        queuePatents.Enqueue(item);
                    }
                    var client = new WebClient();
                    while (queuePatents.Any())
                    {
                        try
                        {
                            if (downloadWait)
                            {
                                await Task.Delay(5000);
                                tbx_rst.Invoke(new MethodInvoker(() =>
                                {
                                    tbx_rst.AppendText($"下载文件暂停,等待恢复\r\n");
                                }));
                                continue;
                            }

                            if (CancellationTokenSourceDown.IsCancellationRequested)
                            {
                                queuePatents.Clear();
                                break;
                            }

                            var item      = queuePatents.Dequeue();
                            var localfile = $"{dir}/{item.Name}-{item.Num}.pdf";
                            if (downloadType == DownloadType.OffcActionOutgoing)
                            {
                                localfile = $"{dir}/{item.Name}-{item.Num}.html";
                            }

                            var cosoleinfo = $"{item.Name}-{item.Num} ";
                            if (!File.Exists(localfile))
                            {
                                if (downloadType == DownloadType.RegistrationCertificate)
                                {
                                    client.DownloadFile(item.PdfFile, localfile);
                                }
                                if (downloadType == DownloadType.OffcActionOutgoing)
                                {
                                    client.DownloadFile(item.OffcActionFile, localfile);
                                }

                                cosoleinfo += $" {downloadType} Download OK\r\n";
                            }
                            else
                            {
                                cosoleinfo += " File Exists\r\n";
                            }

                            tbx_rst.Invoke(new MethodInvoker(() =>
                            {
                                pb_down.PerformStep();
                                lb_down.Text = $"{pb_down.Value}/{pb_down.Maximum}";
                                tbx_rst.AppendText(cosoleinfo);
                            }));
                            await Task.Delay(new Random().Next(1000, 2000));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message, "错误");
                            break;
                        }
                    }



                    btn_down.Invoke(new MethodInvoker(() =>
                    {
                        if (downloadType == DownloadType.RegistrationCertificate)
                        {
                            btn_down.Text = "注册证书下载";
                        }
                        else
                        {
                            btn_down2.Text = "复审文件下载";
                        }

                        tbx_rst.AppendText(downloadType + " 下载完成\r\n");
                        downloadWait = false;
                    }));
                }, CancellationTokenSourceDown.Token);
            }
        }
Beispiel #58
0
        private void DownloadData(DownloadType downloadType, string parameter = "")
        {
            var client = new WebClient();
            XDocument document;

            if (downloadType == DownloadType.BasicUserInfo)
            {
                client.DownloadStringAsync(new Uri(string.Format(SourceURL, UserID)));
                client.DownloadStringCompleted += (s, e) =>
                    {
                        try
                        {
                            document = XDocument.Parse(e.Result);
                            PlayCount = document.Root.Element("{http://schemas.zune.net/profiles/2008/01}playcount").Value.ToString();

                            DownloadData(DownloadType.Badges);
                        }
                        catch
                        {
                            PlayCount = "0";
                        }
                    };
            }
            else if (downloadType == DownloadType.Badges)
            {
                client.DownloadStringAsync(new Uri(string.Format(BadgeURL, UserID)));
                client.DownloadStringCompleted += (s, e) =>
                    {
                        try
                        {
                            document = XDocument.Parse(e.Result);
                            BadgeCount = (from c in document.Root.Elements()
                                          where c.Name == "{http://www.w3.org/2005/Atom}entry"
                                          select c).Count().ToString();

                            DownloadData(DownloadType.RecentTracks);
                        }
                        catch
                        {
                            BadgeCount = "0";
                        }
                    };
            }
            else if (downloadType == DownloadType.RecentTracks)
            {
                client.DownloadStringAsync(new Uri(string.Format(RecentTracksURL, UserID)));
                client.DownloadStringCompleted += (s, e) =>
                {
                    try
                    {
                        document = XDocument.Parse(e.Result);
                        var selection = (from c in document.Root.Elements() where c.Name == "{http://www.w3.org/2005/Atom}entry" select c).Take(4);

                        foreach (XElement element in selection)
                        {
                            string albumID =  element.Element("{http://schemas.zune.net/catalog/music/2007/10}track")
                                .Element("{http://schemas.zune.net/catalog/music/2007/10}album")
                                .Element("{http://schemas.zune.net/catalog/music/2007/10}id").Value.Replace("urn:uuid:","");

                           DownloadData(DownloadType.AlbumImage, albumID);
                        }
                    }
                    catch
                    {

                    }
                };
            }
            else if (downloadType == DownloadType.AlbumImage)
            {
                client.DownloadStringAsync(new Uri(string.Format(AlbumURL, parameter)));
                client.DownloadStringCompleted += (s, e) =>
                {
                    try
                    {
                        document = XDocument.Parse(e.Result);
                        string imageID = document.Root.Element("{http://schemas.zune.net/catalog/music/2007/10}image")
                            .Value.Replace("urn:uuid:", "");

                        RecentTracks.Add(new BitmapImage(new Uri(string.Format(PictureURL, imageID))));
                    }
                    catch
                    {

                    }
                };
            }
        }
        public Download GetResource(DownloadType type, string name) {

            lock (downloads) {
                downloads.RemoveAll(x => x.IsAborted || x.IsComplete != null); // remove already completed downloads from list}
                var existing = downloads.FirstOrDefault(x => x.Name == name || x.Alias == name);
                if (existing != null) return existing;
            }

            if (scanner != null && scanner.HasResource(name)) return null;
            
           
            lock (downloads) {

                if (type == DownloadType.DEMO) {
                    var target = new Uri(name);
                    var targetName = target.Segments.Last();
                    var filePath = Utils.MakePath(SpringPaths.WritableDirectory, "demos", targetName);
                    if (File.Exists(filePath)) return null;
                    var down = new WebFileDownload(name, filePath, null);
                    downloads.Add(down);
                    DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down)); //create dowload bar (handled by MainWindow.cs)
                    down.Start();
                    return down;
                }

                if (type == DownloadType.MOD || type == DownloadType.UNKNOWN) {
                    var down = packageDownloader.GetPackageDownload(name);
                    if (down != null) {
                        down.Alias = name;
                        downloads.Add(down);
                        DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down));
                        return down;
                    }
                }

                if (type == DownloadType.MAP || type == DownloadType.MOD || type == DownloadType.UNKNOWN || type == DownloadType.MISSION) {
                    if (torrentDownloader == null) torrentDownloader = new TorrentDownloader(this); //lazy initialization
                    var down = torrentDownloader.DownloadTorrent(name);
                    if (down != null) {
                        downloads.Add(down);
                        DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down));
                        return down;
                    }
                }

                if (type == DownloadType.GAME) throw new ApplicationException(string.Format("{0} download not supported in this version", type));

                return null;
            }
        }
Beispiel #60
0
        private async Task<DataTable> DownloadByUri(string uri, DownloadType downloadtype)
        {
            using(var client = new System.Net.Http.HttpClient())
            {
                // Request headers
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);

                var response = await client.GetAsync(uri).ConfigureAwait(false);
                var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                // select response jobject from 
                JObject message = JsonConvert.DeserializeObject<JObject>(json.ToString());

                // deserialize json string to datatable, default format is class object
                if (downloadtype == DownloadType.ScheduledWork)
                {
                    return ResponseToScheduledWorkTable(message["response"].ToString());
                }
                else
                {
                    return JsonConvert.DeserializeObject<DataTable>(message["response"].ToString());
                }
            }
        }