twitter.js 9.9 KB

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