]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/models/video/video-channel.ts
Relax plugin package.json validation
[github/Chocobozzz/PeerTube.git] / server / models / video / video-channel.ts
1 import {
2 AllowNull,
3 BeforeDestroy,
4 BelongsTo,
5 Column,
6 CreatedAt,
7 DataType,
8 Default,
9 DefaultScope,
10 ForeignKey,
11 HasMany,
12 Is,
13 Model,
14 Scopes,
15 Sequelize,
16 Table,
17 UpdatedAt
18 } from 'sequelize-typescript'
19 import { ActivityPubActor } from '../../../shared/models/activitypub'
20 import { VideoChannel, VideoChannelSummary } from '../../../shared/models/videos'
21 import {
22 isVideoChannelDescriptionValid,
23 isVideoChannelNameValid,
24 isVideoChannelSupportValid
25 } from '../../helpers/custom-validators/video-channels'
26 import { sendDeleteActor } from '../../lib/activitypub/send'
27 import { AccountModel, ScopeNames as AccountModelScopeNames, SummaryOptions as AccountSummaryOptions } from '../account/account'
28 import { ActorModel, unusedActorAttributesForAPI } from '../activitypub/actor'
29 import { buildServerIdsFollowedBy, buildTrigramSearchIndex, createSimilarityAttribute, getSort, throwIfNotValid } from '../utils'
30 import { VideoModel } from './video'
31 import { CONSTRAINTS_FIELDS, WEBSERVER } from '../../initializers/constants'
32 import { ServerModel } from '../server/server'
33 import { FindOptions, ModelIndexesOptions, Op } from 'sequelize'
34 import { AvatarModel } from '../avatar/avatar'
35 import { VideoPlaylistModel } from './video-playlist'
36
37 // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation
38 const indexes: ModelIndexesOptions[] = [
39 buildTrigramSearchIndex('video_channel_name_trigram', 'name'),
40
41 {
42 fields: [ 'accountId' ]
43 },
44 {
45 fields: [ 'actorId' ]
46 }
47 ]
48
49 export enum ScopeNames {
50 AVAILABLE_FOR_LIST = 'AVAILABLE_FOR_LIST',
51 WITH_ACCOUNT = 'WITH_ACCOUNT',
52 WITH_ACTOR = 'WITH_ACTOR',
53 WITH_VIDEOS = 'WITH_VIDEOS',
54 SUMMARY = 'SUMMARY'
55 }
56
57 type AvailableForListOptions = {
58 actorId: number
59 }
60
61 export type SummaryOptions = {
62 withAccount?: boolean // Default: false
63 withAccountBlockerIds?: number[]
64 }
65
66 @DefaultScope(() => ({
67 include: [
68 {
69 model: ActorModel,
70 required: true
71 }
72 ]
73 }))
74 @Scopes(() => ({
75 [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
76 const base: FindOptions = {
77 attributes: [ 'name', 'description', 'id', 'actorId' ],
78 include: [
79 {
80 attributes: [ 'preferredUsername', 'url', 'serverId', 'avatarId' ],
81 model: ActorModel.unscoped(),
82 required: true,
83 include: [
84 {
85 attributes: [ 'host' ],
86 model: ServerModel.unscoped(),
87 required: false
88 },
89 {
90 model: AvatarModel.unscoped(),
91 required: false
92 }
93 ]
94 }
95 ]
96 }
97
98 if (options.withAccount === true) {
99 base.include.push({
100 model: AccountModel.scope({
101 method: [ AccountModelScopeNames.SUMMARY, { withAccountBlockerIds: options.withAccountBlockerIds } as AccountSummaryOptions ]
102 }),
103 required: true
104 })
105 }
106
107 return base
108 },
109 [ScopeNames.AVAILABLE_FOR_LIST]: (options: AvailableForListOptions) => {
110 // Only list local channels OR channels that are on an instance followed by actorId
111 const inQueryInstanceFollow = buildServerIdsFollowedBy(options.actorId)
112
113 return {
114 include: [
115 {
116 attributes: {
117 exclude: unusedActorAttributesForAPI
118 },
119 model: ActorModel,
120 where: {
121 [Op.or]: [
122 {
123 serverId: null
124 },
125 {
126 serverId: {
127 [ Op.in ]: Sequelize.literal(inQueryInstanceFollow)
128 }
129 }
130 ]
131 }
132 },
133 {
134 model: AccountModel,
135 required: true,
136 include: [
137 {
138 attributes: {
139 exclude: unusedActorAttributesForAPI
140 },
141 model: ActorModel, // Default scope includes avatar and server
142 required: true
143 }
144 ]
145 }
146 ]
147 }
148 },
149 [ScopeNames.WITH_ACCOUNT]: {
150 include: [
151 {
152 model: AccountModel,
153 required: true
154 }
155 ]
156 },
157 [ScopeNames.WITH_VIDEOS]: {
158 include: [
159 VideoModel
160 ]
161 },
162 [ScopeNames.WITH_ACTOR]: {
163 include: [
164 ActorModel
165 ]
166 }
167 }))
168 @Table({
169 tableName: 'videoChannel',
170 indexes
171 })
172 export class VideoChannelModel extends Model<VideoChannelModel> {
173
174 @AllowNull(false)
175 @Is('VideoChannelName', value => throwIfNotValid(value, isVideoChannelNameValid, 'name'))
176 @Column
177 name: string
178
179 @AllowNull(true)
180 @Default(null)
181 @Is('VideoChannelDescription', value => throwIfNotValid(value, isVideoChannelDescriptionValid, 'description', true))
182 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.DESCRIPTION.max))
183 description: string
184
185 @AllowNull(true)
186 @Default(null)
187 @Is('VideoChannelSupport', value => throwIfNotValid(value, isVideoChannelSupportValid, 'support', true))
188 @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEO_CHANNELS.SUPPORT.max))
189 support: string
190
191 @CreatedAt
192 createdAt: Date
193
194 @UpdatedAt
195 updatedAt: Date
196
197 @ForeignKey(() => ActorModel)
198 @Column
199 actorId: number
200
201 @BelongsTo(() => ActorModel, {
202 foreignKey: {
203 allowNull: false
204 },
205 onDelete: 'cascade'
206 })
207 Actor: ActorModel
208
209 @ForeignKey(() => AccountModel)
210 @Column
211 accountId: number
212
213 @BelongsTo(() => AccountModel, {
214 foreignKey: {
215 allowNull: false
216 },
217 hooks: true
218 })
219 Account: AccountModel
220
221 @HasMany(() => VideoModel, {
222 foreignKey: {
223 name: 'channelId',
224 allowNull: false
225 },
226 onDelete: 'CASCADE',
227 hooks: true
228 })
229 Videos: VideoModel[]
230
231 @HasMany(() => VideoPlaylistModel, {
232 foreignKey: {
233 allowNull: true
234 },
235 onDelete: 'CASCADE',
236 hooks: true
237 })
238 VideoPlaylists: VideoPlaylistModel[]
239
240 @BeforeDestroy
241 static async sendDeleteIfOwned (instance: VideoChannelModel, options) {
242 if (!instance.Actor) {
243 instance.Actor = await instance.$get('Actor', { transaction: options.transaction }) as ActorModel
244 }
245
246 if (instance.Actor.isOwned()) {
247 return sendDeleteActor(instance.Actor, options.transaction)
248 }
249
250 return undefined
251 }
252
253 static countByAccount (accountId: number) {
254 const query = {
255 where: {
256 accountId
257 }
258 }
259
260 return VideoChannelModel.count(query)
261 }
262
263 static listForApi (actorId: number, start: number, count: number, sort: string) {
264 const query = {
265 offset: start,
266 limit: count,
267 order: getSort(sort)
268 }
269
270 const scopes = {
271 method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId } as AvailableForListOptions ]
272 }
273 return VideoChannelModel
274 .scope(scopes)
275 .findAndCountAll(query)
276 .then(({ rows, count }) => {
277 return { total: count, data: rows }
278 })
279 }
280
281 static listLocalsForSitemap (sort: string) {
282 const query = {
283 attributes: [ ],
284 offset: 0,
285 order: getSort(sort),
286 include: [
287 {
288 attributes: [ 'preferredUsername', 'serverId' ],
289 model: ActorModel.unscoped(),
290 where: {
291 serverId: null
292 }
293 }
294 ]
295 }
296
297 return VideoChannelModel
298 .unscoped()
299 .findAll(query)
300 }
301
302 static searchForApi (options: {
303 actorId: number
304 search: string
305 start: number
306 count: number
307 sort: string
308 }) {
309 const attributesInclude = []
310 const escapedSearch = VideoModel.sequelize.escape(options.search)
311 const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%')
312 attributesInclude.push(createSimilarityAttribute('VideoChannelModel.name', options.search))
313
314 const query = {
315 attributes: {
316 include: attributesInclude
317 },
318 offset: options.start,
319 limit: options.count,
320 order: getSort(options.sort),
321 where: {
322 [Op.or]: [
323 Sequelize.literal(
324 'lower(immutable_unaccent("VideoChannelModel"."name")) % lower(immutable_unaccent(' + escapedSearch + '))'
325 ),
326 Sequelize.literal(
327 'lower(immutable_unaccent("VideoChannelModel"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))'
328 )
329 ]
330 }
331 }
332
333 const scopes = {
334 method: [ ScopeNames.AVAILABLE_FOR_LIST, { actorId: options.actorId } as AvailableForListOptions ]
335 }
336 return VideoChannelModel
337 .scope(scopes)
338 .findAndCountAll(query)
339 .then(({ rows, count }) => {
340 return { total: count, data: rows }
341 })
342 }
343
344 static listByAccount (options: {
345 accountId: number,
346 start: number,
347 count: number,
348 sort: string
349 }) {
350 const query = {
351 offset: options.start,
352 limit: options.count,
353 order: getSort(options.sort),
354 include: [
355 {
356 model: AccountModel,
357 where: {
358 id: options.accountId
359 },
360 required: true
361 }
362 ]
363 }
364
365 return VideoChannelModel
366 .findAndCountAll(query)
367 .then(({ rows, count }) => {
368 return { total: count, data: rows }
369 })
370 }
371
372 static loadByIdAndPopulateAccount (id: number) {
373 return VideoChannelModel.unscoped()
374 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
375 .findByPk(id)
376 }
377
378 static loadByIdAndAccount (id: number, accountId: number) {
379 const query = {
380 where: {
381 id,
382 accountId
383 }
384 }
385
386 return VideoChannelModel.unscoped()
387 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
388 .findOne(query)
389 }
390
391 static loadAndPopulateAccount (id: number) {
392 return VideoChannelModel.unscoped()
393 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
394 .findByPk(id)
395 }
396
397 static loadByUrlAndPopulateAccount (url: string) {
398 const query = {
399 include: [
400 {
401 model: ActorModel,
402 required: true,
403 where: {
404 url
405 }
406 }
407 ]
408 }
409
410 return VideoChannelModel
411 .scope([ ScopeNames.WITH_ACCOUNT ])
412 .findOne(query)
413 }
414
415 static loadByNameWithHostAndPopulateAccount (nameWithHost: string) {
416 const [ name, host ] = nameWithHost.split('@')
417
418 if (!host || host === WEBSERVER.HOST) return VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
419
420 return VideoChannelModel.loadByNameAndHostAndPopulateAccount(name, host)
421 }
422
423 static loadLocalByNameAndPopulateAccount (name: string) {
424 const query = {
425 include: [
426 {
427 model: ActorModel,
428 required: true,
429 where: {
430 preferredUsername: name,
431 serverId: null
432 }
433 }
434 ]
435 }
436
437 return VideoChannelModel.unscoped()
438 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
439 .findOne(query)
440 }
441
442 static loadByNameAndHostAndPopulateAccount (name: string, host: string) {
443 const query = {
444 include: [
445 {
446 model: ActorModel,
447 required: true,
448 where: {
449 preferredUsername: name
450 },
451 include: [
452 {
453 model: ServerModel,
454 required: true,
455 where: { host }
456 }
457 ]
458 }
459 ]
460 }
461
462 return VideoChannelModel.unscoped()
463 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT ])
464 .findOne(query)
465 }
466
467 static loadAndPopulateAccountAndVideos (id: number) {
468 const options = {
469 include: [
470 VideoModel
471 ]
472 }
473
474 return VideoChannelModel.unscoped()
475 .scope([ ScopeNames.WITH_ACTOR, ScopeNames.WITH_ACCOUNT, ScopeNames.WITH_VIDEOS ])
476 .findByPk(id, options)
477 }
478
479 toFormattedJSON (): VideoChannel {
480 const actor = this.Actor.toFormattedJSON()
481 const videoChannel = {
482 id: this.id,
483 displayName: this.getDisplayName(),
484 description: this.description,
485 support: this.support,
486 isLocal: this.Actor.isOwned(),
487 createdAt: this.createdAt,
488 updatedAt: this.updatedAt,
489 ownerAccount: undefined
490 }
491
492 if (this.Account) videoChannel.ownerAccount = this.Account.toFormattedJSON()
493
494 return Object.assign(actor, videoChannel)
495 }
496
497 toFormattedSummaryJSON (): VideoChannelSummary {
498 const actor = this.Actor.toFormattedJSON()
499
500 return {
501 id: this.id,
502 name: actor.name,
503 displayName: this.getDisplayName(),
504 url: actor.url,
505 host: actor.host,
506 avatar: actor.avatar
507 }
508 }
509
510 toActivityPubObject (): ActivityPubActor {
511 const obj = this.Actor.toActivityPubObject(this.name, 'VideoChannel')
512
513 return Object.assign(obj, {
514 summary: this.description,
515 support: this.support,
516 attributedTo: [
517 {
518 type: 'Person' as 'Person',
519 id: this.Account.Actor.url
520 }
521 ]
522 })
523 }
524
525 getDisplayName () {
526 return this.name
527 }
528
529 isOutdated () {
530 return this.Actor.isOutdated()
531 }
532 }