Beispiel #1
0
 private static void Setup(string[] args)
 {
     // Build dependency container
     DependencyBuilder.Build().BeginLifetimeScope();
     DependencyBuilder.Container.Resolve <ISettingsBuilder>().BuildSettings(args);
     Logger = DependencyBuilder.Container.Resolve <ILogger>();
     Logger.Log("Built dependencies", LogEventLevel.Information);
 }
Beispiel #2
0
        private E <string> Run(ParameterData setup)
        {
            var configResult = ConfRoot.OpenOrCreate(configFilePath);

            if (!configResult.Ok)
            {
                return("Could not create config");
            }
            ConfRoot config = configResult.Value;

            Config.Deprecated.UpgradeScript.CheckAndUpgrade(config);
            ConfigUpgrade2.Upgrade(config.Configs.BotsPath.Value);
            config.Save();

            var builder = new DependencyBuilder(injector);

            builder.AddModule(this);
            builder.AddModule(config);
            builder.AddModule(injector);
            builder.AddModule(config.Db);
            builder.RequestModule <SystemMonitor>();
            builder.RequestModule <DbStore>();
            builder.AddModule(config.Plugins);
            builder.RequestModule <PluginManager>();
            builder.AddModule(config.Web);
            builder.AddModule(config.Web.Interface);
            builder.AddModule(config.Web.Api);
            builder.RequestModule <WebServer>();
            builder.AddModule(config.Rights);
            builder.RequestModule <RightsManager>();
            builder.RequestModule <BotManager>();
            builder.RequestModule <TokenManager>();
            builder.RequestModule <CommandManager>();
            builder.AddModule(config.Factories);
            builder.RequestModule <SpotifyApi>();
            builder.RequestModule <ResourceResolver>();
            builder.RequestModule <Stats>();
            builder.AddModule(config.Tools.Librespot);

            if (!builder.Build())
            {
                Log.Error("Missing core module dependency");
                return("Could not load all core modules");
            }

            YoutubeDlHelper.DataObj = config.Tools.YoutubeDl;

            builder.GetModule <SystemMonitor>().StartTimedSnapshots();
            builder.GetModule <CommandManager>().RegisterCollection(MainCommands.Bag);
            builder.GetModule <RightsManager>().CreateConfigIfNotExists(setup.Interactive);
            builder.GetModule <BotManager>().RunBots(setup.Interactive);
            builder.GetModule <WebServer>().StartWebServer();
            builder.GetModule <Stats>().StartTimer(setup.SendStats);

            return(R.Ok);
        }
Beispiel #3
0
        public async Task Run(ParameterData setup)
        {
            scheduler.VerifyOwnThread();

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
            TaskScheduler.UnobservedTaskException      += UnobservedTaskExceptionHandler;
            Console.CancelKeyPress += ConsoleInterruptHandler;

            var config = ConfRoot.OpenOrCreate(configFilePath);

            if (config is null)
            {
                throw new Exception("Could not create config");
            }
            ConfigUpgrade2.Upgrade(config.Configs.BotsPath.Value);
            config.Save();

            var builder = new DependencyBuilder(injector);

            injector.AddModule(this);
            injector.AddModule(scheduler);
            injector.AddModule(injector);
            injector.AddModule(config);
            injector.AddModule(config.Db);
            injector.AddModule(config.Plugins);
            injector.AddModule(config.Web);
            injector.AddModule(config.Web.Interface);
            injector.AddModule(config.Web.Api);
            injector.AddModule(config.Rights);
            injector.AddModule(config.Factories);
            builder.RequestModule <SystemMonitor>();
            builder.RequestModule <DbStore>();
            builder.RequestModule <PluginManager>();
            builder.RequestModule <WebServer>();
            builder.RequestModule <RightsManager>();
            builder.RequestModule <BotManager>();
            builder.RequestModule <TokenManager>();
            builder.RequestModule <CommandManager>();
            builder.RequestModule <ResourceResolver>();
            builder.RequestModule <Stats>();

            if (!builder.Build())
            {
                throw new Exception("Could not load all core modules");
            }

            Upgrader.PerformUpgrades(injector);
            YoutubeDlHelper.DataObj = config.Tools.YoutubeDl;

            injector.GetModuleOrThrow <CommandManager>().RegisterCollection(MainCommands.Bag);
            injector.GetModuleOrThrow <RightsManager>().CreateConfigIfNotExists(setup.Interactive);
            injector.GetModuleOrThrow <WebServer>().StartWebServer();
            injector.GetModuleOrThrow <Stats>().StartTimer(setup.SendStats);
            await injector.GetModuleOrThrow <BotManager>().RunBots(setup.Interactive);
        }
