twitter.js 21 KB

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