Exemple #1
0
        private void Rescan(List <int> authorIds, bool isNew, CommandTrigger trigger, bool infoUpdated)
        {
            var rescanAfterRefresh = _configService.RescanAfterRefresh;
            var shouldRescan       = true;

            if (isNew)
            {
                _logger.Trace("Forcing rescan. Reason: New author added");
                shouldRescan = true;
            }
            else if (rescanAfterRefresh == RescanAfterRefreshType.Never)
            {
                _logger.Trace("Skipping rescan. Reason: never rescan after refresh");
                shouldRescan = false;
            }
            else if (rescanAfterRefresh == RescanAfterRefreshType.AfterManual && trigger != CommandTrigger.Manual)
            {
                _logger.Trace("Skipping rescan. Reason: not after automatic refreshes");
                shouldRescan = false;
            }
            else if (!infoUpdated)
            {
                _logger.Trace("Skipping rescan. Reason: no metadata updated");
                shouldRescan = false;
            }

            if (shouldRescan)
            {
                // some metadata has updated so rescan unmatched
                // (but don't add new authors to reduce repeated searches against api)
                var folders = _rootFolderService.All().Select(x => x.Path).ToList();

                _commandQueueManager.Push(new RescanFoldersCommand(folders, FilterFilesType.Matched, false, authorIds));
            }
        }
Exemple #2
0
        private void ProcessCommand(string rawString, MessageCreateEventArgs e, CommandTrigger type)
        {
            // The first thing we do is get rid of the prefix string from the command. We take the message from looking like say this:
            // --say something
            // to
            // say something
            // that way we don't have any excess characters getting in the way.
            string rawCommand = rawString.Substring(config.Prefix.Length);

            // A try catch block for executing the command and catching various things and reporting on errors.
            try
            {
                if (type == CommandTrigger.MessageCreate)
                {
                    commandManager.ExecuteOnMessageCommand(rawCommand, e.Channel, e.Author, e.Message, client);
                }
                else if (type == CommandTrigger.BotMentioned)
                {
                    commandManager.ExecuteOnMentionCommand(rawCommand, e.Channel, e.Author, e.Message, client);
                }
            }
            catch (UnauthorizedAccessException ex) // Bad permission
            {
                e.Channel.SendMessageAsync(ex.Message);
            }
            catch (ModuleNotEnabledException x) // Module is disabled
            {
                e.Channel.SendMessageAsync($"{x.Message}");
            }
            catch (Exception ex) // Any other error that could happen inside of the commands.
            {
                e.Channel.SendMessageAsync("Exception occurred while running command:\n```\n" + ex.Message + "\n```");
            }
        }
        private void RescanSeries(Series series, bool isNew, CommandTrigger trigger)
        {
            var rescanAfterRefresh = _configService.RescanAfterRefresh;
            var shouldRescan       = true;

            if (isNew)
            {
                _logger.Trace("Forcing rescan of {0}. Reason: New series", series);
                shouldRescan = true;
            }
            else if (rescanAfterRefresh == RescanAfterRefreshType.Never)
            {
                _logger.Trace("Skipping rescan of {0}. Reason: never rescan after refresh", series);
                shouldRescan = false;
            }
            else if (rescanAfterRefresh == RescanAfterRefreshType.AfterManual && trigger != CommandTrigger.Manual)
            {
                _logger.Trace("Skipping rescan of {0}. Reason: not after automatic scans", series);
                shouldRescan = false;
            }

            if (!shouldRescan)
            {
                return;
            }

            try
            {
                _diskScanService.Scan(series);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Couldn't rescan series {0}", series);
            }
        }
