public void UpdatePlaylistFromStrings(Playlist playlist, IEnumerable <string> collection)
        {
            if (collection is null || playlist is null)
            {
                return;
            }
            using (BackgroundWorker worker = new BackgroundWorker())
            {
                worker.RunWorkerAsync(new object[] { playlist, collection });
                worker.DoWork             += DoUpdatePlaylist;
                worker.RunWorkerCompleted += (s, e) =>
                {
                    if (e.Result is null)
                    {
                        return;
                    }

                    foreach (SongInfo song in e.Result as IEnumerable <SongInfo> )
                    {
                        // add new songs to library and current displayed song collection
                        if (PlaylistLibrary.SongLocations.Add(song.Uri.LocalPath) || AllSongs.Count < PlaylistLibrary.SongLocations.Count)
                        {
                            AllSongs.Add(song);
                            Helpers.ConsoleLogger.Info($"Added {song.Uri.LocalPath} to {PlaylistLibrary.Name}");
                            Helpers.ConsoleLogger.Info($"Added {song.Title} is added to AllSongCollection");
                        }
                        if (!ReferenceEquals(AllSongs, CurrentSongCollection))
                        {
                            CurrentSongCollection.Add(song);
                        }
                    }
                };
            }
        }
Exemple #2
0
        /// <summary>
        /// Cleans up all links to other entries so that this entry can be deleted.
        /// </summary>
        public virtual void DeleteLinks()
        {
            var artistLinks = AllArtists.ToArray();

            foreach (var artist in artistLinks)
            {
                artist.Delete();
            }

            var songLinks = AllSongs.ToArray();

            foreach (var song in songLinks)
            {
                song.Delete();
            }

            var users = UserCollections.ToArray();

            foreach (var user in users)
            {
                user.Delete();
            }

            Tags.DeleteUsages();

            // Archived versions and comments are cascaded
        }
Exemple #3
0
        /// <summary>
        /// Cleans up all links to other entries so that this entry can be deleted.
        /// </summary>
        public virtual void DeleteLinks()
        {
            var artistLinks = AllArtists.ToArray();

            foreach (var artist in artistLinks)
            {
                artist.Delete();
            }

            var songLinks = AllSongs.ToArray();

            foreach (var song in songLinks)
            {
                song.Delete();
            }

            var users = UserCollections.ToArray();

            foreach (var user in users)
            {
                user.Delete();
            }

            //ArchivedVersionsManager.Clear();
            //Comments.Clear();
        }
Exemple #4
0
        private void LoadSongList(Library library)
        {
            List <Song> Songs;
            List <Song> AllSongs;
            List <Song> RemainingSongs;

            // First load all the songs that are in all the libraries.
            AllSongs = Songs = SongLibrary.Songs.OrderBy(S => S.Title).ToList();
            // Then get the ones in the selected library and the ones that aren't.
            if (library == null)
            {
                Songs          = AllSongs;
                RemainingSongs = new List <Song>();
            }
            else
            {
                Songs = SongLibrary.Libraries.Where(l => l.Id == library.Id).First()
                        .Songs
                        .OrderBy(S => S.Title)
                        .ToList();
                RemainingSongs = AllSongs.Except <Song>(Songs).ToList();
            }
            LoadListView(Songs, SongsAtStart); // Need to have a separate list independent of Library for the .Except later on.
            LoadListView(Songs, SongsInLibrary);
            LoadListView(RemainingSongs, SongsAvailable);
        }
