]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/activitypub/actor.ts
Agnostic actor image storage
[github/Chocobozzz/PeerTube.git] / server / models / activitypub / actor.ts
index 58b52ffb1cdab772a736efe3dae7a0f2d3566b7a..09d96b24dc29fd028d6328fba8e0ddbe2a1faa75 100644 (file)
@@ -1,5 +1,6 @@
 import { values } from 'lodash'
 import { extname } from 'path'
+import { literal, Op, Transaction } from 'sequelize'
 import {
   AllowNull,
   BelongsTo,
@@ -16,8 +17,9 @@ import {
   Table,
   UpdatedAt
 } from 'sequelize-typescript'
-import { ActivityPubActorType } from '../../../shared/models/activitypub'
-import { Avatar } from '../../../shared/models/avatars/avatar.model'
+import { ModelCache } from '@server/models/model-cache'
+import { ActivityIconObject, ActivityPubActorType } from '../../../shared/models/activitypub'
+import { ActorImage } from '../../../shared/models/actors/actor-image.model'
 import { activityPubContextify } from '../../helpers/activitypub'
 import {
   isActorFollowersCountValid,
@@ -28,13 +30,6 @@ import {
 } from '../../helpers/custom-validators/activitypub/actor'
 import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
 import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONSTRAINTS_FIELDS, SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants'
-import { AccountModel } from '../account/account'
-import { AvatarModel } from '../avatar/avatar'
-import { ServerModel } from '../server/server'
-import { isOutdated, throwIfNotValid } from '../utils'
-import { VideoChannelModel } from '../video/video-channel'
-import { ActorFollowModel } from './actor-follow'
-import { VideoModel } from '../video/video'
 import {
   MActor,
   MActorAccountChannelId,
@@ -44,10 +39,16 @@ import {
   MActorHost,
   MActorServer,
   MActorSummaryFormattable,
+  MActorUrl,
   MActorWithInboxes
-} from '../../typings/models'
-import * as Bluebird from 'bluebird'
-import { Op, Transaction } from 'sequelize'
+} from '../../types/models'
+import { AccountModel } from '../account/account'
+import { ActorImageModel } from '../account/actor-image'
+import { ServerModel } from '../server/server'
+import { isOutdated, throwIfNotValid } from '../utils'
+import { VideoModel } from '../video/video'
+import { VideoChannelModel } from '../video/video-channel'
+import { ActorFollowModel } from './actor-follow'
 
 enum ScopeNames {
   FULL = 'FULL'
@@ -61,7 +62,6 @@ export const unusedActorAttributesForAPI = [
   'sharedInboxUrl',
   'followersUrl',
   'followingUrl',
-  'url',
   'createdAt',
   'updatedAt'
 ]
@@ -73,7 +73,8 @@ export const unusedActorAttributesForAPI = [
       required: false
     },
     {
-      model: AvatarModel,
+      model: ActorImageModel,
+      as: 'Avatar',
       required: false
     }
   ]
@@ -100,7 +101,8 @@ export const unusedActorAttributesForAPI = [
         required: false
       },
       {
-        model: AvatarModel,
+        model: ActorImageModel,
+        as: 'Avatar',
         required: false
       }
     ]
@@ -122,13 +124,13 @@ export const unusedActorAttributesForAPI = [
         }
       }
     },
-    // {
-    //   fields: [ 'preferredUsername' ],
-    //   unique: true,
-    //   where: {
-    //     serverId: null
-    //   }
-    // },
+    {
+      fields: [ 'preferredUsername' ],
+      unique: true,
+      where: {
+        serverId: null
+      }
+    },
     {
       fields: [ 'inboxUrl', 'sharedInboxUrl' ]
     },
@@ -146,7 +148,7 @@ export const unusedActorAttributesForAPI = [
     }
   ]
 })
