twitter.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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 retryInterval = 1500;
  50. const ordinal = (n) => {
  51. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  52. case 1:
  53. return `${n}st`;
  54. case 2:
  55. return `${n}nd`;
  56. case 3:
  57. return `${n}rd`;
  58. default:
  59. return `${n}th`;
  60. }
  61. };
  62. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  63. const retry = (reason, count) => {
  64. setTimeout(() => {
  65. let terminate = false;
  66. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  67. if (!terminate)
  68. doWork().then(resolve).catch(error => retry(error, count + 1));
  69. }, retryInterval);
  70. };
  71. doWork().then(resolve).catch(error => retry(error, 1));
  72. });
  73. class default_1 {
  74. constructor(opt) {
  75. this.launch = () => {
  76. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => setTimeout(this.work, this.workInterval * 1000));
  77. };
  78. this.queryUser = (username) => this.client.get('users/show', { screen_name: username })
  79. .then((user) => {
  80. ScreenNameNormalizer.savePermaFeedForUser(user);
  81. return user.screen_name;
  82. });
  83. this.workOnFleets = (user, fleets, sendFleets) => this.webshot(user, fleets, sendFleets, this.webshotDelay);
  84. this.sendFleets = (source, ...to) => (msg, text) => {
  85. to.forEach(subscriber => {
  86. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  87. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  88. if (count <= maxTrials) {
  89. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  90. }
  91. else {
  92. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  93. terminate(this.bot.sendTo(subscriber, text, true));
  94. }
  95. });
  96. });
  97. };
  98. this.getFleets = (userID) => new Promise((resolve, reject) => {
  99. const endpoint = `https://api.twitter.com/fleets/v1/user_fleets?user_id=${userID}`;
  100. this.privateClient.get(endpoint, (error, fleetFeed, _) => {
  101. if (error)
  102. reject(error);
  103. else
  104. resolve(fleetFeed);
  105. });
  106. });
  107. this.work = () => {
  108. const lock = this.lock;
  109. if (this.workInterval < 1)
  110. this.workInterval = 1;
  111. if (lock.feed.length === 0) {
  112. setTimeout(() => {
  113. this.work();
  114. }, this.workInterval * 1000);
  115. return;
  116. }
  117. if (lock.workon >= lock.feed.length)
  118. lock.workon = 0;
  119. if (!lock.threads[lock.feed[lock.workon]] ||
  120. !lock.threads[lock.feed[lock.workon]].subscribers ||
  121. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  122. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  123. delete lock.threads[lock.feed[lock.workon]];
  124. lock.feed.splice(lock.workon, 1);
  125. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  126. this.work();
  127. return;
  128. }
  129. const currentFeed = lock.feed[lock.workon];
  130. logger.debug(`pulling feed ${currentFeed}`);
  131. let user;
  132. let match = /https:\/\/twitter.com\/([^\/]+)/.exec(currentFeed);
  133. if (match)
  134. match = /https:\/\/twitter.com\/i\/user\/([^\/]+)/.exec(lock.threads[currentFeed].permaFeed);
  135. if (!match) {
  136. logger.error(`cannot get endpoint for feed ${currentFeed}`);
  137. return;
  138. }
  139. this.client.get('users/show', { user_id: match[1] })
  140. .then((fullUser) => { user = fullUser; return this.getFleets(match[1]); })
  141. .catch(error => {
  142. logger.error(`unhandled error on fetching fleets for ${currentFeed}: ${JSON.stringify(error)}`);
  143. })
  144. .then((fleetFeed) => {
  145. logger.debug(`private api returned ${JSON.stringify(fleetFeed)} for feed ${currentFeed}`);
  146. logger.debug(`api returned ${JSON.stringify(user)} for owner of feed ${currentFeed}`);
  147. const currentThread = lock.threads[currentFeed];
  148. const updateDate = () => currentThread.updatedAt = new Date().toString();
  149. if (!fleetFeed || fleetFeed.fleet_threads.length === 0) {
  150. updateDate();
  151. return;
  152. }
  153. let fleets = fleetFeed.fleet_threads[0].fleets;
  154. const bottomOfFeed = fleets.slice(-1)[0].fleet_id.substring(3);
  155. const updateOffset = () => currentThread.offset = bottomOfFeed;
  156. if (currentThread.offset === '-1') {
  157. updateOffset();
  158. return;
  159. }
  160. if (currentThread.offset !== '0') {
  161. const readCount = fleets.findIndex(fleet => Number(utils_1.BigNumOps.plus(fleet.fleet_id.substring(3), `-${currentThread.offset}`)) > 0);
  162. if (readCount === -1)
  163. return;
  164. fleets = fleets.slice(readCount);
  165. }
  166. return this.workOnFleets(user, fleets, this.sendFleets(`thread ${currentFeed}`, ...currentThread.subscribers))
  167. .then(updateDate).then(updateOffset);
  168. })
  169. .then(() => {
  170. lock.workon++;
  171. let timeout = this.workInterval * 1000 / lock.feed.length;
  172. if (timeout < 1000)
  173. timeout = 1000;
  174. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  175. setTimeout(() => {
  176. this.work();
  177. }, timeout);
  178. });
  179. };
  180. this.client = new Twitter({
  181. consumer_key: opt.consumerKey,
  182. consumer_secret: opt.consumerSecret,
  183. access_token_key: opt.accessTokenKey,
  184. access_token_secret: opt.accessTokenSecret,
  185. });
  186. this.privateClient = new Twitter({
  187. bearer_token: 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
  188. });
  189. this.privateClient.request = request.defaults({
  190. 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 }),
  191. });
  192. this.lockfile = opt.lockfile;
  193. this.lock = opt.lock;
  194. this.workInterval = opt.workInterval;
  195. this.bot = opt.bot;
  196. this.mode = opt.mode;
  197. this.wsUrl = opt.wsUrl;
  198. ScreenNameNormalizer._queryUser = this.queryUser;
  199. exports.sendAllFleets = (username, receiver) => {
  200. this.client.get('users/show', { screen_name: username })
  201. .then((user) => {
  202. const feed = `https://twitter.com/${user.screen_name}`;
  203. return this.getFleets(user.id_str)
  204. .catch(error => {
  205. logger.error(`unhandled error while fetching fleets for ${feed}: ${JSON.stringify(error)}`);
  206. this.bot.sendTo(receiver, `获取 Fleets 时出现错误:${error}`);
  207. })
  208. .then((fleetFeed) => {
  209. if (!fleetFeed || fleetFeed.fleet_threads.length === 0) {
  210. this.bot.sendTo(receiver, `当前用户(@${user.screen_name})没有可用的 Fleets。`);
  211. return;
  212. }
  213. this.workOnFleets(user, fleetFeed.fleet_threads[0].fleets, this.sendFleets(`thread ${feed}`, receiver));
  214. });
  215. })
  216. .catch((err) => {
  217. if (err[0].code !== 50) {
  218. logger.warn(`error looking up user: ${err[0].message}, unable to fetch fleets`);
  219. }
  220. this.bot.sendTo(receiver, `找不到用户 ${username.replace(/^@?(.*)$/, '@$1')}。`);
  221. });
  222. };
  223. }
  224. }
  225. exports.default = default_1;