p2p-database-gun.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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-beta001";
  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<object[]> {
  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.filter(
  49. entry =>
  50. new Date(entry["created_at"]) < intervalStart &&
  51. new Date(entry["created_at"]) >= intervalEnd
  52. );
  53. } else {
  54. return [];
  55. }
  56. }
  57. /**
  58. * Hashtags are stored without reference to the users to provide these information on an extra dashboard to twitter
  59. * @param hashtagEntity extracted hashtags
  60. */
  61. public publishHashtags(hashtagEntity): void {
  62. const timestamp = Date.now();
  63. const hashtagsCommaSeparated = hashtagEntity
  64. .map(el => el.hashtag)
  65. .sort()
  66. .join("|");
  67. const hashtags = this.gun.get(timestamp).put({
  68. hashtags: hashtagsCommaSeparated,
  69. created_at: timestamp
  70. });
  71. this.gun
  72. .get(this.osnPrefix)
  73. .get("hashtags")
  74. .set(hashtags);
  75. }
  76. }