addDirectory method

Future<String> addDirectory(
  1. Map<String, dynamic> directoryContent
)

Adds a directory to IPFS and returns its CID.

Implementation

Future<String> addDirectory(Map<String, dynamic> directoryContent) async {
  // Create a new directory node
  // Note: Standard UnixFS directories don't store their own name/path internally
  final directoryManager = IPFSDirectoryManager();

  // Process each entry in the directory content
  for (final entry in directoryContent.entries) {
    if (entry.value is Uint8List) {
      // Handle file
      final cid = await addFile(entry.value as Uint8List);
      directoryManager.addEntry(
        IPFSDirectoryEntry(
          name: entry.key,
          hash: CID
              .decode(cid)
              .multihash
              .toBytes(), // Decode CID to multihash bytes for the link
          size: fixnum.Int64((entry.value as Uint8List).length),
          isDirectory: false,
        ),
      );
    } else if (entry.value is Map) {
      // Handle subdirectory recursively
      final subDirCid = await addDirectory(
        entry.value as Map<String, dynamic>,
      );
      directoryManager.addEntry(
        IPFSDirectoryEntry(
          name: entry.key,
          hash: CID.decode(subDirCid).multihash.toBytes(),
          size: fixnum.Int64(
            0,
          ), // Tsize should ideally be known, but 0 is acceptable if unknown for now
          isDirectory: true,
        ),
      );
    }
  }

  // Create a block from the directory data
  final pbNode = directoryManager.build();
  final block = await Block.fromData(
    pbNode.writeToBuffer(),
    format: 'dag-pb',
  );

  // Store the directory block
  await _container.get<DatastoreHandler>().putBlock(block);

  // Return the CID of the directory
  return block.cid.toString();
}