twitter.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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.sendAllStories = exports.ScreenNameNormalizer = exports.SessionManager = exports.parseLink = exports.linkBuilder = void 0;
  13. const crypto = require("crypto");
  14. const fs = require("fs");
  15. const http = require("http");
  16. const path = require("path");
  17. const url_1 = require("url");
  18. const util_1 = require("util");
  19. const instagram_private_api_1 = require("instagram-private-api");
  20. const socks_proxy_agent_1 = require("socks-proxy-agent");
  21. const loggers_1 = require("./loggers");
  22. const utils_1 = require("./utils");
  23. const webshot_1 = require("./webshot");
  24. const parseLink = (link) => {
  25. let match = /instagram\.com\/stories\/([^\/?#]+)\/(\d+)/.exec(link);
  26. if (match)
  27. return { userName: ScreenNameNormalizer.normalize(match[1]).split(':')[0], storyId: match[2] };
  28. match =
  29. /instagram\.com\/([^\/?#]+)/.exec(link) ||
  30. /^([^\/?#]+)$/.exec(link);
  31. if (match)
  32. return { userName: ScreenNameNormalizer.normalize(match[1]).split(':')[0] };
  33. return;
  34. };
  35. exports.parseLink = parseLink;
  36. const linkBuilder = (config) => {
  37. if (!config.userName)
  38. return;
  39. if (!config.storyId)
  40. return `https://www.instagram.com/${config.userName}/`;
  41. return `https://www.instagram.com/stories/${config.userName}/${config.storyId}/`;
  42. };
  43. exports.linkBuilder = linkBuilder;
  44. class SessionManager {
  45. constructor(client, file, credentials, codeServicePort) {
  46. this.init = () => {
  47. this.ig.state.generateDevice(this.username);
  48. this.ig.request.end$.subscribe(() => { this.save(); });
  49. const filePath = path.resolve(this.lockfile);
  50. if (fs.existsSync(filePath)) {
  51. try {
  52. const serialized = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  53. return this.ig.state.deserialize(serialized).then(() => {
  54. logger.info(`successfully loaded client session cookies for user ${this.username}`);
  55. });
  56. }
  57. catch (err) {
  58. logger.error(`failed to load client session cookies from file ${this.lockfile}: `, err);
  59. return Promise.resolve();
  60. }
  61. }
  62. else {
  63. return this.login().catch((err) => {
  64. logger.error(`error while trying to log in as user ${this.username}, error: ${err}`);
  65. logger.warn('attempting to retry after 1 minute...');
  66. if (fs.existsSync(filePath))
  67. fs.unlinkSync(filePath);
  68. util_1.promisify(setTimeout)(60000).then(this.init);
  69. });
  70. }
  71. };
  72. this.handle2FA = (submitter) => new Promise((resolve, reject) => {
  73. const token = crypto.randomBytes(20).toString('hex');
  74. logger.info('please submit the code with a one-time token from your browser with this path:');
  75. logger.info(`/confirm-2fa?code=<the code you received>&token=${token}`);
  76. let working;
  77. const server = http.createServer((req, res) => {
  78. const { pathname, query } = url_1.parse(req.url, true);
  79. if (!working && pathname === '/confirm-2fa' && query.token === token &&
  80. typeof (query.code) === 'string' && /^\d{6}$/.test(query.code)) {
  81. const code = query.code;
  82. logger.debug(`received code: ${code}`);
  83. working = true;
  84. submitter(code)
  85. .then(response => { res.write('OK'); res.end(); server.close(() => resolve(response)); })
  86. .catch(err => { res.write('Error'); res.end(); reject(err); })
  87. .finally(() => { working = false; });
  88. }
  89. });
  90. server.listen(this.codeServicePort);
  91. });
  92. this.login = () => this.ig.simulate.preLoginFlow()
  93. .then(() => this.ig.account.login(this.username, this.password))
  94. .catch((err) => {
  95. if (err instanceof instagram_private_api_1.IgLoginTwoFactorRequiredError) {
  96. const { two_factor_identifier, totp_two_factor_on } = err.response.body.two_factor_info;
  97. logger.debug(`2FA info: ${JSON.stringify(err.response.body.two_factor_info)}`);
  98. logger.info(`login is requesting two-factor authentication via ${totp_two_factor_on ? 'TOTP' : 'SMS'}`);
  99. return this.handle2FA(code => this.ig.account.twoFactorLogin({
  100. username: this.username,
  101. verificationCode: code,
  102. twoFactorIdentifier: two_factor_identifier,
  103. verificationMethod: totp_two_factor_on ? '0' : '1',
  104. }));
  105. }
  106. throw err;
  107. })
  108. .then(user => new Promise(resolve => {
  109. logger.info(`successfully logged in as ${this.username}`);
  110. process.nextTick(() => resolve(this.ig.simulate.postLoginFlow().then(() => user)));
  111. }));
  112. this.save = () => this.ig.state.serialize()
  113. .then((serialized) => {
  114. delete serialized.constants;
  115. return fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(serialized, null, 2), 'utf-8');
  116. });
  117. this.ig = client;
  118. this.lockfile = file;
  119. [this.username, this.password] = credentials;
  120. this.codeServicePort = codeServicePort;
  121. }
  122. }
  123. exports.SessionManager = SessionManager;
  124. class ScreenNameNormalizer {
  125. static normalizeLive(username) {
  126. return __awaiter(this, void 0, void 0, function* () {
  127. if (this._queryUser) {
  128. return yield this._queryUser(username)
  129. .catch((err) => {
  130. if (!(err instanceof instagram_private_api_1.IgExactUserNotFoundError)) {
  131. logger.warn(`error looking up user: ${err.message}`);
  132. return `${username}:`;
  133. }
  134. return null;
  135. });
  136. }
  137. return this.normalize(username);
  138. });
  139. }
  140. }
  141. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  142. ScreenNameNormalizer.normalize = (username) => `${username.toLowerCase().replace(/^@/, '')}:`;
  143. let sendAllStories = (segmentId, receiver) => {
  144. throw Error();
  145. };
  146. exports.sendAllStories = sendAllStories;
  147. const logger = loggers_1.getLogger('instagram');
  148. const maxTrials = 3;
  149. const retryInterval = 1500;
  150. const ordinal = (n) => {
  151. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  152. case 1:
  153. return `${n}st`;
  154. case 2:
  155. return `${n}nd`;
  156. case 3:
  157. return `${n}rd`;
  158. default:
  159. return `${n}th`;
  160. }
  161. };
  162. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  163. const retry = (reason, count) => {
  164. setTimeout(() => {
  165. let terminate = false;
  166. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  167. if (!terminate)
  168. doWork().then(resolve).catch(error => retry(error, count + 1));
  169. }, retryInterval);
  170. };
  171. doWork().then(resolve).catch(error => retry(error, 1));
  172. });
  173. class default_1 {
  174. constructor(opt) {
  175. this.launch = () => {
  176. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => {
  177. setTimeout(this.workForAll, this.workInterval * 1000);
  178. setTimeout(() => {
  179. this.work();
  180. setInterval(() => { this.pullOrders = utils_1.Arr.shuffle(this.pullOrders); }, 21600000);
  181. setInterval(this.workForAll, this.workInterval * 10000);
  182. }, this.workInterval * 1200);
  183. });
  184. };
  185. this.queryUser = (rawUserName) => {
  186. const username = ScreenNameNormalizer.normalize(rawUserName).split(':')[0];
  187. if (username in this.cache) {
  188. return Promise.resolve(`${username}:${this.cache[username].user.pk}`);
  189. }
  190. return this.client.user.searchExact(username)
  191. .then(user => {
  192. logger.info(`initialized cache item for user ${user.full_name} (@${username})`);
  193. this.cache[user.username] = { user, stories: {}, pullOrder: 0 };
  194. return `${user.username}:${user.pk}`;
  195. });
  196. };
  197. this.workOnMedia = (mediaItems, sendMedia) => this.webshot(mediaItems, sendMedia, this.webshotDelay);
  198. this.sendStories = (source, ...to) => (msg, text, author) => {
  199. to.forEach(subscriber => {
  200. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  201. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  202. if (count <= maxTrials) {
  203. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  204. }
  205. else {
  206. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  207. terminate(this.bot.sendTo(subscriber, author + text, true));
  208. }
  209. });
  210. });
  211. };
  212. this.cache = {};
  213. this.workForAll = () => {
  214. if (this.isInactiveTime)
  215. return;
  216. logger.debug(`current cache: ${JSON.stringify(this.cache)}`);
  217. utils_1.chainPromises(Object.entries(this.lock.threads).map(([feed, thread]) => {
  218. const id = thread.id;
  219. const userName = parseLink(feed).userName;
  220. logger.debug(`preparing to add user @${userName} to next pull task...`);
  221. return (map = {}) => {
  222. if (userName in this.cache) {
  223. const item = this.cache[userName];
  224. if (item.pullOrder === 0)
  225. item.pullOrder = -1;
  226. return Promise.resolve(Object.assign(map, { [id]: item.user }));
  227. }
  228. return util_1.promisify(setTimeout)((Math.random() * 2 + 1) * 5000).then(() => this.client.user.info(id).then(user => {
  229. logger.info(`initialized cache item for user ${user.full_name} (@${userName})`);
  230. this.cache[userName] = { user, stories: {}, pullOrder: -1 };
  231. return Object.assign(map, { [id]: user });
  232. }));
  233. };
  234. }))
  235. .then(idToUserMap => {
  236. const userIdCache = Object.values(this.cache).some(item => item.pullOrder < 0) ?
  237. this.pullOrders = utils_1.Arr.shuffle(Object.keys(idToUserMap)).map(Number) :
  238. this.pullOrders;
  239. return utils_1.chainPromises(utils_1.Arr.chunk(userIdCache, 20).map(userIds => () => {
  240. logger.info(`pulling stories from users:${userIds.map(id => ` @${idToUserMap[id].username}`)}`);
  241. return this.client.feed.reelsMedia({ userIds }).items()
  242. .then(storyItems => storyItems.forEach(item => {
  243. if (!(item.pk in this.cache[idToUserMap[item.user.pk].username].stories)) {
  244. this.cache[idToUserMap[item.user.pk].username].stories[item.pk] = item;
  245. }
  246. }))
  247. .finally(() => Object.values(this.lock.threads).forEach(thread => {
  248. if (userIds.includes(thread.id))
  249. thread.updatedAt = new Date().toString();
  250. }));
  251. }), (lp1, lp2) => () => lp1().then(() => util_1.promisify(setTimeout)(this.workInterval * 1000).then(lp2)));
  252. })
  253. .catch((error) => {
  254. if (error instanceof instagram_private_api_1.IgNetworkError) {
  255. logger.warn(`error while fetching stories for all: ${JSON.stringify(error.cause)}`);
  256. }
  257. else if (error instanceof instagram_private_api_1.IgLoginRequiredError) {
  258. logger.warn('login required, logging in again...');
  259. this.session.login().then(this.workForAll);
  260. }
  261. else {
  262. logger.error(`unhandled error on fetching media for all: ${error}`);
  263. }
  264. });
  265. };
  266. this.work = () => {
  267. const lock = this.lock;
  268. if (this.workInterval < 1)
  269. this.workInterval = 1;
  270. if (this.isInactiveTime || lock.feed.length === 0) {
  271. setTimeout(this.work, this.workInterval * 1000);
  272. return;
  273. }
  274. if (lock.workon >= lock.feed.length)
  275. lock.workon = 0;
  276. const currentFeed = lock.feed[lock.workon];
  277. if (!lock.threads[currentFeed] ||
  278. !lock.threads[currentFeed].subscribers ||
  279. lock.threads[currentFeed].subscribers.length === 0) {
  280. logger.warn(`nobody subscribes thread ${currentFeed}, removing from feed`);
  281. delete lock.threads[currentFeed];
  282. this.cache[parseLink(currentFeed).userName].pullOrder = 0;
  283. lock.feed.splice(lock.workon, 1);
  284. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  285. this.work();
  286. return;
  287. }
  288. logger.debug(`searching for new items from ${currentFeed} in cache`);
  289. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(currentFeed);
  290. if (!match) {
  291. logger.error(`current feed "${currentFeed}" is invalid, please remove this feed manually`);
  292. lock.workon++;
  293. setTimeout(this.work, this.workInterval * 1000);
  294. return;
  295. }
  296. const cachedFeed = this.cache[match[1]];
  297. if (!cachedFeed) {
  298. setTimeout(this.work, this.workInterval * 1000);
  299. return;
  300. }
  301. const newer = (item) => utils_1.BigNumOps.compare(item.pk, lock.threads[currentFeed].offset) > 0;
  302. const promise = Promise.resolve(Object.values(cachedFeed.stories)
  303. .filter(newer)
  304. .map(story => (Object.assign(Object.assign({}, story), { user: cachedFeed.user })))
  305. .sort((i1, i2) => utils_1.BigNumOps.compare(i2.pk, i1.pk)));
  306. promise.then((mediaItems) => {
  307. const currentThread = lock.threads[currentFeed];
  308. if (!mediaItems || mediaItems.length === 0)
  309. return;
  310. const topOfFeed = mediaItems[0].pk;
  311. const updateOffset = () => currentThread.offset = topOfFeed;
  312. if (currentThread.offset === '-1') {
  313. updateOffset();
  314. return;
  315. }
  316. if (currentThread.offset === '0')
  317. mediaItems.splice(1);
  318. return this.workOnMedia(mediaItems, this.sendStories(`thread ${currentFeed}`, ...currentThread.subscribers))
  319. .then(updateOffset);
  320. })
  321. .then(() => {
  322. lock.workon++;
  323. let timeout = this.workInterval * 1000 / lock.feed.length;
  324. if (timeout < 1000)
  325. timeout = 1000;
  326. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  327. setTimeout(this.work, timeout);
  328. });
  329. };
  330. this.client = new instagram_private_api_1.IgApiClient();
  331. if (opt.proxyUrl) {
  332. try {
  333. const url = new URL(opt.proxyUrl);
  334. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  335. throw Error();
  336. if (!url.port)
  337. url.port = '1080';
  338. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  339. hostname: url.hostname,
  340. port: url.port,
  341. userId: url.username,
  342. password: url.password,
  343. });
  344. }
  345. catch (e) {
  346. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  347. }
  348. }
  349. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  350. this.lockfile = opt.lockfile;
  351. this.lock = opt.lock;
  352. this.inactiveHours = opt.inactiveHours;
  353. this.workInterval = opt.workInterval;
  354. this.bot = opt.bot;
  355. this.webshotDelay = opt.webshotDelay;
  356. this.mode = opt.mode;
  357. this.wsUrl = opt.wsUrl;
  358. ScreenNameNormalizer._queryUser = this.queryUser;
  359. exports.sendAllStories = (rawUserName, receiver) => {
  360. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  361. this.queryUser(rawUserName)
  362. .then(userNameId => {
  363. const [userName, userId] = userNameId.split(':');
  364. if (userName in this.cache && Object.keys(this.cache[userName].stories).length > 0) {
  365. return Promise.resolve(Object.values(this.cache[userName].stories)
  366. .map(story => (Object.assign(Object.assign({}, story), { user: this.cache[userName].user })))
  367. .sort((i1, i2) => utils_1.BigNumOps.compare(i2.pk, i1.pk)));
  368. }
  369. return this.client.feed.reelsMedia({ userIds: [userId] }).items()
  370. .then(storyItems => {
  371. storyItems = storyItems.map(story => (Object.assign(Object.assign({}, story), { user: this.cache[userName].user })));
  372. storyItems.forEach(item => {
  373. if (!(item.pk in this.cache[userName].stories)) {
  374. this.cache[userName].stories[item.pk] = item;
  375. }
  376. });
  377. if (storyItems.length === 0)
  378. this.bot.sendTo(receiver, `当前用户 (@${userName}) 没有可用的推特故事。`);
  379. return storyItems;
  380. });
  381. })
  382. .then(storyItems => this.workOnMedia(storyItems, sender))
  383. .catch((error) => {
  384. if (error instanceof instagram_private_api_1.IgNetworkError) {
  385. logger.warn(`error while fetching stories for ${rawUserName}: ${JSON.stringify(error.cause)}`);
  386. this.bot.sendTo(receiver, `获取 Stories 时出现错误:原因: ${error.cause}`);
  387. }
  388. else if (error instanceof instagram_private_api_1.IgLoginRequiredError) {
  389. logger.warn('login required, logging in again...');
  390. this.session.login().then(() => exports.sendAllStories(rawUserName, receiver));
  391. }
  392. else {
  393. logger.error(`unhandled error while fetching stories for ${rawUserName}: ${error}`);
  394. this.bot.sendTo(receiver, `获取 Stories 时发生未知错误: ${error}`);
  395. }
  396. });
  397. };
  398. }
  399. get pullOrders() {
  400. const arr = [];
  401. Object.values(this.cache).forEach(item => { if (item.pullOrder > 0)
  402. arr[item.pullOrder - 1] = item.user.pk; });
  403. return arr;
  404. }
  405. ;
  406. set pullOrders(arr) {
  407. Object.values(this.cache).forEach(item => { item.pullOrder = arr.indexOf(item.user.pk) + 1; });
  408. }
  409. get isInactiveTime() {
  410. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  411. return this.inactiveHours
  412. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  413. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  414. }
  415. }
  416. exports.default = default_1;