app.js 3.2 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')
10
const fileUpload = require('express-fileupload');
N
Nzix 已提交
11 12
// version check
exec('npm info NeteaseCloudMusicApi version', (err, stdout, stderr) => {
B
binaryify 已提交
13 14 15 16
  if(!err){
    let version = stdout.trim()
    if(packageJSON.version < version){
      console.log(`最新版本: ${version}, 当前版本: ${packageJSON.version}, 请及时更新`)
N
Nzix 已提交
17
    }
B
binaryify 已提交
18
  }
B
binaryify 已提交
19
})
B
improve  
binaryify 已提交
20

N
Nzix 已提交
21
const app = express()
22

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

N
Nzix 已提交
37
// cookie parser
N
Nzix 已提交
38
app.use((req, res, next) => {
B
binaryify 已提交
39 40 41 42 43 44
  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()
  })
  next()
N
Nzix 已提交
45 46
})

N
Nzix 已提交
47 48 49 50
// body parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))

51 52 53
app.use(fileUpload());


N
Nzix 已提交
54

N
Nzix 已提交
55 56
// static
app.use(express.static(path.join(__dirname, 'public')))
57

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

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

B
binaryify 已提交
72
  app.use(route, (req, res) => {
73 74 75
    if(typeof req.query.cookie === 'string'){
      req.query.cookie = cookieToJson(req.query.cookie)
    }
76
    let query = Object.assign({}, {cookie: req.cookies}, req.query, req.body, req.files )
77

B
binaryify 已提交
78 79 80 81 82 83 84
    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 => {
B
v3.32.0  
binaryify 已提交
85
        console.log('[ERR]', decodeURIComponent(req.originalUrl), {status: answer.status, body: answer.body})
N
Nzix 已提交
86
        if(answer.body.code == '301') answer.body.msg = '需要登录'
B
binaryify 已提交
87 88 89 90
        res.append('Set-Cookie', answer.cookie)
        res.status(answer.status).send(answer.body)
      })
  })
N
Nzix 已提交
91
})
N
Nzix 已提交
92

B
binaryify 已提交
93
const port = process.env.PORT || 3000
B
binaryify 已提交
94
const host = process.env.HOST || ''
95

B
Bob 已提交
96
app.server = app.listen(port, host, () => {
B
binaryify 已提交
97
  console.log(`server running @ http://${host ? host : 'localhost'}:${port}`)
B
binaryify 已提交
98
})
99

B
binaryify 已提交
100
module.exports = app