Exemple #4
0
        private UpdatePackage GetUpdatePackage(CommandTrigger updateTrigger)
        {
            _logger.ProgressDebug("Checking for updates");

            var latestAvailable = _checkUpdateService.AvailableUpdate();

            if (latestAvailable == null)
            {
                _logger.ProgressDebug("No update available");
                return(null);
            }

            if (OsInfo.IsNotWindows && !_configFileProvider.UpdateAutomatically && updateTrigger != CommandTrigger.Manual)
            {
                _logger.ProgressDebug("Auto-update not enabled, not installing available update");
                return(null);
            }


            // Safety net, ConfigureUpdateMechanism should take care of invalid settings
            if (_configFileProvider.UpdateMechanism == UpdateMechanism.BuiltIn && _deploymentInfoProvider.IsExternalUpdateMechanism)
            {
                _logger.ProgressDebug("Built-In updater disabled, please use {0} to install", _deploymentInfoProvider.PackageUpdateMechanism);
                return(null);
            }
            else if (_configFileProvider.UpdateMechanism != UpdateMechanism.Script && _deploymentInfoProvider.IsExternalUpdateMechanism)
            {
                _logger.ProgressDebug("Update available, please use {0} to install", _deploymentInfoProvider.PackageUpdateMechanism);
                return(null);
            }

            return(latestAvailable);
        }
Exemple #5
0
 public override void Execute(CommandTrigger trigger)
 {
     if (trigger is not GameCommandTrigger)
     {
         Logger.Error("This command can only be executed in game.");
         return;
     }
     Execute(trigger as GameCommandTrigger);
 }
