request.ts 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. import request = require('request');
  3. var isAuthenticated = false;
  4. /**
  5. * Performs a GET request for the resource.
  6. */
  7. export function get(config: IConfig, options: request.Options, done: (err: Error, result?: string) => void) {
  8. authenticate(config, err => {
  9. if (err) return done(err);
  10. request.get(modify(options), (err: Error, response: any, body: any) => {
  11. if (err) return done(err);
  12. done(null, typeof body === 'string' ? body : String(body));
  13. });
  14. });
  15. }
  16. /**
  17. * Performs a POST request for the resource.
  18. */
  19. export function post(config: IConfig, options: request.Options, done: (err: Error, result?: string) => void) {
  20. authenticate(config, err => {
  21. if (err) return done(err);
  22. request.post(modify(options), (err: Error, response: any, body: any) => {
  23. if (err) return done(err);
  24. done(null, typeof body === 'string' ? body : String(body));
  25. });
  26. });
  27. }
  28. /**
  29. * Authenticates using the configured pass and user.
  30. */
  31. function authenticate(config: IConfig, done: (err: Error) => void) {
  32. if (isAuthenticated || !config.pass || !config.user) return done(null);
  33. var options = {
  34. form: {
  35. formname: 'RpcApiUser_Login',
  36. fail_url: 'https://www.crunchyroll.com/login',
  37. name: config.user,
  38. password: config.pass
  39. },
  40. jar: true,
  41. url: 'https://www.crunchyroll.com/?a=formhandler'
  42. };
  43. request.post(options, (err: Error) => {
  44. if (err) return done(err);
  45. isAuthenticated = true;
  46. done(null);
  47. });
  48. }
  49. /**
  50. * Modifies the options to use the authenticated cookie jar.
  51. */
  52. function modify(options: string|request.Options): request.Options {
  53. if (typeof options !== 'string') {
  54. options.jar = true;
  55. return options;
  56. }
  57. return {jar: true, url: options.toString()};
  58. }