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 { isVideoCategoryValid, isVideoLanguageValid, isVideoPrivacyValid, isVideoUrlValid } from '../../helpers/custom-validators/videos'
23 } from '../../initializers/constants'
24 import { sendDeleteVideo } from '../../lib/index'
26 import { addMethodsToModel, getSort } from '../utils'
28 import { TagInstance } from './tag-interface'
29 import { VideoFileInstance, VideoFileModel } from './video-file-interface'
30 import { VideoAttributes, VideoInstance, VideoMethods } from './video-interface'
31 import { isVideoNameValid, isVideoLicenceValid, isVideoNSFWValid, isVideoDescriptionValid, isVideoDurationValid } from '../../helpers/index'
32 import { logger } from '../../helpers/logger'
33 import { generateImageFromVideoFile, transcode, getVideoFileHeight } from '../../helpers/ffmpeg-utils'
34 import { createTorrentPromise, writeFilePromise, unlinkPromise, renamePromise, statPromise } from '../../helpers/core-utils'
36 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
37 let getOriginalFile: VideoMethods.GetOriginalFile
38 let getVideoFilename: VideoMethods.GetVideoFilename
39 let getThumbnailName: VideoMethods.GetThumbnailName
40 let getThumbnailPath: VideoMethods.GetThumbnailPath
41 let getPreviewName: VideoMethods.GetPreviewName
42 let getPreviewPath: VideoMethods.GetPreviewPath
43 let getTorrentFileName: VideoMethods.GetTorrentFileName
44 let isOwned: VideoMethods.IsOwned
45 let toFormattedJSON: VideoMethods.ToFormattedJSON
46 let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
47 let toActivityPubObject: VideoMethods.ToActivityPubObject
48 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
49 let transcodeOriginalVideofile: VideoMethods.TranscodeOriginalVideofile
50 let createPreview: VideoMethods.CreatePreview
51 let createThumbnail: VideoMethods.CreateThumbnail
52 let getVideoFilePath: VideoMethods.GetVideoFilePath
53 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
54 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
55 let getEmbedPath: VideoMethods.GetEmbedPath
56 let getDescriptionPath: VideoMethods.GetDescriptionPath
57 let getTruncatedDescription: VideoMethods.GetTruncatedDescription
58 let getCategoryLabel: VideoMethods.GetCategoryLabel
59 let getLicenceLabel: VideoMethods.GetLicenceLabel
60 let getLanguageLabel: VideoMethods.GetLanguageLabel
62 let list: VideoMethods.List
63 let listForApi: VideoMethods.ListForApi
64 let listAllAndSharedByAccountForOutbox: VideoMethods.ListAllAndSharedByAccountForOutbox
65 let listUserVideosForApi: VideoMethods.ListUserVideosForApi
66 let load: VideoMethods.Load
67 let loadByUrlAndPopulateAccount: VideoMethods.LoadByUrlAndPopulateAccount
68 let loadByUUID: VideoMethods.LoadByUUID
69 let loadByUUIDOrURL: VideoMethods.LoadByUUIDOrURL
70 let loadAndPopulateAccountAndServerAndTags: VideoMethods.LoadAndPopulateAccountAndServerAndTags
71 let loadByUUIDAndPopulateAccountAndServerAndTags: VideoMethods.LoadByUUIDAndPopulateAccountAndServerAndTags
72 let searchAndPopulateAccountAndServerAndTags: VideoMethods.SearchAndPopulateAccountAndServerAndTags
73 let removeThumbnail: VideoMethods.RemoveThumbnail
74 let removePreview: VideoMethods.RemovePreview
75 let removeFile: VideoMethods.RemoveFile
76 let removeTorrent: VideoMethods.RemoveTorrent
78 export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.DataTypes) {
79 Video = sequelize.define<VideoInstance, VideoAttributes>('Video',
83 defaultValue: DataTypes.UUIDV4,
90 type: DataTypes.STRING,
94 const res = isVideoNameValid(value)
95 if (res === false) throw new Error('Video name is not valid.')
100 type: DataTypes.INTEGER,
103 categoryValid: value => {
104 const res = isVideoCategoryValid(value)
105 if (res === false) throw new Error('Video category is not valid.')
110 type: DataTypes.INTEGER,
114 licenceValid: value => {
115 const res = isVideoLicenceValid(value)
116 if (res === false) throw new Error('Video licence is not valid.')
121 type: DataTypes.INTEGER,
124 languageValid: value => {
125 const res = isVideoLanguageValid(value)
126 if (res === false) throw new Error('Video language is not valid.')
131 type: DataTypes.INTEGER,
134 privacyValid: value => {
135 const res = isVideoPrivacyValid(value)
136 if (res === false) throw new Error('Video privacy is not valid.')
141 type: DataTypes.BOOLEAN,
144 nsfwValid: value => {
145 const res = isVideoNSFWValid(value)
146 if (res === false) throw new Error('Video nsfw attribute is not valid.')
151 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
154 descriptionValid: value => {
155 const res = isVideoDescriptionValid(value)
156 if (res === false) throw new Error('Video description is not valid.')
161 type: DataTypes.INTEGER,
164 durationValid: value => {
165 const res = isVideoDurationValid(value)
166 if (res === false) throw new Error('Video duration is not valid.')
171 type: DataTypes.INTEGER,
180 type: DataTypes.INTEGER,
189 type: DataTypes.INTEGER,
198 type: DataTypes.BOOLEAN,
203 type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.URL.max),
207 const res = isVideoUrlValid(value)
208 if (res === false) throw new Error('Video URL is not valid.')
219 fields: [ 'createdAt' ]
222 fields: [ 'duration' ]
234 fields: [ 'channelId' ]
243 const classMethods = [
247 listAllAndSharedByAccountForOutbox,
249 listUserVideosForApi,
251 loadByUrlAndPopulateAccount,
252 loadAndPopulateAccountAndServerAndTags,
255 loadByUUIDAndPopulateAccountAndServerAndTags,
256 searchAndPopulateAccountAndServerAndTags
258 const instanceMethods = [
261 createTorrentAndSetInfoHash,
277 toFormattedDetailsJSON,
278 optimizeOriginalVideofile,
279 transcodeOriginalVideofile,
280 getOriginalFileHeight,
282 getTruncatedDescription,
288 addMethodsToModel(Video, classMethods, instanceMethods)
293 // ------------------------------ METHODS ------------------------------
295 function associate (models) {
296 Video.belongsTo(models.VideoChannel, {
304 Video.belongsToMany(models.Tag, {
305 foreignKey: 'videoId',
306 through: models.VideoTag,
310 Video.hasMany(models.VideoAbuse, {
318 Video.hasMany(models.VideoFile, {
326 Video.hasMany(models.VideoShare, {
334 Video.hasMany(models.AccountVideoRate, {
343 function afterDestroy (video: VideoInstance) {
347 video.removeThumbnail()
350 if (video.isOwned()) {
352 video.removePreview(),
353 sendDeleteVideo(video, undefined)
356 // Remove physical files and torrents
357 video.VideoFiles.forEach(file => {
358 tasks.push(video.removeFile(file))
359 tasks.push(video.removeTorrent(file))
363 return Promise.all(tasks)
365 logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
369 getOriginalFile = function (this: VideoInstance) {
370 if (Array.isArray(this.VideoFiles) === false) return undefined
372 // The original file is the file that have the higher resolution
373 return maxBy(this.VideoFiles, file => file.resolution)
376 getVideoFilename = function (this: VideoInstance, videoFile: VideoFileInstance) {
377 return this.uuid + '-' + videoFile.resolution + videoFile.extname
380 getThumbnailName = function (this: VideoInstance) {
381 // We always have a copy of the thumbnail
382 const extension = '.jpg'
383 return this.uuid + extension
386 getPreviewName = function (this: VideoInstance) {
387 const extension = '.jpg'
388 return this.uuid + extension
391 getTorrentFileName = function (this: VideoInstance, videoFile: VideoFileInstance) {
392 const extension = '.torrent'
393 return this.uuid + '-' + videoFile.resolution + extension
396 isOwned = function (this: VideoInstance) {
397 return this.remote === false
400 createPreview = function (this: VideoInstance, videoFile: VideoFileInstance) {
401 const imageSize = PREVIEWS_SIZE.width + 'x' + PREVIEWS_SIZE.height
403 return generateImageFromVideoFile(
404 this.getVideoFilePath(videoFile),
405 CONFIG.STORAGE.PREVIEWS_DIR,
406 this.getPreviewName(),
411 createThumbnail = function (this: VideoInstance, videoFile: VideoFileInstance) {
412 const imageSize = THUMBNAILS_SIZE.width + 'x' + THUMBNAILS_SIZE.height
414 return generateImageFromVideoFile(
415 this.getVideoFilePath(videoFile),
416 CONFIG.STORAGE.THUMBNAILS_DIR,
417 this.getThumbnailName(),
422 getVideoFilePath = function (this: VideoInstance, videoFile: VideoFileInstance) {
423 return join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
426 createTorrentAndSetInfoHash = async function (this: VideoInstance, videoFile: VideoFileInstance) {
429 [ CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT + '/tracker/socket' ]
432 CONFIG.WEBSERVER.URL + STATIC_PATHS.WEBSEED + this.getVideoFilename(videoFile)
436 const torrent = await createTorrentPromise(this.getVideoFilePath(videoFile), options)
438 const filePath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
439 logger.info('Creating torrent %s.', filePath)
441 await writeFilePromise(filePath, torrent)
443 const parsedTorrent = parseTorrent(torrent)
444 videoFile.infoHash = parsedTorrent.infoHash
447 getEmbedPath = function (this: VideoInstance) {
448 return '/videos/embed/' + this.uuid
451 getThumbnailPath = function (this: VideoInstance) {
452 return join(STATIC_PATHS.THUMBNAILS, this.getThumbnailName())
455 getPreviewPath = function (this: VideoInstance) {
456 return join(STATIC_PATHS.PREVIEWS, this.getPreviewName())
459 toFormattedJSON = function (this: VideoInstance) {
462 if (this.VideoChannel.Account.Server) {
463 serverHost = this.VideoChannel.Account.Server.host
465 // It means it's our video
466 serverHost = CONFIG.WEBSERVER.HOST
473 category: this.category,
474 categoryLabel: this.getCategoryLabel(),
475 licence: this.licence,
476 licenceLabel: this.getLicenceLabel(),
477 language: this.language,
478 languageLabel: this.getLanguageLabel(),
480 description: this.getTruncatedDescription(),
482 isLocal: this.isOwned(),
483 account: this.VideoChannel.Account.name,
484 duration: this.duration,
487 dislikes: this.dislikes,
488 tags: map<TagInstance, string>(this.Tags, 'name'),
489 thumbnailPath: this.getThumbnailPath(),
490 previewPath: this.getPreviewPath(),
491 embedPath: this.getEmbedPath(),
492 createdAt: this.createdAt,
493 updatedAt: this.updatedAt
499 toFormattedDetailsJSON = function (this: VideoInstance) {
500 const formattedJson = this.toFormattedJSON()
502 // Maybe our server is not up to date and there are new privacy settings since our version
503 let privacyLabel = VIDEO_PRIVACIES[this.privacy]
504 if (!privacyLabel) privacyLabel = 'Unknown'
506 const detailsJson = {
508 privacy: this.privacy,
509 descriptionPath: this.getDescriptionPath(),
510 channel: this.VideoChannel.toFormattedJSON(),
514 // Format and sort video files
515 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
516 detailsJson.files = this.VideoFiles
518 let resolutionLabel = videoFile.resolution + 'p'
520 const videoFileJson = {
521 resolution: videoFile.resolution,
523 magnetUri: generateMagnetUri(this, videoFile, baseUrlHttp, baseUrlWs),
524 size: videoFile.size,
525 torrentUrl: getTorrentUrl(this, videoFile, baseUrlHttp),
526 fileUrl: getVideoFileUrl(this, videoFile, baseUrlHttp)
532 if (a.resolution < b.resolution) return 1
533 if (a.resolution === b.resolution) return 0
537 return Object.assign(formattedJson, detailsJson)
540 toActivityPubObject = function (this: VideoInstance) {
541 const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
542 if (!this.Tags) this.Tags = []
544 const tag = this.Tags.map(t => ({
545 type: 'Hashtag' as 'Hashtag',
552 identifier: this.language + '',
553 name: this.getLanguageLabel()
560 if (Array.isArray(this.AccountVideoRates)) {
561 const likes: string[] = []
562 const dislikes: string[] = []
564 for (const rate of this.AccountVideoRates) {
565 if (rate.type === 'like') {
566 likes.push(rate.Account.url)
567 } else if (rate.type === 'dislike') {
568 dislikes.push(rate.Account.url)
572 likesObject = activityPubCollection(likes)
573 dislikesObject = activityPubCollection(dislikes)
577 for (const file of this.VideoFiles) {
580 mimeType: 'video/' + file.extname.replace('.', ''),
581 url: getVideoFileUrl(this, file, baseUrlHttp),
582 width: file.resolution,
588 mimeType: 'application/x-bittorrent',
589 url: getTorrentUrl(this, file, baseUrlHttp),
590 width: file.resolution
595 mimeType: 'application/x-bittorrent;x-scheme-handler/magnet',
596 url: generateMagnetUri(this, file, baseUrlHttp, baseUrlWs),
597 width: file.resolution
601 const videoObject: VideoTorrentObject = {
602 type: 'Video' as 'Video',
605 // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
606 duration: 'PT' + this.duration + 'S',
610 identifier: this.category + '',
611 name: this.getCategoryLabel()
614 identifier: this.licence + '',
615 name: this.getLicenceLabel()
620 published: this.createdAt.toISOString(),
621 updated: this.updatedAt.toISOString(),
622 mediaType: 'text/markdown',
623 content: this.getTruncatedDescription(),
626 url: getThumbnailUrl(this, baseUrlHttp),
627 mediaType: 'image/jpeg',
628 width: THUMBNAILS_SIZE.width,
629 height: THUMBNAILS_SIZE.height
633 dislikes: dislikesObject
639 getTruncatedDescription = function (this: VideoInstance) {
641 length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
644 return truncate(this.description, options)
647 optimizeOriginalVideofile = async function (this: VideoInstance) {
648 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
649 const newExtname = '.mp4'
650 const inputVideoFile = this.getOriginalFile()
651 const videoInputPath = join(videosDirectory, this.getVideoFilename(inputVideoFile))
652 const videoOutputPath = join(videosDirectory, this.id + '-transcoded' + newExtname)
654 const transcodeOptions = {
655 inputPath: videoInputPath,
656 outputPath: videoOutputPath
660 // Could be very long!
661 await transcode(transcodeOptions)
663 await unlinkPromise(videoInputPath)
665 // Important to do this before getVideoFilename() to take in account the new file extension
666 inputVideoFile.set('extname', newExtname)
668 await renamePromise(videoOutputPath, this.getVideoFilePath(inputVideoFile))
669 const stats = await statPromise(this.getVideoFilePath(inputVideoFile))
671 inputVideoFile.set('size', stats.size)
673 await this.createTorrentAndSetInfoHash(inputVideoFile)
674 await inputVideoFile.save()
677 // Auto destruction...
678 this.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', err))
684 transcodeOriginalVideofile = async function (this: VideoInstance, resolution: VideoResolution) {
685 const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
686 const extname = '.mp4'
688 // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed
689 const videoInputPath = join(videosDirectory, this.getVideoFilename(this.getOriginalFile()))
691 const newVideoFile = (Video['sequelize'].models.VideoFile as VideoFileModel).build({
697 const videoOutputPath = join(videosDirectory, this.getVideoFilename(newVideoFile))
699 const transcodeOptions = {
700 inputPath: videoInputPath,
701 outputPath: videoOutputPath,
705 await transcode(transcodeOptions)
707 const stats = await statPromise(videoOutputPath)
709 newVideoFile.set('size', stats.size)
711 await this.createTorrentAndSetInfoHash(newVideoFile)
713 await newVideoFile.save()
715 this.VideoFiles.push(newVideoFile)
718 getOriginalFileHeight = function (this: VideoInstance) {
719 const originalFilePath = this.getVideoFilePath(this.getOriginalFile())
721 return getVideoFileHeight(originalFilePath)
724 getDescriptionPath = function (this: VideoInstance) {
725 return `/api/${API_VERSION}/videos/${this.uuid}/description`
728 getCategoryLabel = function (this: VideoInstance) {
729 let categoryLabel = VIDEO_CATEGORIES[this.category]
731 // Maybe our server is not up to date and there are new categories since our version
732 if (!categoryLabel) categoryLabel = 'Misc'
737 getLicenceLabel = function (this: VideoInstance) {
738 let licenceLabel = VIDEO_LICENCES[this.licence]
740 // Maybe our server is not up to date and there are new licences since our version
741 if (!licenceLabel) licenceLabel = 'Unknown'
746 getLanguageLabel = function (this: VideoInstance) {
747 // Language is an optional attribute
748 let languageLabel = VIDEO_LANGUAGES[this.language]
749 if (!languageLabel) languageLabel = 'Unknown'
754 removeThumbnail = function (this: VideoInstance) {
755 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
756 return unlinkPromise(thumbnailPath)
759 removePreview = function (this: VideoInstance) {
760 // Same name than video thumbnail
761 return unlinkPromise(CONFIG.STORAGE.PREVIEWS_DIR + this.getPreviewName())
764 removeFile = function (this: VideoInstance, videoFile: VideoFileInstance) {
765 const filePath = join(CONFIG.STORAGE.VIDEOS_DIR, this.getVideoFilename(videoFile))
766 return unlinkPromise(filePath)
769 removeTorrent = function (this: VideoInstance, videoFile: VideoFileInstance) {
770 const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, this.getTorrentFileName(videoFile))
771 return unlinkPromise(torrentPath)
774 // ------------------------------ STATICS ------------------------------
778 include: [ Video['sequelize'].models.VideoFile ]
781 return Video.findAll(query)
784 listAllAndSharedByAccountForOutbox = function (accountId: number, start: number, count: number) {
785 function getRawQuery (select: string) {
786 const queryVideo = 'SELECT ' + select + ' FROM "Videos" AS "Video" ' +
787 'INNER JOIN "VideoChannels" AS "VideoChannel" ON "VideoChannel"."id" = "Video"."channelId" ' +
788 'WHERE "VideoChannel"."accountId" = ' + accountId
789 const queryVideoShare = 'SELECT ' + select + ' FROM "VideoShares" AS "VideoShare" ' +
790 'INNER JOIN "Videos" AS "Video" ON "Video"."id" = "VideoShare"."videoId" ' +
791 'WHERE "VideoShare"."accountId" = ' + accountId
793 let rawQuery = `(${queryVideo}) UNION (${queryVideoShare})`
798 const rawQuery = getRawQuery('"Video"."id"')
799 const rawCountQuery = getRawQuery('COUNT("Video"."id") as "total"')
805 order: [ getSort('createdAt'), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
808 [Sequelize.Op.in]: Sequelize.literal('(' + rawQuery + ')')
813 model: Video['sequelize'].models.VideoShare,
816 [Sequelize.Op.and]: [
819 [Sequelize.Op.not]: null
829 model: Video['sequelize'].models.VideoChannel,
833 model: Video['sequelize'].models.Account,
839 model: Video['sequelize'].models.AccountVideoRate,
840 include: [ Video['sequelize'].models.Account ]
842 Video['sequelize'].models.VideoFile,
843 Video['sequelize'].models.Tag
847 return Bluebird.all([
848 Video.findAll(query),
849 Video['sequelize'].query(rawCountQuery, { type: Sequelize.QueryTypes.SELECT })
850 ]).then(([ rows, totals ]) => {
851 // totals: totalVideos + totalVideoShares
853 let totalVideoShares = 0
854 if (totals[0]) totalVideos = parseInt(totals[0].total, 10)
855 if (totals[1]) totalVideoShares = parseInt(totals[1].total, 10)
857 const total = totalVideos + totalVideoShares
865 listUserVideosForApi = function (userId: number, start: number, count: number, sort: string) {
870 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
873 model: Video['sequelize'].models.VideoChannel,
877 model: Video['sequelize'].models.Account,
885 Video['sequelize'].models.Tag
889 return Video.findAndCountAll(query).then(({ rows, count }) => {
897 listForApi = function (start: number, count: number, sort: string) {
902 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
905 model: Video['sequelize'].models.VideoChannel,
909 model: Video['sequelize'].models.Account,
913 model: Video['sequelize'].models.Server,
920 Video['sequelize'].models.Tag
922 where: createBaseVideosWhere()
925 return Video.findAndCountAll(query).then(({ rows, count }) => {
933 load = function (id: number) {
934 return Video.findById(id)
937 loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
938 const query: Sequelize.FindOptions<VideoAttributes> = {
942 include: [ Video['sequelize'].models.VideoFile ]
945 if (t !== undefined) query.transaction = t
947 return Video.findOne(query)
950 loadByUrlAndPopulateAccount = function (url: string, t?: Sequelize.Transaction) {
951 const query: Sequelize.FindOptions<VideoAttributes> = {
956 Video['sequelize'].models.VideoFile,
958 model: Video['sequelize'].models.VideoChannel,
959 include: [ Video['sequelize'].models.Account ]
964 if (t !== undefined) query.transaction = t
966 return Video.findOne(query)
969 loadByUUIDOrURL = function (uuid: string, url: string, t?: Sequelize.Transaction) {
970 const query: Sequelize.FindOptions<VideoAttributes> = {
977 include: [ Video['sequelize'].models.VideoFile ]
980 if (t !== undefined) query.transaction = t
982 return Video.findOne(query)
985 loadAndPopulateAccountAndServerAndTags = function (id: number) {
987 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
990 model: Video['sequelize'].models.VideoChannel,
993 model: Video['sequelize'].models.Account,
994 include: [ { model: Video['sequelize'].models.Server, required: false } ]
999 model: Video['sequelize'].models.AccountVideoRate,
1000 include: [ Video['sequelize'].models.Account ]
1003 model: Video['sequelize'].models.VideoShare,
1004 include: [ Video['sequelize'].models.Account ]
1006 Video['sequelize'].models.Tag,
1007 Video['sequelize'].models.VideoFile
1011 return Video.findById(id, options)
1014 loadByUUIDAndPopulateAccountAndServerAndTags = function (uuid: string) {
1016 order: [ [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
1022 model: Video['sequelize'].models.VideoChannel,
1025 model: Video['sequelize'].models.Account,
1026 include: [ { model: Video['sequelize'].models.Server, required: false } ]
1031 model: Video['sequelize'].models.AccountVideoRate,
1032 include: [ Video['sequelize'].models.Account ]
1035 model: Video['sequelize'].models.VideoShare,
1036 include: [ Video['sequelize'].models.Account ]
1038 Video['sequelize'].models.Tag,
1039 Video['sequelize'].models.VideoFile
1043 return Video.findOne(options)
1046 searchAndPopulateAccountAndServerAndTags = function (value: string, field: string, start: number, count: number, sort: string) {
1047 const serverInclude: Sequelize.IncludeOptions = {
1048 model: Video['sequelize'].models.Server,
1052 const accountInclude: Sequelize.IncludeOptions = {
1053 model: Video['sequelize'].models.Account,
1054 include: [ serverInclude ]
1057 const videoChannelInclude: Sequelize.IncludeOptions = {
1058 model: Video['sequelize'].models.VideoChannel,
1059 include: [ accountInclude ],
1063 const tagInclude: Sequelize.IncludeOptions = {
1064 model: Video['sequelize'].models.Tag
1067 const query: Sequelize.FindOptions<VideoAttributes> = {
1069 where: createBaseVideosWhere(),
1072 order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ]
1075 if (field === 'tags') {
1076 const escapedValue = Video['sequelize'].escape('%' + value + '%')
1077 query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
1078 `(SELECT "VideoTags"."videoId"
1080 INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
1081 WHERE name ILIKE ${escapedValue}
1084 } else if (field === 'host') {
1085 // FIXME: Include our server? (not stored in the database)
1086 serverInclude.where = {
1088 [Sequelize.Op.iLike]: '%' + value + '%'
1091 serverInclude.required = true
1092 } else if (field === 'account') {
1093 accountInclude.where = {
1095 [Sequelize.Op.iLike]: '%' + value + '%'
1099 query.where[field] = {
1100 [Sequelize.Op.iLike]: '%' + value + '%'
1105 videoChannelInclude, tagInclude
1108 return Video.findAndCountAll(query).then(({ rows, count }) => {
1116 // ---------------------------------------------------------------------------
1118 function createBaseVideosWhere () {
1121 [Sequelize.Op.notIn]: Video['sequelize'].literal(
1122 '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
1125 privacy: VideoPrivacy.PUBLIC
1129 function getBaseUrls (video: VideoInstance) {
1133 if (video.isOwned()) {
1134 baseUrlHttp = CONFIG.WEBSERVER.URL
1135 baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
1137 baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Account.Server.host
1138 baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Account.Server.host
1141 return { baseUrlHttp, baseUrlWs }
1144 function getThumbnailUrl (video: VideoInstance, baseUrlHttp: string) {
1145 return baseUrlHttp + STATIC_PATHS.THUMBNAILS + video.getThumbnailName()
1148 function getTorrentUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1149 return baseUrlHttp + STATIC_PATHS.TORRENTS + video.getTorrentFileName(videoFile)
1152 function getVideoFileUrl (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string) {
1153 return baseUrlHttp + STATIC_PATHS.WEBSEED + video.getVideoFilename(videoFile)
1156 function generateMagnetUri (video: VideoInstance, videoFile: VideoFileInstance, baseUrlHttp: string, baseUrlWs: string) {
1157 const xs = getTorrentUrl(video, videoFile, baseUrlHttp)
1158 const announce = [ baseUrlWs + '/tracker/socket', baseUrlHttp + '/tracker/announce' ]
1159 const urlList = [ getVideoFileUrl(video, videoFile, baseUrlHttp) ]
1161 const magnetHash = {
1165 infoHash: videoFile.infoHash,
1169 return magnetUtil.encode(magnetHash)