public HttpResponseMessage GetInfo(ClientBasicInfo clientBasicInfo)
        {
            var productName           = clientBasicInfo.ProductName;
            var revitVersion          = clientBasicInfo.RevitVersion;
            var currentProductVersion = clientBasicInfo.CurrentProductVersion;

            //ProductName_RevitVersion_OldProductVersion_NewProductVersion
            var latestFilePath = ServerFileUtils.GetLatestFilePath(productName, revitVersion, currentProductVersion);

            if (string.IsNullOrEmpty(latestFilePath) || !File.Exists(latestFilePath))
            {
                return(null);
            }

            var latestFile   = new FileInfo(latestFilePath);
            var downloadInfo = new DownloadFileInfo()
            {
                LatestProductVersion  = ServerFileUtils.GetLatestVersion(Path.GetFileNameWithoutExtension(latestFilePath)),
                DownloadFileMd5       = Md5Utils.GetFileMd5(latestFilePath),
                DownloadFileTotalSize = latestFile.Length
            };
            HttpResponseMessage response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(downloadInfo), Encoding.GetEncoding("UTF-8"), "application/json")
            };

            return(response);
        }
예제 #2
0
        //TestFile directory is used to Test socket
        //See Socket_APM-SAEA\TestFile
        static void Main(string[] args)
        {
            var mainFolder = AppDomain.CurrentDomain.BaseDirectory.Replace("bin", "TestFile");

            ClientBasicInfo basicInfo = new ClientBasicInfo()
            {
                ProductName           = "Airforce094",
                RevitVersion          = "Revit2016",
                CurrentProductVersion = "18.1.6"
            };

            var serverFilePath = Path.Combine(mainFolder, "Server\\Airforce094_Revit2016_18.1.6_18.1.7.zip");

            DownloadFileInfo dlInfo = new DownloadFileInfo()
            {
                LatestProductVersion  = "18.1.7",
                DownloadFileMd5       = Md5Utils.GetFileMd5(serverFilePath),
                DownloadFileTotalSize = new FileInfo(serverFilePath).Length
            };

            ClientLinkInfo clInfo = new ClientLinkInfo()
            {
                IpString = "127.0.0.1",
                Port     = 8885
            };

            var localSavePath = Path.Combine(mainFolder, "Local");
            var tempFilesDir  = Path.Combine(mainFolder, "TempFile");
            var cs            = new ClientSocket();
            var result        = cs.StartClient(basicInfo, dlInfo, clInfo, localSavePath, tempFilesDir);

            Console.WriteLine(result);
            Console.ReadKey();
        }
예제 #3
0
    private void DownFileAsync(DownloadFileInfo fileInfo)
    {
        //创建一个初始化请求对象
        HttpWebRequest request      = (HttpWebRequest)WebRequest.Create(fileInfo.DownURL + fileInfo.FileName);
        RequestState   requestState = new RequestState();

        //设置下载相关参数
        try
        {
            request.KeepAlive              = false;
            request.ProtocolVersion        = HttpVersion.Version11;
            requestState.BUFFER_SIZE       = 1024 * 64;
            requestState.BufferRead        = new byte[requestState.BUFFER_SIZE];
            requestState.Request           = request;
            requestState.SavePath          = fileInfo.SavePath;
            requestState.bFileRangeRequest = false;
            //requestState.FileStream = new FileStream(requestState.SavePath, FileMode.OpenOrCreate);
            requestState.outStream = File.Create(fileInfo.SavePath + fileInfo.FileName);

            //开始异步请求资源
            request.BeginGetResponse(new AsyncCallback(ResponseCallback), requestState);
        }
        catch (WebException)
        {
            requestState.Request.Abort();
            requestState.outStream.Close();
            DownloadError();
        }
    }
예제 #4
0
 private void updateDownloadTransferListView(DownloadFileInfo info, bool isDone)
 {
     if (!isDone)
     {
         TransferFile newFile = new TransferFile();
         newFile = TempChoosedFile;
         Dispatcher.BeginInvoke(new Action(delegate()
         {
             newFile.Status = info.Status;
             FileTransferListView.Items.Add(newFile);
             FileTransferListView.Items.Refresh();
         }));
     }
     else
     {
         Dispatcher.BeginInvoke(new Action(delegate()
         {
             foreach (TransferFile line in FileTransferListView.Items)
             {
                 if (line.FileName.Equals(info.FileName))
                 {
                     line.Status = info.Status;
                     line.Time   = info.Time;
                     line.Kbps   = info.Kbps;
                     _userLogic.UpdateUserTransferFilesLogic(line.FileName, MyUser.UserName);
                     _fileLogic.CopyFileByPaths(line.FileName, downloadPath, uploadPath);
                 }
             }
             FileTransferListView.Items.Refresh();
         }));
     }
     TempChoosedFile = null;
 }
