app.js 3.5 KB
Newer Older
B
binaryify 已提交
1 2 3 4 5 6
const express = require('express')
const apicache = require('apicache')
const path = require('path')
const fs = require('fs')
const app = express()
let cache = apicache.middleware
J
jjeejj 已提交
7 8
const { exec } = require('child_process');
exec('npm info NeteaseCloudMusicApi version', (err, stdout, stderr) => {
B
binaryify 已提交
9
  if (err) {
J
jjeejj 已提交
10 11
    console.error(err);
    return;
B
binaryify 已提交
12
  }
J
jjeejj 已提交
13
  const onlinePackageVersion = stdout.trim();
B
binaryify 已提交
14
  const package = require('./package.json')
J
jjeejj 已提交
15
  if (package.version < onlinePackageVersion) {
B
binaryify 已提交
16 17
    console.log(
      '最新版:Version:' +
J
jjeejj 已提交
18
      onlinePackageVersion +
B
binaryify 已提交
19 20 21 22 23 24
        ',当前版本:' +
        package.version +
        ',请及时更新'
    )
  }
})
J
jjeejj 已提交
25

26
// 跨域设置
B
binaryify 已提交
27 28 29
app.all('*', function(req, res, next) {
  if (req.path !== '/' && !req.path.includes('.')) {
    res.header('Access-Control-Allow-Credentials', true)
B
improve  
binaryify 已提交
30
    // 这里获取 origin 请求头 而不是用 *
B
binaryify 已提交
31 32 33 34
    res.header('Access-Control-Allow-Origin', req.headers['origin'] || '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('Content-Type', 'application/json;charset=utf-8')
B
improve  
binaryify 已提交
35
  }
B
binaryify 已提交
36 37
  next()
})
B
improve  
binaryify 已提交
38

B
binaryify 已提交
39
const onlyStatus200 = (req, res) => res.statusCode === 200
40

B
binaryify 已提交
41
app.use(cache('2 minutes', onlyStatus200))
B
binaryify 已提交
42

B
binaryify 已提交
43
app.use(express.static(path.resolve(__dirname, 'public')))
44

45 46 47 48 49 50 51 52 53
// 补全缺失的cookie
const { completeCookie } = require('./util/init')
app.use(function(req, res, next) {
  let cookie = completeCookie(req.headers.cookie)
  req.headers.cookie = cookie.map(x => x[0]).concat(req.headers.cookie || []).join('; ')
  res.append('Set-Cookie', cookie.map(x => (x.concat('Path=/').join('; '))))
  next()
})

N
Nzix 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
// cookie parser
app.use(function(req, res, next) {
  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()
})

app.use(function(req, res, next) {
  const proxy = req.query.proxy
  if (proxy) {
    req.headers.cookie += `__proxy__${proxy}`
  }
  next()
})

72 73 74
// 因为这几个文件对外所注册的路由 和 其他文件对外注册的路由规则不一样, 所以专门写个MAP对这些文件做特殊处理
const UnusualRouteFileMap = {
  // key 为文件名, value 为对外注册的路由
B
binaryify 已提交
75 76 77 78
  'daily_signin.js': '/daily_signin',
  'fm_trash.js': '/fm_trash',
  'personal_fm.js': '/personal_fm'
}
79

N
Nzix 已提交
80

N
Nzix 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
// 改写router为module
const requestMod = require('./util/request')
let dev = express()
fs.readdirSync(path.join(__dirname, 'module'))
.reverse()
.forEach(file => {
  if (!(/\.js$/i.test(file))) return
  let route = (file in UnusualRouteFileMap) ?  UnusualRouteFileMap[file] : '/' + file.replace(/\.js$/i, '').replace(/_/g, '/')
  let question = require(path.join(__dirname, 'module', file))
  
  dev.use(route, (req, res) => {
    let query = {...req.query, cookie: req.cookies}
    question(query, requestMod)
    .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))
      res.append('Set-Cookie', answer.cookie)
      res.status(answer.status).send(answer.body)
N
Nzix 已提交
103 104
    })
  })
N
Nzix 已提交
105
})
B
v3.0.0  
binaryify 已提交
106
app.use('/', dev)
N
Nzix 已提交
107

B
binaryify 已提交
108
const port = process.env.PORT || 3000
109

N
Nzix 已提交
110
app.server = app.listen(port, () => {
B
binaryify 已提交
111 112
  console.log(`server running @ http://localhost:${port}`)
})
113

B
binaryify 已提交
114
module.exports = app