-export class ActorModel extends Model<ActorModel> {
+export class ActorModel extends Model {
 
   @AllowNull(false)
   @Column(DataType.ENUM(...values(ACTIVITY_PUB_ACTOR_TYPES)))
@@ -213,18 +215,35 @@ export class ActorModel extends Model<ActorModel> {
   @UpdatedAt
   updatedAt: Date
 
-  @ForeignKey(() => AvatarModel)
+  @ForeignKey(() => ActorImageModel)
   @Column
   avatarId: number
 
-  @BelongsTo(() => AvatarModel, {
+  @ForeignKey(() => ActorImageModel)
+  @Column
+  bannerId: number
+
+  @BelongsTo(() => ActorImageModel, {
     foreignKey: {
+      name: 'avatarId',
       allowNull: true
     },
+    as: 'Avatar',
     onDelete: 'set null',
     hooks: true
   })
-  Avatar: AvatarModel
+  Avatar: ActorImageModel
+
+  @BelongsTo(() => ActorImageModel, {
+    foreignKey: {
+      name: 'bannerId',
+      allowNull: true
+    },
+    as: 'Banner',
+    onDelete: 'set null',
+    hooks: true
+  })
+  Banner: ActorImageModel
 
   @HasMany(() => ActorFollowModel, {
     foreignKey: {
@@ -276,17 +295,15 @@ export class ActorModel extends Model<ActorModel> {
   })
   VideoChannel: VideoChannelModel
 
-  private static cache: { [ id: string ]: any } = {}
-
-  static load (id: number): Bluebird<MActor> {
+  static load (id: number): Promise<MActor> {
     return ActorModel.unscoped().findByPk(id)
   }
 
-  static loadFull (id: number): Bluebird<MActorFull> {
+  static loadFull (id: number): Promise<MActorFull> {
     return ActorModel.scope(ScopeNames.FULL).findByPk(id)
   }
 
-  static loadFromAccountByVideoId (videoId: number, transaction: Transaction): Bluebird<MActor> {
+  static loadFromAccountByVideoId (videoId: number, transaction: Transaction): Promise<MActor> {
     const query = {
       include: [
         {
@@ -330,11 +347,11 @@ export class ActorModel extends Model<ActorModel> {
       .then(a => !!a)
   }
 
-  static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Bluebird<MActorFull[]> {
+  static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Promise<MActorFull[]> {
     const query = {
       where: {
         followersUrl: {
-          [ Op.in ]: followersUrls
+          [Op.in]: followersUrls
         }
       },
       transaction
@@ -343,32 +360,54 @@ export class ActorModel extends Model<ActorModel> {
     return ActorModel.scope(ScopeNames.FULL).findAll(query)
   }
 
-  static loadLocalByName (preferredUsername: string, transaction?: Transaction): Bluebird<MActorFull> {
-    // The server actor never change, so we can easily cache it
-    if (preferredUsername === SERVER_ACTOR_NAME && ActorModel.cache[preferredUsername]) {
-      return Bluebird.resolve(ActorModel.cache[preferredUsername])
-    }
+  static loadLocalByName (preferredUsername: string, transaction?: Transaction): Promise<MActorFull> {
+    const fun = () => {
+      const query = {
+        where: {
+          preferredUsername,
+          serverId: null
+        },
+        transaction
+      }
 
-    const query = {
-      where: {
-        preferredUsername,
-        serverId: null
-      },
-      transaction
+      return ActorModel.scope(ScopeNames.FULL)
+                       .findOne(query)
     }
 
-    return ActorModel.scope(ScopeNames.FULL)
-                     .findOne(query)
-                     .then(actor => {
-                       if (preferredUsername === SERVER_ACTOR_NAME) {
-                         ActorModel.cache[ preferredUsername ] = actor
-                       }
+    return ModelCache.Instance.doCache({
+      cacheType: 'local-actor-name',
+      key: preferredUsername,
+      // The server actor never change, so we can easily cache it
+      whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
+      fun
+    })
+  }
+
+  static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Promise<MActorUrl> {
+    const fun = () => {
+      const query = {
+        attributes: [ 'url' ],
+        where: {
+          preferredUsername,
+          serverId: null
+        },
+        transaction
+      }
+
+      return ActorModel.unscoped()
+                       .findOne(query)
+    }
 
-                       return actor
-                     })
+    return ModelCache.Instance.doCache({
+      cacheType: 'local-actor-name',
+      key: preferredUsername,
+      // The server actor never change, so we can easily cache it
+      whitelist: () => preferredUsername === SERVER_ACTOR_NAME,
+      fun
+    })
   }
 
-  static loadByNameAndHost (preferredUsername: string, host: string): Bluebird<MActorFull> {
+  static loadByNameAndHost (preferredUsername: string, host: string): Promise<MActorFull> {
     const query = {
       where: {
         preferredUsername
@@ -387,7 +426,7 @@ export class ActorModel extends Model<ActorModel> {
     return ActorModel.scope(ScopeNames.FULL).findOne(query)
   }
 
-  static loadByUrl (url: string, transaction?: Transaction): Bluebird<MActorAccountChannelId> {
+  static loadByUrl (url: string, transaction?: Transaction): Promise<MActorAccountChannelId> {
     const query = {
       where: {
         url
@@ -410,7 +449,7 @@ export class ActorModel extends Model<ActorModel> {
     return ActorModel.unscoped().findOne(query)
   }
 
-  static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Bluebird<MActorFull> {
+  static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Promise<MActorFull> {
     const query = {
       where: {
         url
@@ -421,13 +460,54 @@ export class ActorModel extends Model<ActorModel> {
     return ActorModel.scope(ScopeNames.FULL).findOne(query)
   }
 
-  static incrementFollows (id: number, column: 'followersCount' | 'followingCount', by: number) {
-    return ActorModel.increment(column, {
-      by,
-      where: {
-        id
-      }
-    })
+  static rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) {
+    const sanitizedOfId = parseInt(ofId + '', 10)
+    const where = { id: sanitizedOfId }
+
+    let columnToUpdate: string
+    let columnOfCount: string
+
+    if (type === 'followers') {
+      columnToUpdate = 'followersCount'
+      columnOfCount = 'targetActorId'
+    } else {
+      columnToUpdate = 'followingCount'
+      columnOfCount = 'actorId'
+    }
+
+    return ActorModel.update({
+      [columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId})`)
+    }, { where, transaction })
+  }
+
+  static loadAccountActorByVideoId (videoId: number): Promise<MActor> {
+    const query = {
+      include: [
+        {
+          attributes: [ 'id' ],
+          model: AccountModel.unscoped(),
+          required: true,
+          include: [
+            {
+              attributes: [ 'id', 'accountId' ],
+              model: VideoChannelModel.unscoped(),
+              required: true,
+              include: [
+                {
+                  attributes: [ 'id', 'channelId' ],
+                  model: VideoModel.unscoped(),
+                  where: {
+                    id: videoId
+                  }
+                }
+              ]
+            }
+          ]
+        }
+      ]
+    }
+
+    return ActorModel.unscoped().findOne(query)
   }
 
   getSharedInbox (this: MActorWithInboxes) {
@@ -435,7 +515,7 @@ export class ActorModel extends Model<ActorModel> {
   }
 
   toFormattedSummaryJSON (this: MActorSummaryFormattable) {
-    let avatar: Avatar = null
+    let avatar: ActorImage = null
     if (this.Avatar) {
       avatar = this.Avatar.toFormattedJSON()
     }
@@ -462,9 +542,11 @@ export class ActorModel extends Model<ActorModel> {
   }
 
   toActivityPubObject (this: MActorAP, name: string) {
-    let icon = undefined
+    let icon: ActivityIconObject
+
     if (this.avatarId) {
       const extension = extname(this.Avatar.filename)
+
       icon = {
         type: 'Image',
         mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',