]>
Commit | Line | Data |
---|---|---|
39445ead | 1 | import * as Bluebird from 'bluebird' |
098eb377 | 2 | import { maxBy } from 'lodash' |
571389d4 | 3 | import * as magnetUtil from 'magnet-uri' |
4d4e5cd4 | 4 | import * as parseTorrent from 'parse-torrent' |
098eb377 | 5 | import { join } from 'path' |
1735c825 C |
6 | import { |
7 | CountOptions, | |
8 | FindOptions, | |
9 | IncludeOptions, | |
10 | ModelIndexesOptions, | |
11 | Op, | |
12 | QueryTypes, | |
13 | ScopeOptions, | |
14 | Sequelize, | |
15 | Transaction, | |
16 | WhereOptions | |
17 | } from 'sequelize' | |
3fd3ab2d | 18 | import { |
4ba3b8ea C |
19 | AllowNull, |
20 | BeforeDestroy, | |
21 | BelongsTo, | |
22 | BelongsToMany, | |
23 | Column, | |
24 | CreatedAt, | |
25 | DataType, | |
26 | Default, | |
27 | ForeignKey, | |
28 | HasMany, | |
2baea0c7 | 29 | HasOne, |
4ba3b8ea C |
30 | Is, |
31 | IsInt, | |
32 | IsUUID, | |
33 | Min, | |
34 | Model, | |
35 | Scopes, | |
36 | Table, | |
9a629c6e | 37 | UpdatedAt |
3fd3ab2d | 38 | } from 'sequelize-typescript' |
7ad9b984 | 39 | import { UserRight, VideoPrivacy, VideoState } from '../../../shared' |
3fd3ab2d | 40 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' |
a8462c8e | 41 | import { Video, VideoDetails, VideoFile } from '../../../shared/models/videos' |
066e94c5 | 42 | import { VideoFilter } from '../../../shared/models/videos/video-query.type' |
62689b94 | 43 | import { createTorrentPromise, peertubeTruncate } from '../../helpers/core-utils' |
da854ddd | 44 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc' |
c48e82b5 | 45 | import { isArray, isBooleanValid } from '../../helpers/custom-validators/misc' |
3fd3ab2d | 46 | import { |
4ba3b8ea C |
47 | isVideoCategoryValid, |
48 | isVideoDescriptionValid, | |
49 | isVideoDurationValid, | |
50 | isVideoLanguageValid, | |
51 | isVideoLicenceValid, | |
418d092a | 52 | isVideoNameValid, |
2baea0c7 C |
53 | isVideoPrivacyValid, |
54 | isVideoStateValid, | |
b64c950a | 55 | isVideoSupportValid |
3fd3ab2d | 56 | } from '../../helpers/custom-validators/videos' |
1735c825 | 57 | import { getVideoFileResolution } from '../../helpers/ffmpeg-utils' |
da854ddd | 58 | import { logger } from '../../helpers/logger' |
f05a1c30 | 59 | import { getServerActor } from '../../helpers/utils' |
65fcc311 | 60 | import { |
1297eb5d | 61 | ACTIVITY_PUB, |
4ba3b8ea | 62 | API_VERSION, |
418d092a | 63 | CONSTRAINTS_FIELDS, |
418d092a | 64 | HLS_REDUNDANCY_DIRECTORY, |
6dd9de95 | 65 | HLS_STREAMING_PLAYLIST_DIRECTORY, |
4ba3b8ea | 66 | REMOTE_SCHEME, |
02756fbd | 67 | STATIC_DOWNLOAD_PATHS, |
4ba3b8ea | 68 | STATIC_PATHS, |
4ba3b8ea C |
69 | VIDEO_CATEGORIES, |
70 | VIDEO_LANGUAGES, | |
71 | VIDEO_LICENCES, | |
2baea0c7 | 72 | VIDEO_PRIVACIES, |
6dd9de95 C |
73 | VIDEO_STATES, |
74 | WEBSERVER | |
74dc3bca | 75 | } from '../../initializers/constants' |
50d6de9c | 76 | import { sendDeleteVideo } from '../../lib/activitypub/send' |
3fd3ab2d C |
77 | import { AccountModel } from '../account/account' |
78 | import { AccountVideoRateModel } from '../account/account-video-rate' | |
50d6de9c | 79 | import { ActorModel } from '../activitypub/actor' |
b6a4fd6b | 80 | import { AvatarModel } from '../avatar/avatar' |
3fd3ab2d | 81 | import { ServerModel } from '../server/server' |
418d092a C |
82 | import { |
83 | buildBlockedAccountSQL, | |
84 | buildTrigramSearchIndex, | |
85 | buildWhereIdOrUUID, | |
3caf77d3 | 86 | createSafeIn, |
418d092a | 87 | createSimilarityAttribute, |
6dd9de95 C |
88 | getVideoSort, |
89 | isOutdated, | |
418d092a C |
90 | throwIfNotValid |
91 | } from '../utils' | |
3fd3ab2d C |
92 | import { TagModel } from './tag' |
93 | import { VideoAbuseModel } from './video-abuse' | |
6dd9de95 | 94 | import { ScopeNames as VideoChannelScopeNames, VideoChannelModel } from './video-channel' |
da854ddd | 95 | import { VideoCommentModel } from './video-comment' |
3fd3ab2d C |
96 | import { VideoFileModel } from './video-file' |
97 | import { VideoShareModel } from './video-share' | |
98 | import { VideoTagModel } from './video-tag' | |
2baea0c7 | 99 | import { ScheduleVideoUpdateModel } from './schedule-video-update' |
40e87e9e | 100 | import { VideoCaptionModel } from './video-caption' |
26b7305a | 101 | import { VideoBlacklistModel } from './video-blacklist' |
098eb377 | 102 | import { remove, writeFile } from 'fs-extra' |
9a629c6e | 103 | import { VideoViewModel } from './video-views' |
c48e82b5 | 104 | import { VideoRedundancyModel } from '../redundancy/video-redundancy' |
098eb377 C |
105 | import { |
106 | videoFilesModelToFormattedJSON, | |
107 | VideoFormattingJSONOptions, | |
108 | videoModelToActivityPubObject, | |
109 | videoModelToFormattedDetailsJSON, | |
110 | videoModelToFormattedJSON | |
111 | } from './video-format-utils' | |
6e46de09 | 112 | import { UserVideoHistoryModel } from '../account/user-video-history' |
7ad9b984 | 113 | import { UserModel } from '../account/user' |
dc133480 | 114 | import { VideoImportModel } from './video-import' |
09209296 | 115 | import { VideoStreamingPlaylistModel } from './video-streaming-playlist' |
418d092a | 116 | import { VideoPlaylistElementModel } from './video-playlist-element' |
6dd9de95 | 117 | import { CONFIG } from '../../initializers/config' |
e8bafea3 C |
118 | import { ThumbnailModel } from './thumbnail' |
119 | import { ThumbnailType } from '../../../shared/models/videos/thumbnail.type' | |
6e46de09 | 120 | |
57c36b27 | 121 | // FIXME: Define indexes here because there is an issue with TS and Sequelize.literal when called directly in the annotation |
1735c825 | 122 | const indexes: (ModelIndexesOptions & { where?: WhereOptions })[] = [ |
57c36b27 C |
123 | buildTrigramSearchIndex('video_name_trigram', 'name'), |
124 | ||
8cd72bd3 C |
125 | { fields: [ 'createdAt' ] }, |
126 | { fields: [ 'publishedAt' ] }, | |
127 | { fields: [ 'duration' ] }, | |
8cd72bd3 | 128 | { fields: [ 'views' ] }, |
8cd72bd3 | 129 | { fields: [ 'channelId' ] }, |
7519127b C |
130 | { |
131 | fields: [ 'originallyPublishedAt' ], | |
132 | where: { | |
133 | originallyPublishedAt: { | |
1735c825 | 134 | [Op.ne]: null |
7519127b C |
135 | } |
136 | } | |
137 | }, | |
439b1744 C |
138 | { |
139 | fields: [ 'category' ], // We don't care videos with an unknown category | |
140 | where: { | |
141 | category: { | |
1735c825 | 142 | [Op.ne]: null |
439b1744 C |
143 | } |
144 | } | |
145 | }, | |
146 | { | |
147 | fields: [ 'licence' ], // We don't care videos with an unknown licence | |
148 | where: { | |
149 | licence: { | |
1735c825 | 150 | [Op.ne]: null |
439b1744 C |
151 | } |
152 | } | |
153 | }, | |
154 | { | |
155 | fields: [ 'language' ], // We don't care videos with an unknown language | |
156 | where: { | |
157 | language: { | |
1735c825 | 158 | [Op.ne]: null |
439b1744 C |
159 | } |
160 | } | |
161 | }, | |
162 | { | |
163 | fields: [ 'nsfw' ], // Most of the videos are not NSFW | |
164 | where: { | |
165 | nsfw: true | |
166 | } | |
167 | }, | |
168 | { | |
169 | fields: [ 'remote' ], // Only index local videos | |
170 | where: { | |
171 | remote: false | |
172 | } | |
173 | }, | |
57c36b27 | 174 | { |
8cd72bd3 C |
175 | fields: [ 'uuid' ], |
176 | unique: true | |
57c36b27 C |
177 | }, |
178 | { | |
8ea6f49a | 179 | fields: [ 'url' ], |
57c36b27 C |
180 | unique: true |
181 | } | |
182 | ] | |
183 | ||
2baea0c7 | 184 | export enum ScopeNames { |
afd2cba5 C |
185 | AVAILABLE_FOR_LIST_IDS = 'AVAILABLE_FOR_LIST_IDS', |
186 | FOR_API = 'FOR_API', | |
4cb6d457 | 187 | WITH_ACCOUNT_DETAILS = 'WITH_ACCOUNT_DETAILS', |
d48ff09d | 188 | WITH_TAGS = 'WITH_TAGS', |
bbe0f064 | 189 | WITH_FILES = 'WITH_FILES', |
191764f3 | 190 | WITH_SCHEDULED_UPDATE = 'WITH_SCHEDULED_UPDATE', |
6e46de09 | 191 | WITH_BLACKLISTED = 'WITH_BLACKLISTED', |
09209296 C |
192 | WITH_USER_HISTORY = 'WITH_USER_HISTORY', |
193 | WITH_STREAMING_PLAYLISTS = 'WITH_STREAMING_PLAYLISTS', | |
e8bafea3 C |
194 | WITH_USER_ID = 'WITH_USER_ID', |
195 | WITH_THUMBNAILS = 'WITH_THUMBNAILS' | |
d48ff09d C |
196 | } |
197 | ||
afd2cba5 C |
198 | type ForAPIOptions = { |
199 | ids: number[] | |
418d092a C |
200 | |
201 | videoPlaylistId?: number | |
202 | ||
afd2cba5 C |
203 | withFiles?: boolean |
204 | } | |
205 | ||
206 | type AvailableForListIDsOptions = { | |
7ad9b984 | 207 | serverAccountId: number |
4e74e803 | 208 | followerActorId: number |
afd2cba5 | 209 | includeLocalVideos: boolean |
418d092a | 210 | |
8519cc92 C |
211 | withoutId?: boolean |
212 | ||
afd2cba5 C |
213 | filter?: VideoFilter |
214 | categoryOneOf?: number[] | |
215 | nsfw?: boolean | |
216 | licenceOneOf?: number[] | |
217 | languageOneOf?: string[] | |
218 | tagsOneOf?: string[] | |
219 | tagsAllOf?: string[] | |
418d092a | 220 | |
afd2cba5 | 221 | withFiles?: boolean |
418d092a | 222 | |
afd2cba5 | 223 | accountId?: number |
d525fc39 | 224 | videoChannelId?: number |
418d092a C |
225 | |
226 | videoPlaylistId?: number | |
227 | ||
9a629c6e | 228 | trendingDays?: number |
8b9a525a C |
229 | user?: UserModel, |
230 | historyOfUser?: UserModel | |
3caf77d3 C |
231 | |
232 | baseWhere?: WhereOptions[] | |
d525fc39 C |
233 | } |
234 | ||
3acc5084 | 235 | @Scopes(() => ({ |
8ea6f49a | 236 | [ ScopeNames.FOR_API ]: (options: ForAPIOptions) => { |
1735c825 | 237 | const query: FindOptions = { |
afd2cba5 C |
238 | where: { |
239 | id: { | |
3acc5084 | 240 | [ Op.in ]: options.ids // FIXME: sequelize ANY seems broken |
afd2cba5 C |
241 | } |
242 | }, | |
418d092a C |
243 | include: [ |
244 | { | |
76564702 C |
245 | model: VideoChannelModel.scope({ method: [ VideoChannelScopeNames.SUMMARY, true ] }), |
246 | required: true | |
2fb5b3a5 C |
247 | }, |
248 | { | |
249 | attributes: [ 'type', 'filename' ], | |
250 | model: ThumbnailModel, | |
251 | required: false | |
418d092a C |
252 | } |
253 | ] | |
afd2cba5 C |
254 | } |
255 | ||
256 | if (options.withFiles === true) { | |
257 | query.include.push({ | |
258 | model: VideoFileModel.unscoped(), | |
259 | required: true | |
260 | }) | |
261 | } | |
262 | ||
418d092a C |
263 | if (options.videoPlaylistId) { |
264 | query.include.push({ | |
265 | model: VideoPlaylistElementModel.unscoped(), | |
15e9d5ca C |
266 | required: true, |
267 | where: { | |
268 | videoPlaylistId: options.videoPlaylistId | |
269 | } | |
418d092a C |
270 | }) |
271 | } | |
272 | ||
afd2cba5 C |
273 | return query |
274 | }, | |
8ea6f49a | 275 | [ ScopeNames.AVAILABLE_FOR_LIST_IDS ]: (options: AvailableForListIDsOptions) => { |
3caf77d3 | 276 | const whereAnd = options.baseWhere ? options.baseWhere : [] |
8519cc92 | 277 | |
1735c825 | 278 | const query: FindOptions = { |
2b62cccd | 279 | raw: true, |
3caf77d3 | 280 | attributes: options.withoutId === true ? [] : [ 'id' ], |
1cd3facc C |
281 | include: [] |
282 | } | |
283 | ||
3caf77d3 C |
284 | whereAnd.push({ |
285 | id: { | |
286 | [ Op.notIn ]: Sequelize.literal( | |
287 | '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")' | |
288 | ) | |
289 | } | |
290 | }) | |
291 | ||
292 | whereAnd.push({ | |
293 | channelId: { | |
294 | [ Op.notIn ]: Sequelize.literal( | |
295 | '(' + | |
296 | 'SELECT id FROM "videoChannel" WHERE "accountId" IN (' + | |
297 | buildBlockedAccountSQL(options.serverAccountId, options.user ? options.user.Account.id : undefined) + | |
298 | ')' + | |
299 | ')' | |
300 | ) | |
301 | } | |
302 | }) | |
303 | ||
1cd3facc C |
304 | // Only list public/published videos |
305 | if (!options.filter || options.filter !== 'all-local') { | |
306 | const privacyWhere = { | |
2186386c C |
307 | // Always list public videos |
308 | privacy: VideoPrivacy.PUBLIC, | |
309 | // Always list published videos, or videos that are being transcoded but on which we don't want to wait for transcoding | |
1735c825 | 310 | [ Op.or ]: [ |
2186386c C |
311 | { |
312 | state: VideoState.PUBLISHED | |
313 | }, | |
314 | { | |
1735c825 | 315 | [ Op.and ]: { |
2186386c C |
316 | state: VideoState.TO_TRANSCODE, |
317 | waitTranscoding: false | |
318 | } | |
319 | } | |
320 | ] | |
1cd3facc C |
321 | } |
322 | ||
3caf77d3 | 323 | whereAnd.push(privacyWhere) |
afd2cba5 C |
324 | } |
325 | ||
418d092a C |
326 | if (options.videoPlaylistId) { |
327 | query.include.push({ | |
328 | attributes: [], | |
329 | model: VideoPlaylistElementModel.unscoped(), | |
330 | required: true, | |
331 | where: { | |
332 | videoPlaylistId: options.videoPlaylistId | |
333 | } | |
334 | }) | |
15e9d5ca C |
335 | |
336 | query.subQuery = false | |
418d092a C |
337 | } |
338 | ||
afd2cba5 | 339 | if (options.filter || options.accountId || options.videoChannelId) { |
1735c825 | 340 | const videoChannelInclude: IncludeOptions = { |
afd2cba5 C |
341 | attributes: [], |
342 | model: VideoChannelModel.unscoped(), | |
343 | required: true | |
344 | } | |
345 | ||
346 | if (options.videoChannelId) { | |
347 | videoChannelInclude.where = { | |
348 | id: options.videoChannelId | |
349 | } | |
350 | } | |
351 | ||
352 | if (options.filter || options.accountId) { | |
1735c825 | 353 | const accountInclude: IncludeOptions = { |
afd2cba5 C |
354 | attributes: [], |
355 | model: AccountModel.unscoped(), | |
356 | required: true | |
357 | } | |
358 | ||
359 | if (options.filter) { | |
360 | accountInclude.include = [ | |
361 | { | |
362 | attributes: [], | |
363 | model: ActorModel.unscoped(), | |
364 | required: true, | |
365 | where: VideoModel.buildActorWhereWithFilter(options.filter) | |
366 | } | |
367 | ] | |
368 | } | |
369 | ||
370 | if (options.accountId) { | |
371 | accountInclude.where = { id: options.accountId } | |
372 | } | |
373 | ||
374 | videoChannelInclude.include = [ accountInclude ] | |
375 | } | |
376 | ||
377 | query.include.push(videoChannelInclude) | |
244e76a5 RK |
378 | } |
379 | ||
4e74e803 | 380 | if (options.followerActorId) { |
687d638c C |
381 | let localVideosReq = '' |
382 | if (options.includeLocalVideos === true) { | |
383 | localVideosReq = ' UNION ALL ' + | |
384 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
385 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
386 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
387 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
388 | 'WHERE "actor"."serverId" IS NULL' | |
389 | } | |
390 | ||
391 | // Force actorId to be a number to avoid SQL injections | |
4e74e803 | 392 | const actorIdNumber = parseInt(options.followerActorId.toString(), 10) |
3caf77d3 C |
393 | whereAnd.push({ |
394 | id: { | |
395 | [ Op.in ]: Sequelize.literal( | |
396 | '(' + | |
397 | 'SELECT "videoShare"."videoId" AS "id" FROM "videoShare" ' + | |
398 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + | |
399 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
400 | ' UNION ALL ' + | |
401 | 'SELECT "video"."id" AS "id" FROM "video" ' + | |
402 | 'INNER JOIN "videoChannel" ON "videoChannel"."id" = "video"."channelId" ' + | |
403 | 'INNER JOIN "account" ON "account"."id" = "videoChannel"."accountId" ' + | |
404 | 'INNER JOIN "actor" ON "account"."actorId" = "actor"."id" ' + | |
405 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "actor"."id" ' + | |
406 | 'WHERE "actorFollow"."actorId" = ' + actorIdNumber + | |
407 | localVideosReq + | |
408 | ')' | |
409 | ) | |
410 | } | |
b6314e3c | 411 | }) |
687d638c C |
412 | } |
413 | ||
48dce1c9 | 414 | if (options.withFiles === true) { |
3caf77d3 C |
415 | whereAnd.push({ |
416 | id: { | |
417 | [ Op.in ]: Sequelize.literal( | |
418 | '(SELECT "videoId" FROM "videoFile")' | |
419 | ) | |
420 | } | |
244e76a5 RK |
421 | }) |
422 | } | |
423 | ||
d525fc39 C |
424 | // FIXME: issues with sequelize count when making a join on n:m relation, so we just make a IN() |
425 | if (options.tagsAllOf || options.tagsOneOf) { | |
d525fc39 | 426 | if (options.tagsOneOf) { |
3caf77d3 C |
427 | whereAnd.push({ |
428 | id: { | |
429 | [ Op.in ]: Sequelize.literal( | |
430 | '(' + | |
431 | 'SELECT "videoId" FROM "videoTag" ' + | |
432 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
433 | 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsOneOf) + ')' + | |
434 | ')' | |
435 | ) | |
436 | } | |
b6314e3c | 437 | }) |
d525fc39 C |
438 | } |
439 | ||
440 | if (options.tagsAllOf) { | |
3caf77d3 C |
441 | whereAnd.push({ |
442 | id: { | |
443 | [ Op.in ]: Sequelize.literal( | |
444 | '(' + | |
445 | 'SELECT "videoId" FROM "videoTag" ' + | |
446 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
447 | 'WHERE "tag"."name" IN (' + createSafeIn(VideoModel, options.tagsAllOf) + ')' + | |
448 | 'GROUP BY "videoTag"."videoId" HAVING COUNT(*) = ' + options.tagsAllOf.length + | |
449 | ')' | |
450 | ) | |
451 | } | |
b6314e3c | 452 | }) |
d525fc39 C |
453 | } |
454 | } | |
455 | ||
456 | if (options.nsfw === true || options.nsfw === false) { | |
3caf77d3 | 457 | whereAnd.push({ nsfw: options.nsfw }) |
d525fc39 C |
458 | } |
459 | ||
460 | if (options.categoryOneOf) { | |
3caf77d3 C |
461 | whereAnd.push({ |
462 | category: { | |
463 | [ Op.or ]: options.categoryOneOf | |
464 | } | |
465 | }) | |
d525fc39 C |
466 | } |
467 | ||
468 | if (options.licenceOneOf) { | |
3caf77d3 C |
469 | whereAnd.push({ |
470 | licence: { | |
471 | [ Op.or ]: options.licenceOneOf | |
472 | } | |
473 | }) | |
0883b324 C |
474 | } |
475 | ||
d525fc39 | 476 | if (options.languageOneOf) { |
3caf77d3 C |
477 | let videoLanguages = options.languageOneOf |
478 | if (options.languageOneOf.find(l => l === '_unknown')) { | |
479 | videoLanguages = videoLanguages.concat([ null ]) | |
d525fc39 | 480 | } |
3caf77d3 C |
481 | |
482 | whereAnd.push({ | |
483 | [Op.or]: [ | |
484 | { | |
485 | language: { | |
486 | [ Op.or ]: videoLanguages | |
487 | } | |
488 | }, | |
489 | { | |
490 | id: { | |
491 | [ Op.in ]: Sequelize.literal( | |
492 | '(' + | |
493 | 'SELECT "videoId" FROM "videoCaption" ' + | |
494 | 'WHERE "language" IN (' + createSafeIn(VideoModel, options.languageOneOf) + ') ' + | |
495 | ')' | |
496 | ) | |
497 | } | |
498 | } | |
499 | ] | |
500 | }) | |
61b909b9 P |
501 | } |
502 | ||
9a629c6e | 503 | if (options.trendingDays) { |
b36f41ca | 504 | query.include.push(VideoModel.buildTrendingQuery(options.trendingDays)) |
9a629c6e C |
505 | |
506 | query.subQuery = false | |
507 | } | |
508 | ||
8b9a525a C |
509 | if (options.historyOfUser) { |
510 | query.include.push({ | |
511 | model: UserVideoHistoryModel, | |
512 | required: true, | |
513 | where: { | |
514 | userId: options.historyOfUser.id | |
515 | } | |
516 | }) | |
80bfd33c C |
517 | |
518 | // Even if the relation is n:m, we know that a user only have 0..1 video history | |
519 | // So we won't have multiple rows for the same video | |
520 | // Without this, we would not be able to sort on "updatedAt" column of UserVideoHistoryModel | |
521 | query.subQuery = false | |
8b9a525a C |
522 | } |
523 | ||
3caf77d3 C |
524 | query.where = { |
525 | [ Op.and ]: whereAnd | |
526 | } | |
527 | ||
244e76a5 RK |
528 | return query |
529 | }, | |
e8bafea3 C |
530 | [ ScopeNames.WITH_THUMBNAILS ]: { |
531 | include: [ | |
532 | { | |
3acc5084 | 533 | model: ThumbnailModel, |
e8bafea3 C |
534 | required: false |
535 | } | |
536 | ] | |
537 | }, | |
09209296 C |
538 | [ ScopeNames.WITH_USER_ID ]: { |
539 | include: [ | |
540 | { | |
541 | attributes: [ 'accountId' ], | |
3acc5084 | 542 | model: VideoChannelModel.unscoped(), |
09209296 C |
543 | required: true, |
544 | include: [ | |
545 | { | |
546 | attributes: [ 'userId' ], | |
3acc5084 | 547 | model: AccountModel.unscoped(), |
09209296 C |
548 | required: true |
549 | } | |
550 | ] | |
551 | } | |
3acc5084 | 552 | ] |
09209296 | 553 | }, |
8ea6f49a | 554 | [ ScopeNames.WITH_ACCOUNT_DETAILS ]: { |
d48ff09d C |
555 | include: [ |
556 | { | |
3acc5084 | 557 | model: VideoChannelModel.unscoped(), |
d48ff09d C |
558 | required: true, |
559 | include: [ | |
6120941f C |
560 | { |
561 | attributes: { | |
562 | exclude: [ 'privateKey', 'publicKey' ] | |
563 | }, | |
3acc5084 | 564 | model: ActorModel.unscoped(), |
3e500247 C |
565 | required: true, |
566 | include: [ | |
567 | { | |
568 | attributes: [ 'host' ], | |
3acc5084 | 569 | model: ServerModel.unscoped(), |
3e500247 | 570 | required: false |
52d9f792 C |
571 | }, |
572 | { | |
3acc5084 | 573 | model: AvatarModel.unscoped(), |
52d9f792 | 574 | required: false |
3e500247 C |
575 | } |
576 | ] | |
6120941f | 577 | }, |
d48ff09d | 578 | { |
3acc5084 | 579 | model: AccountModel.unscoped(), |
d48ff09d C |
580 | required: true, |
581 | include: [ | |
582 | { | |
3acc5084 | 583 | model: ActorModel.unscoped(), |
6120941f C |
584 | attributes: { |
585 | exclude: [ 'privateKey', 'publicKey' ] | |
586 | }, | |
50d6de9c C |
587 | required: true, |
588 | include: [ | |
589 | { | |
3e500247 | 590 | attributes: [ 'host' ], |
3acc5084 | 591 | model: ServerModel.unscoped(), |
50d6de9c | 592 | required: false |
b6a4fd6b C |
593 | }, |
594 | { | |
3acc5084 | 595 | model: AvatarModel.unscoped(), |
b6a4fd6b | 596 | required: false |
50d6de9c C |
597 | } |
598 | ] | |
d48ff09d C |
599 | } |
600 | ] | |
601 | } | |
602 | ] | |
603 | } | |
3acc5084 | 604 | ] |
d48ff09d | 605 | }, |
8ea6f49a | 606 | [ ScopeNames.WITH_TAGS ]: { |
3acc5084 | 607 | include: [ TagModel ] |
d48ff09d | 608 | }, |
8ea6f49a | 609 | [ ScopeNames.WITH_BLACKLISTED ]: { |
191764f3 C |
610 | include: [ |
611 | { | |
612 | attributes: [ 'id', 'reason' ], | |
3acc5084 | 613 | model: VideoBlacklistModel, |
191764f3 C |
614 | required: false |
615 | } | |
616 | ] | |
617 | }, | |
09209296 C |
618 | [ ScopeNames.WITH_FILES ]: (withRedundancies = false) => { |
619 | let subInclude: any[] = [] | |
620 | ||
621 | if (withRedundancies === true) { | |
622 | subInclude = [ | |
623 | { | |
624 | attributes: [ 'fileUrl' ], | |
625 | model: VideoRedundancyModel.unscoped(), | |
626 | required: false | |
627 | } | |
628 | ] | |
629 | } | |
630 | ||
631 | return { | |
632 | include: [ | |
633 | { | |
634 | model: VideoFileModel.unscoped(), | |
3acc5084 | 635 | separate: true, // We may have multiple files, having multiple redundancies so let's separate this join |
09209296 C |
636 | required: false, |
637 | include: subInclude | |
638 | } | |
639 | ] | |
640 | } | |
641 | }, | |
642 | [ ScopeNames.WITH_STREAMING_PLAYLISTS ]: (withRedundancies = false) => { | |
643 | let subInclude: any[] = [] | |
644 | ||
645 | if (withRedundancies === true) { | |
646 | subInclude = [ | |
647 | { | |
648 | attributes: [ 'fileUrl' ], | |
649 | model: VideoRedundancyModel.unscoped(), | |
650 | required: false | |
651 | } | |
652 | ] | |
653 | } | |
654 | ||
655 | return { | |
656 | include: [ | |
657 | { | |
658 | model: VideoStreamingPlaylistModel.unscoped(), | |
3acc5084 | 659 | separate: true, // We may have multiple streaming playlists, having multiple redundancies so let's separate this join |
09209296 C |
660 | required: false, |
661 | include: subInclude | |
662 | } | |
663 | ] | |
664 | } | |
bbe0f064 | 665 | }, |
8ea6f49a | 666 | [ ScopeNames.WITH_SCHEDULED_UPDATE ]: { |
bbe0f064 C |
667 | include: [ |
668 | { | |
3acc5084 | 669 | model: ScheduleVideoUpdateModel.unscoped(), |
bbe0f064 C |
670 | required: false |
671 | } | |
672 | ] | |
6e46de09 C |
673 | }, |
674 | [ ScopeNames.WITH_USER_HISTORY ]: (userId: number) => { | |
675 | return { | |
676 | include: [ | |
677 | { | |
678 | attributes: [ 'currentTime' ], | |
679 | model: UserVideoHistoryModel.unscoped(), | |
680 | required: false, | |
681 | where: { | |
682 | userId | |
683 | } | |
684 | } | |
685 | ] | |
686 | } | |
d48ff09d | 687 | } |
3acc5084 | 688 | })) |
3fd3ab2d C |
689 | @Table({ |
690 | tableName: 'video', | |
57c36b27 | 691 | indexes |
3fd3ab2d C |
692 | }) |
693 | export class VideoModel extends Model<VideoModel> { | |
694 | ||
695 | @AllowNull(false) | |
696 | @Default(DataType.UUIDV4) | |
697 | @IsUUID(4) | |
698 | @Column(DataType.UUID) | |
699 | uuid: string | |
700 | ||
701 | @AllowNull(false) | |
702 | @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name')) | |
703 | @Column | |
704 | name: string | |
705 | ||
706 | @AllowNull(true) | |
707 | @Default(null) | |
1735c825 | 708 | @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category', true)) |
3fd3ab2d C |
709 | @Column |
710 | category: number | |
711 | ||
712 | @AllowNull(true) | |
713 | @Default(null) | |
1735c825 | 714 | @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence', true)) |
3fd3ab2d C |
715 | @Column |
716 | licence: number | |
717 | ||
718 | @AllowNull(true) | |
719 | @Default(null) | |
1735c825 | 720 | @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language', true)) |
9d3ef9fe C |
721 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.LANGUAGE.max)) |
722 | language: string | |
3fd3ab2d C |
723 | |
724 | @AllowNull(false) | |
725 | @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy')) | |
726 | @Column | |
727 | privacy: number | |
728 | ||
729 | @AllowNull(false) | |
47564bbe | 730 | @Is('VideoNSFW', value => throwIfNotValid(value, isBooleanValid, 'NSFW boolean')) |
3fd3ab2d C |
731 | @Column |
732 | nsfw: boolean | |
733 | ||
734 | @AllowNull(true) | |
735 | @Default(null) | |
1735c825 | 736 | @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description', true)) |
3fd3ab2d C |
737 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max)) |
738 | description: string | |
739 | ||
2422c46b C |
740 | @AllowNull(true) |
741 | @Default(null) | |
1735c825 | 742 | @Is('VideoSupport', value => throwIfNotValid(value, isVideoSupportValid, 'support', true)) |
2422c46b C |
743 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.SUPPORT.max)) |
744 | support: string | |
745 | ||
3fd3ab2d C |
746 | @AllowNull(false) |
747 | @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration')) | |
748 | @Column | |
749 | duration: number | |
750 | ||
751 | @AllowNull(false) | |
752 | @Default(0) | |
753 | @IsInt | |
754 | @Min(0) | |
755 | @Column | |
756 | views: number | |
757 | ||
758 | @AllowNull(false) | |
759 | @Default(0) | |
760 | @IsInt | |
761 | @Min(0) | |
762 | @Column | |
763 | likes: number | |
764 | ||
765 | @AllowNull(false) | |
766 | @Default(0) | |
767 | @IsInt | |
768 | @Min(0) | |
769 | @Column | |
770 | dislikes: number | |
771 | ||
772 | @AllowNull(false) | |
773 | @Column | |
774 | remote: boolean | |
775 | ||
776 | @AllowNull(false) | |
777 | @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | |
778 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max)) | |
779 | url: string | |
780 | ||
47564bbe C |
781 | @AllowNull(false) |
782 | @Column | |
783 | commentsEnabled: boolean | |
784 | ||
156c50af LD |
785 | @AllowNull(false) |
786 | @Column | |
7f2cfe3a | 787 | downloadEnabled: boolean |
156c50af | 788 | |
2186386c C |
789 | @AllowNull(false) |
790 | @Column | |
791 | waitTranscoding: boolean | |
792 | ||
793 | @AllowNull(false) | |
794 | @Default(null) | |
795 | @Is('VideoState', value => throwIfNotValid(value, isVideoStateValid, 'state')) | |
796 | @Column | |
797 | state: VideoState | |
798 | ||
3fd3ab2d C |
799 | @CreatedAt |
800 | createdAt: Date | |
801 | ||
802 | @UpdatedAt | |
803 | updatedAt: Date | |
804 | ||
2922e048 | 805 | @AllowNull(false) |
1735c825 | 806 | @Default(DataType.NOW) |
2922e048 JLB |
807 | @Column |
808 | publishedAt: Date | |
809 | ||
7519127b C |
810 | @AllowNull(true) |
811 | @Default(null) | |
c8034165 | 812 | @Column |
813 | originallyPublishedAt: Date | |
814 | ||
3fd3ab2d C |
815 | @ForeignKey(() => VideoChannelModel) |
816 | @Column | |
817 | channelId: number | |
818 | ||
819 | @BelongsTo(() => VideoChannelModel, { | |
feb4bdfd | 820 | foreignKey: { |
50d6de9c | 821 | allowNull: true |
feb4bdfd | 822 | }, |
6b738c7a | 823 | hooks: true |
feb4bdfd | 824 | }) |
3fd3ab2d | 825 | VideoChannel: VideoChannelModel |
7920c273 | 826 | |
3fd3ab2d | 827 | @BelongsToMany(() => TagModel, { |
7920c273 | 828 | foreignKey: 'videoId', |
3fd3ab2d C |
829 | through: () => VideoTagModel, |
830 | onDelete: 'CASCADE' | |
7920c273 | 831 | }) |
3fd3ab2d | 832 | Tags: TagModel[] |
55fa55a9 | 833 | |
e8bafea3 C |
834 | @HasMany(() => ThumbnailModel, { |
835 | foreignKey: { | |
836 | name: 'videoId', | |
837 | allowNull: true | |
838 | }, | |
839 | hooks: true, | |
840 | onDelete: 'cascade' | |
841 | }) | |
842 | Thumbnails: ThumbnailModel[] | |
843 | ||
418d092a C |
844 | @HasMany(() => VideoPlaylistElementModel, { |
845 | foreignKey: { | |
846 | name: 'videoId', | |
847 | allowNull: false | |
848 | }, | |
849 | onDelete: 'cascade' | |
850 | }) | |
851 | VideoPlaylistElements: VideoPlaylistElementModel[] | |
852 | ||
3fd3ab2d | 853 | @HasMany(() => VideoAbuseModel, { |
55fa55a9 C |
854 | foreignKey: { |
855 | name: 'videoId', | |
856 | allowNull: false | |
857 | }, | |
858 | onDelete: 'cascade' | |
859 | }) | |
3fd3ab2d | 860 | VideoAbuses: VideoAbuseModel[] |
93e1258c | 861 | |
3fd3ab2d | 862 | @HasMany(() => VideoFileModel, { |
93e1258c C |
863 | foreignKey: { |
864 | name: 'videoId', | |
865 | allowNull: false | |
866 | }, | |
c48e82b5 | 867 | hooks: true, |
93e1258c C |
868 | onDelete: 'cascade' |
869 | }) | |
3fd3ab2d | 870 | VideoFiles: VideoFileModel[] |
e71bcc0f | 871 | |
09209296 C |
872 | @HasMany(() => VideoStreamingPlaylistModel, { |
873 | foreignKey: { | |
874 | name: 'videoId', | |
875 | allowNull: false | |
876 | }, | |
877 | hooks: true, | |
878 | onDelete: 'cascade' | |
879 | }) | |
880 | VideoStreamingPlaylists: VideoStreamingPlaylistModel[] | |
881 | ||
3fd3ab2d | 882 | @HasMany(() => VideoShareModel, { |
e71bcc0f C |
883 | foreignKey: { |
884 | name: 'videoId', | |
885 | allowNull: false | |
886 | }, | |
887 | onDelete: 'cascade' | |
888 | }) | |
3fd3ab2d | 889 | VideoShares: VideoShareModel[] |
16b90975 | 890 | |
3fd3ab2d | 891 | @HasMany(() => AccountVideoRateModel, { |
16b90975 C |
892 | foreignKey: { |
893 | name: 'videoId', | |
894 | allowNull: false | |
895 | }, | |
896 | onDelete: 'cascade' | |
897 | }) | |
3fd3ab2d | 898 | AccountVideoRates: AccountVideoRateModel[] |
f285faa0 | 899 | |
da854ddd C |
900 | @HasMany(() => VideoCommentModel, { |
901 | foreignKey: { | |
902 | name: 'videoId', | |
903 | allowNull: false | |
904 | }, | |
f05a1c30 C |
905 | onDelete: 'cascade', |
906 | hooks: true | |
da854ddd C |
907 | }) |
908 | VideoComments: VideoCommentModel[] | |
909 | ||
9a629c6e C |
910 | @HasMany(() => VideoViewModel, { |
911 | foreignKey: { | |
912 | name: 'videoId', | |
913 | allowNull: false | |
914 | }, | |
6e46de09 | 915 | onDelete: 'cascade' |
9a629c6e C |
916 | }) |
917 | VideoViews: VideoViewModel[] | |
918 | ||
6e46de09 C |
919 | @HasMany(() => UserVideoHistoryModel, { |
920 | foreignKey: { | |
921 | name: 'videoId', | |
922 | allowNull: false | |
923 | }, | |
924 | onDelete: 'cascade' | |
925 | }) | |
926 | UserVideoHistories: UserVideoHistoryModel[] | |
927 | ||
2baea0c7 C |
928 | @HasOne(() => ScheduleVideoUpdateModel, { |
929 | foreignKey: { | |
930 | name: 'videoId', | |
931 | allowNull: false | |
932 | }, | |
933 | onDelete: 'cascade' | |
934 | }) | |
935 | ScheduleVideoUpdate: ScheduleVideoUpdateModel | |
936 | ||
26b7305a C |
937 | @HasOne(() => VideoBlacklistModel, { |
938 | foreignKey: { | |
939 | name: 'videoId', | |
940 | allowNull: false | |
941 | }, | |
942 | onDelete: 'cascade' | |
943 | }) | |
944 | VideoBlacklist: VideoBlacklistModel | |
945 | ||
dc133480 C |
946 | @HasOne(() => VideoImportModel, { |
947 | foreignKey: { | |
948 | name: 'videoId', | |
949 | allowNull: true | |
950 | }, | |
951 | onDelete: 'set null' | |
952 | }) | |
953 | VideoImport: VideoImportModel | |
954 | ||
40e87e9e C |
955 | @HasMany(() => VideoCaptionModel, { |
956 | foreignKey: { | |
957 | name: 'videoId', | |
958 | allowNull: false | |
959 | }, | |
960 | onDelete: 'cascade', | |
961 | hooks: true, | |
8ea6f49a | 962 | [ 'separate' as any ]: true |
40e87e9e C |
963 | }) |
964 | VideoCaptions: VideoCaptionModel[] | |
965 | ||
f05a1c30 C |
966 | @BeforeDestroy |
967 | static async sendDelete (instance: VideoModel, options) { | |
968 | if (instance.isOwned()) { | |
969 | if (!instance.VideoChannel) { | |
970 | instance.VideoChannel = await instance.$get('VideoChannel', { | |
971 | include: [ | |
972 | { | |
973 | model: AccountModel, | |
974 | include: [ ActorModel ] | |
975 | } | |
976 | ], | |
977 | transaction: options.transaction | |
978 | }) as VideoChannelModel | |
979 | } | |
980 | ||
f05a1c30 C |
981 | return sendDeleteVideo(instance, options.transaction) |
982 | } | |
983 | ||
984 | return undefined | |
985 | } | |
986 | ||
6b738c7a | 987 | @BeforeDestroy |
40e87e9e | 988 | static async removeFiles (instance: VideoModel) { |
f05a1c30 | 989 | const tasks: Promise<any>[] = [] |
f285faa0 | 990 | |
8e0fd45e | 991 | logger.info('Removing files of video %s.', instance.url) |
6b738c7a | 992 | |
3fd3ab2d | 993 | if (instance.isOwned()) { |
f05a1c30 C |
994 | if (!Array.isArray(instance.VideoFiles)) { |
995 | instance.VideoFiles = await instance.$get('VideoFiles') as VideoFileModel[] | |
996 | } | |
997 | ||
3fd3ab2d C |
998 | // Remove physical files and torrents |
999 | instance.VideoFiles.forEach(file => { | |
1000 | tasks.push(instance.removeFile(file)) | |
1001 | tasks.push(instance.removeTorrent(file)) | |
1002 | }) | |
09209296 C |
1003 | |
1004 | // Remove playlists file | |
1005 | tasks.push(instance.removeStreamingPlaylist()) | |
3fd3ab2d | 1006 | } |
40298b02 | 1007 | |
6b738c7a C |
1008 | // Do not wait video deletion because we could be in a transaction |
1009 | Promise.all(tasks) | |
8ea6f49a C |
1010 | .catch(err => { |
1011 | logger.error('Some errors when removing files of video %s in before destroy hook.', instance.uuid, { err }) | |
1012 | }) | |
6b738c7a C |
1013 | |
1014 | return undefined | |
3fd3ab2d | 1015 | } |
f285faa0 | 1016 | |
9f1ddd24 C |
1017 | static listLocal () { |
1018 | const query = { | |
1019 | where: { | |
1020 | remote: false | |
1021 | } | |
1022 | } | |
1023 | ||
e8bafea3 C |
1024 | return VideoModel.scope([ |
1025 | ScopeNames.WITH_FILES, | |
1026 | ScopeNames.WITH_STREAMING_PLAYLISTS, | |
1027 | ScopeNames.WITH_THUMBNAILS | |
1028 | ]).findAll(query) | |
9f1ddd24 C |
1029 | } |
1030 | ||
50d6de9c | 1031 | static listAllAndSharedByActorForOutbox (actorId: number, start: number, count: number) { |
3fd3ab2d C |
1032 | function getRawQuery (select: string) { |
1033 | const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' + | |
1034 | 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' + | |
50d6de9c C |
1035 | 'INNER JOIN "account" AS "Account" ON "Account"."id" = "VideoChannel"."accountId" ' + |
1036 | 'WHERE "Account"."actorId" = ' + actorId | |
3fd3ab2d C |
1037 | const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' + |
1038 | 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' + | |
50d6de9c | 1039 | 'WHERE "VideoShare"."actorId" = ' + actorId |
558d7c23 | 1040 | |
3fd3ab2d C |
1041 | return `(${queryVideo}) UNION (${queryVideoShare})` |
1042 | } | |
aaf61f38 | 1043 | |
3fd3ab2d C |
1044 | const rawQuery = getRawQuery('"Video"."id"') |
1045 | const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"') | |
1046 | ||
1047 | const query = { | |
1048 | distinct: true, | |
1049 | offset: start, | |
1050 | limit: count, | |
1735c825 | 1051 | order: getVideoSort('createdAt', [ 'Tags', 'name', 'ASC' ] as any), // FIXME: sequelize typings |
3fd3ab2d C |
1052 | where: { |
1053 | id: { | |
1735c825 | 1054 | [ Op.in ]: Sequelize.literal('(' + rawQuery + ')') |
3c75ce12 | 1055 | }, |
1735c825 | 1056 | [ Op.or ]: [ |
3c75ce12 C |
1057 | { privacy: VideoPrivacy.PUBLIC }, |
1058 | { privacy: VideoPrivacy.UNLISTED } | |
1059 | ] | |
3fd3ab2d C |
1060 | }, |
1061 | include: [ | |
40e87e9e C |
1062 | { |
1063 | attributes: [ 'language' ], | |
1064 | model: VideoCaptionModel.unscoped(), | |
1065 | required: false | |
1066 | }, | |
3fd3ab2d | 1067 | { |
1d230c44 | 1068 | attributes: [ 'id', 'url' ], |
2c897999 | 1069 | model: VideoShareModel.unscoped(), |
3fd3ab2d | 1070 | required: false, |
e3d5ea4f C |
1071 | // We only want videos shared by this actor |
1072 | where: { | |
1735c825 | 1073 | [ Op.and ]: [ |
e3d5ea4f C |
1074 | { |
1075 | id: { | |
1735c825 | 1076 | [ Op.not ]: null |
e3d5ea4f C |
1077 | } |
1078 | }, | |
1079 | { | |
1080 | actorId | |
1081 | } | |
1082 | ] | |
1083 | }, | |
50d6de9c C |
1084 | include: [ |
1085 | { | |
2c897999 C |
1086 | attributes: [ 'id', 'url' ], |
1087 | model: ActorModel.unscoped() | |
50d6de9c C |
1088 | } |
1089 | ] | |
3fd3ab2d C |
1090 | }, |
1091 | { | |
2c897999 | 1092 | model: VideoChannelModel.unscoped(), |
3fd3ab2d C |
1093 | required: true, |
1094 | include: [ | |
1095 | { | |
2c897999 C |
1096 | attributes: [ 'name' ], |
1097 | model: AccountModel.unscoped(), | |
1098 | required: true, | |
1099 | include: [ | |
1100 | { | |
e3d5ea4f | 1101 | attributes: [ 'id', 'url', 'followersUrl' ], |
2c897999 C |
1102 | model: ActorModel.unscoped(), |
1103 | required: true | |
1104 | } | |
1105 | ] | |
1106 | }, | |
1107 | { | |
e3d5ea4f | 1108 | attributes: [ 'id', 'url', 'followersUrl' ], |
2c897999 | 1109 | model: ActorModel.unscoped(), |
3fd3ab2d C |
1110 | required: true |
1111 | } | |
1112 | ] | |
1113 | }, | |
3fd3ab2d | 1114 | VideoFileModel, |
2c897999 | 1115 | TagModel |
3fd3ab2d C |
1116 | ] |
1117 | } | |
164174a6 | 1118 | |
3fd3ab2d | 1119 | return Bluebird.all([ |
3acc5084 C |
1120 | VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findAll(query), |
1121 | VideoModel.sequelize.query<{ total: string }>(rawCountQuery, { type: QueryTypes.SELECT }) | |
3fd3ab2d C |
1122 | ]).then(([ rows, totals ]) => { |
1123 | // totals: totalVideos + totalVideoShares | |
1124 | let totalVideos = 0 | |
1125 | let totalVideoShares = 0 | |
3acc5084 C |
1126 | if (totals[ 0 ]) totalVideos = parseInt(totals[ 0 ].total, 10) |
1127 | if (totals[ 1 ]) totalVideoShares = parseInt(totals[ 1 ].total, 10) | |
3fd3ab2d C |
1128 | |
1129 | const total = totalVideos + totalVideoShares | |
1130 | return { | |
1131 | data: rows, | |
1132 | total: total | |
1133 | } | |
1134 | }) | |
1135 | } | |
93e1258c | 1136 | |
26b7305a | 1137 | static listUserVideosForApi (accountId: number, start: number, count: number, sort: string, withFiles = false) { |
3acc5084 C |
1138 | function buildBaseQuery (): FindOptions { |
1139 | return { | |
1140 | offset: start, | |
1141 | limit: count, | |
1142 | order: getVideoSort(sort), | |
1143 | include: [ | |
1144 | { | |
1145 | model: VideoChannelModel, | |
1146 | required: true, | |
1147 | include: [ | |
1148 | { | |
1149 | model: AccountModel, | |
1150 | where: { | |
1151 | id: accountId | |
1152 | }, | |
1153 | required: true | |
1154 | } | |
1155 | ] | |
1156 | } | |
1157 | ] | |
1158 | } | |
3fd3ab2d | 1159 | } |
d8755eed | 1160 | |
3acc5084 C |
1161 | const countQuery = buildBaseQuery() |
1162 | const findQuery = buildBaseQuery() | |
1163 | ||
a18f275d C |
1164 | const findScopes = [ |
1165 | ScopeNames.WITH_SCHEDULED_UPDATE, | |
1166 | ScopeNames.WITH_BLACKLISTED, | |
1167 | ScopeNames.WITH_THUMBNAILS | |
1168 | ] | |
3acc5084 | 1169 | |
244e76a5 | 1170 | if (withFiles === true) { |
3acc5084 | 1171 | findQuery.include.push({ |
244e76a5 RK |
1172 | model: VideoFileModel.unscoped(), |
1173 | required: true | |
1174 | }) | |
1175 | } | |
1176 | ||
3acc5084 C |
1177 | return Promise.all([ |
1178 | VideoModel.count(countQuery), | |
a18f275d | 1179 | VideoModel.scope(findScopes).findAll(findQuery) |
3acc5084 C |
1180 | ]).then(([ count, rows ]) => { |
1181 | return { | |
1182 | data: rows, | |
1183 | total: count | |
1184 | } | |
1185 | }) | |
3fd3ab2d | 1186 | } |
93e1258c | 1187 | |
48dce1c9 | 1188 | static async listForApi (options: { |
0626e7af C |
1189 | start: number, |
1190 | count: number, | |
1191 | sort: string, | |
d525fc39 | 1192 | nsfw: boolean, |
06a05d5f | 1193 | includeLocalVideos: boolean, |
48dce1c9 | 1194 | withFiles: boolean, |
d525fc39 C |
1195 | categoryOneOf?: number[], |
1196 | licenceOneOf?: number[], | |
1197 | languageOneOf?: string[], | |
1198 | tagsOneOf?: string[], | |
1199 | tagsAllOf?: string[], | |
0626e7af | 1200 | filter?: VideoFilter, |
48dce1c9 | 1201 | accountId?: number, |
06a05d5f | 1202 | videoChannelId?: number, |
4e74e803 | 1203 | followerActorId?: number |
418d092a | 1204 | videoPlaylistId?: number, |
6e46de09 | 1205 | trendingDays?: number, |
8b9a525a C |
1206 | user?: UserModel, |
1207 | historyOfUser?: UserModel | |
7348b1fd | 1208 | }, countVideos = true) { |
7ad9b984 C |
1209 | if (options.filter && options.filter === 'all-local' && !options.user.hasRight(UserRight.SEE_ALL_VIDEOS)) { |
1210 | throw new Error('Try to filter all-local but no user has not the see all videos right') | |
1cd3facc C |
1211 | } |
1212 | ||
3caf77d3 | 1213 | const query: FindOptions & { where?: null } = { |
48dce1c9 C |
1214 | offset: options.start, |
1215 | limit: options.count, | |
9a629c6e C |
1216 | order: getVideoSort(options.sort) |
1217 | } | |
1218 | ||
1219 | let trendingDays: number | |
1220 | if (options.sort.endsWith('trending')) { | |
1221 | trendingDays = CONFIG.TRENDING.VIDEOS.INTERVAL_DAYS | |
1222 | ||
1223 | query.group = 'VideoModel.id' | |
3fd3ab2d | 1224 | } |
93e1258c | 1225 | |
7ad9b984 C |
1226 | const serverActor = await getServerActor() |
1227 | ||
4e74e803 C |
1228 | // followerActorId === null has a meaning, so just check undefined |
1229 | const followerActorId = options.followerActorId !== undefined ? options.followerActorId : serverActor.id | |
06a05d5f | 1230 | |
afd2cba5 | 1231 | const queryOptions = { |
4e74e803 | 1232 | followerActorId, |
7ad9b984 | 1233 | serverAccountId: serverActor.Account.id, |
afd2cba5 C |
1234 | nsfw: options.nsfw, |
1235 | categoryOneOf: options.categoryOneOf, | |
1236 | licenceOneOf: options.licenceOneOf, | |
1237 | languageOneOf: options.languageOneOf, | |
1238 | tagsOneOf: options.tagsOneOf, | |
1239 | tagsAllOf: options.tagsAllOf, | |
1240 | filter: options.filter, | |
1241 | withFiles: options.withFiles, | |
1242 | accountId: options.accountId, | |
1243 | videoChannelId: options.videoChannelId, | |
418d092a | 1244 | videoPlaylistId: options.videoPlaylistId, |
9a629c6e | 1245 | includeLocalVideos: options.includeLocalVideos, |
7ad9b984 | 1246 | user: options.user, |
8b9a525a | 1247 | historyOfUser: options.historyOfUser, |
9a629c6e | 1248 | trendingDays |
48dce1c9 C |
1249 | } |
1250 | ||
7348b1fd | 1251 | return VideoModel.getAvailableForApi(query, queryOptions, countVideos) |
93e1258c C |
1252 | } |
1253 | ||
0b18f4aa | 1254 | static async searchAndPopulateAccountAndServer (options: { |
06a05d5f | 1255 | includeLocalVideos: boolean |
d4112450 | 1256 | search?: string |
0b18f4aa C |
1257 | start?: number |
1258 | count?: number | |
1259 | sort?: string | |
1260 | startDate?: string // ISO 8601 | |
1261 | endDate?: string // ISO 8601 | |
31d065cc AM |
1262 | originallyPublishedStartDate?: string |
1263 | originallyPublishedEndDate?: string | |
0b18f4aa C |
1264 | nsfw?: boolean |
1265 | categoryOneOf?: number[] | |
1266 | licenceOneOf?: number[] | |
1267 | languageOneOf?: string[] | |
1268 | tagsOneOf?: string[] | |
1269 | tagsAllOf?: string[] | |
1270 | durationMin?: number // seconds | |
1271 | durationMax?: number // seconds | |
7ad9b984 | 1272 | user?: UserModel, |
1cd3facc | 1273 | filter?: VideoFilter |
0b18f4aa | 1274 | }) { |
8ea6f49a | 1275 | const whereAnd = [] |
d525fc39 C |
1276 | |
1277 | if (options.startDate || options.endDate) { | |
8ea6f49a | 1278 | const publishedAtRange = {} |
d525fc39 | 1279 | |
1735c825 C |
1280 | if (options.startDate) publishedAtRange[ Op.gte ] = options.startDate |
1281 | if (options.endDate) publishedAtRange[ Op.lte ] = options.endDate | |
d525fc39 C |
1282 | |
1283 | whereAnd.push({ publishedAt: publishedAtRange }) | |
1284 | } | |
1285 | ||
31d065cc AM |
1286 | if (options.originallyPublishedStartDate || options.originallyPublishedEndDate) { |
1287 | const originallyPublishedAtRange = {} | |
1288 | ||
1735c825 C |
1289 | if (options.originallyPublishedStartDate) originallyPublishedAtRange[ Op.gte ] = options.originallyPublishedStartDate |
1290 | if (options.originallyPublishedEndDate) originallyPublishedAtRange[ Op.lte ] = options.originallyPublishedEndDate | |
31d065cc AM |
1291 | |
1292 | whereAnd.push({ originallyPublishedAt: originallyPublishedAtRange }) | |
1293 | } | |
1294 | ||
d525fc39 | 1295 | if (options.durationMin || options.durationMax) { |
8ea6f49a | 1296 | const durationRange = {} |
d525fc39 | 1297 | |
1735c825 C |
1298 | if (options.durationMin) durationRange[ Op.gte ] = options.durationMin |
1299 | if (options.durationMax) durationRange[ Op.lte ] = options.durationMax | |
d525fc39 C |
1300 | |
1301 | whereAnd.push({ duration: durationRange }) | |
1302 | } | |
1303 | ||
d4112450 | 1304 | const attributesInclude = [] |
dbfd3e9b C |
1305 | const escapedSearch = VideoModel.sequelize.escape(options.search) |
1306 | const escapedLikeSearch = VideoModel.sequelize.escape('%' + options.search + '%') | |
d4112450 C |
1307 | if (options.search) { |
1308 | whereAnd.push( | |
1309 | { | |
dbfd3e9b | 1310 | id: { |
1735c825 | 1311 | [ Op.in ]: Sequelize.literal( |
dbfd3e9b | 1312 | '(' + |
8ea6f49a C |
1313 | 'SELECT "video"."id" FROM "video" ' + |
1314 | 'WHERE ' + | |
1315 | 'lower(immutable_unaccent("video"."name")) % lower(immutable_unaccent(' + escapedSearch + ')) OR ' + | |
1316 | 'lower(immutable_unaccent("video"."name")) LIKE lower(immutable_unaccent(' + escapedLikeSearch + '))' + | |
1317 | 'UNION ALL ' + | |
1318 | 'SELECT "video"."id" FROM "video" LEFT JOIN "videoTag" ON "videoTag"."videoId" = "video"."id" ' + | |
1319 | 'INNER JOIN "tag" ON "tag"."id" = "videoTag"."tagId" ' + | |
1320 | 'WHERE "tag"."name" = ' + escapedSearch + | |
dbfd3e9b C |
1321 | ')' |
1322 | ) | |
1323 | } | |
d4112450 C |
1324 | } |
1325 | ) | |
1326 | ||
1327 | attributesInclude.push(createSimilarityAttribute('VideoModel.name', options.search)) | |
1328 | } | |
1329 | ||
1330 | // Cannot search on similarity if we don't have a search | |
1331 | if (!options.search) { | |
1332 | attributesInclude.push( | |
1333 | Sequelize.literal('0 as similarity') | |
1334 | ) | |
1335 | } | |
d525fc39 | 1336 | |
3caf77d3 | 1337 | const query = { |
57c36b27 | 1338 | attributes: { |
d4112450 | 1339 | include: attributesInclude |
57c36b27 | 1340 | }, |
d525fc39 C |
1341 | offset: options.start, |
1342 | limit: options.count, | |
3caf77d3 | 1343 | order: getVideoSort(options.sort) |
f05a1c30 C |
1344 | } |
1345 | ||
1346 | const serverActor = await getServerActor() | |
afd2cba5 | 1347 | const queryOptions = { |
4e74e803 | 1348 | followerActorId: serverActor.id, |
7ad9b984 | 1349 | serverAccountId: serverActor.Account.id, |
afd2cba5 C |
1350 | includeLocalVideos: options.includeLocalVideos, |
1351 | nsfw: options.nsfw, | |
1352 | categoryOneOf: options.categoryOneOf, | |
1353 | licenceOneOf: options.licenceOneOf, | |
1354 | languageOneOf: options.languageOneOf, | |
1355 | tagsOneOf: options.tagsOneOf, | |
6e46de09 | 1356 | tagsAllOf: options.tagsAllOf, |
7ad9b984 | 1357 | user: options.user, |
3caf77d3 C |
1358 | filter: options.filter, |
1359 | baseWhere: whereAnd | |
48dce1c9 | 1360 | } |
f05a1c30 | 1361 | |
afd2cba5 | 1362 | return VideoModel.getAvailableForApi(query, queryOptions) |
f05a1c30 C |
1363 | } |
1364 | ||
1735c825 | 1365 | static load (id: number | string, t?: Transaction) { |
418d092a | 1366 | const where = buildWhereIdOrUUID(id) |
627621c1 C |
1367 | const options = { |
1368 | where, | |
1369 | transaction: t | |
3fd3ab2d | 1370 | } |
d8755eed | 1371 | |
e8bafea3 | 1372 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) |
3fd3ab2d | 1373 | } |
d8755eed | 1374 | |
1735c825 | 1375 | static loadWithRights (id: number | string, t?: Transaction) { |
418d092a | 1376 | const where = buildWhereIdOrUUID(id) |
09209296 C |
1377 | const options = { |
1378 | where, | |
1379 | transaction: t | |
1380 | } | |
1381 | ||
e8bafea3 C |
1382 | return VideoModel.scope([ |
1383 | ScopeNames.WITH_BLACKLISTED, | |
1384 | ScopeNames.WITH_USER_ID, | |
1385 | ScopeNames.WITH_THUMBNAILS | |
1386 | ]).findOne(options) | |
09209296 C |
1387 | } |
1388 | ||
1735c825 | 1389 | static loadOnlyId (id: number | string, t?: Transaction) { |
418d092a | 1390 | const where = buildWhereIdOrUUID(id) |
627621c1 | 1391 | |
3fd3ab2d | 1392 | const options = { |
627621c1 C |
1393 | attributes: [ 'id' ], |
1394 | where, | |
1395 | transaction: t | |
3fd3ab2d | 1396 | } |
72c7248b | 1397 | |
e8bafea3 | 1398 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) |
627621c1 C |
1399 | } |
1400 | ||
1735c825 | 1401 | static loadWithFiles (id: number, t?: Transaction, logging?: boolean) { |
e8bafea3 C |
1402 | return VideoModel.scope([ |
1403 | ScopeNames.WITH_FILES, | |
1404 | ScopeNames.WITH_STREAMING_PLAYLISTS, | |
1405 | ScopeNames.WITH_THUMBNAILS | |
1406 | ]).findByPk(id, { transaction: t, logging }) | |
3fd3ab2d | 1407 | } |
72c7248b | 1408 | |
627621c1 | 1409 | static loadByUUIDWithFile (uuid: string) { |
8fa5653a C |
1410 | const options = { |
1411 | where: { | |
1412 | uuid | |
1413 | } | |
1414 | } | |
1415 | ||
e8bafea3 | 1416 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(options) |
8fa5653a C |
1417 | } |
1418 | ||
1735c825 C |
1419 | static loadByUrl (url: string, transaction?: Transaction) { |
1420 | const query: FindOptions = { | |
627621c1 C |
1421 | where: { |
1422 | url | |
4157cdb1 C |
1423 | }, |
1424 | transaction | |
627621c1 C |
1425 | } |
1426 | ||
e8bafea3 | 1427 | return VideoModel.scope(ScopeNames.WITH_THUMBNAILS).findOne(query) |
4157cdb1 C |
1428 | } |
1429 | ||
1735c825 C |
1430 | static loadByUrlAndPopulateAccount (url: string, transaction?: Transaction) { |
1431 | const query: FindOptions = { | |
4157cdb1 C |
1432 | where: { |
1433 | url | |
1434 | }, | |
1435 | transaction | |
1436 | } | |
627621c1 | 1437 | |
09209296 C |
1438 | return VideoModel.scope([ |
1439 | ScopeNames.WITH_ACCOUNT_DETAILS, | |
1440 | ScopeNames.WITH_FILES, | |
e8bafea3 C |
1441 | ScopeNames.WITH_STREAMING_PLAYLISTS, |
1442 | ScopeNames.WITH_THUMBNAILS | |
09209296 | 1443 | ]).findOne(query) |
627621c1 C |
1444 | } |
1445 | ||
1735c825 | 1446 | static loadAndPopulateAccountAndServerAndTags (id: number | string, t?: Transaction, userId?: number) { |
418d092a | 1447 | const where = buildWhereIdOrUUID(id) |
627621c1 | 1448 | |
3fd3ab2d | 1449 | const options = { |
3acc5084 | 1450 | order: [ [ 'Tags', 'name', 'ASC' ] ] as any, |
627621c1 | 1451 | where, |
2186386c | 1452 | transaction: t |
3fd3ab2d | 1453 | } |
fd45e8f4 | 1454 | |
3acc5084 | 1455 | const scopes: (string | ScopeOptions)[] = [ |
6e46de09 C |
1456 | ScopeNames.WITH_TAGS, |
1457 | ScopeNames.WITH_BLACKLISTED, | |
09209296 C |
1458 | ScopeNames.WITH_ACCOUNT_DETAILS, |
1459 | ScopeNames.WITH_SCHEDULED_UPDATE, | |
6e46de09 | 1460 | ScopeNames.WITH_FILES, |
e8bafea3 C |
1461 | ScopeNames.WITH_STREAMING_PLAYLISTS, |
1462 | ScopeNames.WITH_THUMBNAILS | |
09209296 C |
1463 | ] |
1464 | ||
1465 | if (userId) { | |
3acc5084 | 1466 | scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] }) |
09209296 C |
1467 | } |
1468 | ||
1469 | return VideoModel | |
1470 | .scope(scopes) | |
1471 | .findOne(options) | |
1472 | } | |
1473 | ||
1735c825 | 1474 | static loadForGetAPI (id: number | string, t?: Transaction, userId?: number) { |
418d092a | 1475 | const where = buildWhereIdOrUUID(id) |
09209296 C |
1476 | |
1477 | const options = { | |
1735c825 | 1478 | order: [ [ 'Tags', 'name', 'ASC' ] ] as any, // FIXME: sequelize typings |
09209296 C |
1479 | where, |
1480 | transaction: t | |
1481 | } | |
1482 | ||
3acc5084 | 1483 | const scopes: (string | ScopeOptions)[] = [ |
09209296 C |
1484 | ScopeNames.WITH_TAGS, |
1485 | ScopeNames.WITH_BLACKLISTED, | |
6e46de09 | 1486 | ScopeNames.WITH_ACCOUNT_DETAILS, |
09209296 | 1487 | ScopeNames.WITH_SCHEDULED_UPDATE, |
e8bafea3 | 1488 | ScopeNames.WITH_THUMBNAILS, |
3acc5084 C |
1489 | { method: [ ScopeNames.WITH_FILES, true ] }, |
1490 | { method: [ ScopeNames.WITH_STREAMING_PLAYLISTS, true ] } | |
6e46de09 C |
1491 | ] |
1492 | ||
1493 | if (userId) { | |
3acc5084 | 1494 | scopes.push({ method: [ ScopeNames.WITH_USER_HISTORY, userId ] }) |
6e46de09 C |
1495 | } |
1496 | ||
d48ff09d | 1497 | return VideoModel |
6e46de09 | 1498 | .scope(scopes) |
da854ddd C |
1499 | .findOne(options) |
1500 | } | |
1501 | ||
09cababd C |
1502 | static async getStats () { |
1503 | const totalLocalVideos = await VideoModel.count({ | |
1504 | where: { | |
1505 | remote: false | |
1506 | } | |
1507 | }) | |
1508 | const totalVideos = await VideoModel.count() | |
1509 | ||
1510 | let totalLocalVideoViews = await VideoModel.sum('views', { | |
1511 | where: { | |
1512 | remote: false | |
1513 | } | |
1514 | }) | |
1515 | // Sequelize could return null... | |
1516 | if (!totalLocalVideoViews) totalLocalVideoViews = 0 | |
1517 | ||
1518 | return { | |
1519 | totalLocalVideos, | |
1520 | totalLocalVideoViews, | |
1521 | totalVideos | |
1522 | } | |
1523 | } | |
1524 | ||
6b616860 C |
1525 | static incrementViews (id: number, views: number) { |
1526 | return VideoModel.increment('views', { | |
1527 | by: views, | |
1528 | where: { | |
1529 | id | |
1530 | } | |
1531 | }) | |
1532 | } | |
1533 | ||
8d427346 C |
1534 | static checkVideoHasInstanceFollow (videoId: number, followerActorId: number) { |
1535 | // Instances only share videos | |
1536 | const query = 'SELECT 1 FROM "videoShare" ' + | |
1537 | 'INNER JOIN "actorFollow" ON "actorFollow"."targetActorId" = "videoShare"."actorId" ' + | |
1538 | 'WHERE "actorFollow"."actorId" = $followerActorId AND "videoShare"."videoId" = $videoId ' + | |
1539 | 'LIMIT 1' | |
1540 | ||
1541 | const options = { | |
1735c825 | 1542 | type: QueryTypes.SELECT, |
8d427346 C |
1543 | bind: { followerActorId, videoId }, |
1544 | raw: true | |
1545 | } | |
1546 | ||
1547 | return VideoModel.sequelize.query(query, options) | |
1548 | .then(results => results.length === 1) | |
1549 | } | |
1550 | ||
7d14d4d2 C |
1551 | static bulkUpdateSupportField (videoChannel: VideoChannelModel, t: Transaction) { |
1552 | const options = { | |
1553 | where: { | |
1554 | channelId: videoChannel.id | |
1555 | }, | |
1556 | transaction: t | |
1557 | } | |
1558 | ||
1559 | return VideoModel.update({ support: videoChannel.support }, options) | |
1560 | } | |
1561 | ||
1562 | static getAllIdsFromChannel (videoChannel: VideoChannelModel) { | |
1563 | const query = { | |
1564 | attributes: [ 'id' ], | |
1565 | where: { | |
1566 | channelId: videoChannel.id | |
1567 | } | |
1568 | } | |
1569 | ||
1570 | return VideoModel.findAll(query) | |
1571 | .then(videos => videos.map(v => v.id)) | |
1572 | } | |
1573 | ||
2d3741d6 | 1574 | // threshold corresponds to how many video the field should have to be returned |
7348b1fd | 1575 | static async getRandomFieldSamples (field: 'category' | 'channelId', threshold: number, count: number) { |
65b21c96 | 1576 | const serverActor = await getServerActor() |
4e74e803 | 1577 | const followerActorId = serverActor.id |
7348b1fd | 1578 | |
65b21c96 C |
1579 | const scopeOptions: AvailableForListIDsOptions = { |
1580 | serverAccountId: serverActor.Account.id, | |
4e74e803 | 1581 | followerActorId, |
8519cc92 C |
1582 | includeLocalVideos: true, |
1583 | withoutId: true // Don't break aggregation | |
7348b1fd C |
1584 | } |
1585 | ||
1735c825 | 1586 | const query: FindOptions = { |
2d3741d6 C |
1587 | attributes: [ field ], |
1588 | limit: count, | |
1589 | group: field, | |
3acc5084 C |
1590 | having: Sequelize.where( |
1591 | Sequelize.fn('COUNT', Sequelize.col(field)), { [ Op.gte ]: threshold } | |
1592 | ), | |
1735c825 | 1593 | order: [ (this.sequelize as any).random() ] |
2d3741d6 C |
1594 | } |
1595 | ||
7348b1fd C |
1596 | return VideoModel.scope({ method: [ ScopeNames.AVAILABLE_FOR_LIST_IDS, scopeOptions ] }) |
1597 | .findAll(query) | |
8ea6f49a | 1598 | .then(rows => rows.map(r => r[ field ])) |
2d3741d6 C |
1599 | } |
1600 | ||
b36f41ca C |
1601 | static buildTrendingQuery (trendingDays: number) { |
1602 | return { | |
1603 | attributes: [], | |
1604 | subQuery: false, | |
1605 | model: VideoViewModel, | |
1606 | required: false, | |
1607 | where: { | |
1608 | startDate: { | |
1735c825 | 1609 | [ Op.gte ]: new Date(new Date().getTime() - (24 * 3600 * 1000) * trendingDays) |
b36f41ca C |
1610 | } |
1611 | } | |
1612 | } | |
1613 | } | |
1614 | ||
066e94c5 | 1615 | private static buildActorWhereWithFilter (filter?: VideoFilter) { |
1cd3facc | 1616 | if (filter && (filter === 'local' || filter === 'all-local')) { |
066e94c5 C |
1617 | return { |
1618 | serverId: null | |
1619 | } | |
1620 | } | |
1621 | ||
1622 | return {} | |
1623 | } | |
afd2cba5 | 1624 | |
6e46de09 | 1625 | private static async getAvailableForApi ( |
3caf77d3 | 1626 | query: FindOptions & { where?: null }, // Forbid where field in query |
7ad9b984 | 1627 | options: AvailableForListIDsOptions, |
6e46de09 C |
1628 | countVideos = true |
1629 | ) { | |
1735c825 | 1630 | const idsScope: ScopeOptions = { |
afd2cba5 C |
1631 | method: [ |
1632 | ScopeNames.AVAILABLE_FOR_LIST_IDS, options | |
1633 | ] | |
1634 | } | |
1635 | ||
8ea6f49a C |
1636 | // Remove trending sort on count, because it uses a group by |
1637 | const countOptions = Object.assign({}, options, { trendingDays: undefined }) | |
1735c825 C |
1638 | const countQuery: CountOptions = Object.assign({}, query, { attributes: undefined, group: undefined }) |
1639 | const countScope: ScopeOptions = { | |
8ea6f49a C |
1640 | method: [ |
1641 | ScopeNames.AVAILABLE_FOR_LIST_IDS, countOptions | |
1642 | ] | |
1643 | } | |
1644 | ||
3caf77d3 C |
1645 | const [ count, ids ] = await Promise.all([ |
1646 | countVideos | |
1647 | ? VideoModel.scope(countScope).count(countQuery) | |
1648 | : Promise.resolve<number>(undefined), | |
1649 | ||
1650 | VideoModel.scope(idsScope) | |
1651 | .findAll(query) | |
1652 | .then(rows => rows.map(r => r.id)) | |
8ea6f49a | 1653 | ]) |
afd2cba5 C |
1654 | |
1655 | if (ids.length === 0) return { data: [], total: count } | |
1656 | ||
1735c825 | 1657 | const secondQuery: FindOptions = { |
b6314e3c C |
1658 | offset: 0, |
1659 | limit: query.limit, | |
9a629c6e C |
1660 | attributes: query.attributes, |
1661 | order: [ // Keep original order | |
1662 | Sequelize.literal( | |
2ba92871 | 1663 | ids.map(id => `"VideoModel".id = ${id} DESC`).join(', ') |
9a629c6e C |
1664 | ) |
1665 | ] | |
b6314e3c | 1666 | } |
df0b219d | 1667 | |
2fb5b3a5 | 1668 | const apiScope: (string | ScopeOptions)[] = [] |
df0b219d C |
1669 | |
1670 | if (options.user) { | |
1671 | apiScope.push({ method: [ ScopeNames.WITH_USER_HISTORY, options.user.id ] }) | |
df0b219d C |
1672 | } |
1673 | ||
1674 | apiScope.push({ | |
1675 | method: [ | |
1676 | ScopeNames.FOR_API, { | |
76564702 C |
1677 | ids, |
1678 | withFiles: options.withFiles, | |
df0b219d C |
1679 | videoPlaylistId: options.videoPlaylistId |
1680 | } as ForAPIOptions | |
1681 | ] | |
1682 | }) | |
1683 | ||
b6314e3c | 1684 | const rows = await VideoModel.scope(apiScope).findAll(secondQuery) |
afd2cba5 C |
1685 | |
1686 | return { | |
1687 | data: rows, | |
1688 | total: count | |
1689 | } | |
1690 | } | |
066e94c5 | 1691 | |
098eb377 | 1692 | static getCategoryLabel (id: number) { |
8ea6f49a | 1693 | return VIDEO_CATEGORIES[ id ] || 'Misc' |
ae5a3dd6 C |
1694 | } |
1695 | ||
098eb377 | 1696 | static getLicenceLabel (id: number) { |
8ea6f49a | 1697 | return VIDEO_LICENCES[ id ] || 'Unknown' |
ae5a3dd6 C |
1698 | } |
1699 | ||
098eb377 | 1700 | static getLanguageLabel (id: string) { |
8ea6f49a | 1701 | return VIDEO_LANGUAGES[ id ] || 'Unknown' |
ae5a3dd6 C |
1702 | } |
1703 | ||
098eb377 | 1704 | static getPrivacyLabel (id: number) { |
8ea6f49a | 1705 | return VIDEO_PRIVACIES[ id ] || 'Unknown' |
2186386c | 1706 | } |
2243730c | 1707 | |
098eb377 | 1708 | static getStateLabel (id: number) { |
8ea6f49a | 1709 | return VIDEO_STATES[ id ] || 'Unknown' |
2243730c C |
1710 | } |
1711 | ||
3fd3ab2d C |
1712 | getOriginalFile () { |
1713 | if (Array.isArray(this.VideoFiles) === false) return undefined | |
aaf61f38 | 1714 | |
3fd3ab2d C |
1715 | // The original file is the file that have the higher resolution |
1716 | return maxBy(this.VideoFiles, file => file.resolution) | |
e4f97bab | 1717 | } |
aaf61f38 | 1718 | |
3acc5084 C |
1719 | async addAndSaveThumbnail (thumbnail: ThumbnailModel, transaction: Transaction) { |
1720 | thumbnail.videoId = this.id | |
1721 | ||
1722 | const savedThumbnail = await thumbnail.save({ transaction }) | |
1723 | ||
e8bafea3 C |
1724 | if (Array.isArray(this.Thumbnails) === false) this.Thumbnails = [] |
1725 | ||
1726 | // Already have this thumbnail, skip | |
3acc5084 | 1727 | if (this.Thumbnails.find(t => t.id === savedThumbnail.id)) return |
e8bafea3 | 1728 | |
3acc5084 | 1729 | this.Thumbnails.push(savedThumbnail) |
e8bafea3 C |
1730 | } |
1731 | ||
3fd3ab2d C |
1732 | getVideoFilename (videoFile: VideoFileModel) { |
1733 | return this.uuid + '-' + videoFile.resolution + videoFile.extname | |
1734 | } | |
165cdc75 | 1735 | |
e8bafea3 C |
1736 | generateThumbnailName () { |
1737 | return this.uuid + '.jpg' | |
7b1f49de C |
1738 | } |
1739 | ||
3acc5084 | 1740 | getMiniature () { |
e8bafea3 C |
1741 | if (Array.isArray(this.Thumbnails) === false) return undefined |
1742 | ||
3acc5084 | 1743 | return this.Thumbnails.find(t => t.type === ThumbnailType.MINIATURE) |
e8bafea3 C |
1744 | } |
1745 | ||
1746 | generatePreviewName () { | |
1747 | return this.uuid + '.jpg' | |
1748 | } | |
1749 | ||
1750 | getPreview () { | |
1751 | if (Array.isArray(this.Thumbnails) === false) return undefined | |
1752 | ||
1753 | return this.Thumbnails.find(t => t.type === ThumbnailType.PREVIEW) | |
3fd3ab2d | 1754 | } |
7b1f49de | 1755 | |
3fd3ab2d C |
1756 | getTorrentFileName (videoFile: VideoFileModel) { |
1757 | const extension = '.torrent' | |
1758 | return this.uuid + '-' + videoFile.resolution + extension | |
1759 | } | |
8e7f08b5 | 1760 | |
3fd3ab2d C |
1761 | isOwned () { |
1762 | return this.remote === false | |
9567011b C |
1763 | } |
1764 | ||
02756fbd C |
1765 | getTorrentFilePath (videoFile: VideoFileModel) { |
1766 | return join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
1767 | } | |
1768 | ||
3fd3ab2d C |
1769 | getVideoFilePath (videoFile: VideoFileModel) { |
1770 | return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
1771 | } | |
14d3270f | 1772 | |
81e504b3 | 1773 | async createTorrentAndSetInfoHash (videoFile: VideoFileModel) { |
3fd3ab2d | 1774 | const options = { |
6cced8f9 C |
1775 | // Keep the extname, it's used by the client to stream the file inside a web browser |
1776 | name: `${this.name} ${videoFile.resolution}p${videoFile.extname}`, | |
81e504b3 | 1777 | createdBy: 'PeerTube', |
3fd3ab2d | 1778 | announceList: [ |
6dd9de95 C |
1779 | [ WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT + '/tracker/socket' ], |
1780 | [ WEBSERVER.URL + '/tracker/announce' ] | |
3fd3ab2d | 1781 | ], |
6dd9de95 | 1782 | urlList: [ WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) ] |
3fd3ab2d | 1783 | } |
14d3270f | 1784 | |
3fd3ab2d | 1785 | const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options) |
e4f97bab | 1786 | |
3fd3ab2d C |
1787 | const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) |
1788 | logger.info('Creating torrent %s.', filePath) | |
e4f97bab | 1789 | |
62689b94 | 1790 | await writeFile(filePath, torrent) |
e4f97bab | 1791 | |
3fd3ab2d C |
1792 | const parsedTorrent = parseTorrent(torrent) |
1793 | videoFile.infoHash = parsedTorrent.infoHash | |
1794 | } | |
e4f97bab | 1795 | |
cef534ed C |
1796 | getWatchStaticPath () { |
1797 | return '/videos/watch/' + this.uuid | |
1798 | } | |
1799 | ||
40e87e9e | 1800 | getEmbedStaticPath () { |
3fd3ab2d C |
1801 | return '/videos/embed/' + this.uuid |
1802 | } | |
e4f97bab | 1803 | |
3acc5084 C |
1804 | getMiniatureStaticPath () { |
1805 | const thumbnail = this.getMiniature() | |
e8bafea3 C |
1806 | if (!thumbnail) return null |
1807 | ||
1808 | return join(STATIC_PATHS.THUMBNAILS, thumbnail.filename) | |
e4f97bab | 1809 | } |
227d02fe | 1810 | |
40e87e9e | 1811 | getPreviewStaticPath () { |
e8bafea3 C |
1812 | const preview = this.getPreview() |
1813 | if (!preview) return null | |
1814 | ||
1815 | // We use a local cache, so specify our cache endpoint instead of potential remote URL | |
1816 | return join(STATIC_PATHS.PREVIEWS, preview.filename) | |
3fd3ab2d | 1817 | } |
40298b02 | 1818 | |
098eb377 C |
1819 | toFormattedJSON (options?: VideoFormattingJSONOptions): Video { |
1820 | return videoModelToFormattedJSON(this, options) | |
14d3270f | 1821 | } |
14d3270f | 1822 | |
2422c46b | 1823 | toFormattedDetailsJSON (): VideoDetails { |
098eb377 | 1824 | return videoModelToFormattedDetailsJSON(this) |
244e76a5 RK |
1825 | } |
1826 | ||
1827 | getFormattedVideoFilesJSON (): VideoFile[] { | |
098eb377 | 1828 | return videoFilesModelToFormattedJSON(this, this.VideoFiles) |
3fd3ab2d | 1829 | } |
e4f97bab | 1830 | |
3fd3ab2d | 1831 | toActivityPubObject (): VideoTorrentObject { |
098eb377 | 1832 | return videoModelToActivityPubObject(this) |
3fd3ab2d C |
1833 | } |
1834 | ||
1835 | getTruncatedDescription () { | |
1836 | if (!this.description) return null | |
93e1258c | 1837 | |
bffbebbe | 1838 | const maxLength = CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max |
c73e83da | 1839 | return peertubeTruncate(this.description, maxLength) |
93e1258c C |
1840 | } |
1841 | ||
056aa7f2 | 1842 | getOriginalFileResolution () { |
3fd3ab2d | 1843 | const originalFilePath = this.getVideoFilePath(this.getOriginalFile()) |
0d0e8dd0 | 1844 | |
056aa7f2 | 1845 | return getVideoFileResolution(originalFilePath) |
3fd3ab2d | 1846 | } |
0d0e8dd0 | 1847 | |
96f29c0f | 1848 | getDescriptionAPIPath () { |
3fd3ab2d | 1849 | return `/api/${API_VERSION}/videos/${this.uuid}/description` |
feb4bdfd C |
1850 | } |
1851 | ||
b9fffa29 C |
1852 | removeFile (videoFile: VideoFileModel, isRedundancy = false) { |
1853 | const baseDir = isRedundancy ? CONFIG.STORAGE.REDUNDANCY_DIR : CONFIG.STORAGE.VIDEOS_DIR | |
1854 | ||
1855 | const filePath = join(baseDir, this.getVideoFilename(videoFile)) | |
62689b94 | 1856 | return remove(filePath) |
ed31c059 | 1857 | .catch(err => logger.warn('Cannot delete file %s.', filePath, { err })) |
feb4bdfd C |
1858 | } |
1859 | ||
3fd3ab2d C |
1860 | removeTorrent (videoFile: VideoFileModel) { |
1861 | const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
62689b94 | 1862 | return remove(torrentPath) |
ed31c059 | 1863 | .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err })) |
aaf61f38 C |
1864 | } |
1865 | ||
09209296 | 1866 | removeStreamingPlaylist (isRedundancy = false) { |
9c6ca37f | 1867 | const baseDir = isRedundancy ? HLS_REDUNDANCY_DIRECTORY : HLS_STREAMING_PLAYLIST_DIRECTORY |
09209296 C |
1868 | |
1869 | const filePath = join(baseDir, this.uuid) | |
1870 | return remove(filePath) | |
1871 | .catch(err => logger.warn('Cannot delete playlist directory %s.', filePath, { err })) | |
1872 | } | |
1873 | ||
1297eb5d C |
1874 | isOutdated () { |
1875 | if (this.isOwned()) return false | |
1876 | ||
9f79ade6 | 1877 | return isOutdated(this, ACTIVITY_PUB.VIDEO_REFRESH_INTERVAL) |
1297eb5d C |
1878 | } |
1879 | ||
04b8c3fb C |
1880 | setAsRefreshed () { |
1881 | this.changed('updatedAt', true) | |
1882 | ||
1883 | return this.save() | |
1884 | } | |
1885 | ||
c48e82b5 | 1886 | getBaseUrls () { |
3fd3ab2d C |
1887 | let baseUrlHttp |
1888 | let baseUrlWs | |
7920c273 | 1889 | |
3fd3ab2d | 1890 | if (this.isOwned()) { |
6dd9de95 C |
1891 | baseUrlHttp = WEBSERVER.URL |
1892 | baseUrlWs = WEBSERVER.WS + '://' + WEBSERVER.HOSTNAME + ':' + WEBSERVER.PORT | |
3fd3ab2d | 1893 | } else { |
50d6de9c C |
1894 | baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Actor.Server.host |
1895 | baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Actor.Server.host | |
6fcd19ba | 1896 | } |
aaf61f38 | 1897 | |
3fd3ab2d | 1898 | return { baseUrlHttp, baseUrlWs } |
15d4ee04 | 1899 | } |
a96aed15 | 1900 | |
c48e82b5 C |
1901 | generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) { |
1902 | const xs = this.getTorrentUrl(videoFile, baseUrlHttp) | |
09209296 | 1903 | const announce = this.getTrackerUrls(baseUrlHttp, baseUrlWs) |
c48e82b5 C |
1904 | let urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ] |
1905 | ||
1906 | const redundancies = videoFile.RedundancyVideos | |
1907 | if (isArray(redundancies)) urlList = urlList.concat(redundancies.map(r => r.fileUrl)) | |
1908 | ||
1909 | const magnetHash = { | |
1910 | xs, | |
1911 | announce, | |
1912 | urlList, | |
1913 | infoHash: videoFile.infoHash, | |
1914 | name: this.name | |
1915 | } | |
1916 | ||
1917 | return magnetUtil.encode(magnetHash) | |
1918 | } | |
1919 | ||
09209296 C |
1920 | getTrackerUrls (baseUrlHttp: string, baseUrlWs: string) { |
1921 | return [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] | |
1922 | } | |
1923 | ||
c48e82b5 | 1924 | getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
3fd3ab2d C |
1925 | return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile) |
1926 | } | |
e4f97bab | 1927 | |
c48e82b5 | 1928 | getTorrentDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
02756fbd C |
1929 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.TORRENTS + this.getTorrentFileName(videoFile) |
1930 | } | |
1931 | ||
c48e82b5 | 1932 | getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
3fd3ab2d C |
1933 | return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) |
1934 | } | |
a96aed15 | 1935 | |
b9fffa29 C |
1936 | getVideoRedundancyUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
1937 | return baseUrlHttp + STATIC_PATHS.REDUNDANCY + this.getVideoFilename(videoFile) | |
1938 | } | |
1939 | ||
c48e82b5 | 1940 | getVideoFileDownloadUrl (videoFile: VideoFileModel, baseUrlHttp: string) { |
02756fbd C |
1941 | return baseUrlHttp + STATIC_DOWNLOAD_PATHS.VIDEOS + this.getVideoFilename(videoFile) |
1942 | } | |
09209296 C |
1943 | |
1944 | getBandwidthBits (videoFile: VideoFileModel) { | |
1945 | return Math.ceil((videoFile.size * 8) / this.duration) | |
1946 | } | |
a96aed15 | 1947 | } |