예제 #5
0
        private List <DownloadFileInfo> procFile(FileInfo fileInfo, List <DownloadFileInfo> lFileInfo)
        {
            DownloadFileInfo dFileInfo = lFileInfo.Where(w => w.FileName == fileInfo.Name).FirstOrDefault();

            if (dFileInfo == null)
            {
                File.Delete(fileInfo.FullName);
            }
            else
            {
                FileStream fs      = fileInfo.OpenRead();
                string     destMd5 = DXInfo.Business.Helper.GetMd5Hash(fs);
                fs.Close();
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (0 == comparer.Compare(dFileInfo.Md5, destMd5))
                {
                    lFileInfo.Remove(dFileInfo);
                }
                else
                {
                    File.Delete(fileInfo.FullName);
                }
            }
            return(lFileInfo);
        }
예제 #6
0
        void CreateLicFile()
        {
            String tenantName       = "Celestial Being GN-00";
            String tenantIdentifier = String.Join(".", tenantName, GetComputerName());

            DownloadFileInfo rqsFileInfo = License.GetRequestTicket(tenantIdentifier);

            var licInfo = new LicenseInfo {
                RequestTicket = SecurityExt.EncodeBase64UrlFromBytes(rqsFileInfo.FileByteArray),
                ClientName    = tenantName,
                Type          = LicenseType.Trial,
                EffectiveDate = DateTime.Now.AddDays(-3),
                ExpiredDate   = DateTime.Now.AddDays(10),
                UsersCount    = 50,
                Buffer        = 10,
                Modules       = new List <String> {
                    "Report", "Analytics", "Contacts"
                }
            };

            DownloadFileInfo licFile = License.GetLicense(tenantName, licInfo);

            using (var writer = new BinaryWriter(File.Open(GetOutputPath(licFile.Filename), FileMode.Create)))
                foreach (Byte b in licFile.FileByteArray)
                {
                    writer.Write(b);
                }
        }
예제 #7
0
        public DownloadFileResult DownloadUpdateSystemFile(DownloadFileInfo downFileInfo)
        {
            UpdateConfig config = SerializeHelper.LoadXmlSerializeFile <UpdateConfig>(this.updateConfigPath);

            downFileInfo.PhysicalPath = Path.Combine(this.versionPath, config.ConfigInfo.CurrentVersion) + "\\" + downFileInfo.FileName;
            return(this.operateFile.DownloadFile(downFileInfo));
        }
        public HttpResponseMessage GetFileExport(GroupByEnum groupBy, string fileType)
        {
            if (string.IsNullOrEmpty(fileType))
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest)
                       {
                           Content = new StringContent($"Requisição inválida.")
                       }
            }
            ;

            byte[] ByteArray        = null;
            var    downloadFileType = new DownloadFileInfo(fileType);

            if (downloadFileType.FileType == DownloadFileTypesEnum.Xls)
            {
                ByteArray = _operationBusiness.ExportXls(_operationBusiness.GetByGroup(groupBy).ToList(), groupBy);
            }

            if (downloadFileType.FileType == DownloadFileTypesEnum.Csv)
            {
                ByteArray = _operationBusiness.ExportCSV(_operationBusiness.GetByGroup(groupBy).ToList(), groupBy);
            }

            return(ByteArray.ExcelResult("Operações", downloadFileType));
        }
    }
예제 #9
0
        public async void SaveFiasDeltaXmlToDirectoryTest()
        {
            DownloadFileInfo lastInfo = await GetDownloadFileInfo();

            string pathFiasCompleteDbfFile = Path.Combine(_workDirectory, "SaveFiasDeltaXmlToDirectoryTest.dbf");
            await lastInfo.SaveFiasDeltaXmlToDirectoryAsync(pathFiasCompleteDbfFile);
        }
예제 #10
0
        static async Task MainAsync(string[] args)
        {
            string           workDirectory = Path.Combine(Environment.CurrentDirectory, "TestData");
            IFIASLoader      loader        = new FIASLoader();
            DownloadFileInfo lastInfo      = await loader.GetLastDownloadFileInfo();

            await Task.WhenAll(
                lastInfo.SaveFiasDeltaDbToDirectoryAsync(workDirectory),
                lastInfo.SaveFiasDeltaXmlToDirectoryAsync(workDirectory),
                lastInfo.SaveFiasCompleteDbfToDirectoryAsync(workDirectory),
                lastInfo.SaveFiasCompleteXmlToDirectoryAsync(workDirectory),
                lastInfo.SaveKladr47ZToDirectoryAsync(workDirectory),
                lastInfo.SaveKladr4ArjToDirectoryAsync(workDirectory)
                );

            string      workDirectoryHistory             = Path.Combine(Environment.CurrentDirectory, "FiasHistoryData");
            IFIASLoader loaderistory                     = new FIASLoader();
            IReadOnlyList <DownloadFileInfo> historyInfo = await loaderistory.GetAllDownloadFileInfo();

            foreach (var fileInfo in historyInfo)
            {
                string currentVersionPath = Path.Combine(workDirectoryHistory, fileInfo.VersionId.ToString());

                await Task.WhenAll(
                    fileInfo.SaveFiasDeltaDbToDirectoryAsync(currentVersionPath),
                    fileInfo.SaveFiasDeltaXmlToDirectoryAsync(currentVersionPath),
                    fileInfo.SaveFiasCompleteDbfToDirectoryAsync(currentVersionPath),
                    fileInfo.SaveFiasCompleteXmlToDirectoryAsync(currentVersionPath),
                    fileInfo.SaveKladr47ZToDirectoryAsync(currentVersionPath),
                    fileInfo.SaveKladr4ArjToDirectoryAsync(currentVersionPath)
                    );
            }
        }
