Exemple #1
0
 public MPC(string host, int port)
 {
     s = new ServerComponent(host, port);
     s.Disconnected += new EventHandler(s_Disconnected);
     CurrentStatus = new Status();
     CurrentPlaylist = new Playlist();
 }
        public ShareCode GetShareCode(ShareableEntityType entityType, Guid entityId)
        {
            //  TODO: Support sharing other entities.
            if (entityType != ShareableEntityType.Playlist)
                throw new NotSupportedException("Only Playlist entityType can be shared currently.");

            ShareCode shareCode;

            try
            {
                Playlist playlistToCopy = PlaylistDao.Get(entityId);

                if (playlistToCopy == null)
                {
                    string errorMessage = string.Format("No playlist found with id: {0}", entityId);
                    throw new ApplicationException(errorMessage);
                }

                var shareablePlaylistCopy = new Playlist(playlistToCopy);
                PlaylistManager.Save(shareablePlaylistCopy);

                shareCode = new ShareCode(shareablePlaylistCopy);
                Save(shareCode);
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                throw;
            }

            return shareCode;
        }
        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.currentPlayList = (Application.Current as App).Plc01[this.currentItemIndex];
            this.playListName.Text = this.currentPlayList.Name;
            this.playListLls.ItemsSource = this.currentPlayList.Songs.ToList();

        }
        /// <summary>
        /// Copy a playlist. Useful for sharing.
        /// </summary>
        /// <param name="id">The playlist ID to copy</param>
        /// <returns>A new playlist with a new ID which has been saved.</returns>
        public Playlist CopyAndSave(Guid id)
        {
            Playlist copiedPlaylist;

            try
            {
                Playlist playlistToCopy = PlaylistDao.Get(id);

                if (playlistToCopy == null)
                {
                    string errorMessage = string.Format("No playlist found with id: {0}", id);
                    throw new ApplicationException(errorMessage);
                }

                copiedPlaylist = new Playlist(playlistToCopy);
                DoSave(copiedPlaylist);
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                throw;
            }

            return copiedPlaylist;
        }
Exemple #5
0
 public Player(Playlist playlist, IAudioInteractor audioInteractor, ILibraryRepository library)
 {
     AudioInteractor = audioInteractor;
     Playlist = playlist;
     _current = this;
     Library = library;
 }
        public void Update(Playlist playlist)
        {
            try
            {
                NHibernateSessionManager.Instance.BeginTransaction();
                playlist.ValidateAndThrow();

                Playlist knownPlaylist = PlaylistDao.Get(playlist.Id);

                if (knownPlaylist == null)
                {
                    PlaylistDao.Update(playlist);
                }
                else
                {
                    PlaylistDao.Merge(playlist);
                }

                NHibernateSessionManager.Instance.CommitTransaction();
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                NHibernateSessionManager.Instance.RollbackTransaction();
                throw;
            }
        }
        public DeleteContentOperation(IPod dev, IEnumerable<Playlist> playlists, bool isAltMode)
            : this(dev, isAltMode)
        {
            _playList = null;

            _playlists = playlists;
        }
        public void Loop()
        {
            var song1 = "song1";
            var song2 = "song2";

            var library = new MemoryLibraryRepository();
            library.ClearLibrary();
            library.AddMusicToLibrary(
                new MusicInfo[] {
                    new MusicInfo() { FullPath = song1 },
                    new MusicInfo() { FullPath = song2 }
                });

            var loopingWatcher = new LoopingPlaylistWatcher();
            var playlist = new Playlist(loopingWatcher);
            var dummyAudio = new DummyAudioInteractor();

            var player = new Player(playlist, dummyAudio, library);

            loopingWatcher.AttachToPlaylist(playlist, library);

            playlist.AddRange(library.GetAllMusic());

            player.MaxPlayCount = 3;
            player.Play();

            Assert.AreEqual(3, dummyAudio.PlayHistory.Count, "There must be three songs in the history.");
            Assert.AreEqual(song1, dummyAudio.PlayHistory[0], "The first song must play first.");
            Assert.AreEqual(song2, dummyAudio.PlayHistory[1], "The second song must play second.");
            Assert.AreEqual(song1, dummyAudio.PlayHistory[2], "The first song must play third.");

            Assert.AreEqual(2, playlist.RemainingSongs, "After playing three songs there must still be 2 songs in the playlist.");
        }
Exemple #9
0
        public void PlayerCanBeGivenANewPlaylist()
        {
            var library = new MemoryLibraryRepository();
            var playlist = new Playlist();
            var dummyAudio = new DummyAudioInteractor();
            var player = new Player(playlist, dummyAudio, null);

            var song = "song1";

            library.ClearLibrary();
            library.AddMusicToLibrary(new MusicInfo[] { new MusicInfo() { FullPath = song } });

            playlist.AddRange(library.GetAllMusic());

            player.Play();

            Assert.AreEqual(song, playlist.CurrentSong.FullPath, "The last song played must be the only one in the library.");

            var song2 = "song 2";

            library.ClearLibrary();
            library.AddMusicToLibrary(new MusicInfo[] { new MusicInfo() { FullPath = song2 } });

            playlist.AddRange(library.GetAllMusic());

            player.PlayCount = 0;
            player.Play();

            Assert.AreEqual(song, playlist.PreviousSong.FullPath, "The previous played must be new song in the library.");
            Assert.AreEqual(song2, playlist.CurrentSong.FullPath, "The current played must be new song in the library.");
        }
        public EditPlaylistViewModel(Playlist playlist, User user)
        {
            Playlist = playlist;
            User = user;

            _songRepo = new SongRepository();
            _artRepo = new ArtRepository();
            _playlistRepo = new PlaylistRepository();
            _playlistRepo.Dispose();

            Art = new ObservableCollection<string>(_artRepo.GetPlaylistArt());
            AllSongs = new ObservableCollection<Song>(_songRepo.GetAllSongs());
            PlaceholderSongs = CurrentSongs;

            Title = Playlist.Title;
            Image = Playlist.Image;
            PlaylistUserID = Playlist.UserID;
            SelectedImage = Playlist.Image;

            // COMMANDS
            AddSongToPlaylistCommand = new RelayCommand(new Action<object>(AddSongToPlaylist));
            RemoveSongFromPlaylistCommand = new RelayCommand(new Action<object>(RemoveSongFromPlaylist));
            CloseEditPlaylistViewCommand = new RelayCommand(new Action<object>(CloseEditPlaylistView));
            SavePlaylistChangesCommand = new RelayCommand(new Action<object>(SavePlaylistChanges), Predicate => {
                if (TitleRule.TitleRegex.IsMatch(Title))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            });
        }
Exemple #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PlaylistViewModel" /> class.
        /// </summary>
        /// <param name="playlist">The playlist info.</param>
        /// <param name="renameRequest">
        /// A function that requests the rename of the playlist. Return true, if the rename is
        /// granted, otherwise false.
        /// </param>
        public PlaylistViewModel(Playlist playlist, Func<string, bool> renameRequest)
        {
            this.playlist = playlist;
            this.renameRequest = renameRequest;

            this.disposable = new CompositeDisposable();

            this.entries = playlist
                .CreateDerivedCollection(entry => new PlaylistEntryViewModel(entry))
                .DisposeWith(this.disposable);
            this.entries.ItemsRemoved.Subscribe(x => x.Dispose());

            this.playlist.WhenAnyValue(x => x.CurrentSongIndex).ToUnit()
                .Merge(this.entries.Changed.ToUnit())
                .Subscribe(_ => this.UpdateCurrentSong())
                .DisposeWith(this.disposable);

            IObservable<List<PlaylistEntryViewModel>> remainingSongs = this.entries.Changed
                .Select(x => Unit.Default)
                .Merge(this.playlist.WhenAnyValue(x => x.CurrentSongIndex).ToUnit())
                .Select(x => this.entries.Reverse().TakeWhile(entry => !entry.IsPlaying).ToList());

            this.songsRemaining = remainingSongs
                .Select(x => x.Count)
                .ToProperty(this, x => x.SongsRemaining)
                .DisposeWith(this.disposable);

            this.timeRemaining = remainingSongs
                .Select(x => x.Any() ? x.Select(entry => entry.Duration).Aggregate((t1, t2) => t1 + t2) : (TimeSpan?)null)
                .ToProperty(this, x => x.TimeRemaining)
                .DisposeWith(this.disposable);

            this.CurrentPlayingEntry = this.Model.WhenAnyValue(x => x.CurrentSongIndex).Select(x => x == null ? null : this.entries[x.Value]);
        }
        protected override bool OnStartup(StartupEventArgs eventArgs) {
            InitSettings();

            SongPlayer = new SongPlayer(ApplicationSettings.Volume);
            Playlist = new Playlist();
            TransitionMgr = new TransitionManager(SongPlayer, Playlist, ApplicationSettings);

            if(eventArgs.CommandLine.Count > 0) {
                HandleArgs(eventArgs.CommandLine.ToArray()).Wait();
            } else {
                LoadStartupSongFiles();
            }

            SpeechController = new SpeechController(SongPlayer, Playlist, ApplicationSettings);
            SpeechController.Init();

            Application = new SpeechMusicControllerApp();
            Application.InitializeComponent();

            var windowMgr = new WindowManager((Hardcodet.Wpf.TaskbarNotification.TaskbarIcon)Application.FindResource(TrayIconResourceName));
            windowMgr.Init(ApplicationSettings, SongPlayer, Playlist, SpeechController);

            Application.Exiting += (s, a) => {
                ApplicationSettings.WriteToDisc();
            };

            windowMgr.Overlay.DisplayText("SMC Running...", 2000);
            Application.Run();
            return false;
        }
	        //@Override
	        public void OnPlaylist(Playlist playlist) 
	        {
	            brightcoveVideoView.AddAll(playlist.Videos);
	            brightcoveVideoView.Start();

	            return;
	        }
Exemple #14
0
        public void WhenThePlayListIsEmpty()
        {
            var dummyPlaylistWatcher = new DummyPlaylistWatcher();
            var playlist = new Playlist(dummyPlaylistWatcher);

            Assert.IsFalse(playlist.AreMoreSongsAvailable(), "There must not be any songs available.");
        }
        public void Test()
        {
            var song1 = "song1";
            var song2 = "song2";
            var song3 = "song3";
            var song4 = "song4";

            _songs = new MusicInfo[] {
                    new MusicInfo() { FullPath = song1 },
                    new MusicInfo() { FullPath = song2 },
                    new MusicInfo() { FullPath = song3 },
                    new MusicInfo() { FullPath = song4 }
                };

            var library = new MemoryLibraryRepository();
            library.ClearLibrary();
            library.AddMusicToLibrary(_songs);

            var loopingWatcher = new RandomSongPlaylistWatcher(2);
            _playlist = new Playlist(loopingWatcher);
            _dummyAudio = new DummyAudioInteractor();

            var player = new Player(_playlist, _dummyAudio, library);

            loopingWatcher.AttachToPlaylist(_playlist, library);

            player.MaxPlayCount = 3;
            player.Play();
        }
