Skip to content
Snippets Groups Projects
Select Git revision
  • main default protected
1 result

cesium-plus.ts

Blame
  • cesium-plus.ts 2.42 KiB
    import { CID } from 'multiformats'
    import { kubo } from './kubo'
    import { Buffer } from 'buffer'
    import { timestampToKey, arrayToVinode, mergeInodesSyncCID } from './processor'
    import { CESIUM_PLUS_PROFILE_IMPORT } from './consts'
    import type { CplusProfile, Avatar, IndexRequest } from './types'
    
    // ========================= import functions
    
    // UNUSED
    /// upload cesium plus profile as dag instead of raw json
    // if avatar is present, upload it as a separate file instead
    async function processCesiumPlusProfile(obj: CplusProfile): Promise<CID> {
      const { avatar, ...profileWithoutAvatar } = obj
      if (avatar != undefined && (avatar as Avatar)._content != undefined) {
        const buffer = Buffer.from((avatar as Avatar)._content, 'base64')
        const fileCandidate = { content: new Uint8Array(buffer) }
        return kubo
          .add(fileCandidate)
          .then((result) => kubo.dag.put({ ...profileWithoutAvatar, avatar: result.cid as CID }) as Promise<CID>)
      } else {
        return kubo.dag.put(obj) as Promise<CID>
      }
    }
    
    // ========================= merge functions
    
    /// wrap cplus raw document in index request
    export async function wrapCplusInIndexRequest(
      cplus: CplusProfile,
      cplusRaw: string,
      convertImg: boolean
    ): Promise<CID> {
      // process avatar separately if requested
      const avatar = cplus.avatar as Avatar
      if (convertImg && avatar != undefined && avatar._content != undefined) {
        const buffer = Buffer.from(avatar._content, 'base64')
        const fileCandidate = { content: new Uint8Array(buffer) }
        kubo.add(fileCandidate)
      }
      // return index request CID
      return kubo
        .add(cplusRaw)
        .then((cid) => ({
          pubkey: cplus.issuer,
          kind: CESIUM_PLUS_PROFILE_IMPORT,
          data: cid.cid,
          time: cplus.time * 1000,
          sig: null
        }))
        .then((ir) => kubo.dag.put(ir))
    }
    
    /// import sorted cplus index requests to AMT
    export async function indexRequestsToAMT(requests: Array<[string, CID]>, rootNodeCid: CID) {
      const chunkSize = 5000
      const n = requests.length
      console.log(Date.now() + ' merging')
      for (let i = 0; i < Math.ceil(n / chunkSize); i++) {
        console.log(Date.now() + ' chunk number ' + i)
        const chunk = requests.slice(i * chunkSize, (i + 1) * chunkSize)
        const tree = arrayToVinode('', chunk) // partial tree for this chunk
        const mergeResult = await mergeInodesSyncCID(rootNodeCid, tree)
        rootNodeCid = mergeResult[1]
        console.log(`new root node ${rootNodeCid} with ${mergeResult[0]} items`)
      }
    }