Exemple #5
0
        //Learning Accessory functions
        private static ConsensusResults ConsensusLearning(SimParams par, Population pop,
                                                          List <int>[] tutors, List <int> learners)
        {
            //Create a consensus based on songs from several males
            List <int>[] ConsensusSongs = new List <int> [learners.Count];
            List <int>[] AddSyls        = new List <int> [learners.Count];
            List <int>[] AllSongs;
            List <int>   CollapsedSongs;
            float        Conform;

            for (int i = 0; i < learners.Count; i++)
            {
                ConsensusSongs[i] = new List <int> {
                };
                AddSyls[i]        = new List <int> {
                };
                AllSongs          = ListeningTest(par, pop, tutors[i].ToArray(), par.ListeningThreshold);
                CollapsedSongs    = AllSongs.SelectMany(x => x).ToList();
                ConsensusSongs[i] = CollapsedSongs.Distinct().ToList();
                for (int j = 0; j < ConsensusSongs[i].Count(); j++)
                {
                    Conform = ConsensusCalc(par, ConsensusSongs[i][j], CollapsedSongs);
                    if (par.NextFloat() < Conform)
                    {
                        AddSyls[i].Add(ConsensusSongs[i][j]);
                    }
                }
            }
            ConsensusResults Returnable = new ConsensusResults(AddSyls, ConsensusSongs);

            return(Returnable);
        }
Exemple #6
0
        //Misc
        public static Population OverLearn(SimParams par, Population pop,
                                           int[] vacant, List <int> notVacant)
        {
            //Get learners and tutors
            List <int> Learners = vacant.ToList();

            List <int>[] Tutors    = ChooseMultipleTutors(par, pop, Learners, notVacant, par.NumTutorOverLearn);
            List <int>[] TutorSyls = new List <int> [Learners.Count];

            //Create combined song with all sylls
            List <int>[] AllSongs;
            List <int>   CollapsedSongs;

            for (int i = 0; i < Learners.Count; i++)
            {
                AllSongs       = ListeningTest(par, pop, Tutors[i].ToArray(), par.ListeningThreshold);
                CollapsedSongs = AllSongs.SelectMany(x => x).ToList();
                TutorSyls[i]   = CollapsedSongs.Distinct().ToList();
            }

            //Add Syls and update song traits
            AddSyllables(par, pop, Learners, TutorSyls);
            UpdateSongTraits(par, pop, Learners);
            return(pop);
        }
Exemple #7
0
 public async Task SearchSongs(IEnumerable <Music> source, string keyword, SortBy criterion)
 {
     AllSongs.SetTo(await Task.Run(() => SearchHelper.SearchSongs(source, keyword, criterion)));
     Songs.SetTo(AllSongs.Take(SongLimit));
     SongsTextBlock.Text           = Settings.settings.ShowCount ? Helper.LocalizeText("SongsWithCount", AllSongs.Count) : Helper.LocalizeText("Songs");
     SongsViewAllButton.Visibility = AllSongs.Count > SongLimit ? Visibility.Visible : Visibility.Collapsed;
     SortSongsButton.Visibility    = Songs.Count < 2 ? Visibility.Collapsed : Visibility.Visible;
 }
Exemple #8
0
        public virtual SongInList AddSong(Song song, int order, string notes)
        {
            ParamIs.NotNull(() => song);

            var link = new SongInList(song, this, order, notes);

            AllSongs.Add(link);
            return(link);
        }
Exemple #9
0
 private void Unsubscribe(IEnumerable <Song> songs)
 {
     foreach (Song song in songs ?? Enumerable.Empty <Song>())
     {
         CurrentSong.Unsubscribe(song);
         OtherSongs.Unsubscribe(song);
         AllSongs.Unsubscribe(song);
     }
 }
        public void Initialize()
        {
            // Create Playlists and Library directory
            if (!Directory.Exists(PlaylistDir))
            {
                Directory.CreateDirectory(PlaylistDir);
            }
            if (!Directory.Exists(SongDir))
            {
                Directory.CreateDirectory(SongDir);
            }

            // load playlists from playlist directory
            GetPlaylistFiles();

            // load songs from library.xml or Library directory
            string library = Path.Combine(Environment.CurrentDirectory, "library.xml");

            if (File.Exists(library))
            {
                PlaylistLibrary = LoadPlaylistFromXmlFile(library);
            }
            else
            {
                PlaylistLibrary = CreatePlaylistFromDirectory("library.xml", Path.Combine(Environment.CurrentDirectory, SongDir));
            }
            if (PlaylistLibrary != null)
            {
                BackgroundWorker worker = new BackgroundWorker();
                LoadSongsFromPlaylist(PlaylistLibrary).ContinueWith((task) =>
                {
                    IEnumerable <SongInfo> songs = task.Result;
                    foreach (SongInfo item in songs)
                    {
                        AllSongs.Add(item);
                    }
                    CurrentSelectedPlaylistFile = PlaylistLibrary;
                    CurrentSongCollection       = AllSongs;
                });
            }

            // init media player
            mMediaPlayer.MediaOpened     += MediaOpened;
            mMediaPlayer.MediaEnded      += MediaEnded;
            mMediaPlayer.MediaFailed     += MediaFailed;
            mMediaPlayer.LoadedBehavior   = MediaState.Manual;
            mMediaPlayer.UnloadedBehavior = MediaState.Stop;
            mMediaPlayer.Play();

            // init timer to update song's position
            mSongTimer = new Timer()
            {
                Enabled  = true,
                Interval = 1000.0 / 60.0
            };
            mSongTimer.Elapsed += TimerUpdateSongPosition;
        }
