server.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. const fs = require('fs')
  2. const path = require('path')
  3. const Koa = require('koa')
  4. const Router = require('koa-router')
  5. const bodyParser = require('koa-bodyparser')
  6. const LRU = require('lru-cache')
  7. const WebSocket = require('ws')
  8. const koaStatic = require('koa-static')
  9. const { routerOptions, lruOptions, watchFileOptions, filePath, ports } = require('./config')
  10. const { dataPath, reviewDataPath, staticPath } = filePath
  11. const { appPort, wsPort } = ports
  12. const router = new Router(routerOptions)
  13. const cache = new LRU(lruOptions)
  14. let STATIC_DATA = ''
  15. const readFile = () => {
  16. fs.readFile(dataPath, (err, buf) => {
  17. if (err) {
  18. console.error(err)
  19. return
  20. }
  21. STATIC_DATA = buf.toString().replace('\n', '').split(',')
  22. })
  23. }
  24. readFile()
  25. setInterval(() => {
  26. readFile()
  27. }, 60 * 60 * 24e3)
  28. fs.watchFile(dataPath, watchFileOptions, (curr, prev) => {
  29. if (curr.mtime !== prev.mtime) {
  30. STATIC_DATA = ''
  31. fs.readFile(dataPath, (err, buf) => {
  32. if (err) {
  33. console.error(err)
  34. return
  35. }
  36. STATIC_DATA = buf.toString().split(',')
  37. })
  38. }
  39. })
  40. const app = new Koa()
  41. const wss = new WebSocket.Server({ port: wsPort })
  42. app.use(koaStatic(path.join(__dirname, staticPath)))
  43. wss.on('connection', ws => {
  44. ws.on('message', msg => {
  45. const res = JSON.parse(msg)
  46. console.log('msg: ', res)
  47. if (res.code) {
  48. const list = cache.get(res.code)
  49. if (res.status === 'update') {
  50. const data = JSON.stringify({ data: list })
  51. wss.clients.forEach(client => {
  52. if (client.readyState === WebSocket.OPEN) {
  53. client.send(data)
  54. }
  55. })
  56. } else if (res.status === 'over') {
  57. list.forEach(el => {
  58. el.status = 1
  59. })
  60. const data = JSON.stringify({ data: list })
  61. wss.clients.forEach(client => {
  62. if (client.readyState === WebSocket.OPEN) {
  63. client.send(data)
  64. }
  65. })
  66. }
  67. }
  68. })
  69. })
  70. app.use(bodyParser())
  71. // 判断是不是api
  72. // app.use((ctx, next) => {
  73. // const url = ctx.url
  74. // const isApi = /^\/api/.test(url)
  75. // ctx.$isApi = isApi
  76. // next()
  77. // })
  78. router.get('/list', (ctx, next) => {
  79. const { code } = ctx.query
  80. let data
  81. if (cache.has(code)) {
  82. data = cache.get(code)
  83. } else {
  84. const jsonData = STATIC_DATA || ''
  85. const len = 25
  86. const sum = jsonData.length - len
  87. const arr = new Array(25).fill(1).map(el => Math.floor(Math.random() * sum))
  88. const groupList = [1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 0, 0, 0, 0, 0, 0, 0]
  89. data = new Array(25).fill(1).map((el, i) => {
  90. const del = groupList.length ? Math.floor(Math.random() * groupList.length) : 0
  91. const group = groupList.splice(del, 1)[0]
  92. return {
  93. text: jsonData.splice(arr[i], 1)[0],
  94. status: 0,
  95. group
  96. }
  97. })
  98. cache.set(code, data)
  99. }
  100. ctx.body = {
  101. code,
  102. data
  103. }
  104. })
  105. router.put('/status/:code', ctx => {
  106. const { params, request } = ctx
  107. const { code } = params
  108. const { index } = request.body
  109. const list = cache.get(code) || []
  110. if (!index && index !== 0) {
  111. throw new Error('index is not find')
  112. }
  113. if (!list || !list.length) {
  114. throw new Error('cache list is not find')
  115. }
  116. list[index].status = list[index].status ? 0 : 1
  117. cache.set(code, list)
  118. ctx.body = { success: true, msg: '更新成功', data: list[index] }
  119. })
  120. router.post('/words', ctx => {
  121. const { request } = ctx
  122. const { words = '' } = request.body
  123. const wordsList = words.split(',')
  124. const noExist = []
  125. const exist = wordsList.filter(el => {
  126. if (STATIC_DATA.indexOf(el) !== -1) {
  127. return true
  128. }
  129. noExist.push(el)
  130. return false
  131. })
  132. const pushNewWords = noExist.join(',')
  133. fs.appendFile(reviewDataPath, pushNewWords, (err) => {
  134. if (err) {
  135. console.error('appendFile error:', err)
  136. }
  137. })
  138. let body = {}
  139. if (exist.length) {
  140. body = { success: false, exist }
  141. } else {
  142. body = { success: true }
  143. }
  144. ctx.body = body
  145. })
  146. router.get('/reviews', ctx => {
  147. const buf = fs.readFileSync(reviewDataPath)
  148. const text = buf.toString()
  149. let list = []
  150. if (text) {
  151. list = text.split(',')
  152. }
  153. ctx.body = { success: true, list }
  154. })
  155. router.post('/reviews', ctx => {
  156. const { request } = ctx
  157. const { words = '' } = request.body
  158. const wordsList = words.split(',')
  159. const noExist = []
  160. const exist = wordsList.filter(el => {
  161. if (STATIC_DATA.indexOf(el) !== -1) {
  162. return true
  163. }
  164. if (el) {
  165. noExist.push(el)
  166. }
  167. return false
  168. })
  169. try {
  170. fs.appendFileSync(dataPath, `,${noExist.join(',')}`)
  171. fs.writeFile(reviewDataPath, '', err => {
  172. if (err) {
  173. return console.error('clear reviewData error:', err)
  174. }
  175. })
  176. if (exist.length) {
  177. ctx.body = { success: true, msg: `${exist.join(',')} 添加失败,词已存在` }
  178. } else {
  179. ctx.body = { success: true, msg: '添加成功' }
  180. }
  181. } catch (error) {
  182. console.error('appendFile error:', error)
  183. ctx.body = { success: false, msg: JSON.stringify(error) }
  184. }
  185. })
  186. app.use(router.routes()).use(router.allowedMethods())
  187. app.on('error', err => console.error(err))
  188. app.listen(appPort)
  189. console.log(`http://127.0.0.1:${appPort}`)