auth-twitch.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 <json11.hpp>
  10. #include "ui-config.h"
  11. #include "obf.h"
  12. using namespace json11;
  13. #include <browser-panel.hpp>
  14. extern QCef *cef;
  15. extern QCefCookieManager *panel_cookies;
  16. /* ------------------------------------------------------------------------- */
  17. #define TWITCH_AUTH_URL \
  18. "https://obsproject.com/app-auth/twitch?action=redirect"
  19. #define TWITCH_TOKEN_URL \
  20. "https://obsproject.com/app-auth/twitch-token"
  21. #define ACCEPT_HEADER \
  22. "Accept: application/vnd.twitchtv.v5+json"
  23. #define TWITCH_SCOPE_VERSION 1
  24. static Auth::Def twitchDef = {
  25. "Twitch",
  26. Auth::Type::OAuth_StreamKey
  27. };
  28. /* ------------------------------------------------------------------------- */
  29. TwitchAuth::TwitchAuth(const Def &d)
  30. : OAuthStreamKey(d)
  31. {
  32. cef->add_popup_whitelist_url(
  33. "https://twitch.tv/popout/frankerfacez/chat?ffz-settings",
  34. this);
  35. uiLoadTimer.setSingleShot(true);
  36. uiLoadTimer.setInterval(500);
  37. connect(&uiLoadTimer, &QTimer::timeout,
  38. this, &TwitchAuth::TryLoadSecondaryUIPanes);
  39. }
  40. bool TwitchAuth::GetChannelInfo()
  41. try {
  42. std::string client_id = TWITCH_CLIENTID;
  43. deobfuscate_str(&client_id[0], TWITCH_HASH);
  44. if (!GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION))
  45. return false;
  46. if (token.empty())
  47. return false;
  48. if (!key_.empty())
  49. return true;
  50. std::string auth;
  51. auth += "Authorization: OAuth ";
  52. auth += token;
  53. std::vector<std::string> headers;
  54. headers.push_back(std::string("Client-ID: ") + client_id);
  55. headers.push_back(ACCEPT_HEADER);
  56. headers.push_back(std::move(auth));
  57. std::string output;
  58. std::string error;
  59. bool success = false;
  60. auto func = [&] () {
  61. success = GetRemoteFile(
  62. "https://api.twitch.tv/kraken/channel",
  63. output,
  64. error,
  65. nullptr,
  66. "application/json",
  67. nullptr,
  68. headers,
  69. nullptr,
  70. 5);
  71. };
  72. ExecThreadedWithoutBlocking(
  73. func,
  74. QTStr("Auth.LoadingChannel.Title"),
  75. QTStr("Auth.LoadingChannel.Text").arg(service()));
  76. if (!success || output.empty())
  77. throw ErrorInfo("Failed to get text from remote", error);
  78. Json json = Json::parse(output, error);
  79. if (!error.empty())
  80. throw ErrorInfo("Failed to parse json", error);
  81. error = json["error"].string_value();
  82. if (!error.empty()) {
  83. if (error == "Unauthorized") {
  84. if (RetryLogin()) {
  85. return GetChannelInfo();
  86. }
  87. throw ErrorInfo(error,
  88. json["message"].string_value());
  89. }
  90. throw ErrorInfo(error, json["error_description"].string_value());
  91. }
  92. name = json["name"].string_value();
  93. key_ = json["stream_key"].string_value();
  94. return true;
  95. } catch (ErrorInfo info) {
  96. QString title = QTStr("Auth.ChannelFailure.Title");
  97. QString text = QTStr("Auth.ChannelFailure.Text")
  98. .arg(service(), info.message.c_str(), info.error.c_str());
  99. QMessageBox::warning(OBSBasic::Get(), title, text);
  100. blog(LOG_WARNING, "%s: %s: %s",
  101. __FUNCTION__,
  102. 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(
  117. OBSBasic *main,
  118. const char *section,
  119. const char *name)
  120. {
  121. const char *val = config_get_string(main->Config(), section, name);
  122. return val ? val : "";
  123. }
  124. bool TwitchAuth::LoadInternal()
  125. {
  126. if (!cef)
  127. return false;
  128. OBSBasic *main = OBSBasic::Get();
  129. name = get_config_str(main, service(), "Name");
  130. firstLoad = false;
  131. return OAuthStreamKey::LoadInternal();
  132. }
  133. class TwitchWidget : public QDockWidget {
  134. public:
  135. inline TwitchWidget() : QDockWidget() {}
  136. QScopedPointer<QCefWidget> widget;
  137. inline void SetWidget(QCefWidget *widget_)
  138. {
  139. setWidget(widget_);
  140. widget.reset(widget_);
  141. }
  142. };
  143. static const char *ffz_script = "\
  144. var ffz = document.createElement('script');\
  145. ffz.setAttribute('src','https://cdn.frankerfacez.com/script/script.min.js');\
  146. document.head.appendChild(ffz);";
  147. static const char *bttv_script = "\
  148. localStorage.setItem('bttv_clickTwitchEmotes', true);\
  149. localStorage.setItem('bttv_darkenedMode', true);\
  150. localStorage.setItem('bttv_bttvGIFEmotes', true);\
  151. var bttv = document.createElement('script');\
  152. bttv.setAttribute('src','https://cdn.betterttv.net/betterttv.js');\
  153. document.head.appendChild(bttv);";
  154. static const char *referrer_script1 = "\
  155. Object.defineProperty(document, 'referrer', {get : function() { return '";
  156. static const char *referrer_script2 = "'; }});";
  157. void TwitchAuth::LoadUI()
  158. {
  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(main->Config(),
  199. 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. info->setFloating(true);
  255. stat->setFloating(true);
  256. QSize statSize = stat->frameSize();
  257. info->move(pos.x() + 50, pos.y() + 50);
  258. stat->move(pos.x() + size.width() / 2 - statSize.width() / 2,
  259. pos.y() + size.height() / 2 - statSize.height() / 2);
  260. if (firstLoad) {
  261. info->setVisible(true);
  262. stat->setVisible(false);
  263. } else {
  264. const char *dockStateStr = config_get_string(main->Config(),
  265. service(), "DockState");
  266. QByteArray dockState =
  267. QByteArray::fromBase64(QByteArray(dockStateStr));
  268. main->restoreState(dockState);
  269. }
  270. }
  271. /* Twitch.tv has an OAuth for itself. If we try to load multiple panel pages
  272. * at once before it's OAuth'ed itself, they will all try to perform the auth
  273. * process at the same time, get their own request codes, and only the last
  274. * code will be valid -- so one or more panels are guaranteed to fail.
  275. *
  276. * To solve this, we want to load just one panel first (the chat), and then all
  277. * subsequent panels should only be loaded once we know that Twitch has auth'ed
  278. * itself (if the cookie "auth-token" exists for twitch.tv).
  279. *
  280. * This is annoying to deal with. */
  281. void TwitchAuth::TryLoadSecondaryUIPanes()
  282. {
  283. QPointer<TwitchAuth> this_ = this;
  284. auto cb = [this_] (bool found)
  285. {
  286. if (!this_) {
  287. return;
  288. }
  289. if (!found) {
  290. QMetaObject::invokeMethod(&this_->uiLoadTimer,
  291. "start");
  292. } else {
  293. QMetaObject::invokeMethod(this_, "LoadSecondaryUIPanes");
  294. }
  295. };
  296. panel_cookies->CheckForCookie("https://www.twitch.tv", "auth-token", cb);
  297. }
  298. bool TwitchAuth::RetryLogin()
  299. {
  300. OAuthLogin login(OBSBasic::Get(), TWITCH_AUTH_URL, false);
  301. if (login.exec() == QDialog::Rejected) {
  302. return false;
  303. }
  304. std::shared_ptr<TwitchAuth> auth = std::make_shared<TwitchAuth>(twitchDef);
  305. std::string client_id = TWITCH_CLIENTID;
  306. deobfuscate_str(&client_id[0], TWITCH_HASH);
  307. return GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  308. QT_TO_UTF8(login.GetCode()), true);
  309. }
  310. std::shared_ptr<Auth> TwitchAuth::Login(QWidget *parent)
  311. {
  312. OAuthLogin login(parent, TWITCH_AUTH_URL, false);
  313. if (login.exec() == QDialog::Rejected) {
  314. return nullptr;
  315. }
  316. std::shared_ptr<TwitchAuth> auth = std::make_shared<TwitchAuth>(twitchDef);
  317. std::string client_id = TWITCH_CLIENTID;
  318. deobfuscate_str(&client_id[0], TWITCH_HASH);
  319. if (!auth->GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  320. QT_TO_UTF8(login.GetCode()))) {
  321. return nullptr;
  322. }
  323. std::string error;
  324. if (auth->GetChannelInfo()) {
  325. return auth;
  326. }
  327. return nullptr;
  328. }
  329. static std::shared_ptr<Auth> CreateTwitchAuth()
  330. {
  331. return std::make_shared<TwitchAuth>(twitchDef);
  332. }
  333. static void DeleteCookies()
  334. {
  335. if (panel_cookies)
  336. panel_cookies->DeleteCookies("twitch.tv", std::string());
  337. }
  338. void RegisterTwitchAuth()
  339. {
  340. OAuth::RegisterOAuth(
  341. twitchDef,
  342. CreateTwitchAuth,
  343. TwitchAuth::Login,
  344. DeleteCookies);
  345. }