1 import { join } from 'path'
2 import * as request from 'request'
3 import * as url from 'url'
4 import { ActivityIconObject } from '../../shared/index'
5 import { ActivityPubActor } from '../../shared/models/activitypub/activitypub-actor'
6 import { ResultList } from '../../shared/models/result-list.model'
7 import { database as db, REMOTE_SCHEME } from '../initializers'
8 import { ACTIVITY_PUB_ACCEPT_HEADER, CONFIG, STATIC_PATHS } from '../initializers/constants'
9 import { VideoInstance } from '../models/video/video-interface'
10 import { isRemoteAccountValid } from './custom-validators'
11 import { logger } from './logger'
12 import { doRequest, doRequestAndSaveToFile } from './requests'
14 function generateThumbnailFromUrl (video: VideoInstance, icon: ActivityIconObject) {
15 const thumbnailName = video.getThumbnailName()
16 const thumbnailPath = join(CONFIG.STORAGE.THUMBNAILS_DIR, thumbnailName)
22 return doRequestAndSaveToFile(options, thumbnailPath)
25 function getActivityPubUrl (type: 'video' | 'videoChannel' | 'account' | 'videoAbuse', id: string) {
26 if (type === 'video') return CONFIG.WEBSERVER.URL + '/videos/watch/' + id
27 else if (type === 'videoChannel') return CONFIG.WEBSERVER.URL + '/video-channels/' + id
28 else if (type === 'account') return CONFIG.WEBSERVER.URL + '/account/' + id
29 else if (type === 'videoAbuse') return CONFIG.WEBSERVER.URL + '/admin/video-abuses/' + id
34 async function getOrCreateAccount (accountUrl: string) {
35 let account = await db.Account.loadByUrl(accountUrl)
37 // We don't have this account in our database, fetch it on remote
39 const res = await fetchRemoteAccountAndCreateServer(accountUrl)
40 if (res === undefined) throw new Error('Cannot fetch remote account.')
42 // Save our new account in database
43 const account = res.account
50 async function fetchRemoteAccountAndCreateServer (accountUrl: string) {
55 'Accept': ACTIVITY_PUB_ACCEPT_HEADER
59 logger.info('Fetching remote account %s.', accountUrl)
63 requestResult = await doRequest(options)
65 logger.warn('Cannot fetch remote account %s.', accountUrl, err)
69 const accountJSON: ActivityPubActor = JSON.parse(requestResult.body)
70 if (isRemoteAccountValid(accountJSON) === false) {
71 logger.debug('Remote account JSON is not valid.', { accountJSON })
75 const followersCount = await fetchAccountCount(accountJSON.followers)
76 const followingCount = await fetchAccountCount(accountJSON.following)
78 const account = db.Account.build({
79 uuid: accountJSON.uuid,
80 name: accountJSON.preferredUsername,
82 publicKey: accountJSON.publicKey.publicKeyPem,
84 followersCount: followersCount,
85 followingCount: followingCount,
86 inboxUrl: accountJSON.inbox,
87 outboxUrl: accountJSON.outbox,
88 sharedInboxUrl: accountJSON.endpoints.sharedInbox,
89 followersUrl: accountJSON.followers,
90 followingUrl: accountJSON.following
93 const accountHost = url.parse(account.url).host
94 const serverOptions = {
102 const [ server ] = await db.Server.findOrCreate(serverOptions)
103 account.set('serverId', server.id)
105 return { account, server }
108 function fetchRemoteVideoPreview (video: VideoInstance) {
110 const host = video.VideoChannel.Account.Server.host
111 const path = join(STATIC_PATHS.PREVIEWS, video.getPreviewName())
113 return request.get(REMOTE_SCHEME.HTTP + '://' + host + path)
116 async function fetchRemoteVideoDescription (video: VideoInstance) {
121 const { body } = await doRequest(options)
122 return body.description ? body.description : ''
125 function activityPubContextify <T> (data: T) {
126 return Object.assign(data,{
128 'https://www.w3.org/ns/activitystreams',
129 'https://w3id.org/security/v1',
131 'Hashtag': 'as:Hashtag',
132 'uuid': 'http://schema.org/identifier',
133 'category': 'http://schema.org/category',
134 'licence': 'http://schema.org/license',
135 'nsfw': 'as:sensitive',
136 'language': 'http://schema.org/inLanguage',
137 'views': 'http://schema.org/Number',
138 'size': 'http://schema.org/Number',
139 'VideoChannel': 'https://peertu.be/ns/VideoChannel'
145 function activityPubCollectionPagination (url: string, page: number, result: ResultList<any>) {
146 const baseUrl = url.split('?').shift
151 totalItems: result.total,
153 id: baseUrl + '?page=' + page,
154 type: 'CollectionPage',
155 totalItems: result.total,
156 next: baseUrl + '?page=' + (page + 1),
162 return activityPubContextify(obj)
165 // ---------------------------------------------------------------------------
168 fetchRemoteAccountAndCreateServer,
169 activityPubContextify,
170 activityPubCollectionPagination,
172 generateThumbnailFromUrl,
174 fetchRemoteVideoPreview,
175 fetchRemoteVideoDescription
178 // ---------------------------------------------------------------------------
180 async function fetchAccountCount (url: string) {
188 requestResult = await doRequest(options)
190 logger.warn('Cannot fetch remote account count %s.', url, err)
194 return requestResult.totalItems ? requestResult.totalItems : 0