void OnResultSimilarClicked(object sender, EventArgs <SearchResult> e)
 {
     searchQuery   = null;
     searchRelated = null;
     UiUtility.ClearContainer <ResultView>(uiResults);
     uiLeftTabs.SelectedIndex = TabIndexSuggestions;
     Library.ClearOpenSuggestions();
     UiUtility.ClearContainer <ResultView>(uiSuggestions);
     SuggestionScanner.SearchSimilar(e.Data.Title, HandleSuggestions);
 }
        void OnMainWindowShown(object sender, EventArgs e)
        {
            if (DesignMode)
            {
                return;
            }
            var app = AppSettings.Instance;

            InitializeLog();
            SearchEngine.Initialize(app.Providers.Keys.Where(k => app.Providers[k].Enabled));
            string[] stopList = File.ReadAllLines(AppSettings.StopListPath)
                                .Select(s => s.Trim())
                                .Where(s => !string.IsNullOrWhiteSpace(s))
                                .ToArray();
            Library.Initialize(AppSettings.GetFolderPath(), stopList);
            InitializeSettings();
            Playlist.Initialize();
            DownloadQueue.Initialize();
            PostProcessingQueue.Initialize();
            uiDownloadQueue.Initialize(DownloadQueue.Instance);
            uiPostProcessingQueue.Initialize(PostProcessingQueue.Instance);
            Action <QueueItem> enqueue = r => uiPostProcessingQueue.Enqueue(r.NewId());

            DownloadQueue.Instance.Completed += (s, evt) => BeginInvoke(new Action(() => enqueue(evt.Data)));
            if (app.UpdateLibraryAfterDownload)
            {
                PostProcessingQueue.Instance.Completed += (s, evt) => LibraryScanner.UpdateLibrary();
            }
            uiCurrentResult.SetResult(UiSettings.Instance.CurrentTrack);
            StartSearch();
            DownloadQueue.Start();
            PostProcessingQueue.Start();
            InitializePlaylist();
            InitializeSuggestions();
            SuggestionScanner.Suggested += OnScannerSuggestions;
            SuggestionScanner.Start(app.DelaySuggestionsScan, app.ScanSuggestionsInterval);
            LibraryScanner.Start(UserSettings.Instance.LibraryFolder, app.TagSeparator, app.DelayLibraryScan, app.ScanLibraryInterval);
            ShowScrollBar(uiResults.Handle, SbVert, true);
            ShowScrollBar(uiPlaylist.Handle, SbVert, true);
            initializing = false;
        }
