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.

215 lines
6.0 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. const Promise = require('bluebird')
  9. /**
  10. * Users model
  11. */
  12. module.exports = class Asset extends Model {
  13. static get tableName() { return 'assets' }
  14. static get jsonSchema () {
  15. return {
  16. type: 'object',
  17. properties: {
  18. id: {type: 'integer'},
  19. filename: {type: 'string'},
  20. hash: {type: 'string'},
  21. ext: {type: 'string'},
  22. kind: {type: 'string'},
  23. mime: {type: 'string'},
  24. fileSize: {type: 'integer'},
  25. metadata: {type: 'object'},
  26. createdAt: {type: 'string'},
  27. updatedAt: {type: 'string'}
  28. }
  29. }
  30. }
  31. static get relationMappings() {
  32. return {
  33. author: {
  34. relation: Model.BelongsToOneRelation,
  35. modelClass: require('./users'),
  36. join: {
  37. from: 'assets.authorId',
  38. to: 'users.id'
  39. }
  40. },
  41. folder: {
  42. relation: Model.BelongsToOneRelation,
  43. modelClass: require('./assetFolders'),
  44. join: {
  45. from: 'assets.folderId',
  46. to: 'assetFolders.id'
  47. }
  48. }
  49. }
  50. }
  51. async $beforeUpdate(opt, context) {
  52. await super.$beforeUpdate(opt, context)
  53. this.updatedAt = moment.utc().toISOString()
  54. }
  55. async $beforeInsert(context) {
  56. await super.$beforeInsert(context)
  57. this.createdAt = moment.utc().toISOString()
  58. this.updatedAt = moment.utc().toISOString()
  59. }
  60. async getAssetPath() {
  61. let hierarchy = []
  62. if (this.folderId) {
  63. hierarchy = await WIKI.models.assetFolders.getHierarchy(this.folderId)
  64. }
  65. return (this.folderId) ? hierarchy.map(h => h.slug).join('/') + `/${this.filename}` : this.filename
  66. }
  67. async deleteAssetCache() {
  68. await fs.remove(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${this.hash}.dat`))
  69. }
  70. static async upload(opts) {
  71. const fileInfo = path.parse(opts.originalname)
  72. const fileHash = assetHelper.generateHash(opts.assetPath)
  73. // Check for existing asset
  74. let asset = await WIKI.models.assets.query().where({
  75. hash: fileHash,
  76. folderId: opts.folderId
  77. }).first()
  78. // Build Object
  79. let assetRow = {
  80. filename: opts.originalname,
  81. hash: fileHash,
  82. ext: fileInfo.ext,
  83. kind: _.startsWith(opts.mimetype, 'image/') ? 'image' : 'binary',
  84. mime: opts.mimetype,
  85. fileSize: opts.size,
  86. folderId: opts.folderId
  87. }
  88. // Save asset data
  89. try {
  90. const fileBuffer = await fs.readFile(opts.path)
  91. if (asset) {
  92. // Patch existing asset
  93. if (opts.mode === 'upload') {
  94. assetRow.authorId = opts.user.id
  95. }
  96. await WIKI.models.assets.query().patch(assetRow).findById(asset.id)
  97. await WIKI.models.knex('assetData').where({
  98. id: asset.id
  99. }).update({
  100. data: fileBuffer
  101. })
  102. } else {
  103. // Create asset entry
  104. assetRow.authorId = opts.user.id
  105. asset = await WIKI.models.assets.query().insert(assetRow)
  106. await WIKI.models.knex('assetData').insert({
  107. id: asset.id,
  108. data: fileBuffer
  109. })
  110. }
  111. // Move temp upload to cache
  112. if (opts.mode === 'upload') {
  113. await fs.move(opts.path, path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${fileHash}.dat`), { overwrite: true })
  114. } else {
  115. await fs.copy(opts.path, path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${fileHash}.dat`), { overwrite: true })
  116. }
  117. // Add to Storage
  118. if (!opts.skipStorage) {
  119. await WIKI.models.storage.assetEvent({
  120. event: 'uploaded',
  121. asset: {
  122. ...asset,
  123. path: await asset.getAssetPath(),
  124. data: fileBuffer,
  125. authorId: opts.user.id,
  126. authorName: opts.user.name,
  127. authorEmail: opts.user.email
  128. }
  129. })
  130. }
  131. } catch (err) {
  132. WIKI.logger.warn(err)
  133. }
  134. }
  135. static async getAsset(assetPath, res) {
  136. try {
  137. const fileHash = assetHelper.generateHash(assetPath)
  138. const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${fileHash}.dat`)
  139. if (await WIKI.models.assets.getAssetFromCache(assetPath, cachePath, res)) {
  140. return
  141. }
  142. if (await WIKI.models.assets.getAssetFromStorage(assetPath, res)) {
  143. return
  144. }
  145. await WIKI.models.assets.getAssetFromDb(assetPath, fileHash, cachePath, res)
  146. } catch (err) {
  147. if (err.code === `ECONNABORTED` || err.code === `EPIPE`) {
  148. return
  149. }
  150. WIKI.logger.error(err)
  151. res.sendStatus(500)
  152. }
  153. }
  154. static async getAssetFromCache(assetPath, cachePath, res) {
  155. try {
  156. await fs.access(cachePath, fs.constants.R_OK)
  157. } catch (err) {
  158. return false
  159. }
  160. const sendFile = Promise.promisify(res.sendFile, {context: res})
  161. res.type(path.extname(assetPath))
  162. await sendFile(cachePath, { dotfiles: 'deny' })
  163. return true
  164. }
  165. static async getAssetFromStorage(assetPath, res) {
  166. const localLocations = await WIKI.models.storage.getLocalLocations({
  167. asset: {
  168. path: assetPath
  169. }
  170. })
  171. for (let location of _.filter(localLocations, location => Boolean(location.path))) {
  172. const assetExists = await WIKI.models.assets.getAssetFromCache(assetPath, location.path, res)
  173. if (assetExists) {
  174. return true
  175. }
  176. }
  177. return false
  178. }
  179. static async getAssetFromDb(assetPath, fileHash, cachePath, res) {
  180. const asset = await WIKI.models.assets.query().where('hash', fileHash).first()
  181. if (asset) {
  182. const assetData = await WIKI.models.knex('assetData').where('id', asset.id).first()
  183. res.type(asset.ext)
  184. res.send(assetData.data)
  185. await fs.outputFile(cachePath, assetData.data)
  186. } else {
  187. res.sendStatus(404)
  188. }
  189. }
  190. static async flushTempUploads() {
  191. return fs.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `uploads`))
  192. }
  193. }