albumsController.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const config = require('../config.js')
  2. const db = require('knex')(config.database)
  3. let albumsController = {}
  4. albumsController.list = function(req, res, next){
  5. if(req.headers.auth !== config.adminToken)
  6. return res.status(401).json({ success: false, description: 'not-authorized'})
  7. let fields = ['id', 'name']
  8. if(req.params.sidebar === undefined)
  9. fields.push('timestamp')
  10. db.table('albums').select(fields).where('enabled', 1).then((albums) => {
  11. if(req.params.sidebar !== undefined)
  12. return res.json({ success: true, albums })
  13. let ids = []
  14. for(let album of albums){
  15. album.date = new Date(album.timestamp * 1000)
  16. album.date = album.date.getFullYear() + '-' + (album.date.getMonth() + 1) + '-' + album.date.getDate() + ' ' + (album.date.getHours() < 10 ? '0' : '') + album.date.getHours() + ':' + (album.date.getMinutes() < 10 ? '0' : '') + album.date.getMinutes() + ':' + (album.date.getSeconds() < 10 ? '0' : '') + album.date.getSeconds()
  17. ids.push(album.id)
  18. }
  19. db.table('files').whereIn('albumid', ids).select('albumid').then((files) => {
  20. let albumsCount = {}
  21. for(let id of ids) albumsCount[id] = 0
  22. for(let file of files) albumsCount[file.albumid] += 1
  23. for(let album of albums) album.files = albumsCount[album.id]
  24. return res.json({ success: true, albums })
  25. })
  26. })
  27. }
  28. albumsController.create = function(req, res, next){
  29. if(req.headers.auth !== config.adminToken)
  30. return res.status(401).json({ success: false, description: 'not-authorized'})
  31. let name = req.body.name
  32. if(name === undefined || name === '')
  33. return res.json({ success: false, description: 'No album name specified' })
  34. db.table('albums').where('name', name).then((album) => {
  35. if(album.length !== 0) return res.json({ success: false, description: 'There\'s already an album with that name' })
  36. db.table('albums').insert({
  37. name: name,
  38. enabled: 1,
  39. timestamp: Math.floor(Date.now() / 1000)
  40. }).then(() => {
  41. return res.json({ success: true })
  42. })
  43. })
  44. }
  45. module.exports = albumsController