]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/avatar.ts
1b38e6cb59060743240f003e212f8f4dcf0ea5d2
[github/Chocobozzz/PeerTube.git] / server / lib / avatar.ts
1 import 'multer'
2 import { sendUpdateActor } from './activitypub/send'
3 import { AVATARS_SIZE, LRU_CACHE, QUEUE_CONCURRENCY } from '../initializers/constants'
4 import { updateActorAvatarInstance } from './activitypub'
5 import { processImage } from '../helpers/image-utils'
6 import { AccountModel } from '../models/account/account'
7 import { VideoChannelModel } from '../models/video/video-channel'
8 import { extname, join } from 'path'
9 import { retryTransactionWrapper } from '../helpers/database-utils'
10 import * as uuidv4 from 'uuid/v4'
11 import { CONFIG } from '../initializers/config'
12 import { sequelizeTypescript } from '../initializers/database'
13 import * as LRUCache from 'lru-cache'
14 import { queue } from 'async'
15 import { downloadImage } from '../helpers/requests'
16
17 async function updateActorAvatarFile (avatarPhysicalFile: Express.Multer.File, accountOrChannel: AccountModel | VideoChannelModel) {
18 const extension = extname(avatarPhysicalFile.filename)
19 const avatarName = uuidv4() + extension
20 const destination = join(CONFIG.STORAGE.AVATARS_DIR, avatarName)
21 await processImage(avatarPhysicalFile.path, destination, AVATARS_SIZE)
22
23 return retryTransactionWrapper(() => {
24 return sequelizeTypescript.transaction(async t => {
25 const avatarInfo = {
26 name: avatarName,
27 fileUrl: null,
28 onDisk: true
29 }
30
31 const updatedActor = await updateActorAvatarInstance(accountOrChannel.Actor, avatarInfo, t)
32 await updatedActor.save({ transaction: t })
33
34 await sendUpdateActor(accountOrChannel, t)
35
36 return updatedActor.Avatar
37 })
38 })
39 }
40
41 type DownloadImageQueueTask = { fileUrl: string, filename: string }
42
43 const downloadImageQueue = queue<DownloadImageQueueTask, Error>((task, cb) => {
44 downloadImage(task.fileUrl, CONFIG.STORAGE.AVATARS_DIR, task.filename, AVATARS_SIZE)
45 .then(() => cb())
46 .catch(err => cb(err))
47 }, QUEUE_CONCURRENCY.AVATAR_PROCESS_IMAGE)
48
49 function pushAvatarProcessInQueue (task: DownloadImageQueueTask) {
50 return new Promise((res, rej) => {
51 downloadImageQueue.push(task, err => {
52 if (err) return rej(err)
53
54 return res()
55 })
56 })
57 }
58
59 // Unsafe so could returns paths that does not exist anymore
60 const avatarPathUnsafeCache = new LRUCache<string, string>({ max: LRU_CACHE.AVATAR_STATIC.MAX_SIZE })
61
62 export {
63 avatarPathUnsafeCache,
64 updateActorAvatarFile,
65 pushAvatarProcessInQueue
66 }