Exemple #16
0
        public void PlaylistsCanGoBack()
        {
            string filename1 = "song1";
            string filename2 = "song1";
            var music1 = new MusicInfo() { FullPath = filename1 };
            var music2 = new MusicInfo() { FullPath = filename2 };
            var dummyPlaylistWatcher = new DummyPlaylistWatcher();
            var playlist = new Playlist(dummyPlaylistWatcher);

            playlist.Enqueue(music1);
            playlist.Enqueue(music2);

            Assert.AreEqual(2, playlist.Count, "There must be two songs in the playlist.");

            MusicInfo song = playlist.CurrentSong;
            Assert.AreEqual(filename1, song.FullPath, "The first item in the playlist must be correct.");

            playlist.MoveToNextSong();

            MusicInfo nextSong = playlist.CurrentSong;
            Assert.AreEqual(filename2, nextSong.FullPath, "The second item in the playlist must be correct.");

            playlist.MoveBackOneSong();
            Assert.AreEqual(filename1, playlist.CurrentSong.FullPath, "Going back one song should go back to the first one.");
        }
        /// <summary>
        /// Adds a playlist to the database.
        /// </summary>
        public void AddPlaylist(Playlist playlist)
        {
            StringBuilder sb = new StringBuilder ();
            sb.AppendFormat ("INSERT INTO playlists VALUES (NULL,{0})", parse(playlist.Name));

            ExecuteQuery (sb.ToString ());
        }
        protected void Create_Click(object sender, EventArgs e)
        {
            var playlist = new Playlist()
            {
                Title = this.Server.HtmlEncode(this.TitleTextBox.Text),
                Description = this.Server.HtmlEncode(this.Description.Text),
                CreationDate = DateTime.UtcNow,
                CreatorId = this.User.Identity.GetUserId()
            };

            Video video = this.Videos.GetByUrl(this.Server.HtmlEncode(this.Url.Text));
            if (video == null)
            {
                video = new Video()
                {
                    Url = this.Server.HtmlEncode(this.Url.Text)
                };
            }

            Category category = this.Categories.All().Where(c => c.Name == this.CategorySelect.SelectedItem.Text).FirstOrDefault();

            playlist.Category = category;
            playlist.Videos.Add(video);

            this.Playlists.Create(playlist);
            this.Playlists.SaveChanges();
        }
        public DeleteContentOperation(IPod dev, Playlist pl, IEnumerable<Track> tracks, bool isAltMode)
            : this(dev, isAltMode)
        {
            _playList = pl;

            _tracks = tracks;
        }
Exemple #20
0
    public MainWindow()
        : base(Gtk.WindowType.Toplevel)
    {
        oXbmc = new XBMC_Communicator();
        oXbmc.SetIp("10.0.0.5");
        oXbmc.SetConnectionTimeout(4000);
        oXbmc.SetCredentials("", "");
        oXbmc.Status.StartHeartBeat();

        Build ();

        this.AllowStaticAccess();

        //Create objects used
        oPlaylist 		= new Playlist(this);
        oControls		= new Controls(this);
        oMenuItems		= new MenuItems(this);
        oContextMenu 	= new ContextMenu(this);
        oShareBrowser 	= new ShareBrowser(this);
        oTrayicon 		= new SysTrayIcon(this);
        oStatusUpdate	= new StatusUpdate(this);
        oMediaInfo		= new MediaInfo(this);
        oNowPlaying		= new NowPlaying(this);
        oGuiConfig		= new GuiConfig(this);

        nbDataContainer.CurrentPage = 0;
    }
Exemple #21
0
        public MainWindow()
        {
            // In order to log exception
            AppDomain currentDomain = default(AppDomain);
            currentDomain = AppDomain.CurrentDomain;
            // Handler for unhandled exceptions.
            currentDomain.UnhandledException += GlobalUnhandledExceptionHandler;
            // Handler for exceptions in threads behind forms.
            System.Windows.Forms.Application.ThreadException += GlobalThreadExceptionHandler;

            // make sure our directory where we will save and load playlists exists
            if (!Directory.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\wamp"))
                Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\wamp");

            //log file

            InitializeComponent();

            Closing += MainWindow_Closing;

            ////Subscribe to PlaylistEditor control PlayPlaylist button event
            //playlistEditorControl.PlayPlaylistButtonPressedEvent += HandlePlayPlaylistButtonPressedEvent;

            //Subscribe to PlaylistEditor control Playlist Changed event
            playlistEditorControl.PlaylistContentsChangedEvent += HandlePlaylistContentsChangedEvent;

            // Subscribe to the selected library changed event in the preferences control.  Note that a name
            // was given to the control in the main window xaml.
            preferencesControl.SelectedLibraryChangedEvent += HandleSelectedLibraryChangedEvent;
            playlistEditorControl.SelectedLibrary = preferencesControl.SelectedLibrary;
            playerControl.SelectedLibrary = preferencesControl.SelectedLibrary;

            //Subscribe to Preferences control SelectedOutputchanged event
            preferencesControl.SelectedOutputChangedEvent += HandleSelectedOutputChangedEvent;
            // and the VolumeEnabled event
            preferencesControl.VolumeEnabledEvent += HandleVolumeEnableEvent;
            // and the AcourateVolumeEnabled event
            preferencesControl.AcourateVolumeEnabledEvent += HandleAcourateVolumeEnableEvent;
            // and the MemoryPlayEnabledEvent
            preferencesControl.MemoryPlayEnabledEvent += HandleMemoryPlayEnableEvent;
            // and the NetworkControlEnabledEvent
            preferencesControl.NetworkControlEnabledEvent += HandleNetworkControlEnableEvent;

            // Try to load the default playlist if it exists
            currentPlaylist = Playlist.OpenPlaylist("default");
            if (currentPlaylist != null)
            {
                playerControl.CurrentPlaylist = currentPlaylist;
                playlistEditorControl.CurrentPlaylist = currentPlaylist;
                Track currentTrack = Properties.Settings.Default.CurrentTrack;
                if (currentTrack != null)
                    playerControl.CurrentTrack = currentTrack;
            }

            if (preferencesControl.SelectedOutput != null)
                playerControl.SelectedOutput = preferencesControl.SelectedOutput;

            Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded, new Action(() => { playerControl.InitButtons(); }));
        }
        public JumpToItemDlg(Playlist playlist)
            : base("TXT_JUMP_TO_ITEM")
        {
            _playlist = playlist;

            InitializeComponent();
            this.Load += new EventHandler(OnLoad);
        }
Exemple #23
0
        static Helpers()
        {
            Playlist1 = new Playlist("Playlist1");
            Playlist1.AddSongs(new[] { LocalSong1, LocalSong2 });

            Playlist2 = new Playlist("Playlist2");
            Playlist2.AddSongs(new[] { (Song)LocalSong1, YoutubeSong1 });
        }
        public Artist Recommend(SpotifyClient client, Playlist playlist)
        {
            //Find a common ancestor for a portion of the artists in the playlist.
            IEnumerable<Track> playlistEntries = playlist.Tracks.Select(track => track.Track);

            Dictionary<string, ArtistGroup> cachedRelatedArtists = new Dictionary<string, ArtistGroup>();

            Dictionary<string, RecommendationCriteria> relatedArtistMap = new Dictionary<string, RecommendationCriteria>();
            playlistEntries.ToList().ForEach(track =>
            {
                ArtistGroup relatedArtists = null;
                if (!cachedRelatedArtists.ContainsKey(track.Artists.First().ID))
                {
                    relatedArtists = client.GetRelatedArtists(track.Artists.First().ID); //Handle only the first artist for now...
                    cachedRelatedArtists.Add(track.Artists.First().ID, relatedArtists);
                }
                else
                {
                    relatedArtists = cachedRelatedArtists[track.Artists.First().ID];
                }

                relatedArtists.Artists.ForEach(relatedArtist =>
                {
                    if (!relatedArtistMap.ContainsKey(relatedArtist.ID))
                    {
                        RecommendationCriteria recommendationCriteria = new RecommendationCriteria();
                        relatedArtistMap.Add(relatedArtist.ID, recommendationCriteria);
                        recommendationCriteria.TargetedArtist = relatedArtist;
                    }

                    if (!relatedArtistMap[relatedArtist.ID].RelatedArtists.Where(artist => artist.ID == track.Artists.First().ID).Any())
                        relatedArtistMap[relatedArtist.ID].RelatedArtists.Add(track.Artists.First());

                    relatedArtistMap[relatedArtist.ID].Weight++;
                });
            });

            //Other ideas:
            //Recommend by the playlist contents.
            //  Evaluate whether the playlist is a collection of like-artists or individual songs of a particular type (e.g. energetic, fast?)
            //Recommend by the artist selected.
            //
            //Recommend something completely new.  
            //Recommend a set of brand-new songs.
            //  Analyze all changelists to get an idea of what a person likes in particular.  
            //  Easily solution is to find artists that they don't have that are similar.
            //  Could also randomly find songs from various areas:
            //      The current Top 10-40 on the charts.
            //      The list of a band that is playing near you live.
            //      Find a whole smattering of a different genre (trip hop, hip hop, grunge alternative).
            //Recommend by a specific song.
            //      Find songs that were popular at the same time (may not need to be part of the same genre).

            IOrderedEnumerable<KeyValuePair<string, RecommendationCriteria>> orderedDictionary = relatedArtistMap.OrderByDescending(keyValuePair => keyValuePair.Value.Weight)
                                                                                                                    .ThenByDescending(keyValuePair => keyValuePair.Value.RelatedArtists.Count());
            KeyValuePair<string, RecommendationCriteria> recommendedEntry = orderedDictionary.First();
            return recommendedEntry.Value.TargetedArtist;
        }
 public UserControl1(TabControl _tabcontrol1, Playlist _playlist)
 {
     InitializeComponent();
     _sunccontext = SynchronizationContext.Current;
     tabcontrol1 = _tabcontrol1;
     tp = new ThreadParams() { player = this, command = PlayingCommand.Stop, playlist = _playlist, isTerminate = false, doStep = 0 };
     th.IsBackground = true;
     th.Start(tp);
 }
        public SpeechController(SongPlayer player, Playlist playlist, AppSettings settings)
        {
            Player = player;
            Playlist = playlist;
            Settings = settings;

            LastInputTime = Environment.TickCount;
            Sentence = new List<string>();
        }
