You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

167 lines
4.4 KiB

  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. async getAssetPath() {
  60. let hierarchy = []
  61. if (this.folderId) {
  62. hierarchy = await WIKI.models.assetFolders.getHierarchy(this.folderId)
  63. }
  64. return (this.folderId) ? hierarchy.map(h => h.slug).join('/') + `/${this.filename}` : this.filename
  65. }
  66. async deleteAssetCache() {
  67. await fs.remove(path.join(process.cwd(), `data/cache/${this.hash}.dat`))
  68. }
  69. static async upload(opts) {
  70. const fileInfo = path.parse(opts.originalname)
  71. const fileHash = assetHelper.generateHash(opts.assetPath)
  72. // Check for existing asset
  73. let asset = await WIKI.models.assets.query().where({
  74. hash: fileHash,
  75. folderId: opts.folderId
  76. }).first()
  77. // Build Object
  78. let assetRow = {
  79. filename: opts.originalname,
  80. hash: fileHash,
  81. ext: fileInfo.ext,
  82. kind: _.startsWith(opts.mimetype, 'image/') ? 'image' : 'binary',
  83. mime: opts.mimetype,
  84. fileSize: opts.size,
  85. folderId: opts.folderId,
  86. authorId: opts.userId
  87. }
  88. // Save asset data
  89. try {
  90. const fileBuffer = await fs.readFile(opts.path)
  91. if (asset) {
  92. // Patch existing asset
  93. await WIKI.models.assets.query().patch(assetRow).findById(asset.id)
  94. await WIKI.models.knex('assetData').where({
  95. id: asset.id
  96. }).update({
  97. data: fileBuffer
  98. })
  99. } else {
  100. // Create asset entry
  101. asset = await WIKI.models.assets.query().insert(assetRow)
  102. await WIKI.models.knex('assetData').insert({
  103. id: asset.id,
  104. data: fileBuffer
  105. })
  106. }
  107. } catch (err) {
  108. WIKI.logger.warn(err)
  109. }
  110. // Move temp upload to cache
  111. await fs.move(opts.path, path.join(process.cwd(), `data/cache/${fileHash}.dat`), { overwrite: true })
  112. }
  113. static async getAsset(assetPath, res) {
  114. let assetExists = await WIKI.models.assets.getAssetFromCache(assetPath, res)
  115. if (!assetExists) {
  116. await WIKI.models.assets.getAssetFromDb(assetPath, res)
  117. }
  118. }
  119. static async getAssetFromCache(assetPath, res) {
  120. const fileHash = assetHelper.generateHash(assetPath)
  121. const cachePath = path.join(process.cwd(), `data/cache/${fileHash}.dat`)
  122. return new Promise((resolve, reject) => {
  123. res.type(path.extname(assetPath))
  124. res.sendFile(cachePath, { dotfiles: 'deny' }, err => {
  125. if (err) {
  126. resolve(false)
  127. } else {
  128. resolve(true)
  129. }
  130. })
  131. })
  132. }
  133. static async getAssetFromDb(assetPath, res) {
  134. const fileHash = assetHelper.generateHash(assetPath)
  135. const cachePath = path.join(process.cwd(), `data/cache/${fileHash}.dat`)
  136. const asset = await WIKI.models.assets.query().where('hash', fileHash).first()
  137. if (asset) {
  138. const assetData = await WIKI.models.knex('assetData').where('id', asset.id).first()
  139. res.type(asset.ext)
  140. res.send(assetData.data)
  141. await fs.outputFile(cachePath, assetData.data)
  142. } else {
  143. res.sendStatus(404)
  144. }
  145. }
  146. }