app.js 3.4 KB
Newer Older
B
binaryify 已提交
1
const fs = require('fs')
N
Nzix 已提交
2 3
const path = require('path')
const express = require('express')
N
Nzix 已提交
4
const bodyParser = require('body-parser')
N
Nzix 已提交
5
const request = require('./util/request')
B
binaryify 已提交
6
const packageJSON = require('./package.json')
N
Nzix 已提交
7
const exec = require('child_process').exec
B
binaryify 已提交
8
const cache = require('./util/apicache').middleware
9
const { cookieToJson } = require('./util/index')
B
binaryify 已提交
10
const fileUpload = require('express-fileupload')
N
Nzix 已提交
11 12
// version check
exec('npm info NeteaseCloudMusicApi version', (err, stdout, stderr) => {
B
binaryify 已提交
13
  if (!err) {
B
binaryify 已提交
14
    let version = stdout.trim()
B
binaryify 已提交
15 16 17 18
    if (packageJSON.version < version) {
      console.log(
        `最新版本: ${version}, 当前版本: ${packageJSON.version}, 请及时更新`,
      )
N
Nzix 已提交
19
    }
B
binaryify 已提交
20
  }
B
binaryify 已提交
21
})
B
improve  
binaryify 已提交
22

N
Nzix 已提交
23
const app = express()
24

N
Nzix 已提交
25
// CORS & Preflight request
N
Nzix 已提交
26
app.use((req, res, next) => {
B
binaryify 已提交
27
  if (req.path !== '/' && !req.path.includes('.')) {
N
Nzix 已提交
28
    res.set({
B
binaryify 已提交
29 30
      'Access-Control-Allow-Credentials': true,
      'Access-Control-Allow-Origin': req.headers.origin || '*',
N
Nzix 已提交
31
      'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type',
B
binaryify 已提交
32
      'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
B
binaryify 已提交
33
      'Content-Type': 'application/json; charset=utf-8',
B
binaryify 已提交
34 35
    })
  }
N
Nzix 已提交
36
  req.method === 'OPTIONS' ? res.status(204).end() : next()
37 38
})

N
Nzix 已提交
39
// cookie parser
N
Nzix 已提交
40
app.use((req, res, next) => {
B
binaryify 已提交
41 42 43 44 45 46 47 48
  req.cookies = {}
  ;(req.headers.cookie || '').split(/\s*;\s*/).forEach((pair) => {
    let crack = pair.indexOf('=')
    if (crack < 1 || crack == pair.length - 1) return
    req.cookies[
      decodeURIComponent(pair.slice(0, crack)).trim()
    ] = decodeURIComponent(pair.slice(crack + 1)).trim()
  })
B
binaryify 已提交
49
  next()
N
Nzix 已提交
50 51
})

N
Nzix 已提交
52 53
// body parser
app.use(bodyParser.json())
B
binaryify 已提交
54
app.use(bodyParser.urlencoded({ extended: false }))
55

B
binaryify 已提交
56
app.use(fileUpload())
N
Nzix 已提交
57

N
Nzix 已提交
58 59
// static
app.use(express.static(path.join(__dirname, 'public')))
60

61
// cache
B
binaryify 已提交
62
app.use(cache('2 minutes', (req, res) => res.statusCode === 200))
N
Nzix 已提交
63 64
// router
const special = {
B
binaryify 已提交
65 66
  'daily_signin.js': '/daily_signin',
  'fm_trash.js': '/fm_trash',
B
binaryify 已提交
67
  'personal_fm.js': '/personal_fm',
N
Nzix 已提交
68
}
N
Nzix 已提交
69

B
binaryify 已提交
70 71 72 73 74 75 76 77 78
fs.readdirSync(path.join(__dirname, 'module'))
  .reverse()
  .forEach((file) => {
    if (!file.endsWith('.js')) return
    let route =
      file in special
        ? special[file]
        : '/' + file.replace(/\.js$/i, '').replace(/_/g, '/')
    let question = require(path.join(__dirname, 'module', file))
N
Nzix 已提交
79

B
binaryify 已提交
80
    app.use(route, (req, res) => {
81 82 83 84 85
      ;[req.query, req.body].forEach((item) => {
        if (typeof item.cookie === 'string') {
          item.cookie = cookieToJson(decodeURIComponent(item.cookie))
        }
      })
B
binaryify 已提交
86 87 88 89 90 91 92
      let query = Object.assign(
        {},
        { cookie: req.cookies },
        req.query,
        req.body,
        req.files,
      )
93

B
binaryify 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
      question(query, request)
        .then((answer) => {
          console.log('[OK]', decodeURIComponent(req.originalUrl))
          res.append('Set-Cookie', answer.cookie)
          res.status(answer.status).send(answer.body)
        })
        .catch((answer) => {
          console.log('[ERR]', decodeURIComponent(req.originalUrl), {
            status: answer.status,
            body: answer.body,
          })
          if (answer.body.code == '301') answer.body.msg = '需要登录'
          res.append('Set-Cookie', answer.cookie)
          res.status(answer.status).send(answer.body)
        })
    })
B
binaryify 已提交
110
  })
N
Nzix 已提交
111

B
binaryify 已提交
112
const port = process.env.PORT || 3000
B
binaryify 已提交
113
const host = process.env.HOST || ''
114

B
Bob 已提交
115
app.server = app.listen(port, host, () => {
B
binaryify 已提交
116
  console.log(`server running @ http://${host ? host : 'localhost'}:${port}`)
B
binaryify 已提交
117
})
118

B
binaryify 已提交
119
module.exports = app