p2p-database-gun.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { Injectable } from "@angular/core";
  2. import Gun from "gun/gun";
  3. import "gun/lib/then";
  4. import "gun/lib/load";
  5. /*
  6. Generated class for the P2pDatabaseGunProvider provider.
  7. See https://angular.io/guide/dependency-injection for more info on providers
  8. and Angular DI.
  9. */
  10. @Injectable()
  11. export class P2pDatabaseGunProvider {
  12. private gun;
  13. osnPrefix: string = "hybridOSN-";
  14. constructor() {
  15. this.gun = Gun();
  16. }
  17. public storeLastTweetHashForUser(userId, hash, timestamp): void {
  18. const tweet = this.gun
  19. .get(timestamp)
  20. .put({ hash: hash, created_at: timestamp });
  21. this.gun
  22. .get(this.osnPrefix + userId)
  23. .get("tweets")
  24. .set(tweet);
  25. }
  26. public async getLastTweetFromUser(userId) {
  27. return new Promise(resolve =>
  28. this.gun
  29. .get(this.osnPrefix + userId)
  30. .get("tweets")
  31. .once(resolve)
  32. );
  33. }
  34. public async fetchPrivateTweetHashsForUserInInterval(
  35. userId,
  36. intervalStart,
  37. intervalEnd
  38. ): Promise<string[]> {
  39. const gunIds = await this.gun
  40. .get(this.osnPrefix + userId)
  41. .get("tweets")
  42. .then();
  43. if (gunIds) {
  44. const entryPromises = [];
  45. Object.keys(gunIds)
  46. .filter(key => key !== "_")
  47. .forEach(key => entryPromises.push(this.gun.get(key).then()));
  48. const entries = await Promise.all(entryPromises);
  49. return entries
  50. .filter(
  51. entry =>
  52. new Date(entry["created_at"]) <= intervalStart &&
  53. new Date(entry["created_at"]) > intervalEnd
  54. )
  55. .map(entry => entry["hash"]);
  56. } else {
  57. return [];
  58. }
  59. }
  60. }