twitter.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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.workForAll, this.workInterval * 10000);
  181. }, this.workInterval * 1200);
  182. });
  183. };
  184. this.queryUser = (rawUserName) => {
  185. const username = ScreenNameNormalizer.normalize(rawUserName).split(':')[0];
  186. if (username in this.cache) {
  187. return Promise.resolve(`${username}:${this.cache[username].user.pk}`);
  188. }
  189. return this.client.user.searchExact(username)
  190. .then(user => {
  191. this.cache[user.username] = { user, stories: {} };
  192. return `${user.username}:${user.pk}`;
  193. });
  194. };
  195. this.workOnMedia = (mediaItems, sendMedia) => this.webshot(mediaItems, sendMedia, this.webshotDelay);
  196. this.sendStories = (source, ...to) => (msg, text, author) => {
  197. to.forEach(subscriber => {
  198. logger.info(`pushing data${source ? ` of ${source}` : ''} to ${JSON.stringify(subscriber)}`);
  199. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  200. if (count <= maxTrials) {
  201. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  202. }
  203. else {
  204. logger.warn(`${count - 1} consecutive failures while sending message chain, trying plain text instead...`);
  205. terminate(this.bot.sendTo(subscriber, author + text, true));
  206. }
  207. });
  208. });
  209. };
  210. this.cache = {};
  211. this.workForAll = () => {
  212. if (this.isInactiveTime)
  213. return;
  214. const idToUserMap = {};
  215. Promise.all(Object.entries(this.lock.threads).map(entry => {
  216. const id = entry[1].id;
  217. const userName = parseLink(entry[0]).userName;
  218. logger.debug(`preparing to add user @${userName} to next pull task...`);
  219. if (userName in this.cache)
  220. return Promise.resolve(idToUserMap[id] = this.cache[userName].user);
  221. return this.client.user.info(id).then(user => {
  222. logger.debug(`initialized cache item for user ${user.full_name} (@${userName})`);
  223. this.cache[userName] = { user, stories: {} };
  224. return idToUserMap[id] = user;
  225. });
  226. }))
  227. .then(() => {
  228. logger.debug(`pulling stories for users: ${Object.values(idToUserMap).map(user => user.username)}`);
  229. return this.client.feed.reelsMedia({ userIds: Object.keys(idToUserMap) }).items()
  230. .then(storyItems => storyItems.forEach(item => {
  231. if (!(item.pk in this.cache[idToUserMap[item.user.pk].username].stories)) {
  232. this.cache[idToUserMap[item.user.pk].username].stories[item.pk] = item;
  233. }
  234. }));
  235. })
  236. .catch((error) => {
  237. if (error instanceof instagram_private_api_1.IgNetworkError) {
  238. logger.warn(`error on fetching stories for all: ${JSON.stringify(error.cause)}`);
  239. }
  240. else if (error instanceof instagram_private_api_1.IgLoginRequiredError) {
  241. logger.warn('login required, logging in again...');
  242. this.session.login().then(this.workForAll);
  243. }
  244. else {
  245. logger.error(`unhandled error on fetching media for all: ${error}`);
  246. }
  247. });
  248. };
  249. this.work = () => {
  250. const lock = this.lock;
  251. logger.debug(`current cache: ${JSON.stringify(this.cache)}`);
  252. if (this.workInterval < 1)
  253. this.workInterval = 1;
  254. if (this.isInactiveTime || lock.feed.length === 0) {
  255. setTimeout(this.work, this.workInterval * 1000);
  256. return;
  257. }
  258. if (lock.workon >= lock.feed.length)
  259. lock.workon = 0;
  260. if (!lock.threads[lock.feed[lock.workon]] ||
  261. !lock.threads[lock.feed[lock.workon]].subscribers ||
  262. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  263. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  264. delete lock.threads[lock.feed[lock.workon]];
  265. lock.feed.splice(lock.workon, 1);
  266. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  267. this.work();
  268. return;
  269. }
  270. const currentFeed = lock.feed[lock.workon];
  271. logger.debug(`searching for new items from ${currentFeed} in cache`);
  272. const promise = new Promise(resolve => {
  273. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(currentFeed);
  274. if (!match) {
  275. logger.error(`current feed "${currentFeed}" is invalid, please remove this feed manually`);
  276. return resolve([]);
  277. }
  278. const cachedFeed = this.cache[match[1]];
  279. if (!cachedFeed) {
  280. setTimeout(this.work, this.workInterval * 1000);
  281. return resolve([]);
  282. }
  283. const newer = (item) => utils_1.BigNumOps.compare(item.pk, lock.threads[currentFeed].offset) > 0;
  284. resolve(Object.values(cachedFeed.stories)
  285. .filter(newer)
  286. .map(story => (Object.assign(Object.assign({}, story), { user: cachedFeed.user })))
  287. .sort((i1, i2) => utils_1.BigNumOps.compare(i2.pk, i1.pk)));
  288. });
  289. promise.then((mediaItems) => {
  290. const currentThread = lock.threads[currentFeed];
  291. const updateDate = () => currentThread.updatedAt = new Date().toString();
  292. if (!mediaItems || mediaItems.length === 0) {
  293. updateDate();
  294. return;
  295. }
  296. const topOfFeed = mediaItems[0].pk;
  297. const updateOffset = () => currentThread.offset = topOfFeed;
  298. if (currentThread.offset === '-1') {
  299. updateOffset();
  300. return;
  301. }
  302. if (currentThread.offset === '0')
  303. mediaItems.splice(1);
  304. return this.workOnMedia(mediaItems, this.sendStories(`thread ${currentFeed}`, ...currentThread.subscribers))
  305. .then(updateDate).then(updateOffset);
  306. })
  307. .then(() => {
  308. lock.workon++;
  309. let timeout = this.workInterval * 1000 / lock.feed.length;
  310. if (timeout < 1000)
  311. timeout = 1000;
  312. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  313. setTimeout(() => {
  314. this.work();
  315. }, timeout);
  316. });
  317. };
  318. this.client = new instagram_private_api_1.IgApiClient();
  319. if (opt.proxyUrl) {
  320. try {
  321. const url = new URL(opt.proxyUrl);
  322. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  323. throw Error();
  324. if (!url.port)
  325. url.port = '1080';
  326. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  327. hostname: url.hostname,
  328. port: url.port,
  329. userId: url.username,
  330. password: url.password,
  331. });
  332. }
  333. catch (e) {
  334. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  335. }
  336. }
  337. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials, opt.codeServicePort);
  338. this.lockfile = opt.lockfile;
  339. this.lock = opt.lock;
  340. this.inactiveHours = opt.inactiveHours;
  341. this.workInterval = opt.workInterval;
  342. this.bot = opt.bot;
  343. this.webshotDelay = opt.webshotDelay;
  344. this.mode = opt.mode;
  345. this.wsUrl = opt.wsUrl;
  346. ScreenNameNormalizer._queryUser = this.queryUser;
  347. exports.sendAllStories = (rawUserName, receiver) => {
  348. const sender = this.sendStories(`instagram stories for ${rawUserName}`, receiver);
  349. this.queryUser(rawUserName)
  350. .then(userNameId => {
  351. const [userName, userId] = userNameId.split(':');
  352. if (userName in this.cache && Object.keys(this.cache[userName].stories).length > 0) {
  353. return Promise.resolve(Object.values(this.cache[userName].stories)
  354. .map(story => (Object.assign(Object.assign({}, story), { user: this.cache[userName].user })))
  355. .sort((i1, i2) => utils_1.BigNumOps.compare(i2.pk, i1.pk)));
  356. }
  357. return this.client.feed.reelsMedia({ userIds: [userId] }).items()
  358. .then(storyItems => {
  359. storyItems = storyItems.map(story => (Object.assign(Object.assign({}, story), { user: this.cache[userName].user })));
  360. storyItems.forEach(item => {
  361. if (!(item.pk in this.cache[userName].stories)) {
  362. this.cache[userName].stories[item.pk] = item;
  363. }
  364. });
  365. if (storyItems.length === 0)
  366. this.bot.sendTo(receiver, `当前用户 (@${userName}) 没有可用的推特故事。`);
  367. return storyItems;
  368. });
  369. })
  370. .then(storyItems => this.workOnMedia(storyItems, sender))
  371. .catch((error) => {
  372. if (error instanceof instagram_private_api_1.IgNetworkError) {
  373. logger.warn(`error on fetching stories for ${rawUserName}: ${JSON.stringify(error.cause)}`);
  374. this.bot.sendTo(receiver, `获取 Fleets 时出现错误:原因: ${error.cause}`);
  375. }
  376. else if (error instanceof instagram_private_api_1.IgLoginRequiredError) {
  377. logger.warn('login required, logging in again...');
  378. this.session.login().then(() => exports.sendAllStories(rawUserName, receiver));
  379. }
  380. else {
  381. logger.error(`unhandled error on fetching media for ${rawUserName}: ${error}`);
  382. this.bot.sendTo(receiver, `获取 Fleets 时发生未知错误: ${error}`);
  383. }
  384. });
  385. };
  386. }
  387. get isInactiveTime() {
  388. const timeToEpoch = (h = 0, m = 0) => new Date().setHours(h, m, 0, 0);
  389. return this.inactiveHours
  390. .map(rangeStr => ((start, end) => ({ start, end }))(...rangeStr.split('-', 2).map(timeStr => timeToEpoch(...timeStr.split(':', 2).map(Number)))))
  391. .some(range => (now => now >= range.start && now < range.end)(Date.now()));
  392. }
  393. }
  394. exports.default = default_1;