Exemple #27
0
        public Application(ITransport trackPlayer)
        {
            TrackPlayer = trackPlayer;

            PlayQueue = new Playlist();

            PlaylistPlayer = new PlaylistPlayer(this);

            Console.WriteLine(@"Application initalised.");
        }
        public PlaylistControl(Playlist playlist)
        {
            InitializeComponent();
            _playlist = playlist;

            PlayListIDLabel.Text = playlist.PlaylistID.ToString();
            PlayListName.Text = playlist.Name;

            songsControl.Fill(GroovesharkAPI.Client.Instance.GetPlaylistSongs(playlist.PlaylistID.ToString()));
        }
Exemple #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Library"/> class.
 /// </summary>
 public Library()
 {
     this.songLocker = new object();
     this.songs = new HashSet<Song>();
     this.playlist = new Playlist();
     this.volume = 1.0f;
     this.AccessMode = AccessMode.Administrator; // We want implicit to be the administrator, till we change to user mode manually
     this.driveNotifier = RemovableDriveNotifier.Create();
     this.driveNotifier.DriveRemoved += (sender, args) => Task.Factory.StartNew(this.Update);
 }
Exemple #30
0
        public void ReturnTheCorrectPlaylists_WhenParamsAreValid()
        {
            var options = Utils.GetOptions(nameof(ReturnTheCorrectPlaylists_WhenParamsAreValid));

            Playlist firstPlaylist = new Playlist
            {
                Id               = 41,
                Title            = "Home",
                PlaylistPlaytime = 5524,
                UserId           = 2,
                Rank             = 552348,
                IsDeleted        = false
            };

            Playlist secondPlaylist = new Playlist
            {
                Id               = 42,
                Title            = "Metal",
                PlaylistPlaytime = 5024,
                UserId           = 2,
                Rank             = 490258,
                IsDeleted        = false
            };

            User user = new User()
            {
                Id = 11
            };

            PlaylistFavorite firstFavorite = new PlaylistFavorite()
            {
                Id         = 10,
                UserId     = 11,
                PlaylistId = 41,
                IsFavorite = true
            };

            PlaylistFavorite secondFavorite = new PlaylistFavorite()
            {
                Id         = 11,
                UserId     = 11,
                PlaylistId = 42,
                IsFavorite = true
            };

            var dateTimeProviderMock = new Mock <IDateTimeProvider>();
            var mockImageService     = new Mock <IPixaBayImageService>();

            using (var arrangeContext = new RidePalDbContext(options))
            {
                arrangeContext.Playlists.Add(firstPlaylist);
                arrangeContext.Playlists.Add(secondPlaylist);
                arrangeContext.Users.Add(user);
                arrangeContext.Favorites.Add(firstFavorite);
                arrangeContext.Favorites.Add(secondFavorite);
                arrangeContext.SaveChanges();
            }

            using (var assertContext = new RidePalDbContext(options))
            {
                //Act
                var sut    = new PlaylistService(assertContext, dateTimeProviderMock.Object, mockImageService.Object);
                var result = sut.GetFavoritePlaylistsOfUser(11).Result.ToList();

                //Assert
                Assert.AreEqual(result.Count, 2);
                Assert.AreEqual(result[0].Id, firstPlaylist.Id);
                Assert.AreEqual(result[0].Title, firstPlaylist.Title);
                Assert.AreEqual(result[1].Id, secondPlaylist.Id);
                Assert.AreEqual(result[1].Title, secondPlaylist.Title);
            }
        }
        }//eom

        public void Add_TrackToPLaylist(string playlistname, string username, int trackid)
        {
            using (var context = new ChinookContext())
            {
                //determine if the playlist exists
                //do a query to find the playlist
                //test results == null
                //  yes
                //      create an instance of playlist
                //      load
                //      add
                //      set tracknumber to 1
                //no
                //      query to find track exists
                //      test results == null
                //          yes
                //              throw an exception
                //          no
                //              query to find max tracknumber
                //              tracknumber++
                //create an instance of playlisttrack
                //load
                //add
                //SaveChange

                int           tracknumber = 0;
                PlaylistTrack newtrack    = null;
                //what would happen if there is no match for the
                //   incoming parameter values
                //we need to ensure that the results have a valid value
                //this value will be resolved by the query either as null
                //  (not found) or an IEnumerable collection
                //we are looking for a single occurance to match the where
                //to achieve a valid value we encapsulate the query in a
                //   (query).FirstOrDefault();
                Playlist exists = (from x in context.Playlists
                                   where x.Name.Equals(playlistname) &&
                                   x.UserName.Equals(username)
                                   select x).FirstOrDefault();
                if (exists == null)
                {
                    //new playlist
                    exists          = new Playlist();
                    exists.Name     = playlistname;
                    exists.UserName = username;
                    context.Playlists.Add(exists);
                    tracknumber = 1;
                }
                else
                {
                    //existing playlist
                    newtrack = (from x in context.PlaylistTracks
                                where x.Playlist.Name.Equals(playlistname) &&
                                x.Playlist.UserName.Equals(username) &&
                                x.TrackId == trackid
                                select x).FirstOrDefault();
                    if (newtrack == null)
                    {
                        //not found can be added
                        tracknumber = (from x in context.PlaylistTracks
                                       where x.Playlist.Name.Equals(playlistname) &&
                                       x.Playlist.UserName.Equals(username)
                                       select x.TrackNumber).Max();
                        tracknumber++;
                    }
                    else
                    {
                        //found violates business rule
                        //two ways of handling the message
                        //a) single error
                        //b) multiple business rule errors

                        //a)
                        //throw new Exception("Song already exists on playlist. Choose something else.");

                        //b) use the BusinessRuleException class to throw the error
                        //   this technique can be used in your BLL and onyour Web page
                        //   to this technique, you will collect your errors within
                        //       a List<string>; then throw the BusinessRuleException
                        //       along with the List<string> errors
                        //
                        errors.Add("**Song already exists on playlist. Choose something else.");
                    }
                }

                //finish all possible business rule validation
                if (errors.Count > 0)
                {
                    throw new BusinessRuleException("Adding Track", errors);
                }

                //add the new playlist track record
                newtrack = new PlaylistTrack();
                //when you do an .Add(xxx) to a entity, the record
                //  is ONLY staged AND NOT yet on the database
                //ANY expected pkey value DOES NOT yet exist

                //newtrack.PlaylistId = exists.PlaylistId; removed
                newtrack.TrackId     = trackid;
                newtrack.TrackNumber = tracknumber;
                exists.PlaylistTracks.Add(newtrack);

                //SaveChange is what actually affects the database
                context.SaveChanges();
            }
        }//eom
 public void CreatePlaylist()
 {
     LoginPage.LoginWithDefault();
     PlaylistManager.CreateSimplePlaylist();
     Assert.IsTrue(Playlist.HasPlaylist(PlaylistManager.CreatedPlaylistName));
 }
Exemple #33
0
 /// <inheritdoc />
 public override string ToString()
 => $"Searched for: {Query}\nStatus: {Status}" +
 $"\nPlaylist? {(Playlist.Equals(default(PlaylistInfo)) ? "NULL" : Playlist.Name)}" +
 $"\nTracks: {Tracks?.Count()}";
Exemple #34
0
        private static void GetAdvertisingPlaylist(string advertListPath, string demographicDataPath,
                                                   DemographicRangeVerifier demographicRangeVerifier, string password, Playlist playlist, ChannelData channelData,
                                                   ChannelSubscriptions channelSubscriptions, DateTime now, Logger logger)
        {
            // if the advertisment or the demographic data file is not found, an exception will be thrown
            // if user has corrupted any of the files, an exception will be thrown
            AdvertList advertList = (AdvertList)Serializer.Deserialize(typeof(AdvertList), advertListPath, password);

            // flatten channel definitions
            HashSet <string> channelDefinitions = new HashSet <string>();

            foreach (Channel channel in channelData.Channels)
            {
                SplitAndInsertChannelDefinitions(ref channelDefinitions, channel.ChannelDefinitions);
            }

            // flatten advert definitions
            HashSet <string> advertDefinitions = new HashSet <string>();

            foreach (AdvertAsset advertasset in advertList.Adverts)
            {
                SplitAndInsertChannelDefinitions(ref advertDefinitions, advertasset.AdvertDefinitions);
            }

            var advertListsFiltered = HashSetLinqAccess.ToHashSet <AdvertPlaylistAsset>(from AdvertAsset advertAsset in advertList.Adverts
                                                                                        where demographicRangeVerifier.IsAssetDemoSyntaxPlayable(advertAsset.DemoRequirements) &&
                                                                                        TreeSearch.IncludeByChannelClassifications(channelDefinitions, advertAsset.InclusionExclusionList) == true &&
                                                                                        TreeSearch.IncludeByAdvertClassifications(advertDefinitions, channelData, channelSubscriptions) == true &&
                                                                                        now >= advertAsset.StartDateTime &&
                                                                                        now <= advertAsset.EndDateTime
                                                                                        select new AdvertPlaylistAsset
            {
                AssetID               = advertAsset.AssetID,
                AssetFilename         = advertAsset.AssetFilename,
                ClickDestination      = advertAsset.ClickDestination,
                AssetWebSite          = advertAsset.AssetWebSite,
                PlayerType            = advertAsset.PlayerType,
                ScheduleInfo          = advertAsset.ScheduleInfo,
                DisplayLength         = advertAsset.DisplayDuration,
                WeightingUnnormalized = advertAsset.Weighting,
                StartDateTime         = advertAsset.StartDateTime,
                EndDateTime           = advertAsset.EndDateTime
            });

            playlist.AdvertBucket.AdvertAssets = advertListsFiltered;
        }
Exemple #35
0
            private void onStart()
            {
                gameBeatmap.Value.Mods.Value = CurrentMods.Value.ToArray();

                switch (Type.Value)
                {
                default:
                case GameTypeTimeshift _:
                    pushGameplayScreen?.Invoke(new PlayerLoader(() => new TimeshiftPlayer(Playlist.First())
                    {
                        Exited = () => leaderboard.RefreshScores()
                    }));
                    break;
                }
            }
 public PlaylistShortResponse(Playlist playlist)
 {
     Alias = playlist.Alias;
     Name  = playlist.Name;
 }
