twitter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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.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 webshot_1 = require("./webshot");
  18. class ScreenNameNormalizer {
  19. static normalizeLive(username) {
  20. return __awaiter(this, void 0, void 0, function* () {
  21. if (this._queryUser) {
  22. return yield this._queryUser(username)
  23. .catch((err) => {
  24. if (err[0].code !== 50) {
  25. logger.warn(`error looking up user: ${err[0].message}`);
  26. return username;
  27. }
  28. return null;
  29. });
  30. }
  31. return this.normalize(username);
  32. });
  33. }
  34. }
  35. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  36. ScreenNameNormalizer.normalize = (username) => username.toLowerCase().replace(/^@/, '');
  37. exports.sendTweet = (id, receiver) => {
  38. throw Error();
  39. };
  40. const logger = loggers_1.getLogger('twitter');
  41. const maxTrials = 3;
  42. const uploadTimeout = 10000;
  43. const retryInterval = 1500;
  44. const ordinal = (n) => {
  45. switch ((~~(n / 10) % 10 === 1) ? 0 : n % 10) {
  46. case 1:
  47. return `${n}st`;
  48. case 2:
  49. return `${n}nd`;
  50. case 3:
  51. return `${n}rd`;
  52. default:
  53. return `${n}th`;
  54. }
  55. };
  56. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  57. const retry = (reason, count) => {
  58. setTimeout(() => {
  59. let terminate = false;
  60. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  61. if (!terminate)
  62. doWork().then(resolve).catch(error => retry(error, count + 1));
  63. }, retryInterval);
  64. };
  65. doWork().then(resolve).catch(error => retry(error, 1));
  66. });
  67. class default_1 {
  68. constructor(opt) {
  69. this.launch = () => {
  70. this.webshot = new webshot_1.default(this.mode, () => setTimeout(this.work, this.workInterval * 1000));
  71. };
  72. this.queryUser = (username) => this.client.get('users/show', { screen_name: username })
  73. .then((user) => user.screen_name);
  74. this.workOnTweets = (tweets, sendTweets) => {
  75. const uploader = (message, lastResort) => {
  76. let timeout = uploadTimeout;
  77. return retryOnError(() => this.bot.uploadPic(message, timeout).then(() => message), (_, count, terminate) => {
  78. if (count <= maxTrials) {
  79. timeout *= (count + 2) / (count + 1);
  80. logger.warn(`retry uploading for the ${ordinal(count)} time...`);
  81. }
  82. else {
  83. logger.warn(`${count - 1} consecutive failures while uploading, trying plain text instead...`);
  84. terminate(lastResort());
  85. }
  86. });
  87. };
  88. return this.webshot(tweets, uploader, sendTweets, this.webshotDelay);
  89. };
  90. this.getTweet = (id, sender) => {
  91. const endpoint = 'statuses/show';
  92. const config = {
  93. id,
  94. tweet_mode: 'extended',
  95. };
  96. return this.client.get(endpoint, config)
  97. .then((tweet) => this.workOnTweets([tweet], sender));
  98. };
  99. this.sendTweets = (source, ...to) => (msg, text, author) => {
  100. to.forEach(subscriber => {
  101. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  102. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  103. if (count <= maxTrials) {
  104. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  105. }
  106. else {
  107. logger.warn(`${count - 1} consecutive failures while sending` +
  108. 'message chain, trying plain text instead...');
  109. terminate(this.bot.sendTo(subscriber, author + text));
  110. }
  111. });
  112. });
  113. };
  114. this.work = () => {
  115. const lock = this.lock;
  116. if (this.workInterval < 1)
  117. this.workInterval = 1;
  118. if (lock.feed.length === 0) {
  119. setTimeout(() => {
  120. this.work();
  121. }, this.workInterval * 1000);
  122. return;
  123. }
  124. if (lock.workon >= lock.feed.length)
  125. lock.workon = 0;
  126. if (!lock.threads[lock.feed[lock.workon]] ||
  127. !lock.threads[lock.feed[lock.workon]].subscribers ||
  128. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  129. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  130. delete lock.threads[lock.feed[lock.workon]];
  131. lock.feed.splice(lock.workon, 1);
  132. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  133. this.work();
  134. return;
  135. }
  136. const currentFeed = lock.feed[lock.workon];
  137. logger.debug(`pulling feed ${currentFeed}`);
  138. const promise = new Promise(resolve => {
  139. let match = currentFeed.match(/https:\/\/twitter.com\/([^\/]+)\/lists\/([^\/]+)/);
  140. let config;
  141. let endpoint;
  142. if (match) {
  143. if (match[1] === 'i') {
  144. config = {
  145. list_id: match[2],
  146. tweet_mode: 'extended',
  147. };
  148. }
  149. else {
  150. config = {
  151. owner_screen_name: match[1],
  152. slug: match[2],
  153. tweet_mode: 'extended',
  154. };
  155. }
  156. endpoint = 'lists/statuses';
  157. }
  158. else {
  159. match = currentFeed.match(/https:\/\/twitter.com\/([^\/]+)/);
  160. if (match) {
  161. config = {
  162. screen_name: match[1],
  163. exclude_replies: false,
  164. tweet_mode: 'extended',
  165. };
  166. endpoint = 'statuses/user_timeline';
  167. }
  168. }
  169. if (endpoint) {
  170. const offset = lock.threads[currentFeed].offset;
  171. if (offset > 0)
  172. config.since_id = offset;
  173. this.client.get(endpoint, config, (error, tweets, response) => {
  174. if (error) {
  175. if (error instanceof Array && error.length > 0 && error[0].code === 34) {
  176. logger.warn(`error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  177. lock.threads[currentFeed].subscribers.forEach(subscriber => {
  178. logger.info(`sending notfound message of ${currentFeed} to ${JSON.stringify(subscriber)}`);
  179. this.bot.sendTo(subscriber, `链接 ${currentFeed} 指向的用户或列表不存在,请退订。`).catch();
  180. });
  181. }
  182. else {
  183. logger.error(`unhandled error on fetching tweets for ${currentFeed}: ${JSON.stringify(error)}`);
  184. }
  185. resolve();
  186. }
  187. else
  188. resolve(tweets);
  189. });
  190. }
  191. });
  192. promise.then((tweets) => {
  193. logger.debug(`api returned ${JSON.stringify(tweets)} for feed ${currentFeed}`);
  194. const currentThread = lock.threads[currentFeed];
  195. const updateDate = () => currentThread.updatedAt = new Date().toString();
  196. if (!tweets || tweets.length === 0) {
  197. updateDate();
  198. return;
  199. }
  200. const topOfFeed = tweets[0].id_str;
  201. const updateOffset = () => currentThread.offset = topOfFeed;
  202. if (currentThread.offset === '-1') {
  203. updateOffset();
  204. return;
  205. }
  206. if (currentThread.offset === '0')
  207. tweets.splice(1);
  208. return this.workOnTweets(tweets, this.sendTweets(`thread ${currentFeed}`, ...currentThread.subscribers))
  209. .then(updateDate).then(updateOffset);
  210. })
  211. .then(() => {
  212. lock.workon++;
  213. let timeout = this.workInterval * 1000 / lock.feed.length;
  214. if (timeout < 1000)
  215. timeout = 1000;
  216. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  217. setTimeout(() => {
  218. this.work();
  219. }, timeout);
  220. });
  221. };
  222. this.client = new Twitter({
  223. consumer_key: opt.consumer_key,
  224. consumer_secret: opt.consumer_secret,
  225. access_token_key: opt.access_token_key,
  226. access_token_secret: opt.access_token_secret,
  227. });
  228. this.lockfile = opt.lockfile;
  229. this.lock = opt.lock;
  230. this.workInterval = opt.workInterval;
  231. this.bot = opt.bot;
  232. this.webshotDelay = opt.webshotDelay;
  233. this.mode = opt.mode;
  234. ScreenNameNormalizer._queryUser = this.queryUser;
  235. exports.sendTweet = (id, receiver) => {
  236. this.getTweet(id, this.sendTweets(`tweet ${id}`, receiver))
  237. .catch((err) => {
  238. if (err[0].code !== 144) {
  239. logger.warn(`error retrieving tweet: ${err[0].message}`);
  240. this.bot.sendTo(receiver, `获取推文时出现错误:${err[0].message}`);
  241. }
  242. this.bot.sendTo(receiver, '找不到请求的推文,它可能已被删除。');
  243. });
  244. };
  245. }
  246. }
  247. exports.default = default_1;