瀏覽代碼

Merge remote-tracking branch 'arsen/content_cli_reworkings' into sumer-cli

Leszek Wiesner 3 年之前
父節點
當前提交
9a5ef875f0
共有 43 個文件被更改,包括 66 次插入2219 次删除
  1. 1 1
      cli/package.json
  2. 19 22
      cli/src/Api.ts
  3. 18 340
      cli/src/base/ContentDirectoryCommandBase.ts
  4. 0 70
      cli/src/base/MediaCommandBase.ts
  5. 0 79
      cli/src/commands/content-directory/addClassSchema.ts
  6. 0 44
      cli/src/commands/content-directory/addMaintainerToClass.ts
  7. 0 55
      cli/src/commands/content-directory/class.ts
  8. 0 24
      cli/src/commands/content-directory/classes.ts
  9. 0 50
      cli/src/commands/content-directory/createClass.ts
  10. 0 58
      cli/src/commands/content-directory/createEntity.ts
  11. 0 45
      cli/src/commands/content-directory/entities.ts
  12. 0 44
      cli/src/commands/content-directory/entity.ts
  13. 0 57
      cli/src/commands/content-directory/initialize.ts
  14. 0 35
      cli/src/commands/content-directory/removeCuratorGroup.ts
  15. 0 45
      cli/src/commands/content-directory/removeEntity.ts
  16. 0 44
      cli/src/commands/content-directory/removeMaintainerFromClass.ts
  17. 0 55
      cli/src/commands/content-directory/updateClassPermissions.ts
  18. 0 61
      cli/src/commands/content-directory/updateEntityPropertyValues.ts
  19. 1 1
      cli/src/commands/content/addCuratorToGroup.ts
  20. 3 3
      cli/src/commands/content/createCuratorGroup.ts
  21. 0 5
      cli/src/commands/content/curatorGroup.ts
  22. 0 1
      cli/src/commands/content/curatorGroups.ts
  23. 1 1
      cli/src/commands/content/removeCuratorFromGroup.ts
  24. 1 1
      cli/src/commands/content/setCuratorGroupStatus.ts
  25. 0 58
      cli/src/commands/media/createChannel.ts
  26. 0 57
      cli/src/commands/media/curateContent.ts
  27. 0 36
      cli/src/commands/media/featuredVideos.ts
  28. 0 25
      cli/src/commands/media/myChannels.ts
  29. 0 33
      cli/src/commands/media/myVideos.ts
  30. 0 44
      cli/src/commands/media/removeChannel.ts
  31. 0 49
      cli/src/commands/media/removeVideo.ts
  32. 0 79
      cli/src/commands/media/setFeaturedVideos.ts
  33. 0 98
      cli/src/commands/media/updateChannel.ts
  34. 0 106
      cli/src/commands/media/updateVideo.ts
  35. 0 59
      cli/src/commands/media/updateVideoLicense.ts
  36. 0 384
      cli/src/commands/media/uploadVideo.ts
  37. 12 34
      cli/src/helpers/InputOutput.ts
  38. 1 7
      cli/src/helpers/JsonSchemaPrompt.ts
  39. 1 1
      content-metadata-protobuf/src/index.ts
  40. 2 2
      types/src/content/index.ts
  41. 3 3
      types/src/index.ts
  42. 2 2
      types/src/scripts/generateAugmentCodec.ts
  43. 1 1
      yarn.lock

+ 1 - 1
cli/package.json

@@ -101,7 +101,7 @@
       "working-groups": {
         "description": "Working group lead and worker actions"
       },
