如何运行此打字稿代码?

时间:2018-06-23 05:12:39

标签: javascript typescript

我找到了一些我想尝试并运行的代码,但不确定在哪里使用。该代码用于在textnow.com上创建帐户,而我正在努力弄清楚如何运行它。如果有人可以帮助我,将不胜感激!

// import dependencies
import * as request from 'request-promise';
import * as md5 from 'md5';
import { URL } from 'url';
import areaCodes from './area-codes';
import { processLoop } from '../../utils';
import { Logger, DebugLevel } from '../../logger';
import { fakeTextNowBonusInfo } from '../../faker';

export class TextNowRegistration {
  private readonly API_BASE = 'https://api.textnow.me/api2.0';
  private readonly API_SECRET = '851a9f2bad15843c1a922890c061830e8ce50e86840575d17e61ef0becdc3576';
  private readonly SITE_KEY = '6LcU4gkTAAAAAM4SyYTmXlKvqwWLuaFLy-30rzBn';
  private readonly AREA_CODE = 540;

  private username: string;
  private password: string;
  private email: string;
  private clientId: string;
  private captchaToken: string;
  private logger: Logger;
  private onCaptchaReceived: (siteKey: string) => Promise<string>;

  constructor(username: string, password: string, email: string, onCaptchaReceived: (siteKey: string) => Promise<string>) {
    this.username = username;
    this.password = password;
    this.email = email;
    this.onCaptchaReceived = onCaptchaReceived;
    this.clientId = null;
    this.captchaToken = null;
    this.logger = new Logger(username);
  }

  private buildSignature(method: string, uri: string, json: any) : string {
    // strip base uri
    let path = uri.replace(this.API_BASE+'/', '');

    // prepare json payload
    let stringified = '';
    if (json) {
      stringified = JSON.stringify(json);
    }

    // hash the payload
    return md5(this.API_SECRET + method + path + stringified);
  }

  private buildUrl(path: string) : string {
    return this.API_BASE + path;
  }

  public register() : Promise<string> {
    return new Promise<string>((resolve, reject) => {
      this.logger.normal(`signing up new user: ${this.username}`);
      this.checkUsername().then((usernameExists: boolean) => {
        // check fif username already exists
        if (usernameExists) throw new Error('the user could not be created as the username is not available');
        return this.checkEmail();
      })
      .then((emailExists: boolean) => {
        // check if email already exists
        if (emailExists) throw new Error('the user could not be created as the email is already registered');
        return this.signUp();
      })
      .then(() => {
        return this.validateCaptcha();
      }).then(() => {
        return this.claimPhoneNumber(this.AREA_CODE);
      }).then((phoneNumber: string) => {
        return resolve(phoneNumber);
      }).catch(reject);
    });
  }

  private checkUsername() : Promise<boolean> {
    return new Promise<boolean>((resolve, reject) => {
      // prepare json request
      this.makeRequest({
        uri: this.buildUrl(`/users/${this.username}?idfa=&idfv=&client_type=TN_IOS_FREE`),
        method: 'HEAD'
      }).then((data: any) => {
        this.logger.red(`the user '${this.username}' is already existing`);
        return resolve(true);
      }).catch((err: any) => {
        this.logger.normal(`the user '${this.username}' is not registered yet`);
        return resolve(false);
      })
    });
  }

  private checkEmail() : Promise<boolean> {
    return new Promise<boolean>((resolve, reject) => {
      // prepare json request
      this.makeRequest({
        uri: this.buildUrl(`/emails/${this.email}?idfa=&idfv=&client_type=TN_IOS_FREE`),
        method: 'HEAD'
      }).then((data: any) => {
        this.logger.red(`the email '${this.email}' is already registered`);
        return resolve(true);
      }).catch((err: any) => {
        this.logger.normal(`the email '${this.email}' is not registered yet`);
        return resolve(false);
      })
    });
  }

