Avoid making retried requests to dead followers
[oweals/peertube.git] / server / models / activitypub / actor.ts
index ecaa43dcf1203d05a17f12714ea398253e8136f6..17f69f7a7aaa157caef66c60695211be230d0f48 100644 (file)
@@ -1,35 +1,19 @@
 import { values } from 'lodash'
-import { join } from 'path'
+import { extname } from 'path'
 import * as Sequelize from 'sequelize'
 import {
-  AllowNull,
-  BelongsTo,
-  Column,
-  CreatedAt,
-  DataType,
-  Default,
-  ForeignKey,
-  HasMany,
-  HasOne,
-  Is,
-  IsUUID,
-  Model,
-  Scopes,
-  Table,
-  UpdatedAt
+  AllowNull, BelongsTo, Column, CreatedAt, DataType, Default, DefaultScope, ForeignKey, HasMany, HasOne, Is, IsUUID, Model, Scopes,
+  Table, UpdatedAt
 } from 'sequelize-typescript'
 import { ActivityPubActorType } from '../../../shared/models/activitypub'
 import { Avatar } from '../../../shared/models/avatars/avatar.model'
-import { activityPubContextify } from '../../helpers'
+import { activityPubContextify } from '../../helpers/activitypub'
 import {
-  isActivityPubUrlValid,
-  isActorFollowersCountValid,
-  isActorFollowingCountValid,
-  isActorNameValid,
-  isActorPrivateKeyValid,
+  isActorFollowersCountValid, isActorFollowingCountValid, isActorPreferredUsernameValid, isActorPrivateKeyValid,
   isActorPublicKeyValid
-} from '../../helpers/custom-validators/activitypub'
-import { ACTIVITY_PUB_ACTOR_TYPES, AVATARS_DIR, CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
+} from '../../helpers/custom-validators/activitypub/actor'
+import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
+import { ACTIVITY_PUB, ACTIVITY_PUB_ACTOR_TYPES, CONFIG, CONSTRAINTS_FIELDS } from '../../initializers'
 import { AccountModel } from '../account/account'
 import { AvatarModel } from '../avatar/avatar'
 import { ServerModel } from '../server/server'
@@ -41,15 +25,35 @@ enum ScopeNames {
   FULL = 'FULL'
 }
 
+@DefaultScope({
+  include: [
+    {
+      model: () => ServerModel,
+      required: false
+    },
+    {
+      model: () => AvatarModel,
+      required: false
+    }
+  ]
+})
 @Scopes({
   [ScopeNames.FULL]: {
     include: [
       {
-        model: () => AccountModel,
+        model: () => AccountModel.unscoped(),
+        required: false
+      },
+      {
+        model: () => VideoChannelModel.unscoped(),
+        required: false
+      },
+      {
+        model: () => ServerModel,
         required: false
       },
       {
-        model: () => VideoChannelModel,
+        model: () => AvatarModel,
         required: false
       }
     ]
@@ -59,8 +63,14 @@ enum ScopeNames {
   tableName: 'actor',
   indexes: [
     {
-      fields: [ 'name', 'serverId' ],
+      fields: [ 'url' ]
+    },
+    {
+      fields: [ 'preferredUsername', 'serverId' ],
       unique: true
+    },
+    {
+      fields: [ 'inboxUrl', 'sharedInboxUrl' ]
     }
   ]
 })
@@ -77,23 +87,23 @@ export class ActorModel extends Model<ActorModel> {
   uuid: string
 
   @AllowNull(false)
-  @Is('ActorName', value => throwIfNotValid(value, isActorNameValid, 'actor name'))
+  @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username'))
   @Column
-  name: string
+  preferredUsername: string
 
   @AllowNull(false)
   @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
   url: string
 
   @AllowNull(true)
   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.PUBLIC_KEY.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max))
   publicKey: string
 
   @AllowNull(true)
   @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.PRIVATE_KEY.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max))
   privateKey: string
 
   @AllowNull(false)
@@ -108,27 +118,27 @@ export class ActorModel extends Model<ActorModel> {
 
   @AllowNull(false)
   @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
   inboxUrl: string
 
   @AllowNull(false)
   @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
   outboxUrl: string
 
   @AllowNull(false)
   @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
   sharedInboxUrl: string
 
   @AllowNull(false)
   @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
   followersUrl: string
 
   @AllowNull(false)
   @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url'))
-  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTOR.URL.max))
+  @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max))
   followingUrl: string
 
   @CreatedAt
@@ -145,7 +155,7 @@ export class ActorModel extends Model<ActorModel> {
     foreignKey: {
       allowNull: true
     },
-    onDelete: 'cascade'
+    onDelete: 'set null'
   })
   Avatar: AvatarModel
 
