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

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

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

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

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

N
Nzix 已提交
50 51
// cache
app.use(cache('2 minutes', ((req, res) => res.statusCode === 200)))
N
Nzix 已提交
52

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

N
Nzix 已提交
56 57
// router
const special = {
B
binaryify 已提交
58 59 60
  'daily_signin.js': '/daily_signin',
  'fm_trash.js': '/fm_trash',
  'personal_fm.js': '/personal_fm'
N
Nzix 已提交
61
}
N
Nzix 已提交
62

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

B
binaryify 已提交
68
  app.use(route, (req, res) => {
69 70 71
    if(typeof req.query.cookie === 'string'){
      req.query.cookie = cookieToJson(req.query.cookie)
    }
72
    let query = Object.assign({}, {cookie: req.cookies}, req.query, req.body )
73

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

B
binaryify 已提交
89
const port = process.env.PORT || 3000
B
binaryify 已提交
90
const host = process.env.HOST || ''
91

B
Bob 已提交
92
app.server = app.listen(port, host, () => {
B
binaryify 已提交
93
  console.log(`server running @ http://${host ? host : 'localhost'}:${port}`)
B
binaryify 已提交
94
})
95

B
binaryify 已提交
96
module.exports = app