123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517 |
- import { DatabaseManager, EventContext, StoreContext } from '@joystream/hydra-common'
- import { FindConditions, Raw } from 'typeorm'
- import {
- IVideoMetadata,
- IPublishedBeforeJoystream,
- ILicense,
- IMediaType,
- IChannelMetadata,
- } from '@joystream/metadata-protobuf'
- import { integrateMeta, isSet, isValidLanguageCode } from '@joystream/metadata-protobuf/utils'
- import { invalidMetadata, inconsistentState, unexpectedData, logger } from '../common'
- import {
-
- CuratorGroup,
- Channel,
- Video,
- VideoCategory,
-
- Language,
- License,
- VideoMediaMetadata,
-
- Asset,
- Membership,
- VideoMediaEncoding,
- ChannelCategory,
- AssetNone,
- AssetExternal,
- AssetJoystreamStorage,
- StorageDataObject,
- } from 'query-node/dist/model'
- import { NewAssets, ContentActor } from '@joystream/types/augment'
- import { DecodedMetadataObject } from '@joystream/metadata-protobuf/types'
- import BN from 'bn.js'
- import { getMostRecentlyCreatedDataObjects } from '../storage/utils'
- import { DataObjectCreationParameters as ObjectCreationParams } from '@joystream/types/storage'
- import { registry } from '@joystream/types'
- export async function processChannelMetadata(
- ctx: EventContext & StoreContext,
- channel: Channel,
- meta: DecodedMetadataObject<IChannelMetadata>,
- assets?: NewAssets
- ): Promise<Channel> {
- const processedAssets = assets ? await processNewAssets(ctx, assets) : []
- integrateMeta(channel, meta, ['title', 'description', 'isPublic'])
-
- if (isSet(meta.category)) {
- channel.category = await processChannelCategory(ctx, channel.category, parseInt(meta.category))
- }
-
- if (isSet(meta.coverPhoto)) {
- const asset = findAssetByIndex(processedAssets, meta.coverPhoto, 'channel cover photo')
- if (asset) {
- channel.coverPhoto = asset
- }
- }
-
- if (isSet(meta.avatarPhoto)) {
- const asset = findAssetByIndex(processedAssets, meta.avatarPhoto, 'channel avatar photo')
- if (asset) {
- channel.avatarPhoto = asset
- }
- }
-
- if (isSet(meta.language)) {
- channel.language = await processLanguage(ctx, channel.language, meta.language)
- }
- return channel
- }
- export async function processVideoMetadata(
- ctx: EventContext & StoreContext,
- video: Video,
- meta: DecodedMetadataObject<IVideoMetadata>,
- assets?: NewAssets
- ): Promise<Video> {
- const processedAssets = assets ? await processNewAssets(ctx, assets) : []
- integrateMeta(video, meta, ['title', 'description', 'duration', 'hasMarketing', 'isExplicit', 'isPublic'])
-
- if (meta.category) {
- video.category = await processVideoCategory(ctx, video.category, parseInt(meta.category))
- }
-
- if (isSet(meta.mediaType) || isSet(meta.mediaPixelWidth) || isSet(meta.mediaPixelHeight)) {
-
- const videoSize = extractVideoSize(assets, meta.video)
- video.mediaMetadata = await processVideoMediaMetadata(ctx, video.mediaMetadata, meta, videoSize)
- }
-
- if (isSet(meta.license)) {
- await updateVideoLicense(ctx, video, meta.license)
- }
-
- if (isSet(meta.thumbnailPhoto)) {
- const asset = findAssetByIndex(processedAssets, meta.thumbnailPhoto, 'thumbnail photo')
- if (asset) {
- video.thumbnailPhoto = asset
- }
- }
-
- if (isSet(meta.video)) {
- const asset = findAssetByIndex(processedAssets, meta.video, 'video')
- if (asset) {
- video.media = asset
- }
- }
-
- if (isSet(meta.language)) {
- video.language = await processLanguage(ctx, video.language, meta.language)
- }
- if (isSet(meta.publishedBeforeJoystream)) {
- video.publishedBeforeJoystream = processPublishedBeforeJoystream(
- ctx,
- video.publishedBeforeJoystream,
- meta.publishedBeforeJoystream
- )
- }
- return video
- }
- function findAssetByIndex(assets: typeof Asset[], index: number, name?: string): typeof Asset | null {
- if (assets[index]) {
- return assets[index]
- } else {
- invalidMetadata(`Invalid${name ? ' ' + name : ''} asset index`, {
- numberOfAssets: assets.length,
- requestedAssetIndex: index,
- })
- return null
- }
- }
- async function processVideoMediaEncoding(
- { store, event }: StoreContext & EventContext,
- existingVideoMediaEncoding: VideoMediaEncoding | undefined,
- metadata: DecodedMetadataObject<IMediaType>
- ): Promise<VideoMediaEncoding> {
- const encoding =
- existingVideoMediaEncoding ||
- new VideoMediaEncoding({
- createdAt: new Date(event.blockTimestamp),
- createdById: '1',
- updatedById: '1',
- })
-
- integrateMeta(encoding, metadata, ['codecName', 'container', 'mimeMediaType'])
- encoding.updatedAt = new Date(event.blockTimestamp)
- await store.save<VideoMediaEncoding>(encoding)
- return encoding
- }
- async function processVideoMediaMetadata(
- ctx: StoreContext & EventContext,
- existingVideoMedia: VideoMediaMetadata | undefined,
- metadata: DecodedMetadataObject<IVideoMetadata>,
- videoSize: number | undefined
- ): Promise<VideoMediaMetadata> {
- const { store, event } = ctx
- const videoMedia =
- existingVideoMedia ||
- new VideoMediaMetadata({
- createdInBlock: event.blockNumber,
- createdAt: new Date(event.blockTimestamp),
- createdById: '1',
- updatedById: '1',
- })
-
- const mediaMetadata = {
- size: isSet(videoSize) ? new BN(videoSize.toString()) : undefined,
- pixelWidth: metadata.mediaPixelWidth,
- pixelHeight: metadata.mediaPixelHeight,
- }
- integrateMeta(videoMedia, mediaMetadata, ['pixelWidth', 'pixelHeight', 'size'])
- videoMedia.updatedAt = new Date(event.blockTimestamp)
- videoMedia.encoding = await processVideoMediaEncoding(ctx, videoMedia.encoding, metadata.mediaType || {})
- await store.save<VideoMediaMetadata>(videoMedia)
- return videoMedia
- }
- export async function convertContentActorToChannelOwner(
- store: DatabaseManager,
- contentActor: ContentActor
- ): Promise<{
- ownerMember?: Membership
- ownerCuratorGroup?: CuratorGroup
- }> {
- if (contentActor.isMember) {
- const memberId = contentActor.asMember.toNumber()
- const member = await store.get(Membership, { where: { id: memberId.toString() } as FindConditions<Membership> })
-
- if (!member) {
- return inconsistentState(`Actor is non-existing member`, memberId)
- }
- return {
- ownerMember: member,
- ownerCuratorGroup: undefined,
- }
- }
- if (contentActor.isCurator) {
- const curatorGroupId = contentActor.asCurator[0].toNumber()
- const curatorGroup = await store.get(CuratorGroup, {
- where: { id: curatorGroupId.toString() } as FindConditions<CuratorGroup>,
- })
-
- if (!curatorGroup) {
- return inconsistentState('Actor is non-existing curator group', curatorGroupId)
- }
- return {
- ownerMember: undefined,
- ownerCuratorGroup: curatorGroup,
- }
- }
-
- logger.error('Not implemented ContentActor type', { contentActor: contentActor.toString() })
- throw new Error('Not-implemented ContentActor type used')
- }
- function processPublishedBeforeJoystream(
- ctx: EventContext & StoreContext,
- currentValue: Date | undefined,
- metadata: DecodedMetadataObject<IPublishedBeforeJoystream>
- ): Date | undefined {
- if (!isSet(metadata)) {
- return currentValue
- }
-
- if (!metadata.isPublished) {
- return undefined
- }
-
- const timestamp = isSet(metadata.date) ? Date.parse(metadata.date) : NaN
-
- if (isNaN(timestamp)) {
- invalidMetadata(`Invalid date used for publishedBeforeJoystream`, {
- timestamp,
- })
- return currentValue
- }
-
- return new Date(timestamp)
- }
- async function processNewAssets(ctx: EventContext & StoreContext, assets: NewAssets): Promise<Array<typeof Asset>> {
- if (assets.isUrls) {
- return assets.asUrls.map((assetUrls) => {
- const resultAsset = new AssetExternal()
- resultAsset.urls = JSON.stringify(assetUrls.map((u) => u.toString()))
- return resultAsset
- })
- } else if (assets.isUpload) {
- const assetsUploaded = assets.asUpload.object_creation_list.length
-
- const objects = await getMostRecentlyCreatedDataObjects(ctx.store, assetsUploaded)
- return objects.map((o) => {
- const resultAsset = new AssetJoystreamStorage()
- resultAsset.dataObjectId = o.id
- return resultAsset
- })
- } else {
- unexpectedData('Unrecognized assets type', assets.type)
- }
- }
- function extractVideoSize(assets: NewAssets | undefined, assetIndex: number | null | undefined): number | undefined {
-
- if (!isSet(assetIndex)) {
- return undefined
- }
-
- if (!assets) {
- invalidMetadata(`Non-existing asset video size extraction requested - no assets were uploaded!`, {
- assetIndex,
- })
- return undefined
- }
-
- if (!assets.isUpload) {
- return undefined
- }
- const dataObjectsParams = assets.asUpload.object_creation_list
-
- if (assetIndex >= dataObjectsParams.length) {
- invalidMetadata(`Non-existing asset video size extraction requested`, {
- assetsProvided: dataObjectsParams.length,
- assetIndex,
- })
- return undefined
- }
-
- const objectParams = assets.asUpload.object_creation_list[assetIndex]
- const params = new ObjectCreationParams(registry, objectParams.toJSON() as any)
- const videoSize = params.getField('size').toNumber()
- return videoSize
- }
- async function processLanguage(
- ctx: EventContext & StoreContext,
- currentLanguage: Language | undefined,
- languageIso: string | undefined
- ): Promise<Language | undefined> {
- const { event, store } = ctx
- if (!isSet(languageIso)) {
- return currentLanguage
- }
-
- if (!isValidLanguageCode(languageIso)) {
- invalidMetadata(`Invalid language ISO-639-1 provided`, languageIso)
- return currentLanguage
- }
-
- const existingLanguage = await store.get(Language, { where: { iso: languageIso } })
-
- if (existingLanguage) {
- return existingLanguage
- }
-
- const newLanguage = new Language({
- iso: languageIso,
- createdInBlock: event.blockNumber,
- createdAt: new Date(event.blockTimestamp),
- updatedAt: new Date(event.blockTimestamp),
-
- createdById: '1',
- updatedById: '1',
- })
- await store.save<Language>(newLanguage)
- return newLanguage
- }
- async function updateVideoLicense(
- ctx: StoreContext & EventContext,
- video: Video,
- licenseMetadata: ILicense | null | undefined
- ): Promise<void> {
- const { store, event } = ctx
- if (!isSet(licenseMetadata)) {
- return
- }
- const previousLicense = video.license
- let license: License | null = null
- if (!isLicenseEmpty(licenseMetadata)) {
-
- license =
- previousLicense ||
- new License({
- createdAt: new Date(event.blockTimestamp),
- createdById: '1',
- updatedById: '1',
- })
- license.updatedAt = new Date(event.blockTimestamp)
- integrateMeta(license, licenseMetadata, ['attribution', 'code', 'customText'])
- await store.save<License>(license)
- }
-
-
-
- video.license = license as License | undefined
- video.updatedAt = new Date(ctx.event.blockTimestamp)
- await store.save<Video>(video)
-
- if (previousLicense && !license) {
- await store.remove<License>(previousLicense)
- }
- }
- function isLicenseEmpty(licenseObject: ILicense): boolean {
- const somePropertySet = Object.values(licenseObject).some((v) => isSet(v))
- return !somePropertySet
- }
- async function processVideoCategory(
- ctx: EventContext & StoreContext,
- currentCategory: VideoCategory | undefined,
- categoryId: number
- ): Promise<VideoCategory | undefined> {
- const { store } = ctx
-
- const category = await store.get(VideoCategory, {
- where: { id: categoryId.toString() },
- })
-
- if (!category) {
- invalidMetadata('Non-existing video category association with video requested', categoryId)
- return currentCategory
- }
- return category
- }
- async function processChannelCategory(
- ctx: EventContext & StoreContext,
- currentCategory: ChannelCategory | undefined,
- categoryId: number
- ): Promise<ChannelCategory | undefined> {
- const { store } = ctx
-
- const category = await store.get(ChannelCategory, {
- where: { id: categoryId.toString() },
- })
-
- if (!category) {
- invalidMetadata('Non-existing channel category association with channel requested', categoryId)
- return currentCategory
- }
- return category
- }
- export async function unsetAssetRelations(store: DatabaseManager, dataObject: StorageDataObject): Promise<void> {
- const channelAssets = ['avatarPhoto', 'coverPhoto'] as const
- const videoAssets = ['thumbnailPhoto', 'media'] as const
-
-
- const channel = await store.get(Channel, {
- where: channelAssets.map((assetName) => ({
- [assetName]: Raw((alias) => `${alias} ->> 'dataObjectId' = :id`, {
- id: dataObject.id,
- }),
- })),
- })
- const video = await store.get(Video, {
- where: videoAssets.map((assetName) => ({
- [assetName]: Raw((alias) => `${alias} ->> 'dataObjectId' = :id`, {
- id: dataObject.id,
- }),
- })),
- })
- if (channel) {
- channelAssets.forEach((assetName) => {
- if (channel[assetName] && (channel[assetName] as AssetJoystreamStorage).dataObjectId === dataObject.id) {
- channel[assetName] = new AssetNone()
- }
- })
- await store.save<Channel>(channel)
-
- logger.info('Content has been disconnected from Channel', {
- channelId: channel.id.toString(),
- dataObjectId: dataObject.id,
- })
- } else if (video) {
- videoAssets.forEach((assetName) => {
- if (video[assetName] && (video[assetName] as AssetJoystreamStorage).dataObjectId === dataObject.id) {
- video[assetName] = new AssetNone()
- }
- })
- await store.save<Video>(video)
-
- logger.info('Content has been disconnected from Video', {
- videoId: video.id.toString(),
- dataObjectId: dataObject.id,
- })
- }
- }
|