twitter.js 15 KB

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