浏览代码

Первый рабочий прототип

Вадим Королёв 1 年之前
父节点
当前提交
4c96d03e93

+ 86 - 0
example-byid.json

@@ -0,0 +1,86 @@
+{
+  "kind": "youtube#videoListResponse",
+  "etag": "10hqyf6pWj1OW3ahOJ8P3HNePMc",
+  "items": [
+    {
+      "kind": "youtube#video",
+      "etag": "nIzxni7ijKW-6GYWAx398GYwOuY",
+      "id": "Ks-_Mh1QhMc",
+      "snippet": {
+        "publishedAt": "2012-10-01T15:27:35Z",
+        "channelId": "UCAuUUnT6oDeKwE6v1NGQxug",
+        "title": "Your body language may shape who you are | Amy Cuddy | TED",
+        "description": "Body language affects how others see us, but it may also change how we see ourselves. Social psychologist Amy Cuddy argues that \"power posing\" -- standing in a posture of confidence, even when we don't feel confident -- can boost feelings of confidence, and might have an impact on our chances for success. (Note: Some of the findings presented in this talk have been referenced in an ongoing debate among social scientists about robustness and reproducibility. Read Amy Cuddy's response here: http://ideas.ted.com/inside-the-debate-about-power-posing-a-q-a-with-amy-cuddy/)\n\nGet TED Talks recommended just for you! Learn more at https://www.ted.com/signup.\n\nThe TED Talks channel features the best talks and performances from the TED Conference, where the world's leading thinkers and doers give the talk of their lives in 18 minutes (or less). Look for talks on Technology, Entertainment and Design -- plus science, business, global issues, the arts and more.\n\nFollow TED on Twitter: http://www.twitter.com/TEDTalks\nLike TED on Facebook: https://www.facebook.com/TED\n\nSubscribe to our channel: https://www.youtube.com/TED",
+        "thumbnails": {
+          "default": {
+            "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/default.jpg",
+            "width": 120,
+            "height": 90
+          },
+          "medium": {
+            "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/mqdefault.jpg",
+            "width": 320,
+            "height": 180
+          },
+          "high": {
+            "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/hqdefault.jpg",
+            "width": 480,
+            "height": 360
+          },
+          "standard": {
+            "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/sddefault.jpg",
+            "width": 640,
+            "height": 480
+          },
+          "maxres": {
+            "url": "https://i.ytimg.com/vi/Ks-_Mh1QhMc/maxresdefault.jpg",
+            "width": 1280,
+            "height": 720
+          }
+        },
+        "channelTitle": "TED",
+        "tags": [
+          "Amy Cuddy",
+          "TED",
+          "TEDTalk",
+          "TEDTalks",
+          "TED Talk",
+          "TED Talks",
+          "TEDGlobal",
+          "brain",
+          "business",
+          "psychology",
+          "self",
+          "success"
+        ],
+        "categoryId": "22",
+        "liveBroadcastContent": "none",
+        "defaultLanguage": "en",
+        "localized": {
+          "title": "Your body language may shape who you are | Amy Cuddy | TED",
+          "description": "Body language affects how others see us, but it may also change how we see ourselves. Social psychologist Amy Cuddy argues that \"power posing\" -- standing in a posture of confidence, even when we don't feel confident -- can boost feelings of confidence, and might have an impact on our chances for success. (Note: Some of the findings presented in this talk have been referenced in an ongoing debate among social scientists about robustness and reproducibility. Read Amy Cuddy's response here: http://ideas.ted.com/inside-the-debate-about-power-posing-a-q-a-with-amy-cuddy/)\n\nGet TED Talks recommended just for you! Learn more at https://www.ted.com/signup.\n\nThe TED Talks channel features the best talks and performances from the TED Conference, where the world's leading thinkers and doers give the talk of their lives in 18 minutes (or less). Look for talks on Technology, Entertainment and Design -- plus science, business, global issues, the arts and more.\n\nFollow TED on Twitter: http://www.twitter.com/TEDTalks\nLike TED on Facebook: https://www.facebook.com/TED\n\nSubscribe to our channel: https://www.youtube.com/TED"
+        },
+        "defaultAudioLanguage": "en"
+      },
+      "contentDetails": {
+        "duration": "PT21M3S",
+        "dimension": "2d",
+        "definition": "hd",
+        "caption": "true",
+        "licensedContent": true,
+        "contentRating": {},
+        "projection": "rectangular"
+      },
+      "statistics": {
+        "viewCount": "24753756",
+        "likeCount": "430018",
+        "favoriteCount": "0",
+        "commentCount": "9776"
+      }
+    }
+  ],
+  "pageInfo": {
+    "totalResults": 1,
+    "resultsPerPage": 1
+  }
+}

