assets.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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.user.id
  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. // Move temp upload to cache
  108. await fs.move(opts.path, path.join(process.cwd(), `data/cache/${fileHash}.dat`), { overwrite: true })
  109. // Add to Storage
  110. if (!opts.skipStorage) {
  111. await WIKI.models.storage.assetEvent({
  112. event: 'uploaded',
  113. asset: {
  114. ...asset,
  115. path: await asset.getAssetPath(),
  116. data: fileBuffer,
  117. authorId: opts.user.id,
  118. authorName: opts.user.name,
  119. authorEmail: opts.user.email
  120. }
  121. })
  122. }
  123. } catch (err) {
  124. WIKI.logger.warn(err)
  125. }
  126. }
  127. static async getAsset(assetPath, res) {
  128. let assetExists = await WIKI.models.assets.getAssetFromCache(assetPath, res)
  129. if (!assetExists) {
  130. await WIKI.models.assets.getAssetFromDb(assetPath, res)
  131. }
  132. }
  133. static async getAssetFromCache(assetPath, res) {
  134. const fileHash = assetHelper.generateHash(assetPath)
  135. const cachePath = path.join(process.cwd(), `data/cache/${fileHash}.dat`)
  136. return new Promise((resolve, reject) => {
  137. res.type(path.extname(assetPath))
  138. res.sendFile(cachePath, { dotfiles: 'deny' }, err => {
  139. if (err) {
  140. resolve(false)
  141. } else {
  142. resolve(true)
  143. }
  144. })
  145. })
  146. }
  147. static async getAssetFromDb(assetPath, res) {
  148. const fileHash = assetHelper.generateHash(assetPath)
  149. const cachePath = path.join(process.cwd(), `data/cache/${fileHash}.dat`)
  150. const asset = await WIKI.models.assets.query().where('hash', fileHash).first()
  151. if (asset) {
  152. const assetData = await WIKI.models.knex('assetData').where('id', asset.id).first()
  153. res.type(asset.ext)
  154. res.send(assetData.data)
  155. await fs.outputFile(cachePath, assetData.data)
  156. } else {
  157. res.sendStatus(404)
  158. }
  159. }
  160. static async flushTempUploads() {
  161. return fs.emptyDir(path.join(process.cwd(), `data/uploads`))
  162. }
  163. }