All files / app/core/services/ipfs ipfs-storage.service.ts

95.16% Statements 59/62
100% Branches 6/6
100% Functions 13/13
95.16% Lines 59/62

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181                  1x         1x     33x 33x           33x   33x 33x 33x       3x   3x     3x     1x 1x 1x   1x   2x   2x         3x   3x 1x       2x 2x 1x     1x     1x   1x   1x 1x           3x 1x       2x         1x     1x 1x 1x 1x 1x           1x 1x     1x       33x 33x 21x           33x         2x         2x 2x             9x             2x 2x                   3x 3x 1x     2x             2x 2x 1x     1x             1x    
import { Injectable, Inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { IStorageProvider } from '../../domain/interfaces/storage.interface';
import { IPFSConfig } from '../../domain/interfaces/ipfs.interface';
import { IPFSClient } from './ipfs-client.service';
import { IndexedDbStorageService } from '../indexed-db-storage.service';
import { IPFSShareLinkService } from './ipfs-share-link.service';
 
export const IPFS_CONFIG = 'IPFS_CONFIG';
 
@Injectable({
  providedIn: 'root'
})
export class IPFSStorageService implements IStorageProvider {
  private ipfsClient: IPFSClient;
  private localCache: IndexedDbStorageService;
  private cidToPathMap = new Map<string, string>();
  private pathToCidMap = new Map<string, string>();
 
  constructor(
    @Inject(IPFS_CONFIG) config: IPFSConfig,
    http: HttpClient,
    localCache: IndexedDbStorageService,
    private shareLinkService: IPFSShareLinkService
  ) {
    this.ipfsClient = new IPFSClient(http, config);
    this.localCache = localCache;
    this.loadCidMappings();
  }
 
  async write(path: string, data: Uint8Array): Promise<void> {
    try {
      // Write to local cache first for immediate availability
      await this.localCache.write(path, data);
 
      // Upload to IPFS
      const result = await firstValueFrom(this.ipfsClient.add(data));
      
      // Store CID mapping
      this.cidToPathMap.set(result.cid, path);
      this.pathToCidMap.set(path, result.cid);
      await this.saveCidMappings();
 
      console.log(`Stored ${path} with CID: ${result.cid}`);
    } catch (error) {
      console.error('Failed to write to IPFS:', error);
      // Local cache still has the data, so operation is partially successful
      throw error;
    }
  }
 
  async read(path: string): Promise<Uint8Array> {
    try {
      // Try local cache first
      if (await this.localCache.exists(path)) {
        return await this.localCache.read(path);
      }
 
      // If not in cache, try IPFS
      const cid = this.pathToCidMap.get(path);
      if (!cid) {
        throw new Error(`No CID mapping found for path: ${path}`);
      }
 
      const data = await firstValueFrom(this.ipfsClient.get(cid));
      
      // Cache locally for future reads
      await this.localCache.write(path, data);
      
      return data;
    } catch (error) {
      console.error('Failed to read from IPFS:', error);
      throw error;
    }
  }
 
  async exists(path: string): Promise<boolean> {
    // Check local cache first
    if (await this.localCache.exists(path)) {
      return true;
    }
 
    // Check if we have a CID mapping
    return this.pathToCidMap.has(path);
  }
 
  async delete(path: string): Promise<void> {
    // Delete from local cache
    await this.localCache.delete(path);
 
    // Remove CID mapping (but don't unpin from IPFS as others might use it)
    const cid = this.pathToCidMap.get(path);
    if (cid) {
      this.pathToCidMap.delete(path);
      this.cidToPathMap.delete(cid);
      await this.saveCidMappings();
    }
  }
 
  async list(): Promise<string[]> {
    // Return paths from both local cache and CID mappings
    const localPaths = await this.localCache.list();
    const ipfsPaths = Array.from(this.pathToCidMap.keys());
    
    // Combine and deduplicate
    return Array.from(new Set([...localPaths, ...ipfsPaths]));
  }
 
  private async loadCidMappings(): Promise<void> {
    try {
      const mappingsData = await this.localCache.read('_ipfs_mappings');
      const mappings = JSON.parse(new TextDecoder().decode(mappingsData));
      
      this.cidToPathMap = new Map(mappings.cidToPath);
      this.pathToCidMap = new Map(mappings.pathToCid);
    } catch (error) {
      // No mappings yet, start fresh
      console.log('No existing CID mappings found');
    }
  }
 
  private async saveCidMappings(): Promise<void> {
    const mappings = {
      cidToPath: Array.from(this.cidToPathMap.entries()),
      pathToCid: Array.from(this.pathToCidMap.entries())
    };
    
    const data = new TextEncoder().encode(JSON.stringify(mappings));
    await this.localCache.write('_ipfs_mappings', data);
  }
 
  /**
   * Get the CID for a given path
   */
  getCidForPath(path: string): string | undefined {
    return this.pathToCidMap.get(path);
  }
 
  /**
   * Check if IPFS client is healthy
   */
  async isHealthy(): Promise<boolean> {
    try {
      return await firstValueFrom(this.ipfsClient.isHealthy());
    } catch {
      return false;
    }
  }
 
  /**
   * Generate a shareable link for content
   */
  generateShareLink(path: string, filename?: string): string | null {
    const cid = this.getCidForPath(path);
    if (!cid) {
      return null;
    }
    
    return this.shareLinkService.generateShareLink(cid, { filename });
  }
 
  /**
   * Generate multiple share links for different gateways
   */
  generateMultipleShareLinks(path: string, filename?: string): string[] {
    const cid = this.getCidForPath(path);
    if (!cid) {
      return [];
    }
    
    return this.shareLinkService.generateMultipleShareLinks(cid, { filename });
  }
 
  /**
   * Get share link service for advanced operations
   */
  getShareLinkService(): IPFSShareLinkService {
    return this.shareLinkService;
  }
}