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 { VideoPrivacy, VideoResolution } from '../../../shared'
8 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects/video-torrent-object'
9 import { activityPubCollection } from '../../helpers/activitypub'
10 import { createTorrentPromise, renamePromise, statPromise, unlinkPromise, writeFilePromise } from '../../helpers/core-utils'
11 import { isVideoCategoryValid, isVideoLanguageValid, isVideoPrivacyValid } from '../../helpers/custom-validators/videos'
12 import { generateImageFromVideoFile, getVideoFileHeight, transcode } from '../../helpers/ffmpeg-utils'
14 isActivityPubUrlValid,
15 isVideoDescriptionValid,
20 } from '../../helpers/index'
21 import { logger } from '../../helpers/logger'
34 } from '../../initializers/constants'
35 import { getAnnounceActivityPubUrl } from '../../lib/activitypub/url'
36 import { sendDeleteVideo } from '../../lib/index'
37 import { addMethodsToModel, getSort } from '../utils'
38 import { TagInstance } from './tag-interface'
39 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
40 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
42 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
43 let getOriginalFile: VideoMethods.GetOriginalFile
44 let getVideoFilename: VideoMethods.GetVideoFilename
45 let getThumbnailName: VideoMethods.GetThumbnailName
46 let getThumbnailPath: VideoMethods.GetThumbnailPath
47 let getPreviewName: VideoMethods.GetPreviewName
48 let getPreviewPath: VideoMethods.GetPreviewPath
49 let getTorrentFileName: VideoMethods.GetTorrentFileName
50 let isOwned: VideoMethods.IsOwned
51 let toFormattedJSON: VideoMethods.ToFormattedJSON
52 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
53 let toActivityPubObject: VideoMethods.ToActivityPubObject
54 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
55 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
56 let createPreview: VideoMethods.CreatePreview
57 let createThumbnail: VideoMethods.CreateThumbnail
58 let getVideoFilePath: VideoMethods.GetVideoFilePath
59 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
60 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
61 let getEmbedPath: VideoMethods.GetEmbedPath
62 let getDescriptionPath: VideoMethods.GetDescriptionPath
63 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
64 let getCategoryLabel: VideoMethods.GetCategoryLabel
65 let getLicenceLabel: VideoMethods.GetLicenceLabel
66 let getLanguageLabel: VideoMethods.GetLanguageLabel
68 let list: VideoMethods.List
69 let listForApi: VideoMethods.ListForApi
70 let listAllAndSharedByAccountForOutbox: VideoMethods.ListAllAndSharedByAccountForOutbox
71 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
72 let load: VideoMethods.Load
73 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
74 let loadByUUID: VideoMethods.LoadByUUID
75 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
76 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
77 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
78 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
79 let removeThumbnail: VideoMethods.RemoveThumbnail
80 let removePreview: VideoMethods.RemovePreview
81 let removeFile: VideoMethods.RemoveFile
82 let removeTorrent: VideoMethods.RemoveTorrent
84 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
85 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
89 defaultValue: DataTypes.UUIDV4,
96 type: DataTypes.STRING,
100 const res = isVideoNameValid(value)
101 if (res === false) throw new Error('Video name is not valid.')
106 type: DataTypes.INTEGER,
109 categoryValid: value => {
110 const res = isVideoCategoryValid(value)
111 if (res === false) throw new Error('Video category is not valid.')
116 type: DataTypes.INTEGER,
120 licenceValid: value => {
121 const res = isVideoLicenceValid(value)
122 if (res === false) throw new Error('Video licence is not valid.')
127 type: DataTypes.INTEGER,
130 languageValid: value => {
131 const res = isVideoLanguageValid(value)
132 if (res === false) throw new Error('Video language is not valid.')
137 type: DataTypes.INTEGER,
140 privacyValid: value => {
141 const res = isVideoPrivacyValid(value)
142 if (res === false) throw new Error('Video privacy is not valid.')
147 type: DataTypes.BOOLEAN,
150 nsfwValid: value => {
151 const res = isVideoNSFWValid(value)
152 if (res === false) throw new Error('Video nsfw attribute is not valid.')
157 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
160 descriptionValid: value => {
161 const res = isVideoDescriptionValid(value)
162 if (res === false) throw new Error('Video description is not valid.')
167 type: DataTypes.INTEGER,
170 durationValid: value => {
171 const res = isVideoDurationValid(value)
172 if (res === false) throw new Error('Video duration is not valid.')
177 type: DataTypes.INTEGER,
186 type: DataTypes.INTEGER,
195 type: DataTypes.INTEGER,
204 type: DataTypes.BOOLEAN,
209 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
213 const res = isActivityPubUrlValid(value)
214 if (res === false) throw new Error('Video URL is not valid.')
225 fields: [ 'createdAt' ]
228 fields: [ 'duration' ]
240 fields: [ 'channelId' ]
249 const classMethods = [
253 listAllAndSharedByAccountForOutbox,
255 listUserVideosForApi,
257 loadByUrlAndPopulateAccount,
258 loadAndPopulateAccountAndServerAndTags,
261 loadByUUIDAndPopulateAccountAndServerAndTags,
262 searchAndPopulateAccountAndServerAndTags
264 const instanceMethods = [
267 createTorrentAndSetInfoHash,
283 toFormattedDetailsJSON,
284 optimizeOriginalVideofile,
285 transcodeOriginalVideofile,
286 getOriginalFileHeight,
288 getTruncatedDescription,
294 addMethodsToModel(Video, classMethods, instanceMethods)
299 // ------------------------------ METHODS ------------------------------
301 function associate (models) {
302 Video.belongsTo(models.VideoChannel, {
310 Video.belongsToMany(models.Tag, {
311 foreignKey: 'videoId',
312 through: models.VideoTag,
316 Video.hasMany(models.VideoAbuse, {
324 Video.hasMany(models.VideoFile, {
332 Video.hasMany(models.VideoShare, {
340 Video.hasMany(models.AccountVideoRate, {
349 function afterDestroy (video: VideoInstance) {
353 video.removeThumbnail()
356 if (video.isOwned()) {
358 video.removePreview(),
359 sendDeleteVideo(video, undefined)
362 // Remove physical files and torrents
363 video.VideoFiles.forEach(file => {
364 tasks.push(video.removeFile(file))
365 tasks.push(video.removeTorrent(file))
369 return Promise.all(tasks)
371 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
375 getOriginalFile = function (this: VideoInstance) {
376 if (Array.isArray(this.VideoFiles) === false) return undefined
378 // The original file is the file that have the higher resolution
379 return maxBy(this.VideoFiles, file => file.resolution)
382 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
383 return this.uuid + '-' + videoFile.resolution + videoFile.extname
386 getThumbnailName = function (this: VideoInstance) {
387 // We always have a copy of the thumbnail
388 const extension = '.jpg'
389 return this.uuid + extension
392 getPreviewName = function (this: VideoInstance) {
393 const extension = '.jpg'
394 return this.uuid + extension
397 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
398 const extension = '.torrent'
399 return this.uuid + '-' + videoFile.resolution + extension
402 isOwned = function (this: VideoInstance) {
403 return this.remote === false
406 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
407 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
409 return generateImageFromVideoFile(
410 this.getVideoFilePath(videoFile),
411 CONFIG.STORAGE.PREVIEWS_DIR,
412 this.getPreviewName(),
417 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
418 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
420 return generateImageFromVideoFile(
421 this.getVideoFilePath(videoFile),
422 CONFIG.STORAGE.THUMBNAILS_DIR,
423 this.getThumbnailName(),
428 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
429 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
432 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
435 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
438 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
442 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
444 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
445 logger.info('Creating torrent %s.', filePath)
447 await writeFilePromise(filePath, torrent)
449 const parsedTorrent = parseTorrent(torrent)
450 videoFile.infoHash = parsedTorrent.infoHash
453 getEmbedPath = function (this: VideoInstance) {
454 return '/videos/embed/' + this.uuid
457 getThumbnailPath = function (this: VideoInstance) {
458 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
461 getPreviewPath = function (this: VideoInstance) {
462 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
465 toFormattedJSON = function (this: VideoInstance) {
468 if (this.VideoChannel.Account.Server) {
469 serverHost = this.VideoChannel.Account.Server.host
471 // It means it's our video
472 serverHost = CONFIG.WEBSERVER.HOST
479 category: this.category,
480 categoryLabel: this.getCategoryLabel(),
481 licence: this.licence,
482 licenceLabel: this.getLicenceLabel(),
483 language: this.language,
484 languageLabel: this.getLanguageLabel(),
486 description: this.getTruncatedDescription(),
488 isLocal: this.isOwned(),
489 account: this.VideoChannel.Account.name,
490 duration: this.duration,
493 dislikes: this.dislikes,
494 tags: map<TagInstance, string>(this.Tags, 'name'),
495 thumbnailPath: this.getThumbnailPath(),
496 previewPath: this.getPreviewPath(),
497 embedPath: this.getEmbedPath(),
498 createdAt: this.createdAt,
499 updatedAt: this.updatedAt
505 toFormattedDetailsJSON = function (this: VideoInstance) {
506 const formattedJson = this.toFormattedJSON()
508 // Maybe our server is not up to date and there are new privacy settings since our version
509 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
510 if (!privacyLabel) privacyLabel = 'Unknown'
512 const detailsJson = {
514 privacy: this.privacy,
515 descriptionPath: this.getDescriptionPath(),
516 channel: this.VideoChannel.toFormattedJSON(),
520 // Format and sort video files
521 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
522 detailsJson.files = this.VideoFiles
524 let resolutionLabel = videoFile.resolution + 'p'
526 const videoFileJson = {
527 resolution: videoFile.resolution,
529 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
530 size: videoFile.size,
531 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
532 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
538 if (a.resolution < b.resolution) return 1
539 if (a.resolution === b.resolution) return 0
543 return Object.assign(formattedJson, detailsJson)
546 toActivityPubObject = function (this: VideoInstance) {
547 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
548 if (!this.Tags) this.Tags = []
550 const tag = this.Tags.map(t => ({
551 type: 'Hashtag' as 'Hashtag',
558 identifier: this.language + '',
559 name: this.getLanguageLabel()
566 if (Array.isArray(this.AccountVideoRates)) {
567 const likes: string[] = []
568 const dislikes: string[] = []
570 for (const rate of this.AccountVideoRates) {
571 if (rate.type === 'like') {
572 likes.push(rate.Account.url)
573 } else if (rate.type === 'dislike') {
574 dislikes.push(rate.Account.url)
578 likesObject = activityPubCollection(likes)
579 dislikesObject = activityPubCollection(dislikes)
583 if (Array.isArray(this.VideoShares)) {
584 const shares: string[] = []
586 for (const videoShare of this.VideoShares) {
587 const shareUrl = getAnnounceActivityPubUrl(this.url, videoShare.Account)
588 shares.push(shareUrl)
591 sharesObject = activityPubCollection(shares)
595 for (const file of this.VideoFiles) {
598 mimeType: 'video/' + file.extname.replace('.', ''),
599 url: getVideoFileUrl(this, file, baseUrlHttp),
600 width: file.resolution,
606 mimeType: 'application/x-bittorrent',
607 url: getTorrentUrl(this, file, baseUrlHttp),
608 width: file.resolution
613 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
614 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
615 width: file.resolution
619 const videoObject: VideoTorrentObject = {
620 type: 'Video' as 'Video',
623 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
624 duration: 'PT' + this.duration + 'S',
628 identifier: this.category + '',
629 name: this.getCategoryLabel()
632 identifier: this.licence + '',
633 name: this.getLicenceLabel()
638 published: this.createdAt.toISOString(),
639 updated: this.updatedAt.toISOString(),
640 mediaType: 'text/markdown',
641 content: this.getTruncatedDescription(),
644 url: getThumbnailUrl(this, baseUrlHttp),
645 mediaType: 'image/jpeg',
646 width: THUMBNAILS_SIZE.width,
647 height: THUMBNAILS_SIZE.height
651 dislikes: dislikesObject,
658 getTruncatedDescription = function (this: VideoInstance) {
660 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
663 return truncate(this.description, options)
666 optimizeOriginalVideofile = async function (this: VideoInstance) {
667 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
668 const newExtname = '.mp4'
669 const inputVideoFile = this.getOriginalFile()
670 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
671 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
673 const transcodeOptions = {
674 inputPath: videoInputPath,
675 outputPath: videoOutputPath
679 // Could be very long!
680 await transcode(transcodeOptions)
682 await unlinkPromise(videoInputPath)
684 // Important to do this before getVideoFilename() to take in account the new file extension
685 inputVideoFile.set('extname', newExtname)
687 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
688 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
690 inputVideoFile.set('size', stats.size)
692 await this.createTorrentAndSetInfoHash(inputVideoFile)
693 await inputVideoFile.save()
696 // Auto destruction...
697 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
703 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
704 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
705 const extname = '.mp4'
707 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
708 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
710 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
716 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
718 const transcodeOptions = {
719 inputPath: videoInputPath,
720 outputPath: videoOutputPath,
724 await transcode(transcodeOptions)
726 const stats = await statPromise(videoOutputPath)
728 newVideoFile.set('size', stats.size)
730 await this.createTorrentAndSetInfoHash(newVideoFile)
732 await newVideoFile.save()
734 this.VideoFiles.push(newVideoFile)
737 getOriginalFileHeight = function (this: VideoInstance) {
738 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
740 return getVideoFileHeight(originalFilePath)
743 getDescriptionPath = function (this: VideoInstance) {
744 return `/api/${API_VERSION}/videos/${this.uuid}/description`
747 getCategoryLabel = function (this: VideoInstance) {
748 let categoryLabel = VIDEO_CATEGORIES[this.category]
750 // Maybe our server is not up to date and there are new categories since our version
751 if (!categoryLabel) categoryLabel = 'Misc'
756 getLicenceLabel = function (this: VideoInstance) {
757 let licenceLabel = VIDEO_LICENCES[this.licence]
759 // Maybe our server is not up to date and there are new licences since our version
760 if (!licenceLabel) licenceLabel = 'Unknown'
765 getLanguageLabel = function (this: VideoInstance) {
766 // Language is an optional attribute
767 let languageLabel = VIDEO_LANGUAGES[this.language]
768 if (!languageLabel) languageLabel = 'Unknown'
773 removeThumbnail = function (this: VideoInstance) {
774 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
775 return unlinkPromise(thumbnailPath)
778 removePreview = function (this: VideoInstance) {
779 // Same name than video thumbnail
780 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
783 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
784 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
785 return unlinkPromise(filePath)
788 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
789 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
790 return unlinkPromise(torrentPath)
793 // ------------------------------ STATICS ------------------------------
797 include: [ Video['sequelize'].models.VideoFile ]
800 return Video.findAll(query)
803 listAllAndSharedByAccountForOutbox = function (accountId: number, start: number, count: number) {
804 function getRawQuery (select: string) {
805 const queryVideo = 'SELECT ' + select + ' FROM "Videos" AS "Video" ' +
806 'INNER JOIN "VideoChannels" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
807 'WHERE "VideoChannel"."accountId" = ' + accountId
808 const queryVideoShare = 'SELECT ' + select + ' FROM "VideoShares" AS "VideoShare" ' +
809 'INNER JOIN "Videos" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
810 'WHERE "VideoShare"."accountId" = ' + accountId
812 let rawQuery = `(${queryVideo}) UNION (${queryVideoShare})`
817 const rawQuery = getRawQuery('"Video"."id"')
818 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
824 order: [ getSort('createdAt'), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
827 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
832 model: Video['sequelize'].models.VideoShare,
835 [Sequelize.Op.and]: [
838 [Sequelize.Op.not]: null
846 include: [ Video['sequelize'].models.Account ]
849 model: Video['sequelize'].models.VideoChannel,
853 model: Video['sequelize'].models.Account,
859 model: Video['sequelize'].models.AccountVideoRate,
860 include: [ Video['sequelize'].models.Account ]
862 Video['sequelize'].models.VideoFile,
863 Video['sequelize'].models.Tag
867 return Bluebird.all([
868 Video.findAll(query),
869 Video['sequelize'].query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
870 ]).then(([ rows, totals ]) => {
871 // totals: totalVideos + totalVideoShares
873 let totalVideoShares = 0
874 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
875 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
877 const total = totalVideos + totalVideoShares
885 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
890 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
893 model: Video['sequelize'].models.VideoChannel,
897 model: Video['sequelize'].models.Account,
905 Video['sequelize'].models.Tag
909 return Video.findAndCountAll(query).then(({ rows, count }) => {
917 listForApi = function (start: number, count: number, sort: string) {
922 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
925 model: Video['sequelize'].models.VideoChannel,
929 model: Video['sequelize'].models.Account,
933 model: Video['sequelize'].models.Server,
940 Video['sequelize'].models.Tag
942 where: createBaseVideosWhere()
945 return Video.findAndCountAll(query).then(({ rows, count }) => {
953 load = function (id: number) {
954 return Video.findById(id)
957 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
958 const query: Sequelize.FindOptions<VideoAttributes> = {
962 include: [ Video['sequelize'].models.VideoFile ]
965 if (t !== undefined) query.transaction = t
967 return Video.findOne(query)
970 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
971 const query: Sequelize.FindOptions<VideoAttributes> = {
976 Video['sequelize'].models.VideoFile,
978 model: Video['sequelize'].models.VideoChannel,
979 include: [ Video['sequelize'].models.Account ]
984 if (t !== undefined) query.transaction = t
986 return Video.findOne(query)
989 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
990 const query: Sequelize.FindOptions<VideoAttributes> = {
997 include: [ Video['sequelize'].models.VideoFile ]
1000 if (t !== undefined) query.transaction = t
1002 return Video.findOne(query)
1005 loadAndPopulateAccountAndServerAndTags = function (id: number) {
1007 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1010 model: Video['sequelize'].models.VideoChannel,
1013 model: Video['sequelize'].models.Account,
1014 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1019 model: Video['sequelize'].models.AccountVideoRate,
1020 include: [ Video['sequelize'].models.Account ]
1023 model: Video['sequelize'].models.VideoShare,
1024 include: [ Video['sequelize'].models.Account ]
1026 Video['sequelize'].models.Tag,
1027 Video['sequelize'].models.VideoFile
1031 return Video.findById(id, options)
1034 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1036 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1042 model: Video['sequelize'].models.VideoChannel,
1045 model: Video['sequelize'].models.Account,
1046 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1051 model: Video['sequelize'].models.AccountVideoRate,
1052 include: [ Video['sequelize'].models.Account ]
1055 model: Video['sequelize'].models.VideoShare,
1056 include: [ Video['sequelize'].models.Account ]
1058 Video['sequelize'].models.Tag,
1059 Video['sequelize'].models.VideoFile
1063 return Video.findOne(options)
1066 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1067 const serverInclude: Sequelize.IncludeOptions = {
1068 model: Video['sequelize'].models.Server,
1072 const accountInclude: Sequelize.IncludeOptions = {
1073 model: Video['sequelize'].models.Account,
1074 include: [ serverInclude ]
1077 const videoChannelInclude: Sequelize.IncludeOptions = {
1078 model: Video['sequelize'].models.VideoChannel,
1079 include: [ accountInclude ],
1083 const tagInclude: Sequelize.IncludeOptions = {
1084 model: Video['sequelize'].models.Tag
1087 const query: Sequelize.FindOptions<VideoAttributes> = {
1089 where: createBaseVideosWhere(),
1092 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1095 if (field === 'tags') {
1096 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1097 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1098 `(SELECT "VideoTags"."videoId"
1100 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1101 WHERE name ILIKE ${escapedValue}
1104 } else if (field === 'host') {
1105 // FIXME: Include our server? (not stored in the database)
1106 serverInclude.where = {
1108 [Sequelize.Op.iLike]: '%' + value + '%'
1111 serverInclude.required = true
1112 } else if (field === 'account') {
1113 accountInclude.where = {
1115 [Sequelize.Op.iLike]: '%' + value + '%'
1119 query.where[field] = {
1120 [Sequelize.Op.iLike]: '%' + value + '%'
1125 videoChannelInclude, tagInclude
1128 return Video.findAndCountAll(query).then(({ rows, count }) => {
1136 // ---------------------------------------------------------------------------
1138 function createBaseVideosWhere () {
1141 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1142 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1145 privacy: VideoPrivacy.PUBLIC
1149 function getBaseUrls (video: VideoInstance) {
1153 if (video.isOwned()) {
1154 baseUrlHttp = CONFIG.WEBSERVER.URL
1155 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1157 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1158 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1161 return { baseUrlHttp, baseUrlWs }
1164 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1165 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1168 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1169 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1172 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1173 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1176 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1177 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1178 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1179 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1181 const magnetHash = {
1185 infoHash: videoFile.infoHash,
1189 return magnetUtil.encode(magnetHash)