auth-youtube.cpp 10 KB

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