  private signUp() : Promise<string> {
    return new Promise<string>((resolve, reject) => {
      // prepare json request
      let body = {
        'dob': '2018-02-17',
        'password': this.password,
        'email': this.email,
        'bonus_info': fakeTextNowBonusInfo()
      };
      // make the code verification request
      this.makeRequest({
        uri: this.buildUrl(`/users/${this.username}?idfa=&idfv=&client_type=TN_IOS_FREE`),
        method: 'PUT',
        body: body
      }).then((data: any) => {
        // check if registration was successfull
        if (!data.result || !data.result.id) {
          throw new Error('there was an error trying to register the user');
        }
        // the user was successfully created
        this.logger.green('successfully registered user');
        this.clientId = data.result.id;
        let url = new URL(data.result.captcha_link);
        this.captchaToken = url.searchParams.get('token');
        return resolve(this.clientId);
      }).catch(reject);
    });
  }

  private claimPhoneNumber(areaCode: number) : Promise<string> {
    return new Promise<string>((resolve, reject) => {
      // make the phone number claim request
      this.logger.normal('claiming phone number with area code: ' + areaCode);
      this.makeRequest({
        uri: this.buildUrl(`/users/${this.username}/phone?idfa=&idfv=&client_id=${this.clientId}&client_type=TN_IOS_FREE`),
        method: 'PUT',
        body: {
          'area_code': areaCode
        }
      }).then((phone: any) => {
        const phoneNumber: string = '+1' + phone;
        this.logger.yellow('claimed phone number: ' + phoneNumber);
        return resolve(phoneNumber);
      }).catch(reject);
    });
  }

  private validateCaptcha() : Promise<void> {
    return new Promise<void>((resolve, reject) => {
      // wait for the captcha to be returned
      this.logger.normal('requested a new recaptcha token');
      this.onCaptchaReceived(this.SITE_KEY).then((token: string) => {
        this.logger.normal('received fresh recaptcha token');
        // prepare json payload
        let body = {
          u: this.captchaToken,
          c: token
        };
        // prepare request
        return request({
          uri: 'https://www.textnow.com/api/identity/validate',
          method: 'POST',
          form: {
            json: JSON.stringify(body)
          },
          json: true,
          headers: {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_2 like Mac OS X) AppleWebKit/602.3.12 (KHTML, like Gecko) Mobile/14C92'
          }
        });
      }).then((data: any) => {
        // check if the validation was successful
        if (data.error_code !== null) throw new Error('there was an error validating the captcha');
        // the validation was successful
        this.logger.normal('successfully validated user captcha');
        return resolve(); 
      }).catch(reject);
    });
  }

  private getRandomAreaCode() : number {
    const length: number = areaCodes.length;
    return Math.floor(Math.random() * length);
  }

  private makeRequest(options: request.OptionsWithUri) : request.RequestPromise {
    // modify and add required headers
    //options.proxy = 'http://localhost:8888';
    options.json = true;
    options.headers = {
      'User-Agent': 'TextNowSwift-Free/8.20.3 (iPhone; iOS 10.2; Scale/2.00)',
      'Accept-Language': 'en-US;q=1'
    };
    // add signature
    options.uri = options.uri + '&signature=' + this.buildSignature(options.method, (options.uri as string), options.body);
    // make request
    return request(options);
  }
}

我将代码转换为.js并尝试运行它,但出现此错误:

module.js:538
    throw err;
    ^

Error: Cannot find module 'request-promise'
    at Function.Module._resolveFilename (module.js:536:15)
    at Function.Module._load (module.js:466:25)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\Users\jashua\Desktop\script.js:4:15)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)

1 个答案:

答案 0 :(得分:0)

我相信您可能会丢失导入语句中列出的部分或全部模块。

安装node / npm,转到拥有此脚本文件的目录并运行

npm i <module>

对于每个丢失的模块,其中<module>是每个import语句中from关键字之后的内容。但是请注意,有些导入语句是相对的(那些以...开头的语句),节点希望在这些位置找到它们,以使脚本成功运行。

除了此基本技巧外,我建议您看一下npm文档和Typescript编译器选项,以更深入地了解。