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