]>
Commit | Line | Data |
---|---|---|
1 | import * as Bluebird from 'bluebird' | |
2 | import { map, maxBy, truncate } from 'lodash' | |
3 | import * as magnetUtil from 'magnet-uri' | |
4 | import * as parseTorrent from 'parse-torrent' | |
5 | import { join } from 'path' | |
6 | import * as Sequelize from 'sequelize' | |
7 | import { | |
8 | AfterDestroy, | |
9 | AllowNull, | |
10 | BelongsTo, | |
11 | BelongsToMany, | |
12 | Column, | |
13 | CreatedAt, | |
14 | DataType, | |
15 | Default, | |
16 | ForeignKey, | |
17 | HasMany, | |
18 | IFindOptions, | |
19 | Is, | |
20 | IsInt, | |
21 | IsUUID, | |
22 | Min, | |
23 | Model, | |
24 | Table, | |
25 | UpdatedAt | |
26 | } from 'sequelize-typescript' | |
27 | import { IIncludeOptions } from 'sequelize-typescript/lib/interfaces/IIncludeOptions' | |
28 | import { VideoPrivacy, VideoResolution } from '../../../shared' | |
29 | import { VideoTorrentObject } from '../../../shared/models/activitypub/objects' | |
30 | import { | |
31 | activityPubCollection, | |
32 | createTorrentPromise, | |
33 | generateImageFromVideoFile, | |
34 | getVideoFileHeight, | |
35 | logger, | |
36 | renamePromise, | |
37 | statPromise, | |
38 | transcode, | |
39 | unlinkPromise, | |
40 | writeFilePromise | |
41 | } from '../../helpers' | |
42 | import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub' | |
43 | import { | |
44 | isVideoCategoryValid, | |
45 | isVideoDescriptionValid, | |
46 | isVideoDurationValid, | |
47 | isVideoLanguageValid, | |
48 | isVideoLicenceValid, | |
49 | isVideoNameValid, | |
50 | isVideoNSFWValid, | |
51 | isVideoPrivacyValid | |
52 | } from '../../helpers/custom-validators/videos' | |
53 | import { | |
54 | API_VERSION, | |
55 | CONFIG, | |
56 | CONSTRAINTS_FIELDS, | |
57 | PREVIEWS_SIZE, | |
58 | REMOTE_SCHEME, | |
59 | STATIC_PATHS, | |
60 | THUMBNAILS_SIZE, | |
61 | VIDEO_CATEGORIES, | |
62 | VIDEO_LANGUAGES, | |
63 | VIDEO_LICENCES, | |
64 | VIDEO_PRIVACIES | |
65 | } from '../../initializers' | |
66 | import { getAnnounceActivityPubUrl } from '../../lib/activitypub' | |
67 | import { sendDeleteVideo } from '../../lib/index' | |
68 | import { AccountModel } from '../account/account' | |
69 | import { AccountVideoRateModel } from '../account/account-video-rate' | |
70 | import { ServerModel } from '../server/server' | |
71 | import { getSort, throwIfNotValid } from '../utils' | |
72 | import { TagModel } from './tag' | |
73 | import { VideoAbuseModel } from './video-abuse' | |
74 | import { VideoChannelModel } from './video-channel' | |
75 | import { VideoFileModel } from './video-file' | |
76 | import { VideoShareModel } from './video-share' | |
77 | import { VideoTagModel } from './video-tag' | |
78 | ||
79 | @Table({ | |
80 | tableName: 'video', | |
81 | indexes: [ | |
82 | { | |
83 | fields: [ 'name' ] | |
84 | }, | |
85 | { | |
86 | fields: [ 'createdAt' ] | |
87 | }, | |
88 | { | |
89 | fields: [ 'duration' ] | |
90 | }, | |
91 | { | |
92 | fields: [ 'views' ] | |
93 | }, | |
94 | { | |
95 | fields: [ 'likes' ] | |
96 | }, | |
97 | { | |
98 | fields: [ 'uuid' ] | |
99 | }, | |
100 | { | |
101 | fields: [ 'channelId' ] | |
102 | } | |
103 | ] | |
104 | }) | |
105 | export class VideoModel extends Model<VideoModel> { | |
106 | ||
107 | @AllowNull(false) | |
108 | @Default(DataType.UUIDV4) | |
109 | @IsUUID(4) | |
110 | @Column(DataType.UUID) | |
111 | uuid: string | |
112 | ||
113 | @AllowNull(false) | |
114 | @Is('VideoName', value => throwIfNotValid(value, isVideoNameValid, 'name')) | |
115 | @Column | |
116 | name: string | |
117 | ||
118 | @AllowNull(true) | |
119 | @Default(null) | |
120 | @Is('VideoCategory', value => throwIfNotValid(value, isVideoCategoryValid, 'category')) | |
121 | @Column | |
122 | category: number | |
123 | ||
124 | @AllowNull(true) | |
125 | @Default(null) | |
126 | @Is('VideoLicence', value => throwIfNotValid(value, isVideoLicenceValid, 'licence')) | |
127 | @Column | |
128 | licence: number | |
129 | ||
130 | @AllowNull(true) | |
131 | @Default(null) | |
132 | @Is('VideoLanguage', value => throwIfNotValid(value, isVideoLanguageValid, 'language')) | |
133 | @Column | |
134 | language: number | |
135 | ||
136 | @AllowNull(false) | |
137 | @Is('VideoPrivacy', value => throwIfNotValid(value, isVideoPrivacyValid, 'privacy')) | |
138 | @Column | |
139 | privacy: number | |
140 | ||
141 | @AllowNull(false) | |
142 | @Is('VideoNSFW', value => throwIfNotValid(value, isVideoNSFWValid, 'NSFW boolean')) | |
143 | @Column | |
144 | nsfw: boolean | |
145 | ||
146 | @AllowNull(true) | |
147 | @Default(null) | |
148 | @Is('VideoDescription', value => throwIfNotValid(value, isVideoDescriptionValid, 'description')) | |
149 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max)) | |
150 | description: string | |
151 | ||
152 | @AllowNull(false) | |
153 | @Is('VideoDuration', value => throwIfNotValid(value, isVideoDurationValid, 'duration')) | |
154 | @Column | |
155 | duration: number | |
156 | ||
157 | @AllowNull(false) | |
158 | @Default(0) | |
159 | @IsInt | |
160 | @Min(0) | |
161 | @Column | |
162 | views: number | |
163 | ||
164 | @AllowNull(false) | |
165 | @Default(0) | |
166 | @IsInt | |
167 | @Min(0) | |
168 | @Column | |
169 | likes: number | |
170 | ||
171 | @AllowNull(false) | |
172 | @Default(0) | |
173 | @IsInt | |
174 | @Min(0) | |
175 | @Column | |
176 | dislikes: number | |
177 | ||
178 | @AllowNull(false) | |
179 | @Column | |
180 | remote: boolean | |
181 | ||
182 | @AllowNull(false) | |
183 | @Is('VideoUrl', value => throwIfNotValid(value, isActivityPubUrlValid, 'url')) | |
184 | @Column(DataType.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max)) | |
185 | url: string | |
186 | ||
187 | @CreatedAt | |
188 | createdAt: Date | |
189 | ||
190 | @UpdatedAt | |
191 | updatedAt: Date | |
192 | ||
193 | @ForeignKey(() => VideoChannelModel) | |
194 | @Column | |
195 | channelId: number | |
196 | ||
197 | @BelongsTo(() => VideoChannelModel, { | |
198 | foreignKey: { | |
199 | allowNull: false | |
200 | }, | |
201 | onDelete: 'cascade' | |
202 | }) | |
203 | VideoChannel: VideoChannelModel | |
204 | ||
205 | @BelongsToMany(() => TagModel, { | |
206 | foreignKey: 'videoId', | |
207 | through: () => VideoTagModel, | |
208 | onDelete: 'CASCADE' | |
209 | }) | |
210 | Tags: TagModel[] | |
211 | ||
212 | @HasMany(() => VideoAbuseModel, { | |
213 | foreignKey: { | |
214 | name: 'videoId', | |
215 | allowNull: false | |
216 | }, | |
217 | onDelete: 'cascade' | |
218 | }) | |
219 | VideoAbuses: VideoAbuseModel[] | |
220 | ||
221 | @HasMany(() => VideoFileModel, { | |
222 | foreignKey: { | |
223 | name: 'videoId', | |
224 | allowNull: false | |
225 | }, | |
226 | onDelete: 'cascade' | |
227 | }) | |
228 | VideoFiles: VideoFileModel[] | |
229 | ||
230 | @HasMany(() => VideoShareModel, { | |
231 | foreignKey: { | |
232 | name: 'videoId', | |
233 | allowNull: false | |
234 | }, | |
235 | onDelete: 'cascade' | |
236 | }) | |
237 | VideoShares: VideoShareModel[] | |
238 | ||
239 | @HasMany(() => AccountVideoRateModel, { | |
240 | foreignKey: { | |
241 | name: 'videoId', | |
242 | allowNull: false | |
243 | }, | |
244 | onDelete: 'cascade' | |
245 | }) | |
246 | AccountVideoRates: AccountVideoRateModel[] | |
247 | ||
248 | @AfterDestroy | |
249 | static removeFilesAndSendDelete (instance: VideoModel) { | |
250 | const tasks = [] | |
251 | ||
252 | tasks.push( | |
253 | instance.removeThumbnail() | |
254 | ) | |
255 | ||
256 | if (instance.isOwned()) { | |
257 | tasks.push( | |
258 | instance.removePreview(), | |
259 | sendDeleteVideo(instance, undefined) | |
260 | ) | |
261 | ||
262 | // Remove physical files and torrents | |
263 | instance.VideoFiles.forEach(file => { | |
264 | tasks.push(instance.removeFile(file)) | |
265 | tasks.push(instance.removeTorrent(file)) | |
266 | }) | |
267 | } | |
268 | ||
269 | return Promise.all(tasks) | |
270 | .catch(err => { | |
271 | logger.error('Some errors when removing files of video %s in after destroy hook.', instance.uuid, err) | |
272 | }) | |
273 | } | |
274 | ||
275 | static list () { | |
276 | const query = { | |
277 | include: [ VideoFileModel ] | |
278 | } | |
279 | ||
280 | return VideoModel.findAll(query) | |
281 | } | |
282 | ||
283 | static listAllAndSharedByAccountForOutbox (accountId: number, start: number, count: number) { | |
284 | function getRawQuery (select: string) { | |
285 | const queryVideo = 'SELECT ' + select + ' FROM "video" AS "Video" ' + | |
286 | 'INNER JOIN "videoChannel" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' + | |
287 | 'WHERE "VideoChannel"."accountId" = ' + accountId | |
288 | const queryVideoShare = 'SELECT ' + select + ' FROM "videoShare" AS "VideoShare" ' + | |
289 | 'INNER JOIN "video" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' + | |
290 | 'WHERE "VideoShare"."accountId" = ' + accountId | |
291 | ||
292 | return `(${queryVideo}) UNION (${queryVideoShare})` | |
293 | } | |
294 | ||
295 | const rawQuery = getRawQuery('"Video"."id"') | |
296 | const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"') | |
297 | ||
298 | const query = { | |
299 | distinct: true, | |
300 | offset: start, | |
301 | limit: count, | |
302 | order: [ getSort('createdAt'), [ 'Tags', 'name', 'ASC' ] ], | |
303 | where: { | |
304 | id: { | |
305 | [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')') | |
306 | } | |
307 | }, | |
308 | include: [ | |
309 | { | |
310 | model: VideoShareModel, | |
311 | required: false, | |
312 | where: { | |
313 | [Sequelize.Op.and]: [ | |
314 | { | |
315 | id: { | |
316 | [Sequelize.Op.not]: null | |
317 | } | |
318 | }, | |
319 | { | |
320 | accountId | |
321 | } | |
322 | ] | |
323 | }, | |
324 | include: [ AccountModel ] | |
325 | }, | |
326 | { | |
327 | model: VideoChannelModel, | |
328 | required: true, | |
329 | include: [ | |
330 | { | |
331 | model: AccountModel, | |
332 | required: true | |
333 | } | |
334 | ] | |
335 | }, | |
336 | { | |
337 | model: AccountVideoRateModel, | |
338 | include: [ AccountModel ] | |
339 | }, | |
340 | VideoFileModel, | |
341 | TagModel | |
342 | ] | |
343 | } | |
344 | ||
345 | return Bluebird.all([ | |
346 | // FIXME: typing issue | |
347 | VideoModel.findAll(query as any), | |
348 | VideoModel.sequelize.query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT }) | |
349 | ]).then(([ rows, totals ]) => { | |
350 | // totals: totalVideos + totalVideoShares | |
351 | let totalVideos = 0 | |
352 | let totalVideoShares = 0 | |
353 | if (totals[0]) totalVideos = parseInt(totals[0].total, 10) | |
354 | if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10) | |
355 | ||
356 | const total = totalVideos + totalVideoShares | |
357 | return { | |
358 | data: rows, | |
359 | total: total | |
360 | } | |
361 | }) | |
362 | } | |
363 | ||
364 | static listUserVideosForApi (userId: number, start: number, count: number, sort: string) { | |
365 | const query = { | |
366 | distinct: true, | |
367 | offset: start, | |
368 | limit: count, | |
369 | order: [ getSort(sort), [ 'Tags', 'name', 'ASC' ] ], | |
370 | include: [ | |
371 | { | |
372 | model: VideoChannelModel, | |
373 | required: true, | |
374 | include: [ | |
375 | { | |
376 | model: AccountModel, | |
377 | where: { | |
378 | userId | |
379 | }, | |
380 | required: true | |
381 | } | |
382 | ] | |
383 | }, | |
384 | TagModel | |
385 | ] | |
386 | } | |
387 | ||
388 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { | |
389 | return { | |
390 | data: rows, | |
391 | total: count | |
392 | } | |
393 | }) | |
394 | } | |
395 | ||
396 | static listForApi (start: number, count: number, sort: string) { | |
397 | const query = { | |
398 | distinct: true, | |
399 | offset: start, | |
400 | limit: count, | |
401 | order: [ getSort(sort), [ 'Tags', 'name', 'ASC' ] ], | |
402 | include: [ | |
403 | { | |
404 | model: VideoChannelModel, | |
405 | required: true, | |
406 | include: [ | |
407 | { | |
408 | model: AccountModel, | |
409 | required: true, | |
410 | include: [ | |
411 | { | |
412 | model: ServerModel, | |
413 | required: false | |
414 | } | |
415 | ] | |
416 | } | |
417 | ] | |
418 | }, | |
419 | TagModel | |
420 | ], | |
421 | where: this.createBaseVideosWhere() | |
422 | } | |
423 | ||
424 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { | |
425 | return { | |
426 | data: rows, | |
427 | total: count | |
428 | } | |
429 | }) | |
430 | } | |
431 | ||
432 | static load (id: number) { | |
433 | return VideoModel.findById(id) | |
434 | } | |
435 | ||
436 | static loadByUUID (uuid: string, t?: Sequelize.Transaction) { | |
437 | const query: IFindOptions<VideoModel> = { | |
438 | where: { | |
439 | uuid | |
440 | }, | |
441 | include: [ VideoFileModel ] | |
442 | } | |
443 | ||
444 | if (t !== undefined) query.transaction = t | |
445 | ||
446 | return VideoModel.findOne(query) | |
447 | } | |
448 | ||
449 | static loadByUrlAndPopulateAccount (url: string, t?: Sequelize.Transaction) { | |
450 | const query: IFindOptions<VideoModel> = { | |
451 | where: { | |
452 | url | |
453 | }, | |
454 | include: [ | |
455 | VideoFileModel, | |
456 | { | |
457 | model: VideoChannelModel, | |
458 | include: [ AccountModel ] | |
459 | } | |
460 | ] | |
461 | } | |
462 | ||
463 | if (t !== undefined) query.transaction = t | |
464 | ||
465 | return VideoModel.findOne(query) | |
466 | } | |
467 | ||
468 | static loadByUUIDOrURL (uuid: string, url: string, t?: Sequelize.Transaction) { | |
469 | const query: IFindOptions<VideoModel> = { | |
470 | where: { | |
471 | [Sequelize.Op.or]: [ | |
472 | { uuid }, | |
473 | { url } | |
474 | ] | |
475 | }, | |
476 | include: [ VideoFileModel ] | |
477 | } | |
478 | ||
479 | if (t !== undefined) query.transaction = t | |
480 | ||
481 | return VideoModel.findOne(query) | |
482 | } | |
483 | ||
484 | static loadAndPopulateAccountAndServerAndTags (id: number) { | |
485 | const options = { | |
486 | order: [ [ 'Tags', 'name', 'ASC' ] ], | |
487 | include: [ | |
488 | { | |
489 | model: VideoChannelModel, | |
490 | include: [ | |
491 | { | |
492 | model: AccountModel, | |
493 | include: [ { model: ServerModel, required: false } ] | |
494 | } | |
495 | ] | |
496 | }, | |
497 | { | |
498 | model: AccountVideoRateModel, | |
499 | include: [ AccountModel ] | |
500 | }, | |
501 | { | |
502 | model: VideoShareModel, | |
503 | include: [ AccountModel ] | |
504 | }, | |
505 | TagModel, | |
506 | VideoFileModel | |
507 | ] | |
508 | } | |
509 | ||
510 | return VideoModel.findById(id, options) | |
511 | } | |
512 | ||
513 | static loadByUUIDAndPopulateAccountAndServerAndTags (uuid: string) { | |
514 | const options = { | |
515 | order: [ [ 'Tags', 'name', 'ASC' ] ], | |
516 | where: { | |
517 | uuid | |
518 | }, | |
519 | include: [ | |
520 | { | |
521 | model: VideoChannelModel, | |
522 | include: [ | |
523 | { | |
524 | model: AccountModel, | |
525 | include: [ { model: ServerModel, required: false } ] | |
526 | } | |
527 | ] | |
528 | }, | |
529 | { | |
530 | model: AccountVideoRateModel, | |
531 | include: [ AccountModel ] | |
532 | }, | |
533 | { | |
534 | model: VideoShareModel, | |
535 | include: [ AccountModel ] | |
536 | }, | |
537 | TagModel, | |
538 | VideoFileModel | |
539 | ] | |
540 | } | |
541 | ||
542 | return VideoModel.findOne(options) | |
543 | } | |
544 | ||
545 | static searchAndPopulateAccountAndServerAndTags (value: string, start: number, count: number, sort: string) { | |
546 | const serverInclude: IIncludeOptions = { | |
547 | model: ServerModel, | |
548 | required: false | |
549 | } | |
550 | ||
551 | const accountInclude: IIncludeOptions = { | |
552 | model: AccountModel, | |
553 | include: [ serverInclude ] | |
554 | } | |
555 | ||
556 | const videoChannelInclude: IIncludeOptions = { | |
557 | model: VideoChannelModel, | |
558 | include: [ accountInclude ], | |
559 | required: true | |
560 | } | |
561 | ||
562 | const tagInclude: IIncludeOptions = { | |
563 | model: TagModel | |
564 | } | |
565 | ||
566 | const query: IFindOptions<VideoModel> = { | |
567 | distinct: true, | |
568 | where: this.createBaseVideosWhere(), | |
569 | offset: start, | |
570 | limit: count, | |
571 | order: [ getSort(sort), [ 'Tags', 'name', 'ASC' ] ] | |
572 | } | |
573 | ||
574 | // TODO: search on tags too | |
575 | // const escapedValue = Video['sequelize'].escape('%' + value + '%') | |
576 | // query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal( | |
577 | // `(SELECT "VideoTags"."videoId" | |
578 | // FROM "Tags" | |
579 | // INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId" | |
580 | // WHERE name ILIKE ${escapedValue} | |
581 | // )` | |
582 | // ) | |
583 | ||
584 | // TODO: search on account too | |
585 | // accountInclude.where = { | |
586 | // name: { | |
587 | // [Sequelize.Op.iLike]: '%' + value + '%' | |
588 | // } | |
589 | // } | |
590 | query.where['name'] = { | |
591 | [Sequelize.Op.iLike]: '%' + value + '%' | |
592 | } | |
593 | ||
594 | query.include = [ | |
595 | videoChannelInclude, tagInclude | |
596 | ] | |
597 | ||
598 | return VideoModel.findAndCountAll(query).then(({ rows, count }) => { | |
599 | return { | |
600 | data: rows, | |
601 | total: count | |
602 | } | |
603 | }) | |
604 | } | |
605 | ||
606 | private static createBaseVideosWhere () { | |
607 | return { | |
608 | id: { | |
609 | [Sequelize.Op.notIn]: VideoModel.sequelize.literal( | |
610 | '(SELECT "videoBlacklist"."videoId" FROM "videoBlacklist")' | |
611 | ) | |
612 | }, | |
613 | privacy: VideoPrivacy.PUBLIC | |
614 | } | |
615 | } | |
616 | ||
617 | getOriginalFile () { | |
618 | if (Array.isArray(this.VideoFiles) === false) return undefined | |
619 | ||
620 | // The original file is the file that have the higher resolution | |
621 | return maxBy(this.VideoFiles, file => file.resolution) | |
622 | } | |
623 | ||
624 | getVideoFilename (videoFile: VideoFileModel) { | |
625 | return this.uuid + '-' + videoFile.resolution + videoFile.extname | |
626 | } | |
627 | ||
628 | getThumbnailName () { | |
629 | // We always have a copy of the thumbnail | |
630 | const extension = '.jpg' | |
631 | return this.uuid + extension | |
632 | } | |
633 | ||
634 | getPreviewName () { | |
635 | const extension = '.jpg' | |
636 | return this.uuid + extension | |
637 | } | |
638 | ||
639 | getTorrentFileName (videoFile: VideoFileModel) { | |
640 | const extension = '.torrent' | |
641 | return this.uuid + '-' + videoFile.resolution + extension | |
642 | } | |
643 | ||
644 | isOwned () { | |
645 | return this.remote === false | |
646 | } | |
647 | ||
648 | createPreview (videoFile: VideoFileModel) { | |
649 | const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height | |
650 | ||
651 | return generateImageFromVideoFile( | |
652 | this.getVideoFilePath(videoFile), | |
653 | CONFIG.STORAGE.PREVIEWS_DIR, | |
654 | this.getPreviewName(), | |
655 | imageSize | |
656 | ) | |
657 | } | |
658 | ||
659 | createThumbnail (videoFile: VideoFileModel) { | |
660 | const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height | |
661 | ||
662 | return generateImageFromVideoFile( | |
663 | this.getVideoFilePath(videoFile), | |
664 | CONFIG.STORAGE.THUMBNAILS_DIR, | |
665 | this.getThumbnailName(), | |
666 | imageSize | |
667 | ) | |
668 | } | |
669 | ||
670 | getVideoFilePath (videoFile: VideoFileModel) { | |
671 | return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
672 | } | |
673 | ||
674 | createTorrentAndSetInfoHash = async function (videoFile: VideoFileModel) { | |
675 | const options = { | |
676 | announceList: [ | |
677 | [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ] | |
678 | ], | |
679 | urlList: [ | |
680 | CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) | |
681 | ] | |
682 | } | |
683 | ||
684 | const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options) | |
685 | ||
686 | const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
687 | logger.info('Creating torrent %s.', filePath) | |
688 | ||
689 | await writeFilePromise(filePath, torrent) | |
690 | ||
691 | const parsedTorrent = parseTorrent(torrent) | |
692 | videoFile.infoHash = parsedTorrent.infoHash | |
693 | } | |
694 | ||
695 | getEmbedPath () { | |
696 | return '/videos/embed/' + this.uuid | |
697 | } | |
698 | ||
699 | getThumbnailPath () { | |
700 | return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName()) | |
701 | } | |
702 | ||
703 | getPreviewPath () { | |
704 | return join(STATIC_PATHS.PREVIEWS, this.getPreviewName()) | |
705 | } | |
706 | ||
707 | toFormattedJSON () { | |
708 | let serverHost | |
709 | ||
710 | if (this.VideoChannel.Account.Server) { | |
711 | serverHost = this.VideoChannel.Account.Server.host | |
712 | } else { | |
713 | // It means it's our video | |
714 | serverHost = CONFIG.WEBSERVER.HOST | |
715 | } | |
716 | ||
717 | return { | |
718 | id: this.id, | |
719 | uuid: this.uuid, | |
720 | name: this.name, | |
721 | category: this.category, | |
722 | categoryLabel: this.getCategoryLabel(), | |
723 | licence: this.licence, | |
724 | licenceLabel: this.getLicenceLabel(), | |
725 | language: this.language, | |
726 | languageLabel: this.getLanguageLabel(), | |
727 | nsfw: this.nsfw, | |
728 | description: this.getTruncatedDescription(), | |
729 | serverHost, | |
730 | isLocal: this.isOwned(), | |
731 | accountName: this.VideoChannel.Account.name, | |
732 | duration: this.duration, | |
733 | views: this.views, | |
734 | likes: this.likes, | |
735 | dislikes: this.dislikes, | |
736 | tags: map<TagModel, string>(this.Tags, 'name'), | |
737 | thumbnailPath: this.getThumbnailPath(), | |
738 | previewPath: this.getPreviewPath(), | |
739 | embedPath: this.getEmbedPath(), | |
740 | createdAt: this.createdAt, | |
741 | updatedAt: this.updatedAt | |
742 | } | |
743 | } | |
744 | ||
745 | toFormattedDetailsJSON () { | |
746 | const formattedJson = this.toFormattedJSON() | |
747 | ||
748 | // Maybe our server is not up to date and there are new privacy settings since our version | |
749 | let privacyLabel = VIDEO_PRIVACIES[this.privacy] | |
750 | if (!privacyLabel) privacyLabel = 'Unknown' | |
751 | ||
752 | const detailsJson = { | |
753 | privacyLabel, | |
754 | privacy: this.privacy, | |
755 | descriptionPath: this.getDescriptionPath(), | |
756 | channel: this.VideoChannel.toFormattedJSON(), | |
757 | account: this.VideoChannel.Account.toFormattedJSON(), | |
758 | files: [] | |
759 | } | |
760 | ||
761 | // Format and sort video files | |
762 | const { baseUrlHttp, baseUrlWs } = this.getBaseUrls() | |
763 | detailsJson.files = this.VideoFiles | |
764 | .map(videoFile => { | |
765 | let resolutionLabel = videoFile.resolution + 'p' | |
766 | ||
767 | return { | |
768 | resolution: videoFile.resolution, | |
769 | resolutionLabel, | |
770 | magnetUri: this.generateMagnetUri(videoFile, baseUrlHttp, baseUrlWs), | |
771 | size: videoFile.size, | |
772 | torrentUrl: this.getTorrentUrl(videoFile, baseUrlHttp), | |
773 | fileUrl: this.getVideoFileUrl(videoFile, baseUrlHttp) | |
774 | } | |
775 | }) | |
776 | .sort((a, b) => { | |
777 | if (a.resolution < b.resolution) return 1 | |
778 | if (a.resolution === b.resolution) return 0 | |
779 | return -1 | |
780 | }) | |
781 | ||
782 | return Object.assign(formattedJson, detailsJson) | |
783 | } | |
784 | ||
785 | toActivityPubObject (): VideoTorrentObject { | |
786 | const { baseUrlHttp, baseUrlWs } = this.getBaseUrls() | |
787 | if (!this.Tags) this.Tags = [] | |
788 | ||
789 | const tag = this.Tags.map(t => ({ | |
790 | type: 'Hashtag' as 'Hashtag', | |
791 | name: t.name | |
792 | })) | |
793 | ||
794 | let language | |
795 | if (this.language) { | |
796 | language = { | |
797 | identifier: this.language + '', | |
798 | name: this.getLanguageLabel() | |
799 | } | |
800 | } | |
801 | ||
802 | let category | |
803 | if (this.category) { | |
804 | category = { | |
805 | identifier: this.category + '', | |
806 | name: this.getCategoryLabel() | |
807 | } | |
808 | } | |
809 | ||
810 | let licence | |
811 | if (this.licence) { | |
812 | licence = { | |
813 | identifier: this.licence + '', | |
814 | name: this.getLicenceLabel() | |
815 | } | |
816 | } | |
817 | ||
818 | let likesObject | |
819 | let dislikesObject | |
820 | ||
821 | if (Array.isArray(this.AccountVideoRates)) { | |
822 | const likes: string[] = [] | |
823 | const dislikes: string[] = [] | |
824 | ||
825 | for (const rate of this.AccountVideoRates) { | |
826 | if (rate.type === 'like') { | |
827 | likes.push(rate.Account.url) | |
828 | } else if (rate.type === 'dislike') { | |
829 | dislikes.push(rate.Account.url) | |
830 | } | |
831 | } | |
832 | ||
833 | likesObject = activityPubCollection(likes) | |
834 | dislikesObject = activityPubCollection(dislikes) | |
835 | } | |
836 | ||
837 | let sharesObject | |
838 | if (Array.isArray(this.VideoShares)) { | |
839 | const shares: string[] = [] | |
840 | ||
841 | for (const videoShare of this.VideoShares) { | |
842 | const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Account) | |
843 | shares.push(shareUrl) | |
844 | } | |
845 | ||
846 | sharesObject = activityPubCollection(shares) | |
847 | } | |
848 | ||
849 | const url = [] | |
850 | for (const file of this.VideoFiles) { | |
851 | url.push({ | |
852 | type: 'Link', | |
853 | mimeType: 'video/' + file.extname.replace('.', ''), | |
854 | url: this.getVideoFileUrl(file, baseUrlHttp), | |
855 | width: file.resolution, | |
856 | size: file.size | |
857 | }) | |
858 | ||
859 | url.push({ | |
860 | type: 'Link', | |
861 | mimeType: 'application/x-bittorrent', | |
862 | url: this.getTorrentUrl(file, baseUrlHttp), | |
863 | width: file.resolution | |
864 | }) | |
865 | ||
866 | url.push({ | |
867 | type: 'Link', | |
868 | mimeType: 'application/x-bittorrent;x-scheme-handler/magnet', | |
869 | url: this.generateMagnetUri(file, baseUrlHttp, baseUrlWs), | |
870 | width: file.resolution | |
871 | }) | |
872 | } | |
873 | ||
874 | // Add video url too | |
875 | url.push({ | |
876 | type: 'Link', | |
877 | mimeType: 'text/html', | |
878 | url: CONFIG.WEBSERVER.URL + '/videos/watch/' + this.uuid | |
879 | }) | |
880 | ||
881 | return { | |
882 | type: 'Video' as 'Video', | |
883 | id: this.url, | |
884 | name: this.name, | |
885 | // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration | |
886 | duration: 'PT' + this.duration + 'S', | |
887 | uuid: this.uuid, | |
888 | tag, | |
889 | category, | |
890 | licence, | |
891 | language, | |
892 | views: this.views, | |
893 | nsfw: this.nsfw, | |
894 | published: this.createdAt.toISOString(), | |
895 | updated: this.updatedAt.toISOString(), | |
896 | mediaType: 'text/markdown', | |
897 | content: this.getTruncatedDescription(), | |
898 | icon: { | |
899 | type: 'Image', | |
900 | url: this.getThumbnailUrl(baseUrlHttp), | |
901 | mediaType: 'image/jpeg', | |
902 | width: THUMBNAILS_SIZE.width, | |
903 | height: THUMBNAILS_SIZE.height | |
904 | }, | |
905 | url, | |
906 | likes: likesObject, | |
907 | dislikes: dislikesObject, | |
908 | shares: sharesObject | |
909 | } | |
910 | } | |
911 | ||
912 | getTruncatedDescription () { | |
913 | if (!this.description) return null | |
914 | ||
915 | const options = { | |
916 | length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max | |
917 | } | |
918 | ||
919 | return truncate(this.description, options) | |
920 | } | |
921 | ||
922 | optimizeOriginalVideofile = async function () { | |
923 | const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR | |
924 | const newExtname = '.mp4' | |
925 | const inputVideoFile = this.getOriginalFile() | |
926 | const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile)) | |
927 | const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname) | |
928 | ||
929 | const transcodeOptions = { | |
930 | inputPath: videoInputPath, | |
931 | outputPath: videoOutputPath | |
932 | } | |
933 | ||
934 | try { | |
935 | // Could be very long! | |
936 | await transcode(transcodeOptions) | |
937 | ||
938 | await unlinkPromise(videoInputPath) | |
939 | ||
940 | // Important to do this before getVideoFilename() to take in account the new file extension | |
941 | inputVideoFile.set('extname', newExtname) | |
942 | ||
943 | await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile)) | |
944 | const stats = await statPromise(this.getVideoFilePath(inputVideoFile)) | |
945 | ||
946 | inputVideoFile.set('size', stats.size) | |
947 | ||
948 | await this.createTorrentAndSetInfoHash(inputVideoFile) | |
949 | await inputVideoFile.save() | |
950 | ||
951 | } catch (err) { | |
952 | // Auto destruction... | |
953 | this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err)) | |
954 | ||
955 | throw err | |
956 | } | |
957 | } | |
958 | ||
959 | transcodeOriginalVideofile = async function (resolution: VideoResolution) { | |
960 | const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR | |
961 | const extname = '.mp4' | |
962 | ||
963 | // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed | |
964 | const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile())) | |
965 | ||
966 | const newVideoFile = new VideoFileModel({ | |
967 | resolution, | |
968 | extname, | |
969 | size: 0, | |
970 | videoId: this.id | |
971 | }) | |
972 | const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile)) | |
973 | ||
974 | const transcodeOptions = { | |
975 | inputPath: videoInputPath, | |
976 | outputPath: videoOutputPath, | |
977 | resolution | |
978 | } | |
979 | ||
980 | await transcode(transcodeOptions) | |
981 | ||
982 | const stats = await statPromise(videoOutputPath) | |
983 | ||
984 | newVideoFile.set('size', stats.size) | |
985 | ||
986 | await this.createTorrentAndSetInfoHash(newVideoFile) | |
987 | ||
988 | await newVideoFile.save() | |
989 | ||
990 | this.VideoFiles.push(newVideoFile) | |
991 | } | |
992 | ||
993 | getOriginalFileHeight () { | |
994 | const originalFilePath = this.getVideoFilePath(this.getOriginalFile()) | |
995 | ||
996 | return getVideoFileHeight(originalFilePath) | |
997 | } | |
998 | ||
999 | getDescriptionPath () { | |
1000 | return `/api/${API_VERSION}/videos/${this.uuid}/description` | |
1001 | } | |
1002 | ||
1003 | getCategoryLabel () { | |
1004 | let categoryLabel = VIDEO_CATEGORIES[this.category] | |
1005 | if (!categoryLabel) categoryLabel = 'Misc' | |
1006 | ||
1007 | return categoryLabel | |
1008 | } | |
1009 | ||
1010 | getLicenceLabel () { | |
1011 | let licenceLabel = VIDEO_LICENCES[this.licence] | |
1012 | if (!licenceLabel) licenceLabel = 'Unknown' | |
1013 | ||
1014 | return licenceLabel | |
1015 | } | |
1016 | ||
1017 | getLanguageLabel () { | |
1018 | let languageLabel = VIDEO_LANGUAGES[this.language] | |
1019 | if (!languageLabel) languageLabel = 'Unknown' | |
1020 | ||
1021 | return languageLabel | |
1022 | } | |
1023 | ||
1024 | removeThumbnail () { | |
1025 | const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName()) | |
1026 | return unlinkPromise(thumbnailPath) | |
1027 | } | |
1028 | ||
1029 | removePreview () { | |
1030 | // Same name than video thumbnail | |
1031 | return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName()) | |
1032 | } | |
1033 | ||
1034 | removeFile (videoFile: VideoFileModel) { | |
1035 | const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile)) | |
1036 | return unlinkPromise(filePath) | |
1037 | } | |
1038 | ||
1039 | removeTorrent (videoFile: VideoFileModel) { | |
1040 | const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile)) | |
1041 | return unlinkPromise(torrentPath) | |
1042 | } | |
1043 | ||
1044 | private getBaseUrls () { | |
1045 | let baseUrlHttp | |
1046 | let baseUrlWs | |
1047 | ||
1048 | if (this.isOwned()) { | |
1049 | baseUrlHttp = CONFIG.WEBSERVER.URL | |
1050 | baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT | |
1051 | } else { | |
1052 | baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + this.VideoChannel.Account.Server.host | |
1053 | baseUrlWs = REMOTE_SCHEME.WS + '://' + this.VideoChannel.Account.Server.host | |
1054 | } | |
1055 | ||
1056 | return { baseUrlHttp, baseUrlWs } | |
1057 | } | |
1058 | ||
1059 | private getThumbnailUrl (baseUrlHttp: string) { | |
1060 | return baseUrlHttp + STATIC_PATHS.THUMBNAILS + this.getThumbnailName() | |
1061 | } | |
1062 | ||
1063 | private getTorrentUrl (videoFile: VideoFileModel, baseUrlHttp: string) { | |
1064 | return baseUrlHttp + STATIC_PATHS.TORRENTS + this.getTorrentFileName(videoFile) | |
1065 | } | |
1066 | ||
1067 | private getVideoFileUrl (videoFile: VideoFileModel, baseUrlHttp: string) { | |
1068 | return baseUrlHttp + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile) | |
1069 | } | |
1070 | ||
1071 | private generateMagnetUri (videoFile: VideoFileModel, baseUrlHttp: string, baseUrlWs: string) { | |
1072 | const xs = this.getTorrentUrl(videoFile, baseUrlHttp) | |
1073 | const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ] | |
1074 | const urlList = [ this.getVideoFileUrl(videoFile, baseUrlHttp) ] | |
1075 | ||
1076 | const magnetHash = { | |
1077 | xs, | |
1078 | announce, | |
1079 | urlList, | |
1080 | infoHash: videoFile.infoHash, | |
1081 | name: this.name | |
1082 | } | |
1083 | ||
1084 | return magnetUtil.encode(magnetHash) | |
1085 | } | |
1086 | } |