Example #3
0
        void InitializeSettings()
        {
            var ui = UiSettings.Instance;

            this.WithLayoutSuspended(() => {
                uiQuery.Text                  = ui.LastSearch;
                uiLogLevel.SelectedItem       = ui.TraceLevel;
                uiSearchLocalOnly.Checked     = ui.SearchLocalOnly;
                uiSearchFavouriteOnly.Checked = ui.SearchFavouritesOnly;
                ToggleFullScreen(ui.FullScreen);
                ToggleLog(UiSettings.Instance.LogCollapsed);
                TogglePlayerFull(UiSettings.Instance.PlayerFull);
                ToggleSearch(UiSettings.Instance.SearchCollapsed);
                ToggleNotifications(UiSettings.Instance.NotificationsCollapsed);
                ToggleCurrentControls(UiSettings.Instance.CurrentControlsCollapsed);
            });
            if (ui.CurrentTrack != null)
            {
                uiBrowser.IsBrowserInitializedChanged += (s, e) => {
                    if (e.IsBrowserInitialized)
                    {
                        BeginInvoke(new Action(() => LoadResult(ui.CurrentTrack, false)));
                    }
                }
            }
            ;
        }

        void InitializeLog()
        {
            logger        = new StreamWriter(AppSettings.LogFilePath, false);
            Logger.Trace += (s, e) => WriteLog(e.Level, e.Message);
            Logger.Trace += (s, e) => {
                lock (shutdownLock) {
                    string now = DateTime.Now.ToLongTimeString();
                    if (!shutdown)
                    {
                        logger.WriteLine(string.Format("{0}: {1}: {2}.", now, e.Level, e.Message));
                        if (e.Level == LogLevel.Error)
                        {
                            logger.Flush();
                        }
                    }
                }
            };
        }

        void InitializeSuggestions()
        {
            this.WithLayoutSuspended(() => {
                foreach (var s in Library.GetOpenSuggestions())
                {
                    AddToResultsViews(uiSuggestions, SuggestionScanner.SuggestionToSearchResult(s), ResultViewType.Suggestion);
                }
            });
        }

        void InitializePlaylist()
        {
            Playlist.Instance.Next += OnPlaylistNext;
            this.WithLayoutSuspended(() => {
                uiPlaylistModeAll.Checked    = Playlist.Instance.Mode == PlaylistMode.RepeatAll;
                uiPlaylistModeRandom.Checked = Playlist.Instance.Mode == PlaylistMode.Random;
                uiPlaylistModeTrack.Checked  = Playlist.Instance.Mode == PlaylistMode.RepeatTrack;
                foreach (var item in Playlist.Instance.Items)
                {
                    AddToResultsViews(uiPlaylist, item, ResultViewType.Playlist);
                }
            });
        }

        void WriteLog(LogLevel level, string text)
        {
            BeginInvoke(new Action(() => {
                if (level < (LogLevel)uiLogLevel.SelectedItem)
                {
                    return;
                }
                var line    = DateTime.Now.ToLongTimeString() + ": ";
                line       += level + ": " + text + Environment.NewLine;
                var newText = uiLog.Text + line;
                if (newText.Length > 10000)
                {
                    newText = newText.Substring(newText.Length - 10000);
                }
                uiLog.Text           = newText;
                uiLog.SelectionStart = uiLog.TextLength;
                uiLog.ScrollToCaret();
            }));
        }

        void AddToPlaylist(SearchResult result)
        {
            if (Playlist.Instance.Add(result))
            {
                AddToResultsViews(uiPlaylist, result, ResultViewType.Playlist);
            }
        }

        void ReplacePlaylist(FlowLayoutPanel container)
        {
            Playlist.Instance.Clear();
            this.WithLayoutSuspended(() => {
                UiUtility.ClearContainer <ResultView>(uiPlaylist);
                foreach (var view in container.Controls)
                {
                    AddToPlaylist(((ResultView)view).Result);
                }
                uiLeftTabs.SelectedIndex = TabIndexPlaylist;
            });
            Playlist.Instance.Start();
        }

        ResultView AddToResultsViews(FlowLayoutPanel container, SearchResult result, ResultViewType type)
        {
            var view = new ResultView(type);

            ConnectResultViewEventHandlers(view);
            container.Controls.Add(view);
            view.SetResult(result);
            return(view);
        }

        void AppendResults(SearchResponse response)
        {
            if (response.Error != null)
            {
                Logger.Error(response.Error, "Search error.");
            }
            else
            {
                BeginInvoke(new Action(() => {
                    this.WithLayoutSuspended(() => {
                        foreach (SearchResult result in response.Results)
                        {
                            var view = AddToResultsViews(uiResults, result, ResultViewType.Search);
                            if (AppSettings.Instance.ScrollToEndOnMoreResults)
                            {
                                appendingResult = true;
                                uiResults.ScrollControlIntoView(view);
                                appendingResult = false;
                            }
                        }
                    });
                }));
            }
        }

        void StartSearch()
        {
            var ui = UiSettings.Instance;

            UiUtility.ClearContainer <ResultView>(uiResults);
            searchRelated = null;
            searchQuery   = uiQuery.Text.Trim();
            UiSettings.Instance.LastSearch = searchQuery;
            var pageSize    = AppSettings.Instance.SearchPageSize;
            var credentials = UserSettings.Instance.Credentials;
            var query       = new SearchQuery(credentials, searchQuery, ui.SearchFavouritesOnly, ui.SearchLocalOnly ? true : (bool?)null, pageSize);

            searchState = SearchEngine.Start(query, AppendResults);
        }

        void PlayResult(SearchResult result)
        {
            AddToPlaylist(result);
            Playlist.Instance.Start();
            Playlist.Instance.Play(result);
            SetPlaylistPlaying(result);
        }

        void SetPlaylistPlaying(SearchResult result)
        {
            this.WithLayoutSuspended(() => {
                foreach (ResultView view in uiPlaylist.Controls)
                {
                    view.SetPlaying(false);
                    if (result != null && view.Result.TypeId.Equals(result.TypeId) && view.Result.VideoId.Equals(result.VideoId))
                    {
                        view.SetPlaying(true);
                    }
                }
            });
        }

        void LoadResult(SearchResult result, bool start)
        {
            try {
                uiPlayer.Ctlcontrols.stop();
            } catch (AxHost.InvalidActiveXStateException) {
            }
            uiBrowser.Load(AppSettings.EmptyHtmlFilePath);
            if (result == null)
            {
                return;
            }
            uiCurrentResult.SetResult(result);
            uiSplitBrowserPlayer.Panel1Collapsed = false;
            uiSplitBrowserPlayer.Panel2Collapsed = false;
            if (result == null)
            {
                return;
            }
            UiSettings.Instance.CurrentTrack = result;
            Logger.Debug("Loading {0} ({1}: {2}) in player.", result.Title, result.TypeId, result.VideoId);
            if (result.Local)
            {
                LoadLocalResult(result, start);
            }
            else
            {
                LoadWebResult(result, start);
            }
        }

        void LoadLocalResult(SearchResult result, bool start)
        {
            uiSplitBrowserPlayer.Panel1Collapsed = true;
            uiPlayer.URL = result.VideoId;
            if (start)
            {
                uiPlayer.Ctlcontrols.play();
            }
            else
            {
                uiPlayer.Ctlcontrols.stop();
            }
        }

        void LoadWebResult(SearchResult result, bool start)
        {
            startPlaying = start;
            var provider = AppSettings.GetProvider(result.TypeId);

            uiSplitBrowserPlayer.Panel2Collapsed = true;
            uiBrowser.RequestHandler             = new RefererRequestHandler(provider.HttpReferer);
            uiBrowser.Load(provider.GetEmbedFilePath());
        }

        void LoadMoreResults()
        {
            var ui     = UiSettings.Instance;
            var typeId = searchRelated?.TypeId;
            SearchCredentials searchCredentials = null;
            var pageSize    = AppSettings.Instance.SearchPageSize;
            var credentials = UserSettings.Instance.Credentials;

            if (typeId != null)
            {
                credentials.TryGetValue(typeId, out searchCredentials);
            }
            SearchQuery q = searchRelated == null ?
                            new SearchQuery(credentials, searchQuery, ui.SearchFavouritesOnly, ui.SearchLocalOnly ? true : (bool?)null, pageSize) :
                            new SearchQuery(typeId, searchCredentials, searchRelated.VideoId, pageSize);

            SearchEngine.Continue(q, searchState, AppendResults);
        }

        void ConnectResultViewEventHandlers(ResultView view)
        {
            view.PlayClicked      += OnResultPlayClicked;
            view.QueueClicked     += OnResultQueueClicked;
            view.RelatedClicked   += OnResultRelatedClicked;
            view.SimilarClicked   += OnResultSimilarClicked;
            view.FavouriteChanged += OnResultFavouriteChanged;
            if (view.Type != ResultViewType.Suggestion)
            {
                view.DownloadClicked += OnResultDownloadClicked;
            }
            else
            {
                view.DownloadClicked += (s, e) => AcceptSuggestion(view);
            }
            if (view.Type == ResultViewType.Playlist)
            {
                view.RemoveClicked += (s, e) => RemoveFromPlaylist(view);
            }
            if (view.Type == ResultViewType.Suggestion)
            {
                view.RemoveClicked += (s, e) => DeclineSuggestion(view);
            }
        }

        void RemoveFromPlaylist(ResultView view)
        {
            view.Dispose();
            uiPlaylist.Controls.Remove(view);
            Playlist.Instance.Remove(view.Result);
        }

        void AcceptSuggestion(ResultView view)
        {
            Library.HandleSuggestion(view.Result.TypeId, view.Result.VideoId, true);
            view.Dispose();
            uiSuggestions.Controls.Remove(view);
            DownloadResult(view.Result);
        }

        void DeclineSuggestion(ResultView view)
        {
            Library.HandleSuggestion(view.Result.TypeId, view.Result.VideoId, false);
            view.Dispose();
            uiSuggestions.Controls.Remove(view);
        }

        void DownloadResult(SearchResult result)
        {
            uiDownloadQueue.Enqueue(new QueueItem(result));
        }

        void HandleSuggestions(SearchResponse response)
        {
            BeginInvoke(new Action(() => {
                this.WithLayoutSuspended(() => {
                    if (response.Results != null)
                    {
                        foreach (var result in response.Results)
                        {
                            AddToResultsViews(uiSuggestions, result, ResultViewType.Suggestion);
                        }
                    }
                });
            }));
        }

        void ToggleFullScreen(bool fullScreen)
        {
            if (fullScreen)
            {
                TopMost                 = true;
                WindowState             = FormWindowState.Normal;
                FormBorderStyle         = FormBorderStyle.None;
                WindowState             = FormWindowState.Maximized;
                uiToggleFullScreen.Text = UnicodeBlackLowerLeftTriangle;
            }
            else
            {
                TopMost                 = false;
                WindowState             = FormWindowState.Maximized;
                FormBorderStyle         = FormBorderStyle.Sizable;
                uiToggleFullScreen.Text = UnicodeBlackUpperRightTriangle;
            }
        }

        void TogglePlayerFull(bool full)
        {
            var ui = UiSettings.Instance;

            ToggleSearch(ui.SearchCollapsed);
            ToggleNotifications(ui.NotificationsCollapsed);
            ToggleCurrentControls(ui.CurrentControlsCollapsed);
            uiToggleSearch.Visible               = !full;
            uiToggleNotifications.Visible        = !full;
            uiToggleCurrentControls.Visible      = !full;
            uiBrowserPlayerContainer.BorderStyle = full ? BorderStyle.None : BorderStyle.FixedSingle;
            uiTogglePlayerFull.Text              = full ? UnicodeWhiteLowerLeftTriangle : UnicodeWhiteUpperRightTriangle;
        }

        void ToggleLog(bool collapsed)
        {
            bool realCollapsed = collapsed || Width < ShowLogMinWidth;

            uiToggleLog.Text = realCollapsed ? UnicodeBlackLeftPointingTriangle : UnicodeBlackRightPointingTriangle;
            uiSplitNotificationsLog.Panel2Collapsed = realCollapsed;
        }

        void ToggleSearch(bool collapsed)
        {
            bool realCollapsed = collapsed || UiSettings.Instance.PlayerFull;

            uiToggleSearch.Text           = realCollapsed ? UnicodeBlackRightPointingTriangle : UnicodeBlackLeftPointingTriangle;
            uiSplitSearch.Panel1Collapsed = realCollapsed;
        }

        void ToggleNotifications(bool collapsed)
        {
            bool realCollapsed = collapsed || UiSettings.Instance.PlayerFull;

            uiToggleNotifications.Text           = realCollapsed ? UnicodeBlackUpPointingTriangle : UnicodeBlackDownPointingTriangle;
            uiSplitNotifications.Panel2Collapsed = realCollapsed;
        }

        void ToggleCurrentControls(bool collapsed)
        {
            bool realCollapsed = collapsed || UiSettings.Instance.PlayerFull;

            uiToggleCurrentControls.Text = realCollapsed ? UnicodeBlackDownPointingTriangle : UnicodeBlackUpPointingTriangle;
            uiSplitBrowserCurrentControls.Panel1Collapsed = realCollapsed;
        }
    }
 void OnSuggestionsSearchMoreClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     SuggestionScanner.UpdateSuggestions(uiSuggestionsFromLocation.SelectedItem.ToString());
 }