auth-youtube.cpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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. #ifdef WIN32
  10. #include <windows.h>
  11. #include <shellapi.h>
  12. #pragma comment(lib, "shell32")
  13. #endif
  14. #include "auth-listener.hpp"
  15. #include "obs-app.hpp"
  16. #include "qt-wrappers.hpp"
  17. #include "ui-config.h"
  18. #include "youtube-api-wrappers.hpp"
  19. #include "window-basic-main.hpp"
  20. #include "obf.h"
  21. using namespace json11;
  22. /* ------------------------------------------------------------------------- */
  23. #define YOUTUBE_AUTH_URL "https://accounts.google.com/o/oauth2/v2/auth"
  24. #define YOUTUBE_TOKEN_URL "https://www.googleapis.com/oauth2/v4/token"
  25. #define YOUTUBE_SCOPE_VERSION 1
  26. #define YOUTUBE_API_STATE_LENGTH 32
  27. #define SECTION_NAME "YouTube"
  28. static const char allowedChars[] =
  29. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  30. static const int allowedCount = static_cast<int>(sizeof(allowedChars) - 1);
  31. /* ------------------------------------------------------------------------- */
  32. static inline void OpenBrowser(const QString auth_uri)
  33. {
  34. QUrl url(auth_uri, QUrl::StrictMode);
  35. QDesktopServices::openUrl(url);
  36. }
  37. void RegisterYoutubeAuth()
  38. {
  39. for (auto &service : youtubeServices) {
  40. OAuth::RegisterOAuth(
  41. service,
  42. [service]() {
  43. return std::make_shared<YoutubeApiWrappers>(
  44. service);
  45. },
  46. YoutubeAuth::Login, []() { return; });
  47. }
  48. }
  49. YoutubeAuth::YoutubeAuth(const Def &d)
  50. : OAuthStreamKey(d), section(SECTION_NAME)
  51. {
  52. }
  53. bool YoutubeAuth::RetryLogin()
  54. {
  55. return true;
  56. }
  57. void YoutubeAuth::SaveInternal()
  58. {
  59. OBSBasic *main = OBSBasic::Get();
  60. config_set_string(main->Config(), service(), "DockState",
  61. main->saveState().toBase64().constData());
  62. const char *section_name = section.c_str();
  63. config_set_string(main->Config(), section_name, "RefreshToken",
  64. refresh_token.c_str());
  65. config_set_string(main->Config(), section_name, "Token", token.c_str());
  66. config_set_uint(main->Config(), section_name, "ExpireTime",
  67. expire_time);
  68. config_set_int(main->Config(), section_name, "ScopeVer",
  69. currentScopeVer);
  70. }
  71. static inline std::string get_config_str(OBSBasic *main, const char *section,
  72. const char *name)
  73. {
  74. const char *val = config_get_string(main->Config(), section, name);
  75. return val ? val : "";
  76. }
  77. bool YoutubeAuth::LoadInternal()
  78. {
  79. OBSBasic *main = OBSBasic::Get();
  80. const char *section_name = section.c_str();
  81. refresh_token = get_config_str(main, section_name, "RefreshToken");
  82. token = get_config_str(main, section_name, "Token");
  83. expire_time =
  84. config_get_uint(main->Config(), section_name, "ExpireTime");
  85. currentScopeVer =
  86. (int)config_get_int(main->Config(), section_name, "ScopeVer");
  87. return implicit ? !token.empty() : !refresh_token.empty();
  88. }
  89. void YoutubeAuth::LoadUI()
  90. {
  91. uiLoaded = true;
  92. }
  93. QString YoutubeAuth::GenerateState()
  94. {
  95. std::uniform_int_distribution<> distr(0, allowedCount);
  96. std::string result;
  97. result.reserve(YOUTUBE_API_STATE_LENGTH);
  98. std::generate_n(std::back_inserter(result), YOUTUBE_API_STATE_LENGTH,
  99. [&] {
  100. return static_cast<char>(
  101. allowedChars[distr(randomSeed)]);
  102. });
  103. return result.c_str();
  104. }
  105. // Static.
  106. std::shared_ptr<Auth> YoutubeAuth::Login(QWidget *owner,
  107. const std::string &service)
  108. {
  109. QString auth_code;
  110. AuthListener server;
  111. auto it = std::find_if(youtubeServices.begin(), youtubeServices.end(),
  112. [service](auto &item) {
  113. return service == item.service;
  114. });
  115. if (it == youtubeServices.end()) {
  116. return nullptr;
  117. }
  118. const auto auth = std::make_shared<YoutubeApiWrappers>(*it);
  119. QString redirect_uri =
  120. QString("http://127.0.0.1:%1").arg(server.GetPort());
  121. QMessageBox dlg(owner);
  122. dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint);
  123. dlg.setWindowTitle(QTStr("YouTube.Auth.WaitingAuth.Title"));
  124. std::string clientid = YOUTUBE_CLIENTID;
  125. std::string secret = YOUTUBE_SECRET;
  126. deobfuscate_str(&clientid[0], YOUTUBE_CLIENTID_HASH);
  127. deobfuscate_str(&secret[0], YOUTUBE_SECRET_HASH);
  128. QString url_template;
  129. url_template += "%1";
  130. url_template += "?response_type=code";
  131. url_template += "&client_id=%2";
  132. url_template += "&redirect_uri=%3";
  133. url_template += "&state=%4";
  134. url_template += "&scope=https://www.googleapis.com/auth/youtube";
  135. QString url = url_template.arg(YOUTUBE_AUTH_URL, clientid.c_str(),
  136. redirect_uri, auth->GenerateState());
  137. QString text = QTStr("YouTube.Auth.WaitingAuth.Text");
  138. text = text.arg(
  139. QString("<a href='%1'>Google OAuth Service</a>").arg(url));
  140. dlg.setText(text);
  141. dlg.setTextFormat(Qt::RichText);
  142. dlg.setStandardButtons(QMessageBox::StandardButton::Cancel);
  143. connect(&dlg, &QMessageBox::buttonClicked, &dlg,
  144. [&](QAbstractButton *) {
  145. #ifdef _DEBUG
  146. blog(LOG_DEBUG, "Action Cancelled.");
  147. #endif
  148. // TODO: Stop server.
  149. dlg.reject();
  150. });
  151. // Async Login.
  152. connect(&server, &AuthListener::ok, &dlg,
  153. [&dlg, &auth_code](QString code) {
  154. #ifdef _DEBUG
  155. blog(LOG_DEBUG, "Got youtube redirected answer: %s",
  156. QT_TO_UTF8(code));
  157. #endif
  158. auth_code = code;
  159. dlg.accept();
  160. });
  161. connect(&server, &AuthListener::fail, &dlg, [&dlg]() {
  162. #ifdef _DEBUG
  163. blog(LOG_DEBUG, "No access granted");
  164. #endif
  165. dlg.reject();
  166. });
  167. auto open_external_browser = [url]() { OpenBrowser(url); };
  168. QScopedPointer<QThread> thread(CreateQThread(open_external_browser));
  169. thread->start();
  170. dlg.exec();
  171. if (!auth->GetToken(YOUTUBE_TOKEN_URL, clientid, secret,
  172. QT_TO_UTF8(redirect_uri), YOUTUBE_SCOPE_VERSION,
  173. QT_TO_UTF8(auth_code), true)) {
  174. return nullptr;
  175. }
  176. return auth;
  177. }