All files / app/core/services/ipfs ipfs-cid-mapping.service.ts

97.61% Statements 82/84
95.83% Branches 23/24
100% Functions 29/29
97.5% Lines 78/80

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 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240                                                  1x 29x 29x 29x   29x 29x           29x 29x     29x             39x 39x 39x   39x 39x             3x             2x 2x             2x 2x             2x 2x 1x 1x 1x               2x 2x 2x 2x 2x   2x 2x               4x   4x 4x 12x                       1x 1x 3x                 1x 4x               1x         1x             3x 3x 2x 2x 4x 3x               1x 1x               2x 2x 2x   2x 2x       29x 29x 29x 1x 1x 1x       1x 1x 1x   1x               44x 44x       44x             45x 45x   45x   68x 68x     45x 68x 68x 68x     45x    
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
 
export interface CIDMapping {
  cid: string;
  path: string;
  hash: string;
  timestamp: Date;
  size?: number;
  mimeType?: string;
  pinned?: boolean;
}
 
export interface CIDMappingStats {
  totalMappings: number;
  totalSize: number;
  pinnedCount: number;
  oldestMapping?: Date;
  newestMapping?: Date;
}
 
@Injectable({
  providedIn: 'root'
})
export class IPFSCIDMappingService {
  private mappings = new Map<string, CIDMapping>();
  private mappingsByPath = new Map<string, string>(); // path -> cid
  private mappingsByHash = new Map<string, string>(); // hash -> cid
  
  private mappingsSubject = new BehaviorSubject<CIDMapping[]>([]);
  private statsSubject = new BehaviorSubject<CIDMappingStats>({
    totalMappings: 0,
    totalSize: 0,
    pinnedCount: 0
  });
 
  mappings$ = this.mappingsSubject.asObservable();
  stats$ = this.statsSubject.asObservable();
 
  constructor() {
    this.loadMappings();
  }
 
  /**
   * Add a new CID mapping
   */
  addMapping(mapping: CIDMapping): void {
    this.mappings.set(mapping.cid, mapping);
    this.mappingsByPath.set(mapping.path, mapping.cid);
    this.mappingsByHash.set(mapping.hash, mapping.cid);
    
    this.saveMappings();
    this.updateState();
  }
 
  /**
   * Get mapping by CID
   */
  getMappingByCID(cid: string): CIDMapping | undefined {
    return this.mappings.get(cid);
  }
 
  /**
   * Get mapping by path
   */
  getMappingByPath(path: string): CIDMapping | undefined {
    const cid = this.mappingsByPath.get(path);
    return cid ? this.mappings.get(cid) : undefined;
  }
 
  /**
   * Get mapping by content hash
   */
  getMappingByHash(hash: string): CIDMapping | undefined {
    const cid = this.mappingsByHash.get(hash);
    return cid ? this.mappings.get(cid) : undefined;
  }
 
  /**
   * Update mapping information
   */
  updateMapping(cid: string, updates: Partial<CIDMapping>): void {
    const mapping = this.mappings.get(cid);
    if (mapping) {
      Object.assign(mapping, updates);
      this.saveMappings();
      this.updateState();
    }
  }
 
  /**
   * Remove a mapping
   */
  removeMapping(cid: string): void {
    const mapping = this.mappings.get(cid);
    if (mapping) {
      this.mappings.delete(cid);
      this.mappingsByPath.delete(mapping.path);
      this.mappingsByHash.delete(mapping.hash);
      
      this.saveMappings();
      this.updateState();
    }
  }
 
  /**
   * Search mappings by various criteria
   */
  searchMappings(query: string): Observable<CIDMapping[]> {
    const lowerQuery = query.toLowerCase();
    
    return this.mappings$.pipe(
      map(mappings => mappings.filter(mapping => 
        mapping.cid.toLowerCase().includes(lowerQuery) ||
        mapping.path.toLowerCase().includes(lowerQuery) ||
        mapping.hash.toLowerCase().includes(lowerQuery) ||
        (mapping.mimeType && mapping.mimeType.toLowerCase().includes(lowerQuery))
      ))
    );
  }
 
  /**
   * Get mappings by date range
   */
  getMappingsByDateRange(startDate: Date, endDate: Date): Observable<CIDMapping[]> {
    return this.mappings$.pipe(
      map(mappings => mappings.filter(mapping => 
        mapping.timestamp >= startDate && mapping.timestamp <= endDate
      ))
    );
  }
 
  /**
   * Get pinned mappings
   */
  getPinnedMappings(): Observable<CIDMapping[]> {
    return this.mappings$.pipe(
      map(mappings => mappings.filter(mapping => mapping.pinned))
    );
  }
 
  /**
   * Export mappings as JSON
   */
  exportMappings(): string {
    const data = {
      version: '1.0',
      timestamp: new Date().toISOString(),
      mappings: Array.from(this.mappings.values())
    };
    return JSON.stringify(data, null, 2);
  }
 
  /**
   * Import mappings from JSON
   */
  importMappings(jsonData: string): void {
    try {
      const data = JSON.parse(jsonData);
      if (data.mappings && Array.isArray(data.mappings)) {
        data.mappings.forEach((mapping: any) => {
          if (mapping.cid && mapping.path && mapping.hash) {
            this.addMapping({
              ...mapping,
              timestamp: new Date(mapping.timestamp)
            });
          }
        });
      }
    } catch (error) {
      console.error('Failed to import mappings:', error);
      throw new Error('Invalid mapping data format');
    }
  }
 
  /**
   * Clear all mappings
   */
  clearMappings(): void {
    this.mappings.clear();
    this.mappingsByPath.clear();
    this.mappingsByHash.clear();
    
    this.saveMappings();
    this.updateState();
  }
 
  private loadMappings(): void {
    try {
      const savedData = localStorage.getItem('ipfs-cid-mappings');
      if (savedData) {
        const data = JSON.parse(savedData);
        data.mappings.forEach((mapping: any) => {
          const mappingObj: CIDMapping = {
            ...mapping,
            timestamp: new Date(mapping.timestamp)
          };
          this.mappings.set(mappingObj.cid, mappingObj);
          this.mappingsByPath.set(mappingObj.path, mappingObj.cid);
          this.mappingsByHash.set(mappingObj.hash, mappingObj.cid);
        });
        this.updateState();
      }
    } catch (error) {
      console.error('Failed to load CID mappings:', error);
    }
  }
 
  private saveMappings(): void {
    try {
      const data = {
        version: '1.0',
        mappings: Array.from(this.mappings.values())
      };
      localStorage.setItem('ipfs-cid-mappings', JSON.stringify(data));
    } catch (error) {
      console.error('Failed to save CID mappings:', error);
    }
  }
 
  private updateState(): void {
    const mappingsArray = Array.from(this.mappings.values());
    this.mappingsSubject.next(mappingsArray);
    
    const stats: CIDMappingStats = {
      totalMappings: mappingsArray.length,
      totalSize: mappingsArray.reduce((sum, m) => sum + (m.size || 0), 0),
      pinnedCount: mappingsArray.filter(m => m.pinned).length
    };
 
    if (mappingsArray.length > 0) {
      const timestamps = mappingsArray.map(m => m.timestamp);
      stats.oldestMapping = new Date(Math.min(...timestamps.map(d => d.getTime())));
      stats.newestMapping = new Date(Math.max(...timestamps.map(d => d.getTime())));
    }
 
    this.statsSubject.next(stats);
  }
}