request.ts 1.8 KB

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