p2p-database-gun.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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-beta010";
  8. constructor() {
  9. this.gun = Gun(["https://hybrid-osn.herokuapp.com/gun"]);
  10. }
  11. /**
  12. * Hashtags are stored without reference to the users to provide these information on an extra dashboard to twitter
  13. * @param hashtagEntity extracted hashtags
  14. */
  15. public async publishHashtags(hashtagEntity): Promise<void> {
  16. const timestamp = new Date().setHours(0, 0, 1, 0);
  17. const hashtagsSeparated = hashtagEntity
  18. .map(el => el.hashtag)
  19. .sort()
  20. .join("|");
  21. const randomId = Math.floor(Math.random() * 10000000000);
  22. const hashtags = await this.gun
  23. .get(randomId)
  24. .put({ hashtags: hashtagsSeparated })
  25. .then();
  26. this.gun
  27. .get(this.osnPrefix)
  28. .get("hashtags")
  29. .get(timestamp)
  30. .set(hashtags);
  31. }
  32. public storeLastTweetHashForUser(userId, hash, timestamp): void {
  33. const tweet = this.gun
  34. .get(timestamp)
  35. .put({ hash: hash, created_at: timestamp });
  36. this.gun
  37. .get(this.osnPrefix)
  38. .get("tweets")
  39. .get(userId)
  40. .set(tweet);
  41. }
  42. public async fetchPrivateTweetHashsForUserInInterval(
  43. userId,
  44. intervalStart,
  45. intervalEnd
  46. ): Promise<object[]> {
  47. const privateTweets = await this.gun
  48. .get(this.osnPrefix)
  49. .get("tweets")
  50. .get(userId)
  51. .then();
  52. if (privateTweets) {
  53. const entries = await Promise.all(
  54. Object.keys(privateTweets)
  55. .filter(key => key !== "_")
  56. .map(key => this.gun.get(key).then())
  57. );
  58. return entries
  59. .filter(
  60. entry =>
  61. new Date(entry["created_at"]) < intervalStart &&
  62. new Date(entry["created_at"]) >= intervalEnd
  63. )
  64. .map(entry => {
  65. entry.userId = userId;
  66. return entry;
  67. });
  68. } else {
  69. return [];
  70. }
  71. }
  72. public async addLike(tweetId: string) {
  73. const likeEntry = await this.getLikes(tweetId);
  74. const likes = this.gun.get(tweetId).put({
  75. likes: likeEntry.likes + 1
  76. });
  77. this.gun
  78. .get(this.osnPrefix)
  79. .get("likes")
  80. .set(likes);
  81. }
  82. public async getLikes(tweetId: string) {
  83. const likeEntry = await this.gun
  84. .get(this.osnPrefix)
  85. .get("likes")
  86. .get(tweetId)
  87. .then();
  88. if (likeEntry === undefined) {
  89. return {
  90. likes: 0
  91. };
  92. } else {
  93. return likeEntry;
  94. }
  95. }
  96. }