Exemple #37
0
        public async Task <Dictionary <string, ScrapedSong> > ReadScoreSaber(Playlist allPlaylist = null)
        {
            if (BeatSync.Paused)
            {
                await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
            }
            Stopwatch sw = new Stopwatch();

            sw.Start();
            Logger.log?.Info("Starting ScoreSaber reading");

            var config = Config.ScoreSaber;
            ScoreSaberReader reader = null;

            try
            {
                reader = new ScoreSaberReader();
            }
            catch (Exception ex)
            {
                Logger.log?.Error(ex);
                return(null);
            }
            var readerSongs = new Dictionary <string, ScrapedSong>();

            if (config.TopRanked.Enabled)
            {
                try
                {
                    var feedSettings = config.TopRanked.ToFeedSettings();
                    var feedPlaylist = config.TopRanked.CreatePlaylist
                        ? PlaylistManager.GetPlaylist(config.TopRanked.FeedPlaylist)
                        : null;
                    var playlistStyle = config.TopRanked.PlaylistStyle;
                    if (BeatSync.Paused)
                    {
                        await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
                    }
                    var songs = await ReadFeed(reader, feedSettings, feedPlaylist, playlistStyle).ConfigureAwait(false);

                    var pages    = songs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();
                    var feedName = reader.GetFeedName(feedSettings);
                    Logger.log?.Info($"{reader.Name}.{feedName} Feed: Found {songs.Count} songs from {pages} {(pages == 1 ? "page" : "pages")}.");
                    readerSongs.Merge(songs);
                }
                catch (Exception ex)
                {
                    Logger.log?.Error("Exception in ReadScoreSaber, Top Ranked.");
                    Logger.log?.Error(ex);
                }
            }

            if (config.Trending.Enabled)
            {
                try
                {
                    var feedSettings = config.Trending.ToFeedSettings();
                    var feedPlaylist = config.Trending.CreatePlaylist
                        ? PlaylistManager.GetPlaylist(config.Trending.FeedPlaylist)
                        : null;
                    var playlistStyle = config.Trending.PlaylistStyle;
                    if (BeatSync.Paused)
                    {
                        await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
                    }
                    var songs = await ReadFeed(reader, feedSettings, feedPlaylist, playlistStyle).ConfigureAwait(false);

                    var pages    = songs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();
                    var feedName = reader.GetFeedName(feedSettings);
                    Logger.log?.Info($"{reader.Name}.{feedName} Feed: Found {songs.Count} songs from {pages} {(pages == 1 ? "page" : "pages")}.");
                    readerSongs.Merge(songs);
                }
                catch (Exception ex)
                {
                    Logger.log?.Error("Exception in ReadScoreSaber, Trending.");
                    Logger.log?.Error(ex);
                }
            }

            if (config.TopPlayed.Enabled)
            {
                try
                {
                    var feedSettings = config.TopPlayed.ToFeedSettings();
                    var feedPlaylist = config.TopPlayed.CreatePlaylist
                        ? PlaylistManager.GetPlaylist(config.TopPlayed.FeedPlaylist)
                        : null;
                    var playlistStyle = config.TopPlayed.PlaylistStyle;
                    if (BeatSync.Paused)
                    {
                        await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
                    }
                    var songs = await ReadFeed(reader, feedSettings, feedPlaylist, playlistStyle).ConfigureAwait(false);

                    var pages    = songs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();
                    var feedName = reader.GetFeedName(feedSettings);
                    Logger.log?.Info($"{reader.Name}.{feedName} Feed: Found {songs.Count} songs from {pages} {(pages == 1 ? "page" : "pages")}.");
                    readerSongs.Merge(songs);
                }
                catch (Exception ex)
                {
                    Logger.log?.Error("Exception in ReadScoreSaber, Top Played.");
                    Logger.log?.Error(ex);
                }
            }

            if (config.LatestRanked.Enabled)
            {
                try
                {
                    var feedSettings = config.LatestRanked.ToFeedSettings();
                    var feedPlaylist = config.LatestRanked.CreatePlaylist
                        ? PlaylistManager.GetPlaylist(config.LatestRanked.FeedPlaylist)
                        : null;
                    var playlistStyle = config.LatestRanked.PlaylistStyle;
                    if (BeatSync.Paused)
                    {
                        await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
                    }
                    var songs = await ReadFeed(reader, feedSettings, feedPlaylist, playlistStyle).ConfigureAwait(false);

                    var pages    = songs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();
                    var feedName = reader.GetFeedName(feedSettings);
                    Logger.log?.Info($"{reader.Name}.{feedName} Feed: Found {songs.Count} songs from {pages} {(pages == 1 ? "page" : "pages")}.");
                    readerSongs.Merge(songs);
                }
                catch (Exception ex)
                {
                    Logger.log?.Error("Exception in ReadScoreSaber, Latest Ranked.");
                    Logger.log?.Error(ex);
                }
            }

            sw.Stop();
            if (BeatSync.Paused)
            {
                await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
            }
            var totalPages = readerSongs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();

            Logger.log?.Info($"{reader.Name}: Found {readerSongs.Count} songs on {totalPages} {(totalPages == 1 ? "page" : "pages")} in {sw.Elapsed.ToString()}");
            return(readerSongs);
        }
Exemple #38
0
        public async Task <Dictionary <string, ScrapedSong> > ReadBeatSaver(Playlist allPlaylist = null)
        {
            if (BeatSync.Paused)
            {
                await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
            }
            Stopwatch sw = new Stopwatch();

            sw.Start();
            Logger.log?.Info("Starting BeatSaver reading");

            var             config = Config.BeatSaver;
            BeatSaverReader reader = null;

            try
            {
                reader = new BeatSaverReader();
            }
            catch (Exception ex)
            {
                Logger.log?.Error("Exception creating BeatSaverReader in ReadBeatSaver.");
                Logger.log?.Error(ex);
                return(null);
            }
            var readerSongs = new Dictionary <string, ScrapedSong>();

            if (config.FavoriteMappers.Enabled && (FavoriteMappers.Mappers?.Count() ?? 0) > 0)
            {
                try
                {
                    var      feedSettings = config.FavoriteMappers.ToFeedSettings() as BeatSaverFeedSettings;
                    Playlist feedPlaylist = null;
                    if (!config.FavoriteMappers.SeparateMapperPlaylists)
                    {
                        feedPlaylist = config.FavoriteMappers.CreatePlaylist
                            ? PlaylistManager.GetPlaylist(config.FavoriteMappers.FeedPlaylist)
                            : null;
                    }

                    var playlistStyle = config.FavoriteMappers.PlaylistStyle;
                    var songs         = new Dictionary <string, ScrapedSong>();
                    foreach (var author in FavoriteMappers.Mappers)
                    {
                        feedSettings.Criteria = author;
                        if (BeatSync.Paused)
                        {
                            await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
                        }
                        var authorSongs = await ReadFeed(reader, feedSettings, feedPlaylist, playlistStyle).ConfigureAwait(false);

                        Logger.log?.Info($"   FavoriteMappers: Found {authorSongs.Count} songs by {author}");
                        if (config.FavoriteMappers.CreatePlaylist && config.FavoriteMappers.SeparateMapperPlaylists)
                        {
                            var playlistFileName = $"{author}.bplist";
                            var mapperPlaylist   = PlaylistManager.GetOrAdd(playlistFileName, () => new Playlist(playlistFileName, author, "BeatSync", "1"));
                            if (mapperPlaylist != null)
                            {
                                if (playlistStyle == PlaylistStyle.Replace)
                                {
                                    mapperPlaylist.Clear();
                                }
                                foreach (var song in authorSongs.Values)
                                {
                                    mapperPlaylist.TryAdd(song.ToPlaylistSong());
                                }
                            }
                        }

                        songs.Merge(authorSongs);
                    }
                    if (feedPlaylist != null)
                    {
                        foreach (var song in songs.Values)
                        {
                            feedPlaylist.TryAdd(song.ToPlaylistSong());
                        }
                    }
                    var pages    = songs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();
                    var feedName = reader.GetFeedName(feedSettings);
                    Logger.log?.Info($"{reader.Name}.{feedName} Feed: Found {songs.Count} songs from {pages} {(pages == 1 ? "page" : "pages")}.");
                    readerSongs.Merge(songs);
                }
                catch (InvalidCastException ex)
                {
                    Logger.log?.Error($"This should never happen in ReadBeatSaver.\n{ex.Message}");
                }
                catch (ArgumentNullException ex)
                {
                    Logger.log?.Critical("Exception in ReadBeatSaver, FavoriteMappers: " + ex.Message);
                }
                catch (Exception ex)
                {
                    Logger.log?.Error("Exception in ReadBeatSaver, FavoriteMappers.");
                    Logger.log?.Error(ex);
                }
            }
            else if (config.FavoriteMappers.Enabled)
            {
                Logger.log?.Warn("BeatSaver's FavoriteMappers feed is enabled, but no mappers could be found in UserData\\FavoriteMappers.ini");
            }
            if (config.Hot.Enabled)
            {
                try
                {
                    var feedSettings = config.Hot.ToFeedSettings();
                    var feedPlaylist = config.Hot.CreatePlaylist
                        ? PlaylistManager.GetPlaylist(config.Hot.FeedPlaylist)
                        : null;
                    var playlistStyle = config.Hot.PlaylistStyle;
                    if (BeatSync.Paused)
                    {
                        await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
                    }
                    var songs = await ReadFeed(reader, feedSettings, feedPlaylist, playlistStyle).ConfigureAwait(false);

                    var pages    = songs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();
                    var feedName = reader.GetFeedName(feedSettings);
                    Logger.log?.Info($"{reader.Name}.{feedName} Feed: Found {songs.Count} songs from {pages} {(pages == 1 ? "page" : "pages")}.");
                    readerSongs.Merge(songs);
                }
                catch (InvalidCastException ex)
                {
                    Logger.log?.Error($"This should never happen in ReadBeatSaver.\n{ex.Message}");
                }
                catch (ArgumentNullException ex)
                {
                    Logger.log?.Critical("Exception in ReadBeatSaver, Hot: " + ex.Message);
                }
                catch (Exception ex)
                {
                    Logger.log?.Error("Exception in ReadBeatSaver, Hot.");
                    Logger.log?.Error(ex);
                }
            }
            if (config.Downloads.Enabled)
            {
                try
                {
                    var feedSettings = config.Downloads.ToFeedSettings();
                    var feedPlaylist = config.Downloads.CreatePlaylist
                        ? PlaylistManager.GetPlaylist(config.Downloads.FeedPlaylist)
                        : null;
                    var playlistStyle = config.Downloads.PlaylistStyle;
                    if (BeatSync.Paused)
                    {
                        await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
                    }
                    var songs = await ReadFeed(reader, feedSettings, feedPlaylist, playlistStyle).ConfigureAwait(false);

                    var pages    = songs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();
                    var feedName = reader.GetFeedName(feedSettings);
                    Logger.log?.Info($"{reader.Name}.{feedName} Feed: Found {songs.Count} songs from {pages} {(pages == 1 ? "page" : "pages")}.");
                    readerSongs.Merge(songs);
                }
                catch (InvalidCastException ex)
                {
                    Logger.log?.Error($"This should never happen in ReadBeatSaver.\n{ex.Message}");
                }
                catch (ArgumentNullException ex)
                {
                    Logger.log?.Critical("Exception in ReadBeatSaver, Downloads: " + ex.Message);
                }
                catch (Exception ex)
                {
                    Logger.log?.Error("Exception in ReadBeatSaver, Downloads.");
                    Logger.log?.Error(ex);
                }
            }
            sw.Stop();
            if (BeatSync.Paused)
            {
                await SongFeedReaders.Utilities.WaitUntil(() => !BeatSync.Paused, 500).ConfigureAwait(false);
            }
            var totalPages = readerSongs.Values.Select(s => s.SourceUri.ToString()).Distinct().Count();

            Logger.log?.Info($"{reader.Name}: Found {readerSongs.Count} songs on {totalPages} {(totalPages == 1 ? "page" : "pages")} in {sw.Elapsed.ToString()}");
            return(readerSongs);
        }