예제 #11
0
        public int GetDownloadCount()
        {
            int count = 0;

            foreach (DownloadFileInfo serverInfo in _ServerVersions)
            {
                DownloadFileInfo foundInfo = null;

                foreach (DownloadFileInfo localInfo in _LocalVersions)
                {
                    if (localInfo.FilePath == serverInfo.FilePath)
                    {
                        foundInfo = localInfo;
                        break;
                    }
                }

                if (foundInfo == null)
                {
                    count++;
                }
                else if (foundInfo.FileVersion < serverInfo.FileVersion)
                {
                    count++;
                }
            }

            return(count);
        }
예제 #12
0
        public void DownloadFileCompleted(string filePath)
        {
            DownloadFileInfo foundInfo = null;

            foreach (DownloadFileInfo localInfo in _LocalVersions)
            {
                if (localInfo.FilePath == _ServerVersions[0].FilePath)
                {
                    foundInfo = localInfo;
                    break;
                }
            }

            if (foundInfo == null)
            {
                foundInfo          = new DownloadFileInfo();
                foundInfo.FilePath = _ServerVersions[0].FilePath;

                _LocalVersions.Add(foundInfo);
            }

            foundInfo.FileVersion = _ServerVersions[0].FileVersion;

            _ServerVersions.RemoveAt(0);
            gameDownloadWnd.progressUpdate.Value++;

            if (NeedDownload())
            {
                GameWebDownloader.GetInstance().DownloadFile(_ServerVersions[0].FilePath, DownloadFileCompleted, this);
            }
        }
예제 #13
0
        public RemoteFileInfo GetRemoteFileInfo(DownloadFileInfo file)
        {
            RemoteFileInfo remoteFileInfo = new RemoteFileInfo();

            remoteFileInfo.AcceptRanges = true;

            FtpWebRequest request = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);

            request.Method = WebRequestMethods.Ftp.GetFileSize;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                remoteFileInfo.FileSize = response.ContentLength;
            }

            request        = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                remoteFileInfo.LastModified = response.LastModified;
            }

            return(remoteFileInfo);
        }
예제 #14
0
    /// <summary>
    /// 文件下载完了
    /// </summary>
    private void DownloadEnd(bool bError = false)
    {
        DownloadFileInfo loadfile = DownloadFileList[0];

        if (bError)
        {
            Debug.LogWarning("下载文件出错 filename:" + loadfile.FileName + " 版本:" + loadfile.FileVer + " Url:" + loadfile.DownURL);
            return;
        }

        CCsvDataManager.Instance.LocalABVerDataMgr.SetLocalABVersion(loadfile.FileName, loadfile.FileVer);
        DownloadFileList.RemoveAt(0);
        int remainCount = DownloadFileList.Count;

        if (loadfile.BelongGameId != 255)
        {
            CGameResDownloadMgr.Instance.DownloadOverGameResCallBack(loadfile.BelongGameId, loadfile.FileName);
        }
        DownLoadProcessMgr.Instance.AddDownloadOverFileName(loadfile.FileName);
        //DownLoadProcessMgr.Instance.ReduceDownFileCount(1);
        if (remainCount == 0)
        {
            isDownloading = false;
        }
        else
        {
            DownFileAsync(DownloadFileList[0]);
            DownLoadProcessMgr.Instance.InitDownloadFileLength(DownloadFileList[0].BelongGameId);
        }
    }
