Esempio n. 1
0
        public void Dispose()
        {
            BotManager.RemoveBot(this);

            lock (SyncRoot)
            {
                if (!IsDisposed)
                {
                    IsDisposed = true;
                }
                else
                {
                    return;
                }
                Log.Info("Bot disconnecting.");

                PluginManager.StopPlugins(this);

                PlayManager.Stop();
                PlayManager = null;

                PlayerConnection.Dispose();                 // before: logStream,
                PlayerConnection = null;

                QueryConnection.Dispose();                 // before: logStream,
                QueryConnection = null;
            }
        }
Esempio n. 2
0
        public BobController(BobControllerData data, QueryConnection queryConnection)
        {
            if (queryConnection == null)
            {
                throw new ArgumentNullException(nameof(queryConnection));
            }

            timeout                             = TickPool.RegisterTick(TimeoutCheck, TimeSpan.FromMilliseconds(100), false);
            musicInfoWaiter                     = new WaitEventBlock <MusicData>();
            isRunning                           = false;
            awaitingConnect                     = false;
            this.bobControllerData              = data;
            this.queryConnection                = queryConnection;
            queryConnection.OnMessageReceived  += GetResponse;
            queryConnection.OnClientConnect    += OnBobConnect;
            queryConnection.OnClientDisconnect += OnBobDisconnnect;
            commandQueue                        = new Queue <string>();
            channelSubscriptions                = new Dictionary <int, SubscriptionData>();
        }
Esempio n. 3
0
        private void GenerateStatusImage(object sender, EventArgs e)
        {
            if (!mainBotData.GenerateStatusAvatar)
            {
                return;
            }

            if (e is PlayInfoEventArgs startEvent)
            {
                var thumresult = FactoryManager.GetThumbnail(startEvent.PlayResource);
                if (!thumresult.Ok)
                {
                    return;
                }

                using (var bmp = ImageUtil.BuildStringImage("Now playing: " + startEvent.ResourceData.ResourceTitle, thumresult.Value))
                {
                    using (var mem = new MemoryStream())
                    {
                        bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Jpeg);
                        var result = QueryConnection.UploadAvatar(mem);
                        if (!result.Ok)
                        {
                            Log.Warn("Could not save avatar: {0}", result.Error);
                        }
                    }
                }
            }
            else
            {
                using (var sleepPic = Util.GetEmbeddedFile("TS3AudioBot.Media.SleepingKitty.png"))
                {
                    var result = QueryConnection.UploadAvatar(sleepPic);
                    if (!result.Ok)
                    {
                        Log.Warn("Could not save avatar: {0}", result.Error);
                    }
                }
            }
        }
Esempio n. 4
0
        public R UpdateBotStatus(string overrideStr = null)
        {
            lock (SyncRoot)
            {
                string setString;
                if (overrideStr != null)
                {
                    setString = overrideStr;
                }
                else if (PlayManager.IsPlaying)
                {
                    setString = QuizMode
                                                ? "<Quiztime!>"
                                                : PlayManager.CurrentPlayData.ResourceData.ResourceTitle;
                }
                else
                {
                    setString = "<Sleeping>";
                }

                return(QueryConnection.ChangeDescription(setString));
            }
        }
