auth-twitch.cpp 9.9 KB

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