Exemple #39
0
        public async Task <Dictionary <string, ScrapedSong> > ReadFeed(IFeedReader reader, IFeedSettings settings, Playlist feedPlaylist, PlaylistStyle playlistStyle)
        {
            //Logger.log?.Info($"Getting songs from {feedName} feed.");
            var songs = await reader.GetSongsFromFeedAsync(settings).ConfigureAwait(false) ?? new Dictionary <string, ScrapedSong>();

            if (songs.Count > 0 && playlistStyle == PlaylistStyle.Replace)
            {
                feedPlaylist.Clear();
            }
            var addDate   = DateTime.Now;
            var decrement = new TimeSpan(1);

            foreach (var scrapedSong in songs)
            {
                if (HistoryManager.TryGetValue(scrapedSong.Value.Hash, out var historyEntry) &&
                    (historyEntry.Flag == HistoryFlag.NotFound ||
                     historyEntry.Flag == HistoryFlag.Deleted))
                {
                    continue;
                }
                //if (string.IsNullOrEmpty(scrapedSong.Value.SongKey))
                //{
                //    try
                //    {
                //        //Logger.log?.Info($"Grabbing key from BeatSaver: {scrapedSong.Value.SongName} by {scrapedSong.Value.MapperName}");
                //        // ScrapedSong doesn't have a Beat Saver key associated with it, probably scraped from ScoreSaber
                //        scrapedSong.Value.UpdateFrom(await BeatSaverReader.GetSongByHashAsync(scrapedSong.Key), false);
                //    }
                //    catch (ArgumentNullException)
                //    {
                //        Logger.log?.Warn($"Unable to find {scrapedSong.Value?.SongName} by {scrapedSong.Value?.MapperName} on Beat Saver ({scrapedSong.Key})");
                //    }
                //}
                var song = scrapedSong.Value.ToPlaylistSong();
                song.DateAdded = addDate;

                feedPlaylist?.TryAdd(song);
                addDate = addDate - decrement;
            }
            feedPlaylist?.TryWriteFile();

            return(songs);
        }
Exemple #40
0
 public override Task <Playlist <TvgMedia> > SyncAsync(Playlist <TvgMedia> playlist, CancellationToken token)
 {
     throw new NotImplementedException();
 }
Exemple #41
0
        public async Task Can_remove_from_HasManyThrough_relationship()
        {
            // Arrange
            Playlist existingPlaylist = _fakers.Playlist.Generate();

            existingPlaylist.PlaylistMusicTracks = new List <PlaylistMusicTrack>
            {
                new PlaylistMusicTrack
                {
                    MusicTrack = _fakers.MusicTrack.Generate()
                },
                new PlaylistMusicTrack
                {
                    MusicTrack = _fakers.MusicTrack.Generate()
                },
                new PlaylistMusicTrack
                {
                    MusicTrack = _fakers.MusicTrack.Generate()
                }
            };

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                await dbContext.ClearTableAsync <MusicTrack>();
                dbContext.Playlists.Add(existingPlaylist);
                await dbContext.SaveChangesAsync();
            });

            var requestBody = new
            {
                atomic__operations = new[]
                {
                    new
                    {
                        op   = "remove",
                        @ref = new
                        {
                            type         = "playlists",
                            id           = existingPlaylist.StringId,
                            relationship = "tracks"
                        },
                        data = new[]
                        {
                            new
                            {
                                type = "musicTracks",
                                id   = existingPlaylist.PlaylistMusicTracks[0].MusicTrack.StringId
                            }
                        }
                    },
                    new
                    {
                        op   = "remove",
                        @ref = new
                        {
                            type         = "playlists",
                            id           = existingPlaylist.StringId,
                            relationship = "tracks"
                        },
                        data = new[]
                        {
                            new
                            {
                                type = "musicTracks",
                                id   = existingPlaylist.PlaylistMusicTracks[2].MusicTrack.StringId
                            }
                        }
                    }
                }
            };

            const string route = "/operations";

            // Act
            (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePostAtomicAsync <string>(route, requestBody);

            // Assert
            httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent);

            responseDocument.Should().BeEmpty();

            await _testContext.RunOnDatabaseAsync(async dbContext =>
            {
                // @formatter:wrap_chained_method_calls chop_always
                // @formatter:keep_existing_linebreaks true

                Playlist playlistInDatabase = await dbContext.Playlists
                                              .Include(playlist => playlist.PlaylistMusicTracks)
                                              .ThenInclude(playlistMusicTrack => playlistMusicTrack.MusicTrack)
                                              .FirstWithIdAsync(existingPlaylist.Id);

                // @formatter:keep_existing_linebreaks restore
                // @formatter:wrap_chained_method_calls restore

                playlistInDatabase.PlaylistMusicTracks.Should().HaveCount(1);
                playlistInDatabase.PlaylistMusicTracks[0].MusicTrack.Id.Should().Be(existingPlaylist.PlaylistMusicTracks[1].MusicTrack.Id);

                List <MusicTrack> tracksInDatabase = await dbContext.MusicTracks.ToListAsync();
                tracksInDatabase.Should().HaveCount(3);
            });
        }
Exemple #42
0
 public MainController()
 {
     Playlist = new Playlist();
 }
        public void ReturnOneFilteredPlaylist_WhenParamsAreValid()
        {
            //Arrange
            var options = Utils.GetOptions(nameof(ReturnOneFilteredPlaylist_WhenParamsAreValid));

            Playlist firstPlaylist = new Playlist
            {
                Id               = 55,
                Title            = "Home",
                PlaylistPlaytime = 4824,
                UserId           = 2,
                Rank             = 552348,
                IsDeleted        = false
            };

            Playlist secondPlaylist = new Playlist
            {
                Id               = 56,
                Title            = "Metal",
                PlaylistPlaytime = 5124,
                UserId           = 2,
                Rank             = 490258,
                IsDeleted        = false
            };

            Playlist thirdPlaylist = new Playlist
            {
                Id               = 57,
                Title            = "Seaside",
                PlaylistPlaytime = 5324,
                UserId           = 2,
                Rank             = 552308,
                IsDeleted        = false
            };

            Genre rock = new Genre
            {
                Id   = 35,
                Name = "rock"
            };

            Genre metal = new Genre
            {
                Id   = 36,
                Name = "metal"
            };

            Genre pop = new Genre
            {
                Id   = 37,
                Name = "pop"
            };

            Genre jazz = new Genre
            {
                Id   = 38,
                Name = "jazz"
            };

            var firstPlaylistGenre  = new PlaylistGenre(35, 55);
            var secondPlaylistGenre = new PlaylistGenre(36, 55);
            var thirdPlaylistGenre  = new PlaylistGenre(36, 56);
            var fourthPlaylistGenre = new PlaylistGenre(37, 56);
            var fifthPlaylistGenre  = new PlaylistGenre(38, 57);

            var dateTimeProviderMock = new Mock <IDateTimeProvider>();
            var mockImageService     = new Mock <IPixaBayImageService>();

            var genres = new List <string>()
            {
                "metal"
            };
            List <int> durationLimits = new List <int>()
            {
                0, 84
            };
            string name = null;

            using (var arrangeContext = new RidePalDbContext(options))
            {
                arrangeContext.Playlists.Add(firstPlaylist);
                arrangeContext.Playlists.Add(secondPlaylist);
                arrangeContext.Playlists.Add(thirdPlaylist);
                arrangeContext.Genres.Add(metal);
                arrangeContext.Genres.Add(rock);
                arrangeContext.Genres.Add(pop);
                arrangeContext.Genres.Add(jazz);
                arrangeContext.PlaylistGenres.Add(firstPlaylistGenre);
                arrangeContext.PlaylistGenres.Add(secondPlaylistGenre);
                arrangeContext.PlaylistGenres.Add(thirdPlaylistGenre);
                arrangeContext.PlaylistGenres.Add(fourthPlaylistGenre);
                arrangeContext.PlaylistGenres.Add(fifthPlaylistGenre);
                arrangeContext.SaveChanges();
            }

            using (var assertContext = new RidePalDbContext(options))
            {
                //Act
                var sut       = new PlaylistService(assertContext, dateTimeProviderMock.Object, mockImageService.Object);
                var count     = sut.ReturnFilteredPlaylistsAndCountAsync(name, genres, durationLimits, 1).Result.Item1;
                var playlists = sut.ReturnFilteredPlaylistsAndCountAsync(name, genres, durationLimits, 1).Result.Item2.ToList();

                //Assert
                Assert.AreEqual(playlists.Count, count);
                Assert.AreEqual(playlists[0].Id, firstPlaylist.Id);
                Assert.AreEqual(playlists[0].Title, firstPlaylist.Title);
            }
        }
Exemple #44
0
 public override void Push(Playlist <TvgMedia> playlist)
 {
     throw new NotImplementedException();
 }
