p2p-database-gun.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { Injectable } from "@angular/core";
  2. import Gun from "gun/gun";
  3. import "gun/lib/then";
  4. @Injectable()
  5. export class P2pDatabaseGunProvider {
  6. private gun;
  7. osnPrefix: string = "hybridOSN-beta003";
  8. constructor() {
  9. this.gun = Gun(["https://hybrid-osn.herokuapp.com/gun"]);
  10. }
  11. public storeLastTweetHashForUser(userId, hash, timestamp): void {
  12. const tweet = this.gun
  13. .get(timestamp)
  14. .put({ hash: hash, created_at: timestamp });
  15. this.gun
  16. .get(this.osnPrefix + "-" + userId)
  17. .get("tweets")
  18. .set(tweet);
  19. }
  20. /**
  21. * Hashtags are stored without reference to the users to provide these information on an extra dashboard to twitter
  22. * @param hashtagEntity extracted hashtags
  23. */
  24. public publishHashtags(hashtagEntity): void {
  25. const timestamp = Date.now();
  26. const hashtagsCommaSeparated = hashtagEntity
  27. .map(el => el.hashtag)
  28. .sort()
  29. .join("|");
  30. const hashtags = this.gun.get(timestamp).put({
  31. hashtags: hashtagsCommaSeparated,
  32. created_at: timestamp
  33. });
  34. this.gun.get(this.osnPrefix + "/hashtags").set(hashtags);
  35. }
  36. public async getLastTweetFromUser(userId) {
  37. return new Promise(resolve =>
  38. this.gun
  39. .get(this.osnPrefix + userId)
  40. .get("tweets")
  41. .once(resolve)
  42. );
  43. }
  44. public async fetchPrivateTweetHashsForUserInInterval(
  45. userId,
  46. intervalStart,
  47. intervalEnd
  48. ): Promise<object[]> {
  49. const gunIds = await this.gun
  50. .get(this.osnPrefix + "-" + userId)
  51. .get("tweets")
  52. .then();
  53. if (gunIds) {
  54. const entries = await Promise.all(
  55. Object.keys(gunIds)
  56. .filter(key => key !== "_")
  57. .map(key => this.gun.get(key).then())
  58. );
  59. return entries.filter(
  60. entry =>
  61. new Date(entry["created_at"]) < intervalStart &&
  62. new Date(entry["created_at"]) >= intervalEnd
  63. );
  64. } else {
  65. return [];
  66. }
  67. }
  68. }