Beispiel #4
0
        private E <string> Run(bool interactive = false)
        {
            var configResult = ConfRoot.OpenOrCreate(configFilePath);

            if (!configResult.Ok)
            {
                return("Could not create config");
            }
            ConfRoot config = configResult.Value;

            Config.Deprecated.UpgradeScript.CheckAndUpgrade(config);
            ConfigUpgrade2.Upgrade(config.Configs.BotsPath.Value);
            config.Save();

            var builder = new DependencyBuilder(injector);

            builder.AddModule(this);
            builder.AddModule(config);
            builder.AddModule(injector);
            builder.AddModule(config.Db);
            builder.RequestModule <SystemMonitor>();
            builder.RequestModule <DbStore>();
            builder.AddModule(config.Plugins);
            builder.RequestModule <PluginManager>();
            builder.AddModule(config.Web);
            builder.AddModule(config.Web.Interface);
            builder.AddModule(config.Web.Api);
            builder.RequestModule <WebServer>();
            builder.AddModule(config.Rights);
            builder.RequestModule <RightsManager>();
            builder.RequestModule <BotManager>();
            builder.RequestModule <TokenManager>();
            builder.RequestModule <CommandManager>();
            builder.AddModule(config.Factories);
            // TODO fix interaction: rfm needs to be in the same injector as the commandsystem, otherwise duplicate error
            // Also TODO find solution to move commandsystem to bot, without breaking api
            builder.RequestModule <ResourceFactory>();

            if (!builder.Build())
            {
                Log.Error("Missing core module dependency");
                return("Could not load all core modules");
            }

            YoutubeDlHelper.DataObj = config.Tools.YoutubeDl;

            builder.GetModule <SystemMonitor>().StartTimedSnapshots();
            builder.GetModule <CommandManager>().RegisterCollection(MainCommands.Bag);
            builder.GetModule <RightsManager>().CreateConfigIfNotExists(interactive);
            builder.GetModule <BotManager>().RunBots(interactive);
            builder.GetModule <WebServer>().StartWebServer();

            return(R.Ok);
        }
