twitter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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.sendAllFleets = exports.ScreenNameNormalizer = void 0;
  13. const fs = require("fs");
  14. const path = require("path");
  15. const request = require("request");
  16. const Twitter = require("twitter");
  17. const loggers_1 = require("./loggers");
  18. const utils_1 = require("./utils");
  19. const webshot_1 = require("./webshot");
  20. class ScreenNameNormalizer {
  21. static savePermaFeedForUser(user) {
  22. this.permaFeeds[`https://twitter.com/${user.screen_name}`] = `https://twitter.com/i/user/${user.id_str}`;
  23. }
  24. static normalizeLive(username) {
  25. return __awaiter(this, void 0, void 0, function* () {
  26. if (this._queryUser) {
  27. return yield this._queryUser(username)
  28. .catch((err) => {
  29. if (err[0].code !== 50) {
  30. logger.warn(`error looking up user: ${err[0].message}`);
  31. return username;
  32. }
  33. return null;
  34. });
  35. }
  36. return this.normalize(username);
  37. });
  38. }
  39. }
  40. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  41. ScreenNameNormalizer.permaFeeds = {};
  42. ScreenNameNormalizer.normalize = (username) => username.toLowerCase().replace(/^@/, '');
  43. let sendAllFleets = (username, receiver) => {
  44. throw Error();
  45. };
  46. exports.sendAllFleets = sendAllFleets;
  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.wsUrl, this.mode, () => setTimeout(this.work, this.workInterval * 1000));
  78. };
  79. this.queryUser = (username) => this.client.get('users/show', { screen_name: username })
  80. .then((user) => {
  81. ScreenNameNormalizer.savePermaFeedForUser(user);
  82. return user.screen_name;
  83. });
  84. this.workOnFleets = (user, fleets, sendFleets) => {
  85. const uploader = (message, lastResort) => {
  86. let timeout = uploadTimeout;
  87. return retryOnError(() => this.bot.uploadPic(message, timeout).then(() => message), (_, count, terminate) => {
  88. if (count <= maxTrials) {
  89. timeout *= (count + 2) / (count + 1);
  90. logger.warn(`retry uploading for the ${ordinal(count)} time...`);
  91. }
  92. else {
  93. logger.warn(`${count - 1} consecutive failures while uploading, trying plain text instead...`);
  94. terminate(lastResort());
  95. }
  96. });
  97. };
  98. return this.webshot(user, fleets, uploader, sendFleets, this.webshotDelay);
  99. };
  100. this.sendFleets = (source, ...to) => (msg, text) => {
  101. to.forEach(subscriber => {
  102. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  103. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  104. if (count <= maxTrials) {
  105. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  106. }
  107. else {
  108. logger.warn(`${count - 1} consecutive failures while sending` +
  109. 'message chain, trying plain text instead...');
  110. terminate(this.bot.sendTo(subscriber, text));
  111. }
  112. });
  113. });
  114. };
  115. this.getFleets = (userID) => new Promise((resolve, reject) => {
  116. const endpoint = `https://api.twitter.com/fleets/v1/user_fleets?user_id=${userID}`;
  117. this.privateClient.get(endpoint, (error, fleetFeed, _) => {
  118. if (error)
  119. reject(error);
  120. else
  121. resolve(fleetFeed);
  122. });
  123. });
  124. this.work = () => {
  125. const lock = this.lock;
  126. if (this.workInterval < 1)
  127. this.workInterval = 1;
  128. if (lock.feed.length === 0) {
  129. setTimeout(() => {
  130. this.work();
  131. }, this.workInterval * 1000);
  132. return;
  133. }
  134. if (lock.workon >= lock.feed.length)
  135. lock.workon = 0;
  136. if (!lock.threads[lock.feed[lock.workon]] ||
  137. !lock.threads[lock.feed[lock.workon]].subscribers ||
  138. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  139. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  140. delete lock.threads[lock.feed[lock.workon]];
  141. lock.feed.splice(lock.workon, 1);
  142. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  143. this.work();
  144. return;
  145. }
  146. const currentFeed = lock.feed[lock.workon];
  147. logger.debug(`pulling feed ${currentFeed}`);
  148. let user;
  149. let match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
  150. if (match)
  151. match = /https:\/\/twitter.com\/i\/user\/([^\/]+)/.exec(lock.threads[currentFeed].permaFeed);
  152. if (!match) {
  153. logger.error(`cannot get endpoint for feed ${currentFeed}`);
  154. return;
  155. }
  156. this.client.get('users/show', { user_id: match[1] })
  157. .then((fullUser) => { user = fullUser; return this.getFleets(match[1]); })
  158. .catch(error => {
  159. logger.error(`unhandled error on fetching fleets for ${currentFeed}: ${JSON.stringify(error)}`);
  160. })
  161. .then((fleetFeed) => {
  162. logger.debug(`private api returned ${JSON.stringify(fleetFeed)} for feed ${currentFeed}`);
  163. logger.debug(`api returned ${JSON.stringify(user)} for owner of feed ${currentFeed}`);
  164. const currentThread = lock.threads[currentFeed];
  165. const updateDate = () => currentThread.updatedAt = new Date().toString();
  166. if (!fleetFeed || fleetFeed.fleet_threads.length === 0) {
  167. updateDate();
  168. return;
  169. }
  170. let fleets = fleetFeed.fleet_threads[0].fleets;
  171. const bottomOfFeed = fleets.slice(-1)[0].fleet_id.substring(3);
  172. const updateOffset = () => currentThread.offset = bottomOfFeed;
  173. if (currentThread.offset === '-1') {
  174. updateOffset();
  175. return;
  176. }
  177. if (currentThread.offset !== '0') {
  178. const readCount = fleets.findIndex(fleet => Number(utils_1.BigNumOps.plus(fleet.fleet_id.substring(3), `-${currentThread.offset}`)) > 0);
  179. if (readCount === -1)
  180. return;
  181. fleets = fleets.slice(readCount);
  182. }
  183. return this.workOnFleets(user, fleets, this.sendFleets(`thread ${currentFeed}`, ...currentThread.subscribers))
  184. .then(updateDate).then(updateOffset);
  185. })
  186. .then(() => {
  187. lock.workon++;
  188. let timeout = this.workInterval * 1000 / lock.feed.length;
  189. if (timeout < 1000)
  190. timeout = 1000;
  191. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  192. setTimeout(() => {
  193. this.work();
  194. }, timeout);
  195. });
  196. };
  197. this.client = new Twitter({
  198. consumer_key: opt.consumerKey,
  199. consumer_secret: opt.consumerSecret,
  200. access_token_key: opt.accessTokenKey,
  201. access_token_secret: opt.accessTokenSecret,
  202. });
  203. this.privateClient = new Twitter({
  204. bearer_token: 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  205. });
  206. this.privateClient.request = request.defaults({
  207. headers: Object.assign(Object.assign({}, this.privateClient.options.request_options.headers), { 'Content-Type': 'application/x-www-form-urlencoded', Cookie: `auth_token=${opt.privateAuthToken}; ct0=${opt.privateCsrfToken};`, 'X-CSRF-Token': opt.privateCsrfToken }),
  208. });
  209. this.lockfile = opt.lockfile;
  210. this.lock = opt.lock;
  211. this.workInterval = opt.workInterval;
  212. this.bot = opt.bot;
  213. this.mode = opt.mode;
  214. this.wsUrl = opt.wsUrl;
  215. ScreenNameNormalizer._queryUser = this.queryUser;
  216. exports.sendAllFleets = (username, receiver) => {
  217. this.client.get('users/show', { screen_name: username })
  218. .then((user) => {
  219. const feed = `https://twitter.com/${user.screen_name}`;
  220. return this.getFleets(user.id_str)
  221. .catch(error => {
  222. logger.error(`unhandled error while fetching fleets for ${feed}: ${JSON.stringify(error)}`);
  223. this.bot.sendTo(receiver, `获取 Fleets 时出现错误:${error}`);
  224. })
  225. .then((fleetFeed) => {
  226. if (!fleetFeed || fleetFeed.fleet_threads.length === 0) {
  227. this.bot.sendTo(receiver, `当前用户(@${user.screen_name})没有可用的 Fleets。`);
  228. return;
  229. }
  230. this.workOnFleets(user, fleetFeed.fleet_threads[0].fleets, this.sendFleets(`thread ${feed}`, receiver));
  231. });
  232. })
  233. .catch((err) => {
  234. if (err[0].code !== 50) {
  235. logger.warn(`error looking up user: ${err[0].message}, unable to fetch fleets`);
  236. }
  237. this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
  238. });
  239. };
  240. }
  241. }
  242. exports.default = default_1;