auth-youtube.cpp 11 KB

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