Exemple #45
0
        public async Task LoadPlaylist(StorageFile file)
        {
            Core.CoreMethods.LibVM.Database.CreatePlaylistDB(file.DisplayName);
            // List<Mediafile> PlaylistSongs = new List<Mediafile>();
            // Dictionary<Playlist, IEnumerable<Mediafile>> PlaylistDict = new Dictionary<Models.Playlist, IEnumerable<Mediafile>>();
            Playlist Playlist = new Playlist()
            {
                Name = file.DisplayName
            };

            using (var streamReader = new StreamReader(await file.OpenStreamForReadAsync()))
            {
                string line;
                int    index       = 0;
                int    failedFiles = 0;
                bool   ext         = false;
                while ((line = streamReader.ReadLine()) != null)
                {
                    if (line.ToLower() == "#extm3u") //m3u header
                    {
                        ext = true;
                    }
                    else if (ext && line.ToLower().StartsWith("#extinf:")) //extinfo of each song
                    {
                        continue;
                    }
                    else if (line.StartsWith("#") || line == "") //pass blank lines
                    {
                        continue;
                    }
                    else
                    {
                        await Task.Run(async() =>
                        {
                            try
                            {
                                index++;
                                FileInfo info = new FileInfo(file.Path);  //get playlist file info to get directory path
                                string path   = line;
                                if (!File.Exists(line) && line[1] != ':') // if file doesn't exist then perhaps the path is relative
                                {
                                    path = info.DirectoryName + line;     //add directory path to song path.
                                }

                                var accessFile = await StorageFile.GetFileFromPathAsync(path);
                                var token      = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(accessFile);

                                Mediafile mp3File = await Core.CoreMethods.CreateMediafile(accessFile); //prepare Mediafile
                                await SettingsViewModel.SaveSingleFileAlbumArtAsync(mp3File, accessFile);

                                await Core.CoreMethods.NotificationManager.ShowAsync(index.ToString() + " songs sucessfully added into playlist: " + file.DisplayName);

                                if (!Core.CoreMethods.LibVM.Database.tracks.Exists(t => t._id == mp3File._id))
                                {
                                    Core.CoreMethods.LibVM.Database.Insert(mp3File);
                                }

                                StorageApplicationPermissions.FutureAccessList.Remove(token);
                            }
                            catch
                            {
                                failedFiles++;
                            }
                        });
                    }
                }
                string message = string.Format("Playlist \"{3}\" successfully imported! Total Songs: {0} Failed: {1} Succeeded: {2}", index, failedFiles, index - failedFiles, file.DisplayName);
                await Core.CoreMethods.NotificationManager.ShowAsync(message);

                Core.CoreMethods.LibVM.Database.CreateDB();
            }
        }
Exemple #46
0
        /// <summary>
        /// Creates the playlist for the user
        /// </summary>
        /// <param name="channelDataPath">Directory on the end user's computer where channel content files reside</param>
        /// <param name="advertListPath">Fully qualified path of the advert list file on the end user's computer</param>
        /// <param name="demographicDataPath">Fully qualified path of the demographic data path on the end user's computer</param>
        /// <param name="playlistDataPath">Fully qualified path on the end user's computer to save the playlist to</param>
        /// <param name="password">Encryption password</param>
        /// <param name="channelSubscriptions">ChannelSubscriptions object with the user's channel subscriptions</param>
        /// <param name="logger">Logger to log debug/error messages</param>
        /// <exception cref="System.Runtime.Serialization.SerializationException">Thrown when an error occurs during serialization/deserializaton</exception>
        /// <exception cref="InvalidOperationException">Thrown when file to be serialized don't match the deserializer's expected type</exception>
        /// <exception cref="DirectoryNotFoundException">thrown when directory to save or load a file from is not found</exception>
        /// <exception cref="FileNotFoundException">thrown when a file is not found</exception>
        /// <exception cref="CryptographicException">thrown when a serialized file is corrupted</exception>
        public static Playlist CreatePlaylist(string channelDataPath,
                                              string advertListPath,
                                              string demographicDataPath,
                                              string playlistDataPath,
                                              string password,
                                              float defaultDisplayDuration,
                                              ChannelSubscriptions channelSubscriptions,
                                              Logger logger)
        {
            Playlist playlist = new Playlist();

            // holds the channels to which the user is subscribed
            ChannelData channelData = new ChannelData();

            // check if channel data directory exists!
            if (!Directory.Exists(channelDataPath))
            {
                return(null);
            }

            string[] fileEntries = Directory.GetFiles(channelDataPath, "*.dat");

            if (channelSubscriptions.SubscriptionSet.Count == 0 || fileEntries.Length == 0)
            {
                return(playlist);
            }

            foreach (string file in fileEntries)
            {
                channelData.Channels.Add((Channel)Serializer.Deserialize(typeof(Channel), file, "password"));
            }

            if (!File.Exists(demographicDataPath))
            {
                return(null);
            }

            DateTime now = DateTime.Now;

            DemographicData demographicData = (DemographicData)Serializer.Deserialize(typeof(DemographicData), demographicDataPath, password);

            DemographicRangeVerifier demographicRangeVerifier = new DemographicRangeVerifier(demographicData);

            GetNonAdvertisingPlaylist(channelData,
                                      password,
                                      playlist,
                                      demographicRangeVerifier,
                                      channelSubscriptions,
                                      now,
                                      defaultDisplayDuration,
                                      logger);

            // advertising playlist
            GetAdvertisingPlaylist(advertListPath,
                                   demographicDataPath,
                                   demographicRangeVerifier,
                                   password,
                                   playlist,
                                   channelData,
                                   channelSubscriptions,
                                   now,
                                   logger);

            Serializer.Serialize(playlist, playlistDataPath, password);

            return(playlist);
        }
        private void OnSavePlaylist(IEnumerable <TrackViewModel> tracks)
        {
            Playlist playlist = null;

            _openSynoSettings.Playlists.Add(playlist);
        }
Exemple #48
0
 public void PlayNext()
 {
     _current = Playlist.First();
     Playlist.Remove(_current);
 }
Exemple #49
0
 public override Playlist <TvgMedia> Sync(Playlist <TvgMedia> playlist)
 {
     throw new NotImplementedException();
 }
Exemple #50
0
 /// <summary>
 /// Gets the items for a playlist.
 /// </summary>
 /// <param name="playlist">The playlist to get items for</param>
 /// <param name="maxResults">The maximum results to return</param>
 /// <returns>The list of playlist items</returns>
 public async Task <IEnumerable <PlaylistItem> > GetPlaylistItems(Playlist playlist, int maxResults = 1)
 {
     Validator.ValidateVariable(playlist, "playlist");
     return(await this.GetPlaylistItems(playlist.Id, maxResults));
 }
Exemple #51
0
        public async Task <ApiResponse <CreatePlaylistFromListResponse> > CreateFromList([FromBody] CreatePlaylistFromListRequest request)
        {
            Playlist playlist;
            var      currentSongIds = new HashSet <int>();
            var      lastOrder      = 0;

            if (request.Id == 0)
            {
                if (string.IsNullOrWhiteSpace(request.Name))
                {
                    return(this.Error <CreatePlaylistFromListResponse>(
                               "Name",
                               "Please select the name of your new playlist."));
                }

                var name = request.Name.Trim();

                if (this.playlistsRepository.All().Any(x => x.Name == name && x.OwnerId == this.User.GetId()))
                {
                    return(this.Error <CreatePlaylistFromListResponse>(
                               "Name",
                               "You already have playlist with that name. Please select a different name."));
                }

                playlist = new Playlist {
                    Name = name, IsSystem = false, OwnerId = this.User.GetId()
                };
                this.playlistsRepository.Add(playlist);
            }
            else
            {
                playlist = this.playlistsRepository.All()
                           .FirstOrDefault(x => x.Id == request.Id && x.OwnerId == this.User.GetId());

                if (playlist == null)
                {
                    return(this.Error <CreatePlaylistFromListResponse>(
                               "Id",
                               "Playlist not found."));
                }

                currentSongIds = this.playlistsRepository.All().Where(x => x.Id == request.Id)
                                 .SelectMany(x => x.Songs.Select(s => s.SongId)).ToList().ToHashSet();
                if (currentSongIds.Count > 0)
                {
                    lastOrder = this.playlistsRepository.All().Where(x => x.Id == request.Id)
                                .Max(x => x.Songs.Max(s => s.Order));
                }
            }

            foreach (var songId in request.SongIds)
            {
                if (!currentSongIds.Contains(songId))
                {
                    playlist.Songs.Add(new PlaylistSong {
                        SongId = songId, Order = ++lastOrder
                    });
                    currentSongIds.Add(songId);
                }
            }

            await this.playlistsRepository.SaveChangesAsync();

            var response = new CreatePlaylistFromListResponse();

            return(response.ToApiResponse());
        }
Exemple #52
0
 private void DoOnPlaylistEnd(object sender, Playlist playlist)
 {
     Console.WriteLine("OnPlaylistEnd. --=" + playlist.PlaylistName + "=--");
     Console.WriteLine();
 }
        }//eom

        public void Add_TrackToPLaylist(string playlistname, string username, int trackid)
        {
            using (var context = new ChinookContext())
            {
                //use the BusinessRuleException to throw errors to the web page
                List <string> reasons     = new List <string>();
                PlaylistTrack newTrack    = null;
                int           tracknumber = 0;

                //Part One
                //determine if the playlist exists
                //query the table using the playlistname and username
                //if the playlist exist, one will get a record,
                //if the playlist does not exist, one will get a null
                //to ENSURE these results the query will be wrap in a .FirstOrDefault()
                //Playlist exists = context.Playlists
                //                    .Where(x => x.UserName.Equals(username, StringComparison.OrdinalIgnoreCase)
                //                             && x.Name.Equals(playlistname, StringComparison.OrdinalIgnoreCase))
                //                    .Select(x => x)
                //                    .FirstOrDefault();
                Playlist exists = (from x in context.Playlists
                                   where x.UserName.Equals(username, StringComparison.OrdinalIgnoreCase) &&
                                   x.Name.Equals(playlistname, StringComparison.OrdinalIgnoreCase)
                                   select x).FirstOrDefault();

                //does the playlist exist
                if (exists == null)
                {
                    //this is a new playlist
                    //create the Playlist record
                    exists          = new Playlist();
                    exists.Name     = playlistname;
                    exists.UserName = username;
                    //stage the add
                    exists = context.Playlists.Add(exists);
                    //since this is a new playlist
                    //the tracknumber will be 1
                    tracknumber = 1;
                }
                else
                {
                    //since the playlist exists, so may the track exist
                    //   on the playlisttracks
                    newTrack = exists.PlaylistTracks
                               .SingleOrDefault(x => x.TrackId == trackid);
                    if (newTrack == null)
                    {
                        tracknumber = exists.PlaylistTracks.Count() + 1;
                    }
                    else
                    {
                        reasons.Add("Track already exists on playlist");
                    }
                }

                //Part Two
                //create the PlaylistTrack entry
                //if there are any reasons NOT to create then
                //throw the BusinessRuleException
                if (reasons.Count() > 0)
                {
                    //issue with adding the track
                    throw new BusinessRuleException("Adding track to playlist",
                                                    reasons);
                }
                else
                {
                    //use the Playlist navigation to PlaylistTracks to
                    // do the add to PlaylistTracks
                    newTrack             = new PlaylistTrack();
                    newTrack.TrackId     = trackid;
                    newTrack.TrackNumber = tracknumber;

                    //how do I fill the PlayListID IF the playlist is brand new
                    //a brand new playlist DOES NOT YET have an id
                    //Note: the pkey for PlaylistID may not yet exist
                    //      using the navigation property on the PlayList entity
                    //      one can let HashSet handle the PlaylistId pkey value
                    //      to be be properly created on PlayList AND placed
                    //      correctly in the "child" record of PlaylistTracks

                    // what is wrong to the attempt:
                    //   newTrack.PlaylistId = exists.PlaylistId;
                    exists.PlaylistTracks.Add(newTrack);  //playlist track staging

                    //physically add any/all data to the database
                    //commit
                    context.SaveChanges();
                }
            }
        }//eom