예제 #15
0
    public void addDownload(string fileURL, string savePath, DownloadCallback succeedCallback, DownloadCallback failedCallback, LuaFunction progressCallback)
    {
        lock (syncLock) {
            DownloadFileInfo info = new DownloadFileInfo();
            info.fileURL      = fileURL;
            info.realFilePath = savePath;

            // 先下载到一个临时文件,然后再复制到正确路径
            info.tmpFilePath = savePath + GameController.getInstance().getMilliseconds();

            info.succeedCallback = () => {
                succeedCallback();

                onDownloadOver();
            };
            info.failedCallback = () => {
                failedCallback();

                onDownloadOver();
            };
            info.progressCallback = progressCallback;

            list.Add(info);
        }
    }
 private static void SetCredentials(DownloadFileInfo file, WebRequest webRequest)
 {
     if (file.Authenticate)
     {
         NetworkCredentialUserName networkCredentialUserName = new NetworkCredentialUserName(file.UserName);
         webRequest.Credentials = new NetworkCredential(networkCredentialUserName.UserName, file.Password, networkCredentialUserName.Domain);
     }
 }
 private static void SetCredentials(DownloadFileInfo file, WebRequest webRequest)
 {
     if (file.Authenticate)
     {
         NetworkCredentialUserName networkCredentialUserName = new NetworkCredentialUserName(file.UserName);
         webRequest.Credentials = new NetworkCredential(networkCredentialUserName.UserName, file.Password, networkCredentialUserName.Domain);
     }
 }
예제 #18
0
 /// <summary>
 /// 添加新下载项
 /// </summary>
 /// <param name="url">rul路径</param>
 /// <param name="path">存放路径</param>
 public void AddDownLoadFile(string url, string path)
 {
     lock (m_LockObj)
     {
         m_ListDownFiles.Add(url);
         DownloadFileInfo data = new DownloadFileInfo(url, path);
         m_LoadQueue.Enqueue(data);
     }
 }
예제 #19
0
        public async void GetLastDownloadFileInfoTest()
        {
            IFIASLoader      loader   = new FIASLoader();
            DownloadFileInfo lastInfo = await loader.GetLastDownloadFileInfo();

            Assert.NotNull(lastInfo);
            Assert.True(lastInfo.VersionId > 0);
            Assert.True(lastInfo.VersionDate > DateTime.MinValue);
        }
예제 #20
0
        /// <summary>
        /// Get Download File Info
        /// </summary>
        /// <param name="basicInfo"></param>
        /// <param name="serverAddress"></param>
        /// <param name="controllerName"></param>
        /// <param name="actionName"></param>
        /// <param name="serverResult"></param>
        /// <returns></returns>
        public static bool RequestDownloadFileInfo(ClientBasicInfo basicInfo,
                                                   string serverAddress,
                                                   string controllerName,
                                                   string actionName,
                                                   ref DownloadFileInfo serverResult)
        {
            var packageInfo = JsonConvert.SerializeObject(basicInfo);

            try
            {
                HttpClient httpClient = new HttpClient
                {
                    BaseAddress = new Uri(serverAddress),
                    Timeout     = TimeSpan.FromMinutes(20)
                };

                if (ConnectionTest(serverAddress))
                {
                    StringContent strData           = new StringContent(packageInfo, Encoding.UTF8, "application/json");
                    string        postUrl           = httpClient.BaseAddress + $"api/{controllerName}/{actionName}";
                    Uri           address           = new Uri(postUrl);
                    Task <HttpResponseMessage> task = httpClient.PostAsync(address, strData);
                    try
                    {
                        task.Wait();
                    }
                    catch
                    {
                        return(false);
                    }
                    HttpResponseMessage response = task.Result;
                    if (!response.IsSuccessStatusCode)
                    {
                        return(false);
                    }

                    try
                    {
                        string jsonResult = response.Content.ReadAsStringAsync().Result;
                        serverResult = JsonConvert.DeserializeObject <DownloadFileInfo>(jsonResult);
                        if (serverResult != null)
                        {
                            return(true);
                        }
                    }
                    catch (Exception ex)
                    {
                        return(false);
                    }
                }
            }
            catch
            {
                return(false);
            }
            return(false);
        }
예제 #21
0
    private void doDownload(DownloadFileInfo data)
    {
        while (_workingCount >= _MaxCount)
        {
            waitHandle.WaitOne();
        }
        _workingCount++;

        OtkClient.DownloadFile(data);
    }
예제 #22
0
 public void AsyncDownload(string fileName, string destination)
 {
     if (fileName == null || destination == null)
         return;
     _isDownloading = true;
     var downloadFileInfo = new DownloadFileInfo {Filename = fileName, Destination = destination};
     _workerDownload.CancelAsync();
     _workerDownload.DoWork += AsyncDownloadWorker;
     _workerDownload.RunWorkerAsync(downloadFileInfo);
 }
예제 #23
0
            public static void SaveLicenseFile(String outputDir, String identifier, LicenseInfo license)
            {
                DownloadFileInfo lic = GetLicense(identifier, license);

                using (var writer = new BinaryWriter(File.Open(Path.Combine(outputDir, lic.Filename), FileMode.Create)))
                    foreach (Byte b in lic.FileByteArray)
                    {
                        writer.Write(b);
                    }
            }
