my_request.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. 'use strict';
  2. import cheerio = require('cheerio');
  3. import request = require('request');
  4. import rp = require('request-promise');
  5. import Promise = require('bluebird');
  6. import uuid = require('uuid');
  7. import path = require('path');
  8. import fs = require('fs-extra');
  9. import log = require('./log');
  10. import { RequestPromise } from 'request-promise';
  11. import { Response } from 'request';
  12. // tslint:disable-next-line:no-var-requires
  13. const cookieStore = require('tough-cookie-file-store');
  14. // tslint:disable-next-line:no-var-requires
  15. const cloudscraper = require('cloudscraper');
  16. const CR_COOKIE_DOMAIN = 'http://crunchyroll.com';
  17. let isAuthenticated = false;
  18. let isPremium = false;
  19. let j: request.CookieJar;
  20. const defaultHeaders: request.Headers =
  21. {
  22. 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
  23. 'Connection': 'keep-alive',
  24. 'Referer': 'https://www.crunchyroll.com/login',
  25. };
  26. function AuthError(msg: string): IAuthError
  27. {
  28. return { name: 'AuthError', message: msg, authError: true };
  29. }
  30. function startSession(config: IConfig): Promise<any>
  31. {
  32. return rp(
  33. {
  34. method: 'GET',
  35. url: config.crSessionUrl,
  36. qs:
  37. {
  38. device_id: config.crDeviceId,
  39. device_type: config.crDeviceType,
  40. access_token: config.crSessionKey,
  41. version: config.crAPIVersion,
  42. locale: config.crLocale,
  43. },
  44. json: true,
  45. })
  46. .then((response: any) =>
  47. {
  48. if ((response.data === undefined) || (response.data.session_id === undefined))
  49. {
  50. throw new Error('Getting session failed: ' + JSON.stringify(response));
  51. }
  52. return response.data.session_id;
  53. });
  54. }
  55. function login(config: IConfig, sessionId: string, user: string, pass: string): Promise<any>
  56. {
  57. return rp(
  58. {
  59. method: 'POST',
  60. url: config.crLoginUrl,
  61. form:
  62. {
  63. account: user,
  64. password: pass,
  65. session_id: sessionId,
  66. version: config.crAPIVersion,
  67. },
  68. json: true,
  69. jar: j,
  70. })
  71. .then((response) =>
  72. {
  73. if (response.error) throw new Error('Login failed: ' + response.message);
  74. return response.data;
  75. });
  76. }
  77. function checkIfUserIsAuth(config: IConfig, done: (err: Error) => void): void
  78. {
  79. if (j === undefined)
  80. {
  81. loadCookies(config);
  82. }
  83. /**
  84. * The main page give us some information about the user
  85. */
  86. const options =
  87. {
  88. headers: defaultHeaders,
  89. jar: j,
  90. url: 'http://www.crunchyroll.com/',
  91. method: 'GET',
  92. };
  93. cloudscraper.request(options, (err: Error, rep: string, body: string) =>
  94. {
  95. if (err)
  96. {
  97. return done(err);
  98. }
  99. const $ = cheerio.load(body);
  100. /* Check if auth worked */
  101. const regexps = /ga\('set', 'dimension[5-8]', '([^']*)'\);/g;
  102. const dims = regexps.exec($('script').text());
  103. for (let i = 1; i < 5; i++)
  104. {
  105. if ((dims[i] !== undefined) && (dims[i] !== '') && (dims[i] !== 'not-registered'))
  106. {
  107. isAuthenticated = true;
  108. }
  109. if ((dims[i] === 'premium') || (dims[i] === 'premiumplus'))
  110. {
  111. isPremium = true;
  112. }
  113. }
  114. if (isAuthenticated === false)
  115. {
  116. const error = $('ul.message, li.error').text();
  117. return done(AuthError('Authentication failed: ' + error));
  118. }
  119. else
  120. {
  121. if (isPremium === false)
  122. {
  123. log.warn('Do not use this app without a premium account.');
  124. }
  125. else
  126. {
  127. log.info('You have a premium account! Good!');
  128. }
  129. }
  130. done(null);
  131. });
  132. }
  133. function loadCookies(config: IConfig)
  134. {
  135. const cookiePath = path.join(config.output || process.cwd(), '.cookies.json');
  136. if (!fs.existsSync(cookiePath))
  137. {
  138. fs.closeSync(fs.openSync(cookiePath, 'w'));
  139. }
  140. j = request.jar(new cookieStore(cookiePath));
  141. }
  142. export function eatCookies(config: IConfig)
  143. {
  144. const cookiePath = path.join(config.output || process.cwd(), '.cookies.json');
  145. if (fs.existsSync(cookiePath))
  146. {
  147. fs.removeSync(cookiePath);
  148. }
  149. j = undefined;
  150. }
  151. /**
  152. * Performs a GET request for the resource.
  153. */
  154. export function get(config: IConfig, options: string|request.Options, done: (err: any, result?: string) => void)
  155. {
  156. if (j === undefined)
  157. {
  158. loadCookies(config);
  159. }
  160. authenticate(config, (err) =>
  161. {
  162. if (err)
  163. {
  164. return done(err);
  165. }
  166. cloudscraper.request(modify(options, 'GET'), (error: any, response: any, body: any) =>
  167. {
  168. if (error) return done(error);
  169. done(null, typeof body === 'string' ? body : String(body));
  170. });
  171. });
  172. }
  173. /**
  174. * Performs a POST request for the resource.
  175. */
  176. export function post(config: IConfig, options: request.Options, done: (err: Error, result?: string) => void)
  177. {
  178. if (j === undefined)
  179. {
  180. loadCookies(config);
  181. }
  182. authenticate(config, (err) =>
  183. {
  184. if (err)
  185. {
  186. return done(err);
  187. }
  188. cloudscraper.request(modify(options, 'POST'), (error: Error, response: any, body: any) =>
  189. {
  190. if (error)
  191. {
  192. return done(error);
  193. }
  194. done(null, typeof body === 'string' ? body : String(body));
  195. });
  196. });
  197. }
  198. /**
  199. * Authenticates using the configured pass and user.
  200. */
  201. function authenticate(config: IConfig, done: (err: Error) => void)
  202. {
  203. if (isAuthenticated)
  204. {
  205. return done(null);
  206. }
  207. /* First of all, check if the user is not already logged via the cookies */
  208. checkIfUserIsAuth(config, (errCheckAuth) =>
  209. {
  210. if (isAuthenticated)
  211. {
  212. return done(null);
  213. }
  214. /* So if we are here now, that mean we are not authenticated so do as usual */
  215. if (!config.pass || !config.user)
  216. {
  217. log.error('You need to give login/password to use Crunchy');
  218. process.exit(-1);
  219. }
  220. log.info('Seems we are not currently logged. Let\'s login!');
  221. if (config.logUsingApi)
  222. {
  223. if (config.crDeviceId === undefined)
  224. {
  225. config.crDeviceId = uuid.v4();
  226. }
  227. if (!config.crSessionUrl || !config.crDeviceType || !config.crAPIVersion ||
  228. !config.crLocale || !config.crLoginUrl)
  229. {
  230. return done(AuthError('Invalid API configuration, please check your config file.'));
  231. }
  232. startSession(config)
  233. .then((sessionId: string) =>
  234. {
  235. defaultHeaders.Cookie = `sess_id=${sessionId}; c_locale=enUS`;
  236. return login(config, sessionId, config.user, config.pass);
  237. })
  238. .then((userData) =>
  239. {
  240. checkIfUserIsAuth(config, (errCheckAuth2) =>
  241. {
  242. if (isAuthenticated)
  243. {
  244. return done(null);
  245. }
  246. else
  247. {
  248. return done(errCheckAuth2);
  249. }
  250. });
  251. })
  252. .catch((errInChk) =>
  253. {
  254. return done(AuthError(errInChk.message));
  255. });
  256. }
  257. else if (config.logUsingCookie)
  258. {
  259. j.setCookie(request.cookie('c_userid=' + config.crUserId + '; Domain=crunchyroll.com; HttpOnly; hostOnly=false;'),
  260. CR_COOKIE_DOMAIN);
  261. j.setCookie(request.cookie('c_userkey=' + config.crUserKey + '; Domain=crunchyroll.com; HttpOnly; hostOnly=false;'),
  262. CR_COOKIE_DOMAIN);
  263. checkIfUserIsAuth(config, (errCheckAuth2) =>
  264. {
  265. if (isAuthenticated)
  266. {
  267. return done(null);
  268. }
  269. else
  270. {
  271. return done(errCheckAuth2);
  272. }
  273. });
  274. }
  275. else
  276. {
  277. /* First get https://www.crunchyroll.com/login to get the login token */
  278. const options =
  279. {
  280. headers: defaultHeaders,
  281. jar: j,
  282. gzip: false,
  283. method: 'GET',
  284. url: 'https://www.crunchyroll.com/login'
  285. };
  286. cloudscraper.request(options, (err: Error, rep: string, body: string) =>
  287. {
  288. if (err) return done(err);
  289. const $ = cheerio.load(body);
  290. /* Get the token from the login page */
  291. const token = $('input[name="login_form[_token]"]').attr('value');
  292. if (token === '')
  293. {
  294. return done(AuthError('Can\'t find token!'));
  295. }
  296. /* Now call the page again with the token and credentials */
  297. const options =
  298. {
  299. headers: defaultHeaders,
  300. form:
  301. {
  302. 'login_form[name]': config.user,
  303. 'login_form[password]': config.pass,
  304. 'login_form[redirect_url]': '/',
  305. 'login_form[_token]': token
  306. },
  307. jar: j,
  308. gzip: false,
  309. method: 'POST',
  310. url: 'https://www.crunchyroll.com/login'
  311. };
  312. cloudscraper.request(options, (err: Error, rep: string, body: string) =>
  313. {
  314. if (err)
  315. {
  316. return done(err);
  317. }
  318. /* Now let's check if we are authentificated */
  319. checkIfUserIsAuth(config, (errCheckAuth2) =>
  320. {
  321. if (isAuthenticated)
  322. {
  323. return done(null);
  324. }
  325. else
  326. {
  327. return done(errCheckAuth2);
  328. }
  329. });
  330. });
  331. });
  332. }
  333. });
  334. }
  335. /**
  336. * Modifies the options to use the authenticated cookie jar.
  337. */
  338. function modify(options: string|request.Options, reqMethod: string): request.Options
  339. {
  340. if (typeof options !== 'string')
  341. {
  342. options.jar = j;
  343. options.headers = defaultHeaders;
  344. options.method = reqMethod;
  345. return options;
  346. }
  347. return {
  348. jar: j,
  349. headers: defaultHeaders,
  350. url: options.toString(),
  351. method: reqMethod
  352. };
  353. }