Exemple #54
0
        /// <summary>
        /// Adds the common nodes.
        /// </summary>
        /// <returns>Task.</returns>
        public static void AddCommonNodes(BaseItem item, XmlWriter writer, ILibraryManager libraryManager, IUserManager userManager, IUserDataManager userDataRepo, IFileSystem fileSystem, IServerConfigurationManager config)
        {
            var writtenProviderIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            if (!string.IsNullOrEmpty(item.OfficialRating))
            {
                writer.WriteElementString("ContentRating", item.OfficialRating);
            }

            writer.WriteElementString("Added", item.DateCreated.ToLocalTime().ToString("G"));

            writer.WriteElementString("LockData", item.IsLocked.ToString(CultureInfo.InvariantCulture).ToLowerInvariant());

            if (item.LockedFields.Length > 0)
            {
                writer.WriteElementString("LockedFields", string.Join("|", item.LockedFields));
            }

            if (item.CriticRating.HasValue)
            {
                writer.WriteElementString("CriticRating", item.CriticRating.Value.ToString(UsCulture));
            }

            if (!string.IsNullOrEmpty(item.Overview))
            {
                writer.WriteElementString("Overview", item.Overview);
            }

            if (!string.IsNullOrEmpty(item.OriginalTitle))
            {
                writer.WriteElementString("OriginalTitle", item.OriginalTitle);
            }
            if (!string.IsNullOrEmpty(item.CustomRating))
            {
                writer.WriteElementString("CustomRating", item.CustomRating);
            }

            if (!string.IsNullOrEmpty(item.Name) && !(item is Episode))
            {
                writer.WriteElementString("LocalTitle", item.Name);
            }

            var forcedSortName = item.ForcedSortName;

            if (!string.IsNullOrEmpty(forcedSortName))
            {
                writer.WriteElementString("SortTitle", forcedSortName);
            }

            if (item.PremiereDate.HasValue)
            {
                if (item is Person)
                {
                    writer.WriteElementString("BirthDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
                }
                else if (!(item is Episode))
                {
                    writer.WriteElementString("PremiereDate", item.PremiereDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
                }
            }

            if (item.EndDate.HasValue)
            {
                if (item is Person)
                {
                    writer.WriteElementString("DeathDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
                }
                else if (!(item is Episode))
                {
                    writer.WriteElementString("EndDate", item.EndDate.Value.ToLocalTime().ToString("yyyy-MM-dd"));
                }
            }

            if (item.RemoteTrailers.Length > 0)
            {
                writer.WriteStartElement("Trailers");

                foreach (var trailer in item.RemoteTrailers)
                {
                    writer.WriteElementString("Trailer", trailer.Url);
                }

                writer.WriteEndElement();
            }

            if (item.ProductionLocations.Length > 0)
            {
                writer.WriteStartElement("Countries");

                foreach (var name in item.ProductionLocations)
                {
                    writer.WriteElementString("Country", name);
                }

                writer.WriteEndElement();
            }

            var hasDisplayOrder = item as IHasDisplayOrder;

            if (hasDisplayOrder != null && !string.IsNullOrEmpty(hasDisplayOrder.DisplayOrder))
            {
                writer.WriteElementString("DisplayOrder", hasDisplayOrder.DisplayOrder);
            }

            if (item.CommunityRating.HasValue)
            {
                writer.WriteElementString("Rating", item.CommunityRating.Value.ToString(UsCulture));
            }

            if (item.ProductionYear.HasValue && !(item is Person))
            {
                writer.WriteElementString("ProductionYear", item.ProductionYear.Value.ToString(UsCulture));
            }

            var hasAspectRatio = item as IHasAspectRatio;

            if (hasAspectRatio != null)
            {
                if (!string.IsNullOrEmpty(hasAspectRatio.AspectRatio))
                {
                    writer.WriteElementString("AspectRatio", hasAspectRatio.AspectRatio);
                }
            }

            if (!string.IsNullOrEmpty(item.PreferredMetadataLanguage))
            {
                writer.WriteElementString("Language", item.PreferredMetadataLanguage);
            }
            if (!string.IsNullOrEmpty(item.PreferredMetadataCountryCode))
            {
                writer.WriteElementString("CountryCode", item.PreferredMetadataCountryCode);
            }

            // Use original runtime here, actual file runtime later in MediaInfo
            var runTimeTicks = item.RunTimeTicks;

            if (runTimeTicks.HasValue)
            {
                var timespan = TimeSpan.FromTicks(runTimeTicks.Value);

                writer.WriteElementString("RunningTime", Math.Floor(timespan.TotalMinutes).ToString(UsCulture));
            }

            if (item.ProviderIds != null)
            {
                foreach (var providerKey in item.ProviderIds.Keys)
                {
                    var providerId = item.ProviderIds[providerKey];
                    if (!string.IsNullOrEmpty(providerId))
                    {
                        writer.WriteElementString(providerKey + "Id", providerId);
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(item.Tagline))
            {
                writer.WriteStartElement("Taglines");
                writer.WriteElementString("Tagline", item.Tagline);
                writer.WriteEndElement();
            }

            if (item.Genres.Length > 0)
            {
                writer.WriteStartElement("Genres");

                foreach (var genre in item.Genres)
                {
                    writer.WriteElementString("Genre", genre);
                }

                writer.WriteEndElement();
            }

            if (item.Studios.Length > 0)
            {
                writer.WriteStartElement("Studios");

                foreach (var studio in item.Studios)
                {
                    writer.WriteElementString("Studio", studio);
                }

                writer.WriteEndElement();
            }

            if (item.Tags.Length > 0)
            {
                writer.WriteStartElement("Tags");

                foreach (var tag in item.Tags)
                {
                    writer.WriteElementString("Tag", tag);
                }

                writer.WriteEndElement();
            }

            var people = libraryManager.GetPeople(item);

            if (people.Count > 0)
            {
                writer.WriteStartElement("Persons");

                foreach (var person in people)
                {
                    writer.WriteStartElement("Person");
                    writer.WriteElementString("Name", person.Name);
                    writer.WriteElementString("Type", person.Type);
                    writer.WriteElementString("Role", person.Role);

                    if (person.SortOrder.HasValue)
                    {
                        writer.WriteElementString("SortOrder", person.SortOrder.Value.ToString(UsCulture));
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }

            var boxset = item as BoxSet;

            if (boxset != null)
            {
                AddLinkedChildren(boxset, writer, "CollectionItems", "CollectionItem");
            }

            var playlist = item as Playlist;

            if (playlist != null && !Playlist.IsPlaylistFile(playlist.Path))
            {
                AddLinkedChildren(playlist, writer, "PlaylistItems", "PlaylistItem");
            }

            var hasShares = item as IHasShares;

            if (hasShares != null)
            {
                AddShares(hasShares, writer);
            }

            AddMediaInfo(item, writer);
        }
Exemple #55
0
 private void onPlaylistChanged(object sender, NotifyCollectionChangedEventArgs e) =>
 playlistLength.Text = $"Length: {Playlist.GetTotalDuration()}";
Exemple #56
0
            private void load(OsuColour colours)
            {
                InternalChildren = new Drawable[]
                {
                    new Box
                    {
                        RelativeSizeAxes = Axes.Both,
                        Colour           = Color4Extensions.FromHex(@"28242d"),
                    },
                    new GridContainer
                    {
                        RelativeSizeAxes = Axes.Both,
                        RowDimensions    = new[]
                        {
                            new Dimension(GridSizeMode.Distributed),
                            new Dimension(GridSizeMode.AutoSize),
                        },
                        Content = new[]
                        {
                            new Drawable[]
                            {
                                new OsuScrollContainer
                                {
                                    Padding = new MarginPadding
                                    {
                                        Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING,
                                        Vertical   = 10
                                    },
                                    RelativeSizeAxes = Axes.Both,
                                    Children         = new[]
                                    {
                                        new Container
                                        {
                                            Padding = new MarginPadding {
                                                Horizontal = WaveOverlayContainer.WIDTH_PADDING
                                            },
                                            RelativeSizeAxes = Axes.X,
                                            AutoSizeAxes     = Axes.Y,
                                            Children         = new Drawable[]
                                            {
                                                new SectionContainer
                                                {
                                                    Padding = new MarginPadding {
                                                        Right = FIELD_PADDING / 2
                                                    },
                                                    Children = new[]
                                                    {
                                                        new Section("Room name")
                                                        {
                                                            Child = NameField = new SettingsTextBox
                                                            {
                                                                RelativeSizeAxes         = Axes.X,
                                                                TabbableContentContainer = this,
                                                                LengthLimit = 100
                                                            },
                                                        },
                                                        new Section("Duration")
                                                        {
                                                            Child = DurationField = new DurationDropdown
                                                            {
                                                                RelativeSizeAxes = Axes.X,
                                                                Items            = new[]
                                                                {
                                                                    TimeSpan.FromMinutes(30),
                                                                    TimeSpan.FromHours(1),
                                                                    TimeSpan.FromHours(2),
                                                                    TimeSpan.FromHours(4),
                                                                    TimeSpan.FromHours(8),
                                                                    TimeSpan.FromHours(12),
                                                                    //TimeSpan.FromHours(16),
                                                                    TimeSpan.FromHours(24),
                                                                    TimeSpan.FromDays(3),
                                                                    TimeSpan.FromDays(7)
                                                                }
                                                            }
                                                        },
                                                        new Section("Room visibility")
                                                        {
                                                            Alpha = disabled_alpha,
                                                            Child = AvailabilityPicker = new RoomAvailabilityPicker
                                                            {
                                                                Enabled = { Value = false }
                                                            },
                                                        },
                                                        new Section("Game type")
                                                        {
                                                            Alpha = disabled_alpha,
                                                            Child = new FillFlowContainer
                                                            {
                                                                AutoSizeAxes     = Axes.Y,
                                                                RelativeSizeAxes = Axes.X,
                                                                Direction        = FillDirection.Vertical,
                                                                Spacing          = new Vector2(7),
                                                                Children         = new Drawable[]
                                                                {
                                                                    TypePicker = new GameTypePicker
                                                                    {
                                                                        RelativeSizeAxes = Axes.X,
                                                                        Enabled          = { Value = false }
                                                                    },
                                                                    typeLabel = new OsuSpriteText
                                                                    {
                                                                        Font   = OsuFont.GetFont(size: 14),
                                                                        Colour = colours.Yellow
                                                                    },
                                                                },
                                                            },
                                                        },
                                                        new Section("Max participants")
                                                        {
                                                            Alpha = disabled_alpha,
                                                            Child = MaxParticipantsField = new SettingsNumberTextBox
                                                            {
                                                                RelativeSizeAxes         = Axes.X,
                                                                TabbableContentContainer = this,
                                                                ReadOnly = true,
                                                            },
                                                        },
                                                        new Section("Password (optional)")
                                                        {
                                                            Alpha = disabled_alpha,
                                                            Child = new SettingsPasswordTextBox
                                                            {
                                                                RelativeSizeAxes         = Axes.X,
                                                                TabbableContentContainer = this,
                                                                ReadOnly = true,
                                                            },
                                                        },
                                                    },
                                                },
                                                new SectionContainer
                                                {
                                                    Anchor  = Anchor.TopRight,
                                                    Origin  = Anchor.TopRight,
                                                    Padding = new MarginPadding {
                                                        Left = FIELD_PADDING / 2
                                                    },
                                                    Children = new[]
                                                    {
                                                        new Section("Playlist")
                                                        {
                                                            Child = new GridContainer
                                                            {
                                                                RelativeSizeAxes = Axes.X,
                                                                Height           = 300,
                                                                Content          = new[]
                                                                {
                                                                    new Drawable[]
                                                                    {
                                                                        playlist = new DrawableRoomPlaylist(true, true)
                                                                        {
                                                                            RelativeSizeAxes = Axes.Both
                                                                        }
                                                                    },
                                                                    new Drawable[]
                                                                    {
                                                                        playlistLength = new OsuSpriteText
                                                                        {
                                                                            Margin = new MarginPadding {
                                                                                Vertical = 5
                                                                            },
                                                                            Colour = colours.Yellow,
                                                                            Font   = OsuFont.GetFont(size: 12),
                                                                        }
                                                                    },
                                                                    new Drawable[]
                                                                    {
                                                                        new PurpleTriangleButton
                                                                        {
                                                                            RelativeSizeAxes = Axes.X,
                                                                            Height           = 40,
                                                                            Text             = "Edit playlist",
                                                                            Action           = () => EditPlaylist?.Invoke()
                                                                        }
                                                                    }
                                                                },
                                                                RowDimensions = new[]
                                                                {
                                                                    new Dimension(),
                                                                    new Dimension(GridSizeMode.AutoSize),
                                                                    new Dimension(GridSizeMode.AutoSize),
                                                                }
                                                            }
                                                        },
                                                    },
                                                },
                                            },
                                        }
                                    },
                                },
                            },
                            new Drawable[]
                            {
                                new Container
                                {
                                    Anchor           = Anchor.BottomLeft,
                                    Origin           = Anchor.BottomLeft,
                                    Y                = 2,
                                    RelativeSizeAxes = Axes.X,
                                    AutoSizeAxes     = Axes.Y,
                                    Children         = new Drawable[]
                                    {
                                        new Box
                                        {
                                            RelativeSizeAxes = Axes.Both,
                                            Colour           = Color4Extensions.FromHex(@"28242d").Darken(0.5f).Opacity(1f),
                                        },
                                        new FillFlowContainer
                                        {
                                            RelativeSizeAxes = Axes.X,
                                            AutoSizeAxes     = Axes.Y,
                                            Direction        = FillDirection.Vertical,
                                            Spacing          = new Vector2(0, 20),
                                            Margin           = new MarginPadding {
                                                Vertical = 20
                                            },
                                            Padding = new MarginPadding {
                                                Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING
                                            },
                                            Children = new Drawable[]
                                            {
                                                ApplyButton = new CreateRoomButton
                                                {
                                                    Anchor  = Anchor.BottomCentre,
                                                    Origin  = Anchor.BottomCentre,
                                                    Size    = new Vector2(230, 55),
                                                    Enabled = { Value = false },
                                                    Action  = apply,
                                                },
                                                ErrorText = new OsuSpriteText
                                                {
                                                    Anchor = Anchor.BottomCentre,
                                                    Origin = Anchor.BottomCentre,
                                                    Alpha  = 0,
                                                    Depth  = 1,
                                                    Colour = colours.RedDark
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    loadingLayer = new LoadingLayer(true)
                };

                TypePicker.Current.BindValueChanged(type => typeLabel.Text = type.NewValue?.Name ?? string.Empty, true);
                RoomName.BindValueChanged(name => NameField.Text           = name.NewValue, true);
                Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true);
                Type.BindValueChanged(type => TypePicker.Current.Value = type.NewValue, true);
                MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true);
                Duration.BindValueChanged(duration => DurationField.Current.Value   = duration.NewValue ?? TimeSpan.FromMinutes(30), true);

                playlist.Items.BindTo(Playlist);
                Playlist.BindCollectionChanged(onPlaylistChanged, true);
            }
        internal async void PlayStarted(PlaylistItem item)
        {
            if (item == null)
            {
                throw new Exception();
            }

            using (var releaser = await _PlaylistUpdateLock.LockAsync())
            {
                // 新たにプレイリストが指定された場合に
                // 連続再生をセットアップする
                if (item.Owner != null)
                {
                    if (item.Owner != Playlist)
                    {
                        Playlist = item.Owner;
                    }
                }

                SourceItems.Clear();
                foreach (var newItem in Playlist.Select(x => new PlaylistItem()
                {
                    ContentId = x,
                    Owner = Playlist,
                    Type = PlaylistItemType.Video,
                }))
                {
                    SourceItems.Add(newItem);
                }

                RaisePropertyChanged(nameof(CanGoBack));
                RaisePropertyChanged(nameof(CanGoNext));
                //                Current = SourceItems.First(x => item.ContentId == x.ContentId);

                // GoNext/GoBack内でCurrentが既に変更済みの場合はスキップ
                // Playlist外から直接PlaylistItemが変更された場合にのみ
                // 現在再生位置の更新を行う
                if (Current != item)
                {
                    Current = item;
                    if (SourceItems != null)
                    {
                        CurrentIndex = PlaylistSettings.IsShuffleEnable ? 0 : SourceItems.IndexOf(Current);
                    }
                    else
                    {
                        CurrentIndex = 0;
                    }

                    // ランダム再生かつ先頭の再生を行う場合は
                    // ランダムアイテムの先頭が現在再生中アイテムになるように
                    // ランダムアイテムリストを修正する
                    // この修正によって、シャッフル再生が先頭しか再生されない問題を回避できる
                    if (CurrentIndex == 0 && PlaylistSettings.IsShuffleEnable)
                    {
                        if (RandamizedItems.FirstOrDefault() != Current)
                        {
                            RandamizedItems.Remove(Current);
                            RandamizedItems.Insert(0, Current);
                        }
                    }
                }
            }
        }
Exemple #58
0
        private async Task <bool> ParseLaunchArgument(LaunchActivatedEventArgs e)
        {
            string[] param = e.Arguments.Split(':');

            string type = param[0];
            string guid = param[1];

            object kvp = null;

            Task t = MusicLibrary.Instance.LoadCache(Window.Current.Dispatcher);

            if (t != null)
            {
                await t;
            }
            //Load playlists as well
            PlaylistManager manager = PlaylistManager.Instance;

            if (type == "Artist")
            {
                Artist artist = MusicLibrary.Instance.GetArtist(new Guid(guid));

                kvp = artist;
            }
            else if (type == "Album")
            {
                Album album = MusicLibrary.Instance.GetAlbum(new Guid(guid));

                kvp = album;
            }
            else if (type == "Playlist")
            {
                Playlist playlist = PlaylistManager.Instance.GetPlaylist(new Guid(guid));

                if (playlist == null)
                {
                    return(false);
                }

                kvp = new KeyValuePair <Playlist, int>(playlist, 0);
            }

            if (kvp == null)
            {
                return(false);
            }

            if (e.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                Window.Current.Content = null;
            }

            Frame rootFrame = new Frame();

            Window.Current.Content = rootFrame;
            if (!rootFrame.Navigate(typeof(NowPlaying), kvp))
            {
                return(false);
            }

            return(true);
        }
Exemple #59
0
 public void LoadPlaylists()
 {
     PlaylistA = GetPlaylistFor(MusicTestsDataObjectsValues.PlaylistA);
     PlaylistB = GetPlaylistFor(MusicTestsDataObjectsValues.PlaylistB);
     PlaylistC = GetPlaylistFor(MusicTestsDataObjectsValues.PlaylistC);
 }
Exemple #60
-1
        public Player()
        {
            // Initialization (TODO: Make all the stuff configurable, of course)
            Playlist = new Playlist();
            PlayedHistory = new List<Song>();
            totalHistory = new List<Song>();
            Queue = new List<Song>();
            RandomSettings = new PlayerRandomSettings(100, true);
            PlaybackState = TP_PLAYBACKSTATE.Stopped;
            playbackMode = TP_PLAYBACKMODE.Playlist;
            playbackDirection = TP_PLAYBACKDIRECTION.Forward;
            PlaybackLoggingMode = TP_PLAYBACKLOG.After80Percent;
            historyPosition = -1;

            // VLC Initialization
            string[] args = new string[] {
                "--ignore-config",
                @"--plugin-path=C:\Program Files (x86)\VideoLAN\VLC\plugins",
                //,"--vout-filter=deinterlace", "--deinterlace-mode=blend"
            };

            instance = new VlcInstance(args);
            vlc = null;
            factory = new MediaPlayerFactory();
            /*vlc = factory.CreatePlayer<IVideoPlayer>();
            vlc.Events.MediaEnded += new EventHandler(Events_MediaEnded);
            vlc.Events.TimeChanged += new EventHandler<Declarations.Events.MediaPlayerTimeChanged>(Events_TimeChanged);
            vlc.Events.PlayerPlaying += new EventHandler(Events_PlayerPlaying);*/
        }