-      "content-directory": {
+      "content": {
         "description": "Interactions with content directory module - managing classes, schemas, entities and permissions"
       },
       "media": {

+ 19 - 22
cli/src/Api.ts

@@ -47,10 +47,10 @@ import { MemberId, Membership } from '@joystream/types/members'
 import { RewardRelationship, RewardRelationshipId } from '@joystream/types/recurring-rewards'
 import { Stake, StakeId } from '@joystream/types/stake'
 
-import { InputValidationLengthConstraint } from '@joystream/types/common'
-import { Class, ClassId, CuratorGroup, CuratorGroupId, Entity, EntityId } from '@joystream/types/content-directory'
+import { InputValidationLengthConstraint, ChannelId, Url } from '@joystream/types/common'
+import { CuratorGroup, CuratorGroupId, Channel, Video, VideoId } from '@joystream/types/content'
 import { ContentId, DataObject } from '@joystream/types/storage'
-import { ServiceProviderRecord, Url } from '@joystream/types/discovery'
+import { ServiceProviderRecord } from '@joystream/types/discovery'
 import _ from 'lodash'
 
 export const DEFAULT_API_URI = 'ws://localhost:9944/'
@@ -67,7 +67,6 @@ export const apiModuleByGroup: { [key in WorkingGroups]: string } = {
 // Api wrapper for handling most common api calls and allowing easy API implementation switch in the future
 export default class Api {
   private _api: ApiPromise
-  private _cdClassesCache: [ClassId, Class][] | null = null
 
   private constructor(originalApi: ApiPromise) {
     this._api = originalApi
@@ -495,43 +494,41 @@ export default class Api {
   }
 
   // Content directory
-  async availableClasses(useCache = true): Promise<[ClassId, Class][]> {
-    return useCache && this._cdClassesCache
-      ? this._cdClassesCache
-      : (this._cdClassesCache = await this.entriesByIds<ClassId, Class>(this._api.query.contentDirectory.classById))
+  async availableChannels(): Promise<[ChannelId, Channel][]> {
+    return await this.entriesByIds<ChannelId, Channel>(this._api.query.content.channelById)
   }
 
   availableCuratorGroups(): Promise<[CuratorGroupId, CuratorGroup][]> {
-    return this.entriesByIds<CuratorGroupId, CuratorGroup>(this._api.query.contentDirectory.curatorGroupById)
+    return this.entriesByIds<CuratorGroupId, CuratorGroup>(this._api.query.content.curatorGroupById)
   }
 
   async curatorGroupById(id: number): Promise<CuratorGroup | null> {
-    const exists = !!(await this._api.query.contentDirectory.curatorGroupById.size(id)).toNumber()
-    return exists ? await this._api.query.contentDirectory.curatorGroupById<CuratorGroup>(id) : null
+    const exists = !!(await this._api.query.content.curatorGroupById.size(id)).toNumber()
+    return exists ? await this._api.query.content.curatorGroupById<CuratorGroup>(id) : null
   }
 
   async nextCuratorGroupId(): Promise<number> {
-    return (await this._api.query.contentDirectory.nextCuratorGroupId<CuratorGroupId>()).toNumber()
+    return (await this._api.query.content.nextCuratorGroupId<CuratorGroupId>()).toNumber()
   }
 
-  async classById(id: number): Promise<Class | null> {
-    const c = await this._api.query.contentDirectory.classById<Class>(id)
+  async channelById(channelId: number): Promise<Channel | null> {
+    const c = await this._api.query.content.channelById<Channel>(channelId)
     return c.isEmpty ? null : c
   }
 
-  async entitiesByClassId(classId: number): Promise<[EntityId, Entity][]> {
-    const entityEntries = await this.entriesByIds<EntityId, Entity>(this._api.query.contentDirectory.entityById)
-    return entityEntries.filter(([, entity]) => entity.class_id.toNumber() === classId)
+  async videosByChannelId(channelId: number): Promise<[VideoId, Video][]> {
+    const videoEntries = await this.entriesByIds<VideoId, Video>(this._api.query.content.videoById)
+    return videoEntries.filter(([, video]) => video.in_channel.toNumber() === channelId)
   }
 
-  async entityById(id: number): Promise<Entity | null> {
-    const exists = !!(await this._api.query.contentDirectory.entityById.size(id)).toNumber()
-    return exists ? await this._api.query.contentDirectory.entityById<Entity>(id) : null
+  async videoById(videoId: number): Promise<Video | null> {
+    const exists = !!(await this._api.query.content.entityById.size(videoId)).toNumber()
+    return exists ? await this._api.query.content.videoById<Video>(videoId) : null
   }
 
   async dataByContentId(contentId: ContentId): Promise<DataObject | null> {
-    const dataObject = await this._api.query.dataDirectory.dataByContentId<Option<DataObject>>(contentId)
-    return dataObject.unwrapOr(null)
+    const dataObject = await this._api.query.dataDirectory.dataByContentId<DataObject>(contentId)
+    return dataObject.isEmpty ? null : dataObject
   }
 
   async ipnsIdentity(storageProviderId: number): Promise<string | null> {

+ 18 - 340
cli/src/base/ContentDirectoryCommandBase.ts

@@ -1,36 +1,15 @@
 import ExitCodes from '../ExitCodes'
 import { WorkingGroups } from '../Types'
-import { ReferenceProperty } from '@joystream/cd-schemas/types/extrinsics/AddClassSchema'
-import { FlattenRelations } from '@joystream/cd-schemas/types/utility'
-import { BOOL_PROMPT_OPTIONS } from '../helpers/prompting'
-import {
-  Class,
-  ClassId,
-  CuratorGroup,
-  CuratorGroupId,
-  Entity,
-  EntityId,
-  Actor,
-  PropertyType,
-  Property,
-} from '@joystream/types/content-directory'
+import { Channel, CuratorGroup, CuratorGroupId, ContentActor } from '@joystream/types/content'
 import { Worker } from '@joystream/types/working-group'
 import { CLIError } from '@oclif/errors'
-import { Codec } from '@polkadot/types/types'
-import AbstractInt from '@polkadot/types/codec/AbstractInt'
-import { AnyJson } from '@polkadot/types/types/helpers'
-import _ from 'lodash'
 import { RolesCommandBase } from './WorkingGroupsCommandBase'
 import { createType } from '@joystream/types'
-import chalk from 'chalk'
 import { flags } from '@oclif/command'
-import { DistinctQuestion } from 'inquirer'
 
 const CONTEXTS = ['Member', 'Curator', 'Lead'] as const
 type Context = typeof CONTEXTS[number]
 
-type ParsedPropertyValue = { value: Codec | null; type: PropertyType['type']; subtype: PropertyType['subtype'] }
-
 /**
  * Abstract base class for commands related to content directory
  */
@@ -57,58 +36,40 @@ export default abstract class ContentDirectoryCommandBase extends RolesCommandBa
     await this.getRequiredLead()
   }
 
-  async getCuratorContext(classNames: string[] = []): Promise<Actor> {
+  async getCuratorContext(): Promise<ContentActor> {
     const curator = await this.getRequiredWorker()
-    const classes = await Promise.all(classNames.map(async (cName) => (await this.classEntryByNameOrId(cName))[1]))
-    const classMaintainers = classes.map(({ class_permissions: permissions }) => permissions.maintainers.toArray())
 
     const groups = await this.getApi().availableCuratorGroups()
     const availableGroupIds = groups
       .filter(
-        ([groupId, group]) =>
-          group.active.valueOf() &&
-          classMaintainers.every((maintainers) => maintainers.some((m) => m.eq(groupId))) &&
-          group.curators.toArray().some((curatorId) => curatorId.eq(curator.workerId))
+        ([, group]) =>
+          group.active.valueOf() && group.curators.toArray().some((curatorId) => curatorId.eq(curator.workerId))
       )
       .map(([id]) => id)
 
     let groupId: number
     if (!availableGroupIds.length) {
-      this.error(
-        'You do not have the required maintainer access to at least one of the following classes: ' +
-          classNames.join(', '),
-        { exit: ExitCodes.AccessDenied }
-      )
+      this.error('You do not have the curator access!', { exit: ExitCodes.AccessDenied })
     } else if (availableGroupIds.length === 1) {
       groupId = availableGroupIds[0].toNumber()
     } else {
       groupId = await this.promptForCuratorGroup('Select Curator Group context', availableGroupIds)
     }
 
-    return createType('Actor', { Curator: [groupId, curator.workerId.toNumber()] })
+    return createType('ContentActor', { Curator: [groupId, curator.workerId.toNumber()] })
   }
 
-  async promptForClass(message = 'Select a class'): Promise<Class> {
-    const classes = await this.getApi().availableClasses()
-    const choices = classes.map(([, c]) => ({ name: c.name.toString(), value: c }))
+  async promptForChannel(message = 'Select a channel'): Promise<Channel> {
+    const channels = await this.getApi().availableChannels()
+    const choices = channels.map(([id, c]) => ({ id: id.toString(), value: c }))
     if (!choices.length) {
-      this.warn('No classes exist to choose from!')
+      this.warn('No channels exist to choose from!')
       this.exit(ExitCodes.InvalidInput)
     }
 
-    const selectedClass = await this.simplePrompt({ message, type: 'list', choices })
-
-    return selectedClass
-  }
-
-  async classEntryByNameOrId(classNameOrId: string): Promise<[ClassId, Class]> {
-    const classes = await this.getApi().availableClasses()
-    const foundClass = classes.find(([id, c]) => id.toString() === classNameOrId || c.name.toString() === classNameOrId)
-    if (!foundClass) {
-      this.error(`Class id not found by class name or id: "${classNameOrId}"!`)
-    }
+    const selectedChannel = await this.simplePrompt({ message, type: 'list', choices })
 
-    return foundClass
+    return selectedChannel
   }
 
   private async curatorGroupChoices(ids?: CuratorGroupId[]) {
@@ -119,8 +80,7 @@ export default abstract class ContentDirectoryCommandBase extends RolesCommandBa
         name:
           `Group ${id.toString()} (` +
           `${group.active.valueOf() ? 'Active' : 'Inactive'}, ` +
-          `${group.curators.toArray().length} member(s), ` +
-          `${group.number_of_classes_maintained.toNumber()} classes maintained)`,
+          `${group.curators.toArray().length} member(s), `,
         value: id.toNumber(),
       }))
   }
@@ -146,12 +106,6 @@ export default abstract class ContentDirectoryCommandBase extends RolesCommandBa
     return selectedIds
   }
 
-  async promptForClassReference(): Promise<ReferenceProperty['Reference']> {
-    const selectedClass = await this.promptForClass()
-    const sameOwner = await this.simplePrompt({ message: 'Same owner required?', ...BOOL_PROMPT_OPTIONS })
-    return { className: selectedClass.name.toString(), sameOwner }
-  }
-
   async promptForCurator(message = 'Choose a Curator', ids?: number[]): Promise<number> {
     const curators = await this.getApi().groupMembers(WorkingGroups.Curators)
     const choices = curators
@@ -207,295 +161,19 @@ export default abstract class ContentDirectoryCommandBase extends RolesCommandBa
     return group
   }
 
-  async getEntity(
-    id: string | number,
-    requiredClass?: string,
-    ownerMemberId?: number,
-    requireSchema = true
-  ): Promise<Entity> {
-    if (typeof id === 'string') {
-      id = parseInt(id)
-    }
-
-    const entity = await this.getApi().entityById(id)
-
-    if (!entity) {
-      this.error(`Entity not found by id: ${id}`, { exit: ExitCodes.InvalidInput })
-    }
-
-    if (requiredClass) {
-      const [classId] = await this.classEntryByNameOrId(requiredClass)
-      if (entity.class_id.toNumber() !== classId.toNumber()) {
-        this.error(`Entity of id ${id} is not of class ${requiredClass}!`, { exit: ExitCodes.InvalidInput })
-      }
-    }
-
-    const { controller } = entity.entity_permissions
-    if (
-      ownerMemberId !== undefined &&
-      (!controller.isOfType('Member') || controller.asType('Member').toNumber() !== ownerMemberId)
-    ) {
-      this.error('Cannot execute this action for specified entity - invalid ownership.', {
-        exit: ExitCodes.AccessDenied,
-      })
-    }
-
-    if (requireSchema && !entity.supported_schemas.toArray().length) {
-      this.error(`${requiredClass || ''} entity of id ${id} has no schema support added!`)
-    }
-
-    return entity
-  }
-
-  async getAndParseKnownEntity<T>(id: string | number, className?: string): Promise<FlattenRelations<T>> {
-    const entity = await this.getEntity(id, className)
-    return this.parseToEntityJson<T>(entity)
-  }
-
-  async entitiesByClassAndOwner(classNameOrId: number | string, ownerMemberId?: number): Promise<[EntityId, Entity][]> {
-    const classId =
-      typeof classNameOrId === 'number' ? classNameOrId : (await this.classEntryByNameOrId(classNameOrId))[0].toNumber()
-
-    return (await this.getApi().entitiesByClassId(classId)).filter(([, entity]) => {
-      const controller = entity.entity_permissions.controller
-      return ownerMemberId !== undefined
-        ? controller.isOfType('Member') && controller.asType('Member').toNumber() === ownerMemberId
-        : true
-    })
-  }
-
-  async promptForEntityEntry(
-    message: string,
-    className: string,
-    propName?: string,
-    ownerMemberId?: number,
-    defaultId?: number | null
-  ): Promise<[EntityId, Entity]> {
-    const [classId, entityClass] = await this.classEntryByNameOrId(className)
-    const entityEntries = await this.entitiesByClassAndOwner(classId.toNumber(), ownerMemberId)
-
-    if (!entityEntries.length) {
-      this.log(`${message}:`)
-      this.error(`No choices available! Exiting...`, { exit: ExitCodes.UnexpectedException })
-    }
-
-    const choosenEntityId = await this.simplePrompt({
-      message,
-      type: 'list',
-      choices: entityEntries.map(([id, entity]) => {
-        const parsedEntityPropertyValues = this.parseEntityPropertyValues(entity, entityClass)
-        return {
-          name: (propName && parsedEntityPropertyValues[propName]?.value?.toString()) || `ID:${id.toString()}`,
-          value: id.toString(), // With numbers there are issues with "default"
-        }
-      }),
-      default: typeof defaultId === 'number' ? defaultId.toString() : undefined,
-    })
-
-    return entityEntries.find(([id]) => choosenEntityId === id.toString())!
-  }
-
-  async promptForEntityId(
-    message: string,
-    className: string,
-    propName?: string,
-    ownerMemberId?: number,
-    defaultId?: number | null
-  ): Promise<number> {
-    return (await this.promptForEntityEntry(message, className, propName, ownerMemberId, defaultId))[0].toNumber()
-  }
-
-  parseStoredPropertyInnerValue(value: Codec | null): AnyJson {
-    if (value === null) {
-      return null
-    }
-
-    if (value instanceof AbstractInt) {
-      return value.toNumber() // Integers (signed ones) are by default converted to hex when using .toJson()
-    }
-
-    return value.toJSON()
-  }
-
-  parseEntityPropertyValues(
-    entity: Entity,
-    entityClass: Class,
-    includedProperties?: string[]
-  ): Record<string, ParsedPropertyValue> {
-    const { properties } = entityClass
-    return Array.from(entity.getField('values').entries()).reduce((columns, [propId, propValue]) => {
-      const prop = properties[propId.toNumber()]
-      const propName = prop.name.toString()
-      const included = !includedProperties || includedProperties.some((p) => p.toLowerCase() === propName.toLowerCase())
-      const { type: propType, subtype: propSubtype } = prop.property_type
-
-      if (included) {
-        columns[propName] = {
-          // If type doesn't match (Boolean(false) for optional fields case) - use "null" as value
-          value: propType !== propValue.type || propSubtype !== propValue.subtype ? null : propValue.getValue(),
-          type: propType,
-          subtype: propSubtype,
-        }
-      }
-      return columns
-    }, {} as Record<string, ParsedPropertyValue>)
-  }
-
-  async parseToEntityJson<T = unknown>(entity: Entity): Promise<FlattenRelations<T>> {
-    const entityClass = (await this.classEntryByNameOrId(entity.class_id.toString()))[1]
-    return (_.mapValues(this.parseEntityPropertyValues(entity, entityClass), (v) =>
-      this.parseStoredPropertyInnerValue(v.value)
-    ) as unknown) as FlattenRelations<T>
-  }
-
-  async createEntityList(
-    className: string,
-    includedProps?: string[],
-    filters: [string, string][] = [],
-    ownerMemberId?: number
-  ): Promise<Record<string, string>[]> {
-    const [classId, entityClass] = await this.classEntryByNameOrId(className)
-    // Create object of default "[not set]" values (prevents breaking the table if entity has no schema support)
-    const defaultValues = entityClass.properties
-      .map((p) => p.name.toString())
-      .reduce((d, propName) => {
-        if (!includedProps || includedProps.includes(propName)) {
-          d[propName] = chalk.grey('[not set]')
-        }
-        return d
-      }, {} as Record<string, string>)
-
-    const entityEntries = await this.entitiesByClassAndOwner(classId.toNumber(), ownerMemberId)
-    const parsedEntities = (await Promise.all(
-      entityEntries.map(([id, entity]) => ({
-        'ID': id.toString(),
-        ...defaultValues,
-        ..._.mapValues(this.parseEntityPropertyValues(entity, entityClass, includedProps), (v) =>
-          v.value === null ? chalk.grey('[not set]') : v.value.toString()
-        ),
-      }))
-    )) as Record<string, string>[]
-
-    return parsedEntities.filter((entity) => filters.every(([pName, pValue]) => entity[pName] === pValue))
-  }
-
-  async getActor(context: typeof CONTEXTS[number], pickedClass: Class) {
-    let actor: Actor
+  async getActor(context: typeof CONTEXTS[number]) {
+    let actor: ContentActor
     if (context === 'Member') {
       const memberId = await this.getRequiredMemberId()
-      actor = this.createType('Actor', { Member: memberId })
+      actor = this.createType('ContentActor', { Member: memberId })
     } else if (context === 'Curator') {
-      actor = await this.getCuratorContext([pickedClass.name.toString()])
+      actor = await this.getCuratorContext()
     } else {
       await this.getRequiredLead()
 
-      actor = this.createType('Actor', { Lead: null })
+      actor = this.createType('ContentActor', { Lead: null })
     }
 
     return actor
   }
-
-  isActorEntityController(actor: Actor, entity: Entity, isMaintainer: boolean): boolean {
-    const entityController = entity.entity_permissions.controller
-    return (
-      (isMaintainer && entityController.isOfType('Maintainers')) ||
-      (entityController.isOfType('Member') &&
-        actor.isOfType('Member') &&
-        entityController.asType('Member').eq(actor.asType('Member'))) ||
-      (entityController.isOfType('Lead') && actor.isOfType('Lead'))
-    )
-  }
-
-  async isEntityPropertyEditableByActor(entity: Entity, classPropertyId: number, actor: Actor): Promise<boolean> {
-    const [, entityClass] = await this.classEntryByNameOrId(entity.class_id.toString())
-
-    const isActorMaintainer =
-      actor.isOfType('Curator') &&
-      entityClass.class_permissions.maintainers.toArray().some((groupId) => groupId.eq(actor.asType('Curator')[0]))
-
-    const isActorController = this.isActorEntityController(actor, entity, isActorMaintainer)
-
-    const {
-      is_locked_from_controller: isLockedFromController,
-      is_locked_from_maintainer: isLockedFromMaintainer,
-    } = entityClass.properties[classPropertyId].locking_policy
-
-    return (
-      (isActorController && !isLockedFromController.valueOf()) ||
-      (isActorMaintainer && !isLockedFromMaintainer.valueOf())
-    )
-  }
-
-  getQuestionsFromProperties(properties: Property[], defaults?: { [key: string]: unknown }): DistinctQuestion[] {
-    return properties.reduce((previousValue, { name, property_type: propertyType, required }) => {
-      const propertySubtype = propertyType.subtype
-      const questionType = propertySubtype === 'Bool' ? 'list' : 'input'
-      const isSubtypeNumber = propertySubtype.toLowerCase().includes('int')
-      const isSubtypeReference = propertyType.isOfType('Single') && propertyType.asType('Single').isOfType('Reference')
-
-      const validate = async (answer: string | number | null) => {
-        if (answer === null) {
-          return true // Can only happen through "filter" if property is not required
-        }
-
-        if ((isSubtypeNumber || isSubtypeReference) && parseInt(answer.toString()).toString() !== answer.toString()) {
-          return `Expected integer value!`
-        }
-
-        if (isSubtypeReference) {
-          try {
-            await this.getEntity(+answer, propertyType.asType('Single').asType('Reference')[0].toString())
-          } catch (e) {
-            return e.message || JSON.stringify(e)
-          }
-        }
-
-        return true
-      }
-
-      const optionalQuestionProperties = {
-        ...{
-          filter: async (answer: string) => {
-            if (required.isFalse && !answer) {
-              return null
-            }
-
-            // Only cast to number if valid
-            // Prevents inquirer bug not allowing to edit invalid values when casted to number
-            // See: https://github.com/SBoudrias/Inquirer.js/issues/866
-            if ((isSubtypeNumber || isSubtypeReference) && (await validate(answer)) === true) {
-              return parseInt(answer)
-            }
-
-            return answer
-          },
-          validate,
-        },
-        ...(propertySubtype === 'Bool' && {
-          choices: ['true', 'false'],
-          filter: (answer: string) => {
-            return answer === 'true' || false
-          },
-        }),
-      }
-
-      const isQuestionOptional = propertySubtype === 'Bool' ? '' : required.isTrue ? '(required)' : '(optional)'
-      const classId = isSubtypeReference
-        ? ` [Class Id: ${propertyType.asType('Single').asType('Reference')[0].toString()}]`
-        : ''
-
-      return [
-        ...previousValue,
-        {
-          name: name.toString(),
-          message: `${name} - ${propertySubtype}${classId} ${isQuestionOptional}`,
-          type: questionType,
-          ...optionalQuestionProperties,
-          ...(defaults && {
-            default: propertySubtype === 'Bool' ? JSON.stringify(defaults[name.toString()]) : defaults[name.toString()],
-          }),
-        },
-      ]
-    }, [] as DistinctQuestion[])
-  }
 }

+ 0 - 70
cli/src/base/MediaCommandBase.ts

@@ -1,70 +0,0 @@
-import ContentDirectoryCommandBase from './ContentDirectoryCommandBase'
-import { VideoEntity, KnownLicenseEntity, LicenseEntity } from '@joystream/cd-schemas/types/entities'
-import fs from 'fs'
-import { DistinctQuestion } from 'inquirer'
-import path from 'path'
-import os from 'os'
-
-const MAX_USER_LICENSE_CONTENT_LENGTH = 4096
-
-/**
- * Abstract base class for higher-level media commands
- */
-export default abstract class MediaCommandBase extends ContentDirectoryCommandBase {
-  async promptForNewLicense(): Promise<VideoEntity['license']> {
-    let licenseInput: LicenseEntity
-    const licenseType: 'known' | 'custom' = await this.simplePrompt({
-      type: 'list',
-      message: 'Choose license type',
-      choices: [
-        { name: 'Creative Commons', value: 'known' },
-        { name: 'Custom (user-defined)', value: 'custom' },
-      ],
-    })
-    if (licenseType === 'known') {
-      const [id, knownLicenseEntity] = await this.promptForEntityEntry('Choose License', 'KnownLicense', 'code')
-      const knownLicense = await this.parseToEntityJson<KnownLicenseEntity>(knownLicenseEntity)
-      licenseInput = { knownLicense: id.toNumber() }
-      if (knownLicense.attributionRequired) {
-        licenseInput.attribution = await this.simplePrompt({ message: 'Attribution' })
-      }
-    } else {
-      let licenseContent: null | string = null
-      while (licenseContent === null) {
-        try {
-          let licensePath: string = await this.simplePrompt({ message: 'Path to license file:' })
-          licensePath = path.resolve(process.cwd(), licensePath.replace(/^~/, os.homedir()))
-          licenseContent = fs.readFileSync(licensePath).toString()
-        } catch (e) {
-          this.warn("The file was not found or couldn't be accessed, try again...")
-        }
-        if (licenseContent !== null && licenseContent.length > MAX_USER_LICENSE_CONTENT_LENGTH) {
-          this.warn(`The license content cannot be more than ${MAX_USER_LICENSE_CONTENT_LENGTH} characters long`)
-          licenseContent = null
-        }
-      }
-      licenseInput = { userDefinedLicense: { new: { content: licenseContent } } }
-    }
-
-    return { new: licenseInput }
-  }
-
-  async promptForPublishedBeforeJoystream(current?: number | null): Promise<number | null> {
-    const publishedBefore = await this.simplePrompt({
-      type: 'confirm',
-      message: `Do you want to set optional first publication date (publishedBeforeJoystream)?`,
-      default: typeof current === 'number',
-    })
-    if (publishedBefore) {
-      const options = ({
-        type: 'datetime',
-        message: 'Date of first publication',
-        format: ['yyyy', '-', 'mm', '-', 'dd', ' ', 'hh', ':', 'MM', ' ', 'TT'],
-        initial: current && new Date(current * 1000),
-      } as unknown) as DistinctQuestion // Need to assert, because we use datetime plugin which has no TS support
-      const date = await this.simplePrompt(options)
-      return Math.floor(new Date(date).getTime() / 1000)
-    }
-    return null
-  }
-}

+ 0 - 79
cli/src/commands/content-directory/addClassSchema.ts

@@ -1,79 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import AddClassSchemaSchema from '@joystream/cd-schemas/schemas/extrinsics/AddClassSchema.schema.json'
-import { AddClassSchema } from '@joystream/cd-schemas/types/extrinsics/AddClassSchema'
-import { InputParser } from '@joystream/cd-schemas'
-import { JsonSchemaPrompter, JsonSchemaCustomPrompts } from '../../helpers/JsonSchemaPrompt'
-import { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-import { IOFlags, getInputJson, saveOutputJson } from '../../helpers/InputOutput'
-import { Class } from '@joystream/types/content-directory'
-
-export default class AddClassSchemaCommand extends ContentDirectoryCommandBase {
-  static description = 'Add a new schema to a class inside content directory. Requires lead access.'
-
-  static flags = {
-    ...IOFlags,
-  }
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    await this.requireLead()
-    await this.requestAccountDecoding(account)
-
-    const { input, output } = this.parse(AddClassSchemaCommand).flags
-
-    let inputJson = await getInputJson<AddClassSchema>(input)
-    if (!inputJson) {
-      let selectedClass: Class | undefined
-      const customPrompts: JsonSchemaCustomPrompts = [
-        [
-          'className',
-          async () => {
-            selectedClass = await this.promptForClass('Select a class to add schema to')
-            return selectedClass.name.toString()
-          },
-        ],
-        [
-          'existingProperties',
-          async () => {
-            const choices = selectedClass!.properties.map((p, i) => ({ name: `${i}: ${p.name.toString()}`, value: i }))
-            if (!choices.length) {
-              return []
-            }
-            return await this.simplePrompt({
-              type: 'checkbox',
-              message: 'Choose existing properties to keep',
-              choices,
-            })
-          },
-        ],
-        [
-          /^newProperties\[\d+\]\.property_type\.(Single|Vector\.vec_type)\.Reference/,
-          async () => this.promptForClassReference(),
-        ],
-        [/^newProperties\[\d+\]\.property_type\.(Single|Vector\.vec_type)\.Text/, { message: 'Provide TextMaxLength' }],
-        [
-          /^newProperties\[\d+\]\.property_type\.(Single|Vector\.vec_type)\.Hash/,
-          { message: 'Provide HashedTextMaxLength' },
-        ],
-      ]
-
-      const prompter = new JsonSchemaPrompter<AddClassSchema>(
-        AddClassSchemaSchema as JSONSchema,
-        undefined,
-        customPrompts
-      )
-
-      inputJson = await prompter.promptAll()
-    }
-
-    this.jsonPrettyPrint(JSON.stringify(inputJson))
-    const confirmed = await this.simplePrompt({ type: 'confirm', message: 'Do you confirm the provided input?' })
-
-    if (confirmed) {
-      saveOutputJson(output, `${inputJson.className}Schema.json`, inputJson)
-      const inputParser = new InputParser(this.getOriginalApi())
-      this.log('Sending the extrinsic...')
-      await this.sendAndFollowTx(account, await inputParser.parseAddClassSchemaExtrinsic(inputJson))
-    }
-  }
-}

+ 0 - 44
cli/src/commands/content-directory/addMaintainerToClass.ts

@@ -1,44 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import chalk from 'chalk'
-
-export default class AddMaintainerToClassCommand extends ContentDirectoryCommandBase {
-  static description = 'Add maintainer (Curator Group) to a class.'
-  static args = [
-    {
-      name: 'className',
-      required: false,
-      description: 'Name or ID of the class (ie. Video)',
-    },
-    {
-      name: 'groupId',
-      required: false,
-      description: 'ID of the Curator Group to add as class maintainer',
-    },
-  ]
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    await this.requireLead()
-
-    let { groupId, className } = this.parse(AddMaintainerToClassCommand).args
-
-    if (className === undefined) {
-      className = (await this.promptForClass()).name.toString()
-    }
-
-    const classId = (await this.classEntryByNameOrId(className))[0].toNumber()
-
-    if (groupId === undefined) {
-      groupId = await this.promptForCuratorGroup()
-    } else {
-      await this.getCuratorGroup(groupId)
-    }
-
-    await this.requestAccountDecoding(account)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'addMaintainerToClass', [classId, groupId])
-
-    console.log(
-      chalk.green(`Curator Group ${chalk.white(groupId)} added as maintainer to ${chalk.white(className)} class!`)
-    )
-  }
-}

+ 0 - 55
cli/src/commands/content-directory/class.ts

@@ -1,55 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import chalk from 'chalk'
-import { displayCollapsedRow, displayHeader, displayTable } from '../../helpers/display'
-
-export default class ClassCommand extends ContentDirectoryCommandBase {
-  static description = 'Show Class details by id or name.'
-  static args = [
-    {
-      name: 'className',
-      required: true,
-      description: 'Name or ID of the Class',
-    },
-  ]
-
-  async run() {
-    const { className } = this.parse(ClassCommand).args
-    const [id, aClass] = await this.classEntryByNameOrId(className)
-    const permissions = aClass.class_permissions
-    const maintainers = permissions.maintainers.toArray()
-
-    displayCollapsedRow({
-      'Name': aClass.name.toString(),
-      'ID': id.toString(),
-      'Any member': permissions.any_member.toString(),
-      'Entity creation blocked': permissions.entity_creation_blocked.toString(),
-      'All property values locked': permissions.all_entity_property_values_locked.toString(),
-      'Number of entities': aClass.current_number_of_entities.toNumber(),
-      'Max. number of entities': aClass.maximum_entities_count.toNumber(),
-      'Default entity creation voucher max.': aClass.default_entity_creation_voucher_upper_bound.toNumber(),
-    })
-
-    displayHeader(`Maintainers`)
-    this.log(
-      maintainers.length ? maintainers.map((groupId) => chalk.white(`Group ${groupId.toString()}`)).join(', ') : 'NONE'
-    )
-
-    displayHeader(`Properties`)
-    if (aClass.properties.length) {
-      displayTable(
-        aClass.properties.map((p, i) => ({
-          'Index': i,
-          'Name': p.name.toString(),
-          'Type': JSON.stringify(p.property_type.toJSON()),
-          'Required': p.required.toString(),
-          'Unique': p.unique.toString(),
-          'Controller lock': p.locking_policy.is_locked_from_controller.toString(),
-          'Maintainer lock': p.locking_policy.is_locked_from_maintainer.toString(),
-        })),
-        3
-      )
-    } else {
-      this.log('NONE')
-    }
-  }
-}

+ 0 - 24
cli/src/commands/content-directory/classes.ts

@@ -1,24 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-// import chalk from 'chalk'
-import { displayTable } from '../../helpers/display'
-
-export default class ClassesCommand extends ContentDirectoryCommandBase {
-  static description = 'List existing content directory classes.'
-
-  async run() {
-    const classes = await this.getApi().availableClasses()
-
-    displayTable(
-      classes.map(([id, c]) => ({
-        'ID': id.toString(),
-        'Name': c.name.toString(),
-        'Any member': c.class_permissions.any_member.toString(),
-        'Entities': c.current_number_of_entities.toNumber(),
-        'Schemas': c.schemas.length,
-        'Maintainers': c.class_permissions.maintainers.toArray().length,
-        'Properties': c.properties.length,
-      })),
-      3
-    )
-  }
-}

+ 0 - 50
cli/src/commands/content-directory/createClass.ts

@@ -1,50 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import CreateClassSchema from '@joystream/cd-schemas/schemas/extrinsics/CreateClass.schema.json'
-import { CreateClass } from '@joystream/cd-schemas/types/extrinsics/CreateClass'
-import { InputParser } from '@joystream/cd-schemas'
-import { JsonSchemaPrompter, JsonSchemaCustomPrompts } from '../../helpers/JsonSchemaPrompt'
-import { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-import { IOFlags, getInputJson, saveOutputJson } from '../../helpers/InputOutput'
-
-export default class CreateClassCommand extends ContentDirectoryCommandBase {
-  static description = 'Create class inside content directory. Requires lead access.'
-  static flags = {
-    ...IOFlags,
-  }
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    await this.requireLead()
-    await this.requestAccountDecoding(account)
-
-    const { input, output } = this.parse(CreateClassCommand).flags
-    const existingClassnames = (await this.getApi().availableClasses()).map(([, aClass]) => aClass.name.toString())
-
-    let inputJson = await getInputJson<CreateClass>(input, CreateClassSchema as JSONSchema)
-    if (!inputJson) {
-      const customPrompts: JsonSchemaCustomPrompts<CreateClass> = [
-        [
-          'name',
-          {
-            validate: (className) => existingClassnames.includes(className) && 'A class with this name already exists!',
-          },
-        ],
-        ['class_permissions.maintainers', () => this.promptForCuratorGroups('Select class maintainers')],
-      ]
-
-      const prompter = new JsonSchemaPrompter<CreateClass>(CreateClassSchema as JSONSchema, undefined, customPrompts)
-
-      inputJson = await prompter.promptAll()
-    }
-
-    this.jsonPrettyPrint(JSON.stringify(inputJson))
-    const confirmed = await this.simplePrompt({ type: 'confirm', message: 'Do you confirm the provided input?' })
-
-    if (confirmed) {
-      saveOutputJson(output, `${inputJson.name}Class.json`, inputJson)
-      this.log('Sending the extrinsic...')
-      const inputParser = new InputParser(this.getOriginalApi())
-      await this.sendAndFollowTx(account, inputParser.parseCreateClassExtrinsic(inputJson))
-    }
-  }
-}

+ 0 - 58
cli/src/commands/content-directory/createEntity.ts

@@ -1,58 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import inquirer from 'inquirer'
-import { InputParser } from '@joystream/cd-schemas'
-import ExitCodes from '../../ExitCodes'
-
-export default class CreateEntityCommand extends ContentDirectoryCommandBase {
-  static description =
-    'Creates a new entity in the specified class (can be executed in Member, Curator or Lead context)'
-
-  static args = [
-    {
-      name: 'className',
-      required: true,
-      description: 'Name or ID of the Class',
-    },
-  ]
-
-  static flags = {
-    context: ContentDirectoryCommandBase.contextFlag,
-  }
-
-  async run() {
-    const { className } = this.parse(CreateEntityCommand).args
-    let { context } = this.parse(CreateEntityCommand).flags
-
-    if (!context) {
-      context = await this.promptForContext()
-    }
-
-    const currentAccount = await this.getRequiredSelectedAccount()
-    await this.requestAccountDecoding(currentAccount)
-    const [, entityClass] = await this.classEntryByNameOrId(className)
-
-    const actor = await this.getActor(context, entityClass)
-
-    if (actor.isOfType('Member') && entityClass.class_permissions.any_member.isFalse) {
-      this.error('Choosen actor has no access to create an entity of this type', { exit: ExitCodes.AccessDenied })
-    }
-
-    const answers: {
-      [key: string]: string | number | null
-    } = await inquirer.prompt(this.getQuestionsFromProperties(entityClass.properties.toArray()))
-
-    this.jsonPrettyPrint(JSON.stringify(answers))
-    await this.requireConfirmation('Do you confirm the provided input?')
-
-    const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi(), [
-      {
-        className: entityClass.name.toString(),
-        entries: [answers],
-      },
-    ])
-
-    const operations = await inputParser.getEntityBatchOperations()
-
-    await this.sendAndFollowNamedTx(currentAccount, 'contentDirectory', 'transaction', [actor, operations])
-  }
-}

+ 0 - 45
cli/src/commands/content-directory/entities.ts

@@ -1,45 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { displayTable } from '../../helpers/display'
-import { flags } from '@oclif/command'
-
-export default class EntitiesCommand extends ContentDirectoryCommandBase {
-  static description = 'Show entities list by class id or name.'
-  static args = [
-    {
-      name: 'className',
-      required: true,
-      description: 'Name or ID of the Class',
-    },
-    {
-      name: 'properties',
-      required: false,
-      description:
-        'Comma-separated properties to include in the results table (ie. code,name). ' +
-        'By default all property values will be included.',
-    },
-  ]
-
-  static flags = {
-    filters: flags.string({
-      required: false,
-      description:
-        'Comma-separated filters, ie. title="Some video",channelId=3.' +
-        'Currently only the = operator is supported.' +
-        'When multiple filters are provided, only the entities that match all of them together will be displayed.',
-    }),
-  }
-
-  async run() {
-    const { className, properties } = this.parse(EntitiesCommand).args
-    const { filters } = this.parse(EntitiesCommand).flags
-    const propsToInclude: string[] | undefined = (properties || undefined) && (properties as string).split(',')
-    const filtersArr: [string, string][] = filters
-      ? filters
-          .split(',')
-          .map((f) => f.split('='))
-          .map(([pName, pValue]) => [pName, pValue.replace(/^"(.+)"$/, '$1')])
-      : []
-
-    displayTable(await this.createEntityList(className, propsToInclude, filtersArr), 3)
-  }
-}

+ 0 - 44
cli/src/commands/content-directory/entity.ts

@@ -1,44 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import chalk from 'chalk'
-import { displayCollapsedRow, displayHeader } from '../../helpers/display'
-import _ from 'lodash'
-
-export default class EntityCommand extends ContentDirectoryCommandBase {
-  static description = 'Show Entity details by id.'
-  static args = [
-    {
-      name: 'id',
-      required: true,
-      description: 'ID of the Entity',
-    },
-  ]
-
-  async run() {
-    const { id } = this.parse(EntityCommand).args
-    const entity = await this.getEntity(id, undefined, undefined, false)
-    const { controller, frozen, referenceable } = entity.entity_permissions
-    const [classId, entityClass] = await this.classEntryByNameOrId(entity.class_id.toString())
-    const propertyValues = this.parseEntityPropertyValues(entity, entityClass)
-
-    displayCollapsedRow({
-      'ID': id,
-      'Class name': entityClass.name.toString(),
-      'Class ID': classId.toNumber(),
-      'Supported schemas': JSON.stringify(entity.supported_schemas.toJSON()),
-      'Controller': controller.type + (controller.isOfType('Member') ? `(${controller.asType('Member')})` : ''),
-      'Frozen': frozen.toString(),
-      'Refrecencable': referenceable.toString(),
-      'Same owner references': entity.reference_counter.same_owner.toNumber(),
-      'Total references': entity.reference_counter.total.toNumber(),
-    })
-    displayHeader('Property values')
-    displayCollapsedRow(
-      _.mapValues(
-        propertyValues,
-        (v) =>
-          (v.value === null ? chalk.grey('[not set]') : v.value.toString()) +
-          ` ${chalk.green(`${v.type}<${v.subtype}>`)}`
-      )
-    )
-  }
-}

+ 0 - 57
cli/src/commands/content-directory/initialize.ts

@@ -1,57 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { InputParser, ExtrinsicsHelper, getInitializationInputs } from '@joystream/cd-schemas'
-import { flags } from '@oclif/command'
-
-export default class InitializeCommand extends ContentDirectoryCommandBase {
-  static description =
-    'Initialize content directory with input data from @joystream/content library or custom, provided one. Requires lead access.'
-
-  static flags = {
-    rootInputsDir: flags.string({
-      required: false,
-      description: 'Custom inputs directory (must follow @joystream/content directory structure)',
-    }),
-  }
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    await this.requireLead()
-    await this.requestAccountDecoding(account)
-
-    const {
-      flags: { rootInputsDir },
-    } = this.parse(InitializeCommand)
-
-    const { classInputs, schemaInputs, entityBatchInputs } = getInitializationInputs(rootInputsDir)
-
-    const currentClasses = await this.getApi().availableClasses()
-
-    if (currentClasses.length) {
-      this.log('There are already some existing classes in the current content directory.')
-      await this.requireConfirmation('Do you wish to continue anyway?')
-    }
-
-    const txHelper = new ExtrinsicsHelper(this.getOriginalApi())
-    const parser = new InputParser(this.getOriginalApi(), classInputs, schemaInputs, entityBatchInputs)
-
-    this.log(`Initializing classes (${classInputs.length} input files found)...\n`)
-    const classExtrinsics = parser.getCreateClassExntrinsics()
-    await txHelper.sendAndCheck(account, classExtrinsics, 'Class initialization failed!')
-
-    this.log(`Initializing schemas (${schemaInputs.length} input files found)...\n`)
-    const schemaExtrinsics = await parser.getAddSchemaExtrinsics()
-    await txHelper.sendAndCheck(account, schemaExtrinsics, 'Schemas initialization failed!')
-
-    this.log(`Initializing entities (${entityBatchInputs.length} input files found)`)
-    const entityOperations = await parser.getEntityBatchOperations()
-
-    this.log(`Sending Transaction extrinsic (${entityOperations.length} operations)...\n`)
-    await txHelper.sendAndCheck(
-      account,
-      [this.getOriginalApi().tx.contentDirectory.transaction({ Lead: null }, entityOperations)],
-      'Entity initialization failed!'
-    )
-
-    this.log('DONE')
-  }
-}

+ 0 - 35
cli/src/commands/content-directory/removeCuratorGroup.ts

@@ -1,35 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import chalk from 'chalk'
-import ExitCodes from '../../ExitCodes'
-
-export default class AddCuratorGroupCommand extends ContentDirectoryCommandBase {
-  static description = 'Remove existing Curator Group.'
-  static args = [
-    {
-      name: 'id',
-      required: false,
-      description: 'ID of the Curator Group to remove',
-    },
-  ]
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    await this.requireLead()
-
-    let { id } = this.parse(AddCuratorGroupCommand).args
-    if (id === undefined) {
-      id = await this.promptForCuratorGroup('Select Curator Group to remove')
-    }
-
-    const group = await this.getCuratorGroup(id)
-
-    if (group.number_of_classes_maintained.toNumber() > 0) {
-      this.error('Cannot remove a group which has some maintained classes!', { exit: ExitCodes.InvalidInput })
-    }
-
-    await this.requestAccountDecoding(account)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'removeCuratorGroup', [id])
-
-    console.log(chalk.green(`Curator Group ${chalk.white(id)} succesfully removed!`))
-  }
-}

+ 0 - 45
cli/src/commands/content-directory/removeEntity.ts

@@ -1,45 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { Actor } from '@joystream/types/content-directory'
-import ExitCodes from '../../ExitCodes'
-
-export default class RemoveEntityCommand extends ContentDirectoryCommandBase {
-  static description = 'Removes a single entity by id (can be executed in Member, Curator or Lead context)'
-  static flags = {
-    context: ContentDirectoryCommandBase.contextFlag,
-  }
-
-  static args = [
-    {
-      name: 'id',
-      required: true,
-      description: 'ID of the entity to remove',
-    },
-  ]
-
-  async run() {
-    let {
-      args: { id },
-      flags: { context },
-    } = this.parse(RemoveEntityCommand)
-
-    const entity = await this.getEntity(id, undefined, undefined, false)
-    const [, entityClass] = await this.classEntryByNameOrId(entity.class_id.toString())
-
-    if (!context) {
-      context = await this.promptForContext()
-    }
-
-    const account = await this.getRequiredSelectedAccount()
-    const actor: Actor = await this.getActor(context, entityClass)
-    if (!actor.isOfType('Curator') && !this.isActorEntityController(actor, entity, false)) {
-      this.error('You are not the entity controller!', { exit: ExitCodes.AccessDenied })
-    }
-
-    await this.requireConfirmation(
-      `Are you sure you want to remove entity ${id} of class ${entityClass.name.toString()}?`
-    )
-    await this.requestAccountDecoding(account)
-
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'removeEntity', [actor, id])
-  }
-}