Beispiel #5
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            var container = DependencyBuilder.Build();

            GlobalConfiguration.Configuration.Formatters.Clear();

            var jsonFormatter = new JsonMediaTypeFormatter();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            GlobalConfiguration.Configuration.Formatters.Add(jsonFormatter);

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
Beispiel #6
0
        public E <string> InitializeBot()
        {
            Log.Info("Bot \"{0}\" connecting to \"{1}\"", config.Name, config.Connect.Address);

            // Registering config changes
            config.Language.Changed += (s, e) =>
            {
                var langResult = LocalizationManager.LoadLanguage(e.NewValue, true);
                if (!langResult.Ok)
                {
                    Log.Error("Failed to load language file ({0})", langResult.Error);
                }
            };
            config.Events.IdleDelay.Changed += (s, e) => EnableIdleTickWorker();
            config.Events.OnIdle.Changed    += (s, e) => EnableIdleTickWorker();

            var builder = new DependencyBuilder(Injector);

            builder.AddModule(this);
            builder.AddModule(config);
            builder.AddModule(Injector);
            builder.AddModule(config.Playlists);
            builder.RequestModule <PlaylistIO>();
            builder.RequestModule <PlaylistManager>();
            builder.AddModule(Id);
            builder.AddModule(new TsFullClient());
            builder.RequestModule <TsBaseFunctions, TsFullClient>();
            builder.RequestModule <Ts3Client>();
            builder.RequestModule <Player>();
            builder.RequestModule <CustomTargetPipe>();
            builder.RequestModule <IVoiceTarget, CustomTargetPipe>();
            builder.RequestModule <SessionManager>();
            builder.RequestModule <ResolveContext>();
            if (!builder.TryCreate <CommandManager>(out var commandManager))
            {
                return("Failed to create commandManager");
            }
            builder.AddModule(commandManager);
            if (config.History.Enabled)
            {
                builder.AddModule(config.History);
                builder.RequestModule <HistoryManager>();
            }
            builder.RequestModule <PlayManager>();

            if (!builder.Build())
            {
                Log.Error("Missing bot module dependency");
                return("Could not load all bot modules");
            }

            {
                var io             = Injector.GetModule <PlaylistIO>();
                var resourceSearch = new ResourceSearch(io);
                Injector.AddModule(resourceSearch);
                var playlistManager = Injector.GetModule <PlaylistManager>();
                playlistManager.ResourceSearch = resourceSearch;
            }

            resourceResolver = Injector.GetModule <ResolveContext>();
            ts3FullClient    = Injector.GetModule <TsFullClient>();
            ts3client        = Injector.GetModule <Ts3Client>();
            player           = Injector.GetModule <Player>();
            player.SetTarget(Injector.GetModule <CustomTargetPipe>());
            Injector.AddModule(ts3FullClient.Book);

            playManager    = Injector.GetModule <PlayManager>();
            targetManager  = Injector.GetModule <IVoiceTarget>();
            sessionManager = Injector.GetModule <SessionManager>();
            stats          = Injector.GetModule <Stats>();

            player.OnSongEnd     += playManager.SongEndedEvent;
            player.OnSongUpdated += (s, e) => playManager.Update(e);
            // Update idle status events
            playManager.BeforeResourceStarted += (s, e) => DisableIdleTickWorker();
            playManager.PlaybackStopped       += (s, e) => EnableIdleTickWorker();
            // Used for the voice_mode script
            playManager.BeforeResourceStarted += BeforeResourceStarted;
            // Update the own status text to the current song title
            playManager.AfterResourceStarted += LoggedUpdateBotStatus;
            playManager.PlaybackStopped      += LoggedUpdateBotStatus;
            playManager.OnResourceUpdated    += LoggedUpdateBotStatus;
            // Log our resource in the history
            if (Injector.TryGet <HistoryManager>(out var historyManager))
            {
                playManager.AfterResourceStarted += (s, e) => historyManager.LogAudioResource(new HistorySaveData(e.PlayResource.BaseData, e.MetaData.ResourceOwnerUid ?? Uid.Null));
            }
            // Update our thumbnail
            playManager.AfterResourceStarted += GenerateStatusImage;
            playManager.PlaybackStopped      += GenerateStatusImage;
            // Stats
            playManager.AfterResourceStarted += (s, e) => stats.TrackSongStart(Id, e.ResourceData.AudioType);
            playManager.ResourceStopped      += (s, e) => stats.TrackSongStop(Id);
            // Register callback for all messages happening
            ts3client.OnMessageReceived += OnMessageReceived;
            // Register callback to remove open private sessions, when user disconnects
            ts3FullClient.OnEachClientLeftView += OnClientLeftView;
            ts3client.OnBotConnected           += OnBotConnected;
            ts3client.OnBotDisconnect          += OnBotDisconnect;
            // Alone mode
            ts3client.OnAloneChanged += OnAloneChanged;
            // Whisper stall
            ts3client.OnWhisperNoTarget += (s, e) => player.SetStall();

            commandManager.RegisterCollection(MainCommands.Bag);
            // TODO remove after plugin rework
            var pluginManager = Injector.GetModule <PluginManager>();

            foreach (var plugin in pluginManager.Plugins)
            {
                if (plugin.Type == PluginType.CorePlugin || plugin.Type == PluginType.Commands)
                {
                    commandManager.RegisterCollection(plugin.CorePlugin.Bag);
                }
            }
            // Restore all alias from the config
            foreach (var alias in config.Commands.Alias.GetAllItems())
            {
                commandManager.RegisterAlias(alias.Key, alias.Value).UnwrapToLog(Log);
            }

            // Connect after everyting is set up
            return(ts3client.Connect());
        }