Esempio n. 5
0
		private bool InitializeBot()
		{
			// Read Config File
			const string configFilePath = "configTS3AudioBot.cfg";
			ConfigFile cfgFile = ConfigFile.Open(configFilePath) ?? ConfigFile.Create(configFilePath) ?? ConfigFile.GetDummy();
			var afd = cfgFile.GetDataStruct<AudioFrameworkData>(typeof(AudioFramework), true);
			var bcd = cfgFile.GetDataStruct<BobControllerData>(typeof(BobController), true);
			var qcd = cfgFile.GetDataStruct<QueryConnectionData>(typeof(QueryConnection), true);
			var hmd = cfgFile.GetDataStruct<HistoryManagerData>(typeof(HistoryManager), true);
			var pmd = cfgFile.GetDataStruct<PluginManagerData>(typeof(PluginManager), true);
			var pld = cfgFile.GetDataStruct<PlaylistManagerData>(typeof(PlaylistManager), true);
			mainBotData = cfgFile.GetDataStruct<MainBotData>(typeof(MainBot), true);
			cfgFile.Close();

			if (consoleOutput)
			{
				Log.RegisterLogger("[%T]%L: %M", "", Console.WriteLine);
			}

			if (writeLog && !string.IsNullOrEmpty(mainBotData.logFile))
			{
				var encoding = new UTF8Encoding(false);
				logStream = new StreamWriter(File.Open(mainBotData.logFile, FileMode.Append, FileAccess.Write, FileShare.Read), encoding);
				Log.RegisterLogger("[%T]%L: %M\n" + (writeLogStack ? "%S\n" : ""), "", (msg) =>
				{
					if (logStream != null)
						try
						{
							logStream.Write(msg);
							logStream.Flush();
						}
						catch (IOException) { }
				});
			}

			Log.Write(Log.Level.Info, "[============ TS3AudioBot started =============]");
			string dateStr = DateTime.Now.ToLongDateString();
			Log.Write(Log.Level.Info, "[=== Date: {0}{1} ===]", new string(' ', Math.Max(0, 32 - dateStr.Length)), dateStr);
			string timeStr = DateTime.Now.ToLongTimeString();
			Log.Write(Log.Level.Info, "[=== Time: {0}{1} ===]", new string(' ', Math.Max(0, 32 - timeStr.Length)), timeStr);
			Log.Write(Log.Level.Info, "[==============================================]");

			Log.Write(Log.Level.Info, "[============ Initializing Commands ===========]");
			CommandManager = new CommandManager();
			CommandManager.RegisterMain(this);

			Log.Write(Log.Level.Info, "[============ Initializing Modules ============]");
			QueryConnection = new QueryConnection(qcd);
			var playlistManager = new PlaylistManager(pld);
			BobController = new BobController(bcd, QueryConnection);
			// old: new VLCConnection(afd.vlcLocation);
			// new: BobController
			AudioFramework = new AudioFramework(afd, BobController, playlistManager);
			SessionManager = new SessionManager();
			HistoryManager = new HistoryManager(hmd);
			PluginManager = new PluginManager(this, pmd);

			Log.Write(Log.Level.Info, "[=========== Initializing Factories ===========]");
			FactoryManager = new ResourceFactoryManager(AudioFramework);
			FactoryManager.DefaultFactorty = new MediaFactory();
			FactoryManager.AddFactory(new YoutubeFactory());
			FactoryManager.AddFactory(new SoundcloudFactory());
			FactoryManager.AddFactory(new TwitchFactory());

			Log.Write(Log.Level.Info, "[=========== Registering callbacks ============]");
			// Inform our HistoryManager when a new resource started successfully
			AudioFramework.OnResourceStarted += HistoryManager.LogAudioResource;
			// Inform the BobClient on start/stop
			AudioFramework.OnResourceStarted += BobController.OnResourceStarted;
			AudioFramework.OnResourceStopped += BobController.OnResourceStopped;
			// In own favor update the own status text to the current song title
			AudioFramework.OnResourceStarted += SongUpdateEvent;
			// Register callback for all messages happening
			QueryConnection.OnMessageReceived += TextCallback;
			// Register callback to remove open private sessions, when user disconnects
			QueryConnection.OnClientDisconnect += (s, e) => SessionManager.RemoveSession(e.InvokerId);


			Log.Write(Log.Level.Info, "[================= Finalizing =================]");
			// Create a default session for all users in all chat
			SessionManager.DefaultSession = new PublicSession(this);
			// Connect the query after everyting is set up
			try { QueryConnection.Connect(); }
			catch (QueryCommandException qcex)
			{
				Log.Write(Log.Level.Error, "There is either a problem with your connection configuration, or the query has not all permissions it needs. ({0})", qcex);
				return false;
			}

			Log.Write(Log.Level.Info, "[============== Connected & Done ==============]");
			return true;
		}
Esempio n. 6
0
        public R InitializeBot()
        {
            Log.Info("Bot connecting...");

            // Read Config File
            var afd  = Config.GetDataStruct <AudioFrameworkData>("AudioFramework", true);
            var tfcd = Config.GetDataStruct <Ts3FullClientData>("QueryConnection", true);
            var hmd  = Config.GetDataStruct <HistoryManagerData>("HistoryManager", true);
            var pld  = Config.GetDataStruct <PlaylistManagerData>("PlaylistManager", true);

            mainBotData = Config.GetDataStruct <MainBotData>("MainBot", true);

            AudioValues.audioFrameworkData = afd;

            Injector.RegisterType <Bot>();
            Injector.RegisterType <BotInjector>();
            Injector.RegisterType <PlaylistManager>();
            Injector.RegisterType <TeamspeakControl>();
            Injector.RegisterType <SessionManager>();
            Injector.RegisterType <HistoryManager>();
            Injector.RegisterType <PlayManager>();
            Injector.RegisterType <IPlayerConnection>();
            Injector.RegisterType <ITargetManager>();
            Injector.RegisterType <Ts3BaseFunctions>();

            Injector.RegisterModule(this);
            Injector.RegisterModule(Injector);
            Injector.RegisterModule(new PlaylistManager(pld));
            var teamspeakClient = new Ts3Full(tfcd);

            Injector.RegisterModule(teamspeakClient);
            Injector.RegisterModule(teamspeakClient.GetLowLibrary <Ts3FullClient>());
            Injector.RegisterModule(new SessionManager());
            HistoryManager historyManager = null;

            if (hmd.EnableHistory)
            {
                Injector.RegisterModule(historyManager = new HistoryManager(hmd), x => x.Initialize());
            }
            Injector.RegisterModule(new PlayManager());
            Injector.RegisterModule(teamspeakClient.TargetPipe);

            if (!Injector.AllResolved())
            {
                Log.Warn("Cyclic bot module dependency");
                Injector.ForceCyclicResolve();
                if (!Injector.AllResolved())
                {
                    Log.Error("Missing bot module dependency");
                    return("Could not load all bot modules");
                }
            }

            PlayerConnection.OnSongEnd        += PlayManager.SongStoppedHook;
            PlayManager.BeforeResourceStarted += BeforeResourceStarted;
            // In own favor update the own status text to the current song title
            PlayManager.AfterResourceStarted += LoggedUpdateBotStatus;
            PlayManager.AfterResourceStopped += LoggedUpdateBotStatus;
            // Log our resource in the history
            if (hmd.EnableHistory)
            {
                PlayManager.AfterResourceStarted += (s, e) => historyManager.LogAudioResource(new HistorySaveData(e.PlayResource.BaseData, e.Owner));
            }
            // Update our thumbnail
            PlayManager.AfterResourceStarted += GenerateStatusImage;
            PlayManager.AfterResourceStopped += GenerateStatusImage;
            // Register callback for all messages happening
            QueryConnection.OnMessageReceived += TextCallback;
            // Register callback to remove open private sessions, when user disconnects
            QueryConnection.OnClientDisconnect += OnClientDisconnect;
            QueryConnection.OnBotDisconnect    += (s, e) => Dispose();
            QueryConnection.OnBotConnected     += OnBotConnected;
            BadgesString = tfcd.ClientBadges;

            // Connect the query after everyting is set up
            try { QueryConnection.Connect(); }
            catch (Ts3Exception qcex)
            {
                Log.Info(qcex, "There is either a problem with your connection configuration, or the query has not all permissions it needs.");
                return("Query error");
            }
            return(R.OkR);
        }