+ 0 - 44
cli/src/commands/content-directory/removeMaintainerFromClass.ts

@@ -1,44 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import chalk from 'chalk'
-
-export default class AddMaintainerToClassCommand extends ContentDirectoryCommandBase {
-  static description = 'Remove maintainer (Curator Group) from class.'
-  static args = [
-    {
-      name: 'className',
-      required: false,
-      description: 'Name or ID of the class (ie. Video)',
-    },
-    {
-      name: 'groupId',
-      required: false,
-      description: 'ID of the Curator Group to remove from maintainers',
-    },
-  ]
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    await this.requireLead()
-
-    let { groupId, className } = this.parse(AddMaintainerToClassCommand).args
-
-    if (className === undefined) {
-      className = (await this.promptForClass()).name.toString()
-    }
-
-    const [classId, aClass] = await this.classEntryByNameOrId(className)
-
-    if (groupId === undefined) {
-      groupId = await this.promptForCuratorGroup('Select a maintainer', aClass.class_permissions.maintainers.toArray())
-    } else {
-      await this.getCuratorGroup(groupId)
-    }
-
-    await this.requestAccountDecoding(account)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'removeMaintainerFromClass', [classId, groupId])
-
-    console.log(
-      chalk.green(`Curator Group ${chalk.white(groupId)} removed as maintainer of ${chalk.white(className)} class!`)
-    )
-  }
-}

