1
0

auth-twitch.cpp 13 KB

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