]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/models/video/video.ts
Lazy description and previews to video form
[github/Chocobozzz/PeerTube.git] / server / models / video / video.ts
index 0b1af4d21efb9963f2382a875986e39b47b955cd..1877c506ae63bf07acbf85e5f359df39eb85c816 100644 (file)
@@ -6,7 +6,7 @@ import * as parseTorrent from 'parse-torrent'
 import { join } from 'path'
 import * as Sequelize from 'sequelize'
 import * as Promise from 'bluebird'
-import { maxBy } from 'lodash'
+import { maxBy, truncate } from 'lodash'
 
 import { TagInstance } from './tag-interface'
 import {
@@ -35,7 +35,10 @@ import {
   VIDEO_CATEGORIES,
   VIDEO_LICENCES,
   VIDEO_LANGUAGES,
-  THUMBNAILS_SIZE
+  THUMBNAILS_SIZE,
+  PREVIEWS_SIZE,
+  CONSTRAINTS_FIELDS,
+  API_VERSION
 } from '../../initializers'
 import { removeVideoToFriends } from '../../lib'
 import { VideoResolution } from '../../../shared'
@@ -48,7 +51,6 @@ import {
 
   VideoMethods
 } from './video-interface'
-import { PREVIEWS_SIZE } from '../../initializers/constants'
 
 let Video: Sequelize.Model<VideoInstance, VideoAttributes>
 let getOriginalFile: VideoMethods.GetOriginalFile
@@ -60,6 +62,7 @@ let getPreviewPath: VideoMethods.GetPreviewPath
 let getTorrentFileName: VideoMethods.GetTorrentFileName
 let isOwned: VideoMethods.IsOwned
 let toFormattedJSON: VideoMethods.ToFormattedJSON
+let toFormattedDetailsJSON: VideoMethods.ToFormattedDetailsJSON
 let toAddRemoteJSON: VideoMethods.ToAddRemoteJSON
 let toUpdateRemoteJSON: VideoMethods.ToUpdateRemoteJSON
 let optimizeOriginalVideofile: VideoMethods.OptimizeOriginalVideofile
@@ -70,6 +73,8 @@ let getVideoFilePath: VideoMethods.GetVideoFilePath
 let createTorrentAndSetInfoHash: VideoMethods.CreateTorrentAndSetInfoHash
 let getOriginalFileHeight: VideoMethods.GetOriginalFileHeight
 let getEmbedPath: VideoMethods.GetEmbedPath
+let getDescriptionPath: VideoMethods.GetDescriptionPath
+let getTruncatedDescription: VideoMethods.GetTruncatedDescription
 
 let generateThumbnailFromData: VideoMethods.GenerateThumbnailFromData
 let list: VideoMethods.List
@@ -79,6 +84,7 @@ let listOwnedAndPopulateAuthorAndTags: VideoMethods.ListOwnedAndPopulateAuthorAn
 let listOwnedByAuthor: VideoMethods.ListOwnedByAuthor
 let load: VideoMethods.Load
 let loadByUUID: VideoMethods.LoadByUUID
+let loadLocalVideoByUUID: VideoMethods.LoadLocalVideoByUUID
 let loadAndPopulateAuthor: VideoMethods.LoadAndPopulateAuthor
 let loadAndPopulateAuthorAndPodAndTags: VideoMethods.LoadAndPopulateAuthorAndPodAndTags
 let loadByUUIDAndPopulateAuthorAndPodAndTags: VideoMethods.LoadByUUIDAndPopulateAuthorAndPodAndTags
@@ -151,7 +157,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
         }
       },
       description: {
-        type: DataTypes.STRING,
+        type: DataTypes.STRING(CONSTRAINTS_FIELDS.VIDEOS.DESCRIPTION.max),
         allowNull: false,
         validate: {
           descriptionValid: value => {
@@ -205,9 +211,6 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
     },
     {
       indexes: [
-        {
-          fields: [ 'authorId' ]
-        },
         {
           fields: [ 'name' ]
         },
@@ -225,6 +228,9 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
         },
         {
           fields: [ 'uuid' ]
+        },
+        {
+          fields: [ 'channelId' ]
         }
       ],
       hooks: {
@@ -246,6 +252,7 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
     loadAndPopulateAuthorAndPodAndTags,
     loadByHostAndUUID,
     loadByUUID,
+    loadLocalVideoByUUID,
     loadByUUIDAndPopulateAuthorAndPodAndTags,
     searchAndPopulateAuthorAndPodAndTags
   ]
@@ -268,11 +275,14 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
     removeTorrent,
     toAddRemoteJSON,
     toFormattedJSON,
+    toFormattedDetailsJSON,
     toUpdateRemoteJSON,
     optimizeOriginalVideofile,
     transcodeOriginalVideofile,
     getOriginalFileHeight,
-    getEmbedPath
+    getEmbedPath,
+    getTruncatedDescription,
+    getDescriptionPath
   ]
   addMethodsToModel(Video, classMethods, instanceMethods)
 
@@ -282,9 +292,9 @@ export default function (sequelize: Sequelize.Sequelize, DataTypes: Sequelize.Da
 // ------------------------------ METHODS ------------------------------
 
 function associate (models) {
-  Video.belongsTo(models.Author, {
+  Video.belongsTo(models.VideoChannel, {
     foreignKey: {
-      name: 'authorId',
+      name: 'channelId',
       allowNull: false
     },
     onDelete: 'cascade'
@@ -313,7 +323,7 @@ function associate (models) {
   })
 }
 
-function afterDestroy (video: VideoInstance, options: { transaction: Sequelize.Transaction }) {
+function afterDestroy (video: VideoInstance) {
   const tasks = []
 
   tasks.push(
@@ -327,7 +337,7 @@ function afterDestroy (video: VideoInstance, options: { transaction: Sequelize.T
 
     tasks.push(
       video.removePreview(),
-      removeVideoToFriends(removeVideoToFriendsParams, options.transaction)
+      removeVideoToFriends(removeVideoToFriendsParams)
     )
 
     // Remove physical files and torrents
@@ -339,7 +349,7 @@ function afterDestroy (video: VideoInstance, options: { transaction: Sequelize.T
 
   return Promise.all(tasks)
     .catch(err => {
-      logger.error('Some errors when removing files of video %d in after destroy hook.', video.uuid, err)
+      logger.error('Some errors when removing files of video %s in after destroy hook.', video.uuid, err)
     })
 }
 
@@ -439,8 +449,8 @@ getPreviewPath = function (this: VideoInstance) {
 toFormattedJSON = function (this: VideoInstance) {
   let podHost
 
-  if (this.Author.Pod) {
-    podHost = this.Author.Pod.host
+  if (this.VideoChannel.Author.Pod) {
+    podHost = this.VideoChannel.Author.Pod.host
   } else {
     // It means it's our video
     podHost = CONFIG.WEBSERVER.HOST
@@ -469,10 +479,10 @@ toFormattedJSON = function (this: VideoInstance) {
     language: this.language,
     languageLabel,
     nsfw: this.nsfw,
-    description: this.description,
+    description: this.getTruncatedDescription(),
     podHost,
     isLocal: this.isOwned(),
-    author: this.Author.name,
+    author: this.VideoChannel.Author.name,
     duration: this.duration,
     views: this.views,
     likes: this.likes,
@@ -482,13 +492,24 @@ toFormattedJSON = function (this: VideoInstance) {
     previewPath: this.getPreviewPath(),
     embedPath: this.getEmbedPath(),
     createdAt: this.createdAt,
-    updatedAt: this.updatedAt,
+    updatedAt: this.updatedAt
+  }
+
+  return json
+}
+
+toFormattedDetailsJSON = function (this: VideoInstance) {
+  const formattedJson = this.toFormattedJSON()
+
+  const detailsJson = {
+    descriptionPath: this.getDescriptionPath(),
+    channel: this.VideoChannel.toFormattedJSON(),
     files: []
   }
 
   // Format and sort video files
   const { baseUrlHttp, baseUrlWs } = getBaseUrls(this)
-  json.files = this.VideoFiles
+  detailsJson.files = this.VideoFiles
                    .map(videoFile => {
                      let resolutionLabel = videoFile.resolution + 'p'
 
@@ -509,7 +530,7 @@ toFormattedJSON = function (this: VideoInstance) {
                      return -1
                    })
 
-  return json
+  return Object.assign(formattedJson, detailsJson)
 }
 
 toAddRemoteJSON = function (this: VideoInstance) {
@@ -524,8 +545,8 @@ toAddRemoteJSON = function (this: VideoInstance) {
       licence: this.licence,
       language: this.language,
       nsfw: this.nsfw,
-      description: this.description,
-      author: this.Author.name,
+      truncatedDescription: this.getTruncatedDescription(),
+      channelUUID: this.VideoChannel.uuid,
       duration: this.duration,
       thumbnailData: thumbnailData.toString('binary'),
       tags: map<TagInstance, string>(this.Tags, 'name'),
@@ -558,8 +579,7 @@ toUpdateRemoteJSON = function (this: VideoInstance) {
     licence: this.licence,
     language: this.language,
     nsfw: this.nsfw,
-    description: this.description,
-    author: this.Author.name,
+    truncatedDescription: this.getTruncatedDescription(),
     duration: this.duration,
     tags: map<TagInstance, string>(this.Tags, 'name'),
     createdAt: this.createdAt,
@@ -582,6 +602,14 @@ toUpdateRemoteJSON = function (this: VideoInstance) {
   return json
 }
 
+getTruncatedDescription = function (this: VideoInstance) {
+  const options = {
+    length: CONSTRAINTS_FIELDS.VIDEOS.TRUNCATED_DESCRIPTION.max
+  }
+
+  return truncate(this.description, options)
+}
+
 optimizeOriginalVideofile = function (this: VideoInstance) {
   const videosDirectory = CONFIG.STORAGE.VIDEOS_DIR
   const newExtname = '.mp4'
@@ -674,6 +702,10 @@ getOriginalFileHeight = function (this: VideoInstance) {
   return getVideoFileHeight(originalFilePath)
 }
 
+getDescriptionPath = function (this: VideoInstance) {
+  return `/api/${API_VERSION}/videos/${this.uuid}/description`
+}
+
 removeThumbnail = function (this: VideoInstance) {
   const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, this.getThumbnailName())
   return unlinkPromise(thumbnailPath)
@@ -723,8 +755,18 @@ listForApi = function (start: number, count: number, sort: string) {
     order: [ getSort(sort), [ Video['sequelize'].models.Tag, 'name', 'ASC' ] ],
     include: [
       {
-        model: Video['sequelize'].models.Author,
-        include: [ { model: Video['sequelize'].models.Pod, required: false } ]
+        model: Video['sequelize'].models.VideoChannel,
+        include: [
+          {
+            model: Video['sequelize'].models.Author,
+            include: [
+              {
+                model: Video['sequelize'].models.Pod,
+                required: false
+              }
+            ]
+          }
+        ]
       },
       Video['sequelize'].models.Tag,
       Video['sequelize'].models.VideoFile
@@ -740,8 +782,8 @@ listForApi = function (start: number, count: number, sort: string) {
   })
 }
 
-loadByHostAndUUID = function (fromHost: string, uuid: string) {
-  const query = {
+loadByHostAndUUID = function (fromHost: string, uuid: string, t?: Sequelize.Transaction) {
+  const query: Sequelize.FindOptions<VideoAttributes> = {
     where: {
       uuid
     },
@@ -750,20 +792,27 @@ loadByHostAndUUID = function (fromHost: string, uuid: string) {
         model: Video['sequelize'].models.VideoFile
       },
       {
-        model: Video['sequelize'].models.Author,
+        model: Video['sequelize'].models.VideoChannel,
         include: [
           {
-            model: Video['sequelize'].models.Pod,
-            required: true,
-            where: {
-              host: fromHost
-            }
+            model: Video['sequelize'].models.Author,
+            include: [
+              {
+                model: Video['sequelize'].models.Pod,
+                required: true,
+                where: {
+                  host: fromHost
+                }
+              }
+            ]
           }
         ]
       }
     ]
   }
 
+  if (t !== undefined) query.transaction = t
+
   return Video.findOne(query)
 }
 
@@ -774,7 +823,10 @@ listOwnedAndPopulateAuthorAndTags = function () {
     },
     include: [
       Video['sequelize'].models.VideoFile,
-      Video['sequelize'].models.Author,
+      {
+        model: Video['sequelize'].models.VideoChannel,
+        include: [ Video['sequelize'].models.Author ]
+      },
       Video['sequelize'].models.Tag
     ]
   }
@@ -792,10 +844,15 @@ listOwnedByAuthor = function (author: string) {
         model: Video['sequelize'].models.VideoFile
       },
       {
-        model: Video['sequelize'].models.Author,
-        where: {
-          name: author
-        }
+        model: Video['sequelize'].models.VideoChannel,
+        include: [
+          {
+            model: Video['sequelize'].models.Author,
+            where: {
+              name: author
+            }
+          }
+        ]
       }
     ]
   }
@@ -807,19 +864,42 @@ load = function (id: number) {
   return Video.findById(id)
 }
 
-loadByUUID = function (uuid: string) {
-  const query = {
+loadByUUID = function (uuid: string, t?: Sequelize.Transaction) {
+  const query: Sequelize.FindOptions<VideoAttributes> = {
     where: {
       uuid
     },
     include: [ Video['sequelize'].models.VideoFile ]
   }
+
+  if (t !== undefined) query.transaction = t
+
+  return Video.findOne(query)
+}
+
+loadLocalVideoByUUID = function (uuid: string, t?: Sequelize.Transaction) {
+  const query: Sequelize.FindOptions<VideoAttributes> = {
+    where: {
+      uuid,
+      remote: false
+    },
+    include: [ Video['sequelize'].models.VideoFile ]
+  }
+
+  if (t !== undefined) query.transaction = t
+
   return Video.findOne(query)
 }
 
 loadAndPopulateAuthor = function (id: number) {
   const options = {
-    include: [ Video['sequelize'].models.VideoFile, Video['sequelize'].models.Author ]
+    include: [
+      Video['sequelize'].models.VideoFile,
+      {
+        model: Video['sequelize'].models.VideoChannel,
+        include: [ Video['sequelize'].models.Author ]
+      }
+    ]
   }
 
   return Video.findById(id, options)
@@ -829,8 +909,13 @@ loadAndPopulateAuthorAndPodAndTags = function (id: number) {
   const options = {
     include: [
       {
-        model: Video['sequelize'].models.Author,
-        include: [ { model: Video['sequelize'].models.Pod, required: false } ]
+        model: Video['sequelize'].models.VideoChannel,
+        include: [
+          {
+            model: Video['sequelize'].models.Author,
+            include: [ { model: Video['sequelize'].models.Pod, required: false } ]
+          }
+        ]
       },
       Video['sequelize'].models.Tag,
       Video['sequelize'].models.VideoFile
@@ -847,8 +932,13 @@ loadByUUIDAndPopulateAuthorAndPodAndTags = function (uuid: string) {
     },
     include: [
       {
-        model: Video['sequelize'].models.Author,
-        include: [ { model: Video['sequelize'].models.Pod, required: false } ]
+        model: Video['sequelize'].models.VideoChannel,
+        include: [
+          {
+            model: Video['sequelize'].models.Author,
+            include: [ { model: Video['sequelize'].models.Pod, required: false } ]
+          }
+        ]
       },
       Video['sequelize'].models.Tag,
       Video['sequelize'].models.VideoFile
@@ -866,9 +956,13 @@ searchAndPopulateAuthorAndPodAndTags = function (value: string, field: string, s
 
   const authorInclude: Sequelize.IncludeOptions = {
     model: Video['sequelize'].models.Author,
-    include: [
-      podInclude
-    ]
+    include: [ podInclude ]
+  }
+
+  const videoChannelInclude: Sequelize.IncludeOptions = {
+    model: Video['sequelize'].models.VideoChannel,
+    include: [ authorInclude ],
+    required: true
   }
 
   const tagInclude: Sequelize.IncludeOptions = {
@@ -894,7 +988,7 @@ searchAndPopulateAuthorAndPodAndTags = function (value: string, field: string, s
     }
   } else if (field === 'tags') {
     const escapedValue = Video['sequelize'].escape('%' + value + '%')
-    query.where['id'].$in = Video['sequelize'].literal(
+    query.where['id'][Sequelize.Op.in] = Video['sequelize'].literal(
       `(SELECT "VideoTags"."videoId"
         FROM "Tags"
         INNER JOIN "VideoTags" ON "Tags"."id" = "VideoTags"."tagId"
@@ -905,26 +999,24 @@ searchAndPopulateAuthorAndPodAndTags = function (value: string, field: string, s
     // FIXME: Include our pod? (not stored in the database)
     podInclude.where = {
       host: {
-        $iLike: '%' + value + '%'
+        [Sequelize.Op.iLike]: '%' + value + '%'
       }
     }
     podInclude.required = true
   } else if (field === 'author') {
     authorInclude.where = {
       name: {
-        $iLike: '%' + value + '%'
+        [Sequelize.Op.iLike]: '%' + value + '%'
       }
     }
-
-    // authorInclude.or = true
   } else {
     query.where[field] = {
-      $iLike: '%' + value + '%'
+      [Sequelize.Op.iLike]: '%' + value + '%'
     }
   }
 
   query.include = [
-    authorInclude, tagInclude, videoFileInclude
+    videoChannelInclude, tagInclude, videoFileInclude
   ]
 
   return Video.findAndCountAll(query).then(({ rows, count }) => {
@@ -940,7 +1032,7 @@ searchAndPopulateAuthorAndPodAndTags = function (value: string, field: string, s
 function createBaseVideosWhere () {
   return {
     id: {
-      $notIn: Video['sequelize'].literal(
+      [Sequelize.Op.notIn]: Video['sequelize'].literal(
         '(SELECT "BlacklistedVideos"."videoId" FROM "BlacklistedVideos")'
       )
     }
@@ -955,8 +1047,8 @@ function getBaseUrls (video: VideoInstance) {
     baseUrlHttp = CONFIG.WEBSERVER.URL
     baseUrlWs = CONFIG.WEBSERVER.WS + '://' + CONFIG.WEBSERVER.HOSTNAME + ':' + CONFIG.WEBSERVER.PORT
   } else {
-    baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.Author.Pod.host
-    baseUrlWs = REMOTE_SCHEME.WS + '://' + video.Author.Pod.host
+    baseUrlHttp = REMOTE_SCHEME.HTTP + '://' + video.VideoChannel.Author.Pod.host
+    baseUrlWs = REMOTE_SCHEME.WS + '://' + video.VideoChannel.Author.Pod.host
   }
 
   return { baseUrlHttp, baseUrlWs }