assets.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. /* global WIKI */
  2. const Model = require('objection').Model
  3. const moment = require('moment')
  4. const path = require('path')
  5. const fs = require('fs-extra')
  6. const _ = require('lodash')
  7. const assetHelper = require('../helpers/asset')
  8. /**
  9. * Users model
  10. */
  11. module.exports = class Asset extends Model {
  12. static get tableName() { return 'assets' }
  13. static get jsonSchema () {
  14. return {
  15. type: 'object',
  16. properties: {
  17. id: {type: 'integer'},
  18. filename: {type: 'string'},
  19. hash: {type: 'string'},
  20. ext: {type: 'string'},
  21. kind: {type: 'string'},
  22. mime: {type: 'string'},
  23. fileSize: {type: 'integer'},
  24. metadata: {type: 'object'},
  25. createdAt: {type: 'string'},
  26. updatedAt: {type: 'string'}
  27. }
  28. }
  29. }
  30. static get relationMappings() {
  31. return {
  32. author: {
  33. relation: Model.BelongsToOneRelation,
  34. modelClass: require('./users'),
  35. join: {
  36. from: 'assets.authorId',
  37. to: 'users.id'
  38. }
  39. },
  40. folder: {
  41. relation: Model.BelongsToOneRelation,
  42. modelClass: require('./assetFolders'),
  43. join: {
  44. from: 'assets.folderId',
  45. to: 'assetFolders.id'
  46. }
  47. }
  48. }
  49. }
  50. async $beforeUpdate(opt, context) {
  51. await super.$beforeUpdate(opt, context)
  52. this.updatedAt = moment.utc().toISOString()
  53. }
  54. async $beforeInsert(context) {
  55. await super.$beforeInsert(context)
  56. this.createdAt = moment.utc().toISOString()
  57. this.updatedAt = moment.utc().toISOString()
  58. }
  59. static async upload(opts) {
  60. const fileInfo = path.parse(opts.originalname)
  61. const fileHash = assetHelper.generateHash(`${opts.folder}/${opts.originalname}`)
  62. // Create asset entry
  63. const asset = await WIKI.models.assets.query().insert({
  64. filename: opts.originalname,
  65. hash: fileHash,
  66. ext: fileInfo.ext,
  67. kind: _.startsWith(opts.mimetype, 'image/') ? 'image' : 'binary',
  68. mime: opts.mimetype,
  69. fileSize: opts.size,
  70. authorId: opts.userId
  71. })
  72. // Save asset data
  73. try {
  74. const fileBuffer = await fs.readFile(opts.path)
  75. await WIKI.models.knex('assetData').insert({
  76. id: asset.id,
  77. data: fileBuffer
  78. })
  79. } catch (err) {
  80. WIKI.logger.warn(err)
  81. }
  82. // Move temp upload to cache
  83. await fs.move(opts.path, path.join(process.cwd(), `data/cache/${fileHash}.dat`))
  84. }
  85. static async getAsset(assetPath, res) {
  86. let asset = await WIKI.models.assets.getAssetFromCache(assetPath, res)
  87. if (!asset) {
  88. // asset = await WIKI.models.assets.getAssetFromDb(assetPath, res)
  89. // if (asset) {
  90. // await WIKI.models.assets.saveAssetToCache(asset)
  91. // }
  92. res.sendStatus(404)
  93. }
  94. }
  95. static async getAssetFromCache(assetPath, res) {
  96. const fileHash = assetHelper.generateHash(assetPath)
  97. const cachePath = path.join(process.cwd(), `data/cache/${fileHash}.dat`)
  98. return new Promise((resolve, reject) => {
  99. res.sendFile(cachePath, { dotfiles: 'deny' }, err => {
  100. if (err) {
  101. resolve(false)
  102. } else {
  103. resolve(true)
  104. }
  105. })
  106. })
  107. }
  108. }