+ 0 - 55
cli/src/commands/content-directory/updateClassPermissions.ts

@@ -1,55 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import CreateClassSchema from '@joystream/cd-schemas/schemas/extrinsics/CreateClass.schema.json'
-import chalk from 'chalk'
-import { JsonSchemaCustomPrompts, JsonSchemaPrompter } from '../../helpers/JsonSchemaPrompt'
-import { CreateClass } from '@joystream/cd-schemas/types/extrinsics/CreateClass'
-import { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-
-export default class UpdateClassPermissionsCommand extends ContentDirectoryCommandBase {
-  static description = 'Update permissions in given class.'
-  static args = [
-    {
-      name: 'className',
-      required: false,
-      description: 'Name or ID of the class (ie. Video)',
-    },
-  ]
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    await this.requireLead()
-
-    let { className } = this.parse(UpdateClassPermissionsCommand).args
-
-    if (className === undefined) {
-      className = (await this.promptForClass()).name.toString()
-    }
-
-    const [classId, aClass] = await this.classEntryByNameOrId(className)
-    const currentPermissions = aClass.class_permissions
-
-    const customPrompts: JsonSchemaCustomPrompts = [
-      ['class_permissions.maintainers', () => this.promptForCuratorGroups('Select class maintainers')],
-    ]
-
-    const prompter = new JsonSchemaPrompter<CreateClass>(
-      CreateClassSchema as JSONSchema,
-      { class_permissions: currentPermissions.toJSON() as CreateClass['class_permissions'] },
-      customPrompts
-    )
-
-    const newPermissions = await prompter.promptSingleProp('class_permissions')
-
-    await this.requestAccountDecoding(account)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'updateClassPermissions', [
-      classId,
-      newPermissions.any_member,
-      newPermissions.entity_creation_blocked,
-      newPermissions.all_entity_property_values_locked,
-      newPermissions.maintainers,
-    ])
-
-    console.log(chalk.green(`${chalk.white(className)} class permissions updated to:`))
-    this.jsonPrettyPrint(JSON.stringify(newPermissions))
-  }
-}

+ 0 - 61
cli/src/commands/content-directory/updateEntityPropertyValues.ts