+ 57 - 5
src/YTMPV/MainWindow.cpp

@@ -1,4 +1,7 @@
 #include "MainWindow.hpp"
+#include "core.hpp"
+#include <YoutubeApi/youtubeapi.hpp>
+#include <unistd.h>
 
 namespace components {
     
@@ -17,9 +20,10 @@ namespace components {
         m_search_btn.set_child(*(this->getButtonContents("Поиск", "find")));
         m_search_btn.signal_clicked().connect(sigc::mem_fun(
             *this,
-            &MainWindow::on_btn_clicked
+            &MainWindow::onSearchButtonClicked
         ));
         m_search_field.set_hexpand(true);
+        m_search_field.set_placeholder_text("Поиск YouTube");
         m_search_box.append(m_search_field);
         m_search_box.append(m_search_btn);
         m_search_box.set_margin(8);
@@ -27,12 +31,13 @@ namespace components {
         // --Body-
         // Модель видео
         m_video_storage = Gio::ListStore<VideoModel>::create();
-        m_video_storage->append(VideoModel::create(1, "7yZvzo4_s6Q", "Hermitcraft 10 - Ep 12:  Who Has The Best Storage System???"));
 
         // Модель выбора
-        auto selection_model = Gtk::SingleSelection::create(m_video_storage);
+        selection_model = Gtk::SingleSelection::create(m_video_storage);
         selection_model->set_autoselect(false);
         selection_model->set_can_unselect(true);
+        selection_model->property_selected().signal_changed().connect(
+            sigc::mem_fun(*this, &MainWindow::onVideoChanged));
         m_video_list.set_model(selection_model);
 
         // Создание фабрики
@@ -42,6 +47,8 @@ namespace components {
         factory->signal_bind().connect(
             sigc::mem_fun(*this, &MainWindow::onVideoBind));
         m_video_list.set_factory(factory);
+        m_video_list.signal_activate().connect(
+            sigc::mem_fun(*this, &MainWindow::onVideoSelected));
 
         // Прокручиваемое окно
         m_video_scroll.set_policy(Gtk::PolicyType::AUTOMATIC, Gtk::PolicyType::AUTOMATIC);
@@ -62,9 +69,21 @@ namespace components {
     {
     }
 
-    void MainWindow::on_btn_clicked()
+    void MainWindow::onSearchButtonClicked()
     {
-        //m_video_storage->append(VideoModel::create(2, "test."));
+        // Очистить предыдущие результаты
+        m_video_storage->remove_all();
+        
+        // Получить результаты поиска
+        Glib::ustring query = m_search_field.get_buffer()->get_text();
+        db::video found;
+        std::vector<std::string> video_ids = ytapi::getVideoIDsByQuery(query.release());
+
+        // Добавить в список видео
+        for (auto id : video_ids) {
+            found = core::getVideoByYTID(id);
+            m_video_storage->append(VideoModel::create(found.id, found.yt_id, found.title));
+        }
     }
 
     void MainWindow::onVideoSetup(const Glib::RefPtr<Gtk::ListItem>& list_item)
@@ -77,6 +96,26 @@ namespace components {
         list_item->set_child(*box_main);
     }
 
+    void MainWindow::onVideoChanged()
+    {
+        auto position = selection_model->get_selected();
+        auto item = m_video_storage->get_item(position);
+        if (!item) return;
+
+        // Запуск mpv в заднем фоне
+        int pid = fork();
+        if (pid == 0) {
+            std::string yt_url = "https://youtu.be/"+item->m_yt_id;
+            execl(
+                "/usr/bin/mpv",     // Путь к mpv
+                "mpv",              // Название файла
+                "--no-terminal",    // Терминал не нужен
+                yt_url.c_str(),     // URL видео
+                (char*)0            // Терминатор
+            );
+        }
+    }
+
     void MainWindow::onVideoBind(const Glib::RefPtr<Gtk::ListItem>& list_item)
     {
         auto pos = list_item->get_position();
@@ -119,6 +158,19 @@ namespace components {
         lbl_title->set_text(item->m_title);
     }
 
+    // DO NOT USE!!
+    void MainWindow::onVideoSelected(unsigned int position)
+    {
+        std::cout << position;
+        auto item = m_video_storage->get_item(position);
+        if (!item) return;
+
+        std::string command = "mpv https://youtu.be/"+item->m_yt_id;
+
+        std::cout << command;
+        system(command.c_str());
+    }
+
     Gtk::Box* MainWindow::getButtonContents(Glib::ustring text, std::string icon_name)
     {
         // Создание иконки и текста

+ 6 - 2
src/YTMPV/MainWindow.hpp

@@ -21,7 +21,6 @@
 #include <giomm/liststore.h>
 
 #include "VideoModel.hpp"
-#include <YoutubeApi/youtubeapi.hpp>
 
 namespace components {
     // Главное окно приложения
@@ -33,11 +32,15 @@ namespace components {
     protected:
         // --Обработка событий--
         // Клик кнопки
-        void on_btn_clicked();
+        void onSearchButtonClicked();
         // При создании элемента в m_video_list
         void onVideoSetup(const Glib::RefPtr<Gtk::ListItem>& list_item);
         // При записи данных в m_video_list
         void onVideoBind(const Glib::RefPtr<Gtk::ListItem>& list_item);
+        // При выборе видео из списка
+        void onVideoSelected(unsigned int position);
+
+        void onVideoChanged();
 
         // --Виджеты--
         Gtk::Box                m_layout;       // Главный контейнер
@@ -53,6 +56,7 @@ namespace components {
         // --Общее--
         // Модель отображения видео
         Glib::RefPtr<Gio::ListStore<VideoModel>> m_video_storage;
+        Glib::RefPtr<Gtk::SingleSelection> selection_model;
         // Возвращает дочерний виджет для кнопок, которым нужны иконка с текстом
         Gtk::Box* getButtonContents(Glib::ustring text, std::string icon_name);
     };

+ 37 - 0
src/YTMPV/core.cpp

@@ -0,0 +1,37 @@
+#include "core.hpp"
+
+namespace core {
+    
+    db::video getVideoByYTID(std::string yt_id) {
+        db::video output;
+
+        // 1. Проверить есть ли видео в базе данных
+        if (db::getVideoByYTID(yt_id, &output)) {
+            // Видео в базе данных найдено
+            std::cout << "Видео найдено в базе данных!" << std::endl;
+            return output;
+        }
+
+        // Видео в базе данных нет. Получаем информацию о нём через ytapi
+        ytapi::video_result found_video = ytapi::getVideoByYTID(yt_id);
+        output.yt_id        = yt_id;
+        output.title        = found_video.title;
+        output.description  = found_video.description;
+        output.published_at = found_video.published_at;
+
+        // Ищем автора в базе данных
+        db::author video_author;
+        if (!db::getAuthorByYTID(found_video.author_yt_id, &video_author)) {
+            // Автора в базе данных нет. Добавляем
+            video_author.yt_id = found_video.author_yt_id;
+            video_author.name = found_video.author_name;
+            db::addAuthor(&video_author);
+        }
+        output.author_obj = video_author;
+
+        // Добавляем видео в БД
+        db::addVideo(&output);
+
+        return output;
+    }
+}

+ 11 - 0
src/YTMPV/core.hpp

@@ -0,0 +1,11 @@
+#pragma once
+#include <YoutubeApi/youtubeapi.hpp>
+#include <Database/database.hpp>
+#include <fstream>
+#include <iostream>
+#include <string>
+
+namespace core {
+    // Возвращает объект видео по его Youtube id
+    db::video getVideoByYTID(std::string yt_id);
+}

+ 1 - 1
src/YTMPV/meson.build

@@ -1,6 +1,6 @@
 ytmpv = executable(
   'ytmpv',
-  ['ytmpv.cpp', 'MainWindow.cpp', 'VideoModel.cpp'],
+  ['ytmpv.cpp', 'core.cpp', 'MainWindow.cpp', 'VideoModel.cpp'],
   link_with: [ytapi_lib, database_lib],
   include_directories: [dir_includes],
   dependencies: [glibmm_dep, curlpp_dep, json_dep, gtkmm_dep]

+ 0 - 0
src/YTMPV/views/BrowseVideosView.cpp


+ 0 - 0
src/YTMPV/views/BrowseVideosView.hpp


+ 0 - 0
src/YTMPV/views/View.cpp


+ 0 - 0
src/YTMPV/views/View.hpp


+ 10 - 36
src/YTMPV/ytmpv.cpp

@@ -1,37 +1,11 @@
-#include "ytmpv.hpp"
-
-db::video getVideoByYTID(std::string yt_id) {
-    db::video output;
-
-    // 1. Проверить есть ли видео в базе данных
-    if (db::getVideoByYTID(yt_id, &output)) {
-        // Видео в базе данных найдено
-        std::cout << "Видео найдено в базе данных!" << std::endl;
-        return output;
-    }
-
-    // Видео в базе данных нет. Получаем информацию о нём через ytapi
-    ytapi::video_result found_video = ytapi::getVideoByYTID(yt_id);
-    output.yt_id        = yt_id;
-    output.title        = found_video.title;
-    output.description  = found_video.description;
-    output.published_at = found_video.published_at;
-
-    // Ищем автора в базе данных
-    db::author video_author;
-    if (!db::getAuthorByYTID(found_video.author_yt_id, &video_author)) {
-        // Автора в базе данных нет. Добавляем
-        video_author.yt_id = found_video.author_yt_id;
-        video_author.name = found_video.author_name;
-        db::addAuthor(&video_author);
-    }
-    output.author_obj = video_author;
-
-    // Добавляем видео в БД
-    db::addVideo(&output);
-
-    return output;
-}
+#include "MainWindow.hpp"
+#include <gtkmm/application.h>
+#include <glibmm/optioncontext.h>
+#include <glibmm/optiongroup.h>
+#include <glibmm/optionentry.h>
+#include <curl/curl.h>
+#include <Database/database.hpp>
+#include <YoutubeApi/youtubeapi.hpp>
 
 int main(int argc, char** argv) {
     // ==Инициализация==
@@ -67,8 +41,8 @@ int main(int argc, char** argv) {
 
     // --Получение данных из файла настроек--
     // TODO
-    std::string db_path = ":memory:";
-    std::string api_key = "key";
+    std::string db_path = "/home/vad/Code/YTMPV/db.sqlite3";
+    std::string api_key = "AIzaSyAymnCxcWln0h379LA_q5TT_tJuTANhTyg";
     
     // --Общая инициализация--
     curl_global_init(CURL_GLOBAL_ALL);

+ 0 - 13
src/YTMPV/ytmpv.hpp

@@ -1,13 +0,0 @@
-#pragma once
-#include <YoutubeApi/youtubeapi.hpp>
-#include <Database/database.hpp>
-#include <fstream>
-#include <iostream>
-#include <glibmm/optioncontext.h>
-#include <glibmm/optiongroup.h>
-#include <glibmm/optionentry.h>
-#include <gtkmm/application.h>
-#include "MainWindow.hpp"
-
-// Возвращает объект видео по его Youtube id
-db::video getVideoByYTID(std::string yt_id);