twitter.js 19 KB

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