request.js 8.3 KB
Newer Older
N
Nzix 已提交
1
const encrypt = require('./crypto')
YXL76's avatar
YXL76 已提交
2
const axios = require('axios')
N
Nzix 已提交
3
const queryString = require('querystring')
T
trazyn 已提交
4
const PacProxyAgent = require('pac-proxy-agent')
YXL76's avatar
YXL76 已提交
5 6
const http = require('http')
const https = require('https')
7 8
const tunnel = require('tunnel')
const qs = require('url')
9 10
// request.debug = true // 开启可看到更详细信息

H
huggy 已提交
11
const chooseUserAgent = (ua = false) => {
12 13 14 15 16 17 18 19
  const userAgentList = {
    mobile: [
      // iOS 13.5.1 14.0 beta with safari
      'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Mobile/15E148 Safari/604.1',
      'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.',
      // iOS with qq micromsg
      'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/602.1.50 (KHTML like Gecko) Mobile/14A456 QQ/6.5.7.408 V1_IPH_SQ_6.5.7_1_APP_A Pixel/750 Core/UIWebView NetType/4G Mem/103',
      'Mozilla/5.0 (iPhone; CPU iPhone OS 13_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.15(0x17000f27) NetType/WIFI Language/zh',
B
binaryify 已提交
20
      // Android -> Huawei Xiaomi
21 22 23 24 25 26 27 28 29 30 31 32 33 34
      'Mozilla/5.0 (Linux; Android 9; PCT-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.64 HuaweiBrowser/10.0.3.311 Mobile Safari/537.36',
      'Mozilla/5.0 (Linux; U; Android 9; zh-cn; Redmi Note 8 Build/PKQ1.190616.001) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.141 Mobile Safari/537.36 XiaoMi/MiuiBrowser/12.5.22',
      // Android + qq micromsg
      'Mozilla/5.0 (Linux; Android 10; YAL-AL00 Build/HUAWEIYAL-AL00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/78.0.3904.62 XWEB/2581 MMWEBSDK/200801 Mobile Safari/537.36 MMWEBID/3027 MicroMessenger/7.0.18.1740(0x27001235) Process/toolsmp WeChat/arm64 NetType/WIFI Language/zh_CN ABI/arm64',
      'Mozilla/5.0 (Linux; U; Android 8.1.0; zh-cn; BKK-AL10 Build/HONORBKK-AL10) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/66.0.3359.126 MQQBrowser/10.6 Mobile Safari/537.36',
    ],
    pc: [
      // macOS 10.15.6  Firefox / Chrome / Safari
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:80.0) Gecko/20100101 Firefox/80.0',
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36',
      'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.2 Safari/605.1.15',
      // Windows 10 Firefox / Chrome / Edge
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0',
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.30 Safari/537.36',
B
binaryify 已提交
35
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13.10586',
36
      // Linux 就算了
B
binaryify 已提交
37
    ],
38
  }
B
binaryify 已提交
39 40 41 42 43
  let realUserAgentList =
    userAgentList[ua] || userAgentList.mobile.concat(userAgentList.pc)
  return ['mobile', 'pc', false].indexOf(ua) > -1
    ? realUserAgentList[Math.floor(Math.random() * realUserAgentList.length)]
    : ua
