mirror of https://github.com/requarks/wiki
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.
238 lines
6.7 KiB
238 lines
6.7 KiB
2 years ago
|
import { Model } from 'objection'
|
||
|
import path from 'path'
|
||
|
import fse from 'fs-extra'
|
||
|
import { startsWith } from 'lodash-es'
|
||
|
import { generateHash } from '../helpers/common.mjs'
|
||
|
|
||
|
import { User } from './users.mjs'
|
||
6 years ago
|
|
||
|
/**
|
||
|
* Users model
|
||
|
*/
|
||
2 years ago
|
export class Asset extends Model {
|
||
6 years ago
|
static get tableName() { return 'assets' }
|
||
|
|
||
|
static get jsonSchema () {
|
||
|
return {
|
||
|
type: 'object',
|
||
|
|
||
|
properties: {
|
||
2 years ago
|
id: {type: 'string'},
|
||
6 years ago
|
filename: {type: 'string'},
|
||
|
hash: {type: 'string'},
|
||
|
ext: {type: 'string'},
|
||
|
kind: {type: 'string'},
|
||
|
mime: {type: 'string'},
|
||
|
fileSize: {type: 'integer'},
|
||
|
metadata: {type: 'object'},
|
||
|
createdAt: {type: 'string'},
|
||
|
updatedAt: {type: 'string'}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
static get relationMappings() {
|
||
|
return {
|
||
|
author: {
|
||
|
relation: Model.BelongsToOneRelation,
|
||
2 years ago
|
modelClass: User,
|
||
6 years ago
|
join: {
|
||
|
from: 'assets.authorId',
|
||
|
to: 'users.id'
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async $beforeUpdate(opt, context) {
|
||
|
await super.$beforeUpdate(opt, context)
|
||
|
|
||
|
this.updatedAt = moment.utc().toISOString()
|
||
|
}
|
||
|
async $beforeInsert(context) {
|
||
|
await super.$beforeInsert(context)
|
||
|
|
||
|
this.createdAt = moment.utc().toISOString()
|
||
|
this.updatedAt = moment.utc().toISOString()
|
||
|
}
|
||
|
|
||
6 years ago
|
async getAssetPath() {
|
||
|
let hierarchy = []
|
||
|
if (this.folderId) {
|
||
2 years ago
|
hierarchy = await WIKI.db.assetFolders.getHierarchy(this.folderId)
|
||
6 years ago
|
}
|
||
|
return (this.folderId) ? hierarchy.map(h => h.slug).join('/') + `/${this.filename}` : this.filename
|
||
|
}
|
||
|
|
||
|
async deleteAssetCache() {
|
||
2 years ago
|
await fse.remove(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${this.hash}.dat`))
|
||
6 years ago
|
}
|
||
|
|
||
6 years ago
|
static async upload(opts) {
|
||
|
const fileInfo = path.parse(opts.originalname)
|
||
|
|
||
6 years ago
|
// Check for existing asset
|
||
2 years ago
|
let asset = await WIKI.db.assets.query().where({
|
||
2 years ago
|
// hash: fileHash,
|
||
6 years ago
|
folderId: opts.folderId
|
||
|
}).first()
|
||
|
|
||
|
// Build Object
|
||
|
let assetRow = {
|
||
6 years ago
|
filename: opts.originalname,
|
||
|
ext: fileInfo.ext,
|
||
2 years ago
|
kind: startsWith(opts.mimetype, 'image/') ? 'image' : 'binary',
|
||
6 years ago
|
mime: opts.mimetype,
|
||
|
fileSize: opts.size,
|
||
5 years ago
|
folderId: opts.folderId
|
||
6 years ago
|
}
|
||
6 years ago
|
|
||
3 years ago
|
// Sanitize SVG contents
|
||
3 years ago
|
if (
|
||
|
WIKI.config.uploads.scanSVG &&
|
||
|
(
|
||
|
opts.mimetype.toLowerCase().startsWith('image/svg') ||
|
||
3 years ago
|
fileInfo.ext.toLowerCase() === '.svg'
|
||
3 years ago
|
)
|
||
|
) {
|
||
3 years ago
|
const svgSanitizeJob = await WIKI.scheduler.registerJob({
|
||
|
name: 'sanitize-svg',
|
||
|
immediate: true,
|
||
|
worker: true
|
||
|
}, opts.path)
|
||
|
await svgSanitizeJob.finished
|
||
|
}
|
||
|
|
||
6 years ago
|
// Save asset data
|
||
|
try {
|
||
2 years ago
|
const fileBuffer = await fse.readFile(opts.path)
|
||
6 years ago
|
|
||
|
if (asset) {
|
||
|
// Patch existing asset
|
||
5 years ago
|
if (opts.mode === 'upload') {
|
||
|
assetRow.authorId = opts.user.id
|
||
|
}
|
||
2 years ago
|
await WIKI.db.assets.query().patch(assetRow).findById(asset.id)
|
||
|
await WIKI.db.knex('assetData').where({
|
||
6 years ago
|
id: asset.id
|
||
|
}).update({
|
||
|
data: fileBuffer
|
||
|
})
|
||
|
} else {
|
||
|
// Create asset entry
|
||
5 years ago
|
assetRow.authorId = opts.user.id
|
||
2 years ago
|
asset = await WIKI.db.assets.query().insert(assetRow)
|
||
|
await WIKI.db.knex('assetData').insert({
|
||
6 years ago
|
id: asset.id,
|
||
|
data: fileBuffer
|
||
|
})
|
||
|
}
|
||
5 years ago
|
|
||
|
// Move temp upload to cache
|
||
2 years ago
|
// if (opts.mode === 'upload') {
|
||
|
// await fs.move(opts.path, path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${fileHash}.dat`), { overwrite: true })
|
||
|
// } else {
|
||
|
// await fs.copy(opts.path, path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${fileHash}.dat`), { overwrite: true })
|
||
|
// }
|
||
5 years ago
|
|
||
|
// Add to Storage
|
||
|
if (!opts.skipStorage) {
|
||
2 years ago
|
await WIKI.db.storage.assetEvent({
|
||
5 years ago
|
event: 'uploaded',
|
||
|
asset: {
|
||
|
...asset,
|
||
|
path: await asset.getAssetPath(),
|
||
|
data: fileBuffer,
|
||
|
authorId: opts.user.id,
|
||
|
authorName: opts.user.name,
|
||
|
authorEmail: opts.user.email
|
||
|
}
|
||
|
})
|
||
|
}
|
||
6 years ago
|
} catch (err) {
|
||
|
WIKI.logger.warn(err)
|
||
|
}
|
||
|
}
|
||
6 years ago
|
|
||
2 years ago
|
static async getThumbnail ({ id, path, locale, siteId }) {
|
||
|
return WIKI.db.tree.query()
|
||
|
.select('tree.*', 'assets.preview', 'assets.previewState')
|
||
|
.innerJoin('assets', 'tree.id', 'assets.id')
|
||
|
.where(id ? { 'tree.id': id } : {
|
||
2 years ago
|
'tree.hash': generateHash(path),
|
||
2 years ago
|
'tree.localeCode': locale,
|
||
|
'tree.siteId': siteId
|
||
|
})
|
||
|
.first()
|
||
|
}
|
||
|
|
||
|
static async getAsset({ path, locale, siteId }, res) {
|
||
4 years ago
|
try {
|
||
2 years ago
|
const fileInfo = '' // assetHelper.getPathInfo(assetPath)
|
||
|
const fileHash = '' // assetHelper.generateHash(assetPath)
|
||
4 years ago
|
const cachePath = path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `cache/${fileHash}.dat`)
|
||
3 years ago
|
|
||
|
// Force unsafe extensions to download
|
||
|
if (WIKI.config.uploads.forceDownload && !['.png', '.apng', '.jpg', '.jpeg', '.gif', '.bmp', '.webp', '.svg'].includes(fileInfo.ext)) {
|
||
3 years ago
|
res.set('Content-disposition', 'attachment; filename=' + encodeURIComponent(fileInfo.base))
|
||
3 years ago
|
}
|
||
|
|
||
2 years ago
|
if (await WIKI.db.assets.getAssetFromCache(assetPath, cachePath, res)) {
|
||
4 years ago
|
return
|
||
|
}
|
||
2 years ago
|
if (await WIKI.db.assets.getAssetFromStorage(assetPath, res)) {
|
||
4 years ago
|
return
|
||
|
}
|
||
2 years ago
|
await WIKI.db.assets.getAssetFromDb(assetPath, fileHash, cachePath, res)
|
||
4 years ago
|
} catch (err) {
|
||
|
if (err.code === `ECONNABORTED` || err.code === `EPIPE`) {
|
||
|
return
|
||
|
}
|
||
|
WIKI.logger.error(err)
|
||
|
res.sendStatus(500)
|
||
6 years ago
|
}
|
||
|
}
|
||
|
|
||
4 years ago
|
static async getAssetFromCache(assetPath, cachePath, res) {
|
||
|
try {
|
||
2 years ago
|
await fse.access(cachePath, fse.constants.R_OK)
|
||
4 years ago
|
} catch (err) {
|
||
|
return false
|
||
|
}
|
||
|
res.type(path.extname(assetPath))
|
||
2 years ago
|
await new Promise(resolve => res.sendFile(cachePath, { dotfiles: 'deny' }, resolve))
|
||
4 years ago
|
return true
|
||
6 years ago
|
}
|
||
6 years ago
|
|
||
4 years ago
|
static async getAssetFromStorage(assetPath, res) {
|
||
2 years ago
|
const localLocations = await WIKI.db.storage.getLocalLocations({
|
||
4 years ago
|
asset: {
|
||
4 years ago
|
path: assetPath
|
||
4 years ago
|
}
|
||
|
})
|
||
2 years ago
|
for (let location of localLocations.filter(location => Boolean(location.path))) {
|
||
2 years ago
|
const assetExists = await WIKI.db.assets.getAssetFromCache(assetPath, location.path, res)
|
||
4 years ago
|
if (assetExists) {
|
||
|
return true
|
||
|
}
|
||
|
}
|
||
|
return false
|
||
|
}
|
||
6 years ago
|
|
||
4 years ago
|
static async getAssetFromDb(assetPath, fileHash, cachePath, res) {
|
||
2 years ago
|
const asset = await WIKI.db.assets.query().where('hash', fileHash).first()
|
||
6 years ago
|
if (asset) {
|
||
2 years ago
|
const assetData = await WIKI.db.knex('assetData').where('id', asset.id).first()
|
||
6 years ago
|
res.type(asset.ext)
|
||
|
res.send(assetData.data)
|
||
2 years ago
|
await fse.outputFile(cachePath, assetData.data)
|
||
6 years ago
|
} else {
|
||
|
res.sendStatus(404)
|
||
|
}
|
||
|
}
|
||
6 years ago
|
|
||
|
static async flushTempUploads() {
|
||
2 years ago
|
return fse.emptyDir(path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, `uploads`))
|
||
6 years ago
|
}
|
||
6 years ago
|
}
|