import { Injectable } from "@angular/core"; import Gun from "gun/gun"; import "gun/lib/then"; @Injectable() export class P2pDatabaseGunProvider { private gun; osnPrefix: string = "hybridOSN-beta003"; constructor() { this.gun = Gun(["https://hybrid-osn.herokuapp.com/gun"]); } public storeLastTweetHashForUser(userId, hash, timestamp): void { const tweet = this.gun .get(timestamp) .put({ hash: hash, created_at: timestamp }); this.gun .get(this.osnPrefix + "-" + userId) .get("tweets") .set(tweet); } /** * Hashtags are stored without reference to the users to provide these information on an extra dashboard to twitter * @param hashtagEntity extracted hashtags */ public publishHashtags(hashtagEntity): void { const timestamp = new Date().setHours(0, 0, 1, 0); const hashtagsCommaSeparated = hashtagEntity .map(el => el.hashtag) .sort() .join("|"); const hashtags = this.gun.get(timestamp).put({ hashtags: hashtagsCommaSeparated, created_at: timestamp }); this.gun.get(this.osnPrefix + "/hashtags").set(hashtags); } public async getLastTweetFromUser(userId) { return new Promise(resolve => this.gun .get(this.osnPrefix + userId) .get("tweets") .once(resolve) ); } public async fetchPrivateTweetHashsForUserInInterval( userId, intervalStart, intervalEnd ): Promise { const gunIds = await this.gun .get(this.osnPrefix + "-" + userId) .get("tweets") .then(); if (gunIds) { const entries = await Promise.all( Object.keys(gunIds) .filter(key => key !== "_") .map(key => this.gun.get(key).then()) ); return entries.filter( entry => new Date(entry["created_at"]) < intervalStart && new Date(entry["created_at"]) >= intervalEnd ); } else { return []; } } public async addLike(id: string) { const likeEntry = await this.getLikes(id); const hashtags = this.gun.get(id).put({ likes: likeEntry.likes + 1 }); this.gun.get(this.osnPrefix + "/likes").set(hashtags); } public async getLikes(id: string) { const likeEntry = await this.gun.get(this.osnPrefix + "/likes").get(id); if (likeEntry === undefined) { return { likes: 0 }; } else { return likeEntry; } } }