N
Nzix 已提交
44
}
N
Nzix 已提交
45
const createRequest = (method, url, data, options) => {
46 47
  return new Promise((resolve, reject) => {
    let headers = { 'User-Agent': chooseUserAgent(options.ua) }
L
lizhenyuls 已提交
48
    if (method.toUpperCase() === 'POST')
49 50
      headers['Content-Type'] = 'application/x-www-form-urlencoded'
    if (url.includes('music.163.com'))
51
      headers['Referer'] = 'https://music.163.com'
B
binaryify 已提交
52
    if (options.realIP) headers['X-Real-IP'] = options.realIP
C
ceabq 已提交
53
      headers['X-Real-IP'] = '118.88.88.88'
54 55 56
    if (typeof options.cookie === 'object')
      headers['Cookie'] = Object.keys(options.cookie)
        .map(
B
binaryify 已提交
57
          (key) =>
58 59
            encodeURIComponent(key) +
            '=' +
B
binaryify 已提交
60
            encodeURIComponent(options.cookie[key]),
61 62 63
        )
        .join('; ')
    else if (options.cookie) headers['Cookie'] = options.cookie
H
huggy 已提交
64

65 66 67
    if (!headers['Cookie']) {
      headers['Cookie'] = options.token || ''
    }
L
lizhenyuls 已提交
68
    if (options.crypto === 'weapi') {
69 70 71 72
      let csrfToken = (headers['Cookie'] || '').match(/_csrf=([^(;|$)]+)/)
      data.csrf_token = csrfToken ? csrfToken[1] : ''
      data = encrypt.weapi(data)
      url = url.replace(/\w*api/, 'weapi')
L
lizhenyuls 已提交
73
    } else if (options.crypto === 'linuxapi') {
74 75 76
      data = encrypt.linuxapi({
        method: method,
        url: url.replace(/\w*api/, 'api'),
B
binaryify 已提交
77
        params: data,
78 79
      })
      headers['User-Agent'] =
H
huggy 已提交
80
        'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'
81
      url = 'https://music.163.com/api/linux/forward'
L
lizhenyuls 已提交
82
    } else if (options.crypto === 'eapi') {
B
binaryify 已提交
83
      const cookie = options.cookie || {}
L
lizhenyuls 已提交
84 85
      const csrfToken = cookie['__csrf'] || ''
      const header = {
B
binaryify 已提交
86 87
        osver: cookie.osver, //系统版本
        deviceId: cookie.deviceId, //encrypt.base64.encode(imei + '\t02:00:00:00:00:00\t5106025eb79a5247\t70ffbaac7')
B
binaryify 已提交
88
        appver: cookie.appver || '8.0.0', // app版本
B
binaryify 已提交
89 90 91 92 93 94 95 96 97 98
        versioncode: cookie.versioncode || '140', //版本号
        mobilename: cookie.mobilename, //设备model
        buildver: cookie.buildver || Date.now().toString().substr(0, 10),
        resolution: cookie.resolution || '1920x1080', //设备分辨率
        __csrf: csrfToken,
        os: cookie.os || 'android',
        channel: cookie.channel,
        requestId: `${Date.now()}_${Math.floor(Math.random() * 1000)
          .toString()
          .padStart(4, '0')}`,
L
lizhenyuls 已提交
99
      }
B
binaryify 已提交
100 101
      if (cookie.MUSIC_U) header['MUSIC_U'] = cookie.MUSIC_U
      if (cookie.MUSIC_A) header['MUSIC_A'] = cookie.MUSIC_A
L
lizhenyuls 已提交
102 103
      headers['Cookie'] = Object.keys(header)
        .map(
B
binaryify 已提交
104 105
          (key) =>
            encodeURIComponent(key) + '=' + encodeURIComponent(header[key]),
L
lizhenyuls 已提交
106 107 108 109
        )
        .join('; ')
      data.header = header
      data = encrypt.eapi(options.url, data)
B
binaryify 已提交
110
      url = url.replace(/\w*api/, 'eapi')
111
    }
N
Nzix 已提交
112

113
    const answer = { status: 500, body: {}, cookie: [] }
114
    let settings = {
T
trazyn 已提交
115 116 117
      method: method,
      url: url,
      headers: headers,
YXL76's avatar
YXL76 已提交
118 119 120
      data: queryString.stringify(data),
      httpAgent: new http.Agent({ keepAlive: true }),
      httpsAgent: new https.Agent({ keepAlive: true }),
T
trazyn 已提交
121 122
    }

L
lizhenyuls 已提交
123 124
    if (options.crypto === 'eapi') settings.encoding = null

125 126 127 128 129
    if (options.proxy) {
      if (options.proxy.indexOf('pac') > -1) {
        settings.httpAgent = new PacProxyAgent(options.proxy)
        settings.httpsAgent = new PacProxyAgent(options.proxy)
      } else {
G
greenhat616 已提交
130
        const purl = qs.parse(options.proxy)
131 132 133 134 135 136 137 138 139 140 141 142 143 144
        if (purl.hostname) {
          const agent = tunnel.httpsOverHttp({
            proxy: {
              host: purl.hostname,
              port: purl.port || 80,
            },
          })
          settings.httpsAgent = agent
          settings.httpAgent = agent
          settings.proxy = false
        } else {
          console.error('代理配置无效,不使用代理')
        }
      }
T
trazyn 已提交
145
    }
146 147 148 149 150 151
    if (options.crypto === 'eapi') {
      settings = {
        ...settings,
        responseType: 'arraybuffer',
      }
    }
YXL76's avatar
YXL76 已提交
152 153 154
    axios(settings)
      .then((res) => {
        const body = res.data
B
binaryify 已提交
155 156 157 158
        answer.cookie = (res.headers['set-cookie'] || []).map((x) =>
          x.replace(/\s*Domain=[^(;|$)]+;*/, ''),
        )
        try {
159 160 161 162 163 164
          if (options.crypto === 'eapi') {
            answer.body = JSON.parse(encrypt.decrypt(body).toString())
          } else {
            answer.body = body
          }

YXL76's avatar
YXL76 已提交
165
          answer.status = answer.body.code || res.status
B
binaryify 已提交
166 167 168 169 170
          if (
            [201, 302, 400, 502, 800, 801, 802, 803].indexOf(answer.body.code) >
            -1
          ) {
            // 特殊状态码
YXL76's avatar
YXL76 已提交
171
            answer.status = 200
172
          }
B
binaryify 已提交
173
        } catch (e) {
174
          // console.log(e)
175 176 177 178 179 180 181
          try {
            answer.body = JSON.parse(body.toString())
          } catch (err) {
            // console.log(err)
            // can't decrypt and can't parse directly
            answer.body = body
          }
YXL76's avatar
YXL76 已提交
182
          answer.status = res.status
N
Nzix 已提交
183
        }
B
binaryify 已提交
184 185 186

        answer.status =
          100 < answer.status && answer.status < 600 ? answer.status : 400
G
greenhat616 已提交
187
        if (answer.status === 200) resolve(answer)
B
binaryify 已提交
188
        else reject(answer)
YXL76's avatar
YXL76 已提交
189 190 191 192 193 194
      })
      .catch((err) => {
        answer.status = 502
        answer.body = { code: 502, msg: err }
        reject(answer)
      })
195
  })
N
Nzix 已提交
196 197 198
}

module.exports = createRequest