Browse Source

Базовая реализация очереди

Вадим Королёв 1 year ago
parent
commit
defb70341e
5 changed files with 58 additions and 8 deletions
  1. 20 2
      src/YTMPV/MainWindow.cpp
  2. 4 0
      src/YTMPV/MainWindow.hpp
  3. 26 3
      src/YTMPV/core.cpp
  4. 7 1
      src/YTMPV/core.hpp
  5. 1 2
      src/YTMPV/ytmpv.cpp

+ 20 - 2
src/YTMPV/MainWindow.cpp

@@ -40,6 +40,7 @@ namespace components {
         auto video_list = m_builder->get_widget<Gtk::ListView>("videoList");
         auto search_button = m_builder->get_widget<Gtk::Button>("searchButton");
         auto start_search_button = m_builder->get_widget<Gtk::Button>("startSearchButton");
+        auto queue_play_button = m_builder->get_widget<Gtk::Button>("queuePlay");
         m_search_body = m_builder->get_widget<Gtk::Paned>("searchBody");
         m_search_entry = m_builder->get_widget<Gtk::Entry>("searchEntry");
         m_start_search_entry = m_builder->get_widget<Gtk::Entry>("startSearchEntry");
@@ -54,6 +55,7 @@ namespace components {
         assert(m_start_search_entry != nullptr);
         assert(m_stackswitcher != nullptr);
         assert(m_body != nullptr);
+        assert(queue_play_button != nullptr);
         
         // -- Создание модели выбора видео в поиске --
         m_video_storage = Gio::ListStore<components::VideoModel>::create();
@@ -101,6 +103,10 @@ namespace components {
         m_rate_like_btn->signal_clicked().connect(sigc::bind(
             sigc::mem_fun(*this, &MainWindow::onRateButtonClicked),
             RateButtonParams { core::VideoRating::LIKE } ));
+
+        // Кнопки очереди
+        queue_play_button->signal_clicked().connect(
+            sigc::mem_fun(*this, &MainWindow::onQueueButtonClick));
     }
 
     void MainWindow::searchVideoByQuery(Glib::ustring query)
@@ -306,18 +312,25 @@ namespace components {
 
     void MainWindow::playSingleVideo(std::string ytid)
     {
+        // Создать процесс для проигрывания видео
         Glib::spawn_async(
             "",
-            m_appcore->getMPVLaunchParams(ytid),
+            m_appcore->getMPVLaunchParams(m_appcore->getYTLink(ytid)),
             Glib::SpawnFlags::DEFAULT
         );
     }
 
     void MainWindow::playQueue()
     {
+        // Создаётся файл .m3u в который помещаются все видео очереди
+        // Затем mpv открывает этот файл и проигрывает
+
+        m_appcore->createQueuePlaylist();
+        std::string playlist_path = m_appcore->getQueueFilePath();
+
         Glib::spawn_async(
             "",
-            m_appcore->getMPVLaunchParams(m_appcore->getQueueYTIDs()),
+            m_appcore->getMPVLaunchParams(playlist_path),
             Glib::SpawnFlags::DEFAULT
         );
     }
@@ -515,4 +528,9 @@ namespace components {
         auto queue_container = m_builder->get_widget<Gtk::Box>("queue");
         queue_container->set_visible(visible);
     }
+
+    void MainWindow::onQueueButtonClick()
+    {
+        playQueue();
+    }
 }

+ 4 - 0
src/YTMPV/MainWindow.hpp

@@ -82,6 +82,8 @@ namespace components {
         // --События--
         // Клик кнопки поиска
         void onSearchButtonClicked();
+        // Клик кнопки проигрывания очереди
+        void onQueueButtonClick();
         // Клик кнопки поиска на стартовой странице
         void onStartSearchButtonClicked();
         // При создании элемента в m_video_list
@@ -130,6 +132,8 @@ namespace components {
 
         // Проигрывает конкретное видео
         void playSingleVideo(std::string yt_id);
+        // Проигрывает очередь видео
+        void playQueue();
         // Открывает страницу видео в YouTube
         void openVideoInWebBrowser(std::string yt_id);
         // Обновляет текущие переменные при просмотре информации о видео

+ 26 - 3
src/YTMPV/core.cpp

@@ -2,6 +2,7 @@
 #include <nlohmann/json.hpp>
 #include <Database/database.hpp>
 #include <iomanip>
+#include <glibmm.h>
 
 using json = nlohmann::json;
 
@@ -104,15 +105,15 @@ namespace core {
         /*ytapi::setVideoRating(ytid, static_cast<int>(rating), m_client_secret);*/
     }
 
-    std::vector<std::string> Core::getMPVLaunchParams(std::string ytid)
+    std::vector<std::string> Core::getMPVLaunchParams(std::string target)
     {
         std::vector<std::string> output;
 
         // Путь до MPV
         output.push_back(m_mpvpath);
 
-        // Ссылка на видео
-        output.push_back(getYTLink(ytid));
+        // Ссылка на видео/плейлист очереди
+        output.push_back(target);
 
         // Без терминала
         output.push_back("--no-terminal");
@@ -265,4 +266,26 @@ namespace core {
     {
         m_queue.push_back(ytid);
     }
+
+    void Core::createQueuePlaylist()
+    {
+        // 1. Получаем путь до файла
+        std::string path = getQueueFilePath();
+
+        // 2. Открываем файл
+        std::ofstream queue_file(path);
+
+        // 3. Для каждого элемента в очереди создаётся строка с youtube ссылкой
+        for (std::string video : m_queue) {
+            queue_file << getYTLink(video) << '\n';
+        }
+    }
+
+    std::string Core::getQueueFilePath()
+    {
+        return Glib::build_filename(
+            Glib::get_user_config_dir(),
+            "ytmpv",
+            "queue.m3u");
+    }
 }

+ 7 - 1
src/YTMPV/core.hpp

@@ -87,6 +87,9 @@ namespace core
 
             // Возвращает режим запуска поверх других окон
             bool getOnTop();
+
+            // Возвращает путь до файла плейлиста очереди
+            std::string getQueueFilePath();
             //}
 
             // Сохраняет настройки в файл по пути m_config_path
@@ -105,7 +108,7 @@ namespace core
             void rateVideo(std::string ytid, VideoRating rating);
             
             // Возвращает параметры запуска MPV
-            std::vector<std::string> getMPVLaunchParams(std::vector<std::string> videos);
+            std::vector<std::string> getMPVLaunchParams(std::string target);
 
             // Возвращает ссылку на видео по его ytid
             std::string getYTLink(std::string ytid);
@@ -128,6 +131,9 @@ namespace core
             // Добавляет видео в очередь
             void addVideoToQueue(std::string ytid);
 
+            // Создаёт файл .m3u и помещает в него текущую очередь
+            void createQueuePlaylist();
+
         protected:
             // ключ API
             std::string m_apikey;

+ 1 - 2
src/YTMPV/ytmpv.cpp

@@ -10,10 +10,9 @@
 
 // TODO:
 /*
- * 1. Окно настройки
  * 2. oAuth
  * 3. Оценка видео
- * 4. Проверка подключения (curl возвращает пустые строки json)
+ * 5. Отследить файл очереди и восстановить
 */
 
 using json = nlohmann::json;