Exemple #1
0
        public void AddDownloadRecord(string name, string classId, string memberId)
        {
            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(classId) || string.IsNullOrWhiteSpace(memberId))
            {
                return;
            }

            string postDate = DateTime.Today.ToString("yyyy/M/d");
            IDictionary <string, string> conditions = new Dictionary <string, string>();

            conditions.Add("Name", name);
            conditions.Add("ClassId", classId);
            conditions.Add("MemberId", memberId);
            conditions.Add("PostDate", postDate);

            ////今天下載過就不再紀錄
            if (m_FTISService.GetDownloadRecordCount(conditions) == 0)
            {
                DownloadRecord downloadRecord = new DownloadRecord()
                {
                    Name     = name,
                    ClassId  = classId,
                    Member   = m_FTISService.GetMemberById(int.Parse(memberId)),
                    PostDate = postDate
                };
                m_FTISService.CreateDownloadRecord(downloadRecord);
            }
        }
        public void OnBeforeDownload(IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
        {
            var handler = OnBeforeDownloadFired;

            if (handler != null)
            {
                handler(this, downloadItem);
            }

            if (!callback.IsDisposed)
            {
                using (callback)
                {
                    Uri originalUri = new Uri(downloadItem.OriginalUrl);

                    // Parse the query string variables into a NameValueCollection.
                    NameValueCollection qscoll = HttpUtility.ParseQueryString(originalUri.Query);
                    var dr = new DownloadRecord()
                    {
                        FileName = downloadItem.SuggestedFileName,

                        Url         = downloadItem.Url,
                        IsCancelled = false
                    };

                    var fDr = Global.DownloadRepository.InitDownload(dr);
                    Global.DownloadRepository.UpdateDownload(downloadItem.Url, downloadItem);
                    callback.Continue(fDr.FullPath, showDialog: false);
                }
            }
        }
Exemple #3
0
    /// <summary>
    /// 更新下载进度
    /// </summary>
    /// <param name="record"></param>
    public void UpdateDownloadSizeAndTime(DownloadRecord record)
    {
        string sql = "update download_record SET downloadSize='{0}',Time='{1}' where id={2} ";

        sql = String.Format(sql, record.DownloadSize, record.Time, record.Id);
        Db.Update(sql);
    }
Exemple #4
0
    public void UpdateFileName(DownloadRecord record)
    {
        string sql = "update download_record SET FileName='{0}' where id={2} ";

        sql = String.Format(sql, record.FileName, record.Id);
        Db.Update(sql);
    }
Exemple #5
0
    public static DownloadResult DownloadObject(DownloadRecord record, String targetFolder, long start = 0, long end = 199)
    {
        GetObjectRequest getObjectRequest = new GetObjectRequest()
        {
            BucketName = BosConfig.BucketName, Key = record.CloudFile.Key
        };

        // 获取 范围内的数据
        getObjectRequest.SetRange(start, end);

        // 获取Object,返回结果为BosObject对象
        try {
            BosObject bosObject = GetBosClient().GetObject(getObjectRequest);

            Stream stream = bosObject.ObjectContent;

            return(FileUtil.saveFileContent(stream, record.FileName, targetFolder));
        } catch (BceServiceException BceServiceException) {
            if (BceServiceException.Message.IndexOf("The requested range cannot be satisfied") != -1)
            {
                DownloadResult result2 = new DownloadResult();
                result2.state = 1;
                return(result2);
            }
            Console.WriteLine("exception:" + BceServiceException);
        }
        DownloadResult result = new DownloadResult();

        result.state = 2;
        return(result);
    }
Exemple #6
0
        public async Task TestGetFiles_Success()
        {
            var downloader = JustDownloadFactory.GetDownloader();

            var records = new DownloadRecord[]
            {
                new DownloadRecord()
                {
                    Name     = "Test",
                    Filename = "TestGetFiles_Success result1.pdf",
                    Source   = new Uri("http://viewnet.com.my/downloads/viewnet_diy_pricelist.pdf")
                },
                new DownloadRecord()
                {
                    Name     = "Test 2",
                    Filename = "TestGetFiles_Success result2.pdf",
                    Source   = new Uri("http://viewnet.com.my/downloads/viewnet_diy_pricelist.pdf")
                },
                new DownloadRecord()
                {
                    Name     = "Test 3",
                    Filename = "TestGetFiles_Success result3.pdf",
                    Source   = new Uri("http://viewnet.com.my/downloads/viewnet_diy_pricelist.pdf")
                },
            };

            await downloader.GetFiles(records);

            foreach (var record in records)
            {
                Assert.IsTrue(File.Exists(record.Filename));
            }
        }
Exemple #7
0
        private void openFolder(DownloadRecord recorde)
        {
            Process p = new Process();

            p.StartInfo.FileName  = "explorer.exe";
            p.StartInfo.Arguments = @" /select, " + recorde.TargetFolder + @"\" + @recorde.FileName;
            p.Start();
        }
Exemple #8
0
        public void Remove(byte[] ciid, byte[] cRefID)
        {
            DownloadRecord dr = Find(ciid, cRefID);

            if (dr != null)
            {
                store.Remove(dr);
            }
        }
Exemple #9
0
    /// <summary>
    /// 下载完成
    /// </summary>
    /// <param name="key"></param>
    public void FinishDownload(string key)
    {
        DownloadRecord record = (DownloadRecord)DownloadRecordMap[key];

        record.DownloadState = 2;
        DownloadRecordService.UpdateDownloadDone(record.Id);

        DownloadStates.Remove(key);
        DownloadRecordMap.Remove(key);
    }
Exemple #10
0
        public bool IsComplete(byte[] ciid, byte[] cRefID)
        {
            DownloadRecord dr = Find(ciid, cRefID);

            if (dr != null)
            {
                return(dr.IsComplete);
            }

            return(false);
        }
    public void Breakpointdownload()
    {
        string         key          = Thread.CurrentThread.Name;
        DownloadRecord downloadInfo = (DownloadRecord)DownloadRecordMap[key];



        double excuteTime = 0;

        while (CheckState(key))
        {
            DateTime startDateTime = DateTime.Now;
            long     start         = downloadInfo.DownloadSize;
            long     end           = start + DownloadSize;
            if (start != 0)
            {
                start += 1;
            }

            DownloadResult result = BaiduBOSAPI.DownloadObject(downloadInfo, downloadInfo.TargetFolder, start, end);

            TimeSpan ts = DateTime.Now - startDateTime;

            excuteTime = Convert.ToDouble(ts.TotalMilliseconds.ToString()) / 1000;
            if (excuteTime == 0)
            {
                excuteTime = 0.01;
            }

            downloadInfo.DownloadSize = end;
            downloadInfo.Time         = downloadInfo.Time + excuteTime;
            DownloadRecordService.UpdateDownloadSizeAndTime(downloadInfo);


            Constant.Win.ExecuteJavascript("changeDownloadPercent('" + JsonConvert.SerializeObject(downloadInfo) + "')");


            if (result.isDone())
            {
                FinishDownload(key);
                //调用js通知下载完成
                Constant.Win.ExecuteJavascript("downloadDone('" + JsonConvert.SerializeObject(downloadInfo) + "')");

                break;
            }
            else if (result.isCloudMiss())
            {
                Constant.Win.ExecuteJavascript("downloadMiss('" + JsonConvert.SerializeObject(downloadInfo) + "')");
                DownloadRecordService.UpdateDowloadState(downloadInfo.Id, 3);
                break;
            }
        }
    }
        public void CreateDownloadTask(string DownloadName, DownloadConfig Dc, bool AdvancedConfig, bool IsRestore)
        {
            DownloadProgressBar Dpb = new DownloadProgressBar();

            Dc.OnReportProgressEvent   += Dpb.OnDownloadProgress;
            Dc.OnDownloadFinishedEvent += Dpb.OnDownloadFinished;
            Dc.OnStateChangedEvent     += Dpb.OnStateChanged;
            var TargetDownloader = new ContentDownloader();

            Program.DownloaderInstances.Add(TargetDownloader);
            Dpb.RestartDownload          += TargetDownloader.RestartDownload;
            Dpb.StopDownload             += TargetDownloader.StopDownload;
            Dpb.CancelDownload           += this.CancelDownload;
            Dpb.OnDownloadFinishedReport += this.OnDownloadFinished;
            Dpb.InitDownloading(DownloadName, Dc.AppID, Dc.DepotID, Dc.Branch);
            this.panelDownloading.Controls.Add(Dpb);
            RegroupDownloadProgressControl();
            if (!IsRestore)
            {
                DownloadRecord Dr = new DownloadRecord();
                Dr.AppID          = Dc.AppID;
                Dr.DepotID        = Dc.DepotID;
                Dr.BranchName     = Dc.Branch;
                Dr.FileToDownload = AllowFileList;
                Dr.InstallDir     = InstallDir;
                Dr.NoForceDepot   = !Dc.ForceDepot;
                Dr.DownloadName   = DownloadName;
                Dr.MaxDownload    = Dc.MaxDownloads;
                Dr.MaxServer      = Dc.MaxServers;
                Dr.AllPlatforms   = Dc.DownloadAllPlatforms;
                Dr.AdvancedConfig = AdvancedConfig;
                Dr.ManifestID     = Dc.ManifestId;
                if (Dc.FilesToDownloadRegex != null)
                {
                    Dr.FileRegex = new List <string>();
                    foreach (System.Text.RegularExpressions.Regex Fileregex in Dc.FilesToDownloadRegex)
                    {
                        Dr.FileRegex.Add(Fileregex.ToString());
                    }
                }
                ConfigStore.TheConfig.DownloadRecord.Add(Dr);
                ConfigStore.Save();
            }
            TargetDownloader.Config = Dc;
            if (!IsRestore)
            {
                TargetDownloader.RestartDownload();
            }
            else
            {
                Dpb.Downloading = false;
            }
        }
Exemple #13
0
        /// <summary>
        /// 分段下载
        /// </summary>
        /// <param name="key"></param>
        /// <param name="targetFolder"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public static DownloadResult DownloadObject(DownloadRecord record, string targetFolder, long start, long end)
        {
            DownloadResult downloadResult = new DownloadResult();
            Random         reum           = new Random();
            int            randomdata     = reum.Next(100000);
            string         tempFileName   = DateUtil.currentTimeMillis(new DateTime()) + randomdata + ".temp";

            try
            {
                GetObjectRequest request = new GetObjectRequest(BosConfig.BucketName, record.CloudFile.Key, targetFolder, tempFileName);
                request.SetRange(start, end);
                //设置签名有效时长
                request.SetSign(TimeUtils.GetCurrentTime(TimeUnit.SECONDS), 600);
                //执行请求
                GetObjectResult result = getCosXmlServer().GetObject(request);
                Console.WriteLine("msg" + result.GetResultInfo());

                if (String.Equals("OK", result.httpMessage))
                {
                }
                else if (String.Equals("Requested Range Not Satisfiable", result.httpMessage))
                {
                    downloadResult.state = 1;
                    File.Delete(targetFolder + @"\" + tempFileName);
                    return(downloadResult);
                }
                else if (String.Equals("Not Found", result.httpMessage))
                {
                    downloadResult.state = 2;
                    File.Delete(targetFolder + @"\" + tempFileName);
                    return(downloadResult);
                }
                Stream stream = new FileStream(targetFolder + @"\" + tempFileName, FileMode.Open);


                downloadResult = FileUtil.saveFileContent(stream, record.FileName, targetFolder);

                File.Delete(targetFolder + @"\" + tempFileName);
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                Console.WriteLine("CosClientException: " + clientEx.Message);
                downloadResult.state = 2;
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                Console.WriteLine("CosServerException: " + serverEx.GetInfo());
                downloadResult.state = 2;
            }
            return(downloadResult);
        }
Exemple #14
0
 /// <summary>
 /// 根据id获取下载记录
 /// </summary>
 /// <param name="id"></param>
 /// <returns></returns>
 public DownloadRecord selectById(int id)
 {
     using (IDbConnection connection = Db.getDbConnection())
     {
         var            query          = connection.Query <DownloadRecord>("select * from download_record where id='" + id + "'");
         DownloadRecord downloadRecord = query.FirstOrDefault();
         if (downloadRecord != null)
         {
             downloadRecord.CloudFile = new CommonCloudFileService().selectById(downloadRecord.CloudFileId);
         }
         return(downloadRecord);
     }
 }
Exemple #15
0
        public DownloadRecord Retrieve(byte[] ciid, byte[] cRefID)
        {
            DownloadRecord dr = Find(ciid, cRefID);

            if (dr != null)
            {
                store.Remove(dr);

                return(dr);
            }

            return(null);
        }
Exemple #16
0
        public void AddDownloadRecord(ref DownloadRecord record)
        {
            var sql = $"INSERT INTO Downloads(DateCreated, DateUpdated, DownloadId, Download) VALUES ('{DateTime.Now}', '{DateTime.Now}', '{record.Download.Id}', '{record.DownloadString}')";
            var id  = TransactNonQuery(sql, (command) =>
            {
                command.ExecuteNonQuery();

                return(command.Connection.LastInsertRowId);
            });

            record.ID = id;
            GetDownloads();
        }
Exemple #17
0
        private DownloadRecord Find(byte[] ciid, byte[] cRefID)
        {
            if ((ciid == null) && (cRefID == null))
            {
                return(null);
            }

            if (store.Count == 0)
            {
                return(null);
            }

            if (store.Count == 1)
            {
                DownloadRecord rec = store[0];

                if (rec != null)
                {
                    if ((ciid != null) && ByteArrayHelper.IsEqual(ciid, rec.CacheItemID))
                    {
                        return(rec);
                    }

                    if ((cRefID != null) && ByteArrayHelper.IsEqual(cRefID, rec.ContentRefenceID))
                    {
                        return(rec);
                    }
                }
            }
            else
            {
                bool searchCiids = (ciid != null);
                bool searchCRefs = (cRefID != null);

                foreach (DownloadRecord rec in store)
                {
                    if (searchCiids && ByteArrayHelper.IsEqual(ciid, rec.CacheItemID))
                    {
                        return(rec);
                    }

                    if (searchCRefs && ByteArrayHelper.IsEqual(cRefID, rec.ContentRefenceID))
                    {
                        return(rec);
                    }
                }
            }

            return(null);
        }
Exemple #18
0
        public async Task TestGetFile_Success()
        {
            var downloader = JustDownloadFactory.GetDownloader();

            var record = new DownloadRecord()
            {
                Name     = "Test",
                Filename = "result.pdf",
                Source   = new Uri("http://viewnet.com.my/downloads/viewnet_diy_pricelist.pdf")
            };

            await downloader.GetFile(record);

            Assert.IsTrue(File.Exists(record.Filename));
        }
 public void UpdateBetaPasswordRecord(uint AppID, uint DepotID, string Branch, string BetaPassword)
 {
     for (int i = 0; i < ConfigStore.TheConfig.DownloadRecord.Count; i++)
     {
         if (ConfigStore.TheConfig.DownloadRecord[i].AppID == AppID &&
             ConfigStore.TheConfig.DownloadRecord[i].DepotID == DepotID &&
             ConfigStore.TheConfig.DownloadRecord[i].BranchName == Branch)
         {
             DownloadRecord Dr = ConfigStore.TheConfig.DownloadRecord[i];
             Dr.BetaPassword = BetaPassword;
             ConfigStore.TheConfig.DownloadRecord[i] = Dr;
             ConfigStore.Save();
             break;
         }
     }
 }
Exemple #20
0
    /// <summary>
    /// 开始下载
    /// </summary>
    /// <param name="key"></param>
    /// <param name="downloadInfo"></param>
    public void StartDownload(DownloadRecord downloadInfo)
    {
        if (DownloadStates[GetDownloadStateKey(downloadInfo)] == null)
        {
            DownloadStates.Add(GetDownloadStateKey(downloadInfo), true);
        }
        if (DownloadRecordMap[GetDownloadStateKey(downloadInfo)] == null)
        {
            DownloadRecordMap.Add(GetDownloadStateKey(downloadInfo), downloadInfo);
        }
        ThreadStart threadStart = new ThreadStart(Breakpointdownload);//通过ThreadStart委托告诉子线程执行什么方法  
        Thread      thread      = new Thread(threadStart);

        thread.Name = GetDownloadStateKey(downloadInfo);
        thread.Start();//启动新线程

        DownloadRecordService.UpdateDowloadState(downloadInfo.Id, 0);
    }
Exemple #21
0
    /// <summary>
    ///  插入一条下载记录
    /// </summary>
    /// <param name="record"></param>
    public void Insert(DownloadRecord record)
    {
        int isExist = isExistFileName(record.FileName);

        while (isExist != 0)
        {
            Random reum       = new Random();
            int    randomdata = reum.Next(100);

            record.FileName = "(" + randomdata + ")" + record.FileName;
            isExist         = isExistFileName(record.FileName);
        }
        string baseInsert = "INSERT INTO download_record (GmtDownload ,DownloadState ,DownloadSize ,Size,CloudFileId,TargetFolder,Time,IsDeleted,Type,FileName) values";
        string sqltpl     = "('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')";

        baseInsert += String.Format(sqltpl, DateTime.UtcNow, 0, record.DownloadSize, record.Size, record.CloudFileId, record.TargetFolder, 0, 0, record.Type, record.FileName);
        Db.Insert(baseInsert);
    }
Exemple #22
0
        public async Task TestGetFile_WeirdUrl()
        {
            var downloader = JustDownloadFactory.GetDownloader();

            var record = new DownloadRecord()
            {
                Name     = "Nope",
                Filename = "TestGetFile_WeirdUrl.pdf",
                Source   = new Uri("http://lalalalala.xz")
            };

            var exception = await Assert.ThrowsExceptionAsync <Exception>(async() =>
            {
                await downloader.GetFile(record);
            });

            Assert.IsNotNull(exception);
            Assert.IsFalse(File.Exists(record.Filename));
        }
Exemple #23
0
        public void Start(byte[] ciid, byte[] cRefID, byte[] buffer, int downloadSize, byte cacheHint = 0)
        {
            if (((ciid == null) && (cRefID == null)) || (buffer == null))
            {
                return;
            }

            if (Find(ciid, cRefID) == null)
            {
                DownloadRecord dr = new DownloadRecord();

                dr.ContentRefenceID = cRefID;
                dr.CacheItemID      = ciid;
                dr.Buffer           = buffer;
                dr.ExpectedSize     = downloadSize;
                dr.CacheHint        = cacheHint;

                store.Add(dr);
            }
        }
Exemple #24
0
        public void AddDownloadRecord(int userId, string modelId)
        {
            var record = db.DownloadRecord.Where(n => (n.UserID == userId) && (n.ModelID == modelId)).FirstOrDefault();

            if (record != null)
            {
                record.DownloadCounts++;
                db.Entry(record).State = EntityState.Modified;
                db.SaveChanges();
            }
            else
            {
                var newRecord = new DownloadRecord();
                newRecord.UserID         = userId;
                newRecord.ModelID        = modelId;
                newRecord.DownloadCounts = 1;
                newRecord.DownloadTime   = DateTime.Now;
                db.DownloadRecord.Add(newRecord);
                db.SaveChanges();
            }
        }
Exemple #25
0
        public void Add(byte[] ciid, byte[] cRefID, byte[] buffer)
        {
            if (buffer == null)
            {
                return;
            }

            DownloadRecord dr = Find(ciid, cRefID);

            if (dr != null)
            {
                if (dr.Buffer != null)
                {
                    dr.Buffer = ByteArrayHelper.Combine(dr.Buffer, buffer);
                }
                else
                {
                    dr.Buffer = buffer;
                }
            }
        }
 public void Process(DownloadRecord record)
 {
     records.Enqueue(record);
     resetEvent.Set();
 }
Exemple #27
0
 public LaunchResult PostLaunchExecutable([CommandParameter(FromBody = true)] DownloadRecord body)
 {
     return(DownloadRepository.LaunchExecutable(body.Url));
 }
Exemple #28
0
 public string GetDownloadStateKey(DownloadRecord downloadInfo)
 {
     return(downloadInfo.Id + "");
 }
        public async ValueTask <MuzlanResponse <DownloadRecord> > DownloadTrack(TrackRecord track, AuthRecord auth, CancellationToken cancellationToken = default)
        {
            var sourceUri = new Uri(track.DownloadUri, $"?key={auth.MediaToken}");

            var fileExtension = NormalizeFileExtension(Path.GetExtension(sourceUri.LocalPath));
            var fileName      = track.Name;

            try
            {
                using var response = await _client.GetAsync(sourceUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);

                response.EnsureSuccessStatusCode();

                var contentLength = response.Content.Headers.GetValues("Content-Length").First();

                var fileSize   = int.Parse(contentLength);
                var fileOffset = 0;
                var bytesRead  = 0;
                var fileData   = new byte[fileSize];

                await OnDownloadProgressChanged(fileOffset, fileSize).ConfigureAwait(false);

                using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);

                bool hasCompletedEvent = false;

                do
                {
                    if (fileOffset >= fileSize)
                    {
                        break;
                    }

                    bytesRead = await stream.ReadAsync(
                        ConvertToMemory(fileData, fileOffset, 8192),
                        cancellationToken).ConfigureAwait(false);

                    fileOffset += bytesRead;

                    if (fileOffset == fileSize)
                    {
                        hasCompletedEvent = true;
                    }

                    await OnDownloadProgressChanged(fileOffset, fileSize).ConfigureAwait(false);
                } while (bytesRead > 0);

                if (!hasCompletedEvent)
                {
                    await OnDownloadProgressChanged(fileSize, fileSize).ConfigureAwait(false);
                }

                var file = new DownloadRecord(fileName + fileExtension, fileData, sourceUri);

                return(MuzlanResponse <DownloadRecord> .FromResult(file, sourceUri));
            }
            catch (Exception ex)
            {
                return(MuzlanResponse <DownloadRecord> .FromException(ex, sourceUri));
            }
        }
 private void UpdateState(DownloadRecord record, ClientDownloadStatus status)
 {
     synchronizationContext.Post(state => record.Status = (ClientDownloadStatus)state, status);
 }