Exemple #6
0
        internal static async Task <ICommandResult> GetCommandResultAsync(this IDurableClient durableClient, ICommand command)
        {
            if (durableClient is null)
            {
                throw new ArgumentNullException(nameof(durableClient));
            }

            if (command is null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            var commandStatus = await durableClient
                                .GetStatusAsync(CommandTrigger.GetCommandOrchestrationInstanceId(command))
                                .ConfigureAwait(false);

            if (commandStatus is null)
            {
                // the command orchestration wasn't created yet
                // there is no way to return a command result

                return(null);
            }
            else if (commandStatus.RuntimeStatus.IsFinal())
            {
                // the command orchestration reached a final state
                // but the message orchestration is responsible to
                // send the result and there could modify the overall
                // command result (e.g. if a send operation fails).

                var commandMessageStatus = await durableClient
                                           .GetStatusAsync(CommandTrigger.GetCommandWrapperOrchestrationInstanceId(command))
                                           .ConfigureAwait(false);

                if (commandMessageStatus?.Output.HasValues ?? false)
                {
                    return(commandMessageStatus.Output
                           .ToObject <ICommandResult>()
                           .ApplyStatus(commandMessageStatus));
                }
            }

            // the command orchestration is in-flight
            // get the current command result from its
            // output or fallback to the default result

            var commandResult = commandStatus.Output.HasValues
                ? commandStatus.Output.ToObject <ICommandResult>()
                : command.CreateResult(); // fallback to the default command result

            return(commandResult.ApplyStatus(commandStatus));
        }
Exemple #7
0
        public Command ToCommand(string id)
        {
            var command = new Command()
            {
                Contexts = Contexts,
                Id       = id
            };

            Trigger trigger = null;

            switch (MatcherType)
            {
            case CommandMatcherType.Command:
                trigger = new CommandTrigger()
                {
                    Name = MatcherString
                };
                break;

            case CommandMatcherType.Regex:
                // find flags at the end of expr like: "test/i"
                // but not like "test\/slash"
                var matches = Regex.Matches(MatcherString, @"[^\\]\/");

                if (matches.Any())
                {
                    var last_match = matches.Last();
                    var index      = last_match.Index + 2; // since we have a [^\\] + \/ (2 chars)
                    var flags      = MatcherString.Substring(index);
                    var expr       = MatcherString.Substring(0, index - 1);
                    trigger = new RegexTrigger()
                    {
                        Expression = expr, Flags = flags.ToCharArray().Select(c => c.ToString()).ToList()
                    };
                }
                else
                {
                    trigger = new RegexTrigger()
                    {
                        Expression = MatcherString
                    };
                }
                break;
            }

            command.Triggers = new List <Trigger>()
            {
                trigger
            };
            return(command);
        }
Exemple #8
0
        /*
         * [Obsolete]
         * public CommandStub(string name, string description, string helpTag)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  CommandName = name;
         *  Description = description;
         *  HelpTag = helpTag;
         *
         *  Args = new List<string>();
         * }
         *
         * [Obsolete]
         * public CommandStub(string name, string description, CommandTrigger trigger = CommandTrigger.MessageCreate)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  CommandName = name;
         *  Description = description;
         *  Trigger = trigger;
         *
         *  Args = new List<string>();
         * }
         *
         * [Obsolete]
         * public CommandStub(Action<CommandArgs> action)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  Do = action;
         *
         *  Args = new List<string>();
         * }
         *
         * [Obsolete]
         * public CommandStub(string name, string description, Action<CommandArgs> action, CommandTrigger trigger = CommandTrigger.MessageCreate)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  Do = action;
         *  CommandName = name;
         *  Description = description;
         *  Trigger = trigger;
         *
         *  Args = new List<string>();
         * }
         *
         * [Obsolete]
         * public CommandStub(string name, string description, string helpTag, Action<CommandArgs> action, CommandTrigger trigger = CommandTrigger.MessageCreate)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  Do = action;
         *  CommandName = name;
         *  Description = description;
         *  HelpTag = helpTag;
         *  Trigger = trigger;
         *
         *  Args = new List<string>();
         * }
         *
         * [Obsolete]
         * public CommandStub(string name, string description, string helpTag, PermissionType minPerm, Action<CommandArgs> action, CommandTrigger trigger = CommandTrigger.MessageCreate)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  Do = action;
         *  CommandName = name;
         *  Description = description;
         *  HelpTag = helpTag;
         *  MinimumPermission = minPerm;
         *  Trigger = trigger;
         *
         *  Args = new List<string>();
         * }
         *
         * [Obsolete]
         * public CommandStub(string name, string description, string helpTag, PermissionType minPerm, int argCount, Action<CommandArgs> action, CommandTrigger trigger = CommandTrigger.MessageCreate)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  Do = action;
         *  CommandName = name;
         *  Description = description;
         *  HelpTag = helpTag;
         *  MinimumPermission = minPerm;
         *  ArgCount = argCount;
         *  Trigger = trigger;
         *
         *  Args = new List<string>();
         * }
         *
         * [Obsolete]
         * public CommandStub(string name, string description, string helpTag, PermissionType minPerm, int argCount, Action<CommandArgs> action)
         * {
         *  this.ID = IDGenerator.GenerateRandomCode();
         *
         *  Do = action;
         *  CommandName = name;
         *  Description = description;
         *  HelpTag = helpTag;
         *  MinimumPermission = minPerm;
         *  ArgCount = argCount;
         *
         *  Args = new List<string>();
         * }
         */

        public CommandStub(string name, string description, string helpTag, Action <CommandArgs> action, PermissionType minPerm = PermissionType.User,
                           int argCount = 0, CommandTrigger trigger = CommandTrigger.MessageCreate)
        {
            ID = IDGenerator.GenerateRandomCode();

            Do          = action;
            CommandName = name;
            Description = description;
            HelpTag     = helpTag;

            MinimumPermission = minPerm;
            ArgCount          = argCount;
            Trigger           = trigger;
            Args = new List <string>();
        }
            /// <summary> Parses the command and spawns the corresponding process.</summary>
            /// <param name="cmd">Command with the command name and its arguments</param>
            /// <param name="trigger">What triggered the command, for some limited access control</param>
            /// <param name="onDone">Callback the process will call on termination</param>
            /// <param name="spawner">The spawner (typically a <see cref="Process"/>) used to spawn the process. If null, <see cref="CommandLine.spawner"/> will be used.</param>
            /// <returns>The spawned <see cref="Process"/>. Can be null if it failed or was executed immediately.</returns>
            public Process StartCmd(string cmd, CommandTrigger trigger, Action <Process> onDone = null, IProcessSpawner spawner = null)
            {
                MyTuple <string, List <string> > parsed = this.ParseCommand(cmd);

                if (parsed.Item1 != "")
                {
                    Command command;
                    if (this.commands.TryGetValue(parsed.Item1, out command))
                    {
                        return(command.Spawn(parsed.Item2, this.log, onDone, spawner ?? this.spawner, trigger));
                    }
                    else
                    {
                        this.log($"Unknown command {parsed.Item1}");
                    }
                }
                return(null);
            }
        private void Rescan(List <Artist> artists, bool isNew, CommandTrigger trigger, bool infoUpdated)
        {
            var rescanAfterRefresh = _configService.RescanAfterRefresh;
            var shouldRescan       = true;
            var filter             = FilterFilesType.Matched;
            var folders            = _rootFolderService.All().Select(x => x.Path).ToList();

            if (isNew)
            {
                _logger.Trace("Forcing rescan. Reason: New artist added");
                shouldRescan = true;

                // only rescan artist folders - otherwise it can be super slow for
                // badly organized / partly matched libraries
                folders = artists.Select(x => x.Path).ToList();
            }
            else if (rescanAfterRefresh == RescanAfterRefreshType.Never)
            {
                _logger.Trace("Skipping rescan. Reason: never rescan after refresh");
                shouldRescan = false;
            }
            else if (rescanAfterRefresh == RescanAfterRefreshType.AfterManual && trigger != CommandTrigger.Manual)
            {
                _logger.Trace("Skipping rescan. Reason: not after automatic refreshes");
                shouldRescan = false;
            }
            else if (!infoUpdated && trigger != CommandTrigger.Manual)
            {
                _logger.Trace("Skipping rescan. Reason: no metadata updated after automatic refresh");
                shouldRescan = false;
            }
            else if (!infoUpdated)
            {
                _logger.Trace("No metadata updated, only scanning new files");
                filter = FilterFilesType.Known;
            }

            if (shouldRescan)
            {
                // some metadata has updated so rescan unmatched
                // (but don't add new artists to reduce repeated searches against api)
                _commandQueueManager.Push(new RescanFoldersCommand(folders, filter, false, artists.Select(x => x.Id).ToList()));
            }
        }
        private void RefreshSelectedArtists(List <int> artistIds, bool isNew, CommandTrigger trigger)
        {
            bool updated = false;
            var  artists = _artistService.GetArtists(artistIds);

            foreach (var artist in artists)
            {
                try
                {
                    updated |= RefreshEntityInfo(artist, null, true, false, null);
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Couldn't refresh info for {0}", artist);
                }
            }

            Rescan(artists, isNew, trigger, updated);
        }
Exemple #12
0
 /// <summary>Creates a new command ready to be registered in a <see cref="CommandLine"/>.</summary>
 /// <param name="name">Unique name of the command, used summon the command.</param>
 /// <param name="actionProvider">Function that returns the </param>
 /// <param name="briefHelp"></param>
 /// <param name="detailedHelp"></param>
 /// <param name="maxArgs">Ignored if <paramref name="nArgs"/> is given</param>
 /// <param name="minArgs">Ignored if <paramref name="nArgs"/> is given</param>
 /// <param name="nArgs">Number of argguments required by the command</param>
 /// <param name="requiredTrigger"></param>
 public Command(string name, ActionProvider actionProvider, string briefHelp, string detailedHelp = null, int maxArgs = int.MaxValue, int minArgs = 0, int nArgs = -1, CommandTrigger requiredTrigger = CommandTrigger.User)
 {
     this.Name      = name;
     this.provider  = actionProvider;
     this.BriefHelp = briefHelp;
     if (detailedHelp != null)
     {
         this.help = detailedHelp.Split(new char[] { '\n' }).ToList();
     }
     if (nArgs >= 0)
     {
         this.MaxArgs = this.MinArgs = nArgs;
     }
     else
     {
         this.MaxArgs = maxArgs;
         this.MinArgs = minArgs;
     }
     this.RequiredTrigger = requiredTrigger;
 }
Exemple #13
0
        private void RefreshSelectedAuthors(List <int> authorIds, bool isNew, CommandTrigger trigger)
        {
            var updated = false;
            var authors = _authorService.GetAuthors(authorIds);

            foreach (var author in authors)
            {
                try
                {
                    var data = GetSkyhookData(author.ForeignAuthorId);
                    updated |= RefreshEntityInfo(author, null, data, true, false, null);
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Couldn't refresh info for {0}", author);
                }
            }

            Rescan(authorIds, isNew, trigger, updated);
        }
        public bool HandleCommand(CommandTrigger trigger)
        {
            if (trigger == null)
            {
                Logger.Warn("No CommandTrigger were pass.");
                return(false);
            }

            if (!CommandsByAlias.TryGetValue(trigger.Args[0], out CommandBase command))
            {
                return(false);
            }

            if (!trigger.DefinedParametersCommand(command))
            {
                Logger.Info("No Parameters to defined in this command.");
                return(false);
            }
            command.Execute(trigger);
            return(true);
        }
Exemple #15
0
        private void RescanArtist(Artist artist, bool isNew, CommandTrigger trigger, bool infoUpdated)
        {
            var rescanAfterRefresh = _configService.RescanAfterRefresh;
            var shouldRescan       = true;

            if (isNew)
            {
                _logger.Trace("Forcing rescan of {0}. Reason: New artist", artist);
                shouldRescan = true;
            }

            else if (rescanAfterRefresh == RescanAfterRefreshType.Never)
            {
                _logger.Trace("Skipping rescan of {0}. Reason: never recan after refresh", artist);
                shouldRescan = false;
            }

            else if (rescanAfterRefresh == RescanAfterRefreshType.AfterManual && trigger != CommandTrigger.Manual)
            {
                _logger.Trace("Skipping rescan of {0}. Reason: not after automatic scans", artist);
                shouldRescan = false;
            }

            if (!shouldRescan)
            {
                return;
            }

            try
            {
                // If some metadata has been updated then rescan unmatched files.
                // Otherwise only scan files that haven't been seen before.
                var filter = infoUpdated ? FilterFilesType.Matched : FilterFilesType.Known;
                _diskScanService.Scan(artist, filter);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Couldn't rescan artist {0}", artist);
            }
        }
        public CommandModel Push <TCommand>(TCommand command, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified)
            where TCommand : Command
        {
            Ensure.That(command, () => command).IsNotNull();

            _logger.Trace("Publishing {0}", command.Name);
            _logger.Trace("Checking if command is queued or started: {0}", command.Name);

            var existingCommands = QueuedOrStarted(command.Name);
            var existing         = existingCommands.SingleOrDefault(c => CommandEqualityComparer.Instance.Equals(c.Body, command));

            if (existing != null)
            {
                _logger.Trace("Command is already in progress: {0}", command.Name);

                return(existing);
            }

            var commandModel = new CommandModel
            {
                Name     = command.Name,
                Body     = command,
                QueuedAt = DateTime.UtcNow,
                Trigger  = trigger,
                Priority = priority,
                Status   = CommandStatus.Queued
            };

            _logger.Trace("Inserting new command: {0}", commandModel.Name);

            _repo.Insert(commandModel);
            _commandQueue.Add(commandModel);

            return(commandModel);
        }
        public CommandModel Push(string commandName, DateTime?lastExecutionTime, DateTime?lastStartTime, CommandPriority priority = CommandPriority.Normal, CommandTrigger trigger = CommandTrigger.Unspecified)
        {
            dynamic command = GetCommand(commandName);

            command.LastExecutionTime = lastExecutionTime;
            command.LastStartTime     = lastStartTime;
            command.Trigger           = trigger;

            return(Push(command, priority, trigger));
        }
Exemple #18
0
 /// <summary>Spawns a new <see cref="Process"/>, taking into account the arguments. Can fail and return null if the arguments are incorrect.</summary>
 /// <param name="args">The arguments given to the command line.</param>
 /// <param name="logger">The logger the process can use to log.</param>
 /// <param name="onDone">The callback to call on process termination.</param>
 /// <param name="spawner">Used to spawn the process</param>
 /// <param name="trigger">What triggered the command</param>
 /// <returns>The spawned process, if successful.</returns>
 public Process Spawn(List <string> args, Action <string> logger, Action <Process> onDone, IProcessSpawner spawner, CommandTrigger trigger)
 {
     if (trigger < this.RequiredTrigger)
     {
         logger?.Invoke($"Permission denied for '{this.Name}'");
     }
     else if (args.Count <= this.MaxArgs && args.Count >= this.MinArgs)
     {
         MyTuple <int, bool, Action <Process> > parameters = this.provider(args, logger);
         return(spawner.Spawn(parameters.Item3, this.Name, onDone, parameters.Item1, parameters.Item2));
     }
     else
     {
         logger?.Invoke($"Wrong number of arguments for '{this.Name}'");
         logger?.Invoke($"Run -help '{this.Name}' for more info");
     }
     return(null);
 }
        public ProjectViewModel(ILifetimeScope lifetimeScope, Dispatcher dispatcher, LocLocalizer localizer, ProjectFileWorkspace workspace)
            : base(lifetimeScope, dispatcher)
        {
            #region Init

            var loadTrigger = new CommandTrigger();

            Receive <IncommingEvent>(e => e.Action());

            IsEnabled = RegisterProperty <bool>(nameof(IsEnabled)).WithDefaultValue(!workspace.ProjectFile.IsEmpty);

            ProjectEntrys = this.RegisterUiCollection <ProjectEntryModel>(nameof(ProjectEntrys))
                            .AndAsync();
            SelectedIndex = RegisterProperty <int>(nameof(SelectedIndex));

            var self = Context.Self;

            void TryUpdateEntry((string ProjectName, string EntryName, ActiveLanguage Lang, string Content) data)
            {
                var(projectName, entryName, lang, content) = data;
                self.Tell(new UpdateRequest(entryName, lang, content, projectName));
            }

            void TryRemoveEntry((string ProjectName, string EntryName) data)
            {
                var(projectName, entryName) = data;
                self.Tell(new RemoveRequest(entryName, projectName));
            }

            OnPreRestart += (exception, o) => Self.Tell(new InitProjectViewModel(workspace.Get(_project)));

            void InitProjectViewModel(InitProjectViewModel obj)
            {
                _project = obj.Project.ProjectName;

                Languages !.Add(new ProjectViewLanguageModel(localizer.ProjectViewLanguageBoxFirstLabel, true));
                Languages.AddRange(obj.Project.ActiveLanguages.Select(al => new ProjectViewLanguageModel(al.Name, false)));
                SelectedIndex += 0;

                foreach (var projectEntry in obj.Project.Entries.OrderBy(le => le.Key))
                {
                    ProjectEntrys.Add(new ProjectEntryModel(obj.Project, projectEntry, TryUpdateEntry, TryRemoveEntry));
                }

                ImportetProjects !.AddRange(obj.Project.Imports);
                loadTrigger.Trigger();
            }

            Receive <InitProjectViewModel>(InitProjectViewModel);

            #endregion

            #region New Entry

            IEnumerable <NewEntryInfoBase> GetEntrys()
            {
                var list = ImportetProjects.ToList();

                list.Add(_project);

                var allEntrys = list.SelectMany(pro => workspace.Get(pro).Entries.Select(e => e.Key)).ToArray();

                return(allEntrys.Select(e => new NewEntryInfo(e)).OfType <NewEntryInfoBase>()
                       .Concat(allEntrys
                               .Select(s => s.Split('_', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault())
                               .Where(s => !string.IsNullOrWhiteSpace(s))
                               .Distinct(StringComparer.Ordinal)
                               .Select(s => new NewEntrySuggestInfo(s !))));
            }

            void AddEntry(EntryAdd entry)
            {
                if (_project != entry.Entry.Project)
                {
                    return;
                }

                ProjectEntrys.Add(new ProjectEntryModel(workspace.Get(_project), entry.Entry, TryUpdateEntry, TryRemoveEntry));
            }

            NewCommad
            .ThenFlow(this.ShowDialog <INewEntryDialog, NewEntryDialogResult?, IEnumerable <NewEntryInfoBase> >(GetEntrys),
                      b =>
            {
                b.Mutate(workspace.Entrys).With(em => em.EntryAdd, em => res => em.NewEntry(_project, res !.Name)).ToSelf()
                .Then(b2 => b2.Action(AddEntry));
            })
Exemple #20
0
 public abstract void Execute(CommandTrigger trigger);