auth-youtube.cpp 12 KB

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