"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.doSearch = void 0; const Twitter = require("twitter"); const loggers_1 = require("./loggers"); const utils_1 = require("./utils"); let doSearch = (conf, receiver) => { throw Error(); }; exports.doSearch = doSearch; const TWITTER_EPOCH = 1288834974657; const snowflake = (epoch) => Number.isNaN(epoch) ? undefined : utils_1.BigNumOps.lShift(String(epoch - 1 - TWITTER_EPOCH), 22); const logger = (0, loggers_1.getLogger)('twitter'); var AdaptiveSearch; (function (AdaptiveSearch) { ; AdaptiveSearch.isCursor = (entry) => entry.sortIndex === '0' || entry.sortIndex === '999999999'; })(AdaptiveSearch || (AdaptiveSearch = {})); class default_1 { constructor(opt) { this.search = (conf) => { for (const key in conf) { if (!conf[key]) delete conf[key]; } const origQuery = conf.query; delete conf.query; const paramNames = { until: 'max_id', since: 'since_id' }; logger.info(`performing custom query ${origQuery} with config: ${JSON.stringify(conf)}`); const query = origQuery.replace(new RegExp(`(${Object.values(paramNames).join('|')}):\d+`, 'g'), ($0, $1) => conf[$1] ? '' : $0).replace(/\(\)/g, '') + Object.keys(paramNames).map(k => conf[k] && `(${paramNames[k]}:${conf[k]})`).join(); const doSearch = (q, tweets = [], cursor) => this.privateClient.get('https://api.twitter.com/2/search/adaptive.json', Object.assign({ q, tweet_mode: 'extended', count: 20, include_entities: true, query_source: 'typed_query' }, (cursor && { cursor }))).then(({ globalObjects: { tweets: tweetDict, users: userDict }, timeline: { instructions: { 0: { addEntries: { entries } } } } }) => { const newTweets = Object.values(tweetDict); let bottomCursor; if (newTweets.length) { logger.debug(`fetched tweets: ${JSON.stringify(newTweets)}`); entries.sort((e1, e2) => Number(e1.sortIndex) - Number(e2.sortIndex)); if (AdaptiveSearch.isCursor(entries[0])) { bottomCursor = entries[0]; logger.info(`custom query ${origQuery} yielded ${newTweets.length} new tweets, next query will follow tweet ${entries[1].entryId.replace(/^sq-I-t-/, '')}`); } else { logger.info(`custom query ${origQuery} ended after yielding ${newTweets.length} new tweets, last entry was tweet ${entries[0].entryId.replace(/^sq-I-t-/, '')}`); } newTweets.forEach(tweet => Object.assign(tweet, { user: userDict[tweet.user_id_str], })); tweets.push(...newTweets); } if (!bottomCursor || !newTweets.length || tweets.length >= conf.count) { logger.info(`custom query ${origQuery} finished successfully, ${tweets.length} tweets have been fetched`); return tweets.slice(0, conf.count); } return doSearch(query, tweets, bottomCursor === null || bottomCursor === void 0 ? void 0 : bottomCursor.content.operation.cursor.value); }); return doSearch(query); }; this.privateClient = new Twitter({ bearer_token: 'AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA', request: { headers: { 'Content-Type': 'application/x-www-form-urlencoded', Cookie: `auth_token=${opt.privateAuthToken}; ct0=${opt.privateCsrfToken};`, 'X-CSRF-Token': opt.privateCsrfToken, }, } }); this.bot = opt.bot; exports.doSearch = ({ query, count, since, until }, receiver) => { const countNum = Number(count) || 15; this.search({ query, count: Math.abs(countNum), since: utils_1.BigNumOps.parse(since) || snowflake(new Date(since).getTime()), until: utils_1.BigNumOps.parse(until) || snowflake(new Date(until).getTime()), }) .then(tweets => (0, utils_1.chainPromises)(tweets.map(tweet => () => this.bot.sendTo(receiver, `\ 用户:${tweet.user.name} (@${tweet.user.screen_name}) 编号:${tweet.id_str} 时间:${tweet.created_at} 媒体:${tweet.extended_entities ? '有' : '无'} 正文:\n${tweet.full_text.replace(/^([\s\S\n]{50})[\s\S\n]+?( https:\/\/t.co\/.*)?$/, '$1…$2')}`)) .concat(() => this.bot.sendTo(receiver, tweets.length ? '自定义查询完毕,使用 /twitter_view <编号> 查看推文详细内容。' : '自定义查询完毕,没有找到符合条件的推文。')))) .catch((err) => { var _a, _b; logger.warn(`error retrieving timeline: ${((_a = err[0]) === null || _a === void 0 ? void 0 : _a.message) || err}`); return this.bot.sendTo(receiver, `自定义查询时出现错误:${((_b = err[0]) === null || _b === void 0 ? void 0 : _b.message) || err}`); }); }; } } exports.default = default_1;