import IPFS from 'ipfs' ; import OrbitDB from 'orbit-db' ; import uuidv4 from 'uuid/v4' ; import Store from '../redux' ; import { ItemProperties } from 'src/components/ItemHeader' ; import { Actions } from 'src/redux/Items' ; export default class Orbit { public static instance ? : any ; public static db ? : any ; public static init ( ipfsOptions = Orbit . ipfsOptions ) { return new Promise ( ( resolve , reject ) => { Orbit . ipfs = new IPFS ( ipfsOptions ) ; Orbit . ipfs . on ( 'error' , ( e ) => reject ( e ) ) ; Orbit . ipfs . on ( 'ready' , async ( ) => { Orbit . instance = new OrbitDB ( Orbit . ipfs ) ; resolve ( ) ; } ) ; } ) ; } public static async openDB ( address ) { if ( ! Orbit . instance ) { await Orbit . init ( ) ; } if ( Orbit . db ) { Orbit . db . close ( ) ; } Orbit . db = await Orbit . instance . docs ( address , { indexBy : 'id' , write : [ '*' ] } ) ; await Orbit . db . load ( ) ; Orbit . db . events . on ( 'replicated' , ( ) => { console . log ( 'OrbitDB: Replicated' ) ; Orbit . loadOrbitToRedux ( ) ; } ) ; Orbit . loadReduxToOrbit ( ) ; Orbit . loadOrbitToRedux ( ) ; localStorage . setItem ( 'orbitDbAddress' , Orbit . db . id ) ; return Orbit . db ; } public static createDB ( ) { return Orbit . openDB ( `readhnlater-${ uuidv4 ( ) }` ) ; } public static async put ( item ) { if ( ! Orbit . db ) { return Promise . reject ( ) ; } await Orbit . db . put ( item ) ; } public static async del ( id ) { if ( ! Orbit . db ) { return Promise . reject ( ) ; } await Orbit . db . del ( id ) ; } public static getDbId ( ) { return Orbit . db ? Orbit . db . id : undefined ; } private static ipfs : any ; private static ipfsOptions = { EXPERIMENTAL : { pubsub : true } , config : { Addresses : { Swarm : [ '/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star' , ] } , } } ; private static async loadReduxToOrbit ( ) { if ( localStorage . getItem ( 'migratedToOrbit' ) ) { return ; } const items = Store . getState ( ) . items . toArray ( ) ; const promises = [ ] ; for ( const item of items ) { promises . push ( Orbit . db . put ( item ) ) ; } await Promise . all ( promises ) ; localStorage . setItem ( 'migratedToOrbit' , new Date ( ) . toUTCString ( ) ) ; console . log ( "Migration to OrbitDB completed!" ) ; } private static async loadOrbitToRedux ( ) { const items = Orbit . db . query ( ( doc ) => doc . id ) ; Store . dispatch ( { type : Actions . LOAD_SAVED_ITEMS , payload : { items } } ) ; } }