예제 #24
0
        public ClientDownLoadViewModel(ClientBasicInfo cb, DownloadFileInfo dl)
        {
            ClientInfo   = cb;
            DownloadInfo = dl;

            LinkInfos = new ObservableCollection <LinkInfo>();
            InitData();

            DownloadCmd = new DelegateCommand(StartDownload);
        }
예제 #25
0
            public static void SaveRequestTicket(String outputDir, String identifier)
            {
                DownloadFileInfo requestTicket = GetRequestTicket(identifier);

                using (var writer = new BinaryWriter(File.Open(Path.Combine(outputDir, requestTicket.Filename), FileMode.Create)))
                    foreach (Byte b in requestTicket.FileByteArray)
                    {
                        writer.Write(b);
                    }
            }
예제 #26
0
 public ActionResult Edit([Bind(Include = "FileID, descricao")] DownloadFileInfo info)
 {
     if (ModelState.IsValid)
     {
         downRepos.Atualizar(info);
         downRepos.SalvarTodos();
         return(RedirectToAction("Projetos"));
     }
     return(View(info));
 }
예제 #27
0
        public bool NeedDownload()
        {
            while (_ServerVersions.Count > 0)
            {
                DownloadFileInfo foundInfo = null;

                foreach (DownloadFileInfo localInfo in _LocalVersions)
                {
                    if (localInfo.FilePath == _ServerVersions[0].FilePath)
                    {
                        foundInfo = localInfo;
                        break;
                    }
                }

                if (foundInfo == null)
                {
                    return(true);
                }

                if (foundInfo.FileVersion < _ServerVersions[0].FileVersion)
                {
                    return(true);
                }

                _ServerVersions.RemoveAt(0);
            }

            string localRoot = AppDomain.CurrentDomain.BaseDirectory + "Games\\" + _gameInfo.Downloadfolder;

            VersionInfo.WriteInfoFile(localRoot, _LocalVersions, true);

            string engineName = AppDomain.CurrentDomain.BaseDirectory + "ChatEngine.dll";

            System.IO.File.Copy(engineName, localRoot + "\\ChatEngine.dll", true);

            string controlName = AppDomain.CurrentDomain.BaseDirectory + "GameControls.dll";

            System.IO.File.Copy(controlName, localRoot + "\\GameControls.dll", true);

            if (gameDownloadWnd != null)
            {
                gameDownloadWnd.Close();
            }
            SetDownloadState(_gameInfo);

            img_GameIcon.Opacity         = 0.8;
            img_GameCashIcon.Source      = new BitmapImage(new Uri("pack://application:,,,/Resources;component/image/GoldCoin.jpg", UriKind.RelativeOrAbsolute));
            img_GamePointIcon.Visibility = Visibility.Visible;

            _bDownloading = false;

            EnterGame(_gameInfo.nCashOrPointGame);
            return(false);
        }
예제 #28
0
        public Stream CreateStream(DownloadFileInfo file, long startPosition, long endPosition)
        {
            FtpWebRequest request = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);

            request.Method        = WebRequestMethods.Ftp.DownloadFile;
            request.ContentOffset = startPosition;

            WebResponse response = request.GetResponse();

            return(response.GetResponseStream());
        }
        public Stream CreateStream(DownloadFileInfo file, long startPosition, long endPosition)
        {
            FtpWebRequest request = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);

            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.ContentOffset = startPosition;

            WebResponse response = request.GetResponse();

            return response.GetResponseStream();
        }
        public Stream CreateStream(DownloadFileInfo file, long startPosition, long endPosition)
        {
            lock (typeof(HttpWebRequest))
            {
                HttpWebRequest request = (HttpWebRequest)m_WebRequestManager.GetWebRequest(file);
                request.AddRange(startPosition, endPosition);

                WebResponse response = request.GetResponse();

                return response.GetResponseStream();
            }
        }
        public Stream CreateStream(DownloadFileInfo file, long startPosition, long endPosition)
        {
            lock (typeof(HttpWebRequest))
            {
                HttpWebRequest request = (HttpWebRequest)m_WebRequestManager.GetWebRequest(file);
                request.AddRange(startPosition, endPosition);

                WebResponse response = request.GetResponse();

                return(response.GetResponseStream());
            }
        }
예제 #32
0
        void CreateRequestTicket()
        {
            String tenantName       = "Celestial Being GN-00";
            String tenantIdentifier = String.Join(".", tenantName, GetComputerName());

            // Example 1
            DownloadFileInfo requestTicket = License.GetRequestTicket(tenantIdentifier);

            File.WriteAllText(GetOutputPath(requestTicket.Filename), SecurityExt.EncodeBase64UrlFromBytes(requestTicket.FileByteArray));

            // Example 2
            License.SaveRequestTicket(OutputDirPath, tenantIdentifier);
        }
