PeerTube/server/lib/activitypub/playlist.ts

219 lines
8.2 KiB
TypeScript
Raw Normal View History

2019-02-26 03:55:40 -06:00
import { PlaylistObject } from '../../../shared/models/activitypub/objects/playlist-object'
import { crawlCollectionPage } from './crawl'
import { ACTIVITY_PUB, CRAWL_REQUEST_CONCURRENCY } from '../../initializers/constants'
2019-02-26 03:55:40 -06:00
import { isArray } from '../../helpers/custom-validators/misc'
import { getOrCreateActorAndServerAndModel } from './actor'
import { logger } from '../../helpers/logger'
import { VideoPlaylistModel } from '../../models/video/video-playlist'
import { doRequest } from '../../helpers/requests'
2019-02-26 03:55:40 -06:00
import { checkUrlsSameHost } from '../../helpers/activitypub'
import * as Bluebird from 'bluebird'
import { PlaylistElementObject } from '../../../shared/models/activitypub/objects/playlist-element-object'
import { getOrCreateVideoAndAccountAndChannel } from './videos'
import { isPlaylistElementObjectValid, isPlaylistObjectValid } from '../../helpers/custom-validators/activitypub/playlist'
import { VideoPlaylistElementModel } from '../../models/video/video-playlist-element'
import { VideoPlaylistPrivacy } from '../../../shared/models/videos/playlist/video-playlist-privacy.model'
import { sequelizeTypescript } from '../../initializers/database'
2019-04-23 02:50:57 -05:00
import { createPlaylistMiniatureFromUrl } from '../thumbnail'
2020-06-18 03:45:25 -05:00
import { FilteredModelAttributes } from '../../types/sequelize'
import { MAccountDefault, MAccountId, MVideoId } from '../../types/models'
import { MVideoPlaylist, MVideoPlaylistId, MVideoPlaylistOwner } from '../../types/models/video/video-playlist'
2019-02-26 03:55:40 -06:00
2019-08-15 04:53:26 -05:00
function playlistObjectToDBAttributes (playlistObject: PlaylistObject, byAccount: MAccountId, to: string[]) {
2020-02-28 09:03:39 -06:00
const privacy = to.includes(ACTIVITY_PUB.PUBLIC)
? VideoPlaylistPrivacy.PUBLIC
: VideoPlaylistPrivacy.UNLISTED
2019-02-26 03:55:40 -06:00
return {
name: playlistObject.name,
description: playlistObject.content,
privacy,
url: playlistObject.id,
uuid: playlistObject.uuid,
ownerAccountId: byAccount.id,
2019-03-05 03:58:44 -06:00
videoChannelId: null,
createdAt: new Date(playlistObject.published),
updatedAt: new Date(playlistObject.updated)
2019-02-26 03:55:40 -06:00
}
}
2019-08-15 04:53:26 -05:00
function playlistElementObjectToDBAttributes (elementObject: PlaylistElementObject, videoPlaylist: MVideoPlaylistId, video: MVideoId) {
2019-02-26 03:55:40 -06:00
return {
position: elementObject.position,
url: elementObject.id,
startTimestamp: elementObject.startTimestamp || null,
stopTimestamp: elementObject.stopTimestamp || null,
videoPlaylistId: videoPlaylist.id,
videoId: video.id
}
}
2019-08-15 04:53:26 -05:00
async function createAccountPlaylists (playlistUrls: string[], account: MAccountDefault) {
2019-02-26 03:55:40 -06:00
await Bluebird.map(playlistUrls, async playlistUrl => {
try {
const exists = await VideoPlaylistModel.doesPlaylistExist(playlistUrl)
if (exists === true) return
// Fetch url
const { body } = await doRequest<PlaylistObject>({
uri: playlistUrl,
json: true,
activityPub: true
})
if (!isPlaylistObjectValid(body)) {
throw new Error(`Invalid playlist object when fetch account playlists: ${JSON.stringify(body)}`)
}
if (!isArray(body.to)) {
throw new Error('Playlist does not have an audience.')
}
return createOrUpdateVideoPlaylist(body, account, body.to)
} catch (err) {
logger.warn('Cannot add playlist element %s.', playlistUrl, { err })
}
}, { concurrency: CRAWL_REQUEST_CONCURRENCY })
}
2019-08-15 04:53:26 -05:00
async function createOrUpdateVideoPlaylist (playlistObject: PlaylistObject, byAccount: MAccountId, to: string[]) {
2019-02-26 03:55:40 -06:00
const playlistAttributes = playlistObjectToDBAttributes(playlistObject, byAccount, to)
if (isArray(playlistObject.attributedTo) && playlistObject.attributedTo.length === 1) {
const actor = await getOrCreateActorAndServerAndModel(playlistObject.attributedTo[0])
if (actor.VideoChannel) {
playlistAttributes.videoChannelId = actor.VideoChannel.id
} else {
logger.warn('Attributed to of video playlist %s is not a video channel.', playlistObject.id, { playlistObject })
}
}
2019-08-15 04:53:26 -05:00
const [ playlist ] = await VideoPlaylistModel.upsert<MVideoPlaylist>(playlistAttributes, { returning: true })
2019-02-26 03:55:40 -06:00
let accItems: string[] = []
await crawlCollectionPage<string>(playlistObject.id, items => {
accItems = accItems.concat(items)
return Promise.resolve()
})
const refreshedPlaylist = await VideoPlaylistModel.loadWithAccountAndChannel(playlist.id, null)
if (playlistObject.icon) {
2019-02-26 03:55:40 -06:00
try {
2019-04-23 02:50:57 -05:00
const thumbnailModel = await createPlaylistMiniatureFromUrl(playlistObject.icon.url, refreshedPlaylist)
await refreshedPlaylist.setAndSaveThumbnail(thumbnailModel, undefined)
2019-02-26 03:55:40 -06:00
} catch (err) {
logger.warn('Cannot generate thumbnail of %s.', playlistObject.id, { err })
}
} else if (refreshedPlaylist.hasThumbnail()) {
await refreshedPlaylist.Thumbnail.destroy()
refreshedPlaylist.Thumbnail = null
2019-02-26 03:55:40 -06:00
}
return resetVideoPlaylistElements(accItems, refreshedPlaylist)
2019-02-26 03:55:40 -06:00
}
2019-08-15 04:53:26 -05:00
async function refreshVideoPlaylistIfNeeded (videoPlaylist: MVideoPlaylistOwner): Promise<MVideoPlaylistOwner> {
2019-03-19 08:13:53 -05:00
if (!videoPlaylist.isOutdated()) return videoPlaylist
try {
const { statusCode, playlistObject } = await fetchRemoteVideoPlaylist(videoPlaylist.url)
if (statusCode === 404) {
logger.info('Cannot refresh remote video playlist %s: it does not exist anymore. Deleting it.', videoPlaylist.url)
await videoPlaylist.destroy()
return undefined
}
if (playlistObject === undefined) {
logger.warn('Cannot refresh remote playlist %s: invalid body.', videoPlaylist.url)
await videoPlaylist.setAsRefreshed()
return videoPlaylist
}
const byAccount = videoPlaylist.OwnerAccount
await createOrUpdateVideoPlaylist(playlistObject, byAccount, playlistObject.to)
return videoPlaylist
} catch (err) {
logger.warn('Cannot refresh video playlist %s.', videoPlaylist.url, { err })
await videoPlaylist.setAsRefreshed()
return videoPlaylist
}
}
2019-02-26 03:55:40 -06:00
// ---------------------------------------------------------------------------
export {
createAccountPlaylists,
playlistObjectToDBAttributes,
playlistElementObjectToDBAttributes,
2019-03-19 08:13:53 -05:00
createOrUpdateVideoPlaylist,
refreshVideoPlaylistIfNeeded
2019-02-26 03:55:40 -06:00
}
// ---------------------------------------------------------------------------
2019-08-15 04:53:26 -05:00
async function resetVideoPlaylistElements (elementUrls: string[], playlist: MVideoPlaylist) {
2019-04-23 02:50:57 -05:00
const elementsToCreate: FilteredModelAttributes<VideoPlaylistElementModel>[] = []
2019-02-26 03:55:40 -06:00
await Bluebird.map(elementUrls, async elementUrl => {
try {
// Fetch url
const { body } = await doRequest<PlaylistElementObject>({
uri: elementUrl,
json: true,
activityPub: true
})
if (!isPlaylistElementObjectValid(body)) throw new Error(`Invalid body in video get playlist element ${elementUrl}`)
if (checkUrlsSameHost(body.id, elementUrl) !== true) {
throw new Error(`Playlist element url ${elementUrl} host is different from the AP object id ${body.id}`)
}
const { video } = await getOrCreateVideoAndAccountAndChannel({ videoObject: { id: body.url }, fetchType: 'only-video' })
elementsToCreate.push(playlistElementObjectToDBAttributes(body, playlist, video))
} catch (err) {
logger.warn('Cannot add playlist element %s.', elementUrl, { err })
}
}, { concurrency: CRAWL_REQUEST_CONCURRENCY })
await sequelizeTypescript.transaction(async t => {
await VideoPlaylistElementModel.deleteAllOf(playlist.id, t)
for (const element of elementsToCreate) {
await VideoPlaylistElementModel.create(element, { transaction: t })
}
})
logger.info('Reset playlist %s with %s elements.', playlist.url, elementsToCreate.length)
return undefined
}
2019-03-19 08:13:53 -05:00
async function fetchRemoteVideoPlaylist (playlistUrl: string): Promise<{ statusCode: number, playlistObject: PlaylistObject }> {
const options = {
uri: playlistUrl,
method: 'GET',
json: true,
activityPub: true
}
logger.info('Fetching remote playlist %s.', playlistUrl)
2020-02-28 09:03:39 -06:00
const { response, body } = await doRequest<any>(options)
2019-03-19 08:13:53 -05:00
if (isPlaylistObjectValid(body) === false || checkUrlsSameHost(body.id, playlistUrl) !== true) {
logger.debug('Remote video playlist JSON is not valid.', { body })
return { statusCode: response.statusCode, playlistObject: undefined }
}
return { statusCode: response.statusCode, playlistObject: body }
}