Exemple #11
0
        public virtual SongInAlbum AddSong(string songName, int trackNum, int discNum)
        {
            ParamIs.NotNullOrEmpty(() => songName);

            var track = new SongInAlbum(songName, this, trackNum, discNum);

            AllSongs.Add(track);

            return(track);
        }
Exemple #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Fill_Songs();

            if (!Page.IsPostBack)
            {
                AllSongs.DataBind();
            }
            Generate_Link();
        }
Exemple #13
0
        public virtual ArtistForSong AddSong(Song song, bool support, ArtistRoles roles)
        {
            ParamIs.NotNull(() => song);

            var link = new ArtistForSong(song, this, support, roles);

            AllSongs.Add(link);
            song.AllArtists.Add(link);

            return(link);
        }
Exemple #14
0
        public void DeleteSong(int songId)
        {
            if (songLookupDictionary.ContainsKey(songId))
            {
                SongModel songToRemove = songLookupDictionary[songId];
                AllSongs.Remove(songToRemove);
                songLookupDictionary.Remove(songId);
            }

            DatabaseManager.Current.DeleteSong(songId);
        }
Exemple #15
0
        public virtual SongInAlbum AddSong(Song song, int trackNum, int discNum)
        {
            ParamIs.NotNull(() => song);

            var track = new SongInAlbum(song, this, trackNum, discNum);

            AllSongs.Add(track);
            song.AllAlbums.Add(track);

            return(track);
        }
Exemple #16
0
 private void SortSongsButton_Click(object sender, RoutedEventArgs e)
 {
     MenuFlyoutHelper.SetSortByMenu(sender, Settings.settings.SearchSongsCriterion, SongsCriteria,
                                    async item =>
     {
         Settings.settings.SearchSongsCriterion = item;
         LoadingProgress.Visibility             = Visibility.Visible;
         AllSongs.SetTo(await Task.Run(() => SearchHelper.SortSongs(AllSongs, CurrentKeyword.Text, item).ToList()));
         Songs.SetTo(AllSongs.Take(Songs.Count));
         LoadingProgress.Visibility = Visibility.Collapsed;
     });
 }
Exemple #17
0
        public virtual void OnSongDeleting(SongInAlbum songInAlbum)
        {
            ParamIs.NotNull(() => songInAlbum);

            if (!songInAlbum.Album.Equals(this))
            {
                throw new ArgumentException("Song is not in album");
            }

            foreach (var song in Songs.Where(song => song.TrackNumber > songInAlbum.TrackNumber))
            {
                song.TrackNumber--;
            }

            AllSongs.Remove(songInAlbum);
        }
