twitter.js 16 KB

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