auth-youtube.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. main->restoreState(dockState);
  139. }
  140. #endif
  141. uiLoaded = true;
  142. }
  143. void YoutubeAuth::SetChatId(const QString &chat_id,
  144. const std::string &api_chat_id)
  145. {
  146. #ifdef BROWSER_AVAILABLE
  147. QString chat_url = QString(YOUTUBE_CHAT_POPOUT_URL).arg(chat_id);
  148. if (chat && chat->cefWidget) {
  149. chat->cefWidget->setURL(chat_url.toStdString());
  150. chat->SetApiChatId(api_chat_id);
  151. }
  152. #else
  153. UNUSED_PARAMETER(chat_id);
  154. UNUSED_PARAMETER(api_chat_id);
  155. #endif
  156. }
  157. void YoutubeAuth::ResetChat()
  158. {
  159. #ifdef BROWSER_AVAILABLE
  160. if (chat && chat->cefWidget) {
  161. chat->cefWidget->setURL(YOUTUBE_CHAT_PLACEHOLDER_URL);
  162. }
  163. #endif
  164. }
  165. QString YoutubeAuth::GenerateState()
  166. {
  167. char state[YOUTUBE_API_STATE_LENGTH + 1];
  168. QRandomGenerator *rng = QRandomGenerator::system();
  169. int i;
  170. for (i = 0; i < YOUTUBE_API_STATE_LENGTH; i++)
  171. state[i] = allowedChars[rng->bounded(0, allowedCount)];
  172. state[i] = 0;
  173. return state;
  174. }
  175. // Static.
  176. std::shared_ptr<Auth> YoutubeAuth::Login(QWidget *owner,
  177. const std::string &service)
  178. {
  179. QString auth_code;
  180. AuthListener server;
  181. auto it = std::find_if(youtubeServices.begin(), youtubeServices.end(),
  182. [service](auto &item) {
  183. return service == item.service;
  184. });
  185. if (it == youtubeServices.end()) {
  186. return nullptr;
  187. }
  188. const auto auth = std::make_shared<YoutubeApiWrappers>(*it);
  189. QString redirect_uri =
  190. QString("http://127.0.0.1:%1").arg(server.GetPort());
  191. QMessageBox dlg(owner);
  192. dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint);
  193. dlg.setWindowTitle(QTStr("YouTube.Auth.WaitingAuth.Title"));
  194. std::string clientid = YOUTUBE_CLIENTID;
  195. std::string secret = YOUTUBE_SECRET;
  196. deobfuscate_str(&clientid[0], YOUTUBE_CLIENTID_HASH);
  197. deobfuscate_str(&secret[0], YOUTUBE_SECRET_HASH);
  198. QString state;
  199. state = auth->GenerateState();
  200. server.SetState(state);
  201. QString url_template;
  202. url_template += "%1";
  203. url_template += "?response_type=code";
  204. url_template += "&client_id=%2";
  205. url_template += "&redirect_uri=%3";
  206. url_template += "&state=%4";
  207. url_template += "&scope=https://www.googleapis.com/auth/youtube";
  208. QString url = url_template.arg(YOUTUBE_AUTH_URL, clientid.c_str(),
  209. redirect_uri, state);
  210. QString text = QTStr("YouTube.Auth.WaitingAuth.Text");
  211. text = text.arg(
  212. QString("<a href='%1'>Google OAuth Service</a>").arg(url));
  213. dlg.setText(text);
  214. dlg.setTextFormat(Qt::RichText);
  215. dlg.setStandardButtons(QMessageBox::StandardButton::Cancel);
  216. connect(&dlg, &QMessageBox::buttonClicked, &dlg,
  217. [&](QAbstractButton *) {
  218. #ifdef _DEBUG
  219. blog(LOG_DEBUG, "Action Cancelled.");
  220. #endif
  221. // TODO: Stop server.
  222. dlg.reject();
  223. });
  224. // Async Login.
  225. connect(&server, &AuthListener::ok, &dlg,
  226. [&dlg, &auth_code](QString code) {
  227. #ifdef _DEBUG
  228. blog(LOG_DEBUG, "Got youtube redirected answer: %s",
  229. QT_TO_UTF8(code));
  230. #endif
  231. auth_code = code;
  232. dlg.accept();
  233. });
  234. connect(&server, &AuthListener::fail, &dlg, [&dlg]() {
  235. #ifdef _DEBUG
  236. blog(LOG_DEBUG, "No access granted");
  237. #endif
  238. dlg.reject();
  239. });
  240. auto open_external_browser = [url]() { OpenBrowser(url); };
  241. QScopedPointer<QThread> thread(CreateQThread(open_external_browser));
  242. thread->start();
  243. dlg.exec();
  244. if (dlg.result() == QMessageBox::Cancel ||
  245. dlg.result() == QDialog::Rejected)
  246. return nullptr;
  247. if (!auth->GetToken(YOUTUBE_TOKEN_URL, clientid, secret,
  248. QT_TO_UTF8(redirect_uri), YOUTUBE_SCOPE_VERSION,
  249. QT_TO_UTF8(auth_code), true)) {
  250. return nullptr;
  251. }
  252. config_t *config = OBSBasic::Get()->Config();
  253. config_remove_value(config, "YouTube", "ChannelName");
  254. ChannelDescription cd;
  255. if (auth->GetChannelDescription(cd))
  256. config_set_string(config, "YouTube", "ChannelName",
  257. QT_TO_UTF8(cd.title));
  258. config_save_safe(config, "tmp", nullptr);
  259. return auth;
  260. }
  261. #ifdef BROWSER_AVAILABLE
  262. void YoutubeChatDock::SetWidget(QCefWidget *widget_)
  263. {
  264. lineEdit = new LineEditAutoResize();
  265. lineEdit->setVisible(false);
  266. lineEdit->setMaxLength(200);
  267. lineEdit->setPlaceholderText(QTStr("YouTube.Chat.Input.Placeholder"));
  268. sendButton = new QPushButton(QTStr("YouTube.Chat.Input.Send"));
  269. sendButton->setVisible(false);
  270. chatLayout = new QHBoxLayout();
  271. chatLayout->setContentsMargins(0, 0, 0, 0);
  272. chatLayout->addWidget(lineEdit, 1);
  273. chatLayout->addWidget(sendButton);
  274. QVBoxLayout *layout = new QVBoxLayout();
  275. layout->setContentsMargins(0, 0, 0, 0);
  276. layout->addWidget(widget_, 1);
  277. layout->addLayout(chatLayout);
  278. QWidget *widget = new QWidget();
  279. widget->setLayout(layout);
  280. setWidget(widget);
  281. QWidget::connect(lineEdit, SIGNAL(returnPressed()), this,
  282. SLOT(SendChatMessage()));
  283. QWidget::connect(sendButton, SIGNAL(pressed()), this,
  284. SLOT(SendChatMessage()));
  285. cefWidget.reset(widget_);
  286. }
  287. void YoutubeChatDock::SetApiChatId(const std::string &id)
  288. {
  289. this->apiChatId = id;
  290. QMetaObject::invokeMethod(this, "EnableChatInput",
  291. Qt::QueuedConnection);
  292. }
  293. void YoutubeChatDock::SendChatMessage()
  294. {
  295. const QString message = lineEdit->text();
  296. if (message == "")
  297. return;
  298. OBSBasic *main = OBSBasic::Get();
  299. YoutubeApiWrappers *apiYouTube(
  300. dynamic_cast<YoutubeApiWrappers *>(main->GetAuth()));
  301. ExecuteFuncSafeBlock([&]() {
  302. lineEdit->setText("");
  303. lineEdit->setPlaceholderText(
  304. QTStr("YouTube.Chat.Input.Sending"));
  305. if (apiYouTube->SendChatMessage(apiChatId, message)) {
  306. os_sleep_ms(3000);
  307. } else {
  308. QString error = apiYouTube->GetLastError();
  309. apiYouTube->GetTranslatedError(error);
  310. QMetaObject::invokeMethod(
  311. this, "ShowErrorMessage", Qt::QueuedConnection,
  312. Q_ARG(const QString &, error));
  313. }
  314. lineEdit->setPlaceholderText(
  315. QTStr("YouTube.Chat.Input.Placeholder"));
  316. });
  317. }
  318. void YoutubeChatDock::ShowErrorMessage(const QString &error)
  319. {
  320. QMessageBox::warning(this, QTStr("YouTube.Chat.Error.Title"),
  321. QTStr("YouTube.Chat.Error.Text").arg(error));
  322. }
  323. void YoutubeChatDock::EnableChatInput()
  324. {
  325. lineEdit->setVisible(true);
  326. sendButton->setVisible(true);
  327. }
  328. #endif