auth-twitch.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. /* ----------------------------------- */
  169. url = "https://www.twitch.tv/popout/";
  170. url += name;
  171. url += "/chat";
  172. QSize size = main->frameSize();
  173. QPoint pos = main->pos();
  174. chat.reset(new TwitchWidget());
  175. chat->setObjectName("twitchChat");
  176. chat->resize(300, 600);
  177. chat->setMinimumSize(200, 300);
  178. chat->setWindowTitle(QTStr("Auth.Chat"));
  179. chat->setAllowedAreas(Qt::AllDockWidgetAreas);
  180. browser = cef->create_widget(nullptr, url, panel_cookies);
  181. chat->SetWidget(browser);
  182. script = bttv_script;
  183. script += ffz_script;
  184. browser->setStartupScript(script);
  185. main->addDockWidget(Qt::RightDockWidgetArea, chat.data());
  186. chatMenu.reset(main->AddDockWidget(chat.data()));
  187. /* ----------------------------------- */
  188. chat->setFloating(true);
  189. chat->move(pos.x() + size.width() - chat->width() - 50, pos.y() + 50);
  190. if (firstLoad) {
  191. chat->setVisible(true);
  192. } else {
  193. const char *dockStateStr = config_get_string(main->Config(),
  194. service(), "DockState");
  195. QByteArray dockState =
  196. QByteArray::fromBase64(QByteArray(dockStateStr));
  197. main->restoreState(dockState);
  198. }
  199. TryLoadSecondaryUIPanes();
  200. uiLoaded = true;
  201. }
  202. void TwitchAuth::LoadSecondaryUIPanes()
  203. {
  204. OBSBasic *main = OBSBasic::Get();
  205. QCefWidget *browser;
  206. std::string url;
  207. std::string script;
  208. QSize size = main->frameSize();
  209. QPoint pos = main->pos();
  210. script = "localStorage.setItem('twilight.theme', 1);";
  211. script += referrer_script1;
  212. script += "https://www.twitch.tv/";
  213. script += name;
  214. script += "/dashboard/live";
  215. script += referrer_script2;
  216. script += bttv_script;
  217. script += ffz_script;
  218. /* ----------------------------------- */
  219. url = "https://www.twitch.tv/popout/";
  220. url += name;
  221. url += "/dashboard/live/stream-info";
  222. info.reset(new TwitchWidget());
  223. info->setObjectName("twitchInfo");
  224. info->resize(300, 650);
  225. info->setMinimumSize(200, 300);
  226. info->setWindowTitle(QTStr("Auth.StreamInfo"));
  227. info->setAllowedAreas(Qt::AllDockWidgetAreas);
  228. browser = cef->create_widget(nullptr, url, panel_cookies);
  229. info->SetWidget(browser);
  230. browser->setStartupScript(script);
  231. main->addDockWidget(Qt::RightDockWidgetArea, info.data());
  232. infoMenu.reset(main->AddDockWidget(info.data()));
  233. /* ----------------------------------- */
  234. url = "https://www.twitch.tv/popout/";
  235. url += name;
  236. url += "/dashboard/live/stats";
  237. stat.reset(new TwitchWidget());
  238. stat->setObjectName("twitchStats");
  239. stat->resize(200, 250);
  240. stat->setMinimumSize(200, 150);
  241. stat->setWindowTitle(QTStr("TwitchAuth.Stats"));
  242. stat->setAllowedAreas(Qt::AllDockWidgetAreas);
  243. browser = cef->create_widget(nullptr, url, panel_cookies);
  244. stat->SetWidget(browser);
  245. browser->setStartupScript(script);
  246. main->addDockWidget(Qt::RightDockWidgetArea, stat.data());
  247. statMenu.reset(main->AddDockWidget(stat.data()));
  248. /* ----------------------------------- */
  249. info->setFloating(true);
  250. stat->setFloating(true);
  251. QSize statSize = stat->frameSize();
  252. info->move(pos.x() + 50, pos.y() + 50);
  253. stat->move(pos.x() + size.width() / 2 - statSize.width() / 2,
  254. pos.y() + size.height() / 2 - statSize.height() / 2);
  255. if (firstLoad) {
  256. info->setVisible(true);
  257. stat->setVisible(false);
  258. } else {
  259. const char *dockStateStr = config_get_string(main->Config(),
  260. service(), "DockState");
  261. QByteArray dockState =
  262. QByteArray::fromBase64(QByteArray(dockStateStr));
  263. main->restoreState(dockState);
  264. }
  265. }
  266. /* Twitch.tv has an OAuth for itself. If we try to load multiple panel pages
  267. * at once before it's OAuth'ed itself, they will all try to perform the auth
  268. * process at the same time, get their own request codes, and only the last
  269. * code will be valid -- so one or more panels are guaranteed to fail.
  270. *
  271. * To solve this, we want to load just one panel first (the chat), and then all
  272. * subsequent panels should only be loaded once we know that Twitch has auth'ed
  273. * itself (if the cookie "auth-token" exists for twitch.tv).
  274. *
  275. * This is annoying to deal with. */
  276. void TwitchAuth::TryLoadSecondaryUIPanes()
  277. {
  278. QPointer<TwitchAuth> this_ = this;
  279. auto cb = [this_] (bool found)
  280. {
  281. if (!this_) {
  282. return;
  283. }
  284. if (!found) {
  285. QMetaObject::invokeMethod(&this_->uiLoadTimer,
  286. "start");
  287. } else {
  288. QMetaObject::invokeMethod(this_, "LoadSecondaryUIPanes");
  289. }
  290. };
  291. panel_cookies->CheckForCookie("https://www.twitch.tv", "auth-token", cb);
  292. }
  293. bool TwitchAuth::RetryLogin()
  294. {
  295. OAuthLogin login(OBSBasic::Get(), TWITCH_AUTH_URL, false);
  296. if (login.exec() == QDialog::Rejected) {
  297. return false;
  298. }
  299. std::shared_ptr<TwitchAuth> auth = std::make_shared<TwitchAuth>(twitchDef);
  300. std::string client_id = TWITCH_CLIENTID;
  301. deobfuscate_str(&client_id[0], TWITCH_HASH);
  302. return GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  303. QT_TO_UTF8(login.GetCode()), true);
  304. }
  305. std::shared_ptr<Auth> TwitchAuth::Login(QWidget *parent)
  306. {
  307. OAuthLogin login(parent, TWITCH_AUTH_URL, false);
  308. if (login.exec() == QDialog::Rejected) {
  309. return nullptr;
  310. }
  311. std::shared_ptr<TwitchAuth> auth = std::make_shared<TwitchAuth>(twitchDef);
  312. std::string client_id = TWITCH_CLIENTID;
  313. deobfuscate_str(&client_id[0], TWITCH_HASH);
  314. if (!auth->GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  315. QT_TO_UTF8(login.GetCode()))) {
  316. return nullptr;
  317. }
  318. std::string error;
  319. if (auth->GetChannelInfo()) {
  320. return auth;
  321. }
  322. return nullptr;
  323. }
  324. static std::shared_ptr<Auth> CreateTwitchAuth()
  325. {
  326. return std::make_shared<TwitchAuth>(twitchDef);
  327. }
  328. static void DeleteCookies()
  329. {
  330. if (panel_cookies)
  331. panel_cookies->DeleteCookies("twitch.tv", std::string());
  332. }
  333. void RegisterTwitchAuth()
  334. {
  335. OAuth::RegisterOAuth(
  336. twitchDef,
  337. CreateTwitchAuth,
  338. TwitchAuth::Login,
  339. DeleteCookies);
  340. }