diff options
Diffstat (limited to 'server/models/actor')
-rw-r--r-- | server/models/actor/actor-follow.ts | 722 | ||||
-rw-r--r-- | server/models/actor/actor-image.ts | 101 | ||||
-rw-r--r-- | server/models/actor/actor.ts | 700 |
3 files changed, 1523 insertions, 0 deletions
diff --git a/server/models/actor/actor-follow.ts b/server/models/actor/actor-follow.ts new file mode 100644 index 000000000..3a09e51d6 --- /dev/null +++ b/server/models/actor/actor-follow.ts | |||
@@ -0,0 +1,722 @@ | |||
1 | import { difference, values } from 'lodash' | ||
2 | import { IncludeOptions, Op, QueryTypes, Transaction, WhereOptions } from 'sequelize' | ||
3 | import { | ||
4 | AfterCreate, | ||
5 | AfterDestroy, | ||
6 | AfterUpdate, | ||
7 | AllowNull, | ||
8 | BelongsTo, | ||
9 | Column, | ||
10 | CreatedAt, | ||
11 | DataType, | ||
12 | Default, | ||
13 | ForeignKey, | ||
14 | Is, | ||
15 | IsInt, | ||
16 | Max, | ||
17 | Model, | ||
18 | Table, | ||
19 | UpdatedAt | ||
20 | } from 'sequelize-typescript' | ||
21 | import { isActivityPubUrlValid } from '@server/helpers/custom-validators/activitypub/misc' | ||
22 | import { getServerActor } from '@server/models/application/application' | ||
23 | import { VideoModel } from '@server/models/video/video' | ||
24 | import { | ||
25 | MActorFollowActorsDefault, | ||
26 | MActorFollowActorsDefaultSubscription, | ||
27 | MActorFollowFollowingHost, | ||
28 | MActorFollowFormattable, | ||
29 | MActorFollowSubscriptions | ||
30 | } from '@server/types/models' | ||
31 | import { AttributesOnly } from '@shared/core-utils' | ||
32 | import { ActivityPubActorType } from '@shared/models' | ||
33 | import { FollowState } from '../../../shared/models/actors' | ||
34 | import { ActorFollow } from '../../../shared/models/actors/follow.model' | ||
35 | import { logger } from '../../helpers/logger' | ||
36 | import { ACTOR_FOLLOW_SCORE, CONSTRAINTS_FIELDS, FOLLOW_STATES, SERVER_ACTOR_NAME } from '../../initializers/constants' | ||
37 | import { AccountModel } from '../account/account' | ||
38 | import { ServerModel } from '../server/server' | ||
39 | import { createSafeIn, getFollowsSort, getSort, searchAttribute, throwIfNotValid } from '../utils' | ||
40 | import { VideoChannelModel } from '../video/video-channel' | ||
41 | import { ActorModel, unusedActorAttributesForAPI } from './actor' | ||
42 | |||
43 | @Table({ | ||
44 | tableName: 'actorFollow', | ||
45 | indexes: [ | ||
46 | { | ||
47 | fields: [ 'actorId' ] | ||
48 | }, | ||
49 | { | ||
50 | fields: [ 'targetActorId' ] | ||
51 | }, | ||
52 | { | ||
53 | fields: [ 'actorId', 'targetActorId' ], | ||
54 | unique: true | ||
55 | }, | ||
56 | { | ||
57 | fields: [ 'score' ] | ||
58 | }, | ||
59 | { | ||
60 | fields: [ 'url' ], | ||
61 | unique: true | ||
62 | } | ||
63 | ] | ||
64 | }) | ||
65 | export class ActorFollowModel extends Model<Partial<AttributesOnly<ActorFollowModel>>> { | ||
66 | |||
67 | @AllowNull(false) | ||
68 | @Column(DataType.ENUM(...values(FOLLOW_STATES))) | ||
69 | state: FollowState | ||
70 | |||
71 | @AllowNull(false) | ||
72 | @Default(ACTOR_FOLLOW_SCORE.BASE) | ||
73 | @IsInt | ||
74 | @Max(ACTOR_FOLLOW_SCORE.MAX) | ||
75 | @Column | ||
76 | score: number | ||
77 | |||
78 | // Allow null because we added this column in PeerTube v3, and don't want to generate fake URLs of remote follows | ||
79 | @AllowNull(true) | ||
80 | @Is('ActorFollowUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | ||
81 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.COMMONS.URL.max)) | ||
82 | url: string | ||
83 | |||
84 | @CreatedAt | ||
85 | createdAt: Date | ||
86 | |||
87 | @UpdatedAt | ||
88 | updatedAt: Date | ||
89 | |||
90 | @ForeignKey(() => ActorModel) | ||
91 | @Column | ||
92 | actorId: number | ||
93 | |||
94 | @BelongsTo(() => ActorModel, { | ||
95 | foreignKey: { | ||
96 | name: 'actorId', | ||
97 | allowNull: false | ||
98 | }, | ||
99 | as: 'ActorFollower', | ||
100 | onDelete: 'CASCADE' | ||
101 | }) | ||
102 | ActorFollower: ActorModel | ||
103 | |||
104 | @ForeignKey(() => ActorModel) | ||
105 | @Column | ||
106 | targetActorId: number | ||
107 | |||
108 | @BelongsTo(() => ActorModel, { | ||
109 | foreignKey: { | ||
110 | name: 'targetActorId', | ||
111 | allowNull: false | ||
112 | }, | ||
113 | as: 'ActorFollowing', | ||
114 | onDelete: 'CASCADE' | ||
115 | }) | ||
116 | ActorFollowing: ActorModel | ||
117 | |||
118 | @AfterCreate | ||
119 | @AfterUpdate | ||
120 | static incrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) { | ||
121 | if (instance.state !== 'accepted') return undefined | ||
122 | |||
123 | return Promise.all([ | ||
124 | ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction), | ||
125 | ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction) | ||
126 | ]) | ||
127 | } | ||
128 | |||
129 | @AfterDestroy | ||
130 | static decrementFollowerAndFollowingCount (instance: ActorFollowModel, options: any) { | ||
131 | return Promise.all([ | ||
132 | ActorModel.rebuildFollowsCount(instance.actorId, 'following', options.transaction), | ||
133 | ActorModel.rebuildFollowsCount(instance.targetActorId, 'followers', options.transaction) | ||
134 | ]) | ||
135 | } | ||
136 | |||
137 | static removeFollowsOf (actorId: number, t?: Transaction) { | ||
138 | const query = { | ||
139 | where: { | ||
140 | [Op.or]: [ | ||
141 | { | ||
142 | actorId | ||
143 | }, | ||
144 | { | ||
145 | targetActorId: actorId | ||
146 | } | ||
147 | ] | ||
148 | }, | ||
149 | transaction: t | ||
150 | } | ||
151 | |||
152 | return ActorFollowModel.destroy(query) | ||
153 | } | ||
154 | |||
155 | // Remove actor follows with a score of 0 (too many requests where they were unreachable) | ||
156 | static async removeBadActorFollows () { | ||
157 | const actorFollows = await ActorFollowModel.listBadActorFollows() | ||
158 | |||
159 | const actorFollowsRemovePromises = actorFollows.map(actorFollow => actorFollow.destroy()) | ||
160 | await Promise.all(actorFollowsRemovePromises) | ||
161 | |||
162 | const numberOfActorFollowsRemoved = actorFollows.length | ||
163 | |||
164 | if (numberOfActorFollowsRemoved) logger.info('Removed bad %d actor follows.', numberOfActorFollowsRemoved) | ||
165 | } | ||
166 | |||
167 | static isFollowedBy (actorId: number, followerActorId: number) { | ||
168 | const query = 'SELECT 1 FROM "actorFollow" WHERE "actorId" = $followerActorId AND "targetActorId" = $actorId LIMIT 1' | ||
169 | const options = { | ||
170 | type: QueryTypes.SELECT as QueryTypes.SELECT, | ||
171 | bind: { actorId, followerActorId }, | ||
172 | raw: true | ||
173 | } | ||
174 | |||
175 | return VideoModel.sequelize.query(query, options) | ||
176 | .then(results => results.length === 1) | ||
177 | } | ||
178 | |||
179 | static loadByActorAndTarget (actorId: number, targetActorId: number, t?: Transaction): Promise<MActorFollowActorsDefault> { | ||
180 | const query = { | ||
181 | where: { | ||
182 | actorId, | ||
183 | targetActorId: targetActorId | ||
184 | }, | ||
185 | include: [ | ||
186 | { | ||
187 | model: ActorModel, | ||
188 | required: true, | ||
189 | as: 'ActorFollower' | ||
190 | }, | ||
191 | { | ||
192 | model: ActorModel, | ||
193 | required: true, | ||
194 | as: 'ActorFollowing' | ||
195 | } | ||
196 | ], | ||
197 | transaction: t | ||
198 | } | ||
199 | |||
200 | return ActorFollowModel.findOne(query) | ||
201 | } | ||
202 | |||
203 | static loadByActorAndTargetNameAndHostForAPI ( | ||
204 | actorId: number, | ||
205 | targetName: string, | ||
206 | targetHost: string, | ||
207 | t?: Transaction | ||
208 | ): Promise<MActorFollowActorsDefaultSubscription> { | ||
209 | const actorFollowingPartInclude: IncludeOptions = { | ||
210 | model: ActorModel, | ||
211 | required: true, | ||
212 | as: 'ActorFollowing', | ||
213 | where: { | ||
214 | preferredUsername: targetName | ||
215 | }, | ||
216 | include: [ | ||
217 | { | ||
218 | model: VideoChannelModel.unscoped(), | ||
219 | required: false | ||
220 | } | ||
221 | ] | ||
222 | } | ||
223 | |||
224 | if (targetHost === null) { | ||
225 | actorFollowingPartInclude.where['serverId'] = null | ||
226 | } else { | ||
227 | actorFollowingPartInclude.include.push({ | ||
228 | model: ServerModel, | ||
229 | required: true, | ||
230 | where: { | ||
231 | host: targetHost | ||
232 | } | ||
233 | }) | ||
234 | } | ||
235 | |||
236 | const query = { | ||
237 | where: { | ||
238 | actorId | ||
239 | }, | ||
240 | include: [ | ||
241 | actorFollowingPartInclude, | ||
242 | { | ||
243 | model: ActorModel, | ||
244 | required: true, | ||
245 | as: 'ActorFollower' | ||
246 | } | ||
247 | ], | ||
248 | transaction: t | ||
249 | } | ||
250 | |||
251 | return ActorFollowModel.findOne(query) | ||
252 | } | ||
253 | |||
254 | static listSubscribedIn (actorId: number, targets: { name: string, host?: string }[]): Promise<MActorFollowFollowingHost[]> { | ||
255 | const whereTab = targets | ||
256 | .map(t => { | ||
257 | if (t.host) { | ||
258 | return { | ||
259 | [Op.and]: [ | ||
260 | { | ||
261 | $preferredUsername$: t.name | ||
262 | }, | ||
263 | { | ||
264 | $host$: t.host | ||
265 | } | ||
266 | ] | ||
267 | } | ||
268 | } | ||
269 | |||
270 | return { | ||
271 | [Op.and]: [ | ||
272 | { | ||
273 | $preferredUsername$: t.name | ||
274 | }, | ||
275 | { | ||
276 | $serverId$: null | ||
277 | } | ||
278 | ] | ||
279 | } | ||
280 | }) | ||
281 | |||
282 | const query = { | ||
283 | attributes: [ 'id' ], | ||
284 | where: { | ||
285 | [Op.and]: [ | ||
286 | { | ||
287 | [Op.or]: whereTab | ||
288 | }, | ||
289 | { | ||
290 | actorId | ||
291 | } | ||
292 | ] | ||
293 | }, | ||
294 | include: [ | ||
295 | { | ||
296 | attributes: [ 'preferredUsername' ], | ||
297 | model: ActorModel.unscoped(), | ||
298 | required: true, | ||
299 | as: 'ActorFollowing', | ||
300 | include: [ | ||
301 | { | ||
302 | attributes: [ 'host' ], | ||
303 | model: ServerModel.unscoped(), | ||
304 | required: false | ||
305 | } | ||
306 | ] | ||
307 | } | ||
308 | ] | ||
309 | } | ||
310 | |||
311 | return ActorFollowModel.findAll(query) | ||
312 | } | ||
313 | |||
314 | static listFollowingForApi (options: { | ||
315 | id: number | ||
316 | start: number | ||
317 | count: number | ||
318 | sort: string | ||
319 | state?: FollowState | ||
320 | actorType?: ActivityPubActorType | ||
321 | search?: string | ||
322 | }) { | ||
323 | const { id, start, count, sort, search, state, actorType } = options | ||
324 | |||
325 | const followWhere = state ? { state } : {} | ||
326 | const followingWhere: WhereOptions = {} | ||
327 | const followingServerWhere: WhereOptions = {} | ||
328 | |||
329 | if (search) { | ||
330 | Object.assign(followingServerWhere, { | ||
331 | host: { | ||
332 | [Op.iLike]: '%' + search + '%' | ||
333 | } | ||
334 | }) | ||
335 | } | ||
336 | |||
337 | if (actorType) { | ||
338 | Object.assign(followingWhere, { type: actorType }) | ||
339 | } | ||
340 | |||
341 | const query = { | ||
342 | distinct: true, | ||
343 | offset: start, | ||
344 | limit: count, | ||
345 | order: getFollowsSort(sort), | ||
346 | where: followWhere, | ||
347 | include: [ | ||
348 | { | ||
349 | model: ActorModel, | ||
350 | required: true, | ||
351 | as: 'ActorFollower', | ||
352 | where: { | ||
353 | id | ||
354 | } | ||
355 | }, | ||
356 | { | ||
357 | model: ActorModel, | ||
358 | as: 'ActorFollowing', | ||
359 | required: true, | ||
360 | where: followingWhere, | ||
361 | include: [ | ||
362 | { | ||
363 | model: ServerModel, | ||
364 | required: true, | ||
365 | where: followingServerWhere | ||
366 | } | ||
367 | ] | ||
368 | } | ||
369 | ] | ||
370 | } | ||
371 | |||
372 | return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query) | ||
373 | .then(({ rows, count }) => { | ||
374 | return { | ||
375 | data: rows, | ||
376 | total: count | ||
377 | } | ||
378 | }) | ||
379 | } | ||
380 | |||
381 | static listFollowersForApi (options: { | ||
382 | actorId: number | ||
383 | start: number | ||
384 | count: number | ||
385 | sort: string | ||
386 | state?: FollowState | ||
387 | actorType?: ActivityPubActorType | ||
388 | search?: string | ||
389 | }) { | ||
390 | const { actorId, start, count, sort, search, state, actorType } = options | ||
391 | |||
392 | const followWhere = state ? { state } : {} | ||
393 | const followerWhere: WhereOptions = {} | ||
394 | const followerServerWhere: WhereOptions = {} | ||
395 | |||
396 | if (search) { | ||
397 | Object.assign(followerServerWhere, { | ||
398 | host: { | ||
399 | [Op.iLike]: '%' + search + '%' | ||
400 | } | ||
401 | }) | ||
402 | } | ||
403 | |||
404 | if (actorType) { | ||
405 | Object.assign(followerWhere, { type: actorType }) | ||
406 | } | ||
407 | |||
408 | const query = { | ||
409 | distinct: true, | ||
410 | offset: start, | ||
411 | limit: count, | ||
412 | order: getFollowsSort(sort), | ||
413 | where: followWhere, | ||
414 | include: [ | ||
415 | { | ||
416 | model: ActorModel, | ||
417 | required: true, | ||
418 | as: 'ActorFollower', | ||
419 | where: followerWhere, | ||
420 | include: [ | ||
421 | { | ||
422 | model: ServerModel, | ||
423 | required: true, | ||
424 | where: followerServerWhere | ||
425 | } | ||
426 | ] | ||
427 | }, | ||
428 | { | ||
429 | model: ActorModel, | ||
430 | as: 'ActorFollowing', | ||
431 | required: true, | ||
432 | where: { | ||
433 | id: actorId | ||
434 | } | ||
435 | } | ||
436 | ] | ||
437 | } | ||
438 | |||
439 | return ActorFollowModel.findAndCountAll<MActorFollowActorsDefault>(query) | ||
440 | .then(({ rows, count }) => { | ||
441 | return { | ||
442 | data: rows, | ||
443 | total: count | ||
444 | } | ||
445 | }) | ||
446 | } | ||
447 | |||
448 | static listSubscriptionsForApi (options: { | ||
449 | actorId: number | ||
450 | start: number | ||
451 | count: number | ||
452 | sort: string | ||
453 | search?: string | ||
454 | }) { | ||
455 | const { actorId, start, count, sort } = options | ||
456 | const where = { | ||
457 | actorId: actorId | ||
458 | } | ||
459 | |||
460 | if (options.search) { | ||
461 | Object.assign(where, { | ||
462 | [Op.or]: [ | ||
463 | searchAttribute(options.search, '$ActorFollowing.preferredUsername$'), | ||
464 | searchAttribute(options.search, '$ActorFollowing.VideoChannel.name$') | ||
465 | ] | ||
466 | }) | ||
467 | } | ||
468 | |||
469 | const query = { | ||
470 | attributes: [], | ||
471 | distinct: true, | ||
472 | offset: start, | ||
473 | limit: count, | ||
474 | order: getSort(sort), | ||
475 | where, | ||
476 | include: [ | ||
477 | { | ||
478 | attributes: [ 'id' ], | ||
479 | model: ActorModel.unscoped(), | ||
480 | as: 'ActorFollowing', | ||
481 | required: true, | ||
482 | include: [ | ||
483 | { | ||
484 | model: VideoChannelModel.unscoped(), | ||
485 | required: true, | ||
486 | include: [ | ||
487 | { | ||
488 | attributes: { | ||
489 | exclude: unusedActorAttributesForAPI | ||
490 | }, | ||
491 | model: ActorModel, | ||
492 | required: true | ||
493 | }, | ||
494 | { | ||
495 | model: AccountModel.unscoped(), | ||
496 | required: true, | ||
497 | include: [ | ||
498 | { | ||
499 | attributes: { | ||
500 | exclude: unusedActorAttributesForAPI | ||
501 | }, | ||
502 | model: ActorModel, | ||
503 | required: true | ||
504 | } | ||
505 | ] | ||
506 | } | ||
507 | ] | ||
508 | } | ||
509 | ] | ||
510 | } | ||
511 | ] | ||
512 | } | ||
513 | |||
514 | return ActorFollowModel.findAndCountAll<MActorFollowSubscriptions>(query) | ||
515 | .then(({ rows, count }) => { | ||
516 | return { | ||
517 | data: rows.map(r => r.ActorFollowing.VideoChannel), | ||
518 | total: count | ||
519 | } | ||
520 | }) | ||
521 | } | ||
522 | |||
523 | static async keepUnfollowedInstance (hosts: string[]) { | ||
524 | const followerId = (await getServerActor()).id | ||
525 | |||
526 | const query = { | ||
527 | attributes: [ 'id' ], | ||
528 | where: { | ||
529 | actorId: followerId | ||
530 | }, | ||
531 | include: [ | ||
532 | { | ||
533 | attributes: [ 'id' ], | ||
534 | model: ActorModel.unscoped(), | ||
535 | required: true, | ||
536 | as: 'ActorFollowing', | ||
537 | where: { | ||
538 | preferredUsername: SERVER_ACTOR_NAME | ||
539 | }, | ||
540 | include: [ | ||
541 | { | ||
542 | attributes: [ 'host' ], | ||
543 | model: ServerModel.unscoped(), | ||
544 | required: true, | ||
545 | where: { | ||
546 | host: { | ||
547 | [Op.in]: hosts | ||
548 | } | ||
549 | } | ||
550 | } | ||
551 | ] | ||
552 | } | ||
553 | ] | ||
554 | } | ||
555 | |||
556 | const res = await ActorFollowModel.findAll(query) | ||
557 | const followedHosts = res.map(row => row.ActorFollowing.Server.host) | ||
558 | |||
559 | return difference(hosts, followedHosts) | ||
560 | } | ||
561 | |||
562 | static listAcceptedFollowerUrlsForAP (actorIds: number[], t: Transaction, start?: number, count?: number) { | ||
563 | return ActorFollowModel.createListAcceptedFollowForApiQuery('followers', actorIds, t, start, count) | ||
564 | } | ||
565 | |||
566 | static listAcceptedFollowerSharedInboxUrls (actorIds: number[], t: Transaction) { | ||
567 | return ActorFollowModel.createListAcceptedFollowForApiQuery( | ||
568 | 'followers', | ||
569 | actorIds, | ||
570 | t, | ||
571 | undefined, | ||
572 | undefined, | ||
573 | 'sharedInboxUrl', | ||
574 | true | ||
575 | ) | ||
576 | } | ||
577 | |||
578 | static listAcceptedFollowingUrlsForApi (actorIds: number[], t: Transaction, start?: number, count?: number) { | ||
579 | return ActorFollowModel.createListAcceptedFollowForApiQuery('following', actorIds, t, start, count) | ||
580 | } | ||
581 | |||
582 | static async getStats () { | ||
583 | const serverActor = await getServerActor() | ||
584 | |||
585 | const totalInstanceFollowing = await ActorFollowModel.count({ | ||
586 | where: { | ||
587 | actorId: serverActor.id | ||
588 | } | ||
589 | }) | ||
590 | |||
591 | const totalInstanceFollowers = await ActorFollowModel.count({ | ||
592 | where: { | ||
593 | targetActorId: serverActor.id | ||
594 | } | ||
595 | }) | ||
596 | |||
597 | return { | ||
598 | totalInstanceFollowing, | ||
599 | totalInstanceFollowers | ||
600 | } | ||
601 | } | ||
602 | |||
603 | static updateScore (inboxUrl: string, value: number, t?: Transaction) { | ||
604 | const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` + | ||
605 | 'WHERE id IN (' + | ||
606 | 'SELECT "actorFollow"."id" FROM "actorFollow" ' + | ||
607 | 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."actorId" ' + | ||
608 | `WHERE "actor"."inboxUrl" = '${inboxUrl}' OR "actor"."sharedInboxUrl" = '${inboxUrl}'` + | ||
609 | ')' | ||
610 | |||
611 | const options = { | ||
612 | type: QueryTypes.BULKUPDATE, | ||
613 | transaction: t | ||
614 | } | ||
615 | |||
616 | return ActorFollowModel.sequelize.query(query, options) | ||
617 | } | ||
618 | |||
619 | static async updateScoreByFollowingServers (serverIds: number[], value: number, t?: Transaction) { | ||
620 | if (serverIds.length === 0) return | ||
621 | |||
622 | const me = await getServerActor() | ||
623 | const serverIdsString = createSafeIn(ActorFollowModel.sequelize, serverIds) | ||
624 | |||
625 | const query = `UPDATE "actorFollow" SET "score" = LEAST("score" + ${value}, ${ACTOR_FOLLOW_SCORE.MAX}) ` + | ||
626 | 'WHERE id IN (' + | ||
627 | 'SELECT "actorFollow"."id" FROM "actorFollow" ' + | ||
628 | 'INNER JOIN "actor" ON "actor"."id" = "actorFollow"."targetActorId" ' + | ||
629 | `WHERE "actorFollow"."actorId" = ${me.Account.actorId} ` + // I'm the follower | ||
630 | `AND "actor"."serverId" IN (${serverIdsString})` + // Criteria on followings | ||
631 | ')' | ||
632 | |||
633 | const options = { | ||
634 | type: QueryTypes.BULKUPDATE, | ||
635 | transaction: t | ||
636 | } | ||
637 | |||
638 | return ActorFollowModel.sequelize.query(query, options) | ||
639 | } | ||
640 | |||
641 | private static async createListAcceptedFollowForApiQuery ( | ||
642 | type: 'followers' | 'following', | ||
643 | actorIds: number[], | ||
644 | t: Transaction, | ||
645 | start?: number, | ||
646 | count?: number, | ||
647 | columnUrl = 'url', | ||
648 | distinct = false | ||
649 | ) { | ||
650 | let firstJoin: string | ||
651 | let secondJoin: string | ||
652 | |||
653 | if (type === 'followers') { | ||
654 | firstJoin = 'targetActorId' | ||
655 | secondJoin = 'actorId' | ||
656 | } else { | ||
657 | firstJoin = 'actorId' | ||
658 | secondJoin = 'targetActorId' | ||
659 | } | ||
660 | |||
661 | const selections: string[] = [] | ||
662 | if (distinct === true) selections.push(`DISTINCT("Follows"."${columnUrl}") AS "selectionUrl"`) | ||
663 | else selections.push(`"Follows"."${columnUrl}" AS "selectionUrl"`) | ||
664 | |||
665 | selections.push('COUNT(*) AS "total"') | ||
666 | |||
667 | const tasks: Promise<any>[] = [] | ||
668 | |||
669 | for (const selection of selections) { | ||
670 | let query = 'SELECT ' + selection + ' FROM "actor" ' + | ||
671 | 'INNER JOIN "actorFollow" ON "actorFollow"."' + firstJoin + '" = "actor"."id" ' + | ||
672 | 'INNER JOIN "actor" AS "Follows" ON "actorFollow"."' + secondJoin + '" = "Follows"."id" ' + | ||
673 | `WHERE "actor"."id" = ANY ($actorIds) AND "actorFollow"."state" = 'accepted' AND "Follows"."${columnUrl}" IS NOT NULL ` | ||
674 | |||
675 | if (count !== undefined) query += 'LIMIT ' + count | ||
676 | if (start !== undefined) query += ' OFFSET ' + start | ||
677 | |||
678 | const options = { | ||
679 | bind: { actorIds }, | ||
680 | type: QueryTypes.SELECT, | ||
681 | transaction: t | ||
682 | } | ||
683 | tasks.push(ActorFollowModel.sequelize.query(query, options)) | ||
684 | } | ||
685 | |||
686 | const [ followers, [ dataTotal ] ] = await Promise.all(tasks) | ||
687 | const urls: string[] = followers.map(f => f.selectionUrl) | ||
688 | |||
689 | return { | ||
690 | data: urls, | ||
691 | total: dataTotal ? parseInt(dataTotal.total, 10) : 0 | ||
692 | } | ||
693 | } | ||
694 | |||
695 | private static listBadActorFollows () { | ||
696 | const query = { | ||
697 | where: { | ||
698 | score: { | ||
699 | [Op.lte]: 0 | ||
700 | } | ||
701 | }, | ||
702 | logging: false | ||
703 | } | ||
704 | |||
705 | return ActorFollowModel.findAll(query) | ||
706 | } | ||
707 | |||
708 | toFormattedJSON (this: MActorFollowFormattable): ActorFollow { | ||
709 | const follower = this.ActorFollower.toFormattedJSON() | ||
710 | const following = this.ActorFollowing.toFormattedJSON() | ||
711 | |||
712 | return { | ||
713 | id: this.id, | ||
714 | follower, | ||
715 | following, | ||
716 | score: this.score, | ||
717 | state: this.state, | ||
718 | createdAt: this.createdAt, | ||
719 | updatedAt: this.updatedAt | ||
720 | } | ||
721 | } | ||
722 | } | ||
diff --git a/server/models/actor/actor-image.ts b/server/models/actor/actor-image.ts new file mode 100644 index 000000000..a35f9edb0 --- /dev/null +++ b/server/models/actor/actor-image.ts | |||
@@ -0,0 +1,101 @@ | |||
1 | import { remove } from 'fs-extra' | ||
2 | import { join } from 'path' | ||
3 | import { AfterDestroy, AllowNull, Column, CreatedAt, Default, Is, Model, Table, UpdatedAt } from 'sequelize-typescript' | ||
4 | import { MActorImageFormattable } from '@server/types/models' | ||
5 | import { AttributesOnly } from '@shared/core-utils' | ||
6 | import { ActorImageType } from '@shared/models' | ||
7 | import { ActorImage } from '../../../shared/models/actors/actor-image.model' | ||
8 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' | ||
9 | import { logger } from '../../helpers/logger' | ||
10 | import { CONFIG } from '../../initializers/config' | ||
11 | import { LAZY_STATIC_PATHS } from '../../initializers/constants' | ||
12 | import { throwIfNotValid } from '../utils' | ||
13 | |||
14 | @Table({ | ||
15 | tableName: 'actorImage', | ||
16 | indexes: [ | ||
17 | { | ||
18 | fields: [ 'filename' ], | ||
19 | unique: true | ||
20 | } | ||
21 | ] | ||
22 | }) | ||
23 | export class ActorImageModel extends Model<Partial<AttributesOnly<ActorImageModel>>> { | ||
24 | |||
25 | @AllowNull(false) | ||
26 | @Column | ||
27 | filename: string | ||
28 | |||
29 | @AllowNull(true) | ||
30 | @Default(null) | ||
31 | @Column | ||
32 | height: number | ||
33 | |||
34 | @AllowNull(true) | ||
35 | @Default(null) | ||
36 | @Column | ||
37 | width: number | ||
38 | |||
39 | @AllowNull(true) | ||
40 | @Is('ActorImageFileUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'fileUrl', true)) | ||
41 | @Column | ||
42 | fileUrl: string | ||
43 | |||
44 | @AllowNull(false) | ||
45 | @Column | ||
46 | onDisk: boolean | ||
47 | |||
48 | @AllowNull(false) | ||
49 | @Column | ||
50 | type: ActorImageType | ||
51 | |||
52 | @CreatedAt | ||
53 | createdAt: Date | ||
54 | |||
55 | @UpdatedAt | ||
56 | updatedAt: Date | ||
57 | |||
58 | @AfterDestroy | ||
59 | static removeFilesAndSendDelete (instance: ActorImageModel) { | ||
60 | logger.info('Removing actor image file %s.', instance.filename) | ||
61 | |||
62 | // Don't block the transaction | ||
63 | instance.removeImage() | ||
64 | .catch(err => logger.error('Cannot remove actor image file %s.', instance.filename, err)) | ||
65 | } | ||
66 | |||
67 | static loadByName (filename: string) { | ||
68 | const query = { | ||
69 | where: { | ||
70 | filename | ||
71 | } | ||
72 | } | ||
73 | |||
74 | return ActorImageModel.findOne(query) | ||
75 | } | ||
76 | |||
77 | toFormattedJSON (this: MActorImageFormattable): ActorImage { | ||
78 | return { | ||
79 | path: this.getStaticPath(), | ||
80 | createdAt: this.createdAt, | ||
81 | updatedAt: this.updatedAt | ||
82 | } | ||
83 | } | ||
84 | |||
85 | getStaticPath () { | ||
86 | if (this.type === ActorImageType.AVATAR) { | ||
87 | return join(LAZY_STATIC_PATHS.AVATARS, this.filename) | ||
88 | } | ||
89 | |||
90 | return join(LAZY_STATIC_PATHS.BANNERS, this.filename) | ||
91 | } | ||
92 | |||
93 | getPath () { | ||
94 | return join(CONFIG.STORAGE.ACTOR_IMAGES, this.filename) | ||
95 | } | ||
96 | |||
97 | removeImage () { | ||
98 | const imagePath = join(CONFIG.STORAGE.ACTOR_IMAGES, this.filename) | ||
99 | return remove(imagePath) | ||
100 | } | ||
101 | } | ||
diff --git a/server/models/actor/actor.ts b/server/models/actor/actor.ts new file mode 100644 index 000000000..65c53f8f8 --- /dev/null +++ b/server/models/actor/actor.ts | |||
@@ -0,0 +1,700 @@ | |||
1 | import { values } from 'lodash' | ||
2 | import { extname } from 'path' | ||
3 | import { literal, Op, Transaction } from 'sequelize' | ||
4 | import { | ||
5 | AllowNull, | ||
6 | BelongsTo, | ||
7 | Column, | ||
8 | CreatedAt, | ||
9 | DataType, | ||
10 | DefaultScope, | ||
11 | ForeignKey, | ||
12 | HasMany, | ||
13 | HasOne, | ||
14 | Is, | ||
15 | Model, | ||
16 | Scopes, | ||
17 | Table, | ||
18 | UpdatedAt | ||
19 | } from 'sequelize-typescript' | ||
20 | import { ModelCache } from '@server/models/model-cache' | ||
21 | import { AttributesOnly } from '@shared/core-utils' | ||
22 | import { ActivityIconObject, ActivityPubActorType } from '../../../shared/models/activitypub' | ||
23 | import { ActorImage } from '../../../shared/models/actors/actor-image.model' | ||
24 | import { activityPubContextify } from '../../helpers/activitypub' | ||
25 | import { | ||
26 | isActorFollowersCountValid, | ||
27 | isActorFollowingCountValid, | ||
28 | isActorPreferredUsernameValid, | ||
29 | isActorPrivateKeyValid, | ||
30 | isActorPublicKeyValid | ||
31 | } from '../../helpers/custom-validators/activitypub/actor' | ||
32 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' | ||
33 | import { | ||
34 | ACTIVITY_PUB, | ||
35 | ACTIVITY_PUB_ACTOR_TYPES, | ||
36 | CONSTRAINTS_FIELDS, | ||
37 | MIMETYPES, | ||
38 | SERVER_ACTOR_NAME, | ||
39 | WEBSERVER | ||
40 | } from '../../initializers/constants' | ||
41 | import { | ||
42 | MActor, | ||
43 | MActorAccountChannelId, | ||
44 | MActorAPAccount, | ||
45 | MActorAPChannel, | ||
46 | MActorFormattable, | ||
47 | MActorFull, | ||
48 | MActorHost, | ||
49 | MActorServer, | ||
50 | MActorSummaryFormattable, | ||
51 | MActorUrl, | ||
52 | MActorWithInboxes | ||
53 | } from '../../types/models' | ||
54 | import { AccountModel } from '../account/account' | ||
55 | import { ServerModel } from '../server/server' | ||
56 | import { isOutdated, throwIfNotValid } from '../utils' | ||
57 | import { VideoModel } from '../video/video' | ||
58 | import { VideoChannelModel } from '../video/video-channel' | ||
59 | import { ActorFollowModel } from './actor-follow' | ||
60 | import { ActorImageModel } from './actor-image' | ||
61 | |||
62 | enum ScopeNames { | ||
63 | FULL = 'FULL' | ||
64 | } | ||
65 | |||
66 | export const unusedActorAttributesForAPI = [ | ||
67 | 'publicKey', | ||
68 | 'privateKey', | ||
69 | 'inboxUrl', | ||
70 | 'outboxUrl', | ||
71 | 'sharedInboxUrl', | ||
72 | 'followersUrl', | ||
73 | 'followingUrl' | ||
74 | ] | ||
75 | |||
76 | @DefaultScope(() => ({ | ||
77 | include: [ | ||
78 | { | ||
79 | model: ServerModel, | ||
80 | required: false | ||
81 | }, | ||
82 | { | ||
83 | model: ActorImageModel, | ||
84 | as: 'Avatar', | ||
85 | required: false | ||
86 | } | ||
87 | ] | ||
88 | })) | ||
89 | @Scopes(() => ({ | ||
90 | [ScopeNames.FULL]: { | ||
91 | include: [ | ||
92 | { | ||
93 | model: AccountModel.unscoped(), | ||
94 | required: false | ||
95 | }, | ||
96 | { | ||
97 | model: VideoChannelModel.unscoped(), | ||
98 | required: false, | ||
99 | include: [ | ||
100 | { | ||
101 | model: AccountModel, | ||
102 | required: true | ||
103 | } | ||
104 | ] | ||
105 | }, | ||
106 | { | ||
107 | model: ServerModel, | ||
108 | required: false | ||
109 | }, | ||
110 | { | ||
111 | model: ActorImageModel, | ||
112 | as: 'Avatar', | ||
113 | required: false | ||
114 | }, | ||
115 | { | ||
116 | model: ActorImageModel, | ||
117 | as: 'Banner', | ||
118 | required: false | ||
119 | } | ||
120 | ] | ||
121 | } | ||
122 | })) | ||
123 | @Table({ | ||
124 | tableName: 'actor', | ||
125 | indexes: [ | ||
126 | { | ||
127 | fields: [ 'url' ], | ||
128 | unique: true | ||
129 | }, | ||
130 | { | ||
131 | fields: [ 'preferredUsername', 'serverId' ], | ||
132 | unique: true, | ||
133 | where: { | ||
134 | serverId: { | ||
135 | [Op.ne]: null | ||
136 | } | ||
137 | } | ||
138 | }, | ||
139 | { | ||
140 | fields: [ 'preferredUsername' ], | ||
141 | unique: true, | ||
142 | where: { | ||
143 | serverId: null | ||
144 | } | ||
145 | }, | ||
146 | { | ||
147 | fields: [ 'inboxUrl', 'sharedInboxUrl' ] | ||
148 | }, | ||
149 | { | ||
150 | fields: [ 'sharedInboxUrl' ] | ||
151 | }, | ||
152 | { | ||
153 | fields: [ 'serverId' ] | ||
154 | }, | ||
155 | { | ||
156 | fields: [ 'avatarId' ] | ||
157 | }, | ||
158 | { | ||
159 | fields: [ 'followersUrl' ] | ||
160 | } | ||
161 | ] | ||
162 | }) | ||
163 | export class ActorModel extends Model<Partial<AttributesOnly<ActorModel>>> { | ||
164 | |||
165 | @AllowNull(false) | ||
166 | @Column(DataType.ENUM(...values(ACTIVITY_PUB_ACTOR_TYPES))) | ||
167 | type: ActivityPubActorType | ||
168 | |||
169 | @AllowNull(false) | ||
170 | @Is('ActorPreferredUsername', value => throwIfNotValid(value, isActorPreferredUsernameValid, 'actor preferred username')) | ||
171 | @Column | ||
172 | preferredUsername: string | ||
173 | |||
174 | @AllowNull(false) | ||
175 | @Is('ActorUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | ||
176 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max)) | ||
177 | url: string | ||
178 | |||
179 | @AllowNull(true) | ||
180 | @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPublicKeyValid, 'public key', true)) | ||
181 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PUBLIC_KEY.max)) | ||
182 | publicKey: string | ||
183 | |||
184 | @AllowNull(true) | ||
185 | @Is('ActorPublicKey', value => throwIfNotValid(value, isActorPrivateKeyValid, 'private key', true)) | ||
186 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.PRIVATE_KEY.max)) | ||
187 | privateKey: string | ||
188 | |||
189 | @AllowNull(false) | ||
190 | @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowersCountValid, 'followers count')) | ||
191 | @Column | ||
192 | followersCount: number | ||
193 | |||
194 | @AllowNull(false) | ||
195 | @Is('ActorFollowersCount', value => throwIfNotValid(value, isActorFollowingCountValid, 'following count')) | ||
196 | @Column | ||
197 | followingCount: number | ||
198 | |||
199 | @AllowNull(false) | ||
200 | @Is('ActorInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'inbox url')) | ||
201 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max)) | ||
202 | inboxUrl: string | ||
203 | |||
204 | @AllowNull(true) | ||
205 | @Is('ActorOutboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'outbox url', true)) | ||
206 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max)) | ||
207 | outboxUrl: string | ||
208 | |||
209 | @AllowNull(true) | ||
210 | @Is('ActorSharedInboxUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'shared inbox url', true)) | ||
211 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max)) | ||
212 | sharedInboxUrl: string | ||
213 | |||
214 | @AllowNull(true) | ||
215 | @Is('ActorFollowersUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'followers url', true)) | ||
216 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max)) | ||
217 | followersUrl: string | ||
218 | |||
219 | @AllowNull(true) | ||
220 | @Is('ActorFollowingUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'following url', true)) | ||
221 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.ACTORS.URL.max)) | ||
222 | followingUrl: string | ||
223 | |||
224 | @AllowNull(true) | ||
225 | @Column | ||
226 | remoteCreatedAt: Date | ||
227 | |||
228 | @CreatedAt | ||
229 | createdAt: Date | ||
230 | |||
231 | @UpdatedAt | ||
232 | updatedAt: Date | ||
233 | |||
234 | @ForeignKey(() => ActorImageModel) | ||
235 | @Column | ||
236 | avatarId: number | ||
237 | |||
238 | @ForeignKey(() => ActorImageModel) | ||
239 | @Column | ||
240 | bannerId: number | ||
241 | |||
242 | @BelongsTo(() => ActorImageModel, { | ||
243 | foreignKey: { | ||
244 | name: 'avatarId', | ||
245 | allowNull: true | ||
246 | }, | ||
247 | as: 'Avatar', | ||
248 | onDelete: 'set null', | ||
249 | hooks: true | ||
250 | }) | ||
251 | Avatar: ActorImageModel | ||
252 | |||
253 | @BelongsTo(() => ActorImageModel, { | ||
254 | foreignKey: { | ||
255 | name: 'bannerId', | ||
256 | allowNull: true | ||
257 | }, | ||
258 | as: 'Banner', | ||
259 | onDelete: 'set null', | ||
260 | hooks: true | ||
261 | }) | ||
262 | Banner: ActorImageModel | ||
263 | |||
264 | @HasMany(() => ActorFollowModel, { | ||
265 | foreignKey: { | ||
266 | name: 'actorId', | ||
267 | allowNull: false | ||
268 | }, | ||
269 | as: 'ActorFollowings', | ||
270 | onDelete: 'cascade' | ||
271 | }) | ||
272 | ActorFollowing: ActorFollowModel[] | ||
273 | |||
274 | @HasMany(() => ActorFollowModel, { | ||
275 | foreignKey: { | ||
276 | name: 'targetActorId', | ||
277 | allowNull: false | ||
278 | }, | ||
279 | as: 'ActorFollowers', | ||
280 | onDelete: 'cascade' | ||
281 | }) | ||
282 | ActorFollowers: ActorFollowModel[] | ||
283 | |||
284 | @ForeignKey(() => ServerModel) | ||
285 | @Column | ||
286 | serverId: number | ||
287 | |||
288 | @BelongsTo(() => ServerModel, { | ||
289 | foreignKey: { | ||
290 | allowNull: true | ||
291 | }, | ||
292 | onDelete: 'cascade' | ||
293 | }) | ||
294 | Server: ServerModel | ||
295 | |||
296 | @HasOne(() => AccountModel, { | ||
297 | foreignKey: { | ||
298 | allowNull: true | ||
299 | }, | ||
300 | onDelete: 'cascade', | ||
301 | hooks: true | ||
302 | }) | ||
303 | Account: AccountModel | ||
304 | |||
305 | @HasOne(() => VideoChannelModel, { | ||
306 | foreignKey: { | ||
307 | allowNull: true | ||
308 | }, | ||
309 | onDelete: 'cascade', | ||
310 | hooks: true | ||
311 | }) | ||
312 | VideoChannel: VideoChannelModel | ||
313 | |||
314 | static load (id: number): Promise<MActor> { | ||
315 | return ActorModel.unscoped().findByPk(id) | ||
316 | } | ||
317 | |||
318 | static loadFull (id: number): Promise<MActorFull> { | ||
319 | return ActorModel.scope(ScopeNames.FULL).findByPk(id) | ||
320 | } | ||
321 | |||
322 | static loadFromAccountByVideoId (videoId: number, transaction: Transaction): Promise<MActor> { | ||
323 | const query = { | ||
324 | include: [ | ||
325 | { | ||
326 | attributes: [ 'id' ], | ||
327 | model: AccountModel.unscoped(), | ||
328 | required: true, | ||
329 | include: [ | ||
330 | { | ||
331 | attributes: [ 'id' ], | ||
332 | model: VideoChannelModel.unscoped(), | ||
333 | required: true, | ||
334 | include: [ | ||
335 | { | ||
336 | attributes: [ 'id' ], | ||
337 | model: VideoModel.unscoped(), | ||
338 | required: true, | ||
339 | where: { | ||
340 | id: videoId | ||
341 | } | ||
342 | } | ||
343 | ] | ||
344 | } | ||
345 | ] | ||
346 | } | ||
347 | ], | ||
348 | transaction | ||
349 | } | ||
350 | |||
351 | return ActorModel.unscoped().findOne(query) | ||
352 | } | ||
353 | |||
354 | static isActorUrlExist (url: string) { | ||
355 | const query = { | ||
356 | raw: true, | ||
357 | where: { | ||
358 | url | ||
359 | } | ||
360 | } | ||
361 | |||
362 | return ActorModel.unscoped().findOne(query) | ||
363 | .then(a => !!a) | ||
364 | } | ||
365 | |||
366 | static listByFollowersUrls (followersUrls: string[], transaction?: Transaction): Promise<MActorFull[]> { | ||
367 | const query = { | ||
368 | where: { | ||
369 | followersUrl: { | ||
370 | [Op.in]: followersUrls | ||
371 | } | ||
372 | }, | ||
373 | transaction | ||
374 | } | ||
375 | |||
376 | return ActorModel.scope(ScopeNames.FULL).findAll(query) | ||
377 | } | ||
378 | |||
379 | static loadLocalByName (preferredUsername: string, transaction?: Transaction): Promise<MActorFull> { | ||
380 | const fun = () => { | ||
381 | const query = { | ||
382 | where: { | ||
383 | preferredUsername, | ||
384 | serverId: null | ||
385 | }, | ||
386 | transaction | ||
387 | } | ||
388 | |||
389 | return ActorModel.scope(ScopeNames.FULL) | ||
390 | .findOne(query) | ||
391 | } | ||
392 | |||
393 | return ModelCache.Instance.doCache({ | ||
394 | cacheType: 'local-actor-name', | ||
395 | key: preferredUsername, | ||
396 | // The server actor never change, so we can easily cache it | ||
397 | whitelist: () => preferredUsername === SERVER_ACTOR_NAME, | ||
398 | fun | ||
399 | }) | ||
400 | } | ||
401 | |||
402 | static loadLocalUrlByName (preferredUsername: string, transaction?: Transaction): Promise<MActorUrl> { | ||
403 | const fun = () => { | ||
404 | const query = { | ||
405 | attributes: [ 'url' ], | ||
406 | where: { | ||
407 | preferredUsername, | ||
408 | serverId: null | ||
409 | }, | ||
410 | transaction | ||
411 | } | ||
412 | |||
413 | return ActorModel.unscoped() | ||
414 | .findOne(query) | ||
415 | } | ||
416 | |||
417 | return ModelCache.Instance.doCache({ | ||
418 | cacheType: 'local-actor-name', | ||
419 | key: preferredUsername, | ||
420 | // The server actor never change, so we can easily cache it | ||
421 | whitelist: () => preferredUsername === SERVER_ACTOR_NAME, | ||
422 | fun | ||
423 | }) | ||
424 | } | ||
425 | |||
426 | static loadByNameAndHost (preferredUsername: string, host: string): Promise<MActorFull> { | ||
427 | const query = { | ||
428 | where: { | ||
429 | preferredUsername | ||
430 | }, | ||
431 | include: [ | ||
432 | { | ||
433 | model: ServerModel, | ||
434 | required: true, | ||
435 | where: { | ||
436 | host | ||
437 | } | ||
438 | } | ||
439 | ] | ||
440 | } | ||
441 | |||
442 | return ActorModel.scope(ScopeNames.FULL).findOne(query) | ||
443 | } | ||
444 | |||
445 | static loadByUrl (url: string, transaction?: Transaction): Promise<MActorAccountChannelId> { | ||
446 | const query = { | ||
447 | where: { | ||
448 | url | ||
449 | }, | ||
450 | transaction, | ||
451 | include: [ | ||
452 | { | ||
453 | attributes: [ 'id' ], | ||
454 | model: AccountModel.unscoped(), | ||
455 | required: false | ||
456 | }, | ||
457 | { | ||
458 | attributes: [ 'id' ], | ||
459 | model: VideoChannelModel.unscoped(), | ||
460 | required: false | ||
461 | } | ||
462 | ] | ||
463 | } | ||
464 | |||
465 | return ActorModel.unscoped().findOne(query) | ||
466 | } | ||
467 | |||
468 | static loadByUrlAndPopulateAccountAndChannel (url: string, transaction?: Transaction): Promise<MActorFull> { | ||
469 | const query = { | ||
470 | where: { | ||
471 | url | ||
472 | }, | ||
473 | transaction | ||
474 | } | ||
475 | |||
476 | return ActorModel.scope(ScopeNames.FULL).findOne(query) | ||
477 | } | ||
478 | |||
479 | static rebuildFollowsCount (ofId: number, type: 'followers' | 'following', transaction?: Transaction) { | ||
480 | const sanitizedOfId = parseInt(ofId + '', 10) | ||
481 | const where = { id: sanitizedOfId } | ||
482 | |||
483 | let columnToUpdate: string | ||
484 | let columnOfCount: string | ||
485 | |||
486 | if (type === 'followers') { | ||
487 | columnToUpdate = 'followersCount' | ||
488 | columnOfCount = 'targetActorId' | ||
489 | } else { | ||
490 | columnToUpdate = 'followingCount' | ||
491 | columnOfCount = 'actorId' | ||
492 | } | ||
493 | |||
494 | return ActorModel.update({ | ||
495 | [columnToUpdate]: literal(`(SELECT COUNT(*) FROM "actorFollow" WHERE "${columnOfCount}" = ${sanitizedOfId})`) | ||
496 | }, { where, transaction }) | ||
497 | } | ||
498 | |||
499 | static loadAccountActorByVideoId (videoId: number): Promise<MActor> { | ||
500 | const query = { | ||
501 | include: [ | ||
502 | { | ||
503 | attributes: [ 'id' ], | ||
504 | model: AccountModel.unscoped(), | ||
505 | required: true, | ||
506 | include: [ | ||
507 | { | ||
508 | attributes: [ 'id', 'accountId' ], | ||
509 | model: VideoChannelModel.unscoped(), | ||
510 | required: true, | ||
511 | include: [ | ||
512 | { | ||
513 | attributes: [ 'id', 'channelId' ], | ||
514 | model: VideoModel.unscoped(), | ||
515 | where: { | ||
516 | id: videoId | ||
517 | } | ||
518 | } | ||
519 | ] | ||
520 | } | ||
521 | ] | ||
522 | } | ||
523 | ] | ||
524 | } | ||
525 | |||
526 | return ActorModel.unscoped().findOne(query) | ||
527 | } | ||
528 | |||
529 | getSharedInbox (this: MActorWithInboxes) { | ||
530 | return this.sharedInboxUrl || this.inboxUrl | ||
531 | } | ||
532 | |||
533 | toFormattedSummaryJSON (this: MActorSummaryFormattable) { | ||
534 | let avatar: ActorImage = null | ||
535 | if (this.Avatar) { | ||
536 | avatar = this.Avatar.toFormattedJSON() | ||
537 | } | ||
538 | |||
539 | return { | ||
540 | url: this.url, | ||
541 | name: this.preferredUsername, | ||
542 | host: this.getHost(), | ||
543 | avatar | ||
544 | } | ||
545 | } | ||
546 | |||
547 | toFormattedJSON (this: MActorFormattable) { | ||
548 | const base = this.toFormattedSummaryJSON() | ||
549 | |||
550 | let banner: ActorImage = null | ||
551 | if (this.Banner) { | ||
552 | banner = this.Banner.toFormattedJSON() | ||
553 | } | ||
554 | |||
555 | return Object.assign(base, { | ||
556 | id: this.id, | ||
557 | hostRedundancyAllowed: this.getRedundancyAllowed(), | ||
558 | followingCount: this.followingCount, | ||
559 | followersCount: this.followersCount, | ||
560 | banner, | ||
561 | createdAt: this.getCreatedAt() | ||
562 | }) | ||
563 | } | ||
564 | |||
565 | toActivityPubObject (this: MActorAPChannel | MActorAPAccount, name: string) { | ||
566 | let icon: ActivityIconObject | ||
567 | let image: ActivityIconObject | ||
568 | |||
569 | if (this.avatarId) { | ||
570 | const extension = extname(this.Avatar.filename) | ||
571 | |||
572 | icon = { | ||
573 | type: 'Image', | ||
574 | mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension], | ||
575 | height: this.Avatar.height, | ||
576 | width: this.Avatar.width, | ||
577 | url: this.getAvatarUrl() | ||
578 | } | ||
579 | } | ||
580 | |||
581 | if (this.bannerId) { | ||
582 | const banner = (this as MActorAPChannel).Banner | ||
583 | const extension = extname(banner.filename) | ||
584 | |||
585 | image = { | ||
586 | type: 'Image', | ||
587 | mediaType: MIMETYPES.IMAGE.EXT_MIMETYPE[extension], | ||
588 | height: banner.height, | ||
589 | width: banner.width, | ||
590 | url: this.getBannerUrl() | ||
591 | } | ||
592 | } | ||
593 | |||
594 | const json = { | ||
595 | type: this.type, | ||
596 | id: this.url, | ||
597 | following: this.getFollowingUrl(), | ||
598 | followers: this.getFollowersUrl(), | ||
599 | playlists: this.getPlaylistsUrl(), | ||
600 | inbox: this.inboxUrl, | ||
601 | outbox: this.outboxUrl, | ||
602 | preferredUsername: this.preferredUsername, | ||
603 | url: this.url, | ||
604 | name, | ||
605 | endpoints: { | ||
606 | sharedInbox: this.sharedInboxUrl | ||
607 | }, | ||
608 | publicKey: { | ||
609 | id: this.getPublicKeyUrl(), | ||
610 | owner: this.url, | ||
611 | publicKeyPem: this.publicKey | ||
612 | }, | ||
613 | published: this.getCreatedAt().toISOString(), | ||
614 | icon, | ||
615 | image | ||
616 | } | ||
617 | |||
618 | return activityPubContextify(json) | ||
619 | } | ||
620 | |||
621 | getFollowerSharedInboxUrls (t: Transaction) { | ||
622 | const query = { | ||
623 | attributes: [ 'sharedInboxUrl' ], | ||
624 | include: [ | ||
625 | { | ||
626 | attribute: [], | ||
627 | model: ActorFollowModel.unscoped(), | ||
628 | required: true, | ||
629 | as: 'ActorFollowing', | ||
630 | where: { | ||
631 | state: 'accepted', | ||
632 | targetActorId: this.id | ||
633 | } | ||
634 | } | ||
635 | ], | ||
636 | transaction: t | ||
637 | } | ||
638 | |||
639 | return ActorModel.findAll(query) | ||
640 | .then(accounts => accounts.map(a => a.sharedInboxUrl)) | ||
641 | } | ||
642 | |||
643 | getFollowingUrl () { | ||
644 | return this.url + '/following' | ||
645 | } | ||
646 | |||
647 | getFollowersUrl () { | ||
648 | return this.url + '/followers' | ||
649 | } | ||
650 | |||
651 | getPlaylistsUrl () { | ||
652 | return this.url + '/playlists' | ||
653 | } | ||
654 | |||
655 | getPublicKeyUrl () { | ||
656 | return this.url + '#main-key' | ||
657 | } | ||
658 | |||
659 | isOwned () { | ||
660 | return this.serverId === null | ||
661 | } | ||
662 | |||
663 | getWebfingerUrl (this: MActorServer) { | ||
664 | return 'acct:' + this.preferredUsername + '@' + this.getHost() | ||
665 | } | ||
666 | |||
667 | getIdentifier () { | ||
668 | return this.Server ? `${this.preferredUsername}@${this.Server.host}` : this.preferredUsername | ||
669 | } | ||
670 | |||
671 | getHost (this: MActorHost) { | ||
672 | return this.Server ? this.Server.host : WEBSERVER.HOST | ||
673 | } | ||
674 | |||
675 | getRedundancyAllowed () { | ||
676 | return this.Server ? this.Server.redundancyAllowed : false | ||
677 | } | ||
678 | |||
679 | getAvatarUrl () { | ||
680 | if (!this.avatarId) return undefined | ||
681 | |||
682 | return WEBSERVER.URL + this.Avatar.getStaticPath() | ||
683 | } | ||
684 | |||
685 | getBannerUrl () { | ||
686 | if (!this.bannerId) return undefined | ||
687 | |||
688 | return WEBSERVER.URL + this.Banner.getStaticPath() | ||
689 | } | ||
690 | |||
691 | isOutdated () { | ||
692 | if (this.isOwned()) return false | ||
693 | |||
694 | return isOutdated(this, ACTIVITY_PUB.ACTOR_REFRESH_INTERVAL) | ||
695 | } | ||
696 | |||
697 | getCreatedAt (this: MActorAPChannel | MActorAPAccount | MActorFormattable) { | ||
698 | return this.remoteCreatedAt || this.createdAt | ||
699 | } | ||
700 | } | ||