@@ -1,61 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import inquirer from 'inquirer'
-import { InputParser } from '@joystream/cd-schemas'
-import ExitCodes from '../../ExitCodes'
-
-export default class UpdateEntityPropertyValues extends ContentDirectoryCommandBase {
-  static description =
-    'Updates the property values of the specified entity (can be executed in Member, Curator or Lead context)'
-
-  static args = [
-    {
-      name: 'id',
-      required: true,
-      description: 'ID of the Entity',
-    },
-  ]
-
-  static flags = {
-    context: ContentDirectoryCommandBase.contextFlag,
-  }
-
-  async run() {
-    const { id } = this.parse(UpdateEntityPropertyValues).args
-    let { context } = this.parse(UpdateEntityPropertyValues).flags
-
-    if (!context) {
-      context = await this.promptForContext()
-    }
-
-    const currentAccount = await this.getRequiredSelectedAccount()
-    await this.requestAccountDecoding(currentAccount)
-
-    const entity = await this.getEntity(id)
-    const [, entityClass] = await this.classEntryByNameOrId(entity.class_id.toString())
-    const defaults = await this.parseToEntityJson(entity)
-
-    const actor = await this.getActor(context, entityClass)
-
-    const isPropertEditableByIndex = await Promise.all(
-      entityClass.properties.map((p, i) => this.isEntityPropertyEditableByActor(entity, i, actor))
-    )
-    const filteredProperties = entityClass.properties.filter((p, i) => isPropertEditableByIndex[i])
-
-    if (!filteredProperties.length) {
-      this.error('No entity properties are editable by choosen actor', { exit: ExitCodes.AccessDenied })
-    }
-
-    const answers: {
-      [key: string]: string | number | null
-    } = await inquirer.prompt(this.getQuestionsFromProperties(filteredProperties, defaults))
-
-    this.jsonPrettyPrint(JSON.stringify(answers))
-    await this.requireConfirmation('Do you confirm the provided input?')
-
-    const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi())
-
-    const operations = await inputParser.getEntityUpdateOperations(answers, entityClass.name.toString(), +id)
-
-    await this.sendAndFollowNamedTx(currentAccount, 'contentDirectory', 'transaction', [actor, operations])
-  }
-}

+ 1 - 1
cli/src/commands/content-directory/addCuratorToGroup.ts → cli/src/commands/content/addCuratorToGroup.ts

@@ -35,7 +35,7 @@ export default class AddCuratorToGroupCommand extends ContentDirectoryCommandBas
     }
 
     await this.requestAccountDecoding(account)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'addCuratorToGroup', [groupId, curatorId])
+    await this.sendAndFollowNamedTx(account, 'content', 'addCuratorToGroup', [groupId, curatorId])
 
     console.log(chalk.green(`Curator ${chalk.white(curatorId)} succesfully added to group ${chalk.white(groupId)}!`))
   }

+ 3 - 3
cli/src/commands/content-directory/createCuratorGroup.ts → cli/src/commands/content/createCuratorGroup.ts

@@ -1,16 +1,16 @@
 import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
 import chalk from 'chalk'
 
-export default class AddCuratorGroupCommand extends ContentDirectoryCommandBase {
+export default class CreateCuratorGroupCommand extends ContentDirectoryCommandBase {
   static description = 'Create new Curator Group.'
-  static aliases = ['addCuratorGroup']
+  static aliases = ['createCuratorGroup']
 
   async run() {
     const account = await this.getRequiredSelectedAccount()
     await this.requireLead()
 
     await this.requestAccountDecoding(account)
-    await this.buildAndSendExtrinsic(account, 'contentDirectory', 'addCuratorGroup')
+    await this.buildAndSendExtrinsic(account, 'content', 'createCuratorGroup')
 
     const newGroupId = (await this.getApi().nextCuratorGroupId()) - 1
     console.log(chalk.green(`New group succesfully created! (ID: ${chalk.white(newGroupId)})`))

+ 0 - 5
cli/src/commands/content-directory/curatorGroup.ts → cli/src/commands/content/curatorGroup.ts

@@ -16,9 +16,6 @@ export default class CuratorGroupCommand extends ContentDirectoryCommandBase {
   async run() {
     const { id } = this.parse(CuratorGroupCommand).args
     const group = await this.getCuratorGroup(id)
-    const classesMaintained = (await this.getApi().availableClasses()).filter(([, c]) =>
-      c.class_permissions.maintainers.toArray().some((gId) => gId.toNumber() === parseInt(id))
-    )
     const members = (await this.getApi().groupMembers(WorkingGroups.Curators)).filter((curator) =>
       group.curators.toArray().some((groupCurator) => groupCurator.eq(curator.workerId))
     )
@@ -27,8 +24,6 @@ export default class CuratorGroupCommand extends ContentDirectoryCommandBase {
       'ID': id,
       'Status': group.active.valueOf() ? 'Active' : 'Inactive',
     })
-    displayHeader(`Classes maintained (${classesMaintained.length})`)
-    this.log(classesMaintained.map(([, c]) => chalk.white(c.name.toString())).join(', '))
     displayHeader(`Group Members (${members.length})`)
     this.log(
       members

+ 0 - 1
cli/src/commands/content-directory/curatorGroups.ts → cli/src/commands/content/curatorGroups.ts

@@ -13,7 +13,6 @@ export default class CuratorGroupsCommand extends ContentDirectoryCommandBase {
         groups.map(([id, group]) => ({
           'ID': id.toString(),
           'Status': group.active.valueOf() ? 'Active' : 'Inactive',
-          'Classes maintained': group.number_of_classes_maintained.toNumber(),
           'Members': group.curators.toArray().length,
         })),
         5

+ 1 - 1
cli/src/commands/content-directory/removeCuratorFromGroup.ts → cli/src/commands/content/removeCuratorFromGroup.ts

@@ -39,7 +39,7 @@ export default class RemoveCuratorFromGroupCommand extends ContentDirectoryComma
     }
 
     await this.requestAccountDecoding(account)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'removeCuratorFromGroup', [groupId, curatorId])
+    await this.sendAndFollowNamedTx(account, 'content', 'removeCuratorFromGroup', [groupId, curatorId])
 
     this.log(chalk.green(`Curator ${chalk.white(curatorId)} successfully removed from group ${chalk.white(groupId)}!`))
   }

+ 1 - 1
cli/src/commands/content-directory/setCuratorGroupStatus.ts → cli/src/commands/content/setCuratorGroupStatus.ts

@@ -48,7 +48,7 @@ export default class SetCuratorGroupStatusCommand extends ContentDirectoryComman
     }
 
     await this.requestAccountDecoding(account)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'setCuratorGroupStatus', [id, status])
+    await this.sendAndFollowNamedTx(account, 'content', 'setCuratorGroupStatus', [id, status])
 
     console.log(
       chalk.green(

+ 0 - 58
cli/src/commands/media/createChannel.ts

@@ -1,58 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import ChannelEntitySchema from '@joystream/cd-schemas/schemas/entities/ChannelEntity.schema.json'
-import { ChannelEntity } from '@joystream/cd-schemas/types/entities/ChannelEntity'
-import { InputParser } from '@joystream/cd-schemas'
-import { IOFlags, getInputJson, saveOutputJson } from '../../helpers/InputOutput'
-import { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-import { JsonSchemaCustomPrompts, JsonSchemaPrompter } from '../../helpers/JsonSchemaPrompt'
-
-import { flags } from '@oclif/command'
-import _ from 'lodash'
-
-export default class CreateChannelCommand extends ContentDirectoryCommandBase {
-  static description = 'Create a new channel on Joystream (requires a membership).'
-  static flags = {
-    ...IOFlags,
-    confirm: flags.boolean({ char: 'y', name: 'confirm', required: false, description: 'Confirm the provided input' }),
-  }
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    const memberId = await this.getRequiredMemberId()
-    const actor = { Member: memberId }
-
-    await this.requestAccountDecoding(account)
-
-    const channelJsonSchema = (ChannelEntitySchema as unknown) as JSONSchema
-
-    const { input, output, confirm } = this.parse(CreateChannelCommand).flags
-
-    let inputJson = await getInputJson<ChannelEntity>(input, channelJsonSchema)
-    if (!inputJson) {
-      const customPrompts: JsonSchemaCustomPrompts = [
-        ['language', () => this.promptForEntityId('Choose channel language', 'Language', 'name')],
-        ['isCensored', 'skip'],
-      ]
-
-      const prompter = new JsonSchemaPrompter<ChannelEntity>(channelJsonSchema, undefined, customPrompts)
-
-      inputJson = await prompter.promptAll()
-    }
-
-    this.jsonPrettyPrint(JSON.stringify(inputJson))
-    const confirmed =
-      confirm || (await this.simplePrompt({ type: 'confirm', message: 'Do you confirm the provided input?' }))
-
-    if (confirmed) {
-      saveOutputJson(output, `${_.startCase(inputJson.handle)}Channel.json`, inputJson)
-      const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi(), [
-        {
-          className: 'Channel',
-          entries: [inputJson],
-        },
-      ])
-      const operations = await inputParser.getEntityBatchOperations()
-      await this.sendAndFollowNamedTx(account, 'contentDirectory', 'transaction', [actor, operations])
-    }
-  }
-}

+ 0 - 57
cli/src/commands/media/curateContent.ts

@@ -1,57 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { InputParser } from '@joystream/cd-schemas'
-import { flags } from '@oclif/command'
-import { ChannelEntity } from '@joystream/cd-schemas/types/entities/ChannelEntity'
-import { VideoEntity } from '@joystream/cd-schemas/types/entities/VideoEntity'
-
-const CLASSES = ['Channel', 'Video'] as const
-const STATUSES = ['Accepted', 'Censored'] as const
-
-export default class CurateContentCommand extends ContentDirectoryCommandBase {
-  static description = `Set the curation status of given entity (${CLASSES.join('/')}). Requires Curator access.`
-  static flags = {
-    className: flags.enum({
-      options: [...CLASSES],
-      description: `Name of the class of the entity to curate (${CLASSES.join('/')})`,
-      char: 'c',
-      required: true,
-    }),
-    status: flags.enum({
-      description: `Specifies the curation status (${STATUSES.join('/')})`,
-      char: 's',
-      options: [...STATUSES],
-      required: true,
-    }),
-    id: flags.integer({
-      description: 'ID of the entity to curate',
-      required: true,
-    }),
-  }
-
-  async run() {
-    const { className, status, id } = this.parse(CurateContentCommand).flags
-
-    const account = await this.getRequiredSelectedAccount()
-    // Get curator actor with required maintainer access to $className (Video/Channel) class
-    const actor = await this.getCuratorContext([className])
-
-    await this.requestAccountDecoding(account)
-
-    const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi())
-
-    await this.getEntity(id, className) // Check if entity exists and is of given class
-
-    const entityUpdateInput: Partial<ChannelEntity & VideoEntity> = {
-      isCensored: status === 'Censored',
-    }
-
-    this.log(`Updating the ${className} with:`)
-    this.jsonPrettyPrint(JSON.stringify(entityUpdateInput))
-    const confirmed = await this.simplePrompt({ type: 'confirm', message: 'Do you confirm the provided input?' })
-
-    if (confirmed) {
-      const operations = await inputParser.getEntityUpdateOperations(entityUpdateInput, className, id)
-      await this.sendAndFollowNamedTx(account, 'contentDirectory', 'transaction', [actor, operations], true)
-    }
-  }
-}

+ 0 - 36
cli/src/commands/media/featuredVideos.ts

@@ -1,36 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { displayTable } from '../../helpers/display'
-import { FeaturedVideoEntity, VideoEntity } from '@joystream/cd-schemas/types/entities'
-import chalk from 'chalk'
-
-export default class FeaturedVideosCommand extends ContentDirectoryCommandBase {
-  static description = 'Show a list of currently featured videos.'
-
-  async run() {
-    const featuredEntries = await this.entitiesByClassAndOwner('FeaturedVideo')
-    const featured = await Promise.all(
-      featuredEntries
-        .filter(([, entity]) => entity.supported_schemas.toArray().length) // Ignore FeaturedVideo entities without schema
-        .map(([, entity]) => this.parseToEntityJson<FeaturedVideoEntity>(entity))
-    )
-
-    const videoIds: number[] = featured.map(({ video: videoId }) => videoId)
-
-    const videos = await Promise.all(videoIds.map((videoId) => this.getAndParseKnownEntity<VideoEntity>(videoId)))
-
-    if (videos.length) {
-      displayTable(
-        videos.map(({ title, channel }, index) => ({
-          featuredVideoEntityId: featuredEntries[index][0].toNumber(),
-          videoId: videoIds[index],
-          channelId: channel,
-          title,
-        })),
-        3
-      )
-      this.log(`\nTIP: Use ${chalk.bold('content-directory:entity ID')} command to see more details about given video`)
-    } else {
-      this.log(`No videos have been featured yet! Set some with ${chalk.bold('media:setFeaturedVideos')}`)
-    }
-  }
-}

+ 0 - 25
cli/src/commands/media/myChannels.ts

@@ -1,25 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { ChannelEntity } from '@joystream/cd-schemas/types/entities/ChannelEntity'
-import { displayTable } from '../../helpers/display'
-import chalk from 'chalk'
-
-export default class MyChannelsCommand extends ContentDirectoryCommandBase {
-  static description = "Show the list of channels associated with current account's membership."
-
-  async run() {
-    const memberId = await this.getRequiredMemberId()
-
-    const props: (keyof ChannelEntity)[] = ['handle', 'isPublic']
-
-    const list = await this.createEntityList('Channel', props, [], memberId)
-
-    if (list.length) {
-      displayTable(list, 3)
-      this.log(
-        `\nTIP: Use ${chalk.bold('content-directory:entity ID')} command to see more details about given channel`
-      )
-    } else {
-      this.log(`No channels created yet! Create a channel with ${chalk.bold('media:createChannel')}`)
-    }
-  }
-}

+ 0 - 33
cli/src/commands/media/myVideos.ts

@@ -1,33 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { VideoEntity } from '@joystream/cd-schemas/types/entities/VideoEntity'
-import { displayTable } from '../../helpers/display'
-import chalk from 'chalk'
-import { flags } from '@oclif/command'
-
-export default class MyVideosCommand extends ContentDirectoryCommandBase {
-  static description = "Show the list of videos associated with current account's membership."
-  static flags = {
-    channel: flags.integer({
-      char: 'c',
-      required: false,
-      description: 'Channel id to filter the videos by',
-    }),
-  }
-
-  async run() {
-    const memberId = await this.getRequiredMemberId()
-
-    const { channel } = this.parse(MyVideosCommand).flags
-    const props: (keyof VideoEntity)[] = ['title', 'isPublic', 'channel']
-    const filters: [string, string][] = channel !== undefined ? [['channel', channel.toString()]] : []
-
-    const list = await this.createEntityList('Video', props, filters, memberId)
-
-    if (list.length) {
-      displayTable(list, 3)
-      this.log(`\nTIP: Use ${chalk.bold('content-directory:entity ID')} command to see more details about given video`)
-    } else {
-      this.log(`No videos uploaded yet! Upload a video with ${chalk.bold('media:uploadVideo')}`)
-    }
-  }
-}

+ 0 - 44
cli/src/commands/media/removeChannel.ts

@@ -1,44 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { Entity } from '@joystream/types/content-directory'
-import { createType } from '@joystream/types'
-import { ChannelEntity } from '@joystream/cd-schemas/types/entities'
-
-export default class RemoveChannelCommand extends ContentDirectoryCommandBase {
-  static description = 'Removes a channel (required controller access).'
-  static args = [
-    {
-      name: 'id',
-      required: false,
-      description: 'ID of the Channel entity',
-    },
-  ]
-
-  async run() {
-    const {
-      args: { id },
-    } = this.parse(RemoveChannelCommand)
-
-    const account = await this.getRequiredSelectedAccount()
-    const memberId = await this.getRequiredMemberId()
-    const actor = createType('Actor', { Member: memberId })
-
-    await this.requestAccountDecoding(account)
-
-    let channelEntity: Entity, channelId: number
-    if (id) {
-      channelId = parseInt(id)
-      channelEntity = await this.getEntity(channelId, 'Channel', memberId)
-    } else {
-      const [id, channel] = await this.promptForEntityEntry('Select a channel to remove', 'Channel', 'handle', memberId)
-      channelId = id.toNumber()
-      channelEntity = channel
-    }
-    const channel = await this.parseToEntityJson<ChannelEntity>(channelEntity)
-
-    await this.requireConfirmation(`Are you sure you want to remove "${channel.handle}" channel?`)
-
-    const api = this.getOriginalApi()
-    this.log(`Removing Channel entity (ID: ${channelId})...`)
-    await this.sendAndFollowTx(account, api.tx.contentDirectory.removeEntity(actor, channelId))
-  }
-}

+ 0 - 49
cli/src/commands/media/removeVideo.ts

@@ -1,49 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { Entity } from '@joystream/types/content-directory'
-import { VideoEntity } from '@joystream/cd-schemas/types/entities'
-import { createType } from '@joystream/types'
-
-export default class RemoveVideoCommand extends ContentDirectoryCommandBase {
-  static description = 'Remove given Video entity and associated entities (VideoMedia, License) from content directory.'
-  static args = [
-    {
-      name: 'id',
-      required: false,
-      description: 'ID of the Video entity',
-    },
-  ]
-
-  async run() {
-    const {
-      args: { id },
-    } = this.parse(RemoveVideoCommand)
-
-    const account = await this.getRequiredSelectedAccount()
-    const memberId = await this.getRequiredMemberId()
-    const actor = createType('Actor', { Member: memberId })
-
-    await this.requestAccountDecoding(account)
-
-    let videoEntity: Entity, videoId: number
-    if (id) {
-      videoId = parseInt(id)
-      videoEntity = await this.getEntity(videoId, 'Video', memberId)
-    } else {
-      const [id, video] = await this.promptForEntityEntry('Select a video to remove', 'Video', 'title', memberId)
-      videoId = id.toNumber()
-      videoEntity = video
-    }
-
-    const video = await this.parseToEntityJson<VideoEntity>(videoEntity)
-
-    await this.requireConfirmation(`Are you sure you want to remove the "${video.title}" video?`)
-
-    const api = this.getOriginalApi()
-    this.log(`Removing the Video entity (ID: ${videoId})...`)
-    await this.sendAndFollowTx(account, api.tx.contentDirectory.removeEntity(actor, videoId))
-    this.log(`Removing the VideoMedia entity (ID: ${video.media})...`)
-    await this.sendAndFollowTx(account, api.tx.contentDirectory.removeEntity(actor, video.media))
-    this.log(`Removing the License entity (ID: ${video.license})...`)
-    await this.sendAndFollowTx(account, api.tx.contentDirectory.removeEntity(actor, video.license))
-  }
-}

+ 0 - 79
cli/src/commands/media/setFeaturedVideos.ts

@@ -1,79 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import { VideoEntity } from '@joystream/cd-schemas/types/entities'
-import { InputParser, ExtrinsicsHelper } from '@joystream/cd-schemas'
-import { FlattenRelations } from '@joystream/cd-schemas/types/utility'
-import { flags } from '@oclif/command'
-import { createType } from '@joystream/types'
-
-export default class SetFeaturedVideosCommand extends ContentDirectoryCommandBase {
-  static description = 'Set currently featured videos (requires lead/maintainer access).'
-  static args = [
-    {
-      name: 'videoIds',
-      required: true,
-      description: 'Comma-separated video ids',
-    },
-  ]
-
-  static flags = {
-    add: flags.boolean({
-      description: 'If provided - currently featured videos will not be removed.',
-      required: false,
-    }),
-  }
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    let actor = createType('Actor', { Lead: null })
-    try {
-      await this.getRequiredLead()
-    } catch (e) {
-      actor = await this.getCuratorContext(['FeaturedVideo'])
-    }
-
-    await this.requestAccountDecoding(account)
-
-    const {
-      args: { videoIds },
-      flags: { add },
-    } = this.parse(SetFeaturedVideosCommand)
-
-    const ids: number[] = videoIds.split(',').map((id: string) => parseInt(id))
-
-    const videos: [number, FlattenRelations<VideoEntity>][] = (
-      await Promise.all(ids.map((id) => this.getAndParseKnownEntity<VideoEntity>(id, 'Video')))
-    ).map((video, index) => [ids[index], video])
-
-    this.log(
-      `Featured videos that will ${add ? 'be added to' : 'replace'} existing ones:`,
-      videos.map(([id, { title }]) => ({ id, title }))
-    )
-
-    await this.requireConfirmation('Do you confirm the provided input?')
-
-    if (!add) {
-      const currentlyFeaturedIds = (await this.entitiesByClassAndOwner('FeaturedVideo')).map(([id]) => id.toNumber())
-      const removeTxs = currentlyFeaturedIds.map((id) =>
-        this.getOriginalApi().tx.contentDirectory.removeEntity(actor, id)
-      )
-
-      if (currentlyFeaturedIds.length) {
-        this.log(`Removing existing FeaturedVideo entities (${currentlyFeaturedIds.join(', ')})...`)
-
-        const txHelper = new ExtrinsicsHelper(this.getOriginalApi())
-        await txHelper.sendAndCheck(account, removeTxs, 'The removal of existing FeaturedVideo entities failed')
-      }
-    }
-
-    this.log('Adding new FeaturedVideo entities...')
-    const featuredVideoEntries = videos.map(([id]) => ({ video: id }))
-    const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi(), [
-      {
-        className: 'FeaturedVideo',
-        entries: featuredVideoEntries,
-      },
-    ])
-    const operations = await inputParser.getEntityBatchOperations()
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'transaction', [actor, operations])
-  }
-}

