twitter.js 19 KB

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