Пример #1
0
        /// <summary>
        /// Open the Inventory for a category to navigate within it and execute Actions on the Items.
        /// <para>
        /// getsCommand is a function which takes an Item and returns wether the Item should receive a/many Command/s or not
        /// </para>
        /// <para>onItemSelection is an Action which  is executed with the selected Item</para>
        /// <para>isAvailable is a FUnc which determines wether the item is available or not. It is appended to each Option</para>
        /// <para>UnavailableMessage is a Func which retruns the string to be printed when the Optionw as selected & unavailable</para>
        /// <para>if allowItemActions = false, no Item Actions are allowed</para>
        /// </summary>
        void NavigateItems(string category, Func <Item, bool> getsCommand, Action <Item> onItemSelection, Func <Item, bool> isAvailable, Func <Item, string> UnavailableMessage, bool allowItemActions)
        {
            Option selected = null;

            while (selected != Optionhandler.Exit)
            {
                List <Item> Items = this.GetAllItems(category);
                if (Items.Count == 0)
                {
                    return;
                }
                printHeader();
                Optionhandler OH = new Optionhandler(true);
                OH.setName("Inventory.Item");
                foreach (Item i in Items)
                {
                    if (allowItemActions == false)
                    {
                        if (getsCommand(i))
                        {
                            //Options which are available on the Item are defined on the Item and wrapped by the GenericItemOption
                            GenericItemOption opt = new GenericItemOption(i);
                            if (isAvailable != null)
                            {
                                Func <bool> f = () => isAvailable(i);
                                opt.SetAvailable(f);
                            }
                            if (UnavailableMessage != null)
                            {
                                Func <string> ff = () => UnavailableMessage(i);
                                opt.setNotAvailable(ff);
                            }
                            OH.AddOption(opt);
                        }
                        else
                        {
                            CIO.Print(i.getDescription());
                        }
                    }
                    else
                    {
                        GenericItemOption opt = new GenericItemOption(i);
                        OH.AddOption(opt);
                    }
                }
                selected = OH.selectOption(false);
                if (selected.GetType() == typeof(GenericItemOption))
                {
                    onItemSelection(((GenericItemOption)selected).getItem());
                }
            }
        }
        private void GetGame(List <GenericItemOption> gameList, string caption)
        {
            var item = plugin.PlayniteApi.Dialogs.ChooseItemWithSearch(gameList, (a) =>
            {
                try
                {
                    return(new List <GenericItemOption>(services.getGameListSGDB(a).Select(game => new GenericItemOption(game.name, game.id.ToString()))));
                }
                catch
                {
                    var sgdbException = new Exception("Service failure.");
                    throw sgdbException;
                }
            }, options.GameData.Name, caption);

            this.searchSelection = item;
        }
        public override void OnApplicationStarted()
        {
            Task.Run(() =>
            {
                // Clear temporary dowload folder and re-create it
                var downloadPath = Path.Combine(GetPluginUserDataPath(), "Temp");
                if (Directory.Exists(downloadPath))
                {
                    foreach (var file in Directory.EnumerateFiles(downloadPath, "*.pext"))
                    {
                        File.Delete(file);
                    }
                    foreach (var file in Directory.EnumerateFiles(downloadPath, "*.pthm"))
                    {
                        File.Delete(file);
                    }
                }
                else
                {
                    Directory.CreateDirectory(downloadPath);
                }
                if (_extensionsDirectories.Count == 0)
                {
                    return;
                }

                if (_playniteAPI.ApplicationInfo.InOfflineMode)
                {
                    _logger.Info("Application is in offline mode, skipping extension update check");
                    return;
                }

                IEnumerable <IGrouping <string, PlayniteExtensionConfig> > configs = _extensionsDirectories
                                                                                     .Where(Directory.Exists)
                                                                                     .SelectMany(extensionsDirectory =>
                                                                                                 Directory.EnumerateFiles(extensionsDirectory, "*.yaml", SearchOption.AllDirectories)
                                                                                                 .Select(file =>
                {
                    try
                    {
                        var config = YamlUtils.FromYaml <PlayniteExtensionConfig>(file);
                        return(config?.UpdaterConfig == null ? null : config);
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, $"Exception while trying to deserialize {file}!\n");
                    }

                    return(null);
                }).NotNull().GroupBy(config =>
                {
                    var repo = $"{config.UpdaterConfig.GitHubUser}/{config.UpdaterConfig.GitHubRepo}";
                    return(repo);
                }));

                configs.Do(async group =>
                {
                    var repo = group.Key;
                    _logger.Info($"Found: {repo}");

                    List <GitHubRelease> releases;

                    try
                    {
                        releases = await GitHub.GetGitHubReleases(repo);
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e, $"Exception while loading releases for {repo}");
                        return;
                    }

                    if (releases == null || releases.Count == 0)
                    {
                        _logger.Error($"Found no releases for {repo}");
                        return;
                    }

                    var latest         = releases[0];
                    var sLatestVersion = latest.tag_name;

                    if (sLatestVersion[0] == 'v')
                    {
                        sLatestVersion = sLatestVersion.Substring(1);
                    }

                    var canParseLatest = Version.TryParse(sLatestVersion, out var latestVersion);
                    List <Tuple <PlayniteExtensionConfig, bool> > shouldUpdate = group.Select(config =>
                    {
                        var canParseCurrent = Version.TryParse(config.Version, out var currentVersion);

                        if (canParseCurrent)
                        {
                            if (canParseLatest)
                            {
                                if (currentVersion < latestVersion)
                                {
                                    _logger.Info($"There is a new version available for {config.Name}: {latestVersion}");
                                    return(new Tuple <PlayniteExtensionConfig, bool>(config, true));
                                }

                                if (currentVersion != latestVersion)
                                {
                                    return(new Tuple <PlayniteExtensionConfig, bool>(config, false));
                                }

                                _logger.Info($"{config.Name} is up-to-date");
                                return(new Tuple <PlayniteExtensionConfig, bool>(config, false));
                            }

                            if (config.Version.Equals(sLatestVersion, StringComparison.OrdinalIgnoreCase))
                            {
                                _logger.Info($"{config.Name} is up-to-date");
                                return(new Tuple <PlayniteExtensionConfig, bool>(config, false));
                            }

                            _logger.Info($"There is a new version for {config.Name}: {sLatestVersion}");
                            return(new Tuple <PlayniteExtensionConfig, bool>(config, true));
                        }

                        if (config.Version.Equals(sLatestVersion, StringComparison.OrdinalIgnoreCase))
                        {
                            _logger.Info($"{config.Name} is up-to-date");
                            return(new Tuple <PlayniteExtensionConfig, bool>(config, false));
                        }

                        _logger.Info($"There is a new version for {config.Name}: {sLatestVersion}");
                        return(new Tuple <PlayniteExtensionConfig, bool>(config, true));
                    }).ToList();

                    if (shouldUpdate.Any(x => x.Item2))
                    {
                        var extensionsNameString = shouldUpdate
                                                   .Where(x => x.Item2)
                                                   .Select(x => x.Item1.Name)
                                                   .Aggregate((x, y) => $"{x}\n-{y}");
                        var message = $"The following Extension(s) can be updated:\n-{extensionsNameString}\nClick this message to download the release from {repo}.";

                        _playniteAPI.Notifications.Add(new NotificationMessage(repo, message, NotificationType.Info,
                                                                               () =>
                        {
                            Process.Start(latest.html_url);
                            // Check if there are assets associated with the release
                            if (latest.assets != null)
                            {
                                var playnitePath = Environment.ExpandEnvironmentVariables(PlayniteApi.Paths.ApplicationPath);
                                playnitePath     = Path.Combine(playnitePath, "Playnite.DesktopApp.exe");
                                var options      = new List <GenericItemOption>();
                                // Add all .pext and .pthm files as options
                                foreach (var asset in latest.assets)
                                {
                                    var path = Path.Combine(GetPluginUserDataPath(), "Temp", asset.name);
                                    var ext  = Path.GetExtension(asset.name).ToLower();
                                    if (ext == ".pext" || ext == ".pthm")
                                    {
                                        options.Add(new GenericItemOption(asset.name, asset.browser_download_url));
                                    }
                                }
                                // Only try to dowload and install if any options were found
                                if (options.Count > 0)
                                {
                                    GenericItemOption selected = options[0];
                                    // Let the user select a file to download
                                    // if multiple extension files have been found
                                    if (options.Count > 1)
                                    {
                                        selected = PlayniteApi.Dialogs.ChooseItemWithSearch(
                                            options,
                                            query => options.Where(o => query == null || query.Length == 0 || o.Name.ToLower().Contains(query.ToLower())).ToList(),
                                            null,
                                            "Multiple extension files found. Select the one you want to install."
                                            );
                                    }
                                    // Download and install selected option
                                    if (selected != null)
                                    {
                                        var path = Path.Combine(GetPluginUserDataPath(), "Temp", selected.Name);
                                        PlayniteApi.Dialogs.ActivateGlobalProgress(args =>
                                        {
                                            using (var webclient = new System.Net.WebClient())
                                            {
                                                // Dowload extension file into temporary folder
                                                webclient.DownloadFile(selected.Description, path);
                                            }
                                        }, new GlobalProgressOptions($"Dowloading {selected.Name}", false));
                                        // Open Playnite with installext argument to trigger
                                        // extension installation
                                        Process.Start("\"" + playnitePath + "\"", $"--installext \"{path}\"");
                                    }
                                }
                            }
                        }));
                    }
                    else
                    {
                        _logger.Info($"No Update available for {repo}");
                    }
                });
            }, _token);
        }