p2p-database-gun.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  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-beta011";
  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 = this.gun
  23. .get(randomId)
  24. .put({ hashtags: hashtagsSeparated });
  25. this.gun
  26. .get(this.osnPrefix)
  27. .get("hashtags")
  28. .get(timestamp)
  29. .set(hashtags);
  30. }
  31. public storeLastTweetHashForUser(userId, hash, timestamp): void {
  32. const tweet = this.gun
  33. .get(timestamp)
  34. .put({ hash: hash, created_at: timestamp });
  35. this.gun
  36. .get(this.osnPrefix)
  37. .get("tweets")
  38. .get(userId)
  39. .set(tweet);
  40. }
  41. public async fetchPrivateTweetHashsForUserInInterval(
  42. userId,
  43. intervalStart,
  44. intervalEnd
  45. ): Promise<object[]> {
  46. const privateTweets = await this.gun
  47. .get(this.osnPrefix)
  48. .get("tweets")
  49. .get(userId)
  50. .then();
  51. if (privateTweets) {
  52. const entries = await Promise.all(
  53. Object.keys(privateTweets)
  54. .filter(key => key !== "_")
  55. .map(key => this.gun.get(key).then())
  56. );
  57. return entries
  58. .filter(entry => {
  59. const createdAtDate = new Date(entry["created_at"]);
  60. return createdAtDate < intervalStart && createdAtDate >= intervalEnd;
  61. })
  62. .map(entry => {
  63. entry.userId = userId;
  64. return entry;
  65. });
  66. } else {
  67. return [];
  68. }
  69. }
  70. public async addLike(tweetId: string) {
  71. const likeEntry = await this.getLikes(tweetId);
  72. const likes = this.gun.get(tweetId).put({
  73. likes: likeEntry.likes + 1
  74. });
  75. this.gun
  76. .get(this.osnPrefix)
  77. .get("likes")
  78. .set(likes);
  79. }
  80. public async getLikes(tweetId: string) {
  81. const likeEntry = await this.gun
  82. .get(this.osnPrefix)
  83. .get("likes")
  84. .get(tweetId)
  85. .then();
  86. if (likeEntry === undefined) {
  87. return {
  88. likes: 0
  89. };
  90. } else {
  91. return likeEntry;
  92. }
  93. }
  94. }