assets.js 6.6 KB

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