Example #1
0
        /// <summary>
        /// Handles the message activity asynchronously.
        /// </summary>
        /// <param name="turnContext">The turn context.</param>
        /// <returns>Task tracking operation.</returns>
        public async Task HandleMessageAsync(ITurnContext turnContext)
        {
            bool messageWithFileDownloadInfo = turnContext.Activity.Attachments?[0].ContentType == FileDownloadInfo.ContentType;

            if (messageWithFileDownloadInfo)
            {
                Attachment       file         = turnContext.Activity.Attachments[0];
                FileDownloadInfo fileDownload = JObject.FromObject(file.Content).ToObject <FileDownloadInfo>();

                string filePath = "Files\\" + file.Name;
                using (WebClient client = new WebClient())
                {
                    client.DownloadFile(fileDownload.DownloadUrl, filePath);
                }

                var reply = turnContext.Activity.CreateReply();
                reply.TextFormat = "xml";
                reply.Text       = $"Complete downloading <b>{file.Name}</b>";
                await turnContext.SendActivityAsync(reply).ConfigureAwait(false);
            }
            else
            {
                string filename = "teams-logo.png";
                string filePath = "Files\\" + filename;
                long   fileSize = new FileInfo(filePath).Length;
                await this.SendFileCardAsync(turnContext, filename, fileSize).ConfigureAwait(false);
            }
        }
Example #2
0
        public void RefreshData()
        {
            chkAutoFormatUrl.Checked           = Utility.GetRegSetting("AutoFormatURL", 1) == 1;
            chkIsMirrorServer.Checked          = Utility.GetRegSetting("IsMirrorServer", 1) == 1;
            chkMirrorCD.Checked                = Utility.GetRegSetting("MirrorCD", 0) == 1;
            chkAutoCheckUpdaterVersion.Checked = Utility.GetRegSetting("AutoCheckUpdaterVersion", 1) == 1;

            chkHttpProxy.Checked                  = Utility.GetRegSetting("ProxyEnabled", 0) == 1;
            chkUseDefaultProxy.Checked            = Utility.GetRegSetting("ProxyUseDefault", 1) == 1;
            chkUseDefaultProxyCredentials.Checked = Utility.GetRegSetting("ProxyUseDefaultCredentials", 1) == 1;
            chkProxyBypassOnLocal.Checked         = Utility.GetRegSetting("ProxyBypassOnLocal", 1) == 1;
            chkProxySuppress417Errors.Checked     = Utility.GetRegSetting("ProxyExpect100Continue", 0) == 0;
            txtProxyServerName.Text               = Utility.GetRegSetting("ProxyServerName", "");
            var port = Utility.GetRegSetting("ProxyPort", 0);

            if (port > 0)
            {
                txtProxyPort.Text = port.ToString();
            }
            else
            {
                txtProxyPort.Text = "";
            }
            txtProxyPassword.Text = Utility.GetRegSetting("ProxyPassword", "");
            txtProxyUsername.Text = Utility.GetRegSetting("ProxyUsername", "");
            txtProxyDomain.Text   = Utility.GetRegSetting("ProxyDomain", "");

            lnkOpenFolder.Text = FileDownloadInfo.DownloadedCacheFolder("");
            refreshGrid();
            syncGui();
            refreshSystemInfo();
        }
