1 import { join } from 'path'
2 import * as request from 'request'
3 import * as Sequelize from 'sequelize'
4 import * as url from 'url'
5 import { ActivityIconObject } from '../../shared/index'
6 import { Activity } from '../../shared/models/activitypub/activity'
7 import { ActivityPubActor } from '../../shared/models/activitypub/activitypub-actor'
8 import { VideoChannelObject } from '../../shared/models/activitypub/objects/video-channel-object'
9 import { ResultList } from '../../shared/models/result-list.model'
10 import { database as db, REMOTE_SCHEME } from '../initializers'
11 import { ACTIVITY_PUB_ACCEPT_HEADER, CONFIG, STATIC_PATHS } from '../initializers/constants'
12 import { videoChannelActivityObjectToDBAttributes } from '../lib/activitypub/misc'
13 import { sendVideoAnnounce } from '../lib/activitypub/send-request'
14 import { sendVideoChannelAnnounce } from '../lib/index'
15 import { AccountInstance } from '../models/account/account-interface'
16 import { VideoChannelInstance } from '../models/video/video-channel-interface'
17 import { VideoInstance } from '../models/video/video-interface'
18 import { isRemoteAccountValid } from './custom-validators'
19 import { isVideoChannelObjectValid } from './custom-validators/activitypub/videos'
20 import { logger } from './logger'
21 import { signObject } from './peertube-crypto'
22 import { doRequest, doRequestAndSaveToFile } from './requests'
23 import { getServerAccount } from './utils'
25 function generateThumbnailFromUrl (video: VideoInstance, icon: ActivityIconObject) {
26 const thumbnailName = video.getThumbnailName()
27 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
33 return doRequestAndSaveToFile(options, thumbnailPath)
36 async function shareVideoChannelByServer (videoChannel: VideoChannelInstance, t: Sequelize.Transaction) {
37 const serverAccount = await getServerAccount()
39 await db.VideoChannelShare.create({
40 accountId: serverAccount.id,
41 videoChannelId: videoChannel.id
42 }, { transaction: t })
44 return sendVideoChannelAnnounce(serverAccount, videoChannel, t)
47 async function shareVideoByServer (video: VideoInstance, t: Sequelize.Transaction) {
48 const serverAccount = await getServerAccount()
50 await db.VideoShare.create({
51 accountId: serverAccount.id,
53 }, { transaction: t })
55 return sendVideoAnnounce(serverAccount, video, t)
58 function getActivityPubUrl (type: 'video' | 'videoChannel' | 'account' | 'videoAbuse', id: string) {
59 if (type === 'video') return CONFIG.WEBSERVER.URL + '/videos/watch/' + id
60 else if (type === 'videoChannel') return CONFIG.WEBSERVER.URL + '/video-channels/' + id
61 else if (type === 'account') return CONFIG.WEBSERVER.URL + '/account/' + id
62 else if (type === 'videoAbuse') return CONFIG.WEBSERVER.URL + '/admin/video-abuses/' + id
67 async function getOrCreateAccount (accountUrl: string) {
68 let account = await db.Account.loadByUrl(accountUrl)
70 // We don't have this account in our database, fetch it on remote
72 const res = await fetchRemoteAccountAndCreateServer(accountUrl)
73 if (res === undefined) throw new Error('Cannot fetch remote account.')
75 // Save our new account in database
76 account = await res.account.save()
82 async function getOrCreateVideoChannel (ownerAccount: AccountInstance, videoChannelUrl: string) {
83 let videoChannel = await db.VideoChannel.loadByUrl(videoChannelUrl)
85 // We don't have this account in our database, fetch it on remote
87 videoChannel = await fetchRemoteVideoChannel(ownerAccount, videoChannelUrl)
88 if (videoChannel === undefined) throw new Error('Cannot fetch remote video channel.')
90 // Save our new video channel in database
91 await videoChannel.save()
97 async function fetchRemoteAccountAndCreateServer (accountUrl: string) {
102 'Accept': ACTIVITY_PUB_ACCEPT_HEADER
106 logger.info('Fetching remote account %s.', accountUrl)
110 requestResult = await doRequest(options)
112 logger.warn('Cannot fetch remote account %s.', accountUrl, err)
116 const accountJSON: ActivityPubActor = JSON.parse(requestResult.body)
117 if (isRemoteAccountValid(accountJSON) === false) {
118 logger.debug('Remote account JSON is not valid.', { accountJSON })
122 const followersCount = await fetchAccountCount(accountJSON.followers)
123 const followingCount = await fetchAccountCount(accountJSON.following)
125 const account = db.Account.build({
126 uuid: accountJSON.uuid,
127 name: accountJSON.preferredUsername,
128 url: accountJSON.url,
129 publicKey: accountJSON.publicKey.publicKeyPem,
131 followersCount: followersCount,
132 followingCount: followingCount,
133 inboxUrl: accountJSON.inbox,
134 outboxUrl: accountJSON.outbox,
135 sharedInboxUrl: accountJSON.endpoints.sharedInbox,
136 followersUrl: accountJSON.followers,
137 followingUrl: accountJSON.following
140 const accountHost = url.parse(account.url).host
141 const serverOptions = {
149 const [ server ] = await db.Server.findOrCreate(serverOptions)
150 account.set('serverId', server.id)
152 return { account, server }
155 async function fetchRemoteVideoChannel (ownerAccount: AccountInstance, videoChannelUrl: string) {
157 uri: videoChannelUrl,
160 'Accept': ACTIVITY_PUB_ACCEPT_HEADER
164 logger.info('Fetching remote video channel %s.', videoChannelUrl)
168 requestResult = await doRequest(options)
170 logger.warn('Cannot fetch remote video channel %s.', videoChannelUrl, err)
174 const videoChannelJSON: VideoChannelObject = JSON.parse(requestResult.body)
175 if (isVideoChannelObjectValid(videoChannelJSON) === false) {
176 logger.debug('Remote video channel JSON is not valid.', { videoChannelJSON })
180 const videoChannelAttributes = videoChannelActivityObjectToDBAttributes(videoChannelJSON, ownerAccount)
181 const videoChannel = db.VideoChannel.build(videoChannelAttributes)
182 videoChannel.Account = ownerAccount
187 function fetchRemoteVideoPreview (video: VideoInstance) {
189 const host = video.VideoChannel.Account.Server.host
190 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
192 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path)
195 async function fetchRemoteVideoDescription (video: VideoInstance) {
200 const { body } = await doRequest(options)
201 return body.description ? body.description : ''
204 function activityPubContextify <T> (data: T) {
205 return Object.assign(data,{
207 'https://www.w3.org/ns/activitystreams',
208 'https://w3id.org/security/v1',
210 'Hashtag': 'as:Hashtag',
211 'uuid': 'http://schema.org/identifier',
212 'category': 'http://schema.org/category',
213 'licence': 'http://schema.org/license',
214 'nsfw': 'as:sensitive',
215 'language': 'http://schema.org/inLanguage',
216 'views': 'http://schema.org/Number',
217 'size': 'http://schema.org/Number',
218 'VideoChannel': 'https://peertu.be/ns/VideoChannel'
224 function activityPubCollectionPagination (url: string, page: number, result: ResultList<any>) {
225 const baseUrl = url.split('?').shift
230 totalItems: result.total,
232 id: baseUrl + '?page=' + page,
233 type: 'CollectionPage',
234 totalItems: result.total,
235 next: baseUrl + '?page=' + (page + 1),
241 return activityPubContextify(obj)
244 function buildSignedActivity (byAccount: AccountInstance, data: Object) {
245 const activity = activityPubContextify(data)
247 return signObject(byAccount, activity) as Promise<Activity>
250 // ---------------------------------------------------------------------------
253 fetchRemoteAccountAndCreateServer,
254 activityPubContextify,
255 activityPubCollectionPagination,
257 generateThumbnailFromUrl,
259 fetchRemoteVideoPreview,
260 fetchRemoteVideoDescription,
261 shareVideoChannelByServer,
263 getOrCreateVideoChannel,
267 // ---------------------------------------------------------------------------
269 async function fetchAccountCount (url: string) {
277 requestResult = await doRequest(options)
279 logger.warn('Cannot fetch remote account count %s.', url, err)
283 return requestResult.totalItems ? requestResult.totalItems : 0