Exemple #18
0
        public static async Task <AllSongs> GetSongInfo(IConfiguration configuration, string url)
        {
            var song    = new AllSongs();
            var videoID = GetYouTubeVideoID(url);

            if (!string.IsNullOrWhiteSpace(videoID))
            {
                var ytService = GetYouTubeService(configuration);

                if (ytService != null)
                {
                    try
                    {
                        var videoRequest = ytService.Videos.List("snippet,contentDetails");
                        videoRequest.Id = videoID;

                        var videoItemsResponse = await videoRequest.ExecuteAsync();

                        var videoItem = videoItemsResponse.Items.FirstOrDefault();

                        if (videoItem != null)
                        {
                            var availableVideo = !(videoItem.Snippet.Title.ToLower().Contains("deleted") &&
                                                   videoItem.Snippet.Description.Contains("unavailable"));

                            if (availableVideo)
                            {
                                song = new AllSongs()
                                {
                                    OriginalGame  = "NEW",
                                    OriginalTitle = videoItem.Snippet.Title,
                                    Channel       = videoItem.Snippet.ChannelTitle,
                                    Duration      = ConvertToTime(videoItem.ContentDetails.Duration),
                                    YouTubeLink   = $"https://youtu.be/{videoID}"
                                };
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            return(song);
        }
Exemple #19
0
        private void Subscribe(IEnumerable <Song> songs)
        {
            foreach (Song song in songs ?? Enumerable.Empty <Song>())
            {
                bool isCurrentSong = song == song.Parent.Parent.CurrentSong;

                if (isCurrentSong)
                {
                    CurrentSong.Subscribe(song);
                }
                else
                {
                    OtherSongs.Subscribe(song);
                }

                AllSongs.Subscribe(song);
            }
        }
Exemple #20
0
        public void Reset(IEnumerable <Song> songs, Song currentlyPlaying)
        {
            Logger.LogDebug("PartyService: Reset");
            Console.WriteLine("PartyService: Reset");

            AllSongs.Clear();
            foreach (Song song in songs)
            {
                AllSongs.Add(song);
            }

            AllVotes.Clear();
            CanVote          = true;
            CurrentlyPlaying = currentlyPlaying;

            SongListingStream.OnNext(GenerateSongListing(AllSongs, CurrentlyPlaying));
            VotingResultsStream.OnNext(GenerateVotingResults(AllSongs, AllVotes, CanVote));
        }
Exemple #21
0
 public static void LoadPlaylists()
 {
     if (File.Exists("Playlists.xml"))
     {
         XElement playlists = XElement.Load("Playlists.xml");
         foreach (XElement playlist in playlists.Elements("playlist"))
         {
             ObservableCollection <Song> songs = new ObservableCollection <Song>();
             foreach (XElement song in playlist.Elements("song"))
             {
                 Song songToAdd = AllSongs.FirstOrDefault(s => s.Name == song.Value);
                 if (songToAdd != null)
                 {
                     songs.Add(songToAdd);
                 }
             }
             Playlists.Add(new Playlist(playlist.Attribute("name").Value, songs));
         }
     }
 }
Exemple #22
0
        public static void LoadAndSortSongs()
        {
            IEnumerable <string> songFiles = Directory.EnumerateFiles(@"C:\Users\mathewtraylor\Downloads", "*.*", SearchOption.AllDirectories)
                                             .Where(f => f.EndsWith(".mp3", StringComparison.InvariantCultureIgnoreCase) || f.EndsWith(".wav", StringComparison.InvariantCultureIgnoreCase));

            foreach (string filename in songFiles)
            {
                AllSongs.Add(new Song(filename));
            }

            IEnumerable <IGrouping <string, Song> > artists = AllSongs.GroupBy(s => s.Artists);

            foreach (IGrouping <string, Song> artist in artists)
            {
                Artists.Add(new Artist(artist.Key, artist.Count()));
            }

            IEnumerable <IGrouping <string, Song> > albums = AllSongs.GroupBy(s => s.Album);

            foreach (IGrouping <string, Song> album in albums)
            {
                Albums.Add(new Album(album.Key, album.Count()));
            }
        }
Exemple #23
0
        public static AllSongs SearchSongFirst(string song, List <AllSongs> playlist)
        {
            song = song.ToLower();

            if (song.Contains("\""))
            {
                song = song.Replace("\"", string.Empty);
                return(playlist.Where(x => x.Title.Contains(song)).FirstOrDefault());
            }

            song = GetString(song);

            AllSongs result     = null;
            double   maxScore   = 0;
            int      maxMatches = 0;
            var      words      = song.Split(' ');

            foreach (var p in playlist)
            {
                var title = GetString(p.Title);

                //var title = p.LowerCaseTitle.Replace('/', ' ').Replace(':', ' ').Replace('-', ' ').Replace('(', ' ').Replace(')', ' ');
                var pWords = title.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                var count  = 0;

                foreach (var w in words)
                {
                    if (pWords.Contains(w))
                    {
                        count++;
                    }
                }

                var percentage = count / (double)pWords.Length;

                if (count >= maxMatches)
                {
                    if (count > maxMatches)
                    {
                        maxScore   = percentage;
                        result     = p;
                        maxMatches = count;
                    }
                    else
                    {
                        if (percentage > maxScore)
                        {
                            maxScore   = percentage;
                            result     = p;
                            maxMatches = count;
                        }
                    }
                }
            }

            if (result == null)
            {
                return(playlist.Where(x => x.Title.Contains(song)).FirstOrDefault());
            }

            return(result);
        }
Exemple #24
0
 public void Add(Song song)
 {
     AllSongs.Add(song);
 }
        public async Task <ActionResult> Create(IFormCollection collection, AllSongs song)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var youTubeLink = collection["YouTubeLink"].ToString();

                    if (!string.IsNullOrWhiteSpace(youTubeLink))
                    {
                        var table = TableStorageService.ConnectToTable(Constants.AllSongsTableName);
                        TableContinuationToken tableContinuationToken = null;
                        int maxKey     = 0;
                        var songExists = false;

                        do
                        {
                            var tableQuerySegment = await table.ExecuteQuerySegmentedAsync(new TableQuery <AllSongs>(), tableContinuationToken);

                            var songs = tableQuerySegment.Results;

                            var max = songs.Max(x => x.RowKey);
                            maxKey = Math.Max(maxKey, int.Parse(max));

                            tableContinuationToken = tableQuerySegment.ContinuationToken;
                            songExists             = songs.Any(x => x.YouTubeLink == youTubeLink);
                        }while (tableContinuationToken != null && !songExists);

                        if (!songExists)
                        {
                            var    i     = (maxKey + 1).ToString("D4");
                            string title = collection["OriginalTitle"];
                            string game  = collection["OriginalGame"];

                            var newSong = new AllSongs()
                            {
                                RowKey            = i,
                                OriginalGame      = game,
                                Game              = game.ToLower(),
                                OriginalTitle     = title,
                                PartitionKey      = StringFunctions.ReplaceChars(game.ToLower()),
                                Title             = StringFunctions.ReplaceChars(title.ToLower()),
                                Channel           = collection["Channel"],
                                Duration          = collection["Duration"],
                                YouTubeLink       = youTubeLink,
                                LastTimeRequested = null,
                                RecentlyAdded     = "✓",
                                Counter           = 0,
                                Likes             = 0
                            };

                            await TableStorageService.InsertEntity(newSong, Constants.AllSongsTableName);

                            //TODO: add tags from webpage

                            return(RedirectToAction("Index", "Playlist", new { ac = "The song was successfully added!", type = "success" }));
                        }
                        else
                        {
                            return(RedirectToAction("Index", "Playlist", new { ac = "The YouTube video URL already exists in the playlist!", type = "danger" }));
                        }
                    }
                    else
                    {
                        return(View());
                    }
                }
                else
                {
                    return(View());
                }
            }
            catch (Exception)
            {
                return(View());
            }
        }
        public async Task <ActionResult> RequestSong(string pk, string rk)
        {
            var tableSong = TableStorageService.ConnectToTable("CurrentSong");
            var queryCS   = await tableSong.ExecuteQuerySegmentedAsync(new TableQuery <AzureTableSong>(), null);

            var currentSong = queryCS.Results.FirstOrDefault();

            if (currentSong.RowKey != rk)
            {
                var song = await TableStorageService.RetrieveEntity <AllSongs>(pk, rk, Constants.AllSongsTableName);

                if (song != null)
                {
                    var position = 1;

                    var channel = CookieService.Get(Request, Constants.ChannelCookieName);

                    var user = await userManager.GetUserAsync(User);

                    var userName = user.UserName;

                    var isModOwner = await userManager.IsInRoleAsync(user, "Moderator") ||
                                     await userManager.IsInRoleAsync(user, "Owner");

                    var queueSongs = await TableStorageService.RetrieveAllEntities <AzureTableSong>(Constants.QueueTableName);

                    if (queueSongs.Count > 0)
                    {
                        if (!isModOwner)
                        {
                            var friend = await TableStorageService.RetrieveEntity <Friends>(channel, "1", Constants.FriendsTableName);

                            if (friend != null)
                            {
                                var friendRequests = queueSongs.Count(x => x.RequestedById == channel);
                                if (friendRequests > 1)
                                {
                                    return(RedirectToAction("Index", "Playlist", new { ac = "Error. You already have two song requests on the queue.", type = "danger" }));
                                }
                            }
                            else
                            {
                                var userExists = queueSongs.Any(x => x.RequestedById == channel);
                                if (userExists)
                                {
                                    return(RedirectToAction("Index", "Playlist", new { ac = "Error. You already have a song request on the queue.", type = "danger" }));
                                }
                            }
                        }

                        var songExists = queueSongs.Any(x => x.RowKey == rk);
                        if (songExists)
                        {
                            return(RedirectToAction("Index", "Playlist", new { ac = $"Error. That song is already on the queue.", type = "danger" }));
                        }

                        queueSongs = queueSongs.OrderBy(x => x.Position).ToList();
                        position   = queueSongs.Last().Position + 1;
                    }

                    var lastRequest = (song.LastTimeRequested.HasValue)
                        ? MathFunctions.GetCooldownMinutes(song.LastTimeRequested.Value) : 100;

                    if (isModOwner || lastRequest > 60)
                    {
                        var updateSong = new AllSongs()
                        {
                            PartitionKey      = song.PartitionKey,
                            RowKey            = song.RowKey,
                            Counter           = song.Counter0 + 1,
                            LastTimeRequested = DateTime.UtcNow
                        };

                        await TableStorageService.MergeEntity(updateSong, Constants.AllSongsTableName);

                        var newSongQueue = new AzureTableSong()
                        {
                            PartitionKey      = song.PartitionKey,
                            RowKey            = song.RowKey,
                            Title             = song.OriginalTitle,
                            OriginalGame      = song.OriginalGame,
                            LowerCaseTitle    = song.Title,
                            Channel           = song.Channel,
                            VideoId           = song.YouTubeLink.Replace("https://youtu.be/", string.Empty),
                            YouTubeLink       = song.YouTubeLink,
                            Duration          = song.Duration,
                            TotalTime         = 0,
                            RecentlyAdded     = song.RecentlyAdded,
                            RequestedBy       = userName,
                            RequestedById     = channel,
                            Counter           = song.Counter0 + 1,
                            Likes             = song.Likes0,
                            Position          = position,
                            LastTimeRequested = song.LastTimeRequested
                        };

                        await TableStorageService.InsertEntity(newSongQueue, Constants.QueueTableName);

                        return(RedirectToAction("Index", "SongsQueue", new { ac = $"The song was added to the queue in position {position}.", type = "success" }));
                    }
                    else
                    {
                        return(RedirectToAction("Index", "Playlist", new { ac = $"Error. That song is in cooldown. Please wait {60 - lastRequest} minutes to request it again.", type = "danger" }));
                    }
                }

                return(RedirectToAction("Index", "Playlist", new { ac = "Error. The song does not exist.", type = "danger" }));
            }
            else
            {
                return(RedirectToAction("Index", "Playlist", new { ac = "Error. The song is currently playing.", type = "danger" }));
            }
        }