Beispiel #7
0
        public E <string> InitializeBot()
        {
            Log.Info("Bot \"{0}\" connecting to \"{1}\"", config.Name, config.Connect.Address);

            // Registering config changes
            config.Language.Changed += (s, e) =>
            {
                var langResult = LocalizationManager.LoadLanguage(e.NewValue, true);
                if (!langResult.Ok)
                {
                    Log.Error("Failed to load language file ({0})", langResult.Error);
                }
            };
            config.Events.IdleTime.Changed += (s, e) => EnableIdleTickWorker();
            config.Events.OnIdle.Changed   += (s, e) => EnableIdleTickWorker();

            var builder = new DependencyBuilder(Injector);

            builder.AddModule(this);
            builder.AddModule(config);
            builder.AddModule(Injector);
            builder.AddModule(config.Playlists);
            builder.RequestModule <PlaylistIO>();
            builder.RequestModule <PlaylistManager>();
            builder.AddModule(Id);
            builder.AddModule(new Ts3FullClient());
            builder.RequestModule <Ts3BaseFunctions, Ts3FullClient>();
            builder.RequestModule <Ts3Client>();
            builder.RequestModule <IPlayerConnection, Ts3Client>();
            builder.RequestModule <SessionManager>();
            if (config.History.Enabled)
            {
                builder.AddModule(config.History);
                builder.RequestModule <HistoryManager>();
            }
            builder.RequestModule <PlayManager>();

            if (!builder.Build())
            {
                Log.Error("Missing bot module dependency");
                return("Could not load all bot modules");
            }

            tsFullClient     = Injector.GetModule <Ts3FullClient>();
            clientConnection = Injector.GetModule <Ts3Client>();
            playerConnection = clientConnection;
            Injector.AddModule <IVoiceTarget>(clientConnection.TargetPipe);
            Injector.AddModule(tsFullClient.Book);

            playManager    = Injector.GetModule <PlayManager>();
            targetManager  = Injector.GetModule <IVoiceTarget>();
            sessionManager = Injector.GetModule <SessionManager>();

            playerConnection.OnSongEnd     += playManager.SongStoppedEvent;
            playerConnection.OnSongUpdated += (s, e) => playManager.Update(e);
            // Update idle status events
            playManager.BeforeResourceStarted += (s, e) => DisableIdleTickWorker();
            playManager.AfterResourceStopped  += (s, e) => EnableIdleTickWorker();
            // Used for the voice_mode script
            playManager.BeforeResourceStarted += BeforeResourceStarted;
            // Update the own status text to the current song title
            playManager.AfterResourceStarted += LoggedUpdateBotStatus;
            playManager.AfterResourceStopped += LoggedUpdateBotStatus;
            playManager.OnResourceUpdated    += LoggedUpdateBotStatus;
            // Log our resource in the history
            if (Injector.TryGet <HistoryManager>(out var historyManager))
            {
                playManager.AfterResourceStarted += (s, e) => historyManager.LogAudioResource(new HistorySaveData(e.PlayResource.BaseData, e.Invoker.ClientUid));
            }
            // Update our thumbnail
            playManager.AfterResourceStarted += GenerateStatusImage;
            playManager.AfterResourceStopped += GenerateStatusImage;
            // Register callback for all messages happening
            clientConnection.OnMessageReceived += OnMessageReceived;
            // Register callback to remove open private sessions, when user disconnects
            tsFullClient.OnEachClientLeftView += OnClientLeftView;
            clientConnection.OnBotConnected   += OnBotConnected;
            clientConnection.OnBotDisconnect  += OnBotDisconnect;

            // Restore all alias from the config
            foreach (var alias in config.Commands.Alias.GetAllItems())
            {
                commandManager.RegisterAlias(alias.Key, alias.Value).UnwrapToLog(Log);
            }

            // Connect the query after everyting is set up
            return(clientConnection.Connect());
        }
