auth-twitch.cpp 10 KB

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