예제 #33
0
    /// <summary>
    /// 请求下载文件
    /// </summary>
    /// <param name="downUrl"></param>
    /// <param name="savePath"></param>
    /// <param name="fileName"></param>
    public void RequestDownload(string downUrl, string savePath, string fileName, uint ver, byte resbelonggameid)
    {
        DownloadFileInfo downfile = new DownloadFileInfo(downUrl, savePath, fileName, ver, resbelonggameid);

        DownloadFileList.Add(downfile);
        DownLoadProcessMgr.Instance.AddDownFileCount(1);
        if (!isDownloading)
        {
            DownLoadProcessMgr.Instance.InitDownloadFileLength(downfile.BelongGameId);
            DownFileAsync(downfile);
            isDownloading = true;
        }
    }
예제 #34
0
        /// <summary>
        /// Download file from server
        /// </summary>
        /// <param name="apiSession">api session</param>
        /// <param name="remoteFilePath">Path to the remote file. Like /some/folder/file.txt </param>
        /// <param name="streamToWriteTo">stream for writing. You should dispose the stream by yourself</param>
        /// <param name="cancellationToken">cancellation token</param>
        /// <returns>returns file info</returns>
        public async Task <DownloadFileInfo> DownloadFileAsync(ApiSession apiSession, string remoteFilePath, Stream streamToWriteTo, CancellationToken cancellationToken)
        {
            if (apiSession == null)
            {
                throw new ArgumentNullException(nameof(apiSession));
            }

            DownloadFileInfo fileInfo = null;

            await DownloadFileAsync(apiSession, remoteFilePath, (fi) => { fileInfo = fi; return(true); }, streamToWriteTo, cancellationToken);

            return(fileInfo);
        }
        public WebRequest GetWebRequest(DownloadFileInfo file)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }

            WebRequest webRequest = m_WebRequestFactory.CreateRequest(file.Uri);
            webRequest.Timeout = 30000;

            SetCredentials(file, webRequest);

            return webRequest;
        }
        public RemoteFileInfo GetRemoteFileInfo(DownloadFileInfo file)
        {
            RemoteFileInfo remoteFileInfo = new RemoteFileInfo();
            WebRequest webRequest = m_WebRequestManager.GetWebRequest(file);
            webRequest.Method = "HEAD";

            HttpWebResponse httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
            remoteFileInfo.LastModified = httpWebResponse.LastModified;
            remoteFileInfo.MimeType = httpWebResponse.ContentType;
            remoteFileInfo.FileSize = httpWebResponse.ContentLength;
            remoteFileInfo.AcceptRanges = string.Compare(httpWebResponse.Headers["Accept-Ranges"], "bytes", StringComparison.OrdinalIgnoreCase) == 0;

            return remoteFileInfo;
        }
        public RemoteFileInfo GetRemoteFileInfo(DownloadFileInfo file)
        {
            RemoteFileInfo remoteFileInfo = new RemoteFileInfo();
            remoteFileInfo.AcceptRanges = true;

            FtpWebRequest request = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);
            request.Method = WebRequestMethods.Ftp.GetFileSize;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                remoteFileInfo.FileSize = response.ContentLength;
            }

            request = (FtpWebRequest)m_WebRequestManager.GetWebRequest(file);
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                remoteFileInfo.LastModified = response.LastModified;
            }

            return remoteFileInfo;
        }
예제 #38
0
        //Copys the files from the temp download location to the application directory.
        private void InstallDownloadedFiles(DownloadFileInfo[] allFiles, DownloadFileInfo[] downloadFiles)
        {
            RenameOldFiles(downloadFiles);

            for (Int32 i = 0; i <= downloadFiles.GetUpperBound(0); i++)
            {
                String newFilepath = appDirectory + downloadFiles[i].Path + downloadFiles[i].Name;
                String oldFilepath = downloadDirectory + downloadFiles[i].Path + downloadFiles[i].Name;

                if (File.Exists(oldFilepath))
                {
                    if (!Directory.Exists(appDirectory + downloadFiles[i].Path))
                    { Directory.CreateDirectory(appDirectory + downloadFiles[i].Path); }

                    File.Move(oldFilepath, newFilepath);
                }
            }
        }
예제 #39
0
 //Checks to make sure the downloaded files are ok.
 private Boolean HashCheckDownloadFiles(DownloadFileInfo[] files)
 {
     for (Int32 i = 0; i <= files.GetUpperBound(0); i++)
     {
         if (File.Exists(downloadDirectory + files[i].Path + files[i].Name))
         {
             if (MD5CalcFile(downloadDirectory + files[i].Path + files[i].Name) != files[i].Hash)
             { return false; }
         }
     }
     return true;
 }