Example #3
0
        // ---------[ UI FUNCTIONALITY ]---------
        public override void DisplayDownload(FileDownloadInfo downloadInfo)
        {
            Debug.Assert(downloadInfo != null);

            if (m_updateCoroutine != null)
            {
                this.StopCoroutine(m_updateCoroutine);
            }

            m_downloadInfo = downloadInfo;

            Int64 bytesReceived = (downloadInfo.request == null
                                   ? 0
                                   : (Int64)downloadInfo.request.downloadedBytes);

            m_data = new DownloadDisplayData()
            {
                bytesReceived  = bytesReceived,
                bytesPerSecond = 0,
                bytesTotal     = downloadInfo.fileSize,
                isActive       = !downloadInfo.isDone,
            };

            if (Application.isPlaying && this.isActiveAndEnabled)
            {
                m_updateCoroutine = this.StartCoroutine(UpdateCoroutine());
            }
        }
        // ---------[ UI FUNCTIONALITY ]---------
        /// <summary>Displays the appropriate field of a given modfile.</summary>
        public void DisplayDownload(FileDownloadInfo download)
        {
            this.m_download = download;

            string displayText = string.Empty;

            if (download != null)
            {
                if (download.request == null ||
                    download.request.downloadedBytes == 0)
                {
                    displayText = this.m_unstartedText;
                }
                else if (download.isDone)
                {
                    displayText = this.m_completedText;
                }
                else if (download.bytesPerSecond <= 1)
                {
                    displayText = this.m_notDownloadingText;
                }
                else
                {
                    int secondsRemaining = (int)((download.fileSize - (Int64)download.request.downloadedBytes)
                                                 / download.bytesPerSecond);

                    displayText = ValueFormatting.SecondsAsTime(secondsRemaining);
                }
            }

            this.m_textComponent.text = displayText;
        }
        internal static async Task ProcessAttachment(Attachment attachment, IDialogContext context)
        {
            var replyMessage = context.MakeMessage();

            if (attachment.ContentType == FileDownloadInfo.ContentType)
            {
                FileDownloadInfo downloadInfo = (attachment.Content as JObject).ToObject <FileDownloadInfo>();

                if (downloadInfo != null)
                {
                    if (downloadInfo.FileType == "txt")
                    {
                        try
                        {
                            var httpClient = new HttpClient();
                            HttpResponseMessage response = await httpClient.GetAsync(downloadInfo.DownloadUrl);

                            var fileContents = await response.Content.ReadAsStringAsync();

                            replyMessage.Text = (fileContents.Length < 25)
                                                                ? $"File contents: {fileContents}"
                                                                : $"First 25 bytes: {fileContents.Substring(0, 25)}";
                        }
                        catch (Exception ex)
                        {
                            replyMessage.Text = $"Could not read file: {ex.Message}";
                        }
                    }
                }
            }

            await context.PostAsync(replyMessage);
        }
        public void FileDownloadInfoInitsWithNoArgs()
        {
            var fileDownloadInfo = new FileDownloadInfo();

            Assert.NotNull(fileDownloadInfo);
            Assert.IsType <FileDownloadInfo>(fileDownloadInfo);
        }
