auth-twitch.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. throw ErrorInfo(error, json["error_description"].string_value());
  84. name = json["name"].string_value();
  85. key_ = json["stream_key"].string_value();
  86. return true;
  87. } catch (ErrorInfo info) {
  88. QString title = QTStr("Auth.ChannelFailure.Title");
  89. QString text = QTStr("Auth.ChannelFailure.Text")
  90. .arg(service(), info.message.c_str(), info.error.c_str());
  91. QMessageBox::warning(OBSBasic::Get(), title, text);
  92. blog(LOG_WARNING, "%s: %s: %s",
  93. __FUNCTION__,
  94. info.message.c_str(),
  95. info.error.c_str());
  96. return false;
  97. }
  98. void TwitchAuth::SaveInternal()
  99. {
  100. OBSBasic *main = OBSBasic::Get();
  101. config_set_string(main->Config(), service(), "Name", name.c_str());
  102. if (uiLoaded) {
  103. config_set_string(main->Config(), service(), "DockState",
  104. main->saveState().toBase64().constData());
  105. }
  106. OAuthStreamKey::SaveInternal();
  107. }
  108. static inline std::string get_config_str(
  109. OBSBasic *main,
  110. const char *section,
  111. const char *name)
  112. {
  113. const char *val = config_get_string(main->Config(), section, name);
  114. return val ? val : "";
  115. }
  116. bool TwitchAuth::LoadInternal()
  117. {
  118. if (!cef)
  119. return false;
  120. OBSBasic *main = OBSBasic::Get();
  121. name = get_config_str(main, service(), "Name");
  122. firstLoad = false;
  123. return OAuthStreamKey::LoadInternal();
  124. }
  125. class TwitchWidget : public QDockWidget {
  126. public:
  127. inline TwitchWidget() : QDockWidget() {}
  128. QScopedPointer<QCefWidget> widget;
  129. inline void SetWidget(QCefWidget *widget_)
  130. {
  131. setWidget(widget_);
  132. widget.reset(widget_);
  133. }
  134. };
  135. static const char *ffz_script = "\
  136. var ffz = document.createElement('script');\
  137. ffz.setAttribute('src','https://cdn.frankerfacez.com/script/script.min.js');\
  138. document.head.appendChild(ffz);";
  139. static const char *bttv_script = "\
  140. localStorage.setItem('bttv_clickTwitchEmotes', true);\
  141. localStorage.setItem('bttv_darkenedMode', true);\
  142. localStorage.setItem('bttv_bttvGIFEmotes', true);\
  143. var bttv = document.createElement('script');\
  144. bttv.setAttribute('src','https://cdn.betterttv.net/betterttv.js');\
  145. document.head.appendChild(bttv);";
  146. static const char *referrer_script1 = "\
  147. Object.defineProperty(document, 'referrer', {get : function() { return '";
  148. static const char *referrer_script2 = "'; }});";
  149. void TwitchAuth::LoadUI()
  150. {
  151. if (uiLoaded)
  152. return;
  153. if (!GetChannelInfo())
  154. return;
  155. OBSBasic::InitBrowserPanelSafeBlock();
  156. OBSBasic *main = OBSBasic::Get();
  157. QCefWidget *browser;
  158. std::string url;
  159. std::string script;
  160. /* ----------------------------------- */
  161. url = "https://www.twitch.tv/popout/";
  162. url += name;
  163. url += "/chat";
  164. QSize size = main->frameSize();
  165. QPoint pos = main->pos();
  166. chat.reset(new TwitchWidget());
  167. chat->setObjectName("twitchChat");
  168. chat->resize(300, 600);
  169. chat->setMinimumSize(200, 300);
  170. chat->setWindowTitle(QTStr("Auth.Chat"));
  171. chat->setAllowedAreas(Qt::AllDockWidgetAreas);
  172. browser = cef->create_widget(nullptr, url, panel_cookies);
  173. chat->SetWidget(browser);
  174. script = bttv_script;
  175. script += ffz_script;
  176. browser->setStartupScript(script);
  177. main->addDockWidget(Qt::RightDockWidgetArea, chat.data());
  178. chatMenu.reset(main->AddDockWidget(chat.data()));
  179. /* ----------------------------------- */
  180. chat->setFloating(true);
  181. chat->move(pos.x() + size.width() - chat->width() - 50, pos.y() + 50);
  182. if (firstLoad) {
  183. chat->setVisible(true);
  184. } else {
  185. const char *dockStateStr = config_get_string(main->Config(),
  186. service(), "DockState");
  187. QByteArray dockState =
  188. QByteArray::fromBase64(QByteArray(dockStateStr));
  189. main->restoreState(dockState);
  190. }
  191. TryLoadSecondaryUIPanes();
  192. uiLoaded = true;
  193. }
  194. void TwitchAuth::LoadSecondaryUIPanes()
  195. {
  196. OBSBasic *main = OBSBasic::Get();
  197. QCefWidget *browser;
  198. std::string url;
  199. std::string script;
  200. QSize size = main->frameSize();
  201. QPoint pos = main->pos();
  202. script = "localStorage.setItem('twilight.theme', 1);";
  203. script += referrer_script1;
  204. script += "https://www.twitch.tv/";
  205. script += name;
  206. script += "/dashboard/live";
  207. script += referrer_script2;
  208. script += bttv_script;
  209. script += ffz_script;
  210. /* ----------------------------------- */
  211. url = "https://www.twitch.tv/popout/";
  212. url += name;
  213. url += "/dashboard/live/stream-info";
  214. info.reset(new TwitchWidget());
  215. info->setObjectName("twitchInfo");
  216. info->resize(300, 650);
  217. info->setMinimumSize(200, 300);
  218. info->setWindowTitle(QTStr("Auth.StreamInfo"));
  219. info->setAllowedAreas(Qt::AllDockWidgetAreas);
  220. browser = cef->create_widget(nullptr, url, panel_cookies);
  221. info->SetWidget(browser);
  222. browser->setStartupScript(script);
  223. main->addDockWidget(Qt::RightDockWidgetArea, info.data());
  224. infoMenu.reset(main->AddDockWidget(info.data()));
  225. /* ----------------------------------- */
  226. url = "https://www.twitch.tv/popout/";
  227. url += name;
  228. url += "/dashboard/live/stats";
  229. stat.reset(new TwitchWidget());
  230. stat->setObjectName("twitchStats");
  231. stat->resize(200, 250);
  232. stat->setMinimumSize(200, 150);
  233. stat->setWindowTitle(QTStr("TwitchAuth.Stats"));
  234. stat->setAllowedAreas(Qt::AllDockWidgetAreas);
  235. browser = cef->create_widget(nullptr, url, panel_cookies);
  236. stat->SetWidget(browser);
  237. browser->setStartupScript(script);
  238. main->addDockWidget(Qt::RightDockWidgetArea, stat.data());
  239. statMenu.reset(main->AddDockWidget(stat.data()));
  240. /* ----------------------------------- */
  241. info->setFloating(true);
  242. stat->setFloating(true);
  243. QSize statSize = stat->frameSize();
  244. info->move(pos.x() + 50, pos.y() + 50);
  245. stat->move(pos.x() + size.width() / 2 - statSize.width() / 2,
  246. pos.y() + size.height() / 2 - statSize.height() / 2);
  247. if (firstLoad) {
  248. info->setVisible(true);
  249. stat->setVisible(false);
  250. } else {
  251. const char *dockStateStr = config_get_string(main->Config(),
  252. service(), "DockState");
  253. QByteArray dockState =
  254. QByteArray::fromBase64(QByteArray(dockStateStr));
  255. main->restoreState(dockState);
  256. }
  257. }
  258. /* Twitch.tv has an OAuth for itself. If we try to load multiple panel pages
  259. * at once before it's OAuth'ed itself, they will all try to perform the auth
  260. * process at the same time, get their own request codes, and only the last
  261. * code will be valid -- so one or more panels are guaranteed to fail.
  262. *
  263. * To solve this, we want to load just one panel first (the chat), and then all
  264. * subsequent panels should only be loaded once we know that Twitch has auth'ed
  265. * itself (if the cookie "auth-token" exists for twitch.tv).
  266. *
  267. * This is annoying to deal with. */
  268. void TwitchAuth::TryLoadSecondaryUIPanes()
  269. {
  270. QPointer<TwitchAuth> this_ = this;
  271. auto cb = [this_] (bool found)
  272. {
  273. if (!this_) {
  274. return;
  275. }
  276. if (!found) {
  277. QMetaObject::invokeMethod(&this_->uiLoadTimer,
  278. "start");
  279. } else {
  280. QMetaObject::invokeMethod(this_, "LoadSecondaryUIPanes");
  281. }
  282. };
  283. panel_cookies->CheckForCookie("https://www.twitch.tv", "auth-token", cb);
  284. }
  285. bool TwitchAuth::RetryLogin()
  286. {
  287. OAuthLogin login(OBSBasic::Get(), TWITCH_AUTH_URL, false);
  288. if (login.exec() == QDialog::Rejected) {
  289. return false;
  290. }
  291. std::shared_ptr<TwitchAuth> auth = std::make_shared<TwitchAuth>(twitchDef);
  292. std::string client_id = TWITCH_CLIENTID;
  293. deobfuscate_str(&client_id[0], TWITCH_HASH);
  294. return GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  295. QT_TO_UTF8(login.GetCode()), true);
  296. }
  297. std::shared_ptr<Auth> TwitchAuth::Login(QWidget *parent)
  298. {
  299. OAuthLogin login(parent, TWITCH_AUTH_URL, false);
  300. if (login.exec() == QDialog::Rejected) {
  301. return nullptr;
  302. }
  303. std::shared_ptr<TwitchAuth> auth = std::make_shared<TwitchAuth>(twitchDef);
  304. std::string client_id = TWITCH_CLIENTID;
  305. deobfuscate_str(&client_id[0], TWITCH_HASH);
  306. if (!auth->GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION,
  307. QT_TO_UTF8(login.GetCode()))) {
  308. return nullptr;
  309. }
  310. std::string error;
  311. if (auth->GetChannelInfo()) {
  312. return auth;
  313. }
  314. return nullptr;
  315. }
  316. static std::shared_ptr<Auth> CreateTwitchAuth()
  317. {
  318. return std::make_shared<TwitchAuth>(twitchDef);
  319. }
  320. static void DeleteCookies()
  321. {
  322. if (panel_cookies)
  323. panel_cookies->DeleteCookies("twitch.tv", std::string());
  324. }
  325. void RegisterTwitchAuth()
  326. {
  327. OAuth::RegisterOAuth(
  328. twitchDef,
  329. CreateTwitchAuth,
  330. TwitchAuth::Login,
  331. DeleteCookies);
  332. }