auth-youtube.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #include "auth-youtube.hpp"
  2. #include <iostream>
  3. #include <QMessageBox>
  4. #include <QThread>
  5. #include <vector>
  6. #include <QDesktopServices>
  7. #include <QHBoxLayout>
  8. #include <QUrl>
  9. #include <QRandomGenerator>
  10. #ifdef WIN32
  11. #include <windows.h>
  12. #include <shellapi.h>
  13. #pragma comment(lib, "shell32")
  14. #endif
  15. #include "auth-listener.hpp"
  16. #include "obs-app.hpp"
  17. #include "qt-wrappers.hpp"
  18. #include "ui-config.h"
  19. #include "youtube-api-wrappers.hpp"
  20. #include "window-basic-main.hpp"
  21. #include "obf.h"
  22. #ifdef BROWSER_AVAILABLE
  23. #include "window-dock-browser.hpp"
  24. #endif
  25. using namespace json11;
  26. /* ------------------------------------------------------------------------- */
  27. #define YOUTUBE_AUTH_URL "https://accounts.google.com/o/oauth2/v2/auth"
  28. #define YOUTUBE_TOKEN_URL "https://www.googleapis.com/oauth2/v4/token"
  29. #define YOUTUBE_SCOPE_VERSION 1
  30. #define YOUTUBE_API_STATE_LENGTH 32
  31. #define SECTION_NAME "YouTube"
  32. #define YOUTUBE_CHAT_PLACEHOLDER_URL \
  33. "https://obsproject.com/placeholders/youtube-chat"
  34. #define YOUTUBE_CHAT_POPOUT_URL \
  35. "https://www.youtube.com/live_chat?is_popout=1&dark_theme=1&v=%1"
  36. static const char allowedChars[] =
  37. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  38. static const int allowedCount = static_cast<int>(sizeof(allowedChars) - 1);
  39. /* ------------------------------------------------------------------------- */
  40. static inline void OpenBrowser(const QString auth_uri)
  41. {
  42. QUrl url(auth_uri, QUrl::StrictMode);
  43. QDesktopServices::openUrl(url);
  44. }
  45. void RegisterYoutubeAuth()
  46. {
  47. for (auto &service : youtubeServices) {
  48. OAuth::RegisterOAuth(
  49. service,
  50. [service]() {
  51. return std::make_shared<YoutubeApiWrappers>(
  52. service);
  53. },
  54. YoutubeAuth::Login, []() { return; });
  55. }
  56. }
  57. YoutubeAuth::YoutubeAuth(const Def &d)
  58. : OAuthStreamKey(d), section(SECTION_NAME)
  59. {
  60. }
  61. bool YoutubeAuth::RetryLogin()
  62. {
  63. return true;
  64. }
  65. void YoutubeAuth::SaveInternal()
  66. {
  67. OBSBasic *main = OBSBasic::Get();
  68. config_set_string(main->Config(), service(), "DockState",
  69. main->saveState().toBase64().constData());
  70. const char *section_name = section.c_str();
  71. config_set_string(main->Config(), section_name, "RefreshToken",
  72. refresh_token.c_str());
  73. config_set_string(main->Config(), section_name, "Token", token.c_str());
  74. config_set_uint(main->Config(), section_name, "ExpireTime",
  75. expire_time);
  76. config_set_int(main->Config(), section_name, "ScopeVer",
  77. currentScopeVer);
  78. }
  79. static inline std::string get_config_str(OBSBasic *main, const char *section,
  80. const char *name)
  81. {
  82. const char *val = config_get_string(main->Config(), section, name);
  83. return val ? val : "";
  84. }
  85. bool YoutubeAuth::LoadInternal()
  86. {
  87. OBSBasic *main = OBSBasic::Get();
  88. const char *section_name = section.c_str();
  89. refresh_token = get_config_str(main, section_name, "RefreshToken");
  90. token = get_config_str(main, section_name, "Token");
  91. expire_time =
  92. config_get_uint(main->Config(), section_name, "ExpireTime");
  93. currentScopeVer =
  94. (int)config_get_int(main->Config(), section_name, "ScopeVer");
  95. firstLoad = false;
  96. return implicit ? !token.empty() : !refresh_token.empty();
  97. }
  98. #ifdef BROWSER_AVAILABLE
  99. static const char *ytchat_script = "\
  100. const obsCSS = document.createElement('style');\
  101. obsCSS.innerHTML = \"#panel-pages.yt-live-chat-renderer {display: none;}\
  102. yt-live-chat-viewer-engagement-message-renderer {display: none;}\";\
  103. document.querySelector('head').appendChild(obsCSS);";
  104. #endif
  105. void YoutubeAuth::LoadUI()
  106. {
  107. if (uiLoaded)
  108. return;
  109. #ifdef BROWSER_AVAILABLE
  110. if (!cef)
  111. return;
  112. OBSBasic::InitBrowserPanelSafeBlock();
  113. OBSBasic *main = OBSBasic::Get();
  114. QCefWidget *browser;
  115. QSize size = main->frameSize();
  116. QPoint pos = main->pos();
  117. chat.reset(new YoutubeChatDock());
  118. chat->setObjectName("ytChat");
  119. chat->resize(300, 600);
  120. chat->setMinimumSize(200, 300);
  121. chat->setWindowTitle(QTStr("Auth.Chat"));
  122. chat->setAllowedAreas(Qt::AllDockWidgetAreas);
  123. browser = cef->create_widget(chat.data(), YOUTUBE_CHAT_PLACEHOLDER_URL,
  124. panel_cookies);
  125. browser->setStartupScript(ytchat_script);
  126. chat->SetWidget(browser);
  127. main->addDockWidget(Qt::RightDockWidgetArea, chat.data());
  128. chatMenu.reset(main->AddDockWidget(chat.data()));
  129. chat->setFloating(true);
  130. chat->move(pos.x() + size.width() - chat->width() - 50, pos.y() + 50);
  131. if (firstLoad) {
  132. chat->setVisible(true);
  133. } else {
  134. const char *dockStateStr = config_get_string(
  135. main->Config(), service(), "DockState");
  136. QByteArray dockState =
  137. QByteArray::fromBase64(QByteArray(dockStateStr));
  138. if (main->isVisible() || !main->isMaximized())
  139. main->restoreState(dockState);
  140. }
  141. #endif
  142. uiLoaded = true;
  143. }
  144. void YoutubeAuth::SetChatId(const QString &chat_id,
  145. const std::string &api_chat_id)
  146. {
  147. #ifdef BROWSER_AVAILABLE
  148. QString chat_url = QString(YOUTUBE_CHAT_POPOUT_URL).arg(chat_id);
  149. if (chat && chat->cefWidget) {
  150. chat->cefWidget->setURL(chat_url.toStdString());
  151. chat->SetApiChatId(api_chat_id);
  152. }
  153. #else
  154. UNUSED_PARAMETER(chat_id);
  155. UNUSED_PARAMETER(api_chat_id);
  156. #endif
  157. }
  158. void YoutubeAuth::ResetChat()
  159. {
  160. #ifdef BROWSER_AVAILABLE
  161. if (chat && chat->cefWidget) {
  162. chat->cefWidget->setURL(YOUTUBE_CHAT_PLACEHOLDER_URL);
  163. }
  164. #endif
  165. }
  166. QString YoutubeAuth::GenerateState()
  167. {
  168. char state[YOUTUBE_API_STATE_LENGTH + 1];
  169. QRandomGenerator *rng = QRandomGenerator::system();
  170. int i;
  171. for (i = 0; i < YOUTUBE_API_STATE_LENGTH; i++)
  172. state[i] = allowedChars[rng->bounded(0, allowedCount)];
  173. state[i] = 0;
  174. return state;
  175. }
  176. // Static.
  177. std::shared_ptr<Auth> YoutubeAuth::Login(QWidget *owner,
  178. const std::string &service)
  179. {
  180. QString auth_code;
  181. AuthListener server;
  182. auto it = std::find_if(youtubeServices.begin(), youtubeServices.end(),
  183. [service](auto &item) {
  184. return service == item.service;
  185. });
  186. if (it == youtubeServices.end()) {
  187. return nullptr;
  188. }
  189. const auto auth = std::make_shared<YoutubeApiWrappers>(*it);
  190. QString redirect_uri =
  191. QString("http://127.0.0.1:%1").arg(server.GetPort());
  192. QMessageBox dlg(owner);
  193. dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint);
  194. dlg.setWindowTitle(QTStr("YouTube.Auth.WaitingAuth.Title"));
  195. std::string clientid = YOUTUBE_CLIENTID;
  196. std::string secret = YOUTUBE_SECRET;
  197. deobfuscate_str(&clientid[0], YOUTUBE_CLIENTID_HASH);
  198. deobfuscate_str(&secret[0], YOUTUBE_SECRET_HASH);
  199. QString state;
  200. state = auth->GenerateState();
  201. server.SetState(state);
  202. QString url_template;
  203. url_template += "%1";
  204. url_template += "?response_type=code";
  205. url_template += "&client_id=%2";
  206. url_template += "&redirect_uri=%3";
  207. url_template += "&state=%4";
  208. url_template += "&scope=https://www.googleapis.com/auth/youtube";
  209. QString url = url_template.arg(YOUTUBE_AUTH_URL, clientid.c_str(),
  210. redirect_uri, state);
  211. QString text = QTStr("YouTube.Auth.WaitingAuth.Text");
  212. text = text.arg(
  213. QString("<a href='%1'>Google OAuth Service</a>").arg(url));
  214. dlg.setText(text);
  215. dlg.setTextFormat(Qt::RichText);
  216. dlg.setStandardButtons(QMessageBox::StandardButton::Cancel);
  217. connect(&dlg, &QMessageBox::buttonClicked, &dlg,
  218. [&](QAbstractButton *) {
  219. #ifdef _DEBUG
  220. blog(LOG_DEBUG, "Action Cancelled.");
  221. #endif
  222. // TODO: Stop server.
  223. dlg.reject();
  224. });
  225. // Async Login.
  226. connect(&server, &AuthListener::ok, &dlg,
  227. [&dlg, &auth_code](QString code) {
  228. #ifdef _DEBUG
  229. blog(LOG_DEBUG, "Got youtube redirected answer: %s",
  230. QT_TO_UTF8(code));
  231. #endif
  232. auth_code = code;
  233. dlg.accept();
  234. });
  235. connect(&server, &AuthListener::fail, &dlg, [&dlg]() {
  236. #ifdef _DEBUG
  237. blog(LOG_DEBUG, "No access granted");
  238. #endif
  239. dlg.reject();
  240. });
  241. auto open_external_browser = [url]() { OpenBrowser(url); };
  242. QScopedPointer<QThread> thread(CreateQThread(open_external_browser));
  243. thread->start();
  244. dlg.exec();
  245. if (dlg.result() == QMessageBox::Cancel ||
  246. dlg.result() == QDialog::Rejected)
  247. return nullptr;
  248. if (!auth->GetToken(YOUTUBE_TOKEN_URL, clientid, secret,
  249. QT_TO_UTF8(redirect_uri), YOUTUBE_SCOPE_VERSION,
  250. QT_TO_UTF8(auth_code), true)) {
  251. return nullptr;
  252. }
  253. config_t *config = OBSBasic::Get()->Config();
  254. config_remove_value(config, "YouTube", "ChannelName");
  255. ChannelDescription cd;
  256. if (auth->GetChannelDescription(cd))
  257. config_set_string(config, "YouTube", "ChannelName",
  258. QT_TO_UTF8(cd.title));
  259. config_save_safe(config, "tmp", nullptr);
  260. return auth;
  261. }
  262. #ifdef BROWSER_AVAILABLE
  263. void YoutubeChatDock::SetWidget(QCefWidget *widget_)
  264. {
  265. lineEdit = new LineEditAutoResize();
  266. lineEdit->setVisible(false);
  267. lineEdit->setMaxLength(200);
  268. lineEdit->setPlaceholderText(QTStr("YouTube.Chat.Input.Placeholder"));
  269. sendButton = new QPushButton(QTStr("YouTube.Chat.Input.Send"));
  270. sendButton->setVisible(false);
  271. chatLayout = new QHBoxLayout();
  272. chatLayout->setContentsMargins(0, 0, 0, 0);
  273. chatLayout->addWidget(lineEdit, 1);
  274. chatLayout->addWidget(sendButton);
  275. QVBoxLayout *layout = new QVBoxLayout();
  276. layout->setContentsMargins(0, 0, 0, 0);
  277. layout->addWidget(widget_, 1);
  278. layout->addLayout(chatLayout);
  279. QWidget *widget = new QWidget();
  280. widget->setLayout(layout);
  281. setWidget(widget);
  282. QWidget::connect(lineEdit, SIGNAL(returnPressed()), this,
  283. SLOT(SendChatMessage()));
  284. QWidget::connect(sendButton, SIGNAL(pressed()), this,
  285. SLOT(SendChatMessage()));
  286. cefWidget.reset(widget_);
  287. }
  288. void YoutubeChatDock::SetApiChatId(const std::string &id)
  289. {
  290. this->apiChatId = id;
  291. QMetaObject::invokeMethod(this, "EnableChatInput",
  292. Qt::QueuedConnection);
  293. }
  294. void YoutubeChatDock::SendChatMessage()
  295. {
  296. const QString message = lineEdit->text();
  297. if (message == "")
  298. return;
  299. OBSBasic *main = OBSBasic::Get();
  300. YoutubeApiWrappers *apiYouTube(
  301. dynamic_cast<YoutubeApiWrappers *>(main->GetAuth()));
  302. ExecuteFuncSafeBlock([&]() {
  303. lineEdit->setText("");
  304. lineEdit->setPlaceholderText(
  305. QTStr("YouTube.Chat.Input.Sending"));
  306. if (apiYouTube->SendChatMessage(apiChatId, message)) {
  307. os_sleep_ms(3000);
  308. } else {
  309. QString error = apiYouTube->GetLastError();
  310. apiYouTube->GetTranslatedError(error);
  311. QMetaObject::invokeMethod(
  312. this, "ShowErrorMessage", Qt::QueuedConnection,
  313. Q_ARG(const QString &, error));
  314. }
  315. lineEdit->setPlaceholderText(
  316. QTStr("YouTube.Chat.Input.Placeholder"));
  317. });
  318. }
  319. void YoutubeChatDock::ShowErrorMessage(const QString &error)
  320. {
  321. QMessageBox::warning(this, QTStr("YouTube.Chat.Error.Title"),
  322. QTStr("YouTube.Chat.Error.Text").arg(error));
  323. }
  324. void YoutubeChatDock::EnableChatInput()
  325. {
  326. lineEdit->setVisible(true);
  327. sendButton->setVisible(true);
  328. }
  329. #endif