예제 #1
0
        private int ScanSongs()
        {
            int changesMade = 0;

            Config.ConfigFile config      = SongPlayerFactory.GetConfigFile();
            string[]          directories = config.GetValue("library.path").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            string[]          extensions  = config.GetValue("library.extensions").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

            if (extensions.Length == 0)
            {
                extensions = new string[] { "mp3" }
            }
            ;

            List <string> files = new List <string>();

            foreach (string directory in directories)
            {
                if (Directory.Exists(directory))
                {
                    foreach (string extension in extensions)
                    {
                        files.AddRange(Directory.GetFiles(directory, "*." + extension, SearchOption.AllDirectories).AsEnumerable <string>());
                    }
                }
            }

            //Find removed songs
            lock (lockObject)
            {
                if (_songs.RemoveAll(s => !files.Any(f => f == s.FileName)) > 0)
                {
                    changesMade++;
                }
            }

            //Find added songs
            foreach (string fileName in files)
            {
                lock (lockObject)
                {
                    if (_songs.Any(s => s.FileName == fileName))
                    {
                        continue;
                    }
                }

                Song song = new Song();
                song.FileName = fileName;
                FileInfo fileInfo = new FileInfo(fileName);
                song.Name = Regex.Replace(fileInfo.Name, @"\" + fileInfo.Extension + "$", string.Empty, RegexOptions.IgnoreCase);

                AddSong(song);

                changesMade++;
            }

            return(changesMade);
        }
        public void Update()
        {
            while (_running)
            {
                if (!_songLibrary.ScanLibrary())
                {
                    Thread.Sleep(500);
                }

                try
                {
                    WMPPlayState playState;
                    lock (lockObject)
                    {
                        playState = player.playState;
                    }

                    if (playState == WMPPlayState.wmppsStopped ||
                        playState == WMPPlayState.wmppsUndefined)
                    {
                        Next(null);
                    }
                }
                catch
                {
                }

                string status;
                if (SongPlayerFactory.GetSongPlayer().PlayerStatus.RequestedSong != null)
                {
                    status = string.Format("Currently playing: {0} sec -> {1}", SongPlayerFactory.GetSongPlayer().PlayerStatus.Position, SongPlayerFactory.GetSongPlayer().PlayerStatus.RequestedSong.Song.GetArtistAndTitle());
                }
                else
                {
                    status = "No song playing...";
                }

                OnPlayerStatusChanged(status);

                int minimalsonginqueue;

                if (!int.TryParse(SongPlayerFactory.GetConfigFile().GetValue("player.minimalsonginqueue"), out minimalsonginqueue))
                {
                    minimalsonginqueue = 0;
                }

                //Enqueue random song when the queue is empty and the current song is almost finished
                if (_currentSong != null && _queue.Count < minimalsonginqueue + ((int)(DateTime.Now - _currentSongStart).TotalSeconds + 20 > _currentSong.Song.Duration ? 1 : 0))
                {
                    RequestedSong requestedSong = _songLibrary.GetRandomSong();
                    if (requestedSong != null)
                    {
                        Enqueue(requestedSong.Song, requestedSong.RequesterName);
                    }
                }
            }
        }
예제 #3
0
        public bool ScanLibrary()
        {
            int minutesBetweenScans;

            if (!int.TryParse(SongPlayerFactory.GetConfigFile().GetValue("library.minutesbetweenscans"), out minutesBetweenScans))
            {
                minutesBetweenScans = 2;
            }

            int tagChanges = UpdateTags();

            if (tagChanges > 0)
            {
                int songCount  = _songs.Count();
                int noTagCount = _songs.Count(s => s.TagRead);
                OnStatusChanged(string.Format("Library updated: {0} songs. Tags read: {1}/{0}. Next scan: {2}.", songCount, noTagCount, (_lastFullUpdate + TimeSpan.FromMinutes(minutesBetweenScans)).ToShortTimeString()));
            }
            else
            {
                OnStatusChanged("Library update completed (" + _songs.Count() + " songs). Next scan: " + (_lastFullUpdate + TimeSpan.FromMinutes(minutesBetweenScans)).ToShortTimeString());
            }

            _unsavedChanges = _unsavedChanges || tagChanges > 0;

            //Save, but no more than once every 2 minutes
            if (_unsavedChanges && _lastSerialize + TimeSpan.FromMinutes(2) < DateTime.Now)
            {
                Serialize();
            }

            //No need to scan...
            if (_lastFullUpdate + TimeSpan.FromMinutes(minutesBetweenScans) > DateTime.Now)
            {
                return(tagChanges > 0);
            }

            int fileChanges = ScanSongs();

            if (fileChanges > 0 || tagChanges > 0)
            {
                int songCount  = _songs.Count();
                int noTagCount = _songs.Count(s => s.TagRead);
                OnStatusChanged(string.Format("Library updated: {0} songs. Tags read: {1}/{0}. Next scan: {2}.", songCount, noTagCount, (_lastFullUpdate + TimeSpan.FromMinutes(minutesBetweenScans)).ToShortTimeString()));
            }

            _lastFullUpdate = DateTime.Now;

            if (fileChanges == 0 || tagChanges == 0)
            {
                OnStatusChanged("Library update completed (" + _songs.Count() + " songs). Next scan: " + (_lastFullUpdate + TimeSpan.FromMinutes(minutesBetweenScans)).ToShortTimeString());
            }

            _unsavedChanges = _unsavedChanges || fileChanges > 0 || tagChanges > 0;

            return(fileChanges > 0 || tagChanges > 0);
        }
예제 #4
0
 static void Program_LibraryStatusChanged(string status)
 {
     lock (consoleLock)
     {
         Console.SetCursorPosition(0, 2);
         Console.Write(new string(' ', Console.WindowWidth));
         Console.SetCursorPosition(0, 2);
         Console.Write("Library: {0}", SongPlayerFactory.GetConfigFile().GetValue("library.path"));
         Console.SetCursorPosition(0, 3);
         Console.Write(new string(' ', Console.WindowWidth));
         Console.SetCursorPosition(0, 3);
         Console.Write(status.Substring(0, Math.Min(status.Length, Console.WindowWidth)));
     }
 }
        private bool ClientAllowed(string requesterName)
        {
            if (string.IsNullOrEmpty(requesterName))
            {
                return(true);
            }

            string allowedClients = SongPlayerFactory.GetConfigFile().GetValue("server.clients");

            //Only allow clients from config file
            return(string.IsNullOrEmpty(allowedClients) ||
                   allowedClients.Equals("all", StringComparison.OrdinalIgnoreCase) ||
                   SongPlayerFactory.GetConfigFile().GetValue("server.clients").ContainsOrdinalIgnoreCase(requesterName));
        }
예제 #6
0
        private static void Run()
        {
            Console.Clear();
            DrawArt();

            using (HttpListener listener = new HttpListener())
            {
                if (!int.TryParse(SongPlayerFactory.GetConfigFile().GetValue("server.port"), out port))
                {
                    port = 8765;
                }

                prefix = string.Format("http://*:{0}/", port);

                DrawProgramStatus();

                SongPlayerFactory.GetSongPlayer().LibraryStatusChanged += new StatusChangedEventHandler(Program_LibraryStatusChanged);
                SongPlayerFactory.GetSongPlayer().PlayerStatusChanged  += new StatusChangedEventHandler(Program_PlayerStatusChanged);

                listener.Prefixes.Add(prefix);

                listener.Start();

                while (_running)
                {
                    HttpListenerContext context = listener.GetContext();
                    Stopwatch           watch   = Stopwatch.StartNew();

                    Program_LastRequestChanged(string.Format("{0} - {1}\t{2}", DateTime.Now.ToString("HH:mm:ss"), context.Request.UserHostAddress, context.Request.RawUrl));

                    try
                    {
                        Dispatcher.ProcessRequest(context);

                        watch.Stop();
                    }
                    catch (Exception ex)
                    {
                        context.Response.StatusCode = 500;

                        using (var writer = new StreamWriter(context.Response.OutputStream))
                            writer.Write(ex.ToString());
                    }
                }
            }
        }
예제 #7
0
        static void Program_LibraryStatusChanged(string status)
        {
            lock (consoleLock)
            {
                string[] directories = SongPlayerFactory.GetConfigFile().GetValue("library.path").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                string libraryPath = string.Join("';'", directories.Select(x => Directory.Exists(x) ? x : x + "- please create folder"));

                Console.SetCursorPosition(0, 2);
                Console.Write(new string(' ', Console.WindowWidth));
                Console.SetCursorPosition(0, 2);
                Console.Write("Library: '{0}'", libraryPath);
                Console.SetCursorPosition(0, 3);
                Console.Write(new string(' ', Console.WindowWidth));
                Console.SetCursorPosition(0, 3);
                Console.Write(status.Substring(0, Math.Min(status.Length, Console.WindowWidth)));
            }
        }
        public void Enqueue(Song song, string requesterName)
        {
            if (!ClientAllowed(requesterName))
            {
                return;
            }

            int maximalsonginqueue;

            if (!int.TryParse(SongPlayerFactory.GetConfigFile().GetValue("player.maximalsonginqueue"), out maximalsonginqueue))
            {
                maximalsonginqueue = int.MaxValue;
            }

            if (_queue.Count >= maximalsonginqueue)
            {
                return;
            }

            SongLibrary.UpdateSingleTag(song);
            _queue.Add(new RequestedSong {
                Song = song, RequesterName = requesterName, RequestedDate = DateTime.Now
            });
        }
예제 #9
0
        private async static Task Run()
        {
            // list of tasks
            List <Task> tasks = new List <Task>();

            Console.Clear();
            DrawArt();

            using (HttpListener listener = new HttpListener())
            {
                host = SongPlayerFactory.GetConfigFile().GetValue("server.host");
                if (string.IsNullOrWhiteSpace(host))
                {
                    host = "*";
                }

                if (!int.TryParse(SongPlayerFactory.GetConfigFile().GetValue("server.port"), out port))
                {
                    port = 8765;
                }

                DrawProgramStatus();

                string stringVolume = SongPlayerFactory.GetConfigFile().GetValue("player.startupvolume");
                int    volume;
                if (!int.TryParse(stringVolume, out volume))
                {
                    volume = 50;
                }

                SongPlayerFactory.GetSongPlayer().Volume = volume;
                SongPlayerFactory.GetSongPlayer().LibraryStatusChanged += new StatusChangedEventHandler(Program_LibraryStatusChanged);
                SongPlayerFactory.GetSongPlayer().PlayerStatusChanged  += new StatusChangedEventHandler(Program_PlayerStatusChanged);

                listener.Prefixes.Add(Prefix);

                listener.Start();

                // maximum number of tasks
                int maximumNumberOfTasks = 4 * Environment.ProcessorCount;
                Program_LastRequestChanged(string.Format("Asynchronous handles a maximum of {0} requests.", maximumNumberOfTasks));


                using (SemaphoreSlim semaphore = new SemaphoreSlim(maximumNumberOfTasks, maximumNumberOfTasks))
                {
                    while (_running)
                    {
                        // wait until a semaphore request is released
                        await semaphore.WaitAsync();

                        tasks.RemoveAll(x => x.Status == TaskStatus.RanToCompletion);

                        tasks.Add(Task.Run(() =>
                        {
                            listener.GetContextAsync().ContinueWith(async(t) =>
                            {
                                HttpListenerContext context = await t;

                                try
                                {
                                    Program_LastRequestChanged(string.Format("{0} - {1}\t{2}", DateTime.Now.ToString("HH:mm:ss"), context.Request.UserHostAddress, context.Request.RawUrl));

                                    Dispatcher.ProcessRequest(context);
                                    return;
                                }
                                catch (Exception ex)
                                {
                                    context.Response.StatusCode = 500;

                                    using (var writer = new StreamWriter(context.Response.OutputStream))
                                        writer.Write(ex.ToString());
                                }
                                finally
                                {
                                    // release semaphore request
                                    semaphore.Release();
                                }
                            });
                        }));
                    }
                }
            }

            await Task.WhenAll(tasks);
        }