Пример #1
0
        public MainWindowViewModel()
        {
            Samples = new ObservableCollection<string>();

            RefreshSamplesCommand = new System.Wpf.Mvvm.Commands.AsyncDelegateCommand(async (t) =>
            {
                var d = new DownloadDialog();
                d.ShowDialog();
            }, (obj) => true);

            foreach (var s in Directory.GetFiles(Environment.CurrentDirectory + "\\Samples\\", "*.dll"))
            {
                var ass = Assembly.LoadFile(s);
                foreach (var t in ass.GetTypes())
                {
                    if (t.BaseType.Name == typeof(Sample).Name)
                    {
                        var inst = ass.CreateInstance(t.FullName) as Sample;

                        _samples.Add(inst.Name, inst.View);
                    }
                }
            }

            foreach (var item in _samples)
            {
                Samples.Add(item.Key);
            }
        }
        private void downloadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripItem    item = (ToolStripItem)sender;
            ContextMenuStrip menu = (ContextMenuStrip)item.Owner;
            DataGridView     grid = (DataGridView)menu.SourceControl;

            if (grid.Rows[SelectedRow].HeaderCell.Value.GetType() == typeof(Song))
            {
                Song s = (Song)grid.Rows[SelectedRow].HeaderCell.Value;
                DownloadDialog.ShowDialog();
                if (ActiveUser.GetPremium())
                {
                    try
                    {
                        File.Copy(s.GetFileName(), DownloadDialog.SelectedPath + $"{s.GetMetadata().GetName()}-{s.GetMetadata().GetArtist()}"
                                  + s.GetInfo()["format"], true);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("File already exists", "Error", MessageBoxButtons.OK);
                    }
                }
                else
                {
                    MessageBox.Show("Download exclusive to premium members", "Error", MessageBoxButtons.OK);
                }
            }
        }
Пример #3
0
        private bool DownloadExecuteFile()
        {
            string dirPath = Path.GetDirectoryName(_downloadFilePath);

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

            string url = GithubUtil.GetDownloadUrlForLatestAsset("vip00112", "GTLauncherDependency", "GoodbyeDPI*.zip");

            if (string.IsNullOrWhiteSpace(url))
            {
                return(false);
            }

            using (var dialog = new DownloadDialog(url, _downloadFilePath))
            {
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    // Unzip
                    return(ZipUtil.Unzip(_downloadFilePath, Path.GetDirectoryName(_downloadFilePath), true));
                }
            }

            return(false);
        }
Пример #4
0
        public Tuple <bool, byte[]> Download(Uri link)
        {
            using DownloadDialog dialog = new DownloadDialog(link.AbsoluteUri);
            bool success = dialog.ShowDialog() == DialogResult.OK;

            return(new Tuple <bool, byte[]>(success, success ? dialog.Result : null));
        }
Пример #5
0
        private async void ExecuteOpenLinkCommand()
        {
            _info = new LinkInfo();
            DownloadDialog dialog = new DownloadDialog();
            var            res    = await dialog.ShowAsync();

            switch (res)
            {
            case ContentDialogResult.None:
                break;

            case ContentDialogResult.Primary:
                _info.Path = dialog.Link;
                _info.Type = LinkType.Online;
                ReadLinkInfo(_info);
                if (RecentList.All(p => p.Path != _info.Path))
                {
                    _dataAccess.AddRecent(_info);
                    RecentList.Add(_info);
                }
                break;

            case ContentDialogResult.Secondary:
                break;
            }
        }
