auth-twitch.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. #include "auth-twitch.hpp"
  2. #include <QPushButton>
  3. #include <QHBoxLayout>
  4. #include <QVBoxLayout>
  5. #include <qt-wrappers.hpp>
  6. #include <obs-app.hpp>
  7. #include "window-dock-browser.hpp"
  8. #include "window-basic-main.hpp"
  9. #include "remote-text.hpp"
  10. #include <json11.hpp>
  11. #include "ui-config.h"
  12. #include "obf.h"
  13. using namespace json11;
  14. /* ------------------------------------------------------------------------- */
  15. #define TWITCH_AUTH_URL "https://obsproject.com/app-auth/twitch?action=redirect"
  16. #define TWITCH_TOKEN_URL "https://obsproject.com/app-auth/twitch-token"
  17. #define ACCEPT_HEADER "Accept: application/vnd.twitchtv.v5+json"
  18. #define TWITCH_SCOPE_VERSION 1
  19. static Auth::Def twitchDef = {"Twitch", Auth::Type::OAuth_StreamKey};
  20. /* ------------------------------------------------------------------------- */
  21. TwitchAuth::TwitchAuth(const Def &d) : OAuthStreamKey(d)
  22. {
  23. if (!cef)
  24. return;
  25. cef->add_popup_whitelist_url(
  26. "https://twitch.tv/popout/frankerfacez/chat?ffz-settings",
  27. this);
  28. uiLoadTimer.setSingleShot(true);
  29. uiLoadTimer.setInterval(500);
  30. connect(&uiLoadTimer, &QTimer::timeout, this,
  31. &TwitchAuth::TryLoadSecondaryUIPanes);
  32. }
  33. bool TwitchAuth::GetChannelInfo()
  34. try {
  35. std::string client_id = TWITCH_CLIENTID;
  36. deobfuscate_str(&client_id[0], TWITCH_HASH);
  37. if (!GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION))
  38. return false;
  39. if (token.empty())
  40. return false;
  41. if (!key_.empty())
  42. return true;
  43. std::string auth;
  44. auth += "Authorization: OAuth ";
  45. auth += token;
  46. std::vector<std::string> headers;
  47. headers.push_back(std::string("Client-ID: ") + client_id);
  48. headers.push_back(ACCEPT_HEADER);
  49. headers.push_back(std::move(auth));
  50. std::string output;
  51. std::string error;
  52. long error_code = 0;
  53. bool success = false;
  54. auto func = [&]() {
  55. success = GetRemoteFile("https://api.twitch.tv/kraken/channel",
  56. output, error, &error_code,
  57. "application/json", nullptr, headers,
  58. nullptr, 5);
  59. };
  60. ExecThreadedWithoutBlocking(
  61. func, QTStr("Auth.LoadingChannel.Title"),
  62. QTStr("Auth.LoadingChannel.Text").arg(service()));
  63. if (error_code == 403) {
  64. OBSMessageBox::warning(OBSBasic::Get(),
  65. Str("TwitchAuth.TwoFactorFail.Title"),
  66. Str("TwitchAuth.TwoFactorFail.Text"),
  67. true);
  68. blog(LOG_WARNING, "%s: %s", __FUNCTION__,
  69. "Got 403 from Twitch, user probably does not "
  70. "have two-factor authentication enabled on "
  71. "their account");
  72. return false;
  73. }
  74. if (!success || output.empty())
  75. throw ErrorInfo("Failed to get text from remote", error);
  76. Json json = Json::parse(output, error);
  77. if (!error.empty())
  78. throw ErrorInfo("Failed to parse json", error);
  79. error = json["error"].string_value();
  80. if (!error.empty()) {
  81. if (error == "Unauthorized") {
  82. if (RetryLogin()) {
  83. return GetChannelInfo();
  84. }
  85. throw ErrorInfo(error, json["message"].string_value());
  86. }
  87. throw ErrorInfo(error,
  88. json["error_description"].string_value());
  89. }
  90. name = json["name"].string_value();
  91. key_ = json["stream_key"].string_value();
  92. return true;
  93. } catch (ErrorInfo info) {
  94. QString title = QTStr("Auth.ChannelFailure.Title");
  95. QString text = QTStr("Auth.ChannelFailure.Text")
  96. .arg(service(), info.message.c_str(),
  97. info.error.c_str());
  98. QMessageBox::warning(OBSBasic::Get(), title, text);
  99. blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(),
  100. info.error.c_str());
  101. return false;
  102. }
  103. void TwitchAuth::SaveInternal()
  104. {
  105. OBSBasic *main = OBSBasic::Get();
  106. config_set_string(main->Config(), service(), "Name", name.c_str());
  107. if (uiLoaded) {
  108. config_set_string(main->Config(), service(), "DockState",
  109. main->saveState().toBase64().constData());
  110. }
  111. OAuthStreamKey::SaveInternal();
  112. }
  113. static inline std::string get_config_str(OBSBasic *main, const char *section,
  114. const char *name)
  115. {
  116. const char *val = config_get_string(main->Config(), section, name);
  117. return val ? val : "";
  118. }
  119. bool TwitchAuth::LoadInternal()
  120. {
  121. if (!cef)
  122. return false;
  123. OBSBasic *main = OBSBasic::Get();
  124. name = get_config_str(main, service(), "Name");
  125. firstLoad = false;
  126. return OAuthStreamKey::LoadInternal();
  127. }
  128. static const char *ffz_script = "\
  129. var ffz = document.createElement('script');\
  130. ffz.setAttribute('src','https://cdn.frankerfacez.com/script/script.min.js');\
  131. document.head.appendChild(ffz);";
  132. static const char *bttv_script = "\
  133. localStorage.setItem('bttv_clickTwitchEmotes', true);\
  134. localStorage.setItem('bttv_darkenedMode', true);\
  135. localStorage.setItem('bttv_bttvGIFEmotes', true);\
  136. var bttv = document.createElement('script');\
  137. bttv.setAttribute('src','https://cdn.betterttv.net/betterttv.js');\
  138. document.head.appendChild(bttv);";
  139. static const char *referrer_script1 = "\
  140. Object.defineProperty(document, 'referrer', {get : function() { return '";
  141. static const char *referrer_script2 = "'; }});";
  142. void TwitchAuth::LoadUI()
  143. {
  144. if (!cef)
  145. return;
  146. if (uiLoaded)
  147. return;
  148. if (!GetChannelInfo())
  149. return;
  150. OBSBasic::InitBrowserPanelSafeBlock();
  151. OBSBasic *main = OBSBasic::Get();
  152. QCefWidget *browser;
  153. std::string url;
  154. std::string script;
  155. std::string moderation_tools_url;
  156. moderation_tools_url = "https://www.twitch.tv/";
  157. moderation_tools_url += name;
  158. moderation_tools_url += "/dashboard/settings/moderation?no-reload=true";
  159. /* ----------------------------------- */
  160. url = "https://www.twitch.tv/popout/";
  161. url += name;
  162. url += "/chat";
  163. QSize size = main->frameSize();
  164. QPoint pos = main->pos();
  165. chat.reset(new BrowserDock());
  166. chat->setObjectName("twitchChat");
  167. chat->resize(300, 600);
  168. chat->setMinimumSize(200, 300);
  169. chat->setWindowTitle(QTStr("Auth.Chat"));
  170. chat->setAllowedAreas(Qt::AllDockWidgetAreas);
  171. browser = cef->create_widget(nullptr, url, panel_cookies);
  172. chat->SetWidget(browser);
  173. cef->add_force_popup_url(moderation_tools_url, chat.data());
  174. script = "localStorage.setItem('twilight.theme', 1);";
  175. script += bttv_script;
  176. script += ffz_script;
  177. browser->setStartupScript(script);
  178. main->addDockWidget(Qt::RightDockWidgetArea, chat.data());
  179. chatMenu.reset(main->AddDockWidget(chat.data()));
  180. /* ----------------------------------- */
  181. chat->setFloating(true);
  182. chat->move(pos.x() + size.width() - chat->width() - 50, pos.y() + 50);
  183. if (firstLoad) {
  184. chat->setVisible(true);
  185. } else {
  186. const char *dockStateStr = config_get_string(
  187. main->Config(), service(), "DockState");
  188. QByteArray dockState =
  189. QByteArray::fromBase64(QByteArray(dockStateStr));
  190. main->restoreState(dockState);
  191. }
  192. TryLoadSecondaryUIPanes();
  193. uiLoaded = true;
  194. }
  195. void TwitchAuth::LoadSecondaryUIPanes()
  196. {
  197. OBSBasic *main = OBSBasic::Get();
  198. QCefWidget *browser;
  199. std::string url;
  200. std::string script;
  201. QSize size = main->frameSize();
  202. QPoint pos = main->pos();
  203. script = "localStorage.setItem('twilight.theme', 1);";
  204. script += referrer_script1;
  205. script += "https://www.twitch.tv/";
  206. script += name;
  207. script += "/dashboard/live";
  208. script += referrer_script2;
  209. script += bttv_script;
  210. script += ffz_script;
  211. /* ----------------------------------- */
  212. url = "https://www.twitch.tv/popout/";
  213. url += name;
  214. url += "/dashboard/live/stream-info";
  215. info.reset(new BrowserDock());
  216. info->setObjectName("twitchInfo");
  217. info->resize(300, 650);
  218. info->setMinimumSize(200, 300);
  219. info->setWindowTitle(QTStr("Auth.StreamInfo"));
  220. info->setAllowedAreas(Qt::AllDockWidgetAreas);
  221. browser = cef->create_widget(nullptr, url, panel_cookies);
  222. info->SetWidget(browser);
  223. browser->setStartupScript(script);
  224. main->addDockWidget(Qt::RightDockWidgetArea, info.data());
  225. infoMenu.reset(main->AddDockWidget(info.data()));
  226. /* ----------------------------------- */
  227. url = "https://www.twitch.tv/popout/";
  228. url += name;
  229. url += "/dashboard/live/stats";
  230. stat.reset(new BrowserDock());
  231. stat->setObjectName("twitchStats");
  232. stat->resize(200, 250);
  233. stat->setMinimumSize(200, 150);
  234. stat->setWindowTitle(QTStr("TwitchAuth.Stats"));
  235. stat->setAllowedAreas(Qt::AllDockWidgetAreas);
  236. browser = cef->create_widget(nullptr, url, panel_cookies);
  237. stat->SetWidget(browser);
  238. browser->setStartupScript(script);
  239. main->addDockWidget(Qt::RightDockWidgetArea, stat.data());
  240. statMenu.reset(main->AddDockWidget(stat.data()));
  241. /* ----------------------------------- */
  242. url = "https://www.twitch.tv/popout/";
  243. url += name;
  244. url += "/dashboard/live/activity-feed";
  245. feed.reset(new BrowserDock());
  246. feed->setObjectName("twitchFeed");
  247. feed->resize(300, 650);
  248. feed->setMinimumSize(200, 300);
  249. feed->setWindowTitle(QTStr("TwitchAuth.Feed"));
  250. feed->setAllowedAreas(Qt::AllDockWidgetAreas);
  251. browser = cef->create_widget(nullptr, url, panel_cookies);
  252. feed->SetWidget(browser);
  253. browser->setStartupScript(script);
  254. main->addDockWidget(Qt::RightDockWidgetArea, feed.data());
  255. feedMenu.reset(main->AddDockWidget(feed.data()));
  256. /* ----------------------------------- */
  257. info->setFloating(true);
  258. stat->setFloating(true);
  259. feed->setFloating(true);
  260. QSize statSize = stat->frameSize();
  261. info->move(pos.x() + 50, pos.y() + 50);
  262. stat->move(pos.x() + size.width() / 2 - statSize.width() / 2,
  263. pos.y() + size.height() / 2 - statSize.height() / 2);
  264. feed->move(pos.x() + 100, pos.y() + 100);
  265. if (firstLoad) {
  266. info->setVisible(true);
  267. stat->setVisible(false);
  268. feed->setVisible(false);
  269. } else {
  270. uint32_t lastVersion = config_get_int(App()->GlobalConfig(),
  271. "General", "LastVersion");
  272. if (lastVersion <= MAKE_SEMANTIC_VERSION(23, 0, 2)) {
  273. feed->setVisible(false);
  274. }
  275. const char *dockStateStr = config_get_string(
  276. main->Config(), service(), "DockState");
  277. QByteArray dockState =
  278. QByteArray::fromBase64(QByteArray(dockStateStr));
  279. main->restoreState(dockState);
  280. }
  281. }
  282. /* Twitch.tv has an OAuth for itself. If we try to load multiple panel pages
  283. * at once before it's OAuth'ed itself, they will all try to perform the auth
  284. * process at the same time, get their own request codes, and only the last
  285. * code will be valid -- so one or more panels are guaranteed to fail.
  286. *
  287. * To solve this, we want to load just one panel first (the chat), and then all
  288. * subsequent panels should only be loaded once we know that Twitch has auth'ed
  289. * itself (if the cookie "auth-token" exists for twitch.tv).
  290. *
  291. * This is annoying to deal with. */
  292. void TwitchAuth::TryLoadSecondaryUIPanes()
  293. {
  294. QPointer<TwitchAuth> this_ = this;
  295. auto cb = [this_](bool found) {
  296. if (!this_) {
  297. return;
  298. }
  299. if (!found) {
  300. QMetaObject::invokeMethod(&this_->uiLoadTimer, "start");
  301. } else {
  302. QMetaObject::invokeMethod(this_,
  303. "LoadSecondaryUIPanes");
  304. }
  305. };
  306. panel_cookies->CheckForCookie("https://www.twitch.tv", "auth-token",
  307. cb);
  308. }
  309. bool TwitchAuth::RetryLogin()
  310. {
  311. OAuthLogin login(OBSBasic::Get(), TWITCH_AUTH_URL, false);
  312. if (login.exec() == QDialog::Rejected) {
  313. return false;
  314. }
  315. std::shared_ptr<TwitchAuth> auth =
  316. std::make_shared<TwitchAuth>(twitchDef);
  317. std::string client_id = TWITCH_CLIENTID;
  318. deobfuscate_str(&client_id[0], TWITCH_HASH);
  319. return GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  320. QT_TO_UTF8(login.GetCode()), true);
  321. }
  322. std::shared_ptr<Auth> TwitchAuth::Login(QWidget *parent)
  323. {
  324. OAuthLogin login(parent, TWITCH_AUTH_URL, false);
  325. if (login.exec() == QDialog::Rejected) {
  326. return nullptr;
  327. }
  328. std::shared_ptr<TwitchAuth> auth =
  329. std::make_shared<TwitchAuth>(twitchDef);
  330. std::string client_id = TWITCH_CLIENTID;
  331. deobfuscate_str(&client_id[0], TWITCH_HASH);
  332. if (!auth->GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  333. QT_TO_UTF8(login.GetCode()))) {
  334. return nullptr;
  335. }
  336. std::string error;
  337. if (auth->GetChannelInfo()) {
  338. return auth;
  339. }
  340. return nullptr;
  341. }
  342. static std::shared_ptr<Auth> CreateTwitchAuth()
  343. {
  344. return std::make_shared<TwitchAuth>(twitchDef);
  345. }
  346. static void DeleteCookies()
  347. {
  348. if (panel_cookies)
  349. panel_cookies->DeleteCookies("twitch.tv", std::string());
  350. }
  351. void RegisterTwitchAuth()
  352. {
  353. OAuth::RegisterOAuth(twitchDef, CreateTwitchAuth, TwitchAuth::Login,
  354. DeleteCookies);
  355. }