+ 0 - 98
cli/src/commands/media/updateChannel.ts

@@ -1,98 +0,0 @@
-import ContentDirectoryCommandBase from '../../base/ContentDirectoryCommandBase'
-import ChannelEntitySchema from '@joystream/cd-schemas/schemas/entities/ChannelEntity.schema.json'
-import { ChannelEntity } from '@joystream/cd-schemas/types/entities/ChannelEntity'
-import { InputParser } from '@joystream/cd-schemas'
-import { IOFlags, getInputJson, saveOutputJson } from '../../helpers/InputOutput'
-import { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-import { JsonSchemaCustomPrompts, JsonSchemaPrompter } from '../../helpers/JsonSchemaPrompt'
-import { Actor, Entity } from '@joystream/types/content-directory'
-import { flags } from '@oclif/command'
-import { createType } from '@joystream/types'
-import _ from 'lodash'
-
-export default class UpdateChannelCommand extends ContentDirectoryCommandBase {
-  static description = 'Update one of the owned channels on Joystream (requires a membership).'
-  static flags = {
-    ...IOFlags,
-    asCurator: flags.boolean({
-      description: 'Provide this flag in order to use Curator context for the update',
-      required: false,
-    }),
-  }
-
-  static args = [
-    {
-      name: 'id',
-      description: 'ID of the channel to update',
-      required: false,
-    },
-  ]
-
-  async run() {
-    const {
-      args: { id },
-      flags: { asCurator },
-    } = this.parse(UpdateChannelCommand)
-
-    const account = await this.getRequiredSelectedAccount()
-
-    let memberId: number | undefined, actor: Actor
-
-    if (asCurator) {
-      actor = await this.getCuratorContext(['Channel'])
-    } else {
-      memberId = await this.getRequiredMemberId()
-      actor = createType('Actor', { Member: memberId })
-    }
-
-    await this.requestAccountDecoding(account)
-
-    let channelEntity: Entity, channelId: number
-    if (id) {
-      channelId = parseInt(id)
-      channelEntity = await this.getEntity(channelId, 'Channel', memberId)
-    } else {
-      const [id, channel] = await this.promptForEntityEntry('Select a channel to update', 'Channel', 'handle', memberId)
-      channelId = id.toNumber()
-      channelEntity = channel
-    }
-
-    const currentValues = await this.parseToEntityJson<ChannelEntity>(channelEntity)
-    this.jsonPrettyPrint(JSON.stringify(currentValues))
-
-    const channelJsonSchema = (ChannelEntitySchema as unknown) as JSONSchema
-
-    const { input, output } = this.parse(UpdateChannelCommand).flags
-
-    let inputJson = await getInputJson<ChannelEntity>(input, channelJsonSchema)
-    if (!inputJson) {
-      const customPrompts: JsonSchemaCustomPrompts<ChannelEntity> = [
-        [
-          'language',
-          () =>
-            this.promptForEntityId('Choose channel language', 'Language', 'name', undefined, currentValues.language),
-        ],
-      ]
-
-      if (!asCurator) {
-        // Skip isCensored is it's not updated by the curator
-        customPrompts.push(['isCensored', 'skip'])
-      }
-
-      const prompter = new JsonSchemaPrompter<ChannelEntity>(channelJsonSchema, currentValues, customPrompts)
-
-      inputJson = await prompter.promptAll()
-    }
-
-    this.jsonPrettyPrint(JSON.stringify(inputJson))
-    const confirmed = await this.simplePrompt({ type: 'confirm', message: 'Do you confirm the provided input?' })
-
-    if (confirmed) {
-      saveOutputJson(output, `${_.startCase(inputJson.handle)}Channel.json`, inputJson)
-      const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi())
-      const updateOperations = await inputParser.getEntityUpdateOperations(inputJson, 'Channel', channelId)
-      this.log('Sending the extrinsic...')
-      await this.sendAndFollowNamedTx(account, 'contentDirectory', 'transaction', [actor, updateOperations])
-    }
-  }
-}

+ 0 - 106
cli/src/commands/media/updateVideo.ts

