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