twitter.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import * as fs from 'fs';
  2. import * as path from 'path';
  3. import * as Twitter from 'twitter-api-v2';
  4. import { getLogger } from './loggers';
  5. import QQBot, { Message } from './koishi';
  6. import RedisSvc from './redis';
  7. import { chainPromises, BigNumOps } from './utils';
  8. import Webshot from './webshot';
  9. interface IWorkerOption {
  10. lock: ILock;
  11. lockfile: string;
  12. bot: QQBot;
  13. workInterval: number;
  14. webshotDelay: number;
  15. consumerKey: string;
  16. consumerSecret: string;
  17. accessTokenKey?: string;
  18. accessTokenSecret?: string;
  19. mode: number;
  20. wsUrl: string;
  21. redis?: IRedisConfig;
  22. }
  23. export const parseLink = (link: string): string[] => {
  24. let match =
  25. /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
  26. /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
  27. if (match) return [match[1], `/lists/${match[2]}`];
  28. match =
  29. /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
  30. if (match) return [match[1], `/status/${match[2]}`];
  31. match =
  32. /twitter.com\/([^\/?#]+)/.exec(link) ||
  33. /^([^\/?#]+)$/.exec(link);
  34. if (match) return [match[1]];
  35. return;
  36. }
  37. export const linkBuilder = (userName: string, more = ''): string => {
  38. if (!userName) return;
  39. return `https://twitter.com/${userName}${more}`;
  40. }
  41. export class ScreenNameNormalizer {
  42. // tslint:disable-next-line: variable-name
  43. public static _queryUser: (username: string) => Promise<string>;
  44. public static normalize = (username: string) => username.toLowerCase().replace(/^@/, '');
  45. public static async normalizeLive(username: string) {
  46. username = this.normalize(username);
  47. if (this._queryUser) {
  48. return await this._queryUser(username)
  49. .then(userNameId => userNameId.split(':')[0])
  50. .catch((err: Twitter.InlineErrorV2) => {
  51. if (err.title === 'Not Found Error') {
  52. logger.warn(`error looking up user: ${showApiError(err)}`);
  53. return username;
  54. }
  55. return null;
  56. });
  57. }
  58. return username;
  59. }
  60. }
  61. export let sendTweet = (id: string, receiver: IChat, forceRefresh: boolean): void => {
  62. throw Error();
  63. };
  64. export interface ITimelineQueryConfig {
  65. username: string;
  66. count?: number;
  67. since?: string;
  68. until?: string;
  69. noreps?: boolean;
  70. norts?: boolean;
  71. }
  72. export let sendTimeline = (
  73. conf: {[key in keyof ITimelineQueryConfig]: string},
  74. receiver: IChat
  75. ): void => {
  76. throw Error();
  77. };
  78. const TWITTER_EPOCH = 1288834974657;
  79. const snowflake = (epoch: number) => Number.isNaN(epoch) ? undefined :
  80. BigNumOps.lShift(String(epoch - 1 - TWITTER_EPOCH), 22);
  81. const logger = getLogger('twitter');
  82. const maxTrials = 3;
  83. const retryInterval = 1500;
  84. const ordinal = (n: number) => {
  85. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  86. case 1:
  87. return `${n}st`;
  88. case 2:
  89. return `${n}nd`;
  90. case 3:
  91. return `${n}rd`;
  92. default:
  93. return `${n}th`;
  94. }
  95. };
  96. const retryOnError = <T, U>(
  97. doWork: () => Promise<T>,
  98. onRetry: (error, count: number, terminate: (defaultValue: U) => void) => void
  99. ) => new Promise<T | U>(resolve => {
  100. const retry = (reason, count: number) => {
  101. setTimeout(() => {
  102. let terminate = false;
  103. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  104. if (!terminate) doWork().then(resolve).catch(error => retry(error, count + 1));
  105. }, retryInterval);
  106. };
  107. doWork().then(resolve).catch(error => retry(error, 1));
  108. });
  109. const showApiError = (err: Partial<Twitter.InlineErrorV2 & Twitter.ErrorV2 & Error>) =>
  110. err.errors && err.errors[0].message || err.detail || err.stack || JSON.stringify(err);
  111. const toMutableConst = <T>(o: T) => {
  112. // credits: https://stackoverflow.com/a/60493166
  113. type DeepMutableArrays<T> =
  114. (T extends object ? { [K in keyof T]: DeepMutableArrays<T[K]> } : T) extends infer O ?
  115. O extends ReadonlyArray<any> ? { -readonly [K in keyof O]: O[K] } : O : never;
  116. return o as DeepMutableArrays<T>
  117. };
  118. const v2SingleParams = toMutableConst({
  119. expansions: ['attachments.media_keys', 'author_id', 'referenced_tweets.id'],
  120. 'tweet.fields': ['created_at', 'entities'],
  121. 'media.fields': ['url', 'variants', 'alt_text'],
  122. 'user.fields': ['id', 'name', 'username']
  123. } as const);
  124. type PickRequired<T, K extends keyof T> = Pick<Required<T>, K> & T;
  125. export type TweetObject = PickRequired<
  126. Twitter.TweetV2SingleResult['data'],
  127. typeof v2SingleParams['tweet.fields'][number]
  128. >;
  129. export type UserObject = PickRequired<
  130. Twitter.TweetV2SingleResult['includes']['users'][number],
  131. typeof v2SingleParams['user.fields'][number]
  132. >;
  133. export type MediaObject =
  134. Twitter.TweetV2SingleResult['includes']['media'][number] & (
  135. {type: 'video' | 'animated_gif', variants: Twitter.MediaVariantsV2[]} |
  136. {type: 'photo', url: string}
  137. );
  138. export interface Tweet extends Twitter.TweetV2SingleResult {
  139. data: TweetObject,
  140. includes: {
  141. media: MediaObject[],
  142. users: UserObject[],
  143. }
  144. };
  145. export default class {
  146. private client: Twitter.TwitterApiReadOnly;
  147. private lock: ILock;
  148. private lockfile: string;
  149. private workInterval: number;
  150. private bot: QQBot;
  151. private webshotDelay: number;
  152. private webshot: Webshot;
  153. private mode: number;
  154. private wsUrl: string;
  155. private redis: RedisSvc;
  156. constructor(opt: IWorkerOption) {
  157. this.client = new Twitter.TwitterApi({
  158. appKey: opt.consumerKey,
  159. appSecret: opt.consumerSecret,
  160. }).readOnly;
  161. this.lockfile = opt.lockfile;
  162. this.lock = opt.lock;
  163. this.workInterval = opt.workInterval;
  164. this.bot = opt.bot;
  165. this.webshotDelay = opt.webshotDelay;
  166. this.mode = opt.mode;
  167. this.wsUrl = opt.wsUrl;
  168. if (opt.redis) this.redis = new RedisSvc(opt.redis);
  169. ScreenNameNormalizer._queryUser = this.queryUser;
  170. sendTweet = (idOrQuery, receiver, forceRefresh) => {
  171. const match = /^last(|-\d+)@([^\/?#,]+)((?:,no.*?=[^,]*)*)$/.exec(idOrQuery);
  172. const query = () => this.queryTimeline({
  173. username: match[2],
  174. count: 1 - Number(match[1]),
  175. noreps: {on: true, off: false}[match[3].replace(/.*,noreps=([^,]*).*/, '$1')],
  176. norts: {on: true, off: false}[match[3].replace(/.*,norts=([^,]*).*/, '$1')],
  177. }).then(tweets => tweets.slice(-1)[0].data.id);
  178. (match ? query() : Promise.resolve(idOrQuery))
  179. .then((id: string) => this.getTweet(
  180. id,
  181. this.sendTweets({sourceInfo: `tweet ${id}`, reportOnSkip: true, force: forceRefresh}, receiver),
  182. forceRefresh
  183. ))
  184. .catch((err: Twitter.InlineErrorV2) => {
  185. if (err.title !== 'Not Found Error') {
  186. logger.warn(`error retrieving tweet: ${showApiError(err)}`);
  187. this.bot.sendTo(receiver, `获取推文时出现错误:${showApiError(err)}`);
  188. }
  189. if (err.resource_type === 'user') {
  190. return this.bot.sendTo(receiver, `找不到用户 ${match[2].replace(/^@?(.*)$/, '@$1')}。`);
  191. }
  192. this.bot.sendTo(receiver, '找不到请求的推文,它可能已被删除。');
  193. });
  194. };
  195. sendTimeline = ({username, count, since, until, noreps, norts}, receiver) => {
  196. const countNum = Number(count) || 10;
  197. (countNum > 0 ? this.queryTimeline : this.queryTimelineReverse)({
  198. username,
  199. count: Math.abs(countNum),
  200. since: BigNumOps.parse(since) || snowflake(new Date(since).getTime()),
  201. until: BigNumOps.parse(until) || snowflake(new Date(until).getTime()),
  202. noreps: {on: true, off: false}[noreps],
  203. norts: {on: true, off: false}[norts],
  204. })
  205. .then(tweets => chainPromises(
  206. tweets.map(({data}) => () => this.bot.sendTo(receiver, `\
  207. 编号:${data.id}
  208. 时间:${data.created_at}
  209. 媒体:${(data.attachments || {}).media_keys ? '有' : '无'}
  210. 正文:\n${data.text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`
  211. ))
  212. .concat(() => this.bot.sendTo(receiver, tweets.length ?
  213. '时间线查询完毕,使用 /twipic_view <编号> 查看媒体推文详细内容。' :
  214. '时间线查询完毕,没有找到符合条件的媒体推文。'
  215. ))
  216. ))
  217. .catch((err: Twitter.InlineErrorV2) => {
  218. if (err.title !== 'Not Found Error') {
  219. logger.warn(`error retrieving timeline: ${showApiError(err)}`);
  220. return this.bot.sendTo(receiver, `获取时间线时出现错误:${showApiError(err)}`);
  221. }
  222. this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
  223. });
  224. };
  225. }
  226. public launch = () => {
  227. this.client.appLogin().then(client => {
  228. this.client = client.readOnly;
  229. this.webshot = new Webshot(
  230. this.wsUrl,
  231. this.mode,
  232. () => setTimeout(this.work, this.workInterval * 1000)
  233. );
  234. });
  235. };
  236. public queryUser = (username: string) => {
  237. const thread = this.lock.threads[linkBuilder(username)];
  238. if (thread && thread.id) return Promise.resolve(`${username}:${thread.id}`);
  239. return this.client.v2.userByUsername(username).then(({data: {username, id}, errors}) => {
  240. if (errors && errors.length > 0) throw errors[0];
  241. if (thread) thread.id = id;
  242. return `${username}:${id}`;
  243. })
  244. }
  245. public queryTimelineReverse = (conf: ITimelineQueryConfig) => {
  246. if (!conf.since) return this.queryTimeline(conf);
  247. const count = conf.count;
  248. const maxID = conf.until;
  249. conf.count = undefined;
  250. const until = () =>
  251. BigNumOps.min(maxID, BigNumOps.plus(conf.since, String(7 * 24 * 3600 * 1000 * 2 ** 22)));
  252. conf.until = until();
  253. const promise = (tweets: Tweet[]): Promise<Tweet[]> =>
  254. this.queryTimeline(conf).then(newTweets => {
  255. tweets = newTweets.concat(tweets);
  256. conf.since = conf.until;
  257. conf.until = until();
  258. if (
  259. tweets.length >= count ||
  260. BigNumOps.compare(conf.since, conf.until) >= 0
  261. ) {
  262. return tweets.slice(-count);
  263. }
  264. return promise(tweets);
  265. });
  266. return promise([]);
  267. };
  268. public queryTimeline = (
  269. {username, count, since, until, noreps, norts}: ITimelineQueryConfig
  270. ) => {
  271. username = username.replace(/^@?(.*)$/, '@$1');
  272. return this.queryUser(username.slice(1)).then(userNameId => {
  273. const getMore = (lastTweets: Tweet[] = []) => {
  274. logger.info(`querying timeline of ${username} with config: ${
  275. JSON.stringify({
  276. ...(count && {count}),
  277. ...(since && {since}),
  278. ...(until && {until}),
  279. ...(noreps && {noreps}),
  280. ...(norts && {norts}),
  281. })}`);
  282. return this.get('userTimeline', userNameId.split(':')[1], {
  283. expansions: ['attachments.media_keys', 'author_id'],
  284. 'tweet.fields': ['created_at'],
  285. exclude: [
  286. ...(noreps ?? true) ? ['replies' as const] : [],
  287. ...(norts ?? false) ? ['retweets' as const] : [],
  288. ],
  289. max_results: Math.min(Math.max(count || 0, 20), 100),
  290. ...(since && {since_id: since}),
  291. ...(until && {until_id: until}),
  292. }).then(newTweets => {
  293. logger.info(`timeline query of ${username} yielded ${newTweets.length} new tweets`);
  294. const tweets = lastTweets.concat(newTweets.filter(({data}) => (data.attachments || {}).media_keys));
  295. if (tweets.length < count) {
  296. until = BigNumOps.plus('-1', newTweets.slice(-1)[0].data.id);
  297. logger.info(`starting next query at offset ${until}...`);
  298. return getMore(tweets);
  299. }
  300. logger.info(`timeline query of ${username} finished successfully, ${
  301. tweets.length
  302. } media tweets have been fetched`);
  303. return tweets.slice(0, count);
  304. });
  305. }
  306. return getMore();
  307. });
  308. };
  309. private workOnTweets = (
  310. tweets: Tweet[],
  311. sendTweets: (cacheId: string, msg: string, text: string, author: string) => void,
  312. refresh = false
  313. ) => Promise.all(tweets.map(({data, includes}) =>
  314. ((this.redis && !refresh) ?
  315. this.redis.waitForProcess(`webshot/${data.id}`, this.webshotDelay * 4)
  316. .then(() => this.redis.getContent(`webshot/${data.id}`)) :
  317. Promise.reject())
  318. .then(content => {
  319. if (content === null) throw Error();
  320. logger.info(`retrieved cached webshot of tweet ${data.id} from redis database, message chain:`);
  321. const {msg, text, author} = JSON.parse(content) as {[key: string]: string};
  322. let cacheId = data.id;
  323. const retweetRef = (data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
  324. if (retweetRef) cacheId += `,rt:${retweetRef.id}`;
  325. logger.info(JSON.stringify(Message.parseCQCode(msg)));
  326. sendTweets(cacheId, Message.parseCQCode(msg), text, author);
  327. return null as Tweet;
  328. })
  329. .catch(() => {
  330. this.redis.startProcess(`webshot/${data.id}`);
  331. return {data, includes} as Tweet;
  332. })
  333. )).then(tweets =>
  334. this.webshot(
  335. tweets.filter(t => t),
  336. (cacheId: string, msg: string, text: string, author: string) => {
  337. Promise.resolve()
  338. .then(() => {
  339. if (!this.redis) return;
  340. const [twid, rtid] = cacheId.split(',rt:');
  341. logger.info(`caching webshot of tweet ${twid} to redis database`);
  342. this.redis.cacheContent(`webshot/${twid}`,
  343. JSON.stringify({msg: Message.toCQCode(msg), text, author, rtid})
  344. ).then(() => this.redis.finishProcess(`webshot/${twid}`));
  345. })
  346. .then(() => sendTweets(cacheId, msg, text, author));
  347. },
  348. this.webshotDelay
  349. )
  350. );
  351. private handleRetweet = (tweet: Tweet) => {
  352. const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
  353. if (retweetRef) return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
  354. .then(({data: {referenced_tweets}, includes: {media}}) => ({
  355. ...tweet,
  356. data: {
  357. ...tweet.data,
  358. referenced_tweets: [retweetRef, ...(referenced_tweets || [])],
  359. },
  360. includes: {
  361. ...tweet.includes,
  362. media
  363. }
  364. }) as Tweet);
  365. return Promise.resolve(tweet);
  366. };
  367. public getTweet = (
  368. id: string,
  369. sender: (cacheId: string, msg: string, text: string, author: string) => void,
  370. refresh = false
  371. ) =>
  372. ((this.redis && !refresh) ?
  373. this.redis.waitForProcess(`webshot/${id}`, this.webshotDelay * 4)
  374. .then(() => this.redis.getContent(`webshot/${id}`))
  375. .then(content => {
  376. if (content === null) throw Error();
  377. const {rtid} = JSON.parse(content);
  378. return {data: {id, ...rtid && {referenced_tweets: [{type: 'retweeted', id: rtid}]}}} as Tweet;
  379. }) :
  380. Promise.reject()
  381. )
  382. .catch(() => this.client.v2.singleTweet(id, v2SingleParams))
  383. .then((tweet: Tweet) => {
  384. if (tweet.data.text) {
  385. logger.debug(`api returned tweet ${JSON.stringify(tweet)} for query id=${id}`);
  386. return this.handleRetweet(tweet);
  387. } else {
  388. logger.debug(`skipped querying api as this tweet has been cached`);
  389. }
  390. return tweet;
  391. })
  392. .then((tweet: Tweet) => this.workOnTweets([tweet], sender, refresh));
  393. private sendTweets = (
  394. config: {sourceInfo?: string, reportOnSkip?: boolean, force?: boolean}
  395. = {reportOnSkip: false, force: false},
  396. ...to: IChat[]
  397. ) => (id: string, msg: string, text: string, author: string) => {
  398. to.forEach(subscriber => {
  399. const [twid, rtid] = id.split(',rt:');
  400. const {sourceInfo: source, reportOnSkip, force} = config;
  401. const targetStr = JSON.stringify(subscriber);
  402. const send = () => retryOnError(
  403. () => this.bot.sendTo(subscriber, msg),
  404. (_, count, terminate: (doNothing: Promise<void>) => void) => {
  405. if (count <= maxTrials) {
  406. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  407. } else {
  408. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  409. terminate(this.bot.sendTo(subscriber, author + text, true));
  410. }
  411. }
  412. ).then(() => {
  413. if (this.redis) {
  414. logger.info(`caching push status of tweet ${rtid ? `${rtid} (RTed as ${twid})` : twid} for ${targetStr}...`);
  415. return this.redis.cacheForChat(rtid || twid, subscriber);
  416. }
  417. });
  418. ((this.redis && !force) ? this.redis.isCachedForChat(rtid || twid, subscriber) : Promise.resolve(false))
  419. .then(isCached => {
  420. if (isCached) {
  421. logger.info(`skipped subscriber ${targetStr} as tweet ${rtid ? `${rtid} (or its RT)` : twid} has been sent already`);
  422. if (!reportOnSkip) return;
  423. text = `[最近发送过的推文:${rtid || twid}]`;
  424. msg = author + text;
  425. }
  426. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${targetStr}`);
  427. return send();
  428. });
  429. });
  430. };
  431. private get = <T extends 'userTimeline' | 'listTweets'>(
  432. type: T, targetId: string, params: Parameters<typeof this.client.v2[T]>[1]
  433. ) => {
  434. const {since_id, max_results} = (params as Twitter.TweetV2UserTimelineParams);
  435. const getMore = (res: Twitter.TweetUserTimelineV2Paginator | Twitter.TweetV2ListTweetsPaginator) => {
  436. if (res.errors && res.errors.length > 0) {
  437. const [err] = res.errors;
  438. if (!res.data) throw err;
  439. if (err.title === 'Authorization Error') {
  440. logger.warn(`non-fatal error while querying ${type} with id ${targetId}, error: ${err.detail}`);
  441. }
  442. }
  443. if (!res.meta.next_token || // at last page
  444. BigNumOps.compare(res.tweets.slice(-1)[0].id, since_id || '0') !== 1 || // at specified boundary
  445. !since_id && res.meta.result_count >= max_results // at specified max count
  446. ) return res;
  447. return res.fetchNext().then<typeof res>(getMore);
  448. };
  449. if (type === 'listTweets') delete (params as any).since_id;
  450. return this.client.v2[type](targetId, params).then(getMore)
  451. .then(({includes, tweets}) => tweets.map((tweet): Tweet =>
  452. ({
  453. data: tweet as TweetObject,
  454. includes: {
  455. media: includes.medias(tweet) as MediaObject[],
  456. users: [includes.author(tweet)]
  457. }
  458. })
  459. ))
  460. .then(tweets => Promise.all(tweets.map(this.handleRetweet)));
  461. };
  462. public work = () => {
  463. const lock = this.lock;
  464. if (this.workInterval < 1) this.workInterval = 1;
  465. if (lock.feed.length === 0) {
  466. setTimeout(() => {
  467. this.work();
  468. }, this.workInterval * 1000);
  469. return;
  470. }
  471. if (lock.workon >= lock.feed.length) lock.workon = 0;
  472. if (!lock.threads[lock.feed[lock.workon]] ||
  473. !lock.threads[lock.feed[lock.workon]].subscribers ||
  474. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  475. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  476. delete lock.threads[lock.feed[lock.workon]];
  477. lock.feed.splice(lock.workon, 1);
  478. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  479. this.work();
  480. return;
  481. }
  482. const currentFeed = lock.feed[lock.workon];
  483. logger.debug(`pulling feed ${currentFeed}`);
  484. const promise = new Promise<Tweet[]>(resolve => {
  485. let job = Promise.resolve();
  486. let id = lock.threads[currentFeed].id;
  487. let endpoint: Parameters<typeof this.get>[0];
  488. let match = /https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/.exec(currentFeed);
  489. if (match) {
  490. endpoint = 'listTweets';
  491. if (match[1] === 'i') {
  492. id = match[2];
  493. } else if (id === undefined) {
  494. job = job.then(() => this.client.v1.list({
  495. owner_screen_name: match[1],
  496. slug: match[2],
  497. })).then(({id_str}) => {
  498. lock.threads[currentFeed].id = id = id_str;
  499. });
  500. }
  501. } else {
  502. match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
  503. if (match) {
  504. endpoint = 'userTimeline';
  505. if (id === undefined) {
  506. job = job.then(() => this.queryUser(
  507. match[1].replace(/^@?(.*)$/, '$1')
  508. )).then(userNameId => {
  509. lock.threads[currentFeed].id = id = userNameId.split(':')[1];
  510. });
  511. }
  512. }
  513. }
  514. const offset = lock.threads[currentFeed].offset;
  515. job.then(() => this.get(endpoint, id, {
  516. ...v2SingleParams,
  517. max_results: 20,
  518. exclude: ['retweets'],
  519. ...(offset as unknown as number > 0) && {since_id: offset},
  520. ...(offset as unknown as number < -1) && {until_id: offset.slice(1)},
  521. })).catch((err: Twitter.InlineErrorV2) => {
  522. if (err.title === 'Not Found Error') {
  523. logger.warn(`error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
  524. lock.threads[currentFeed].subscribers.forEach(subscriber => {
  525. logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
  526. this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
  527. });
  528. } else {
  529. logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
  530. }
  531. return [] as Tweet[];
  532. }).then(resolve);
  533. });
  534. promise.then((tweets: Tweet[]) => {
  535. logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
  536. const currentThread = lock.threads[currentFeed];
  537. const setOffset = (offset: string) => currentThread.offset = offset;
  538. const updateDate = () => currentThread.updatedAt = new Date().toString();
  539. if (tweets.length === 0) {
  540. if (currentThread.offset as unknown as number < -1) {
  541. setOffset(BigNumOps.plus('1', currentThread.offset));
  542. }
  543. updateDate();
  544. return;
  545. }
  546. const currentUser = tweets[0].includes.users.find(user => user.id === currentThread.id);
  547. if (currentUser.username !== parseLink(currentFeed)[1]) {
  548. lock.feed[lock.workon] = linkBuilder(currentUser.username);
  549. }
  550. const topOfFeed = tweets[0].data.id;
  551. logger.info(`current offset: ${currentThread.offset}, current top of feed: ${topOfFeed}`);
  552. const bottomOfFeed = tweets.slice(-1)[0].data.id;
  553. const updateOffset = () => setOffset(topOfFeed);
  554. tweets = tweets.filter(({data}) => (data.attachments || {}).media_keys);
  555. logger.info(`found ${tweets.length} tweets with extended entities`);
  556. if (currentThread.offset === '-1') { updateOffset(); return; }
  557. if (currentThread.offset as unknown as number <= 0) {
  558. if (tweets.length === 0) {
  559. setOffset(BigNumOps.plus('1', '-' + bottomOfFeed));
  560. lock.workon--;
  561. return;
  562. }
  563. tweets.splice(1);
  564. }
  565. if (tweets.length === 0) { updateDate(); updateOffset(); return; }
  566. return this.workOnTweets(tweets, this.sendTweets({sourceInfo: `thread ${currentFeed}`}, ...currentThread.subscribers))
  567. .then(updateDate).then(updateOffset);
  568. })
  569. .then(() => {
  570. lock.workon++;
  571. let timeout = this.workInterval * 1000 / lock.feed.length;
  572. if (timeout < 1000) timeout = 1000;
  573. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  574. setTimeout(() => {
  575. this.work();
  576. }, timeout);
  577. });
  578. };
  579. }