@@ -1,106 +0,0 @@
-import VideoEntitySchema from '@joystream/cd-schemas/schemas/entities/VideoEntity.schema.json'
-import { VideoEntity } from '@joystream/cd-schemas/types/entities/VideoEntity'
-import { InputParser } from '@joystream/cd-schemas'
-import { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-import { JsonSchemaCustomPrompts, JsonSchemaPrompter } from '../../helpers/JsonSchemaPrompt'
-import { Actor, Entity } from '@joystream/types/content-directory'
-import { createType } from '@joystream/types'
-import { flags } from '@oclif/command'
-import MediaCommandBase from '../../base/MediaCommandBase'
-
-export default class UpdateVideoCommand extends MediaCommandBase {
-  static description = 'Update existing video information (requires controller/maintainer access).'
-  static flags = {
-    // TODO: ...IOFlags, - providing input as json
-    asCurator: flags.boolean({
-      description: 'Specify in order to update the video as curator',
-      required: false,
-    }),
-  }
-
-  static args = [
-    {
-      name: 'id',
-      description: 'ID of the Video to update',
-      required: false,
-    },
-  ]
-
-  async run() {
-    const {
-      args: { id },
-      flags: { asCurator },
-    } = this.parse(UpdateVideoCommand)
-
-    const account = await this.getRequiredSelectedAccount()
-
-    let memberId: number | undefined, actor: Actor
-
-    if (asCurator) {
-      actor = await this.getCuratorContext(['Video'])
-    } else {
-      memberId = await this.getRequiredMemberId()
-      actor = createType('Actor', { Member: memberId })
-    }
-
-    await this.requestAccountDecoding(account)
-
-    let videoEntity: Entity, videoId: number
-    if (id) {
-      videoId = parseInt(id)
-      videoEntity = await this.getEntity(videoId, 'Video', memberId)
-    } else {
-      const [id, video] = await this.promptForEntityEntry('Select a video to update', 'Video', 'title', memberId)
-      videoId = id.toNumber()
-      videoEntity = video
-    }
-
-    const currentValues = await this.parseToEntityJson<VideoEntity>(videoEntity)
-    const videoJsonSchema = (VideoEntitySchema as unknown) as JSONSchema
-
-    const {
-      language: currLanguageId,
-      category: currCategoryId,
-      publishedBeforeJoystream: currPublishedBeforeJoystream,
-    } = currentValues
-
-    const customizedPrompts: JsonSchemaCustomPrompts<VideoEntity> = [
-      [
-        'language',
-        () => this.promptForEntityId('Choose Video language', 'Language', 'name', undefined, currLanguageId),
-      ],
-      [
-        'category',
-        () => this.promptForEntityId('Choose Video category', 'ContentCategory', 'name', undefined, currCategoryId),
-      ],
-      ['publishedBeforeJoystream', () => this.promptForPublishedBeforeJoystream(currPublishedBeforeJoystream)],
-    ]
-    const videoPrompter = new JsonSchemaPrompter<VideoEntity>(videoJsonSchema, currentValues, customizedPrompts)
-
-    // Prompt for other video data
-    const updatedProps: Partial<VideoEntity> = await videoPrompter.promptMultipleProps([
-      'language',
-      'category',
-      'title',
-      'description',
-      'thumbnailUrl',
-      'duration',
-      'isPublic',
-      'isExplicit',
-      'hasMarketing',
-      'publishedBeforeJoystream',
-      'skippableIntroDuration',
-    ])
-
-    if (asCurator) {
-      updatedProps.isCensored = await videoPrompter.promptSingleProp('isCensored')
-    }
-
-    this.jsonPrettyPrint(JSON.stringify(updatedProps))
-
-    // Parse inputs into operations and send final extrinsic
-    const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi())
-    const videoUpdateOperations = await inputParser.getEntityUpdateOperations(updatedProps, 'Video', videoId)
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'transaction', [actor, videoUpdateOperations], true)
-  }
-}

+ 0 - 59
cli/src/commands/media/updateVideoLicense.ts

@@ -1,59 +0,0 @@
-import MediaCommandBase from '../../base/MediaCommandBase'
-import { LicenseEntity, VideoEntity } from '@joystream/cd-schemas/types/entities'
-import { InputParser } from '@joystream/cd-schemas'
-import { Entity } from '@joystream/types/content-directory'
-import { createType } from '@joystream/types'
-
-export default class UpdateVideoLicenseCommand extends MediaCommandBase {
-  static description = 'Update existing video license (requires controller/maintainer access).'
-  // TODO: ...IOFlags, - providing input as json
-
-  static args = [
-    {
-      name: 'id',
-      description: 'ID of the Video',
-      required: false,
-    },
-  ]
-
-  async run() {
-    const {
-      args: { id },
-    } = this.parse(UpdateVideoLicenseCommand)
-
-    const account = await this.getRequiredSelectedAccount()
-    const memberId = await this.getRequiredMemberId()
-    const actor = createType('Actor', { Member: memberId })
-
-    await this.requestAccountDecoding(account)
-
-    let videoEntity: Entity, videoId: number
-    if (id) {
-      videoId = parseInt(id)
-      videoEntity = await this.getEntity(videoId, 'Video', memberId)
-    } else {
-      const [id, video] = await this.promptForEntityEntry('Select a video to update', 'Video', 'title', memberId)
-      videoId = id.toNumber()
-      videoEntity = video
-    }
-
-    const video = await this.parseToEntityJson<VideoEntity>(videoEntity)
-    const currentLicense = await this.getAndParseKnownEntity<LicenseEntity>(video.license)
-
-    this.log('Current license:', currentLicense)
-
-    const updateInput: Partial<VideoEntity> = {
-      license: await this.promptForNewLicense(),
-    }
-
-    const api = this.getOriginalApi()
-    const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi())
-    const videoUpdateOperations = await inputParser.getEntityUpdateOperations(updateInput, 'Video', videoId)
-
-    this.log('Setting new license...')
-    await this.sendAndFollowTx(account, api.tx.contentDirectory.transaction(actor, videoUpdateOperations), true)
-
-    this.log(`Removing old License entity (ID: ${video.license})...`)
-    await this.sendAndFollowTx(account, api.tx.contentDirectory.removeEntity(actor, video.license))
-  }
-}

+ 0 - 384
cli/src/commands/media/uploadVideo.ts

