assets.js 3.6 KB

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