twitter.js 19 KB

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