Esempio n. 7
0
 public BotInfo GetInfo() => new BotInfo
 {
     Id = Id, NickName = QueryConnection.GetSelf().OkOr(null)?.Name
 };
Esempio n. 8
0
        private void TextCallback(object sender, TextMessage textMessage)
        {
            Log.Debug("Got message from {0}: {1}", textMessage.InvokerName, textMessage.Message);

            textMessage.Message = textMessage.Message.TrimStart(' ');
            if (!textMessage.Message.StartsWith("!", StringComparison.Ordinal))
            {
                return;
            }

            var refreshResult = QueryConnection.RefreshClientBuffer(true);

            if (!refreshResult.Ok)
            {
                Log.Warn("Bot is not correctly set up. Some commands might not work or are slower. ({0})", refreshResult.Error);
            }

            var clientResult = QueryConnection.GetClientById(textMessage.InvokerId);

            // get the current session
            UserSession session = null;
            var         result  = SessionManager.GetSession(textMessage.InvokerId);

            if (result.Ok)
            {
                session = result.Value;
            }
            else
            {
                if (clientResult.Ok)
                {
                    session = SessionManager.CreateSession(clientResult.Value);
                }
                else
                {
                    Log.Warn("Could not create session with user, some commands might not work ({0})", clientResult.Error);
                }
            }

            var invoker = new InvokerData(textMessage.InvokerUid)
            {
                ClientId  = textMessage.InvokerId,
                Visibiliy = textMessage.Target,
                NickName  = textMessage.InvokerName,
            };

            if (clientResult.Ok)
            {
                invoker.ChannelId  = clientResult.Value.ChannelId;
                invoker.DatabaseId = clientResult.Value.DatabaseId;
            }

            var info = CreateExecInfo(invoker, session);

            UserSession.SessionToken sessionLock = null;
            try
            {
                if (session != null)
                {
                    sessionLock = session.GetLock();
                    // check if the user has an open request
                    if (session.ResponseProcessor != null)
                    {
                        var msg = session.ResponseProcessor(textMessage.Message);
                        session.ClearResponse();
                        if (!string.IsNullOrEmpty(msg))
                        {
                            info.Write(msg).UnwrapThrow();
                        }
                        return;
                    }
                }

                CallScript(info, textMessage.Message, true, false);
            }
            finally
            {
                sessionLock?.Dispose();
            }
        }
Esempio n. 9
0
 private void OnBotConnected(object sender, EventArgs e)
 {
     QueryConnection.ChangeBadges(BadgesString);
 }
Esempio n. 10
0
 private void OnBotConnected(object sender, EventArgs e)
 {
     Log.Info("Bot connected.");
     QueryConnection.ChangeBadges(BadgesString);
 }
Esempio n. 11
0
		public BobController(BobControllerData data, QueryConnection queryConnection)
		{
			if (queryConnection == null)
				throw new ArgumentNullException(nameof(queryConnection));

			timeout = TickPool.RegisterTick(TimeoutCheck, TimeSpan.FromMilliseconds(100), false);
			musicInfoWaiter = new WaitEventBlock<MusicData>();
			isRunning = false;
			awaitingConnect = false;
			this.bobControllerData = data;
			this.queryConnection = queryConnection;
			queryConnection.OnMessageReceived += GetResponse;
			queryConnection.OnClientConnect += OnBobConnect;
			queryConnection.OnClientDisconnect += OnBobDisconnnect;
			commandQueue = new Queue<string>();
			channelSubscriptions = new Dictionary<int, SubscriptionData>();
		}