Pārlūkot izejas kodu

Add entities to private tweets

Carsten Porth 6 gadi atpakaļ
vecāks
revīzija
c45af3adef

+ 40 - 1
app/src/pages/write-tweet/write-tweet.ts

@@ -10,6 +10,7 @@ import { TwitterApiProvider } from "../../providers/twitter-api/twitter-api";
 import { Storage } from "@ionic/storage";
 import { P2pStorageIpfsProvider } from "../../providers/p2p-storage-ipfs/p2p-storage-ipfs";
 import { P2pDatabaseGunProvider } from "../../providers/p2p-database-gun/p2p-database-gun";
+import twittertext from "twitter-text";
 
 @IonicPage()
 @Component({
@@ -84,13 +85,51 @@ export class WriteTweetPage {
 
   private async buildPrivateTweet() {
     const status = this.tweet.value["text"].trim();
+    const entities = await this.getEntities(status);
+
     return {
       full_text: status,
       user_id: await this.storage.get("userId"),
       created_at: Date.now(),
       private_tweet: true,
       display_text_range: [0, status.length],
-      entities: {}
+      entities: entities
+    };
+  }
+
+  private async getEntities(status: string) {
+    return {
+      hashtags: twittertext.extractHashtagsWithIndices(status),
+      urls: twittertext.extractUrlsWithIndices(status),
+      user_mentions: await this.getMentions(status)
     };
   }
+
+  private async getMentions(status: string) {
+    // extract mentions
+    const entities = twittertext.extractMentionsWithIndices(status);
+
+    // add user_id
+    const entitiesWithPromises = entities.map(async mention => {
+      try {
+        const user = await this.twitter.fetchUserFromScreenName(
+          mention.screenName
+        );
+        mention["id_str"] = user[0]["id_str"];
+        mention["screen_name"] = mention.screenName;
+        delete mention.screenName;
+      } catch (err) {
+        console.error(
+          "There is no user signed up to twitter with username: " +
+            mention.screenName
+        );
+      }
+      return mention;
+    });
+
+    // filter for valid users and return
+    return (await Promise.all(entitiesWithPromises)).filter(el =>
+      el.hasOwnProperty("id_str")
+    );
+  }
 }

+ 7 - 0
app/src/providers/twitter-api/twitter-api.ts

@@ -38,6 +38,13 @@ export class TwitterApiProvider {
     return res.data;
   }
 
+  public async fetchUserFromScreenName(screenName) {
+    const res = await this.client.get("users/lookup", {
+      screen_name: screenName
+    });
+    return res.data;
+  }
+
   public async fetchUserTimeline(userId, maxId?) {
     const res = await this.client.get("statuses/user_timeline", {
       user_id: userId,