Beispiel #8
0
        public Bot(Id id, ConfBot config, BotInjector injector)
        {
            this.Id       = id;
            this.config   = config;
            this.Injector = injector;

            // Registering config changes
            config.Language.Changed += async(s, e) =>
            {
                var langResult = await localization.LoadLanguage(e.NewValue, true);

                if (!langResult.Ok)
                {
                    Log.Error("Failed to load language file ({0})", langResult.Error);
                }
            };
            config.Events.IdleDelay.Changed += (s, e) => EnableIdleTickWorker();
            config.Events.OnIdle.Changed    += (s, e) => EnableIdleTickWorker();

            var builder = new DependencyBuilder(Injector);

            Injector.HideParentModule <CommandManager>();
            Injector.HideParentModule <DedicatedTaskScheduler>();
            Injector.AddModule(this);
            Injector.AddModule(config);
            Injector.AddModule(Injector);
            Injector.AddModule(config.Playlists);
            Injector.AddModule(config.History);
            Injector.AddModule(Id);
            builder.RequestModule <PlaylistIO>();
            builder.RequestModule <PlaylistManager>();
            builder.RequestModule <DedicatedTaskScheduler>();
            builder.RequestModule <TsFullClient>();
            builder.RequestModule <TsBaseFunctions, TsFullClient>();
            builder.RequestModule <Ts3Client>();
            builder.RequestModule <Player>();
            builder.RequestModule <CustomTargetPipe>();
            builder.RequestModule <IVoiceTarget, CustomTargetPipe>();
            builder.RequestModule <SessionManager>();
            builder.RequestModule <ResolveContext>();
            builder.RequestModule <CommandManager>();
            builder.RequestModule <LocalizationManager>();
            if (config.History.Enabled)
            {
                builder.RequestModule <HistoryManager>();
            }
            builder.RequestModule <PlayManager>();

            if (!builder.Build())
            {
                Log.Error("Missing bot module dependency");
                throw new Exception("Could not load all bot modules");
            }
            Injector.ClearHiddenParentModules();

            resourceResolver = Injector.GetModuleOrThrow <ResolveContext>();
            ts3FullClient    = Injector.GetModuleOrThrow <TsFullClient>();
            ts3client        = Injector.GetModuleOrThrow <Ts3Client>();
            player           = Injector.GetModuleOrThrow <Player>();
            Scheduler        = Injector.GetModuleOrThrow <DedicatedTaskScheduler>();
            var customTarget = Injector.GetModuleOrThrow <CustomTargetPipe>();

            player.SetTarget(customTarget);
            Injector.AddModule(ts3FullClient.Book);
            playManager    = Injector.GetModuleOrThrow <PlayManager>();
            targetManager  = Injector.GetModuleOrThrow <IVoiceTarget>();
            sessionManager = Injector.GetModuleOrThrow <SessionManager>();
            stats          = Injector.GetModuleOrThrow <Stats>();
            var commandManager = Injector.GetModuleOrThrow <CommandManager>();

            localization = Injector.GetModuleOrThrow <LocalizationManager>();

            idleTickWorker = Scheduler.Invoke(() => Scheduler.CreateTimer(OnIdle, TimeSpan.MaxValue, false)).Result;

            player.OnSongEnd     += playManager.SongStoppedEvent;
            player.OnSongUpdated += (s, e) => playManager.Update(e);
            // Update idle status events
            playManager.BeforeResourceStarted += (s, e) => { DisableIdleTickWorker(); return(Task.CompletedTask); };
            playManager.PlaybackStopped       += (s, e) => { EnableIdleTickWorker(); return(Task.CompletedTask); };
            // Used for custom scripts, like voice_mode, onsongstart
            playManager.BeforeResourceStarted += BeforeResourceStarted;
            playManager.AfterResourceStarted  += AfterResourceStarted;
            // Update the own status text to the current song title
            playManager.AfterResourceStarted += (s, e) => UpdateBotStatus();
            playManager.PlaybackStopped      += (s, e) => UpdateBotStatus();
            playManager.OnResourceUpdated    += (s, e) => UpdateBotStatus();
            // Log our resource in the history
            if (Injector.TryGet <HistoryManager>(out var historyManager))
            {
                playManager.AfterResourceStarted += (s, e) =>
                {
                    if (e.PlayInfo != null)
                    {
                        historyManager.LogAudioResource(new HistorySaveData(e.PlayResource.AudioResource, e.PlayInfo.ResourceOwnerUid));
                    }
                    return(Task.CompletedTask);
                }
            }
            ;
            // Update our thumbnail
            playManager.AfterResourceStarted += (s, e) => GenerateStatusImage(true, e);
            playManager.PlaybackStopped      += (s, e) => GenerateStatusImage(false, null);
            // Stats
            playManager.AfterResourceStarted += (s, e) => { stats.TrackSongStart(Id, e.ResourceData.AudioType); return(Task.CompletedTask); };
            playManager.ResourceStopped      += (s, e) => { stats.TrackSongStop(Id); return(Task.CompletedTask); };
            // Register callback for all messages happening
            ts3client.OnMessageReceived += OnMessageReceived;
            // Register callback to remove open private sessions, when user disconnects
            ts3FullClient.OnEachClientLeftView += OnClientLeftView;
            ts3client.OnBotConnected           += OnBotConnected;
            ts3client.OnBotDisconnected        += OnBotDisconnected;
            ts3client.OnBotStoppedReconnecting += OnBotStoppedReconnecting;
            // Alone mode
            ts3client.OnAloneChanged += OnAloneChanged;
            ts3client.OnAloneChanged += (s, e) => { customTarget.Alone = e.Alone; return(Task.CompletedTask); };
            // Whisper stall
            ts3client.OnWhisperNoTarget += (s, e) => player.SetStall();

            commandManager.RegisterCollection(MainCommands.Bag);
            // TODO remove after plugin rework
            var pluginManager = Injector.GetModuleOrThrow <PluginManager>();

            foreach (var plugin in pluginManager.Plugins)
            {
                if (plugin.Type == PluginType.CorePlugin || plugin.Type == PluginType.Commands)
                {
                    commandManager.RegisterCollection(plugin.CorePlugin.Bag);
                }
            }
            // Restore all alias from the config
            foreach (var alias in config.Commands.Alias.GetAllItems())
            {
                commandManager.RegisterAlias(alias.Key, alias.Value).UnwrapToLog(Log);
            }
        }