p2p-database-gun.ts 1.5 KB

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