twitter.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.sendTimeline = exports.sendTweet = exports.ScreenNameNormalizer = exports.linkBuilder = exports.parseLink = void 0;
  13. const fs = require("fs");
  14. const path = require("path");
  15. const Twitter = require("twitter-api-v2");
  16. const loggers_1 = require("./loggers");
  17. const koishi_1 = require("./koishi");
  18. const redis_1 = require("./redis");
  19. const utils_1 = require("./utils");
  20. const webshot_1 = require("./webshot");
  21. const parseLink = (link) => {
  22. let match = /twitter.com\/([^\/?#]+)\/lists\/([^\/?#]+)/.exec(link) ||
  23. /^([^\/?#]+)\/([^\/?#]+)$/.exec(link);
  24. if (match)
  25. return [match[1], `/lists/${match[2]}`];
  26. match =
  27. /twitter.com\/([^\/?#]+)\/status\/(\d+)/.exec(link);
  28. if (match)
  29. return [match[1], `/status/${match[2]}`];
  30. match =
  31. /twitter.com\/([^\/?#]+)/.exec(link) ||
  32. /^([^\/?#]+)$/.exec(link);
  33. if (match)
  34. return [match[1]];
  35. return;
  36. };
  37. exports.parseLink = parseLink;
  38. const linkBuilder = (userName, more = '') => {
  39. if (!userName)
  40. return;
  41. return `https://twitter.com/${userName}${more}`;
  42. };
  43. exports.linkBuilder = linkBuilder;
  44. class ScreenNameNormalizer {
  45. static normalizeLive(username) {
  46. return __awaiter(this, void 0, void 0, function* () {
  47. username = this.normalize(username);
  48. if (this._queryUser) {
  49. return yield this._queryUser(username)
  50. .then(userNameId => userNameId.split(':')[0])
  51. .catch((err) => {
  52. if (err.title === 'Not Found Error') {
  53. logger.warn(`error looking up user: ${showApiError(err)}`);
  54. return username;
  55. }
  56. return null;
  57. });
  58. }
  59. return username;
  60. });
  61. }
  62. }
  63. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  64. ScreenNameNormalizer.normalize = (username) => username.toLowerCase().replace(/^@/, '');
  65. let sendTweet = (id, receiver, forceRefresh) => {
  66. throw Error();
  67. };
  68. exports.sendTweet = sendTweet;
  69. let sendTimeline = (conf, receiver) => {
  70. throw Error();
  71. };
  72. exports.sendTimeline = sendTimeline;
  73. const TWITTER_EPOCH = 1288834974657;
  74. const snowflake = (epoch) => Number.isNaN(epoch) ? undefined :
  75. utils_1.BigNumOps.lShift(String(epoch - 1 - TWITTER_EPOCH), 22);
  76. const logger = (0, loggers_1.getLogger)('twitter');
  77. const maxTrials = 3;
  78. const retryInterval = 1500;
  79. const ordinal = (n) => {
  80. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  81. case 1:
  82. return `${n}st`;
  83. case 2:
  84. return `${n}nd`;
  85. case 3:
  86. return `${n}rd`;
  87. default:
  88. return `${n}th`;
  89. }
  90. };
  91. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  92. const retry = (reason, count) => {
  93. setTimeout(() => {
  94. let terminate = false;
  95. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  96. if (!terminate)
  97. doWork().then(resolve).catch(error => retry(error, count + 1));
  98. }, retryInterval);
  99. };
  100. doWork().then(resolve).catch(error => retry(error, 1));
  101. });
  102. const showApiError = (err) => err.errors && err.errors[0].message || err.detail || err.stack || JSON.stringify(err);
  103. const toMutableConst = (o) => {
  104. return o;
  105. };
  106. const v2SingleParams = toMutableConst({
  107. expansions: ['attachments.media_keys', 'author_id', 'referenced_tweets.id'],
  108. 'tweet.fields': ['created_at', 'entities'],
  109. 'media.fields': ['url', 'variants', 'alt_text'],
  110. 'user.fields': ['id', 'name', 'username']
  111. });
  112. ;
  113. class default_1 {
  114. constructor(opt) {
  115. this.launch = () => {
  116. this.client.appLogin().then(client => {
  117. this.client = client.readOnly;
  118. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => setTimeout(this.work, this.workInterval * 1000));
  119. });
  120. };
  121. this.queryUser = (username) => {
  122. const thread = this.lock.threads[(0, exports.linkBuilder)(username)];
  123. if (thread && thread.id)
  124. return Promise.resolve(`${username}:${thread.id}`);
  125. return this.client.v2.userByUsername(username).then(({ data: { username, id }, errors }) => {
  126. if (errors && errors.length > 0)
  127. throw errors[0];
  128. if (thread)
  129. thread.id = id;
  130. return `${username}:${id}`;
  131. });
  132. };
  133. this.queryTimelineReverse = (conf) => {
  134. if (!conf.since)
  135. return this.queryTimeline(conf);
  136. const count = conf.count;
  137. const maxID = conf.until;
  138. conf.count = undefined;
  139. const until = () => utils_1.BigNumOps.min(maxID, utils_1.BigNumOps.plus(conf.since, String(7 * 24 * 3600 * 1000 * Math.pow(2, 22))));
  140. conf.until = until();
  141. const promise = (tweets) => this.queryTimeline(conf).then(newTweets => {
  142. tweets = newTweets.concat(tweets);
  143. conf.since = conf.until;
  144. conf.until = until();
  145. if (tweets.length >= count ||
  146. utils_1.BigNumOps.compare(conf.since, conf.until) >= 0) {
  147. return tweets.slice(-count);
  148. }
  149. return promise(tweets);
  150. });
  151. return promise([]);
  152. };
  153. this.queryTimeline = ({ username, count, since, until, noreps, norts }) => {
  154. username = username.replace(/^@?(.*)$/, '@$1');
  155. logger.info(`querying timeline of ${username} with config: ${JSON.stringify(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, (count && { count })), (since && { since })), (until && { until })), (noreps && { noreps })), (norts && { norts })))}`);
  156. return this.queryUser(username.slice(1)).then(userNameId => this.get('userTimeline', userNameId.split(':')[1], Object.assign(Object.assign(Object.assign({ expansions: ['attachments.media_keys', 'author_id'], 'tweet.fields': ['created_at'], exclude: [
  157. ...(noreps !== null && noreps !== void 0 ? noreps : true) ? ['replies'] : [],
  158. ...(norts !== null && norts !== void 0 ? norts : false) ? ['retweets'] : [],
  159. ] }, (count && { max_results: Math.min(Math.max(count, 5), 100) })), (since && { since_id: since })), (until && { until_id: until }))).then(tweets => tweets.slice(0, count)));
  160. };
  161. this.workOnTweets = (tweets, sendTweets, refresh = false) => Promise.all(tweets.map(({ data, includes }) => ((this.redis && !refresh) ?
  162. this.redis.waitForProcess(`webshot/${data.id}`, this.webshotDelay * 4)
  163. .then(() => this.redis.getContent(`webshot/${data.id}`)) :
  164. Promise.reject())
  165. .then(content => {
  166. if (content === null)
  167. throw Error();
  168. logger.info(`retrieved cached webshot of tweet ${data.id} from redis database, message chain:`);
  169. const { msg, text, author } = JSON.parse(content);
  170. let cacheId = data.id;
  171. const retweetRef = (data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
  172. if (retweetRef)
  173. cacheId += `,rt:${retweetRef.id}`;
  174. logger.info(JSON.stringify(koishi_1.Message.parseCQCode(msg)));
  175. sendTweets(cacheId, koishi_1.Message.parseCQCode(msg), text, author);
  176. return null;
  177. })
  178. .catch(() => {
  179. this.redis.startProcess(`webshot/${data.id}`);
  180. return { data, includes };
  181. }))).then(tweets => this.webshot(tweets.filter(t => t), (cacheId, msg, text, author) => {
  182. Promise.resolve()
  183. .then(() => {
  184. if (!this.redis)
  185. return;
  186. const [twid, rtid] = cacheId.split(',rt:');
  187. logger.info(`caching webshot of tweet ${twid} to redis database`);
  188. this.redis.cacheContent(`webshot/${twid}`, JSON.stringify({ msg: koishi_1.Message.toCQCode(msg), text, author, rtid })).then(() => this.redis.finishProcess(`webshot/${twid}`));
  189. })
  190. .then(() => sendTweets(cacheId, msg, text, author));
  191. }, this.webshotDelay));
  192. this.handleRetweet = (tweet) => {
  193. const retweetRef = (tweet.data.referenced_tweets || []).find(ref => ref.type === 'retweeted');
  194. if (retweetRef)
  195. return this.client.v2.singleTweet(retweetRef.id, v2SingleParams)
  196. .then(({ data: { referenced_tweets }, includes: { media } }) => (Object.assign(Object.assign({}, tweet), { data: Object.assign(Object.assign({}, tweet.data), { referenced_tweets: [retweetRef, ...(referenced_tweets || [])] }), includes: Object.assign(Object.assign({}, tweet.includes), { media }) })));
  197. return Promise.resolve(tweet);
  198. };
  199. this.getTweet = (id, sender, refresh = false) => ((this.redis && !refresh) ?
  200. this.redis.waitForProcess(`webshot/${id}`, this.webshotDelay * 4)
  201. .then(() => this.redis.getContent(`webshot/${id}`))
  202. .then(content => {
  203. if (content === null)
  204. throw Error();
  205. const { rtid } = JSON.parse(content);
  206. return { data: Object.assign({ id }, rtid && { referenced_tweets: [{ type: 'retweeted', id: rtid }] }) };
  207. }) :
  208. Promise.reject())
  209. .catch(() => this.client.v2.singleTweet(id, v2SingleParams))
  210. .then((tweet) => {
  211. if (tweet.data.text) {
  212. logger.debug(`api returned tweet ${JSON.stringify(tweet)} for query id=${id}`);
  213. return this.handleRetweet(tweet);
  214. }
  215. else {
  216. logger.debug(`skipped querying api as this tweet has been cached`);
  217. }
  218. return tweet;
  219. })
  220. .then((tweet) => this.workOnTweets([tweet], sender, refresh));
  221. this.sendTweets = (config = { reportOnSkip: false, force: false }, ...to) => (id, msg, text, author) => {
  222. to.forEach(subscriber => {
  223. const [twid, rtid] = id.split(',rt:');
  224. const { sourceInfo: source, reportOnSkip, force } = config;
  225. const targetStr = JSON.stringify(subscriber);
  226. const send = () => retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  227. if (count <= maxTrials) {
  228. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  229. }
  230. else {
  231. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  232. terminate(this.bot.sendTo(subscriber, author + text, true));
  233. }
  234. }).then(() => {
  235. if (this.redis) {
  236. logger.info(`caching push status of tweet ${rtid ? `${rtid} (RTed as ${twid})` : twid} for ${targetStr}...`);
  237. return this.redis.cacheForChat(rtid || twid, subscriber);
  238. }
  239. });
  240. ((this.redis && !force) ? this.redis.isCachedForChat(rtid || twid, subscriber) : Promise.resolve(false))
  241. .then(isCached => {
  242. if (isCached) {
  243. logger.info(`skipped subscriber ${targetStr} as tweet ${rtid ? `${rtid} (or its RT)` : twid} has been sent already`);
  244. if (!reportOnSkip)
  245. return;
  246. text = `[最近发送过的推文:${rtid || twid}]`;
  247. msg = author + text;
  248. }
  249. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${targetStr}`);
  250. return send();
  251. });
  252. });
  253. };
  254. this.get = (type, targetId, params) => {
  255. const { since_id, max_results } = params;
  256. const getMore = (res) => {
  257. if (res.errors && res.errors.length > 0) {
  258. const [err] = res.errors;
  259. if (!res.data)
  260. throw err;
  261. if (err.title === 'Authorization Error') {
  262. logger.warn(`non-fatal error while querying ${type} with id ${targetId}, error: ${err.detail}`);
  263. }
  264. }
  265. if (!res.meta.next_token ||
  266. utils_1.BigNumOps.compare(res.tweets.slice(-1)[0].id, since_id || '0') !== 1 ||
  267. !since_id && res.meta.result_count >= max_results)
  268. return res;
  269. return res.fetchNext().then(getMore);
  270. };
  271. if (type === 'listTweets')
  272. delete params.since_id;
  273. return this.client.v2[type](targetId, params).then(getMore)
  274. .then(({ includes, tweets }) => tweets.map((tweet) => ({
  275. data: tweet,
  276. includes: {
  277. media: includes.medias(tweet),
  278. users: [includes.author(tweet)]
  279. }
  280. })))
  281. .then(tweets => Promise.all(tweets.map(this.handleRetweet)));
  282. };
  283. this.work = () => {
  284. const lock = this.lock;
  285. if (this.workInterval < 1)
  286. this.workInterval = 1;
  287. if (lock.feed.length === 0) {
  288. setTimeout(() => {
  289. this.work();
  290. }, this.workInterval * 1000);
  291. return;
  292. }
  293. if (lock.workon >= lock.feed.length)
  294. lock.workon = 0;
  295. if (!lock.threads[lock.feed[lock.workon]] ||
  296. !lock.threads[lock.feed[lock.workon]].subscribers ||
  297. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  298. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  299. delete lock.threads[lock.feed[lock.workon]];
  300. lock.feed.splice(lock.workon, 1);
  301. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  302. this.work();
  303. return;
  304. }
  305. const currentFeed = lock.feed[lock.workon];
  306. logger.debug(`pulling feed ${currentFeed}`);
  307. const promise = new Promise(resolve => {
  308. let job = Promise.resolve();
  309. let id = lock.threads[currentFeed].id;
  310. let endpoint;
  311. let match = /https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/.exec(currentFeed);
  312. if (match) {
  313. endpoint = 'listTweets';
  314. if (match[1] === 'i') {
  315. id = match[2];
  316. }
  317. else if (id === undefined) {
  318. job = job.then(() => this.client.v1.list({
  319. owner_screen_name: match[1],
  320. slug: match[2],
  321. })).then(({ id_str }) => {
  322. lock.threads[currentFeed].id = id = id_str;
  323. });
  324. }
  325. }
  326. else {
  327. match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
  328. if (match) {
  329. endpoint = 'userTimeline';
  330. if (id === undefined) {
  331. job = job.then(() => this.queryUser(match[1].replace(/^@?(.*)$/, '$1'))).then(userNameId => {
  332. lock.threads[currentFeed].id = id = userNameId.split(':')[1];
  333. });
  334. }
  335. }
  336. }
  337. const offset = lock.threads[currentFeed].offset;
  338. job.then(() => this.get(endpoint, id, Object.assign(Object.assign(Object.assign({}, v2SingleParams), { max_results: 20 }), (offset > 0) && { since_id: offset }))).catch((err) => {
  339. if (err.title === 'Not Found Error') {
  340. logger.warn(`error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
  341. lock.threads[currentFeed].subscribers.forEach(subscriber => {
  342. logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
  343. this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
  344. });
  345. }
  346. else {
  347. logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${showApiError(err)}`);
  348. }
  349. return [];
  350. }).then(resolve);
  351. });
  352. promise.then((tweets) => {
  353. logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
  354. const currentThread = lock.threads[currentFeed];
  355. const updateDate = () => currentThread.updatedAt = new Date().toString();
  356. if (tweets.length === 0) {
  357. updateDate();
  358. return;
  359. }
  360. const currentUser = tweets[0].includes.users.find(user => user.id === currentThread.id);
  361. if (currentUser.username !== (0, exports.parseLink)(currentFeed)[1]) {
  362. lock.feed[lock.workon] = (0, exports.linkBuilder)(currentUser.username);
  363. }
  364. const topOfFeed = tweets[0].data.id;
  365. const updateOffset = () => currentThread.offset = topOfFeed;
  366. if (currentThread.offset === '-1') {
  367. updateOffset();
  368. return;
  369. }
  370. if (currentThread.offset === '0')
  371. tweets.splice(1);
  372. return this.workOnTweets(tweets, this.sendTweets({ sourceInfo: `thread ${currentFeed}` }, ...currentThread.subscribers))
  373. .then(updateDate).then(updateOffset);
  374. })
  375. .then(() => {
  376. lock.workon++;
  377. let timeout = this.workInterval * 1000 / lock.feed.length;
  378. if (timeout < 1000)
  379. timeout = 1000;
  380. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  381. setTimeout(() => {
  382. this.work();
  383. }, timeout);
  384. });
  385. };
  386. this.client = new Twitter.TwitterApi({
  387. appKey: opt.consumerKey,
  388. appSecret: opt.consumerSecret,
  389. }).readOnly;
  390. this.lockfile = opt.lockfile;
  391. this.lock = opt.lock;
  392. this.workInterval = opt.workInterval;
  393. this.bot = opt.bot;
  394. this.webshotDelay = opt.webshotDelay;
  395. this.mode = opt.mode;
  396. this.wsUrl = opt.wsUrl;
  397. if (opt.redis)
  398. this.redis = new redis_1.default(opt.redis);
  399. ScreenNameNormalizer._queryUser = this.queryUser;
  400. exports.sendTweet = (idOrQuery, receiver, forceRefresh) => {
  401. const match = /^last(|-\d+)@([^\/?#,]+)((?:,no.*?=[^,]*)*)$/.exec(idOrQuery);
  402. const query = () => this.queryTimeline({
  403. username: match[2],
  404. count: 1 - Number(match[1]),
  405. noreps: { on: true, off: false }[match[3].replace(/.*,noreps=([^,]*).*/, '$1')],
  406. norts: { on: true, off: false }[match[3].replace(/.*,norts=([^,]*).*/, '$1')],
  407. }).then(tweets => tweets.slice(-1)[0].data.id);
  408. (match ? query() : Promise.resolve(idOrQuery))
  409. .then((id) => this.getTweet(id, this.sendTweets({ sourceInfo: `tweet ${id}`, reportOnSkip: true, force: forceRefresh }, receiver), forceRefresh))
  410. .catch((err) => {
  411. if (err.title !== 'Not Found Error') {
  412. logger.warn(`error retrieving tweet: ${showApiError(err)}`);
  413. this.bot.sendTo(receiver, `获取推文时出现错误:${showApiError(err)}`);
  414. }
  415. if (err.resource_type === 'user') {
  416. return this.bot.sendTo(receiver, `找不到用户 ${match[2].replace(/^@?(.*)$/, '@$1')}。`);
  417. }
  418. this.bot.sendTo(receiver, '找不到请求的推文,它可能已被删除。');
  419. });
  420. };
  421. exports.sendTimeline = ({ username, count, since, until, noreps, norts }, receiver) => {
  422. const countNum = Number(count) || 10;
  423. (countNum > 0 ? this.queryTimeline : this.queryTimelineReverse)({
  424. username,
  425. count: Math.abs(countNum),
  426. since: utils_1.BigNumOps.parse(since) || snowflake(new Date(since).getTime()),
  427. until: utils_1.BigNumOps.parse(until) || snowflake(new Date(until).getTime()),
  428. noreps: { on: true, off: false }[noreps],
  429. norts: { on: true, off: false }[norts],
  430. })
  431. .then(tweets => (0, utils_1.chainPromises)(tweets.map(({ data }) => () => this.bot.sendTo(receiver, `\
  432. 编号:${data.id}
  433. 时间:${data.created_at}
  434. 媒体:${(data.attachments || {}).media_keys ? '有' : '无'}
  435. 正文:\n${data.text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`))
  436. .concat(() => this.bot.sendTo(receiver, tweets.length ?
  437. '时间线查询完毕,使用 /twi_view <编号> 查看推文详细内容。' :
  438. '时间线查询完毕,没有找到符合条件的推文。'))))
  439. .catch((err) => {
  440. if (err.title !== 'Not Found Error') {
  441. logger.warn(`error retrieving timeline: ${showApiError(err)}`);
  442. return this.bot.sendTo(receiver, `获取时间线时出现错误:${showApiError(err)}`);
  443. }
  444. this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
  445. });
  446. };
  447. }
  448. }
  449. exports.default = default_1;