Browse Source

fix typos, try avoid triggering rate limit

Mike L 3 years ago
parent
commit
8bf06705eb
2 changed files with 49 additions and 34 deletions
  1. 24 18
      dist/twitter.js
  2. 25 16
      src/twitter.ts

+ 24 - 18
dist/twitter.js

@@ -191,21 +191,22 @@ class default_1 {
                 }, this.workInterval * 1200 / this.lock.feed.length);
             });
         };
+        this.queryUserObject = (userName) => this.client.user.searchExact(userName)
+            .catch((error) => {
+            if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
+                logger.warn('login required, logging in again...');
+                return this.session.login().then(() => this.client.user.searchExact(userName));
+            }
+            else
+                throw error;
+        });
         this.queryUser = (rawUserName) => {
             const username = ScreenNameNormalizer.normalize(rawUserName).split(':')[0];
             for (const { user } of Object.values(this.cache)) {
                 if (user.username === username)
                     return Promise.resolve(`${username}:${user.pk}`);
             }
-            return this.client.user.searchExact(username)
-                .catch((error) => {
-                if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
-                    logger.warn('login required, logging in again...');
-                    return this.session.login().then(() => this.client.user.searchExact(username));
-                }
-                else
-                    throw error;
-            })
+            return this.queryUserObject(username)
                 .then(({ pk, username, full_name }) => {
                 this.cache[pk] = { user: { pk, username, full_name }, stories: {}, pullOrder: 0 };
                 fs.writeFileSync(path.resolve(this.cachefile), JSON.stringify(this.cache));
@@ -255,13 +256,18 @@ class default_1 {
                 return utils_1.chainPromises(utils_1.Arr.chunk(userIdCache, 20).map(userIds => () => {
                     logger.info(`pulling stories from users:${userIds.map(id => ` @${this.cache[id].user.username}`)}`);
                     return this.client.feed.reelsMedia({ userIds }).request()
-                        .then(({ reels }) => utils_1.chainPromises(Object.keys(reels).map(userId => () => this.client.user.info(userId).then(({ pk, username, full_name }) => {
-                        const cacheItem = this.cache[pk];
-                        cacheItem.user = { pk, username, full_name };
-                        return Promise.all(reels[userId].items
-                            .filter(item => !(item.pk in cacheItem.stories))
-                            .map(item => this.webshot([Object.assign(Object.assign({}, item), { user: cacheItem.user })], (msgs, text, author) => cacheItem.stories[item.pk] = { pk: item.pk, msgs, text, author, original: item }, this.webshotDelay)));
-                    }))))
+                        .then(({ reels }) => utils_1.chainPromises(Object.keys(reels).map(userId => this.cache[userId]).map(cacheItem => () => this.queryUserObject(cacheItem.user.username)
+                        .catch((error) => {
+                        if (error instanceof instagram_private_api_1.IgExactUserNotFoundError) {
+                            return this.client.user.info(cacheItem.user.pk)
+                                .then(({ username, full_name }) => {
+                                cacheItem.user.username = username;
+                                cacheItem.user.full_name = full_name;
+                            });
+                        }
+                    }).finally(() => Promise.all(reels[cacheItem.user.pk].items
+                        .filter(item => !(item.pk in cacheItem.stories))
+                        .map(item => this.webshot([Object.assign(Object.assign({}, item), { user: cacheItem.user })], (msgs, text, author) => cacheItem.stories[item.pk] = { pk: item.pk, msgs, text, author, original: item }, this.webshotDelay)))))))
                         .finally(() => {
                         fs.writeFileSync(path.resolve(this.cachefile), JSON.stringify(this.cache));
                         Object.values(this.lock.threads).forEach(thread => {
@@ -353,7 +359,7 @@ class default_1 {
                             const username = cachedFeed.user.username;
                             const author = `${cachedFeed.user.full_name} (@${username}) `;
                             this.bot.sendTo(subscriber, `请注意,用户${author}已开启问答互动。需退订请回复:/igstory_unsub ${username}${Object.keys(cachedFeed.stories).some(id => id > topOfFeed) ?
-                                `\n本次推送已截止于此条动态,下次推送在 ${Math.floor(this.workInterval * 1000 / lock.feed.length)} 秒后。` : ''}`);
+                                `\n本次推送已截止于此条动态,下次推送在 ${Math.floor(this.workInterval / lock.feed.length)} 秒后。` : ''}`);
                         });
                     }
                 });
@@ -427,7 +433,7 @@ class default_1 {
                 }
                 else if (error instanceof instagram_private_api_1.IgLoginRequiredError || error instanceof instagram_private_api_1.IgCookieNotFoundError) {
                     logger.warn('login required, logging in again...');
-                    reply('等待登中,稍后会处理请求,请稍候……');
+                    reply('等待登中,稍后会处理请求,请稍候……');
                     this.session.login().then(retryAction);
                 }
                 else {

+ 25 - 16
src/twitter.ts

@@ -306,7 +306,7 @@ export default class {
             reply(`获取 Stories 时出现错误:原因: ${error.cause}`);
           } else if (error instanceof IgLoginRequiredError || error instanceof IgCookieNotFoundError) {
             logger.warn('login required, logging in again...');
-            reply('等待登中,稍后会处理请求,请稍候……');
+            reply('等待登中,稍后会处理请求,请稍候……');
             this.session.login().then(retryAction);
           } else {
             logger.error(`unhandled error while fetching stories for ${rawUserName}: ${error}`);
@@ -387,18 +387,21 @@ export default class {
     );
   };
 
+  public queryUserObject = (userName: string) =>
+    this.client.user.searchExact(userName)
+    .catch((error: IgClientError) => {
+      if (error instanceof IgLoginRequiredError || error instanceof IgCookieNotFoundError) {
+        logger.warn('login required, logging in again...');
+        return this.session.login().then(() => this.client.user.searchExact(userName));
+      } else throw error;
+    });
+
   public queryUser = (rawUserName: string) => {
     const username = ScreenNameNormalizer.normalize(rawUserName).split(':')[0];
     for (const {user} of Object.values(this.cache)) {
       if (user.username === username) return Promise.resolve(`${username}:${user.pk}`);
     }
-    return this.client.user.searchExact(username)
-      .catch((error: IgClientError) => {
-        if (error instanceof IgLoginRequiredError || error instanceof IgCookieNotFoundError) {
-          logger.warn('login required, logging in again...');
-          return this.session.login().then(() => this.client.user.searchExact(username));
-        } else throw error;
-      })
+    return this.queryUserObject(username)
       .then(({pk, username, full_name}) => {
         this.cache[pk] = {user: {pk, username, full_name}, stories: {}, pullOrder: 0};
         fs.writeFileSync(path.resolve(this.cachefile), JSON.stringify(this.cache));
@@ -467,11 +470,17 @@ export default class {
             logger.info(`pulling stories from users:${userIds.map(id => ` @${this.cache[id].user.username}`)}`);
             return this.client.feed.reelsMedia({userIds}).request()
               .then(({reels}) => chainPromises(
-                Object.keys(reels).map(userId => () =>
-                  this.client.user.info(userId).then(({pk, username, full_name}) => {
-                    const cacheItem = this.cache[pk];
-                    cacheItem.user = {pk, username, full_name};
-                    return Promise.all(reels[userId].items
+                Object.keys(reels).map(userId => this.cache[userId]).map(cacheItem => () =>
+                  this.queryUserObject(cacheItem.user.username)
+                    .catch((error: IgClientError) => {
+                      if (error instanceof IgExactUserNotFoundError) {
+                        return this.client.user.info(cacheItem.user.pk)
+                          .then(({username, full_name}) => {
+                            cacheItem.user.username = username;
+                            cacheItem.user.full_name = full_name;
+                          });
+                      }
+                    }).finally(() => Promise.all(reels[cacheItem.user.pk].items
                       .filter(item => !(item.pk in cacheItem.stories))
                       .map(item => this.webshot(
                         [{...item, user: cacheItem.user}],
@@ -479,8 +488,8 @@ export default class {
                           cacheItem.stories[item.pk] = {pk: item.pk, msgs, text, author, original: item},
                         this.webshotDelay
                       ))
-                    );
-                  })
+                    )
+                  )
                 )
               ))
               .finally(() => {
@@ -585,7 +594,7 @@ export default class {
               this.bot.sendTo(subscriber,
                 `请注意,用户${author}已开启问答互动。需退订请回复:/igstory_unsub ${username}${
                   Object.keys(cachedFeed.stories).some(id => id > topOfFeed) ?
-                    `\n本次推送已截止于此条动态,下次推送在 ${Math.floor(this.workInterval * 1000 / lock.feed.length)} 秒后。` : ''}`);
+                    `\n本次推送已截止于此条动态,下次推送在 ${Math.floor(this.workInterval / lock.feed.length)} 秒后。` : ''}`);
             });
           }
         });