Example #7
0
        private string installViaSetupExe(string setupExePath, FileDownloadInfo di, out string logFileName)
        {
            if (di.InstalledVersion != "(not installed)")
            {
                // uninstall previous version first!
                UninstallExistingMsi(di.FullFilePath, di, this, true, !String.IsNullOrEmpty(_dbPassword) || _dbUsesWindowsAuthentication, _dbPassword, _dbUsesWindowsAuthentication);
            }

            string url = "";

            logFileName = setupExePath + ".install_log";
            var p = new Process();

            var optionalData = "";
            var passive      = "";

            if (_silentInstall)
            {
                passive = @" /passive ";

                if (_includeOptionalData)
                {
                    optionalData = @" OPTIONALDATA=""TRUE"" ";
                }
                else
                {
                    optionalData = @" OPTIONALDATA=""FALSE"" ";
                }
            }

            var encPassword = Utility.EncryptText(_dbPassword);

            p.StartInfo = new ProcessStartInfo(setupExePath, url + @" PASSWORD=""" + encPassword + @""" USEWINDOWSAUTH=""" + _dbUsesWindowsAuthentication.ToString().ToLower() + @"""  AUTOLOGIN=""TRUE"" " + passive + optionalData + @" /L*v """ + setupExePath.Replace(@"\", @"\\") + @".install_log"" ");
            p.Start();

            if (_installingNewUpdater)
            {
                // an exe locks files when it's running -- meaning if we try to update the updater while it's running,
                // we're guaranteed it will fail.
                copyForMirrorIfNeeded(Directory.GetParent(setupExePath).FullName, di);
                return(null);
            }


            p.WaitForExit();

            // ASSUMPTION: all setup.exe are renamed to coincide with their corresponding msi file...
            string msiName = di.FileName.ToLower().Replace(".exe", ".msi");

            waitForMsiToFinish(this, msiName);
            di.TriedToInstall = true;
            if (di.Child != null)
            {
                di.Child.TriedToInstall = true;
            }

            copyForMirrorIfNeeded(Directory.GetParent(setupExePath).FullName, di);

            return(msiName);
        }
        // ---------[ INITIALIZATION ]---------
        public void OnEnable()
        {
            GetData();
            FileDownloadInfo downloadInfo = DownloadClient.GetActiveModBinaryDownload(m_data.profile.modId,
                                                                                      m_data.currentBuild.modfileId);

            DisplayDownload(downloadInfo);
        }
        private static async Task HandleExcelAttachement(IDialogContext context, Activity activity, TokenResponse token, Attachment attachment)
        {
            if (attachment.ContentType == FileDownloadInfo.ContentType)
            {
                FileDownloadInfo downloadInfo = (attachment.Content as JObject).ToObject <FileDownloadInfo>();
                var filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Files/");
                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                filePath += attachment.Name + DateTime.Now.Millisecond; // just to avoid name collision with other users.
                if (downloadInfo != null)
                {
                    using (WebClient myWebClient = new WebClient())
                    {
                        // Download the Web resource and save it into the current filesystem folder.
                        myWebClient.DownloadFile(downloadInfo.DownloadUrl, filePath);
                    }
                    if (File.Exists(filePath))
                    {
                        string emailId = await GetUserEmailId(activity);

                        string domainName  = emailId.Split('@').LastOrDefault();
                        var    teamDetails = ExcelHelper.GetAddTeamDetails(filePath, domainName);
                        if (teamDetails == null)
                        {
                            await context.PostAsync($"Attachment received but unfortunately we are not able to read your excel file. Please make sure that all the colums are correct.");
                        }
                        else
                        {
                            string lastAction;
                            if (context.UserData.TryGetValue(LastAction, out lastAction))
                            {
                                await context.PostAsync($"Attachment received. Working on getting your {teamDetails.Count} Teams ready.");

                                GraphAPIHelper helper = new GraphAPIHelper();
                                if (lastAction == "create team")
                                {
                                    await helper.ProcessCreateNewRequest(context, teamDetails, token.Token);
                                }
                                else
                                {
                                    await helper.ProcessUpdateRequest(context, teamDetails, token.Token);
                                }
                            }
                            else
                            {
                                await context.PostAsync($"Not able to process your file. Please restart the flow.");
                            }
                            await SendHelpMessage(context, activity);
                        }

                        File.Delete(filePath);
                    }
                }
            }
        }
Example #10
0
        public static List <Model.Expense> ReadCsv(Attachment attachment)
        {
            var expenseList = new List <Model.Expense>();

            if (attachment.ContentType == FileDownloadInfo.ContentType)
            {
                FileDownloadInfo downloadInfo = (attachment.Content as JObject).ToObject <FileDownloadInfo>();
                var filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Files/");

                filePath += attachment.Name + DateTime.Now.Millisecond; // just to avoid name collision with other users
                if (downloadInfo != null)
                {
                    using (WebClient myWebClient = new WebClient())
                    {
                        // Download the Web resource and save it into the current filesystem folder.
                        myWebClient.DownloadFile(downloadInfo.DownloadUrl, filePath);
                    }
                    if (File.Exists(filePath))
                    {
                        using (TextFieldParser parser = new TextFieldParser(filePath))
                        {
                            bool isFirstRow = true;
                            parser.TextFieldType = FieldType.Delimited;
                            parser.SetDelimiters(",");
                            while (!parser.EndOfData)
                            {
                                string[] fields = parser.ReadFields();

                                if (isFirstRow)
                                {
                                    isFirstRow = false;
                                    continue;
                                }
                                try
                                {
                                    var expense = new Model.Expense()
                                    {
                                        SerialNumber = Convert.ToDouble(fields[0]),
                                        ReportName   = fields[1],
                                        Date         = DateTime.Parse(fields[2]),
                                        Description  = fields[3],
                                        Currency     = Currency.Rupee,
                                        TotalAmount  = Convert.ToDecimal(fields[4])
                                    };
                                    expenseList.Add(expense);
                                }
                                catch (Exception ex)
                                {
                                    throw;
                                }
                            }
                        }
                    }
                }
            }
            return(expenseList);
        }
Example #11
0
        public void OnModDownloadStarted(int modId, FileDownloadInfo downloadInfo)
        {
            Debug.Assert(this.modView != null);

            if (this.m_isInitialized &&
                this.m_modId == modId)
            {
                this.modView.DisplayDownload(downloadInfo);
            }
        }
 public void OnModDownloadStarted(int modId, FileDownloadInfo downloadInfo)
 {
     foreach (ModView view in this.m_modViews)
     {
         if (view.data.profile.modId == modId)
         {
             view.DisplayDownload(downloadInfo);
         }
     }
 }
Example #13
0
        // ---------[ UI FUNCTIONALITY ]---------
        /// <summary>Displays the appropriate field of a given download.</summary>
        public void DisplayDownload(FileDownloadInfo downloadInfo)
        {
            this.m_downloadInfo = downloadInfo;

            // display
            object fieldValue    = this.reference.GetValue(this.m_downloadInfo);
            string displayString = ValueFormatting.FormatValue(fieldValue,
                                                               this.formatting.method,
                                                               this.formatting.toStringParameter);

            this.m_textComponent.text = displayString;
        }
Example #14
0
 private void refreshGrid()
 {
     dataGridView1.Rows.Clear();
     foreach (string f in Utility.GetAllFiles(FileDownloadInfo.DownloadedCacheFolder(""), true))
     {
         var fi  = new FileInfo(f);
         var idx = dataGridView1.Rows.Add(true, fi.Name, (((decimal)fi.Length) / 1024.0M / 1024.0M).ToString("###,###,##0.00"), fi.FullName);
         var lnk = dataGridView1.Rows[idx].Cells[1] as DataGridViewLinkCell;
         lnk.Tag         = fi.FullName;
         lnk.ToolTipText = "Show " + fi.Name + " in Windows Explorer";
     }
     btnDelete.Enabled = dataGridView1.Rows.Count > 0;
 }
Example #15
0
        private void Connection_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            FileDownloadInfo info = e.UserState as FileDownloadInfo;

            if (info == null)
            {
                return;
            }

            info.Args.Progress = e.ProgressPercentage * 0.01;

            FileDownloadProgress?.Invoke(this, info.Args);
        }
        public void FileDownloadInfoInits()
        {
            var downloadUrl = "https://example-download-url.com";
            var uniqueId    = "file-unique-id-123";
            var fileType    = ".txt";
            var etag        = "etag123";

            var fileDownloadInfo = new FileDownloadInfo(downloadUrl, uniqueId, fileType, etag);

            Assert.NotNull(fileDownloadInfo);
            Assert.IsType <FileDownloadInfo>(fileDownloadInfo);
            Assert.Equal(downloadUrl, fileDownloadInfo.DownloadUrl);
            Assert.Equal(uniqueId, fileDownloadInfo.UniqueId);
            Assert.Equal(fileType, fileDownloadInfo.FileType);
            Assert.Equal(etag, fileDownloadInfo.Etag);
        }
Example #17
0
        // ---------[ EVENTS ]---------
        /// <summary>Initializes the component display.</summary>
        protected virtual void OnDownloadStarted(ModfileIdPair idPair, FileDownloadInfo downloadInfo)
        {
            if (this.m_modId == idPair.modId)
            {
                this.m_downloadInfo = downloadInfo;

                if (!this.isActiveAndEnabled && this.hideIfInactive)
                {
                    this.gameObject.SetActive(true);
                }

                if (this.isActiveAndEnabled && this.m_updateCoroutine == null)
                {
                    this.m_updateCoroutine = this.StartCoroutine(this.UpdateCoroutine());
                }
            }
        }
Example #18
0
        public Task <bool> DownloadEpisode(int episode)
        {
            var info = new FileDownloadInfo();

            if (_episodes.ContainsKey(episode))
            {
                var episodeToUse = _episodes[episode];
                episodeToUse.IsDownloaded = false;
                info.FileUri          = episodeToUse.FileUri.ToString();
                info.FilePath         = Path.Combine(Config.Instance.ConfigObject.RootPath, FolderPath, episodeToUse.PublishDateUtc.Year.ToString(), episodeToUse.FileName);
                info.EpNumber         = episode;
                info.PodcastShortCode = ShortCode;
                FileDownloader.AddFile(info);
                FileDownloader.OnDownloadFinishedEvent += OnFinishDownloading;
                return(Task.FromResult(true));
            }
            return(Task.FromResult(false));
        }
Example #19
0
        private System.Collections.IEnumerator UpdateCoroutine()
        {
            float timeStepElapsed        = 0f;
            Int64 timeStepStartByteCount = (m_downloadInfo.request == null
                                            ? 0
                                            : (Int64)m_downloadInfo.request.downloadedBytes);

            while (m_downloadInfo != null &&
                   !m_downloadInfo.isDone)
            {
                if (m_data.bytesTotal <= 0)
                {
                    m_data.bytesTotal = m_downloadInfo.fileSize;
                }

                if (m_downloadInfo.request != null)
                {
                    m_data.bytesReceived = (Int64)m_downloadInfo.request.downloadedBytes;
                }

                if (timeStepElapsed >= 1f)
                {
                    m_data.bytesPerSecond = (Int64)((m_data.bytesReceived - timeStepStartByteCount)
                                                    / timeStepElapsed);

                    timeStepElapsed        = 0f;
                    timeStepStartByteCount = m_data.bytesReceived;
                }

                PresentData();

                yield return(null);

                timeStepElapsed += Time.unscaledDeltaTime;
            }

            m_data.bytesReceived  = m_data.bytesTotal;
            m_data.bytesPerSecond = 0;
            m_data.isActive       = false;

            m_downloadInfo = null;

            PresentData();
        }
Example #20
0
        public static void UninstallExistingMsi(string exeOrMsiFullPath, FileDownloadInfo fdi, Form parentForm, bool silentMode, bool autoLogin, string password, bool useWindowsAuth)
        {
            var splash = new frmSplash();

            try {
                var p = new Process();

                if (fdi.ProductGuid == Guid.Empty && String.IsNullOrEmpty(fdi.UninstallString))
                {
                    // this FileDownloadInfo represents the 'new' installer file, and it was not looked up from the registry.
                    var apps = Utility.ListInstalledApplications();
                    apps.TryGetValue(fdi.DisplayName, out fdi);
                    // now, fdi represents the currently installed version info, meaning the uninstall info, if any, should be present.
                }

                if (fdi.ProductGuid != Guid.Empty)
                {
                    splash.ChangeText(getDisplayMember("UninstallExistingMsi{start}", "Uninstalling version {0} of {1}, please be patient...", fdi.InstalledVersion, fdi.DisplayName));
                    //string logFileName = exeOrMsiFullPath + ".uninstall_log";
                    // "B" format in following line means:
                    //      32 digits separated by hyphens, enclosed in brackets:
                    //      {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
                    //p.StartInfo = new ProcessStartInfo("msiexec.exe", " " + (silentMode ? " /passive " : "") + (autoLogin ? @" AUTOLOGIN=""TRUE"" " : "") + @" USEWINDOWSAUTH=""" + useWindowsAuth.ToString().ToUpper() + @""" PASSWORD=""" + password + @""" /L*v """ + logFileName + @""" /X" + fdi.ProductGuid.ToString("B"));

                    var encPassword = Utility.EncryptText(password);

                    p.StartInfo = new ProcessStartInfo("msiexec.exe", " " + (silentMode ? " /passive " : "") + (autoLogin ? @" AUTOLOGIN=""TRUE"" " : "") + @" USEWINDOWSAUTH=""" + useWindowsAuth.ToString().ToUpper() + @""" PASSWORD=""" + encPassword + @""" /X" + fdi.ProductGuid.ToString("B"));
                    p.Start();
                    p.WaitForExit();
                    waitForMsiToFinish(parentForm, "/X" + fdi.ProductGuid.ToString("B"));

                    //                waitForMsiToFinish(parentForm, fdi.FileName ?? fdi.ProductGuid.ToString("B"));
                }
                else if (!String.IsNullOrEmpty(fdi.UninstallString))
                {
                    splash.ChangeText(getDisplayMember("UninstallExistingMsi{start}", "Uninstalling version {0} of {1}, please be patient...", fdi.InstalledVersion, fdi.DisplayName));
                    p.StartInfo = new ProcessStartInfo("cmd.exe", " /k " + fdi.UninstallString);
                    p.Start();
                    p.WaitForExit();
                }
            } finally {
                splash.Close();
            }
        }
        public async Task<FileDownloadInfo> GetInfoForDownload(string requestedVirtualPath)
        {
            if (string.IsNullOrEmpty(requestedVirtualPath))
            {
                return null;
            }

            await EnsureProjectSettings().ConfigureAwait(false);

            if (!requestedVirtualPath.StartsWith(_rootPath.RootVirtualPath))
            {
                _log.LogWarning($"GetInfoForDownload: {requestedVirtualPath} was not valid for root path {_rootPath.RootVirtualPath}");
                return null;
            }

            var virtualSubPath = requestedVirtualPath.Substring(_rootPath.RootVirtualPath.Length);
            var segments = virtualSubPath.Split('/');

            if (segments.Length == 0)
            {
                _log.LogWarning($"GetInfoForDownload: {requestedVirtualPath} was not valid for root path {_rootPath.RootVirtualPath}");
                return null;
            }

            var currentFsPath = Path.Combine(_rootPath.RootFileSystemPath, Path.Combine(segments));
            var ext = Path.GetExtension(currentFsPath);

            if (!File.Exists(currentFsPath))
            {
                _log.LogWarning($"GetInfoForDownload: {requestedVirtualPath} does not exist");
                return null;
            }

            var result = new FileDownloadInfo()
            {
                FileName = Path.GetFileName(currentFsPath),
                FileSystemPath = currentFsPath,
                MimeType = GetMimeType(ext)
            };

            return result;


        }
Example #22
0
        // ---------[ UI FUNCTIONALITY ]---------
        /// <summary>Displays the download.</summary>
        public void DisplayDownload(FileDownloadInfo download)
        {
            float p = 0f;
            if(download != null)
            {
                if(download.isDone)
                {
                    p = 1f;
                }
                else if(download.request != null
                        && download.fileSize > 0)
                {
                    p = ((float)download.request.downloadedBytes
                         / (float)download.fileSize);
                }
            }

            this.GetComponent<HorizontalProgressBar>().percentComplete = p;
        }
Example #23
0
        private void copyForMirror(string sourceFolder, FileDownloadInfo di)
        {
            // we copy directly to the web app uploads folder if possible.
            // if the web app doesn't exist, we copy it to the mirror_installers temp folder
            // so later when the web app is installed, it'll slurp the files up into the uploads folder.

            var    destPath       = Utility.ResolveDirectoryPath(Utility.GetTempDirectory(500) + @"\mirror_installers", true);
            string actualDestPath = "";

            try {
                var ggWebAppPath = Utility.GetIISPhysicalPath("gringlobal");
                if (!String.IsNullOrEmpty(ggWebAppPath))
                {
                    // copying directly to the web server folder
                    destPath       = ggWebAppPath;
                    actualDestPath = Utility.ResolveFilePath(destPath + di.AppRelativeUrl.Replace("~/", @"\").Replace(@"\\", @"\"), true);
                }
                else
                {
                    // copying to the mirrors_installers cache folder for later
                    actualDestPath = Utility.ResolveFilePath(destPath + di.AppRelativeUrl.Replace("~/uploads/installers/", @"\").Replace(@"\\", @"\"), true);
                }
            } catch {
                // copying to the mirrors_installers cache folder for later
                actualDestPath = Utility.ResolveFilePath(destPath + di.AppRelativeUrl.Replace("~/uploads/installers/", @"\").Replace(@"\\", @"\"), true);
            }

            var actualSourcePath = Utility.ResolveFilePath(sourceFolder + @"\" + di.FileName, false);

            if (File.Exists(actualSourcePath))
            {
                if (File.Exists(actualDestPath))
                {
                    File.Delete(actualDestPath);
                }
                File.Copy(actualSourcePath, actualDestPath);

                //using (GUISvc.GUI gui = new GrinGlobal.Updater.GUISvc.GUI()) {
                //    // TODO: add the file mapping if needed...
                //}
            }
        }
Example #24
0
        // ---------[ UI FUNCTIONALITY ]---------
        /// <summary>Displays download for a given mod.</summary>
        public void DisplayProfile(ModProfile profile)
        {
            int newId = ModProfile.NULL_ID;

            if (profile != null)
            {
                newId = profile.id;
            }

            // check for change
            if (this.m_modId != newId)
            {
                // reset everything
                if (this.m_updateCoroutine != null)
                {
                    this.StopCoroutine(this.m_updateCoroutine);
                    this.m_updateCoroutine = null;
                }

                this.m_modId        = newId;
                this.m_downloadInfo = null;

                // check if currently downloading
                bool isDownloading = false;

                if (newId != ModProfile.NULL_ID)
                {
                    foreach (var kvp in DownloadClient.modfileDownloadMap)
                    {
                        if (kvp.Key.modId == this.m_modId)
                        {
                            isDownloading = true;
                            OnDownloadStarted(kvp.Key, kvp.Value);
                        }
                    }
                }

                // set active/inactive as appropriate
                this.gameObject.SetActive(isDownloading || !this.hideIfInactive);
            }
        }
        public void CardTests_FileDownloadInfoAttachment()
        {
            FileDownloadInfo fileDownloadInfo = new FileDownloadInfo
            {
                DownloadUrl = "https://bing.com",
                UniqueId    = "b83b9f77-7003-4d63-985c-9611c98303f3",
                FileType    = "txt"
            };

            string contents = JsonConvert.SerializeObject(new Attachment
            {
                Content     = fileDownloadInfo,
                ContentType = FileDownloadInfo.ContentType
            });
            Attachment attachment = JsonConvert.DeserializeObject <Attachment>(File.ReadAllText(@"Jsons\SampleFileDownloadInfoAttachment.json"));

            Assert.IsNotNull(attachment);
            Assert.IsNotNull(attachment.Content);
            Assert.IsTrue(JObject.DeepEquals(JObject.FromObject(fileDownloadInfo), JObject.FromObject(attachment.Content)));
            Assert.AreEqual(FileDownloadInfo.ContentType, attachment.ContentType);
        }
Example #26
0
        private void SyncFiles()
        {
            FileSyncStarted?.Invoke(this, EventArgs.Empty);

            var cfg = FilesToDownload.Find((x) => Path.GetFileName(x).ToLowerInvariant() == "config.xml");

            if (cfg != null)    // push the config to the front so it gets downloaded first, so we can do settings ASAP
            {
                FilesToDownload.Remove(cfg);
                FilesToDownload.Insert(0, cfg);
            }

            // TODO sort the world paths first, so settings can pick a world


            // download what we gotta get
            for (int i = 0; i < MaxDownloads; i++)
            {
                FileDownloadInfo info = new FileDownloadInfo();
                info.Connection = new WebClient();
                info.Connection.UploadValuesCompleted += Connection_UploadValuesCompleted;
                info.Connection.UploadProgressChanged += Connection_UploadProgressChanged;

                info.Args = new FileProgressEventArgs(string.Empty, string.Empty, i + 1, 0);
                DownloadPool.Add(info);

                StartDLJob(info);
            }

            bool done = false;

            while (!done)
            {
                Thread.Sleep(100);
                lock (DownloadPool)
                    done = DownloadPool.Count == 0;
            }

            FileSyncEnded?.Invoke(this, EventArgs.Empty);
        }
Example #27
0
        private void copyForMirrorIfNeeded(string sourceFolder, FileDownloadInfo di)
        {
            // copy from installercache to somewhere under localhost/gringlobal/uploads folder
            if (_isMirrorServer)
            {
                // note we copy the parent and child as well, if either exists
                // if we install the setup.exe, we get the corresponding .msi
                // if we install the .msi, we get the corresponding .exe.

                if (di.Parent != null)
                {
                    copyForMirror(sourceFolder, di.Parent);
                }

                copyForMirror(sourceFolder, di);

                if (di.Child != null)
                {
                    copyForMirror(sourceFolder, di.Child);
                }
            }
        }
Example #28
0
        private void Connection_UploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e)
        {
            FileDownloadInfo info = e.UserState as FileDownloadInfo;

            if (info == null)
            {
                return;
            }

            if (e.Error != null || e.Cancelled)
            {
                info.Args.Progress = -1;
                FileDownloadError?.Invoke(this, info.Args);
            }

            info.Args.Progress = 1;
            FileDownloadProgress?.Invoke(this, info.Args);

            lock (info.LocalFile.Directory)
            {
                if (!info.LocalFile.Directory.Exists)
                {
                    info.LocalFile.Directory.Create();
                }
            }

            var           fs = info.LocalFile.OpenWrite();
            var           ms = new MemoryStream(e.Result);
            DeflateStream df = new DeflateStream(ms, CompressionMode.Decompress);

            df.CopyTo(fs);
            df.Close();
            fs.Close();

            FileDownloadCompleted?.Invoke(this, info.Args);

            StartDLJob(info);
        }
Example #29
0
        protected virtual void StartDLJob(FileDownloadInfo info)
        {
            string jobURL = PopDownloadFile();

            if (jobURL == string.Empty)
            {
                lock (DownloadPool)
                    DownloadPool.Remove(info);

                info.Connection.Dispose();
                info = null;
            }
            else
            {
                info.Args.DownloadFileName = jobURL;
                info.Args.Progress         = 0;
                lock (RootDir)
                    info.LocalFile = new FileInfo(Path.Combine(RootDir.FullName, jobURL));
                info.Args.LocalFileName = info.LocalFile.FullName;

                FileDownloadStarted?.Invoke(this, info.Args);

                string uriString = string.Empty;
                lock (UpdateServerURL)
                    uriString = UpdateServerURL + "dl.aspx";

                NameValueCollection data = new NameValueCollection();

                string cryptoFileName = HorizonCrypto.EncryptString(jobURL, CryptoSecret);

                data.Add("Timestamp", HorizonCrypto.TimeStamp());
                data.Add("Data", cryptoFileName);

                info.Connection.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

                info.Connection.UploadValuesAsync(new Uri(uriString), "POST", data, info);
            }
        }
        public void DisplayDownload(FileDownloadInfo downloadInfo)
        {
            bool activeDownload = (downloadInfo != null && !downloadInfo.isDone);

            if (downloadDisplay != null)
            {
                if (m_downloadDisplayCoroutine != null)
                {
                    this.StopCoroutine(m_downloadDisplayCoroutine);
                }

                downloadDisplay.gameObject.SetActive(activeDownload);

                if (this.isActiveAndEnabled &&
                    activeDownload)
                {
                    downloadDisplay.DisplayDownload(downloadInfo);
                    m_downloadDisplayCoroutine = this.StartCoroutine(MonitorDownloadCoroutine(data.profile.modId));
                }

                m_data.binaryDownload = downloadDisplay.data;
            }
            else
            {
                DownloadDisplayData data = new DownloadDisplayData();
                data.bytesReceived  = 0;
                data.bytesPerSecond = 0;
                data.bytesTotal     = 0;
                data.isActive       = activeDownload;

                if (downloadInfo != null)
                {
                    data.bytesReceived = (downloadInfo.request == null
                                          ? 0 : (Int64)downloadInfo.request.downloadedBytes);
                    data.bytesTotal = downloadInfo.fileSize;
                }
            }
        }