@@ -197,17 +207,7 @@ export class ActorModel extends Model<ActorModel> {
   VideoChannel: VideoChannelModel
 
   static load (id: number) {
-    return ActorModel.scope(ScopeNames.FULL).findById(id)
-  }
-
-  static loadByUUID (uuid: string) {
-    const query = {
-      where: {
-        uuid
-      }
-    }
-
-    return ActorModel.scope(ScopeNames.FULL).findOne(query)
+    return ActorModel.unscoped().findById(id)
   }
 
   static listByFollowersUrls (followersUrls: string[], transaction?: Sequelize.Transaction) {
@@ -223,10 +223,10 @@ export class ActorModel extends Model<ActorModel> {
     return ActorModel.scope(ScopeNames.FULL).findAll(query)
   }
 
-  static loadLocalByName (name: string) {
+  static loadLocalByName (preferredUsername: string) {
     const query = {
       where: {
-        name,
+        preferredUsername,
         serverId: null
       }
     }
@@ -234,10 +234,10 @@ export class ActorModel extends Model<ActorModel> {
     return ActorModel.scope(ScopeNames.FULL).findOne(query)
   }
 
-  static loadByNameAndHost (name: string, host: string) {
+  static loadByNameAndHost (preferredUsername: string, host: string) {
     const query = {
       where: {
-        name
+        preferredUsername
       },
       include: [
         {
@@ -267,32 +267,24 @@ export class ActorModel extends Model<ActorModel> {
   toFormattedJSON () {
     let avatar: Avatar = null
     if (this.Avatar) {
-      avatar = {
-        path: join(AVATARS_DIR.ACCOUNT, this.Avatar.filename),
-        createdAt: this.Avatar.createdAt,
-        updatedAt: this.Avatar.updatedAt
-      }
-    }
-
-    let host = CONFIG.WEBSERVER.HOST
-    let score: number
-    if (this.Server) {
-      host = this.Server.host
-      score = this.Server.score
+      avatar = this.Avatar.toFormattedJSON()
     }
 
     return {
       id: this.id,
+      url: this.url,
       uuid: this.uuid,
-      host,
-      score,
+      name: this.preferredUsername,
+      host: this.getHost(),
       followingCount: this.followingCount,
       followersCount: this.followersCount,
-      avatar
+      avatar,
+      createdAt: this.createdAt,
+      updatedAt: this.updatedAt
     }
   }
 
-  toActivityPubObject (preferredUsername: string, type: 'Account' | 'Application' | 'VideoChannel') {
+  toActivityPubObject (name: string, type: 'Account' | 'Application' | 'VideoChannel') {
     let activityPubType
     if (type === 'Account') {
       activityPubType = 'Person' as 'Person'
@@ -302,6 +294,16 @@ export class ActorModel extends Model<ActorModel> {
       activityPubType = 'Group' as 'Group'
     }
 
+    let icon = undefined
+    if (this.avatarId) {
+      const extension = extname(this.Avatar.filename)
+      icon = {
+        type: 'Image',
+        mediaType: extension === '.png' ? 'image/png' : 'image/jpeg',
+        url: this.getAvatarUrl()
+      }
+    }
+
     const json = {
       type: activityPubType,
       id: this.url,
@@ -309,9 +311,9 @@ export class ActorModel extends Model<ActorModel> {
       followers: this.getFollowersUrl(),
       inbox: this.inboxUrl,
       outbox: this.outboxUrl,
-      preferredUsername,
+      preferredUsername: this.preferredUsername,
       url: this.url,
-      name: this.name,
+      name,
       endpoints: {
         sharedInbox: this.sharedInboxUrl
       },
@@ -320,7 +322,8 @@ export class ActorModel extends Model<ActorModel> {
         id: this.getPublicKeyUrl(),
         owner: this.url,
         publicKeyPem: this.publicKey
-      }
+      },
+      icon
     }
 
     return activityPubContextify(json)
@@ -361,4 +364,29 @@ export class ActorModel extends Model<ActorModel> {
   isOwned () {
     return this.serverId === null
   }
+
+  getWebfingerUrl () {
+    return 'acct:' + this.preferredUsername + '@' + this.getHost()
+  }
+
+  getHost () {
+    return this.Server ? this.Server.host : CONFIG.WEBSERVER.HOST
+  }
+
+  getAvatarUrl () {
+    if (!this.avatarId) return undefined
+
+    return CONFIG.WEBSERVER.URL + this.Avatar.getWebserverPath()
+  }
+
+  isOutdated () {
+    if (this.isOwned()) return false
+
+    const now = Date.now()
+    const createdAtTime = this.createdAt.getTime()
+    const updatedAtTime = this.updatedAt.getTime()
+
+    return (now - createdAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL &&
+      (now - updatedAtTime) > ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL
+  }
 }