]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/helpers/activitypub.ts
Server shares user videos
[github/Chocobozzz/PeerTube.git] / server / helpers / activitypub.ts
CommitLineData
571389d4
C
1import { join } from 'path'
2import * as request from 'request'
efc32059 3import * as Sequelize from 'sequelize'
e4f97bab 4import * as url from 'url'
571389d4 5import { ActivityIconObject } from '../../shared/index'
e4f97bab 6import { ActivityPubActor } from '../../shared/models/activitypub/activitypub-actor'
20494f12 7import { VideoChannelObject } from '../../shared/models/activitypub/objects/video-channel-object'
e4f97bab 8import { ResultList } from '../../shared/models/result-list.model'
571389d4 9import { database as db, REMOTE_SCHEME } from '../initializers'
350e31d6 10import { ACTIVITY_PUB_ACCEPT_HEADER, CONFIG, STATIC_PATHS } from '../initializers/constants'
20494f12
C
11import { videoChannelActivityObjectToDBAttributes } from '../lib/activitypub/misc'
12import { sendVideoAnnounce } from '../lib/activitypub/send-request'
13import { sendVideoChannelAnnounce } from '../lib/index'
14import { AccountInstance } from '../models/account/account-interface'
efc32059 15import { VideoChannelInstance } from '../models/video/video-channel-interface'
0d0e8dd0 16import { VideoInstance } from '../models/video/video-interface'
571389d4 17import { isRemoteAccountValid } from './custom-validators'
20494f12 18import { isVideoChannelObjectValid } from './custom-validators/activitypub/videos'
571389d4
C
19import { logger } from './logger'
20import { doRequest, doRequestAndSaveToFile } from './requests'
efc32059 21import { getServerAccount } from './utils'
0d0e8dd0
C
22
23function generateThumbnailFromUrl (video: VideoInstance, icon: ActivityIconObject) {
24 const thumbnailName = video.getThumbnailName()
25 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
26
27 const options = {
28 method: 'GET',
29 uri: icon.url
30 }
31 return doRequestAndSaveToFile(options, thumbnailPath)
32}
33
efc32059
C
34async function shareVideoChannelByServer (videoChannel: VideoChannelInstance, t: Sequelize.Transaction) {
35 const serverAccount = await getServerAccount()
36
37 await db.VideoChannelShare.create({
38 accountId: serverAccount.id,
39 videoChannelId: videoChannel.id
40 }, { transaction: t })
41
20494f12 42 return sendVideoChannelAnnounce(serverAccount, videoChannel, t)
efc32059
C
43}
44
45async function shareVideoByServer (video: VideoInstance, t: Sequelize.Transaction) {
46 const serverAccount = await getServerAccount()
47
48 await db.VideoShare.create({
49 accountId: serverAccount.id,
50 videoId: video.id
51 }, { transaction: t })
52
20494f12 53 return sendVideoAnnounce(serverAccount, video, t)
efc32059
C
54}
55
8e13fa7d 56function getActivityPubUrl (type: 'video' | 'videoChannel' | 'account' | 'videoAbuse', id: string) {
571389d4
C
57 if (type === 'video') return CONFIG.WEBSERVER.URL + '/videos/watch/' + id
58 else if (type === 'videoChannel') return CONFIG.WEBSERVER.URL + '/video-channels/' + id
59 else if (type === 'account') return CONFIG.WEBSERVER.URL + '/account/' + id
8e13fa7d 60 else if (type === 'videoAbuse') return CONFIG.WEBSERVER.URL + '/admin/video-abuses/' + id
0d0e8dd0
C
61
62 return ''
63}
64
65async function getOrCreateAccount (accountUrl: string) {
66 let account = await db.Account.loadByUrl(accountUrl)
67
68 // We don't have this account in our database, fetch it on remote
69 if (!account) {
60862425 70 const res = await fetchRemoteAccountAndCreateServer(accountUrl)
350e31d6 71 if (res === undefined) throw new Error('Cannot fetch remote account.')
0d0e8dd0
C
72
73 // Save our new account in database
20494f12 74 account = await res.account.save()
0d0e8dd0
C
75 }
76
77 return account
78}
e4f97bab 79
20494f12
C
80async function getOrCreateVideoChannel (ownerAccount: AccountInstance, videoChannelUrl: string) {
81 let videoChannel = await db.VideoChannel.loadByUrl(videoChannelUrl)
82
83 // We don't have this account in our database, fetch it on remote
84 if (!videoChannel) {
85 videoChannel = await fetchRemoteVideoChannel(ownerAccount, videoChannelUrl)
86 if (videoChannel === undefined) throw new Error('Cannot fetch remote video channel.')
87
88 // Save our new video channel in database
89 await videoChannel.save()
90 }
91
92 return videoChannel
93}
94
60862425 95async function fetchRemoteAccountAndCreateServer (accountUrl: string) {
e4f97bab
C
96 const options = {
97 uri: accountUrl,
350e31d6
C
98 method: 'GET',
99 headers: {
100 'Accept': ACTIVITY_PUB_ACCEPT_HEADER
101 }
e4f97bab
C
102 }
103
350e31d6
C
104 logger.info('Fetching remote account %s.', accountUrl)
105
e4f97bab
C
106 let requestResult
107 try {
108 requestResult = await doRequest(options)
109 } catch (err) {
350e31d6 110 logger.warn('Cannot fetch remote account %s.', accountUrl, err)
e4f97bab
C
111 return undefined
112 }
113
350e31d6
C
114 const accountJSON: ActivityPubActor = JSON.parse(requestResult.body)
115 if (isRemoteAccountValid(accountJSON) === false) {
116 logger.debug('Remote account JSON is not valid.', { accountJSON })
117 return undefined
118 }
e4f97bab
C
119
120 const followersCount = await fetchAccountCount(accountJSON.followers)
121 const followingCount = await fetchAccountCount(accountJSON.following)
122
123 const account = db.Account.build({
124 uuid: accountJSON.uuid,
125 name: accountJSON.preferredUsername,
126 url: accountJSON.url,
127 publicKey: accountJSON.publicKey.publicKeyPem,
128 privateKey: null,
129 followersCount: followersCount,
130 followingCount: followingCount,
131 inboxUrl: accountJSON.inbox,
132 outboxUrl: accountJSON.outbox,
133 sharedInboxUrl: accountJSON.endpoints.sharedInbox,
134 followersUrl: accountJSON.followers,
135 followingUrl: accountJSON.following
136 })
137
138 const accountHost = url.parse(account.url).host
60862425 139 const serverOptions = {
e4f97bab
C
140 where: {
141 host: accountHost
142 },
143 defaults: {
144 host: accountHost
145 }
146 }
60862425
C
147 const [ server ] = await db.Server.findOrCreate(serverOptions)
148 account.set('serverId', server.id)
e4f97bab 149
60862425 150 return { account, server }
e4f97bab
C
151}
152
20494f12
C
153async function fetchRemoteVideoChannel (ownerAccount: AccountInstance, videoChannelUrl: string) {
154 const options = {
155 uri: videoChannelUrl,
156 method: 'GET',
157 headers: {
158 'Accept': ACTIVITY_PUB_ACCEPT_HEADER
159 }
160 }
161
162 logger.info('Fetching remote video channel %s.', videoChannelUrl)
163
164 let requestResult
165 try {
166 requestResult = await doRequest(options)
167 } catch (err) {
168 logger.warn('Cannot fetch remote video channel %s.', videoChannelUrl, err)
169 return undefined
170 }
171
172 const videoChannelJSON: VideoChannelObject = JSON.parse(requestResult.body)
173 if (isVideoChannelObjectValid(videoChannelJSON) === false) {
174 logger.debug('Remote video channel JSON is not valid.', { videoChannelJSON })
175 return undefined
176 }
177
178 const videoChannelAttributes = videoChannelActivityObjectToDBAttributes(videoChannelJSON, ownerAccount)
179 const videoChannel = db.VideoChannel.build(videoChannelAttributes)
180 videoChannel.Account = ownerAccount
181
182 return videoChannel
183}
184
571389d4
C
185function fetchRemoteVideoPreview (video: VideoInstance) {
186 // FIXME: use url
60862425 187 const host = video.VideoChannel.Account.Server.host
571389d4
C
188 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
189
190 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path)
191}
192
193async function fetchRemoteVideoDescription (video: VideoInstance) {
194 const options = {
195 uri: video.url
196 }
197
198 const { body } = await doRequest(options)
199 return body.description ? body.description : ''
200}
201
202function activityPubContextify <T> (data: T) {
e4f97bab
C
203 return Object.assign(data,{
204 '@context': [
205 'https://www.w3.org/ns/activitystreams',
206 'https://w3id.org/security/v1',
207 {
208 'Hashtag': 'as:Hashtag',
209 'uuid': 'http://schema.org/identifier',
210 'category': 'http://schema.org/category',
211 'licence': 'http://schema.org/license',
212 'nsfw': 'as:sensitive',
213 'language': 'http://schema.org/inLanguage',
214 'views': 'http://schema.org/Number',
8e13fa7d
C
215 'size': 'http://schema.org/Number',
216 'VideoChannel': 'https://peertu.be/ns/VideoChannel'
e4f97bab
C
217 }
218 ]
219 })
220}
221
222function activityPubCollectionPagination (url: string, page: number, result: ResultList<any>) {
223 const baseUrl = url.split('?').shift
224
225 const obj = {
226 id: baseUrl,
227 type: 'Collection',
228 totalItems: result.total,
229 first: {
230 id: baseUrl + '?page=' + page,
231 type: 'CollectionPage',
232 totalItems: result.total,
233 next: baseUrl + '?page=' + (page + 1),
234 partOf: baseUrl,
235 items: result.data
236 }
237 }
238
239 return activityPubContextify(obj)
240}
241
242// ---------------------------------------------------------------------------
243
244export {
60862425 245 fetchRemoteAccountAndCreateServer,
e4f97bab 246 activityPubContextify,
0d0e8dd0
C
247 activityPubCollectionPagination,
248 getActivityPubUrl,
249 generateThumbnailFromUrl,
571389d4
C
250 getOrCreateAccount,
251 fetchRemoteVideoPreview,
efc32059
C
252 fetchRemoteVideoDescription,
253 shareVideoChannelByServer,
20494f12
C
254 shareVideoByServer,
255 getOrCreateVideoChannel
e4f97bab
C
256}
257
258// ---------------------------------------------------------------------------
259
260async function fetchAccountCount (url: string) {
261 const options = {
262 uri: url,
263 method: 'GET'
264 }
265
266 let requestResult
267 try {
268 requestResult = await doRequest(options)
269 } catch (err) {
350e31d6 270 logger.warn('Cannot fetch remote account count %s.', url, err)
e4f97bab
C
271 return undefined
272 }
273
274 return requestResult.totalItems ? requestResult.totalItems : 0
275}