@@ -1,384 +0,0 @@
-import VideoEntitySchema from '@joystream/cd-schemas/schemas/entities/VideoEntity.schema.json'
-import VideoMediaEntitySchema from '@joystream/cd-schemas/schemas/entities/VideoMediaEntity.schema.json'
-import { VideoEntity } from '@joystream/cd-schemas/types/entities/VideoEntity'
-import { VideoMediaEntity } from '@joystream/cd-schemas/types/entities/VideoMediaEntity'
-import { InputParser } from '@joystream/cd-schemas'
-import { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-import { JsonSchemaPrompter } from '../../helpers/JsonSchemaPrompt'
-import { flags } from '@oclif/command'
-import fs from 'fs'
-import ExitCodes from '../../ExitCodes'
-import { ContentId } from '@joystream/types/storage'
-import ipfsHash from 'ipfs-only-hash'
-import { cli } from 'cli-ux'
-import axios, { AxiosRequestConfig } from 'axios'
-import { URL } from 'url'
-import ipfsHttpClient from 'ipfs-http-client'
-import first from 'it-first'
-import last from 'it-last'
-import toBuffer from 'it-to-buffer'
-import ffprobeInstaller from '@ffprobe-installer/ffprobe'
-import ffmpeg from 'fluent-ffmpeg'
-import MediaCommandBase from '../../base/MediaCommandBase'
-import { getInputJson, validateInput, IOFlags } from '../../helpers/InputOutput'
-
-ffmpeg.setFfprobePath(ffprobeInstaller.path)
-
-const DATA_OBJECT_TYPE_ID = 1
-const MAX_FILE_SIZE = 2000 * 1024 * 1024
-
-type VideoMetadata = {
-  width?: number
-  height?: number
-  codecName?: string
-  codecFullName?: string
-  duration?: number
-}
-
-export default class UploadVideoCommand extends MediaCommandBase {
-  static description = 'Upload a new Video to a channel (requires a membership).'
-  static flags = {
-    input: IOFlags.input,
-    channel: flags.integer({
-      char: 'c',
-      required: false,
-      description:
-        'ID of the channel to assign the video to (if omitted - one of the owned channels can be selected from the list)',
-    }),
-    confirm: flags.boolean({ char: 'y', name: 'confirm', required: false, description: 'Confirm the provided input' }),
-  }
-
-  static args = [
-    {
-      name: 'filePath',
-      required: true,
-      description: 'Path to the media file to upload',
-    },
-  ]
-
-  private createReadStreamWithProgressBar(filePath: string, barTitle: string, fileSize?: number) {
-    // Progress CLI UX:
-    // https://github.com/oclif/cli-ux#cliprogress
-    // https://www.npmjs.com/package/cli-progress
-    if (!fileSize) {
-      fileSize = fs.statSync(filePath).size
-    }
-    const progress = cli.progress({ format: `${barTitle} | {bar} | {value}/{total} KB processed` })
-    let processedKB = 0
-    const fileSizeKB = Math.ceil(fileSize / 1024)
-    progress.start(fileSizeKB, processedKB)
-    return {
-      fileStream: fs
-        .createReadStream(filePath)
-        .pause() // Explicitly pause to prevent switching to flowing mode (https://nodejs.org/api/stream.html#stream_event_data)
-        .on('error', () => {
-          progress.stop()
-          this.error(`Error while trying to read data from: ${filePath}!`, {
-            exit: ExitCodes.FsOperationFailed,
-          })
-        })
-        .on('data', (data) => {
-          processedKB += data.length / 1024
-          progress.update(processedKB)
-        })
-        .on('end', () => {
-          progress.update(fileSizeKB)
-          progress.stop()
-        }),
-      progressBar: progress,
-    }
-  }
-
-  private async calculateFileIpfsHash(filePath: string, fileSize: number): Promise<string> {
-    const { fileStream } = this.createReadStreamWithProgressBar(filePath, 'Calculating file hash', fileSize)
-    const hash: string = await ipfsHash.of(fileStream)
-
-    return hash
-  }
-
-  private async getUploadUrl(storageProviderId: number, contentId: ContentId): Promise<string> {
-    const endpoint = await this.getApi().storageProviderEndpoint(storageProviderId)
-    return new URL(`asset/v0/${contentId.encode()}`, endpoint).toString()
-  }
-
-  private async getVideoMetadata(filePath: string): Promise<VideoMetadata | null> {
-    let metadata: VideoMetadata | null = null
-    const metadataPromise = new Promise<VideoMetadata>((resolve, reject) => {
-      ffmpeg.ffprobe(filePath, (err, data) => {
-        if (err) {
-          reject(err)
-          return
-        }
-        const videoStream = data.streams.find((s) => s.codec_type === 'video')
-        if (videoStream) {
-          resolve({
-            width: videoStream.width,
-            height: videoStream.height,
-            codecName: videoStream.codec_name,
-            codecFullName: videoStream.codec_long_name,
-            duration: videoStream.duration !== undefined ? Math.ceil(Number(videoStream.duration)) || 0 : undefined,
-          })
-        } else {
-          reject(new Error('No video stream found in file'))
-        }
-      })
-    })
-
-    try {
-      metadata = await metadataPromise
-    } catch (e) {
-      const message = e.message || e
-      this.warn(`Failed to get video metadata via ffprobe (${message})`)
-    }
-
-    return metadata
-  }
-
-  private async uploadVideo(filePath: string, fileSize: number, uploadUrl: string) {
-    const { fileStream, progressBar } = this.createReadStreamWithProgressBar(filePath, 'Uploading', fileSize)
-    fileStream.on('end', () => {
-      cli.action.start('Waiting for the file to be processed...')
-    })
-
-    try {
-      const config: AxiosRequestConfig = {
-        headers: {
-          'Content-Type': '', // https://github.com/Joystream/storage-node-joystream/issues/16
-          'Content-Length': fileSize.toString(),
-        },
-        maxContentLength: MAX_FILE_SIZE,
-        maxBodyLength: MAX_FILE_SIZE,
-      }
-      await axios.put(uploadUrl, fileStream, config)
-      cli.action.stop()
-
-      this.log('File uploaded!')
-    } catch (e) {
-      progressBar.stop()
-      cli.action.stop()
-      const msg = (e.response && e.response.data && e.response.data.message) || e.message || e
-      this.error(`Unexpected error when trying to upload a file: ${msg}`, {
-        exit: ExitCodes.ExternalInfrastructureError,
-      })
-    }
-  }
-
-  private async promptForVideoInput(
-    channelId: number,
-    fileSize: number,
-    contentId: ContentId,
-    videoMetadata: VideoMetadata | null
-  ) {
-    // Set the defaults
-    const videoMediaDefaults: Partial<VideoMediaEntity> = {
-      pixelWidth: videoMetadata?.width,
-      pixelHeight: videoMetadata?.height,
-    }
-    const videoDefaults: Partial<VideoEntity> = {
-      duration: videoMetadata?.duration,
-      skippableIntroDuration: 0,
-    }
-
-    // Prompt for data
-    const videoJsonSchema = (VideoEntitySchema as unknown) as JSONSchema
-    const videoMediaJsonSchema = (VideoMediaEntitySchema as unknown) as JSONSchema
-
-    const videoMediaPrompter = new JsonSchemaPrompter<VideoMediaEntity>(videoMediaJsonSchema, videoMediaDefaults)
-    const videoPrompter = new JsonSchemaPrompter<VideoEntity>(videoJsonSchema, videoDefaults)
-
-    // Prompt for the data
-    const encodingSuggestion =
-      videoMetadata && videoMetadata.codecFullName ? ` (suggested: ${videoMetadata.codecFullName})` : ''
-    const encoding = await this.promptForEntityId(
-      `Choose Video encoding${encodingSuggestion}`,
-      'VideoMediaEncoding',
-      'name'
-    )
-    const { pixelWidth, pixelHeight } = await videoMediaPrompter.promptMultipleProps(['pixelWidth', 'pixelHeight'])
-    const language = await this.promptForEntityId('Choose Video language', 'Language', 'name')
-    const category = await this.promptForEntityId('Choose Video category', 'ContentCategory', 'name')
-    const videoProps = await videoPrompter.promptMultipleProps([
-      'title',
-      'description',
-      'thumbnailUrl',
-      'duration',
-      'isPublic',
-      'isExplicit',
-      'hasMarketing',
-      'skippableIntroDuration',
-    ])
-
-    const license = await videoPrompter.promptSingleProp('license', () => this.promptForNewLicense())
-    const publishedBeforeJoystream = await videoPrompter.promptSingleProp('publishedBeforeJoystream', () =>
-      this.promptForPublishedBeforeJoystream()
-    )
-
-    // Create final inputs
-    const videoMediaInput: VideoMediaEntity = {
-      encoding,
-      pixelWidth,
-      pixelHeight,
-      size: fileSize,
-      location: { new: { joystreamMediaLocation: { new: { dataObjectId: contentId.encode() } } } },
-    }
-    return {
-      ...videoProps,
-      channel: channelId,
-      language,
-      category,
-      license,
-      media: { new: videoMediaInput },
-      publishedBeforeJoystream,
-    }
-  }
-
-  private async getVideoInputFromFile(
-    filePath: string,
-    channelId: number,
-    fileSize: number,
-    contentId: ContentId,
-    videoMetadata: VideoMetadata | null
-  ) {
-    let videoInput = await getInputJson<any>(filePath)
-    if (typeof videoInput !== 'object' || videoInput === null) {
-      this.error('Invalid input json - expected an object', { exit: ExitCodes.InvalidInput })
-    }
-    const videoMediaDefaults: Partial<VideoMediaEntity> = {
-      pixelWidth: videoMetadata?.width,
-      pixelHeight: videoMetadata?.height,
-      size: fileSize,
-    }
-    const videoDefaults: Partial<VideoEntity> = {
-      channel: channelId,
-      duration: videoMetadata?.duration,
-    }
-    const inputVideoMedia =
-      videoInput.media && typeof videoInput.media === 'object' && (videoInput.media as any).new
-        ? (videoInput.media as any).new
-        : {}
-    videoInput = {
-      ...videoDefaults,
-      ...videoInput,
-      media: {
-        new: {
-          ...videoMediaDefaults,
-          ...inputVideoMedia,
-          location: { new: { joystreamMediaLocation: { new: { dataObjectId: contentId.encode() } } } },
-        },
-      },
-    }
-
-    const videoJsonSchema = (VideoEntitySchema as unknown) as JSONSchema
-    await validateInput(videoInput, videoJsonSchema)
-
-    return videoInput as VideoEntity
-  }
-
-  async run() {
-    const account = await this.getRequiredSelectedAccount()
-    const memberId = await this.getRequiredMemberId()
-    const actor = { Member: memberId }
-
-    await this.requestAccountDecoding(account)
-
-    const {
-      args: { filePath },
-      flags: { channel: inputChannelId, input, confirm },
-    } = this.parse(UploadVideoCommand)
-
-    // Basic file validation
-    if (!fs.existsSync(filePath)) {
-      this.error('File does not exist under provided path!', { exit: ExitCodes.FileNotFound })
-    }
-
-    const { size: fileSize } = fs.statSync(filePath)
-    if (fileSize > MAX_FILE_SIZE) {
-      this.error(`File size too large! Max. file size is: ${(MAX_FILE_SIZE / 1024 / 1024).toFixed(2)} MB`)
-    }
-
-    const videoMetadata = await this.getVideoMetadata(filePath)
-    this.log('Video media file parameters established:', { ...(videoMetadata || {}), size: fileSize })
-
-    // Check if any providers are available
-    if (!(await this.getApi().isAnyProviderAvailable())) {
-      this.error('No active storage providers available! Try again later...', {
-        exit: ExitCodes.ActionCurrentlyUnavailable,
-      })
-    }
-
-    // Start by prompting for a channel to make sure user has one available
-    let channelId: number
-    if (inputChannelId === undefined) {
-      channelId = await this.promptForEntityId(
-        'Select a channel to publish the video under',
-        'Channel',
-        'handle',
-        memberId
-      )
-    } else {
-      await this.getEntity(inputChannelId, 'Channel', memberId) // Validates if exists and belongs to member
-      channelId = inputChannelId
-    }
-
-    // Calculate hash and create content id
-    const contentId = ContentId.generate(this.getTypesRegistry())
-    const ipfsCid = await this.calculateFileIpfsHash(filePath, fileSize)
-
-    this.log('Video identification established:', {
-      contentId: contentId.toString(),
-      encodedContentId: contentId.encode(),
-      ipfsHash: ipfsCid,
-    })
-
-    // Send dataDirectory.addContent extrinsic
-    await this.sendAndFollowNamedTx(account, 'dataDirectory', 'addContent', [
-      memberId,
-      contentId,
-      DATA_OBJECT_TYPE_ID,
-      fileSize,
-      ipfsCid,
-    ])
-
-    const dataObject = await this.getApi().dataByContentId(contentId)
-    if (!dataObject) {
-      this.error('Data object could not be retrieved from chain', { exit: ExitCodes.ApiError })
-    }
-
-    this.log('Data object:', dataObject.toJSON())
-
-    // Get storage provider identity
-    const storageProviderId = dataObject.liaison.toNumber()
-    const ipnsIdentity = await this.getApi().ipnsIdentity(storageProviderId)
-
-    if (!ipnsIdentity) {
-      this.error('Storage provider IPNS identity could not be determined', { exit: ExitCodes.ApiError })
-    }
-
-    // Resolve upload url and upload the video
-    const uploadUrl = await this.getUploadUrl(storageProviderId, contentId)
-    this.log('Resolved upload url:', uploadUrl)
-
-    await this.uploadVideo(filePath, fileSize, uploadUrl)
-
-    // No input, create prompting helpers
-    const videoInput = input
-      ? await this.getVideoInputFromFile(input, channelId, fileSize, contentId, videoMetadata)
-      : await this.promptForVideoInput(channelId, fileSize, contentId, videoMetadata)
-
-    this.jsonPrettyPrint(JSON.stringify(videoInput))
-
-    if (!confirm) {
-      await this.requireConfirmation('Do you confirm the provided input?', true)
-    }
-
-    // Parse inputs into operations and send final extrinsic
-    const inputParser = InputParser.createWithKnownSchemas(this.getOriginalApi(), [
-      {
-        className: 'Video',
-        entries: [videoInput],
-      },
-    ])
-    const operations = await inputParser.getEntityBatchOperations()
-    await this.sendAndFollowNamedTx(account, 'contentDirectory', 'transaction', [actor, operations])
-  }
-}

+ 12 - 34
cli/src/helpers/InputOutput.ts

@@ -3,14 +3,8 @@ import { CLIError } from '@oclif/errors'
 import ExitCodes from '../ExitCodes'
 import fs from 'fs'
 import path from 'path'
-import Ajv from 'ajv'
-import $RefParser, { JSONSchema } from '@apidevtools/json-schema-ref-parser'
-import { getSchemasLocation } from '@joystream/cd-schemas'
 import chalk from 'chalk'
 
-// Default schema path for resolving refs
-const DEFAULT_SCHEMA_PATH = getSchemasLocation('entities') + path.sep
-
 export const IOFlags = {
   input: flags.string({
     char: 'i',
@@ -25,36 +19,20 @@ export const IOFlags = {
   }),
 }
 
-export async function getInputJson<T>(inputPath?: string, schema?: JSONSchema, schemaPath?: string): Promise<T | null> {
-  if (inputPath) {
-    let content, jsonObj
-    try {
-      content = fs.readFileSync(inputPath).toString()
-    } catch (e) {
-      throw new CLIError(`Cannot access the input file at: ${inputPath}`, { exit: ExitCodes.FsOperationFailed })
-    }
-    try {
-      jsonObj = JSON.parse(content)
-    } catch (e) {
-      throw new CLIError(`JSON parsing failed for file: ${inputPath}`, { exit: ExitCodes.InvalidInput })
-    }
-    if (schema) {
-      await validateInput(jsonObj, schema, schemaPath)
-    }
-
-    return jsonObj as T
+export async function getInputJson<T>(inputPath: string): Promise<T> {
+  let content, jsonObj
+  try {
+    content = fs.readFileSync(inputPath).toString()
+  } catch (e) {
+    throw new CLIError(`Cannot access the input file at: ${inputPath}`, { exit: ExitCodes.FsOperationFailed })
   }
-
-  return null
-}
-
-export async function validateInput(input: unknown, schema: JSONSchema, schemaPath?: string): Promise<void> {
-  const ajv = new Ajv({ allErrors: true })
-  schema = await $RefParser.dereference(schemaPath || DEFAULT_SCHEMA_PATH, schema, {})
-  const valid = ajv.validate(schema, input) as boolean
-  if (!valid) {
-    throw new CLIError(`Input JSON file is not valid: ${ajv.errorsText()}`)
+  try {
+    jsonObj = JSON.parse(content)
+  } catch (e) {
+    throw new CLIError(`JSON parsing failed for file: ${inputPath}`, { exit: ExitCodes.InvalidInput })
   }
+
+  return jsonObj as T
 }
 
 export function saveOutputJson(outputPath: string | undefined, fileName: string, data: any): void {

+ 1 - 7
cli/src/helpers/JsonSchemaPrompt.ts

@@ -4,8 +4,6 @@ import _ from 'lodash'
 import RefParser, { JSONSchema } from '@apidevtools/json-schema-ref-parser'
 import chalk from 'chalk'
 import { BOOL_PROMPT_OPTIONS } from './prompting'
-import { getSchemasLocation } from '@joystream/cd-schemas'
-import path from 'path'
 
 type CustomPromptMethod = () => Promise<any>
 type CustomPrompt = DistinctQuestion | CustomPromptMethod | { $item: CustomPrompt } | 'skip'
@@ -14,10 +12,6 @@ type CustomPrompt = DistinctQuestion | CustomPromptMethod | { $item: CustomPromp
 // eslint-disable-next-line @typescript-eslint/ban-types
 export type JsonSchemaCustomPrompts<T = Record<string, unknown>> = [keyof T | (string & {}) | RegExp, CustomPrompt][]
 
-// Default schema path for resolving refs
-// TODO: Would be nice to skip the filename part (but without it it doesn't work)
-const DEFAULT_SCHEMA_PATH = getSchemasLocation('entities') + path.sep
-
 export class JsonSchemaPrompter<JsonResult> {
   schema: JSONSchema
   schemaPath: string
@@ -29,7 +23,7 @@ export class JsonSchemaPrompter<JsonResult> {
     schema: JSONSchema,
     defaults?: Partial<JsonResult>,
     customPrompts?: JsonSchemaCustomPrompts,
-    schemaPath: string = DEFAULT_SCHEMA_PATH
+    schemaPath = ''
   ) {
     this.customPropmpts = customPrompts
     this.schema = schema

+ 1 - 1
content-metadata-protobuf/src/index.ts

@@ -7,4 +7,4 @@ export * from '../compiled/proto/Video_pb'
 export * from '../compiled/proto/Channel_pb'
 export * from '../compiled/proto/Person_pb'
 export * from '../compiled/proto/Playlist_pb'
-export * from '../compiled/proto/Series_pb'
+export * from '../compiled/proto/Series_pb'

+ 2 - 2
types/src/content/index.ts

@@ -168,7 +168,7 @@ export class PersonActor extends JoyEnum({
   Curator: CuratorId,
 }) {}
 
-export const contentDirectoryTypes = {
+export const contentTypes = {
   CuratorId,
   CuratorGroupId,
   CuratorGroup,
@@ -211,4 +211,4 @@ export const contentDirectoryTypes = {
   MaxNumber,
 }
 
-export default contentDirectoryTypes
+export default contentTypes

+ 3 - 3
types/src/index.ts

@@ -11,7 +11,7 @@ import hiring from './hiring'
 import workingGroup from './working-group'
 import storage from './storage'
 import proposals from './proposals'
-import contentDirectory from './content'
+import content from './content'
 import legacy from './legacy'
 import { InterfaceTypes } from '@polkadot/types/types/registry'
 import { TypeRegistry, Text, UInt, Null, bool, Option, Vec, BTreeSet, BTreeMap } from '@polkadot/types'
@@ -32,7 +32,7 @@ export {
   workingGroup,
   storage,
   proposals,
-  contentDirectory,
+  content,
 }
 
 export const types: RegistryTypes = {
@@ -50,7 +50,7 @@ export const types: RegistryTypes = {
   ...workingGroup,
   ...storage,
   ...proposals,
-  ...contentDirectory,
+  ...content,
 }
 
 // Allows creating types without api instance (it's not a recommended way though, so should be used just for mocks)

+ 2 - 2
types/src/scripts/generateAugmentCodec.ts

@@ -20,7 +20,7 @@ import hiring from '../hiring'
 import workingGroup from '../working-group'
 import storage from '../storage'
 import proposals from '../proposals'
-import contentDirectory from '../content'
+import content from '../content'
 import legacy from '../legacy'
 
 const AUGMENT_INTERFACES_PATH = path.join(__dirname, '../../augment')
@@ -42,7 +42,7 @@ const typesByModule = {
   'working-group': workingGroup,
   'storage': storage,
   'proposals': proposals,
-  'content': contentDirectory,
+  'content': content,
 }
 
 type Imports = { [moduleName: string]: string[] }

+ 1 - 1
yarn.lock

@@ -30214,4 +30214,4 @@ zen-observable@^0.8.0, zen-observable@^0.8.14:
 zepto@^1.2.0:
   version "1.2.0"
   resolved "https://registry.yarnpkg.com/zepto/-/zepto-1.2.0.tgz#e127bd9e66fd846be5eab48c1394882f7c0e4f98"
-  integrity sha1-4Se9nmb9hGvl6rSME5SIL3wOT5g=
+  integrity sha1-4Se9nmb9hGvl6rSME5SIL3wOT5g=