p2p-database-gun.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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<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. /**
  60. * Hashtags are stored without reference to the users to provide these information on an extra dashboard to twitter
  61. * @param hashtagEntity extracted hashtags
  62. */
  63. public publishHashtags(hashtagEntity): void {
  64. const timestamp = Date.now();
  65. const hashtagsCommaSeparated = hashtagEntity
  66. .map(el => el.hashtag)
  67. .sort()
  68. .join("|");
  69. const hashtags = this.gun.get(timestamp).put({
  70. hashtags: hashtagsCommaSeparated,
  71. created_at: timestamp
  72. });
  73. this.gun
  74. .get(this.osnPrefix)
  75. .get("hashtags")
  76. .set(hashtags);
  77. }
  78. }