auth-youtube.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  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),
  60. section(SECTION_NAME)
  61. {
  62. }
  63. YoutubeAuth::~YoutubeAuth()
  64. {
  65. if (!uiLoaded)
  66. return;
  67. #ifdef BROWSER_AVAILABLE
  68. OBSBasic *main = OBSBasic::Get();
  69. main->RemoveDockWidget(YOUTUBE_CHAT_DOCK_NAME);
  70. chat = nullptr;
  71. #endif
  72. }
  73. bool YoutubeAuth::RetryLogin()
  74. {
  75. return true;
  76. }
  77. void YoutubeAuth::SaveInternal()
  78. {
  79. OBSBasic *main = OBSBasic::Get();
  80. config_set_string(main->Config(), service(), "DockState",
  81. main->saveState().toBase64().constData());
  82. const char *section_name = section.c_str();
  83. config_set_string(main->Config(), section_name, "RefreshToken",
  84. refresh_token.c_str());
  85. config_set_string(main->Config(), section_name, "Token", token.c_str());
  86. config_set_uint(main->Config(), section_name, "ExpireTime",
  87. expire_time);
  88. config_set_int(main->Config(), section_name, "ScopeVer",
  89. currentScopeVer);
  90. }
  91. static inline std::string get_config_str(OBSBasic *main, const char *section,
  92. const char *name)
  93. {
  94. const char *val = config_get_string(main->Config(), section, name);
  95. return val ? val : "";
  96. }
  97. bool YoutubeAuth::LoadInternal()
  98. {
  99. OBSBasic *main = OBSBasic::Get();
  100. const char *section_name = section.c_str();
  101. refresh_token = get_config_str(main, section_name, "RefreshToken");
  102. token = get_config_str(main, section_name, "Token");
  103. expire_time =
  104. config_get_uint(main->Config(), section_name, "ExpireTime");
  105. currentScopeVer =
  106. (int)config_get_int(main->Config(), section_name, "ScopeVer");
  107. firstLoad = false;
  108. return implicit ? !token.empty() : !refresh_token.empty();
  109. }
  110. #ifdef BROWSER_AVAILABLE
  111. static const char *ytchat_script = "\
  112. const obsCSS = document.createElement('style');\
  113. obsCSS.innerHTML = \"#panel-pages.yt-live-chat-renderer {display: none;}\
  114. yt-live-chat-viewer-engagement-message-renderer {display: none;}\";\
  115. document.querySelector('head').appendChild(obsCSS);";
  116. #endif
  117. void YoutubeAuth::LoadUI()
  118. {
  119. if (uiLoaded)
  120. return;
  121. #ifdef BROWSER_AVAILABLE
  122. if (!cef)
  123. return;
  124. OBSBasic::InitBrowserPanelSafeBlock();
  125. OBSBasic *main = OBSBasic::Get();
  126. QCefWidget *browser;
  127. QSize size = main->frameSize();
  128. QPoint pos = main->pos();
  129. chat = new YoutubeChatDock(QTStr("Auth.Chat"));
  130. chat->setObjectName(YOUTUBE_CHAT_DOCK_NAME);
  131. chat->resize(300, 600);
  132. chat->setMinimumSize(200, 300);
  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. }
  144. #endif
  145. main->NewYouTubeAppDock();
  146. if (!firstLoad) {
  147. const char *dockStateStr = config_get_string(
  148. main->Config(), service(), "DockState");
  149. QByteArray dockState =
  150. QByteArray::fromBase64(QByteArray(dockStateStr));
  151. if (main->isVisible() || !main->isMaximized())
  152. main->restoreState(dockState);
  153. }
  154. uiLoaded = true;
  155. }
  156. void YoutubeAuth::SetChatId(const QString &chat_id,
  157. const std::string &api_chat_id)
  158. {
  159. #ifdef BROWSER_AVAILABLE
  160. QString chat_url = QString(YOUTUBE_CHAT_POPOUT_URL).arg(chat_id);
  161. if (chat && chat->cefWidget) {
  162. chat->cefWidget->setURL(chat_url.toStdString());
  163. chat->SetApiChatId(api_chat_id);
  164. }
  165. #else
  166. UNUSED_PARAMETER(chat_id);
  167. UNUSED_PARAMETER(api_chat_id);
  168. #endif
  169. }
  170. void YoutubeAuth::ResetChat()
  171. {
  172. #ifdef BROWSER_AVAILABLE
  173. if (chat && chat->cefWidget) {
  174. chat->cefWidget->setURL(YOUTUBE_CHAT_PLACEHOLDER_URL);
  175. }
  176. #endif
  177. }
  178. QString YoutubeAuth::GenerateState()
  179. {
  180. char state[YOUTUBE_API_STATE_LENGTH + 1];
  181. QRandomGenerator *rng = QRandomGenerator::system();
  182. int i;
  183. for (i = 0; i < YOUTUBE_API_STATE_LENGTH; i++)
  184. state[i] = allowedChars[rng->bounded(0, allowedCount)];
  185. state[i] = 0;
  186. return state;
  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. #if defined(__APPLE__) && QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
  230. /* We can't show clickable links with the native NSAlert, so let's
  231. * force the old non-native dialog instead. */
  232. dlg.setOption(QMessageBox::Option::DontUseNativeDialog);
  233. #endif
  234. connect(&dlg, &QMessageBox::buttonClicked, &dlg,
  235. [&](QAbstractButton *) {
  236. #ifdef _DEBUG
  237. blog(LOG_DEBUG, "Action Cancelled.");
  238. #endif
  239. // TODO: Stop server.
  240. dlg.reject();
  241. });
  242. // Async Login.
  243. connect(&server, &AuthListener::ok, &dlg,
  244. [&dlg, &auth_code](QString code) {
  245. #ifdef _DEBUG
  246. blog(LOG_DEBUG, "Got youtube redirected answer: %s",
  247. QT_TO_UTF8(code));
  248. #endif
  249. auth_code = code;
  250. dlg.accept();
  251. });
  252. connect(&server, &AuthListener::fail, &dlg, [&dlg]() {
  253. #ifdef _DEBUG
  254. blog(LOG_DEBUG, "No access granted");
  255. #endif
  256. dlg.reject();
  257. });
  258. auto open_external_browser = [url]() {
  259. OpenBrowser(url);
  260. };
  261. QScopedPointer<QThread> thread(CreateQThread(open_external_browser));
  262. thread->start();
  263. #if defined(__APPLE__) && QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) && \
  264. QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
  265. const bool nativeDialogs =
  266. qApp->testAttribute(Qt::AA_DontUseNativeDialogs);
  267. App()->setAttribute(Qt::AA_DontUseNativeDialogs, true);
  268. dlg.exec();
  269. App()->setAttribute(Qt::AA_DontUseNativeDialogs, nativeDialogs);
  270. #else
  271. dlg.exec();
  272. #endif
  273. if (dlg.result() == QMessageBox::Cancel ||
  274. dlg.result() == QDialog::Rejected)
  275. return nullptr;
  276. if (!auth->GetToken(YOUTUBE_TOKEN_URL, clientid, secret,
  277. QT_TO_UTF8(redirect_uri), YOUTUBE_SCOPE_VERSION,
  278. QT_TO_UTF8(auth_code), true)) {
  279. return nullptr;
  280. }
  281. config_t *config = OBSBasic::Get()->Config();
  282. config_remove_value(config, "YouTube", "ChannelName");
  283. ChannelDescription cd;
  284. if (auth->GetChannelDescription(cd))
  285. config_set_string(config, "YouTube", "ChannelName",
  286. QT_TO_UTF8(cd.title));
  287. config_save_safe(config, "tmp", nullptr);
  288. return auth;
  289. }
  290. #ifdef BROWSER_AVAILABLE
  291. void YoutubeChatDock::SetWidget(QCefWidget *widget_)
  292. {
  293. lineEdit = new LineEditAutoResize();
  294. lineEdit->setVisible(false);
  295. lineEdit->setMaxLength(200);
  296. lineEdit->setPlaceholderText(QTStr("YouTube.Chat.Input.Placeholder"));
  297. sendButton = new QPushButton(QTStr("YouTube.Chat.Input.Send"));
  298. sendButton->setVisible(false);
  299. chatLayout = new QHBoxLayout();
  300. chatLayout->setContentsMargins(0, 0, 0, 0);
  301. chatLayout->addWidget(lineEdit, 1);
  302. chatLayout->addWidget(sendButton);
  303. QVBoxLayout *layout = new QVBoxLayout();
  304. layout->setContentsMargins(0, 0, 0, 0);
  305. layout->addWidget(widget_, 1);
  306. layout->addLayout(chatLayout);
  307. QWidget *widget = new QWidget();
  308. widget->setLayout(layout);
  309. setWidget(widget);
  310. QWidget::connect(lineEdit, &LineEditAutoResize::returnPressed, this,
  311. &YoutubeChatDock::SendChatMessage);
  312. QWidget::connect(sendButton, &QPushButton::pressed, this,
  313. &YoutubeChatDock::SendChatMessage);
  314. cefWidget.reset(widget_);
  315. }
  316. void YoutubeChatDock::SetApiChatId(const std::string &id)
  317. {
  318. this->apiChatId = id;
  319. QMetaObject::invokeMethod(this, "EnableChatInput",
  320. Qt::QueuedConnection);
  321. }
  322. void YoutubeChatDock::SendChatMessage()
  323. {
  324. const QString message = lineEdit->text();
  325. if (message == "")
  326. return;
  327. OBSBasic *main = OBSBasic::Get();
  328. YoutubeApiWrappers *apiYouTube(
  329. dynamic_cast<YoutubeApiWrappers *>(main->GetAuth()));
  330. ExecuteFuncSafeBlock([&]() {
  331. lineEdit->setText("");
  332. lineEdit->setPlaceholderText(
  333. QTStr("YouTube.Chat.Input.Sending"));
  334. if (apiYouTube->SendChatMessage(apiChatId, message)) {
  335. os_sleep_ms(3000);
  336. } else {
  337. QString error = apiYouTube->GetLastError();
  338. apiYouTube->GetTranslatedError(error);
  339. QMetaObject::invokeMethod(
  340. this, "ShowErrorMessage", Qt::QueuedConnection,
  341. Q_ARG(const QString &, error));
  342. }
  343. lineEdit->setPlaceholderText(
  344. QTStr("YouTube.Chat.Input.Placeholder"));
  345. });
  346. }
  347. void YoutubeChatDock::ShowErrorMessage(const QString &error)
  348. {
  349. QMessageBox::warning(this, QTStr("YouTube.Chat.Error.Title"),
  350. QTStr("YouTube.Chat.Error.Text").arg(error));
  351. }
  352. void YoutubeChatDock::EnableChatInput()
  353. {
  354. lineEdit->setVisible(true);
  355. sendButton->setVisible(true);
  356. }
  357. #endif