assets.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 folderPath = opts.hierarchy.map(h => h.slug).join('/')
  62. const fileHash = opts.folderId ? assetHelper.generateHash(`${folderPath}/${opts.originalname}`) : assetHelper.generateHash(opts.originalname)
  63. // Create asset entry
  64. const asset = await WIKI.models.assets.query().insert({
  65. filename: opts.originalname,
  66. hash: fileHash,
  67. ext: fileInfo.ext,
  68. kind: _.startsWith(opts.mimetype, 'image/') ? 'image' : 'binary',
  69. mime: opts.mimetype,
  70. fileSize: opts.size,
  71. folderId: opts.folderId,
  72. authorId: opts.userId
  73. })
  74. // Save asset data
  75. try {
  76. const fileBuffer = await fs.readFile(opts.path)
  77. await WIKI.models.knex('assetData').insert({
  78. id: asset.id,
  79. data: fileBuffer
  80. })
  81. } catch (err) {
  82. WIKI.logger.warn(err)
  83. }
  84. // Move temp upload to cache
  85. await fs.move(opts.path, path.join(process.cwd(), `data/cache/${fileHash}.dat`))
  86. }
  87. static async getAsset(assetPath, res) {
  88. let assetExists = await WIKI.models.assets.getAssetFromCache(assetPath, res)
  89. if (!assetExists) {
  90. await WIKI.models.assets.getAssetFromDb(assetPath, res)
  91. }
  92. }
  93. static async getAssetFromCache(assetPath, res) {
  94. const fileHash = assetHelper.generateHash(assetPath)
  95. const cachePath = path.join(process.cwd(), `data/cache/${fileHash}.dat`)
  96. return new Promise((resolve, reject) => {
  97. res.type(path.extname(assetPath))
  98. res.sendFile(cachePath, { dotfiles: 'deny' }, err => {
  99. if (err) {
  100. resolve(false)
  101. } else {
  102. resolve(true)
  103. }
  104. })
  105. })
  106. }
  107. static async getAssetFromDb(assetPath, res) {
  108. const fileHash = assetHelper.generateHash(assetPath)
  109. const cachePath = path.join(process.cwd(), `data/cache/${fileHash}.dat`)
  110. const asset = await WIKI.models.assets.query().where('hash', fileHash).first()
  111. if (asset) {
  112. const assetData = await WIKI.models.knex('assetData').where('id', asset.id).first()
  113. res.type(asset.ext)
  114. res.send(assetData.data)
  115. await fs.outputFile(cachePath, assetData.data)
  116. } else {
  117. res.sendStatus(404)
  118. }
  119. }
  120. }