]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/videos.ts
263c2629c87561096841d268e51b511a927c8eac
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / videos.ts
1 import * as Bluebird from 'bluebird'
2 import * as magnetUtil from 'magnet-uri'
3 import { join } from 'path'
4 import * as request from 'request'
5 import { ActivityIconObject } from '../../../shared/index'
6 import { VideoTorrentObject } from '../../../shared/models/activitypub/objects'
7 import { VideoPrivacy } from '../../../shared/models/videos'
8 import { isVideoTorrentObjectValid } from '../../helpers/custom-validators/activitypub/videos'
9 import { isVideoFileInfoHashValid } from '../../helpers/custom-validators/videos'
10 import { retryTransactionWrapper } from '../../helpers/database-utils'
11 import { logger } from '../../helpers/logger'
12 import { doRequest, doRequestAndSaveToFile } from '../../helpers/requests'
13 import { ACTIVITY_PUB, CONFIG, REMOTE_SCHEME, sequelizeTypescript, STATIC_PATHS, VIDEO_MIMETYPE_EXT } from '../../initializers'
14 import { ActorModel } from '../../models/activitypub/actor'
15 import { TagModel } from '../../models/video/tag'
16 import { VideoModel } from '../../models/video/video'
17 import { VideoChannelModel } from '../../models/video/video-channel'
18 import { VideoFileModel } from '../../models/video/video-file'
19 import { VideoShareModel } from '../../models/video/video-share'
20 import { getOrCreateActorAndServerAndModel } from './actor'
21
22 function fetchRemoteVideoPreview (video: VideoModel, reject: Function) {
23 const host = video.VideoChannel.Account.Actor.Server.host
24 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
25
26 // We need to provide a callback, if no we could have an uncaught exception
27 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path, err => {
28 if (err) reject(err)
29 })
30 }
31
32 async function fetchRemoteVideoDescription (video: VideoModel) {
33 const host = video.VideoChannel.Account.Actor.Server.host
34 const path = video.getDescriptionPath()
35 const options = {
36 uri: REMOTE_SCHEME.HTTP + '://' + host + path,
37 json: true
38 }
39
40 const { body } = await doRequest(options)
41 return body.description ? body.description : ''
42 }
43
44 function generateThumbnailFromUrl (video: VideoModel, icon: ActivityIconObject) {
45 const thumbnailName = video.getThumbnailName()
46 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
47
48 const options = {
49 method: 'GET',
50 uri: icon.url
51 }
52 return doRequestAndSaveToFile(options, thumbnailPath)
53 }
54
55 async function videoActivityObjectToDBAttributes (videoChannel: VideoChannelModel,
56 videoObject: VideoTorrentObject,
57 to: string[] = [],
58 cc: string[] = []) {
59 let privacy = VideoPrivacy.PRIVATE
60 if (to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.PUBLIC
61 else if (cc.indexOf(ACTIVITY_PUB.PUBLIC) !== -1) privacy = VideoPrivacy.UNLISTED
62
63 const duration = videoObject.duration.replace(/[^\d]+/, '')
64 let language = null
65 if (videoObject.language) {
66 language = parseInt(videoObject.language.identifier, 10)
67 }
68
69 let category = null
70 if (videoObject.category) {
71 category = parseInt(videoObject.category.identifier, 10)
72 }
73
74 let licence = null
75 if (videoObject.licence) {
76 licence = parseInt(videoObject.licence.identifier, 10)
77 }
78
79 let description = null
80 if (videoObject.content) {
81 description = videoObject.content
82 }
83
84 return {
85 name: videoObject.name,
86 uuid: videoObject.uuid,
87 url: videoObject.id,
88 category,
89 licence,
90 language,
91 description,
92 nsfw: videoObject.nsfw,
93 commentsEnabled: videoObject.commentsEnabled,
94 channelId: videoChannel.id,
95 duration: parseInt(duration, 10),
96 createdAt: new Date(videoObject.published),
97 // FIXME: updatedAt does not seems to be considered by Sequelize
98 updatedAt: new Date(videoObject.updated),
99 views: videoObject.views,
100 likes: 0,
101 dislikes: 0,
102 remote: true,
103 privacy
104 }
105 }
106
107 function videoFileActivityUrlToDBAttributes (videoCreated: VideoModel, videoObject: VideoTorrentObject) {
108 const mimeTypes = Object.keys(VIDEO_MIMETYPE_EXT)
109 const fileUrls = videoObject.url.filter(u => {
110 return mimeTypes.indexOf(u.mimeType) !== -1 && u.mimeType.startsWith('video/')
111 })
112
113 if (fileUrls.length === 0) {
114 throw new Error('Cannot find video files for ' + videoCreated.url)
115 }
116
117 const attributes = []
118 for (const fileUrl of fileUrls) {
119 // Fetch associated magnet uri
120 const magnet = videoObject.url.find(u => {
121 return u.mimeType === 'application/x-bittorrent;x-scheme-handler/magnet' && u.width === fileUrl.width
122 })
123
124 if (!magnet) throw new Error('Cannot find associated magnet uri for file ' + fileUrl.href)
125
126 const parsed = magnetUtil.decode(magnet.href)
127 if (!parsed || isVideoFileInfoHashValid(parsed.infoHash) === false) throw new Error('Cannot parse magnet URI ' + magnet.href)
128
129 const attribute = {
130 extname: VIDEO_MIMETYPE_EXT[ fileUrl.mimeType ],
131 infoHash: parsed.infoHash,
132 resolution: fileUrl.width,
133 size: fileUrl.size,
134 videoId: videoCreated.id
135 }
136 attributes.push(attribute)
137 }
138
139 return attributes
140 }
141
142 async function getOrCreateVideo (videoObject: VideoTorrentObject, channelActor: ActorModel) {
143 logger.debug('Adding remote video %s.', videoObject.id)
144
145 return sequelizeTypescript.transaction(async t => {
146 const sequelizeOptions = {
147 transaction: t
148 }
149 const videoFromDatabase = await VideoModel.loadByUUIDOrURLAndPopulateAccount(videoObject.uuid, videoObject.id, t)
150 if (videoFromDatabase) return videoFromDatabase
151
152 const videoData = await videoActivityObjectToDBAttributes(channelActor.VideoChannel, videoObject, videoObject.to, videoObject.cc)
153 const video = VideoModel.build(videoData)
154
155 // Don't block on request
156 generateThumbnailFromUrl(video, videoObject.icon)
157 .catch(err => logger.warn('Cannot generate thumbnail of %s.', videoObject.id, err))
158
159 const videoCreated = await video.save(sequelizeOptions)
160
161 const videoFileAttributes = videoFileActivityUrlToDBAttributes(videoCreated, videoObject)
162 if (videoFileAttributes.length === 0) {
163 throw new Error('Cannot find valid files for video %s ' + videoObject.url)
164 }
165
166 const tasks = videoFileAttributes.map(f => VideoFileModel.create(f, { transaction: t }))
167 await Promise.all(tasks)
168
169 const tags = videoObject.tag.map(t => t.name)
170 const tagInstances = await TagModel.findOrCreateTags(tags, t)
171 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
172
173 logger.info('Remote video with uuid %s inserted.', videoObject.uuid)
174
175 videoCreated.VideoChannel = channelActor.VideoChannel
176 return videoCreated
177 })
178 }
179
180 async function getOrCreateAccountAndVideoAndChannel (videoObject: VideoTorrentObject | string, actor?: ActorModel) {
181 if (typeof videoObject === 'string') {
182 const videoFromDatabase = await VideoModel.loadByUrlAndPopulateAccount(videoObject)
183 if (videoFromDatabase) {
184 return {
185 video: videoFromDatabase,
186 actor: videoFromDatabase.VideoChannel.Account.Actor,
187 channelActor: videoFromDatabase.VideoChannel.Actor
188 }
189 }
190
191 videoObject = await fetchRemoteVideo(videoObject)
192 if (!videoObject) throw new Error('Cannot fetch remote video')
193 }
194
195 if (!actor) {
196 const actorObj = videoObject.attributedTo.find(a => a.type === 'Person')
197 if (!actorObj) throw new Error('Cannot find associated actor to video ' + videoObject.url)
198
199 actor = await getOrCreateActorAndServerAndModel(actorObj.id)
200 }
201
202 const channel = videoObject.attributedTo.find(a => a.type === 'Group')
203 if (!channel) throw new Error('Cannot find associated video channel to video ' + videoObject.url)
204
205 const channelActor = await getOrCreateActorAndServerAndModel(channel.id)
206
207 const options = {
208 arguments: [ videoObject, channelActor ],
209 errorMessage: 'Cannot insert the remote video with many retries.'
210 }
211
212 const video = await retryTransactionWrapper(getOrCreateVideo, options)
213
214 return { actor, channelActor, video }
215 }
216
217 async function addVideoShares (instance: VideoModel, shareUrls: string[]) {
218 for (const shareUrl of shareUrls) {
219 // Fetch url
220 const { body } = await doRequest({
221 uri: shareUrl,
222 json: true,
223 activityPub: true
224 })
225 const actorUrl = body.actor
226 if (!actorUrl) continue
227
228 const actor = await getOrCreateActorAndServerAndModel(actorUrl)
229
230 const entry = {
231 actorId: actor.id,
232 videoId: instance.id
233 }
234
235 await VideoShareModel.findOrCreate({
236 where: entry,
237 defaults: entry
238 })
239 }
240 }
241
242 export {
243 getOrCreateAccountAndVideoAndChannel,
244 fetchRemoteVideoPreview,
245 fetchRemoteVideoDescription,
246 generateThumbnailFromUrl,
247 videoActivityObjectToDBAttributes,
248 videoFileActivityUrlToDBAttributes,
249 getOrCreateVideo,
250 addVideoShares}
251
252 // ---------------------------------------------------------------------------
253
254 async function fetchRemoteVideo (videoUrl: string): Promise<VideoTorrentObject> {
255 const options = {
256 uri: videoUrl,
257 method: 'GET',
258 json: true,
259 activityPub: true
260 }
261
262 logger.info('Fetching remote video %s.', videoUrl)
263
264 const { body } = await doRequest(options)
265
266 if (isVideoTorrentObjectValid(body) === false) {
267 logger.debug('Remote video JSON is not valid.', { body })
268 return undefined
269 }
270
271 return body
272 }