twitter.js 20 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.sendPost = exports.getPostOwner = exports.WebshotHelpers = exports.ScreenNameNormalizer = exports.SessionManager = exports.urlSegmentToId = exports.idToUrlSegment = exports.isValidUrlSegment = exports.parseLink = exports.linkBuilder = void 0;
  13. const fs = require("fs");
  14. const path = require("path");
  15. const util_1 = require("util");
  16. const instagram_id_to_url_segment_1 = require("instagram-id-to-url-segment");
  17. Object.defineProperty(exports, "idToUrlSegment", { enumerable: true, get: function () { return instagram_id_to_url_segment_1.instagramIdToUrlSegment; } });
  18. Object.defineProperty(exports, "urlSegmentToId", { enumerable: true, get: function () { return instagram_id_to_url_segment_1.urlSegmentToInstagramId; } });
  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 koishi_1 = require("./koishi");
  23. const utils_1 = require("./utils");
  24. const webshot_1 = require("./webshot");
  25. const parseLink = (link) => {
  26. let match = /instagram\.com\/p\/([A-Za-z0-9\-_]+)/.exec(link);
  27. if (match)
  28. return { postUrlSegment: match[1] };
  29. match =
  30. /instagram\.com\/([^\/?#]+)/.exec(link) ||
  31. /^([^\/?#]+)$/.exec(link);
  32. if (match)
  33. return { userName: ScreenNameNormalizer.normalize(match[1]).split(':')[0] };
  34. return;
  35. };
  36. exports.parseLink = parseLink;
  37. const isValidUrlSegment = (input) => /^[A-Za-z0-9\-_]+$/.test(input);
  38. exports.isValidUrlSegment = isValidUrlSegment;
  39. const linkBuilder = (config) => {
  40. if (config.userName)
  41. return `https://www.instagram.com/${config.userName}/`;
  42. if (config.postUrlSegment)
  43. return `https://www.instagram.com/p/${config.postUrlSegment}/`;
  44. };
  45. exports.linkBuilder = linkBuilder;
  46. class SessionManager {
  47. constructor(client, file, credentials) {
  48. this.init = () => {
  49. this.ig.state.generateDevice(this.username);
  50. this.ig.request.end$.subscribe(() => { this.save(); });
  51. const filePath = path.resolve(this.lockfile);
  52. if (fs.existsSync(filePath)) {
  53. try {
  54. const serialized = JSON.parse(fs.readFileSync(filePath, 'utf8'));
  55. return this.ig.state.deserialize(serialized).then(() => {
  56. logger.info(`successfully loaded client session cookies for user ${this.username}`);
  57. });
  58. }
  59. catch (err) {
  60. logger.error(`failed to load client session cookies from file ${this.lockfile}: `, err);
  61. return Promise.resolve();
  62. }
  63. }
  64. else
  65. return this.login();
  66. };
  67. this.login = () => this.ig.simulate.preLoginFlow()
  68. .then(() => this.ig.account.login(this.username, this.password))
  69. .then(() => new Promise(resolve => {
  70. logger.info(`successfully logged in as ${this.username}`);
  71. process.nextTick(() => resolve(this.ig.simulate.postLoginFlow()));
  72. }));
  73. this.save = () => this.ig.state.serialize()
  74. .then((serialized) => {
  75. delete serialized.constants;
  76. return fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(serialized, null, 2), 'utf-8');
  77. });
  78. this.ig = client;
  79. this.lockfile = file;
  80. [this.username, this.password] = credentials;
  81. }
  82. }
  83. exports.SessionManager = SessionManager;
  84. class ScreenNameNormalizer {
  85. static normalizeLive(username) {
  86. return __awaiter(this, void 0, void 0, function* () {
  87. if (this._queryUser) {
  88. return yield this._queryUser(username)
  89. .catch((err) => {
  90. if (!(err instanceof instagram_private_api_1.IgExactUserNotFoundError)) {
  91. logger.warn(`error looking up user: ${err.message}`);
  92. return `${username}:`;
  93. }
  94. return null;
  95. });
  96. }
  97. return this.normalize(username);
  98. });
  99. }
  100. }
  101. exports.ScreenNameNormalizer = ScreenNameNormalizer;
  102. ScreenNameNormalizer.normalize = (username) => `${username.toLowerCase().replace(/^@/, '')}:`;
  103. let browserLogin = (page) => Promise.reject();
  104. let browserSaveCookies = browserLogin;
  105. const acceptCookieConsent = (page) => page.click('button:has-text("すべて許可")', { timeout: 5000 })
  106. .then(() => logger.info('accepted cookie consent'))
  107. .catch((err) => { if (err.name !== 'TimeoutError')
  108. throw err; });
  109. exports.WebshotHelpers = {
  110. handleLogin: browserLogin,
  111. handleCookieConsent: acceptCookieConsent,
  112. };
  113. let getPostOwner = (segmentId) => Promise.reject();
  114. exports.getPostOwner = getPostOwner;
  115. let sendPost = (segmentId, receiver) => {
  116. throw Error();
  117. };
  118. exports.sendPost = sendPost;
  119. const logger = loggers_1.getLogger('instagram');
  120. const maxTrials = 3;
  121. const retryInterval = 1500;
  122. const ordinal = (n) => {
  123. switch ((Math.trunc(n / 10) % 10 === 1) ? 0 : n % 10) {
  124. case 1:
  125. return `${n}st`;
  126. case 2:
  127. return `${n}nd`;
  128. case 3:
  129. return `${n}rd`;
  130. default:
  131. return `${n}th`;
  132. }
  133. };
  134. const retryOnError = (doWork, onRetry) => new Promise(resolve => {
  135. const retry = (reason, count) => {
  136. setTimeout(() => {
  137. let terminate = false;
  138. onRetry(reason, count, defaultValue => { terminate = true; resolve(defaultValue); });
  139. if (!terminate)
  140. doWork().then(resolve).catch(error => retry(error, count + 1));
  141. }, retryInterval);
  142. };
  143. doWork().then(resolve).catch(error => retry(error, 1));
  144. });
  145. class default_1 {
  146. constructor(opt) {
  147. this.webshotCookies = [];
  148. this.launch = () => {
  149. this.webshot = new webshot_1.default(this.wsUrl, this.mode, () => this.webshotCookies, doOnNewPage => {
  150. this.queryUserMedia = ((userName, targetId) => {
  151. let page;
  152. const url = linkBuilder({ userName });
  153. logger.debug(`pulling ${targetId !== '0' ? `feed ${url} up to ${targetId}` : `top of feed ${url}`}...`);
  154. return doOnNewPage(newPage => {
  155. page = newPage;
  156. let timeout = this.webshotDelay;
  157. const startTime = new Date().getTime();
  158. const getTimerTime = () => new Date().getTime() - startTime;
  159. const getTimeout = () => Math.max(500, timeout - getTimerTime());
  160. return page.context().addCookies(this.webshotCookies)
  161. .then(() => page.goto(url, { waitUntil: 'load', timeout: getTimeout() }))
  162. .then(response => {
  163. if (response.status() !== 200) {
  164. const err = new Error(`error navigating to user page, error was: ${response.status()} ${response.statusText()}`);
  165. throw Object.defineProperty(err, 'name', {
  166. value: 'ResponseError',
  167. });
  168. }
  169. }).then(() => acceptCookieConsent(page))
  170. .then(() => (next => Promise.race([
  171. browserLogin(page)
  172. .catch((err) => {
  173. if (err.name === 'TimeoutError')
  174. logger.warn('navigation timed out, assuming login has failed');
  175. throw err;
  176. })
  177. .then(() => browserSaveCookies(page))
  178. .then(() => page.goto(url)).then(next),
  179. next(),
  180. ]))(() => page.waitForSelector('article', { timeout: getTimeout() }))).then(handle => {
  181. const postHandler = () => {
  182. const toId = (href) => { var _a; return instagram_id_to_url_segment_1.urlSegmentToInstagramId(((_a = /\/p\/(.*)\/$/.exec(href)) !== null && _a !== void 0 ? _a : [, ''])[1]); };
  183. if (targetId === '0') {
  184. return handle.$$eval('a', as => as.filter(a => !a.querySelector('[aria-label="IGTV"]'))[0].href).then(href => Number(toId(href)) > 0 ? [toId(href)] : []);
  185. }
  186. return handle.$$eval('a', as => as.filter(a => !a.querySelector('[aria-label="IGTV"]')).map(a => a.href)).then(hrefs => {
  187. let id;
  188. const itemIds = [];
  189. for (const href of hrefs) {
  190. id = toId(href);
  191. if (id && utils_1.BigNumOps.compare(id, targetId) > 0)
  192. itemIds.push(id);
  193. else
  194. return itemIds;
  195. }
  196. logger.info('unable to find a smaller id than target, trying on next page...');
  197. return null;
  198. });
  199. };
  200. return postHandler().then(itemIds => {
  201. if (itemIds)
  202. return itemIds;
  203. timeout += this.webshotDelay / 2;
  204. return handle.$$('a')
  205. .then(as => { as.pop().scrollIntoViewIfNeeded(); return as.length + 1; })
  206. .then(loadedCount => page.waitForFunction(count => document.querySelectorAll('article a').length > count, loadedCount))
  207. .then(postHandler);
  208. });
  209. }).catch((err) => {
  210. if (err.name !== 'TimeoutError' && err.name !== 'ResponseError')
  211. throw err;
  212. if (err.name === 'ResponseError') {
  213. logger.warn(`error while fetching tweets for ${userName}: ${err.message}`);
  214. }
  215. else
  216. logger.warn(`navigation timed out at ${getTimerTime()} ms`);
  217. return [];
  218. }).then(itemIds => util_1.promisify(setTimeout)(getTimeout()).then(() => itemIds.map(id => this.lazyGetMediaById(id))));
  219. }).finally(() => { page.close(); });
  220. });
  221. setTimeout(this.work, this.workInterval * 1000);
  222. });
  223. };
  224. this.queryUser = (username) => this.client.user.searchExact(username)
  225. .then(user => `${user.username}:${user.pk}`);
  226. this.workOnMedia = (lazyMediaItems, sendMedia) => this.webshot(lazyMediaItems, sendMedia, this.webshotDelay);
  227. this.urlSegmentToId = instagram_id_to_url_segment_1.urlSegmentToInstagramId;
  228. this.lazyGetMediaById = (id) => ({
  229. pk: id,
  230. item: () => this.client.media.info(id).then(media => {
  231. const mediaItem = media.items[0];
  232. logger.debug(`api returned media post ${JSON.stringify(mediaItem)} for query id=${id}`);
  233. return mediaItem;
  234. }),
  235. });
  236. this.getMedia = (segmentId, sender) => this.workOnMedia([this.lazyGetMediaById(instagram_id_to_url_segment_1.urlSegmentToInstagramId(segmentId))], sender);
  237. this.sendMedia = (source, ...to) => (msg, text, author) => {
  238. to.forEach(subscriber => {
  239. logger.info(`pushing data${source ? ` of ${koishi_1.Message.ellipseBase64(source)}` : ''} to ${JSON.stringify(subscriber)}`);
  240. retryOnError(() => this.bot.sendTo(subscriber, msg), (_, count, terminate) => {
  241. if (count <= maxTrials) {
  242. logger.warn(`retry sending to ${subscriber.chatID} for the ${ordinal(count)} time...`);
  243. }
  244. else {
  245. logger.warn(`${count - 1} consecutive failures while sending` +
  246. 'message chain, trying plain text instead...');
  247. terminate(this.bot.sendTo(subscriber, author + text));
  248. }
  249. });
  250. });
  251. };
  252. this.work = () => {
  253. const lock = this.lock;
  254. if (this.workInterval < 1)
  255. this.workInterval = 1;
  256. if (lock.feed.length === 0) {
  257. setTimeout(() => {
  258. this.work();
  259. }, this.workInterval * 1000);
  260. return;
  261. }
  262. if (lock.workon >= lock.feed.length)
  263. lock.workon = 0;
  264. if (!lock.threads[lock.feed[lock.workon]] ||
  265. !lock.threads[lock.feed[lock.workon]].subscribers ||
  266. lock.threads[lock.feed[lock.workon]].subscribers.length === 0) {
  267. logger.warn(`nobody subscribes thread ${lock.feed[lock.workon]}, removing from feed`);
  268. delete lock.threads[lock.feed[lock.workon]];
  269. lock.feed.splice(lock.workon, 1);
  270. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  271. this.work();
  272. return;
  273. }
  274. const currentFeed = lock.feed[lock.workon];
  275. const promise = new Promise(resolve => {
  276. const match = /https:\/\/www\.instagram\.com\/([^\/]+)/.exec(currentFeed);
  277. if (match) {
  278. resolve(this.queryUserMedia(match[1], this.lock.threads[currentFeed].offset));
  279. }
  280. resolve([]);
  281. });
  282. promise.then((mediaItems) => {
  283. const currentThread = lock.threads[currentFeed];
  284. const updateDate = () => currentThread.updatedAt = new Date().toString();
  285. if (!mediaItems || mediaItems.length === 0) {
  286. updateDate();
  287. return;
  288. }
  289. const topOfFeed = mediaItems[0].pk;
  290. const updateOffset = () => currentThread.offset = topOfFeed;
  291. if (currentThread.offset === '-1') {
  292. updateOffset();
  293. return;
  294. }
  295. if (currentThread.offset === '0')
  296. mediaItems.splice(1);
  297. return this.workOnMedia(mediaItems, this.sendMedia(`thread ${currentFeed}`, ...currentThread.subscribers))
  298. .then(updateDate).then(updateOffset);
  299. })
  300. .then(() => {
  301. lock.workon++;
  302. let timeout = this.workInterval * 1000 / lock.feed.length;
  303. if (timeout < 1000)
  304. timeout = 1000;
  305. fs.writeFileSync(path.resolve(this.lockfile), JSON.stringify(lock));
  306. setTimeout(() => {
  307. this.work();
  308. }, timeout);
  309. });
  310. };
  311. this.client = new instagram_private_api_1.IgApiClient();
  312. if (opt.proxyUrl) {
  313. try {
  314. const url = new URL(opt.proxyUrl);
  315. if (!/^socks(?:4a?|5h?)?:$/.test(url.protocol))
  316. throw Error();
  317. if (!url.port)
  318. url.port = '1080';
  319. this.client.request.defaults.agent = new socks_proxy_agent_1.SocksProxyAgent({
  320. hostname: url.hostname,
  321. port: url.port,
  322. userId: url.username,
  323. password: url.password,
  324. });
  325. }
  326. catch (e) {
  327. logger.warn(`invalid socks proxy url: ${opt.proxyUrl}, ignoring`);
  328. }
  329. }
  330. this.session = new SessionManager(this.client, opt.sessionLockfile, opt.credentials);
  331. this.lockfile = opt.lockfile;
  332. this.webshotCookiesLockfile = opt.webshotCookiesLockfile;
  333. this.lock = opt.lock;
  334. this.workInterval = opt.workInterval;
  335. this.bot = opt.bot;
  336. this.webshotDelay = opt.webshotDelay;
  337. this.mode = opt.mode;
  338. this.wsUrl = opt.wsUrl;
  339. const cookiesFilePath = path.resolve(this.webshotCookiesLockfile);
  340. try {
  341. this.webshotCookies = JSON.parse(fs.readFileSync(cookiesFilePath, 'utf8'));
  342. logger.info(`loaded webshot cookies from file ${this.webshotCookiesLockfile}`);
  343. }
  344. catch (err) {
  345. logger.warn(`failed to load webshot cookies from file ${this.webshotCookiesLockfile}: `, err.message);
  346. logger.warn('cookies will be saved to this file when needed');
  347. }
  348. browserLogin = page => page.fill('input[name="username"]', opt.credentials[0])
  349. .then(() => logger.warn('blocked by login dialog, trying to log in manually...'))
  350. .then(() => page.fill('input[name="password"]', opt.credentials[1]))
  351. .then(() => page.click('button[type="submit"]'))
  352. .then(() => page.click('button:has-text("情報を保存")'));
  353. browserSaveCookies = page => page.context().cookies()
  354. .then(cookies => {
  355. this.webshotCookies = cookies;
  356. logger.info('successfully logged in, saving cookies to file...');
  357. fs.writeFileSync(path.resolve(this.webshotCookiesLockfile), JSON.stringify(cookies, null, 2), 'utf-8');
  358. });
  359. exports.WebshotHelpers.handleLogin = page => browserLogin(page)
  360. .then(() => page.waitForSelector('img[data-testid="user-avatar"]', { timeout: this.webshotDelay }))
  361. .then(() => browserSaveCookies(page))
  362. .catch((err) => {
  363. if (err.name === 'TimeoutError')
  364. logger.warn('navigation timed out, assuming login has failed');
  365. throw err;
  366. });
  367. ScreenNameNormalizer._queryUser = this.queryUser;
  368. const parseMediaError = (err) => {
  369. if (!(err instanceof instagram_private_api_1.IgResponseError && err.text === 'Media not found or unavailable')) {
  370. logger.warn(`error retrieving instagram media: ${err.message}`);
  371. return `获取媒体时出现错误:${err.message}`;
  372. }
  373. return '找不到请求的媒体,它可能已被删除。';
  374. };
  375. exports.getPostOwner = (segmentId) => this.client.media.info(instagram_id_to_url_segment_1.urlSegmentToInstagramId(segmentId))
  376. .then(media => media.items[0].user)
  377. .then(user => `${user.username}:${user.pk}`)
  378. .catch((err) => { throw Error(parseMediaError(err)); });
  379. exports.sendPost = (segmentId, receiver) => {
  380. this.getMedia(segmentId, this.sendMedia(`instagram media ${segmentId}`, receiver))
  381. .catch((err) => { this.bot.sendTo(receiver, parseMediaError(err)); });
  382. };
  383. }
  384. }
  385. exports.default = default_1;