예제 #40
0
        //Downloads an array of files
        private void DownloadFiles(DownloadFileInfo[] files)
        {
            WebClient wc = new WebClient();
            if (!Directory.Exists(downloadDirectory))
            { Directory.CreateDirectory(downloadDirectory); }

            for (Int32 i = 0; i <= files.GetUpperBound(0); i++)
            {
                if (File.Exists(downloadDirectory + files[i].Path + files[i].Name))
                { File.Delete(downloadDirectory + files[i].Path + files[i].Name); }

                if (!Directory.Exists(downloadDirectory + files[i].Path))
                { Directory.CreateDirectory(downloadDirectory + files[i].Path); }

                wc.DownloadFile(files[i].Url, downloadDirectory + files[i].Path + files[i].Name);
            }
            wc.Dispose();
        }
예제 #41
0
        //Checks what files we already have. Returns files that need to be downloaded.
        private DownloadFileInfo[] CheckFilesToDownload(DownloadFileInfo[] files)
        {
            DownloadFileInfo[] returnFiles = null;

            for (Int32 i = 0; i <= files.GetUpperBound(0); i++)
            {
                String hashPath = appDirectory + @"\" + files[i].Path + files[i].Name;

                if (FileNeedsDownloaded(files[i].Hash, hashPath))
                {
                    if (returnFiles == null) { returnFiles = new DownloadFileInfo[1]; }
                    else { Array.Resize(ref returnFiles, returnFiles.GetUpperBound(0) + 2); }
                    returnFiles[returnFiles.GetUpperBound(0)] = files[i];
                }

            }

            return returnFiles;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="SegmentDownloader"/> class.
 /// </summary>
 /// <param name="file">The file.</param>
 /// <param name="networkProtocolProvider">The network protocol provider.</param>
 /// <param name="downloadSegmentInfo">The download segment information.</param>
 /// <param name="segmentDownloadRateCalculator">The segment download rate calculator.</param>
 public SegmentDownloader(DownloadFileInfo file, INetworkProtocolProvider networkProtocolProvider, DownloadSegmentPositions downloadSegmentInfo, ISegmentDownloadRateCalculator segmentDownloadRateCalculator)
     : this(null, downloadSegmentInfo, segmentDownloadRateCalculator)
 {
     m_File = file;
     m_NetworkProtocolProvider = networkProtocolProvider;
 }
 public DownloadTaskInfo(DownloadFileInfo downloadFileInfo, bool startImmediately)
 {
     StartImmediately = startImmediately;
     DownloadFileInfo = downloadFileInfo;
 }
예제 #44
0
 //Renames the old files
 private void RenameOldFiles(DownloadFileInfo[] files)
 {
     for (Int32 i = 0; i <= files.GetUpperBound(0); i++)
     {
         String filename = appDirectory + files[i].Path + files[i].Name;
         if (File.Exists(filename))
         {
             if (File.Exists(filename + ".old")) { File.Delete(filename + ".old"); }
             File.Move(filename, filename + ".old");
         }
     }
 }
예제 #45
0
        public bool Update(string directory, VersionInfo build)
        {
            if (!File.Exists(directory + @"\Yatse2.exe"))
                return false;

            Tools.FindAndKillProcess("Yatse2");

            var version = Tools.GetFileRevision(directory + @"\Yatse2.exe");
            if (version == build.Build)
            {
                return false;
            }

            var filesinfo = GetVersionInfo(new VersionInfo { Beta = true, Build = version });
            if (filesinfo != null)
            {
                Log("Update : Checking current install against web build : " + version);
                foreach (var files in filesinfo.FileInfos)
                {
                    if (!File.Exists(directory + files.FilePath))
                        continue;
                    if (FileHash.CheckFileHashString(directory + files.FilePath, files.FileHash)) continue;
                    if (File.Exists(directory + files.FilePath + ".bck"))
                        File.Delete(directory + files.FilePath + ".bck");
                    File.Move(directory + files.FilePath, directory + files.FilePath + ".bck");
                    Log("Update : Backup modified file : " + files.FilePath,true);
                }
            }
            else
            {
                Log("Update : Current build no more on server : " + version,true);
            }

            DownloadFile(_repository + "/Download/" + _platform + "/" + build.Build + "/Update", "Update");
            Log("Update : Updating to build : " + build.Build, true);
            filesinfo = GetVersionInfo(build);
            if (filesinfo != null)
            {
                bool res;
                using (var q = new ThreadedDownlads(Threads, _tempDirectory, false))
                {
                    foreach (var files in filesinfo.FileInfos)
                    {
                        var info = new DownloadFileInfo
                                       {
                                           FileSource =
                                               _platformUrl + @"/" + build.Build + @"/Files/" + files.FileHash + ".dat",
                                           FileDestination = directory + files.FilePath,
                                           FileHash = files.FileHash
                                       };
                        q.EnqueueTask(info);
                    }
                    res = q.WaitEnd();
                }
                return res;
            }

            Log("Update : New build no more on server : " + build.Build,true);
            return false;
        }
        private void DownloadButtonOnTouchUpInside(object sender, EventArgs eventArgs)
        {
            var libFolder =
                        Path.Combine(
                            Environment.GetFolderPath(Environment.SpecialFolder.Personal),
                            "..",
                            "Library",
                            "MyApp",
                            "Images");

            var download1 = new DownloadFileInfo
            {
                Index = 0,
                //FileHttpUrl = "http://crockerj.com/photos/post23/fatcat10.jpg",
                FileHttpUrl = "http://drpinna.com/wp-content/uploads/2010/02/fat-cat1.jpg",
                DestinationDiskPath = Path.Combine(libFolder, "fatCat1.jpeg")
            };

            var download2 = new DownloadFileInfo
            {
                Index = 1,
                FileHttpUrl = "http://drpinna.com/wp-content/uploads/2010/02/fat-cat1.jpg",
                DestinationDiskPath = Path.Combine(libFolder, "fatCat2.jpeg")
            };

            var download3 = new DownloadFileInfo
            {
                Index = 2,
                //FileHttpUrl = "http://s3.favim.com/orig/42/cat-fat-cat-kitty-pursia-Favim.com-358172.jpg",
                FileHttpUrl = "http://drpinna.com/wp-content/uploads/2010/02/fat-cat1.jpg",
                DestinationDiskPath = Path.Combine(libFolder, "fatCat3.jpeg")
            };

            var download4 = new DownloadFileInfo
            {
                Index = 3,
                //FileHttpUrl = "http://www.zastavki.com/pictures/originals/2013/Animals___Cats__fat_cat_043905_.jpg",
                FileHttpUrl = "http://drpinna.com/wp-content/uploads/2010/02/fat-cat1.jpg",
                DestinationDiskPath = Path.Combine(libFolder, "fatCat4.jpg")
            };

            var download5 = new DownloadFileInfo
            {
                Index = 4,
                //FileHttpUrl = "http://images4.fanpop.com/image/photos/15700000/Honey-and-her-favorite-toy-Mr-Chipmunk-honey-the-fat-cat-15761646-2560-1920.jpg",
                FileHttpUrl = "http://drpinna.com/wp-content/uploads/2010/02/fat-cat1.jpg",
                DestinationDiskPath = Path.Combine(libFolder, "fatCat5.jpeg")
            };

            session.DownloadQueue.Add(download1);
            session.DownloadQueue.Add(download2);
            session.DownloadQueue.Add(download3);
            session.DownloadQueue.Add(download4);
            session.DownloadQueue.Add(download5);
        }
예제 #47
0
 //Splits a string array into download files array.
 private DownloadFileInfo[] StringToDownloadFilesArray(String[] downloadList)
 {
     DownloadFileInfo[] filesList = null;
     Int32 currentFileIndex = -1;
     for (Int32 i = 0; i <= downloadList.GetUpperBound(0); i++)
     {
         String[] lineSplit = downloadList[i].Split(new String[] { "=" }, StringSplitOptions.None);
         switch (lineSplit[0])
         {
             case "FileInfoStart":
                 if (filesList == null) { filesList = new DownloadFileInfo[1]; }
                 else { Array.Resize(ref filesList, filesList.GetUpperBound(0) + 2); }
                 currentFileIndex = filesList.GetUpperBound(0);
                 break;
             case "PATH":
                 filesList[currentFileIndex].Path = lineSplit[1];
                 break;
             case "URL":
                 filesList[currentFileIndex].Url = lineSplit[1];
                 break;
             case "HASH":
                 filesList[currentFileIndex].Hash = lineSplit[1];
                 break;
             case "ACTION":
                 filesList[currentFileIndex].Action = lineSplit[1];
                 break;
             case "NAME":
                 filesList[currentFileIndex].Name = lineSplit[1];
                 break;
             case "SIZE":
                 filesList[currentFileIndex].Size = Int64.Parse(lineSplit[1]);
                 break;
         }
     }
     return filesList;
 }
예제 #48
0
        public bool Install(VersionInfo build,string targetDirectory)
        {
            var filesinfo = GetVersionInfo(build);

            Log("Install : Build " + build.Build + " to : " + targetDirectory,true);
            DownloadFile(_repository + "/Download/" + _platform + "/" + build.Build + "/Install", "Install");
            bool res;
            using (var q = new ThreadedDownlads(Threads, _tempDirectory, false))
            {
                foreach (var files in filesinfo.FileInfos)
                {
                    var info = new DownloadFileInfo
                                   {
                                       FileSource =
                                           _platformUrl + @"/" + build.Build + @"/Files/" + files.FileHash + ".dat",
                                       FileDestination = targetDirectory + files.FilePath,
                                       FileHash = files.FileHash
                                   };
                    q.EnqueueTask(info);
                }
                res = q.WaitEnd();
            }
            return res;
        }