YouTubeChatDock.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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)
  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. }
  141. #else
  142. UNUSED_PARAMETER(chat_id);
  143. #endif
  144. }
  145. void YoutubeAuth::ResetChat()
  146. {
  147. #ifdef BROWSER_AVAILABLE
  148. if (chat && chat->cefWidget) {
  149. chat->cefWidget->setURL(YOUTUBE_CHAT_PLACEHOLDER_URL);
  150. }
  151. #endif
  152. }
  153. void YoutubeAuth::ReloadChat()
  154. {
  155. #ifdef BROWSER_AVAILABLE
  156. if (chat && chat->cefWidget) {
  157. chat->cefWidget->reloadPage();
  158. }
  159. #endif
  160. }
  161. QString YoutubeAuth::GenerateState()
  162. {
  163. char state[YOUTUBE_API_STATE_LENGTH + 1];
  164. QRandomGenerator *rng = QRandomGenerator::system();
  165. int i;
  166. for (i = 0; i < YOUTUBE_API_STATE_LENGTH; i++)
  167. state[i] = allowedChars[rng->bounded(0, allowedCount)];
  168. state[i] = 0;
  169. return state;
  170. }
  171. // Static.
  172. std::shared_ptr<Auth> YoutubeAuth::Login(QWidget *owner, const std::string &service)
  173. {
  174. QString auth_code;
  175. AuthListener server;
  176. auto it = std::find_if(youtubeServices.begin(), youtubeServices.end(),
  177. [service](auto &item) { return service == item.service; });
  178. if (it == youtubeServices.end()) {
  179. return nullptr;
  180. }
  181. const auto auth = std::make_shared<YoutubeApiWrappers>(*it);
  182. QString redirect_uri = QString("http://127.0.0.1:%1").arg(server.GetPort());
  183. QMessageBox dlg(owner);
  184. dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint);
  185. dlg.setWindowTitle(QTStr("YouTube.Auth.WaitingAuth.Title"));
  186. std::string clientid = YOUTUBE_CLIENTID;
  187. std::string secret = YOUTUBE_SECRET;
  188. deobfuscate_str(&clientid[0], YOUTUBE_CLIENTID_HASH);
  189. deobfuscate_str(&secret[0], YOUTUBE_SECRET_HASH);
  190. QString state;
  191. state = auth->GenerateState();
  192. server.SetState(state);
  193. QString url_template;
  194. url_template += "%1";
  195. url_template += "?response_type=code";
  196. url_template += "&client_id=%2";
  197. url_template += "&redirect_uri=%3";
  198. url_template += "&state=%4";
  199. url_template += "&scope=https://www.googleapis.com/auth/youtube";
  200. QString url = url_template.arg(YOUTUBE_AUTH_URL, clientid.c_str(), redirect_uri, state);
  201. QString text = QTStr("YouTube.Auth.WaitingAuth.Text");
  202. text = text.arg(QString("<a href='%1'>Google OAuth Service</a>").arg(url));
  203. dlg.setText(text);
  204. dlg.setTextFormat(Qt::RichText);
  205. dlg.setStandardButtons(QMessageBox::StandardButton::Cancel);
  206. #if defined(__APPLE__) && QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
  207. /* We can't show clickable links with the native NSAlert, so let's
  208. * force the old non-native dialog instead. */
  209. dlg.setOption(QMessageBox::Option::DontUseNativeDialog);
  210. #endif
  211. connect(&dlg, &QMessageBox::buttonClicked, &dlg, [&](QAbstractButton *) {
  212. #ifdef _DEBUG
  213. blog(LOG_DEBUG, "Action Cancelled.");
  214. #endif
  215. // TODO: Stop server.
  216. dlg.reject();
  217. });
  218. // Async Login.
  219. connect(&server, &AuthListener::ok, &dlg, [&dlg, &auth_code](QString code) {
  220. #ifdef _DEBUG
  221. blog(LOG_DEBUG, "Got youtube redirected answer: %s", QT_TO_UTF8(code));
  222. #endif
  223. auth_code = code;
  224. dlg.accept();
  225. });
  226. connect(&server, &AuthListener::fail, &dlg, [&dlg]() {
  227. #ifdef _DEBUG
  228. blog(LOG_DEBUG, "No access granted");
  229. #endif
  230. dlg.reject();
  231. });
  232. auto open_external_browser = [url]() {
  233. OpenBrowser(url);
  234. };
  235. QScopedPointer<QThread> thread(CreateQThread(open_external_browser));
  236. thread->start();
  237. #if defined(__APPLE__) && QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) && QT_VERSION < QT_VERSION_CHECK(6, 6, 0)
  238. const bool nativeDialogs = qApp->testAttribute(Qt::AA_DontUseNativeDialogs);
  239. App()->setAttribute(Qt::AA_DontUseNativeDialogs, true);
  240. dlg.exec();
  241. App()->setAttribute(Qt::AA_DontUseNativeDialogs, nativeDialogs);
  242. #else
  243. dlg.exec();
  244. #endif
  245. if (dlg.result() == QMessageBox::Cancel || dlg.result() == QDialog::Rejected)
  246. return nullptr;
  247. if (!auth->GetToken(YOUTUBE_TOKEN_URL, clientid, secret, QT_TO_UTF8(redirect_uri), YOUTUBE_SCOPE_VERSION,
  248. QT_TO_UTF8(auth_code), true)) {
  249. return nullptr;
  250. }
  251. config_t *config = OBSBasic::Get()->Config();
  252. config_remove_value(config, "YouTube", "ChannelName");
  253. ChannelDescription cd;
  254. if (auth->GetChannelDescription(cd))
  255. config_set_string(config, "YouTube", "ChannelName", QT_TO_UTF8(cd.title));
  256. config_save_safe(config, "tmp", nullptr);
  257. return auth;
  258. }
  259. #ifdef BROWSER_AVAILABLE
  260. void YoutubeChatDock::YoutubeCookieCheck()
  261. {
  262. QPointer<YoutubeChatDock> this_ = this;
  263. auto cb = [this_](bool currentlyLoggedIn) {
  264. bool previouslyLoggedIn = this_->isLoggedIn;
  265. this_->isLoggedIn = currentlyLoggedIn;
  266. bool loginStateChanged = (currentlyLoggedIn && !previouslyLoggedIn) ||
  267. (!currentlyLoggedIn && previouslyLoggedIn);
  268. if (loginStateChanged) {
  269. OBSBasic *main = OBSBasic::Get();
  270. if (main->GetYouTubeAppDock() != nullptr) {
  271. QMetaObject::invokeMethod(main->GetYouTubeAppDock(), "SettingsUpdated",
  272. Qt::QueuedConnection, Q_ARG(bool, !currentlyLoggedIn));
  273. }
  274. }
  275. };
  276. if (panel_cookies) {
  277. panel_cookies->CheckForCookie("https://www.youtube.com", "SID", cb);
  278. }
  279. }
  280. #endif