Пример #6
0
        /// <summary>更新程序</summary>
        /// <param name="isManual">是否为手动点击更新</param>
        private static void UpdateApp(bool isManual)
        {
            string      url = AppConfig.RequestUseGithub ? GithubLatestApi : GiteeLatestApi;
            XmlDocument doc = GetWebJsonToXml(url);

            if (doc == null)
            {
                if (isManual)
                {
                    MessageBoxEx.Show(AppString.Message.NetworkDtaReadFailed);
                    url = AppConfig.RequestUseGithub ? GithubLatest : GiteeReleases;
                    ExternalProgram.OpenUrl(url);
                }
                return;
            }
            XmlNode    root      = doc.FirstChild;
            XmlElement tagNameXE = (XmlElement)root.SelectSingleNode("tag_name");
            Version    webVer    = new Version(tagNameXE.InnerText);
            Version    appVer    = new Version(Application.ProductVersion);

            //appVer = new Version(0, 0, 0, 0);//测试用
            if (appVer >= webVer)
            {
                if (isManual)
                {
                    MessageBoxEx.Show(AppString.Message.VersionIsLatest);
                }
            }
            else
            {
                XmlElement bodyXE = (XmlElement)root.SelectSingleNode("body");
                string     info   = AppString.Message.UpdateInfo.Replace("%v1", appVer.ToString()).Replace("%v2", webVer.ToString());
                info += "\r\n\r\n" + MachinedInfo(bodyXE.InnerText);
                if (MessageBoxEx.Show(info, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    string     netVer   = Environment.Version > new Version(4, 0) ? "4.0" : "3.5";
                    XmlElement assetsXE = (XmlElement)root.SelectSingleNode("assets");
                    foreach (XmlElement itemXE in assetsXE.SelectNodes("item"))
                    {
                        XmlElement nameXE = (XmlElement)itemXE.SelectSingleNode("name");
                        if (nameXE != null && nameXE.InnerText.Contains(netVer))
                        {
                            XmlElement urlXE = (XmlElement)itemXE.SelectSingleNode("browser_download_url");
                            using (DownloadDialog dlg = new DownloadDialog())
                            {
                                dlg.Url      = urlXE?.InnerText;
                                dlg.FilePath = Path.GetTempFileName();
                                if (dlg.ShowDialog() == DialogResult.OK)
                                {
                                    MessageBoxEx.Show(AppString.Message.UpdateSucceeded, MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    SingleInstance.Restart(null, dlg.FilePath);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #7
0
        private void downloadFileButton_Click(object sender, System.EventArgs e)
        {
            var dlg = new DownloadDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                //
            }
        }
Пример #8
0
        public DownloadDialogViewModel(DownloadDialog downloadDialog)
        {
            this.downloadDialog = downloadDialog;

            DownloadSamples();

            OkCommand = new AsyncDelegateCommand(async (s) =>
            {
                downloadDialog.Close();
            }, (obj) => done);
        }
Пример #9
0
        private async void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            if (seasonDetailVM.Detail == null || seasonDetailVM.Detail.episodes == null || seasonDetailVM.Detail.episodes.Count == 0)
            {
                return;
            }
            var downloadItem = new DownloadItem()
            {
                Cover      = seasonDetailVM.Detail.cover,
                SeasonID   = seasonDetailVM.Detail.season_id,
                SeasonType = seasonDetailVM.Detail.type,
                Episodes   = new List <DownloadEpisodeItem>(),
                Subtitle   = seasonDetailVM.Detail.subtitle,
                Title      = seasonDetailVM.Detail.title,
                Type       = DownloadType.Season
            };
            int i = 0;

            foreach (var item in seasonDetailVM.Detail.episodes)
            {
                // 检查正在下载及下载完成是否存在此视频
                int state = 0;
                if (DownloadVM.Instance.Downloadings.FirstOrDefault(x => x.EpisodeID == item.id.ToString()) != null)
                {
                    state = 2;
                }
                if (DownloadVM.Instance.Downloadeds.FirstOrDefault(x => x.Epsidoes.FirstOrDefault(y => y.EpisodeID == item.id.ToString()) != null) != null)
                {
                    state = 3;
                }

                //如果正在下载state=2,下载完成state=3
                downloadItem.Episodes.Add(new DownloadEpisodeItem()
                {
                    CID       = item.cid,
                    EpisodeID = item.id.ToString(),
                    Index     = i,
                    Title     = item.title + " " + item.long_title,
                    State     = state,
                    AVID      = item.aid,
                    BVID      = item.bvid,
                    ShowBadge = item.show_badge,
                    Badge     = item.badge,
                    IsPreview = item.IsPreview
                });
                i++;
            }

            DownloadDialog downloadDialog = new DownloadDialog(downloadItem);
            await downloadDialog.ShowAsync();
        }
Пример #10
0
 private static bool UpdateCheck()
 {
     SetSplash(3, "Comparing online version");
     if (Assembly.GetExecutingAssembly().GetName().Version >= UpToolLib.UpdateCheck.OnlineVersion)
     {
         return(true);
     }
     byte[] dl;
     SetSplash(4, "Downloading latest");
     using (DownloadDialog dlg = new DownloadDialog(UpToolLib.UpdateCheck.Installer.AbsoluteUri))
     {
         if (dlg.ShowDialog() != DialogResult.OK)
         {
             throw new Exception("Failed to update");
         }
         dl = dlg.Result;
     }
     SetSplash(8, "Verifying");
     using (SHA256CryptoServiceProvider sha256 = new SHA256CryptoServiceProvider())
     {
         string pkgHash = BitConverter.ToString(sha256.ComputeHash(dl)).Replace("-", string.Empty).ToUpper();
         if (pkgHash != UpToolLib.UpdateCheck.InstallerHash)
         {
             throw new Exception(
                       $"The hash is not equal to the one stored in the repo:\r\nPackage: {pkgHash}\r\nOnline: {UpToolLib.UpdateCheck.InstallerHash}");
         }
     }
     SetSplash(9, "Installing");
     if (Directory.Exists(PathTool.GetRelative("Install", "tmp")))
     {
         Directory.Delete(PathTool.GetRelative("Install", "tmp"), true);
     }
     Directory.CreateDirectory(PathTool.GetRelative("Install", "tmp"));
     using (MemoryStream ms = new MemoryStream(dl))
     {
         using ZipArchive ar = new ZipArchive(ms);
         ar.ExtractToDirectory(PathTool.GetRelative("Install", "tmp"), true);
     }
     Splash.Hide();
     Process.Start(new ProcessStartInfo
     {
         FileName         = PathTool.GetRelative("Install", "tmp", "Installer.exe"),
         Arguments        = "i -p",
         CreateNoWindow   = true,
         WindowStyle      = ProcessWindowStyle.Hidden,
         WorkingDirectory = PathTool.GetRelative("Install")
     });
     return(false);
 }
        public void TestDownloadConfiguration()
        {
            Console.WriteLine("TestDownloadConfiguration");

            // a configuration with a single component that contains two download components
            ConfigFile         configFile         = new ConfigFile();
            SetupConfiguration setupConfiguration = new SetupConfiguration();

            configFile.Children.Add(setupConfiguration);
            ComponentCmd component1 = new ComponentCmd();

            setupConfiguration.Children.Add(component1);
            component1.command          = "cmd.exe /C exit /b 0";
            component1.required_install = true;
            DownloadDialog component1downloaddialog = new DownloadDialog(
                string.Format("{0} Download Dialog", component1.id));

            component1.Children.Add(component1downloaddialog);
            Download component1download1 = new Download();

            component1download1.componentname       = "download 1";
            component1download1.sourceurl           = Assembly.GetExecutingAssembly().Location;
            component1download1.destinationpath     = Path.GetTempPath();
            component1download1.destinationfilename = Guid.NewGuid().ToString();
            component1downloaddialog.Children.Add(component1download1);
            Download component1download2 = new Download();

            component1download2.componentname       = "download 2";
            component1download2.sourceurl           = Assembly.GetExecutingAssembly().Location;
            component1download2.destinationpath     = Path.GetTempPath();
            component1download2.destinationfilename = Guid.NewGuid().ToString();
            component1downloaddialog.Children.Add(component1download2);

            // save config file
            string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");

            Console.WriteLine("Writing '{0}'", configFilename);
            configFile.SaveAs(configFilename);

            // execute dotNetInstaller
            Assert.AreEqual(0, dotNetInstallerExeUtils.Run(configFilename));
            File.Delete(configFilename);
            Assert.IsTrue(File.Exists(Path.Combine(component1download1.destinationpath, component1download1.destinationfilename)));
            File.Delete(Path.Combine(component1download1.destinationpath, component1download1.destinationfilename));
            Assert.IsTrue(File.Exists(Path.Combine(component1download2.destinationpath, component1download2.destinationfilename)));
            File.Delete(Path.Combine(component1download2.destinationpath, component1download2.destinationfilename));
        }
Пример #12
0
        private async void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            if (videoDetailVM.VideoInfo == null || videoDetailVM.VideoInfo.pages == null || videoDetailVM.VideoInfo.pages.Count == 0)
            {
                return;
            }
            var downloadItem = new DownloadItem()
            {
                Cover    = videoDetailVM.VideoInfo.pic,
                ID       = videoDetailVM.VideoInfo.aid,
                Episodes = new List <DownloadEpisodeItem>(),
                Subtitle = videoDetailVM.VideoInfo.bvid,
                Title    = videoDetailVM.VideoInfo.title,
                Type     = DownloadType.Video
            };
            int i = 0;

            foreach (var item in videoDetailVM.VideoInfo.pages)
            {
                //检查正在下载及下载完成是否存在此视频
                int state = 0;
                if (DownloadVM.Instance.Downloadings.FirstOrDefault(x => x.EpisodeID == item.cid) != null)
                {
                    state = 2;
                }
                if (DownloadVM.Instance.Downloadeds.FirstOrDefault(x => x.Epsidoes.FirstOrDefault(y => y.CID == item.cid) != null) != null)
                {
                    state = 3;
                }
                //如果正在下载state=2,下载完成state=3
                downloadItem.Episodes.Add(new DownloadEpisodeItem()
                {
                    AVID      = videoDetailVM.VideoInfo.aid,
                    BVID      = videoDetailVM.VideoInfo.bvid,
                    CID       = item.cid,
                    EpisodeID = "",
                    Index     = i,
                    Title     = "P" + item.page + " " + item.part,
                    State     = state
                });
                i++;
            }

            DownloadDialog downloadDialog = new DownloadDialog(downloadItem);
            await downloadDialog.ShowAsync();
        }
        public void TestNoDownloadWhenSourceFileExsts()
        {
            Console.WriteLine("TestNoDownloadWhenSourceFileExsts");

            // a configuration where the source file exists, no download dialog should show
            ConfigFile         configFile         = new ConfigFile();
            SetupConfiguration setupConfiguration = new SetupConfiguration();

            configFile.Children.Add(setupConfiguration);
            ComponentCmd cmd = new ComponentCmd();

            setupConfiguration.Children.Add(cmd);
            cmd.command          = "cmd.exe /C exit /b 0";
            cmd.required_install = true;
            DownloadDialog cmddownloaddialog = new DownloadDialog(
                string.Format("{0} Download Dialog", cmd.id));

            cmd.Children.Add(cmddownloaddialog);
            cmddownloaddialog.autostartdownload = false;
            Download download = new Download();

            download.componentname       = "download 1";
            download.sourceurl           = string.Format("http://{0}/dummy.exe", Guid.NewGuid());
            download.sourcepath          = Assembly.GetExecutingAssembly().Location;
            download.destinationpath     = Path.GetTempPath();
            download.destinationfilename = Guid.NewGuid().ToString();
            download.alwaysdownload      = false;
            cmddownloaddialog.Children.Add(download);

            // save config file
            string configFilename = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");

            Console.WriteLine("Writing '{0}'", configFilename);
            configFile.SaveAs(configFilename);

            // execute dotNetInstaller
            dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions();
            options.configFile = configFilename;
            options.args       = "/qb";
            options.quiet      = false;
            Assert.AreEqual(0, dotNetInstallerExeUtils.Run(options));
            File.Delete(configFilename);
            Assert.IsTrue(File.Exists(Path.Combine(download.destinationpath, download.destinationfilename)));
            File.Delete(Path.Combine(download.destinationpath, download.destinationfilename));
        }
Пример #14
0
        public void TestDisplayConfigWebConfiguration()
        {
            // config file with a web configuration (that will not be downloaded)
            ConfigFile       configFile       = new ConfigFile();
            string           configFilename   = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
            WebConfiguration webConfiguration = new WebConfiguration();
            DownloadDialog   downloadDialog   = new DownloadDialog();

            downloadDialog.Children.Add(new Download());
            webConfiguration.Children.Add(downloadDialog);
            configFile.Children.Add(webConfiguration);
            Console.WriteLine("Writing '{0}'", configFilename);
            configFile.SaveAs(configFilename);
            // execute
            dotNetInstallerExeUtils.RunOptions options = new dotNetInstallerExeUtils.RunOptions(configFilename);
            options.args  = "/qb /DisplayConfig";
            options.log   = false;
            options.quiet = false;
            Assert.AreEqual(0, dotNetInstallerExeUtils.Run(options));
            // cleanup
            File.Delete(configFilename);
        }
Пример #15
0
        internal void UpdateAction()
        {
            if (Global.UpdateModel == null)
            {
                return;
            }

            var download = new DownloadDialog();
            var result   = download.ShowDialog();

            if (result.HasValue && result.Value)
            {
                NotificationManager.RemoveNotification(s => s.Kind == StatusType.Update);

                //TODO: Check if possible to close.

                if (Dialog.Ask("ScreenToGif", LocalizationHelper.Get("Update.CloseThis"), LocalizationHelper.Get("Update.CloseThis.Detail")))
                {
                    Application.Current.Shutdown(69);
                }
            }
        }
Пример #16
0
        /// <summary>更新程序</summary>
        /// <param name="isManual">是否为手动点击更新</param>
        private static void UpdateApp(bool isManual)
        {
            using (UAWebClient client = new UAWebClient())
            {
                string      url = AppConfig.RequestUseGithub ? AppConfig.GithubLatestApi : AppConfig.GiteeLatestApi;
                XmlDocument doc = client.GetWebJsonToXml(url);
                if (doc == null)
                {
                    if (isManual)
                    {
                        if (AppMessageBox.Show(AppString.Message.WebDataReadFailed + "\r\n"
                                               + AppString.Message.OpenWebUrl, MessageBoxButtons.OKCancel) != DialogResult.OK)
                        {
                            return;
                        }
                        url = AppConfig.RequestUseGithub ? AppConfig.GithubLatest : AppConfig.GiteeReleases;
                        ExternalProgram.OpenWebUrl(url);
                    }
                    return;
                }
                XmlNode root      = doc.FirstChild;
                XmlNode tagNameXN = root.SelectSingleNode("tag_name");
                Version webVer    = new Version(tagNameXN.InnerText);
                Version appVer    = new Version(Application.ProductVersion);
#if DEBUG
                appVer = new Version(0, 0, 0, 0);//测试用
#endif
                if (appVer >= webVer)
                {
                    if (isManual)
                    {
                        AppMessageBox.Show(AppString.Message.VersionIsLatest,
                                           MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    XmlNode bodyXN = root.SelectSingleNode("body");
                    string  info   = AppString.Message.UpdateInfo.Replace("%v1", appVer.ToString()).Replace("%v2", webVer.ToString());
                    info += "\r\n\r\n" + MachinedInfo(bodyXN.InnerText);
                    if (MessageBox.Show(info, AppString.General.AppName,
                                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string  netVer   = Environment.Version > new Version(4, 0) ? "4.0" : "3.5";
                        XmlNode assetsXN = root.SelectSingleNode("assets");
                        foreach (XmlNode itemXN in assetsXN.SelectNodes("item"))
                        {
                            XmlNode nameXN = itemXN.SelectSingleNode("name");
                            if (nameXN != null && nameXN.InnerText.Contains(netVer))
                            {
                                XmlNode urlXN = itemXN.SelectSingleNode("browser_download_url");
                                using (DownloadDialog dlg = new DownloadDialog())
                                {
                                    dlg.Url      = urlXN?.InnerText;
                                    dlg.FilePath = $@"{AppConfig.AppDataDir}\{webVer}.exe";
                                    dlg.Text     = AppString.General.AppName;
                                    if (dlg.ShowDialog() == DialogResult.OK)
                                    {
                                        AppMessageBox.Show(AppString.Message.UpdateSucceeded,
                                                           MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        SingleInstance.Restart(null, dlg.FilePath);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #17
0
        private void HandleUri(string uri)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                WindowState = FormWindowState.Normal;
            }

            Activate();

            var fields = uri.Substring("smmm:".Length).Split(',');

            // TODO: lib-ify
            string itemType = fields.FirstOrDefault(x => x.StartsWith("gb_itemtype", StringComparison.InvariantCultureIgnoreCase));

            itemType = itemType.Substring(itemType.IndexOf(":") + 1);

            string itemId = fields.FirstOrDefault(x => x.StartsWith("gb_itemid", StringComparison.InvariantCultureIgnoreCase));

            itemId = itemId.Substring(itemId.IndexOf(":") + 1);

            var dummyInfo = new ModInfo();

            using (var client = new UpdaterWebClient())
            {
                var response = client.DownloadString(
                    string.Format("https://api.gamebanana.com/Core/Item/Data?itemtype={0}&itemid={1}&fields=name,authors",
                                  itemType, itemId)
                    );

                var array = JsonConvert.DeserializeObject <string[]>(response);
                dummyInfo.Name = array[0];

                var authors = JsonConvert.DeserializeObject <Dictionary <string, string[][]> >(array[1]);

                // for every array of string[] in authors, select the first element of each array
                var authorList = from i in (from x in authors select x.Value) from j in i select j[0];
                dummyInfo.Author = string.Join(", ", authorList);
            }

            DialogResult result = MessageBox.Show(this, $"Do you want to install mod \"{dummyInfo.Name}\" by {dummyInfo.Author} from {new Uri(fields[0]).DnsSafeHost}?", "Mod Download", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result != DialogResult.Yes)
            {
                return;
            }

            string updatePath = Path.Combine("mods", ".updates");

            #region create update folder
            do
            {
                try
                {
                    result = DialogResult.Cancel;
                    if (!Directory.Exists(updatePath))
                    {
                        Directory.CreateDirectory(updatePath);
                    }
                }
                catch (Exception ex)
                {
                    result = MessageBox.Show(this, "Failed to create temporary update directory:\n" + ex.Message
                                             + "\n\nWould you like to retry?", "Directory Creation Failed", MessageBoxButtons.RetryCancel);
                }
            } while (result == DialogResult.Retry);
            #endregion

            string dummyPath = dummyInfo.Name;

            foreach (char c in Path.GetInvalidFileNameChars())
            {
                dummyPath = dummyPath.Replace(c, '_');
            }

            dummyPath = Path.Combine("mods", dummyPath);

            var updates = new List <ModDownload>
            {
                new ModDownload(dummyInfo, dummyPath, fields[0], null, 0)
            };

            using (var progress = new DownloadDialog(updates, updatePath))
            {
                progress.ShowDialog(this);
            }

            do
            {
                try
                {
                    result = DialogResult.Cancel;
                    Directory.Delete(updatePath, true);
                }
                catch (Exception ex)
                {
                    result = MessageBox.Show(this, "Failed to remove temporary update directory:\n" + ex.Message
                                             + "\n\nWould you like to retry? You can remove the directory manually later.",
                                             "Directory Deletion Failed", MessageBoxButtons.RetryCancel);
                }
            } while (result == DialogResult.Retry);

            LoadModList();
        }
Пример #18
0
        internal bool InstallUpdate(bool wasPromptedManually = false)
        {
            try
            {
                //No new release available.
                if (Global.UpdateAvailable == null)
                {
                    return(false);
                }

                //TODO: Check if Windows is not turning off.

                //Prompt if:
                //Not configured to download the update automatically OR
                //Configured to download but set to prompt anyway OR
                //Download not completed (perharps because the notification was triggered by a query on Fosshub).
                if (UserSettings.All.PromptToInstall || !UserSettings.All.InstallUpdates || string.IsNullOrWhiteSpace(Global.UpdateAvailable.InstallerPath))
                {
                    var download = new DownloadDialog {
                        WasPromptedManually = wasPromptedManually
                    };
                    var result = download.ShowDialog();

                    if (!result.HasValue || !result.Value)
                    {
                        return(false);
                    }
                }

                //Only try to install if the update was downloaded.
                if (!File.Exists(Global.UpdateAvailable.InstallerPath))
                {
                    return(false);
                }

                var files              = Directory.EnumerateFiles(AppDomain.CurrentDomain.BaseDirectory).ToList();
                var isInstaller        = files.Any(x => x.ToLowerInvariant().EndsWith("screentogif.visualelementsmanifest.xml"));
                var hasSharpDx         = files.Any(x => x.ToLowerInvariant().EndsWith("sharpdx.dll"));
                var hasGifski          = files.Any(x => x.ToLowerInvariant().EndsWith("gifski.dll"));
                var hasMenuShortcut    = File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft", "Windows", "Start Menu", "Programs", "ScreenToGif.lnk"));
                var hasDesktopShortcut = File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Desktop", "ScreenToGif.lnk"));

                var startInfo = new ProcessStartInfo
                {
                    FileName  = "msiexec",
                    Arguments = $" {(isInstaller ? "/i" : "/a")} \"{Global.UpdateAvailable.InstallerPath}\"" +
                                $" {(isInstaller ? "INSTALLDIR" : "TARGETDIR")}=\"{AppDomain.CurrentDomain.BaseDirectory}\" INSTALLAUTOMATICALLY=yes INSTALLPORTABLE={(isInstaller ? "no" : "yes")}" +
                                $" ADDLOCAL=Binary{(isInstaller ? ",Auxiliar" : "")}{(hasSharpDx ? ",SharpDX" : "")}{(hasGifski ? ",Gifski" : "")}" +
                                $" {(wasPromptedManually ? "RUNAFTER=yes" : "")}" +
                                (isInstaller ? $" INSTALLDESKTOPSHORTCUT={(hasDesktopShortcut ? "yes" : "no")} INSTALLSHORTCUT={(hasMenuShortcut ? "yes" : "no")}" : ""),
                    Verb = "runas"
                };

                using (var process = new Process {
                    StartInfo = startInfo
                })
                    process.Start();

                return(true);
            }
            catch (Exception ex)
            {
                LogWriter.Log(ex, "Impossible to automatically install update");

                ErrorDialog.Ok("ScreenToGif", "It was not possible to install the update", ex.Message, ex);
                return(false);
            }
        }
Пример #19
0
        private async Task Launch(LaunchOption option)
        {
            //Check connection to launch agent
            if (AppServiceManager.appServiceConnection == null)
            {
                return;
            }

            List <MinecraftAssembly> missingLibs   = null; //include missing natives
            List <MinecraftAsset>    missingAssets = new List <MinecraftAsset>();

            #region Libraries and natives check
            ValueSet valueSet = new ValueSet();
            valueSet["type"]    = "librariesCheck";
            valueSet["version"] = option.versionId;
            AppServiceResponse response = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

            string responseJson = response.Message["value"].ToString();
            try
            {
                missingLibs = JsonConvert.DeserializeObject <List <MinecraftAssembly> >(responseJson);
            }
            catch (JsonException)
            { }
            #endregion

            #region Assets check
            valueSet            = new ValueSet();
            valueSet["type"]    = "assetsCheck";
            valueSet["version"] = option.versionId;
            response            = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

            object obj = null;
            response.Message.TryGetValue("index_path", out obj);
            // Asset index dose not exist or invalid
            if (obj != null)
            {
                string path = obj.ToString();
                string url  = response.Message["index_url"].ToString();

                try
                {
                    using (HttpClient client = new HttpClient())
                    {
                        string json = await client.GetStringAsync(url);

                        StorageFile file = await CoreManager.WorkDir.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting);

                        await FileIO.WriteTextAsync(file, json);
                    }
                }
                catch (Exception e)
                {
                    await _msgDialog.Show(
                        CoreManager.GetStringFromResource("/StartPage/LaunchFailed"),
                        "Cannot fetch asset index \r\n " + e.Message + "\r\n" + e.StackTrace
                        );

                    return;
                }

                //Check again after asset index downloaded
                response = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

                obj = null;
                response.Message.TryGetValue("index_path", out obj);
                if (obj != null)
                {
                    await _msgDialog.Show(
                        CoreManager.GetStringFromResource("/StartPage/LaunchFailed"),
                        "Asset index validation failed");

                    return;
                }
            }

            responseJson = response.Message["missing_assets"].ToString();
            try
            {
                missingAssets = JsonConvert.DeserializeObject <List <MinecraftAsset> >(responseJson);
            }
            catch (JsonException) { }
            #endregion

            //Found missing libs, go to download.
            if ((missingLibs != null && missingLibs.Count > 0) || (missingAssets != null && missingAssets.Count > 0))
            {
                missingLibs.ForEach(lib =>
                {
                    DownloadItem item = new DownloadItem(lib.Name, lib.Path, lib.Url);
                    DownloadManager.DownloadQuene.Add(item);
                });
                missingAssets.ForEach(ass =>
                {
                    DownloadItem item = new DownloadItem(
                        string.Format("{0}: {1}", CoreManager.GetStringFromResource("/Resources/Asset"), ass.Hash),
                        ass.GetPath(),
                        ass.GetDownloadUrl()
                        );
                    DownloadManager.DownloadQuene.Add(item);
                });

                DownloadManager.StartDownload();
                await DownloadDialog.ShowAsync();

                return;
            }

            DebugWriteLine("Serializing launch message to json");

            string messageJson;
            try
            {
                LaunchOptionBase tmp = option as LaunchOptionBase;
                if (string.IsNullOrWhiteSpace(option.javaExt))
                {
                    tmp.javaExt = CoreManager.GlobalJVMPath;
                }
                messageJson = JsonConvert.SerializeObject(tmp);
            }
            catch (JsonSerializationException exp)
            {
                DebugWriteLine("ERROR: " + exp.Message);
                return;
            }

            DebugWriteLine(messageJson);

            //Check if the launch message was successfully generated
            if (!string.IsNullOrWhiteSpace(messageJson))
            {
                valueSet = new ValueSet();
                valueSet.Add("type", "launch");
                valueSet.Add("launch_option", messageJson);
                valueSet.Add("auth_type", CoreManager.AccountTypeTag);
                valueSet.Add("auth_username", CoreManager.Username);
                response = await AppServiceManager.appServiceConnection.SendMessageAsync(valueSet);

                //Display error
                obj = response.Message["result"];
                if (obj is bool && !((bool)obj))
                {
                    await _msgDialog.Show(
                        CoreManager.GetStringFromResource("/StartPage/LaunchFailed"),
                        response.Message["errorMessage"].ToString() + "\r\n" + response.Message["errorStack"]
                        );
                }
            }
        }