auth-twitch.cpp 12 KB

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