UNPKG

lemmy-bot

Version:

A bot API for Lemmy, the fediverse link aggregator.

800 lines 56.9 kB
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
    if (kind === "m") throw new TypeError("Private method is not writable");
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
    return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
    if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
    if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
    return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _LemmyBot_instances, _LemmyBot_isDryRun, _LemmyBot_isRunning, _LemmyBot_isLoggedIn, _LemmyBot_instance, _LemmyBot_timeouts, _LemmyBot_markAsBot, _LemmyBot_enableLogs, _LemmyBot_defaultMinutesUntilReprocess, _LemmyBot_federationOptions, _LemmyBot_tasks, _LemmyBot_delayedTasks, _LemmyBot_dbFile, _LemmyBot_listingType, _LemmyBot_credentials, _LemmyBot_defaultSecondsBetweenPolls, _LemmyBot_handlers, _LemmyBot_federationOptionMaps, _LemmyBot_botActions, _LemmyBot_runChecker, _LemmyBot_runBot, _LemmyBot_login, _LemmyBot_getCommunityIdsForAllowList, _LemmyBot_assignOptionsToMaps, _LemmyBot_handleEntry, _LemmyBot_filterFromResponse, _LemmyBot_getModlogItems, _LemmyBot_performLoggedInBotAction, _LemmyBot_log;
Object.defineProperty(exports, "__esModule", { value: true });
const lemmy_js_client_1 = require("lemmy-js-client");
const helpers_1 = require("./helpers");
const db_1 = require("./db");
const reprocessHandler_1 = __importDefault(require("./reprocessHandler"));
const node_cron_1 = __importDefault(require("node-cron"));
const types_1 = require("./types");
const DEFAULT_SECONDS_BETWEEN_POLLS = 30;
const DEFAULT_MINUTES_UNTIL_REPROCESS = undefined;
class LemmyBot {
    constructor({ instance, credentials, handlers, connection: { minutesUntilReprocess: defaultMinutesUntilReprocess = DEFAULT_MINUTES_UNTIL_REPROCESS, secondsBetweenPolls: defaultSecondsBetweenPolls = DEFAULT_SECONDS_BETWEEN_POLLS } = {
        secondsBetweenPolls: DEFAULT_SECONDS_BETWEEN_POLLS,
        minutesUntilReprocess: DEFAULT_MINUTES_UNTIL_REPROCESS
    }, dbFile, federation, schedule, markAsBot = true, enableLogs = true, dryRun = false, secure = true }) {
        var _a, _b, _c, _d, _e;
        _LemmyBot_instances.add(this);
        _LemmyBot_isDryRun.set(this, void 0);
        _LemmyBot_isRunning.set(this, void 0);
        _LemmyBot_isLoggedIn.set(this, false);
        _LemmyBot_instance.set(this, void 0);
        _LemmyBot_timeouts.set(this, []);
        _LemmyBot_markAsBot.set(this, void 0);
        _LemmyBot_enableLogs.set(this, void 0);
        _LemmyBot_defaultMinutesUntilReprocess.set(this, void 0);
        _LemmyBot_federationOptions.set(this, void 0);
        _LemmyBot_tasks.set(this, []);
        _LemmyBot_delayedTasks.set(this, []);
        _LemmyBot_dbFile.set(this, void 0);
        _LemmyBot_listingType.set(this, void 0);
        _LemmyBot_credentials.set(this, void 0);
        _LemmyBot_defaultSecondsBetweenPolls.set(this, DEFAULT_SECONDS_BETWEEN_POLLS);
        _LemmyBot_handlers.set(this, void 0);
        _LemmyBot_federationOptionMaps.set(this, {
            allowMap: new Map(),
            blockMap: new Map()
        });
        _LemmyBot_botActions.set(this, {
            createPost: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: 'Creating post',
                action: () => this.__httpClient__.createPost(form)
            }),
            editPost: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Editing post ID ${form.post_id}`,
                action: () => this.__httpClient__.editPost(Object.assign({}, form))
            }),
            reportPost: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Reporting to post ID ${form.post_id} for ${form.reason}`,
                action: () => this.__httpClient__.createPostReport(form)
            }),
            votePost: (form) => {
                const score = (0, helpers_1.correctVote)(form.score);
                const prefix = score === types_1.Vote.Upvote ? 'Up' : score === types_1.Vote.Downvote ? 'Down' : 'Un';
                return __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                    logMessage: `${prefix}voting post ID ${form.post_id}`,
                    action: () => this.__httpClient__.likePost(Object.assign(Object.assign({}, form), { score }))
                });
            },
            getPostVotes: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Getting votes for post ${form.post_id}`,
                action: () => this.__httpClient__.listPostLikes(form)
            }),
            createComment: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: form.parent_id
                    ? `Replying to comment ID ${form.parent_id}`
                    : `Replying to post ID ${form.post_id}`,
                action: () => this.__httpClient__.createComment(form)
            }),
            editComment: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Editing comment ID ${form.comment_id}`,
                action: () => this.__httpClient__.editComment(form)
            }),
            reportComment: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                action: () => this.__httpClient__.createCommentReport(form),
                logMessage: `Reporting to comment ID ${form.comment_id} for ${form.reason}`
            }),
            distinguishComment: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Distinguishing comment ${form.comment_id}`,
                action: () => this.__httpClient__.distinguishComment(form)
            }),
            voteComment: (form) => __awaiter(this, void 0, void 0, function* () {
                const score = (0, helpers_1.correctVote)(form.score);
                const prefix = score === types_1.Vote.Upvote ? 'Up' : score === types_1.Vote.Downvote ? 'Down' : 'Un';
                return yield __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                    logMessage: `${prefix}voting comment ID ${form.comment_id}`,
                    action: () => this.__httpClient__.likeComment(Object.assign(Object.assign({}, form), { score }))
                });
            }),
            getCommentVotes: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Getting votes for comment ID ${form.comment_id}`,
                action: () => this.__httpClient__.listCommentLikes(form)
            }),
            getCommunity: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Getting community ${form.id ? form.id : form.name}`,
                action: () => this.__httpClient__.getCommunity(form)
            }),
            banFromCommunity: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Banning user ID ${form.person_id} from ${form.community_id}`,
                action: () => this.__httpClient__.banFromCommunity(form)
            }),
            banFromSite: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Banning user ID ${form.person_id} from ${__classPrivateFieldGet(this, _LemmyBot_instance, "f")}`,
                action: () => this.__httpClient__.banPerson(form)
            }),
            sendPrivateMessage: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Sending private message to user ID ${form.recipient_id}`,
                action: () => this.__httpClient__.createPrivateMessage(form)
            }),
            reportPrivateMessage: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Reporting private message ID ${form.private_message_id}. Reason: ${form.reason}`,
                action: () => this.__httpClient__.createPrivateMessageReport(form)
            }),
            approveRegistrationApplication: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Approving application ID ${form.id}`,
                action: () => this.__httpClient__.approveRegistrationApplication(form)
            }),
            removePost: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Removing post ID ${form.post_id}`,
                action: () => this.__httpClient__.removePost(form)
            }),
            removeComment: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Removing comment ID ${form.comment_id}`,
                action: () => this.__httpClient__.removeComment(form)
            }),
            resolvePostReport: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Resolving post report ID ${form.report_id}`,
                action: () => this.__httpClient__.resolvePostReport(form)
            }),
            resolveCommentReport: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Resolving comment report ID ${form.report_id}`,
                action: () => this.__httpClient__.resolveCommentReport(form)
            }),
            resolvePrivateMessageReport: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Resolving private message report ID ${form.report_id}`,
                action: () => this.__httpClient__.resolvePrivateMessageReport(form)
            }),
            featurePost: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `${form.featured ? 'F' : 'Unf'}eaturing report ID ${form.post_id}`,
                action: () => this.__httpClient__.featurePost(form)
            }),
            lockPost: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `${form.locked ? 'L' : 'Unl'}ocking report ID ${form.post_id}`,
                action: () => this.__httpClient__.lockPost(form)
            }),
            followCommunity: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Following community ID ${form.community_id}`,
                action: () => this.__httpClient__.followCommunity(form)
            }),
            uploadImage: (image) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: 'Uploading image',
                action: () => this.__httpClient__.uploadImage({ image })
            }),
            getPost: (options) => this.__httpClient__.getPost(options),
            getComment: (options) => this.__httpClient__.getComment(options),
            getParentOfComment: (_a) => __awaiter(this, [_a], void 0, function* ({ path, post_id }) {
                const pathList = path.split('.').filter((i) => i !== '0');
                if (pathList.length === 1) {
                    return {
                        type: 'post',
                        post: yield __classPrivateFieldGet(this, _LemmyBot_botActions, "f").getPost({
                            id: post_id
                        })
                    };
                }
                else {
                    const parentId = Number(pathList[pathList.length - 2]);
                    return {
                        type: 'comment',
                        comment: yield __classPrivateFieldGet(this, _LemmyBot_botActions, "f").getComment({ id: parentId })
                    };
                }
            }),
            isCommunityMod: (_a) => __awaiter(this, [_a], void 0, function* ({ community, person }) {
                const { moderates } = yield this.__httpClient__.getPersonDetails({
                    person_id: person.id
                });
                return moderates.some((comm) => comm.community.id === community.id);
            }),
            resolveObject: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Resolving object: ${form.q}`,
                action: () => this.__httpClient__.resolveObject(form)
            }),
            getPersonDetails: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Getting details for ${form.username ? form.username : `user with ID ${form.person_id}`}`,
                action: () => this.__httpClient__.getPersonDetails(form)
            }),
            listMedia: (form = {}) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: 'Listing media posted by bot',
                action: () => this.__httpClient__.listMedia(form)
            }),
            listAllMedia: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: 'Listing all media posted on instance',
                action: () => this.__httpClient__.listAllMedia(form)
            }),
            hidePost: (form) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                logMessage: `Hiding posts with IDs = ${form.post_ids.join(', ')}`,
                action: () => this.__httpClient__.hidePost(form)
            })
        });
        _LemmyBot_getModlogItems.set(this, (type) => this.__httpClient__.getModlog({
            type_: type,
            limit: 50
        }));
        _LemmyBot_log.set(this, (output) => {
            if (__classPrivateFieldGet(this, _LemmyBot_enableLogs, "f")) {
                console.log(output);
            }
        });
        if (!instance) {
            console.log('Cannot use bot without instance!');
            process.exit(1);
        }
        switch (federation) {
            case undefined:
            case 'local': {
                __classPrivateFieldSet(this, _LemmyBot_federationOptions, {
                    allowList: [instance]
                }, "f");
                break;
            }
            case 'all': {
                __classPrivateFieldSet(this, _LemmyBot_federationOptions, {
                    blockList: []
                }, "f");
                break;
            }
            default: {
                if (((_b = (_a = federation.allowList) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0 &&
                    ((_d = (_c = federation.blockList) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0) {
                    throw 'Cannot have both block list and allow list defined for federation options';
                }
                else if ((!federation.allowList || federation.allowList.length === 0) &&
                    (!federation.blockList || federation.blockList.length === 0)) {
                    throw 'Neither the block list nor allow list has any instances. To fix this issue, make sure either allow list or block list (not both) has at least one instance.\n\nAlternatively, the you can set the federation property to one of the strings "local" or "all".';
                }
                else if ((_e = federation.blockList) === null || _e === void 0 ? void 0 : _e.includes(instance)) {
                    throw 'Cannot put bot instance in blocklist unless blocking specific communities';
                }
                else {
                    __classPrivateFieldSet(this, _LemmyBot_federationOptions, federation, "f");
                    if (__classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").allowList &&
                        !__classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").allowList.some((i) => i === instance ||
                            i.instance === instance)) {
                        __classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").allowList.push(instance);
                    }
                }
            }
        }
        if (schedule) {
            const tasks = Array.isArray(schedule) ? schedule : [schedule];
            for (const task of tasks) {
                if (!node_cron_1.default.validate(task.cronExpression)) {
                    throw `Schedule has invalid cron expression (${task.cronExpression}). Consult this documentation for valid expressions: https://www.gnu.org/software/mcron/manual/html_node/Crontab-file.html`;
                }
                __classPrivateFieldGet(this, _LemmyBot_tasks, "f").push(node_cron_1.default.schedule(task.cronExpression, () => task.doTask({
                    botActions: __classPrivateFieldGet(this, _LemmyBot_botActions, "f"),
                    __httpClient__: this.__httpClient__
                }), task.timezone || task.runAtStart
                    ? Object.assign(Object.assign({}, (task.timezone ? { timezone: task.timezone } : {})), (task.runAtStart ? { runOnInit: task.runAtStart } : {})) : undefined));
            }
        }
        __classPrivateFieldSet(this, _LemmyBot_credentials, credentials, "f");
        __classPrivateFieldSet(this, _LemmyBot_defaultSecondsBetweenPolls, defaultSecondsBetweenPolls, "f");
        __classPrivateFieldSet(this, _LemmyBot_isDryRun, dryRun, "f");
        __classPrivateFieldSet(this, _LemmyBot_isRunning, false, "f");
        __classPrivateFieldSet(this, _LemmyBot_markAsBot, markAsBot, "f");
        __classPrivateFieldSet(this, _LemmyBot_enableLogs, enableLogs, "f");
        __classPrivateFieldSet(this, _LemmyBot_instance, instance, "f");
        __classPrivateFieldSet(this, _LemmyBot_defaultMinutesUntilReprocess, defaultMinutesUntilReprocess, "f");
        this.__httpClient__ = new lemmy_js_client_1.LemmyHttp(`http${secure ? 's' : ''}://${__classPrivateFieldGet(this, _LemmyBot_instance, "f")}`);
        this.__httpClient__.setHeaders({ 'user-agent': 'Lemmy-Bot/0.6.1' });
        __classPrivateFieldSet(this, _LemmyBot_dbFile, dbFile, "f");
        __classPrivateFieldSet(this, _LemmyBot_listingType, (0, helpers_1.getListingType)(__classPrivateFieldGet(this, _LemmyBot_federationOptions, "f")), "f");
        __classPrivateFieldSet(this, _LemmyBot_handlers, (0, helpers_1.parseHandlers)(handlers), "f");
    }
    start() {
        __classPrivateFieldGet(this, _LemmyBot_log, "f").call(this, 'Starting bot');
        __classPrivateFieldSet(this, _LemmyBot_isRunning, true, "f");
        __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runBot).call(this);
    }
    stop() {
        __classPrivateFieldGet(this, _LemmyBot_log, "f").call(this, 'Stopping bot');
        __classPrivateFieldSet(this, _LemmyBot_isRunning, false, "f");
        __classPrivateFieldSet(this, _LemmyBot_isLoggedIn, false, "f");
    }
}
_LemmyBot_isDryRun = new WeakMap(), _LemmyBot_isRunning = new WeakMap(), _LemmyBot_isLoggedIn = new WeakMap(), _LemmyBot_instance = new WeakMap(), _LemmyBot_timeouts = new WeakMap(), _LemmyBot_markAsBot = new WeakMap(), _LemmyBot_enableLogs = new WeakMap(), _LemmyBot_defaultMinutesUntilReprocess = new WeakMap(), _LemmyBot_federationOptions = new WeakMap(), _LemmyBot_tasks = new WeakMap(), _LemmyBot_delayedTasks = new WeakMap(), _LemmyBot_dbFile = new WeakMap(), _LemmyBot_listingType = new WeakMap(), _LemmyBot_credentials = new WeakMap(), _LemmyBot_defaultSecondsBetweenPolls = new WeakMap(), _LemmyBot_handlers = new WeakMap(), _LemmyBot_federationOptionMaps = new WeakMap(), _LemmyBot_botActions = new WeakMap(), _LemmyBot_getModlogItems = new WeakMap(), _LemmyBot_log = new WeakMap(), _LemmyBot_instances = new WeakSet(), _LemmyBot_runChecker = function _LemmyBot_runChecker(checker_1) {
    return __awaiter(this, arguments, void 0, function* (checker, secondsBetweenPolls = __classPrivateFieldGet(this, _LemmyBot_defaultSecondsBetweenPolls, "f")) {
        if (__classPrivateFieldGet(this, _LemmyBot_isRunning, "f")) {
            if (__classPrivateFieldGet(this, _LemmyBot_isLoggedIn, "f") || !__classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
                checker();
                const timeout = setTimeout(() => {
                    __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, checker, secondsBetweenPolls);
                    __classPrivateFieldSet(this, _LemmyBot_timeouts, __classPrivateFieldGet(this, _LemmyBot_timeouts, "f").filter((t) => t !== timeout), "f");
                }, 1000 *
                    (secondsBetweenPolls < DEFAULT_SECONDS_BETWEEN_POLLS
                        ? DEFAULT_SECONDS_BETWEEN_POLLS
                        : secondsBetweenPolls));
                __classPrivateFieldGet(this, _LemmyBot_timeouts, "f").push(timeout);
            }
            else if (__classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
                yield __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_login).call(this);
                const timeout = setTimeout(() => {
                    __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, checker, secondsBetweenPolls);
                    __classPrivateFieldSet(this, _LemmyBot_timeouts, __classPrivateFieldGet(this, _LemmyBot_timeouts, "f").filter((t) => t !== timeout), "f");
                }, 5000);
                __classPrivateFieldGet(this, _LemmyBot_timeouts, "f").push(timeout);
            }
        }
        else {
            while (__classPrivateFieldGet(this, _LemmyBot_timeouts, "f").length > 0) {
                clearTimeout(__classPrivateFieldGet(this, _LemmyBot_timeouts, "f").pop());
            }
        }
    });
}, _LemmyBot_runBot = function _LemmyBot_runBot() {
    return __awaiter(this, void 0, void 0, function* () {
        var _a, _b;
        const { comment: commentOptions, post: postOptions, privateMessage: privateMessageOptions, registrationApplication: registrationApplicationOptions, mention: mentionOptions, reply: replyOptions, commentReport: commentReportOptions, postReport: postReportOptions, privateMessageReport: privateMessageReportOptions, modRemovePost: modRemovePostOptions, modLockPost: modLockPostOptions, modFeaturePost: modFeaturePostOptions, modRemoveComment: modRemoveCommentOptions, modRemoveCommunity: modRemoveCommunityOptions, modBanFromCommunity: modBanFromCommunityOptions, modAddModToCommunity: modAddModToCommunityOptions, modTransferCommunity: modTransferCommunityOptions, modAddAdmin: modAddAdminOptions, modBanFromSite: modBanFromSiteOptions } = __classPrivateFieldGet(this, _LemmyBot_handlers, "f");
        yield (0, db_1.setupDB)(__classPrivateFieldGet(this, _LemmyBot_log, "f"), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
        if (__classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            yield __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_login).call(this);
        }
        const subList = (_a = __classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").allowList) === null || _a === void 0 ? void 0 : _a.filter((option) => typeof option !== 'string');
        if (subList &&
            subList.length === ((_b = __classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").allowList) === null || _b === void 0 ? void 0 : _b.length)) {
            __classPrivateFieldSet(this, _LemmyBot_listingType, 'Subscribed', "f");
            yield Promise.allSettled(subList.flatMap(({ communities, instance }) => communities.map((name) => __classPrivateFieldGet(this, _LemmyBot_botActions, "f")
                .getCommunity({ name: `${name}@${instance}` })
                .then(({ community_view: { community: { id } } }) => this.__httpClient__.followCommunity({
                community_id: id,
                follow: true
            }))
                .catch(() => console.log(`Could not subscribe to !${name}@${instance}`)))));
        }
        if (__classPrivateFieldGet(this, _LemmyBot_delayedTasks, "f").length > 0) {
            yield Promise.all(__classPrivateFieldGet(this, _LemmyBot_delayedTasks, "f"));
        }
        for (const task of __classPrivateFieldGet(this, _LemmyBot_tasks, "f")) {
            task.start();
        }
        yield __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_getCommunityIdsForAllowList).call(this);
        if (postOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const response = yield this.__httpClient__.getPosts({
                    type_: __classPrivateFieldGet(this, _LemmyBot_listingType, "f"),
                    sort: postOptions.sort
                });
                const posts = __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_filterFromResponse).call(this, response.posts);
                yield (0, db_1.useDatabaseFunctions)('posts', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(posts.map((postView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        getStorageInfo: get,
                        upsert,
                        entry: { postView },
                        id: postView.post.id,
                        options: postOptions
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), postOptions.secondsBetweenPolls);
        }
        if (commentOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const response = yield this.__httpClient__.getComments({
                    type_: __classPrivateFieldGet(this, _LemmyBot_listingType, "f"),
                    sort: commentOptions.sort
                });
                const comments = __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_filterFromResponse).call(this, response.comments);
                yield (0, db_1.useDatabaseFunctions)('comments', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(comments.map((commentView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        getStorageInfo: get,
                        upsert,
                        options: commentOptions,
                        entry: { commentView },
                        id: commentView.comment.id
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), commentOptions.secondsBetweenPolls);
        }
        if (privateMessageOptions && __classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { private_messages } = yield this.__httpClient__.getPrivateMessages({
                    limit: 50,
                    unread_only: true
                });
                yield (0, db_1.useDatabaseFunctions)('messages', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(private_messages.map((messageView) => __awaiter(this, void 0, void 0, function* () {
                        return Promise.all([
                            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                                getStorageInfo: get,
                                options: privateMessageOptions,
                                entry: { messageView },
                                id: messageView.private_message.id,
                                upsert
                            }),
                            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                                action: () => this.__httpClient__.markPrivateMessageAsRead({
                                    private_message_id: messageView.private_message.id,
                                    read: true
                                }),
                                logMessage: `Marked private message ID ${messageView.private_message.id} from ${messageView.creator.id} as read`
                            })
                        ]);
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), privateMessageOptions.secondsBetweenPolls);
        }
        if (registrationApplicationOptions && __classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { registration_applications } = yield this.__httpClient__.listRegistrationApplications({
                    unread_only: true,
                    limit: 50
                });
                yield (0, db_1.useDatabaseFunctions)('registrations', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(registration_applications.map((applicationView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        getStorageInfo: get,
                        upsert,
                        entry: { applicationView },
                        id: applicationView.registration_application.id,
                        options: registrationApplicationOptions
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), registrationApplicationOptions.secondsBetweenPolls);
        }
        if (mentionOptions && __classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { mentions } = yield this.__httpClient__.getPersonMentions({
                    limit: 50,
                    unread_only: true,
                    sort: 'New'
                });
                yield (0, db_1.useDatabaseFunctions)('mentions', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(mentions.map((mentionView) => Promise.all([
                        __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                            entry: { mentionView },
                            options: mentionOptions,
                            getStorageInfo: get,
                            id: mentionView.person_mention.id,
                            upsert
                        }),
                        __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                            action: () => this.__httpClient__.markPersonMentionAsRead({
                                person_mention_id: mentionView.person_mention.id,
                                read: true
                            }),
                            logMessage: `Marked mention ${mentionView.person_mention.id} from ${mentionView.creator.id} as read`
                        })
                    ])));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), mentionOptions.secondsBetweenPolls);
        }
        if (replyOptions && __classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { replies } = yield this.__httpClient__.getReplies({
                    limit: 50,
                    sort: 'New',
                    unread_only: true
                });
                yield (0, db_1.useDatabaseFunctions)('replies', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(replies.map((replyView) => __awaiter(this, void 0, void 0, function* () {
                        return Promise.all([
                            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                                entry: { replyView },
                                options: replyOptions,
                                getStorageInfo: get,
                                id: replyView.comment_reply.id,
                                upsert
                            }),
                            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_performLoggedInBotAction).call(this, {
                                action: () => this.__httpClient__.markCommentReplyAsRead({
                                    comment_reply_id: replyView.comment_reply.id,
                                    read: true
                                }),
                                logMessage: `Marking reply ${replyView.comment_reply.id} from ${replyView.creator.id} as read`
                            })
                        ]);
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), replyOptions.secondsBetweenPolls);
        }
        if (commentReportOptions && __classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { comment_reports } = yield this.__httpClient__.listCommentReports({
                    unresolved_only: true,
                    limit: 50
                });
                yield (0, db_1.useDatabaseFunctions)('commentReports', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(comment_reports.map((reportView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { reportView },
                        options: commentReportOptions,
                        getStorageInfo: get,
                        id: reportView.comment_report.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), commentReportOptions.secondsBetweenPolls);
        }
        if (postReportOptions && __classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { post_reports } = yield this.__httpClient__.listPostReports({
                    unresolved_only: true,
                    limit: 50
                });
                yield (0, db_1.useDatabaseFunctions)('postReports', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(post_reports.map((reportView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { reportView },
                        options: postReportOptions,
                        getStorageInfo: get,
                        id: reportView.post_report.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), postReportOptions.secondsBetweenPolls);
        }
        if (privateMessageReportOptions && __classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { private_message_reports } = yield this.__httpClient__.listPrivateMessageReports({
                    limit: 50,
                    unresolved_only: true
                });
                if (privateMessageReportOptions) {
                    yield (0, db_1.useDatabaseFunctions)('messageReports', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                        yield Promise.all(private_message_reports.map((reportView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                            entry: { reportView },
                            options: privateMessageReportOptions,
                            getStorageInfo: get,
                            id: reportView.private_message_report.id,
                            upsert
                        })));
                    }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
                }
            }), privateMessageReportOptions.secondsBetweenPolls);
        }
        if (modRemovePostOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { removed_posts } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModRemovePost');
                yield (0, db_1.useDatabaseFunctions)('removedPosts', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(removed_posts.map((removedPostView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { removedPostView },
                        options: modRemovePostOptions,
                        getStorageInfo: get,
                        id: removedPostView.mod_remove_post.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modRemovePostOptions.secondsBetweenPolls);
        }
        if (modLockPostOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { locked_posts } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModLockPost');
                yield (0, db_1.useDatabaseFunctions)('lockedPosts', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(locked_posts.map((lockedPostView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { lockedPostView },
                        options: modLockPostOptions,
                        getStorageInfo: get,
                        id: lockedPostView.mod_lock_post.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modLockPostOptions.secondsBetweenPolls);
        }
        if (modFeaturePostOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { featured_posts } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModFeaturePost');
                yield (0, db_1.useDatabaseFunctions)('featuredPosts', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(featured_posts.map((featuredPostView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { featuredPostView },
                        options: modFeaturePostOptions,
                        getStorageInfo: get,
                        id: featuredPostView.mod_feature_post.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modFeaturePostOptions.secondsBetweenPolls);
        }
        if (modRemoveCommentOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { removed_comments } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModRemoveComment');
                yield (0, db_1.useDatabaseFunctions)('removedComments', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(removed_comments.map((removedCommentView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { removedCommentView },
                        options: modRemoveCommentOptions,
                        getStorageInfo: get,
                        id: removedCommentView.mod_remove_comment.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modRemoveCommentOptions.secondsBetweenPolls);
        }
        if (modRemoveCommunityOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { removed_communities } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModRemoveCommunity');
                yield (0, db_1.useDatabaseFunctions)('removedCommunities', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(removed_communities.map((removedCommunityView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { removedCommunityView },
                        options: modRemoveCommunityOptions,
                        getStorageInfo: get,
                        id: removedCommunityView.mod_remove_community.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modRemoveCommunityOptions.secondsBetweenPolls);
        }
        if (modBanFromCommunityOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { banned_from_community } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModBanFromCommunity');
                yield (0, db_1.useDatabaseFunctions)('communityBans', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(banned_from_community.map((banView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { banView },
                        options: modBanFromCommunityOptions,
                        getStorageInfo: get,
                        id: banView.mod_ban_from_community.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modBanFromCommunityOptions.secondsBetweenPolls);
        }
        if (modAddModToCommunityOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { added_to_community } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModAddCommunity');
                yield (0, db_1.useDatabaseFunctions)('modsAddedToCommunities', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(added_to_community.map((modAddedToCommunityView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { modAddedToCommunityView },
                        options: modAddModToCommunityOptions,
                        getStorageInfo: get,
                        id: modAddedToCommunityView.mod_add_community.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modAddModToCommunityOptions.secondsBetweenPolls);
        }
        if (modTransferCommunityOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { transferred_to_community } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModTransferCommunity');
                yield (0, db_1.useDatabaseFunctions)('modsTransferredToCommunities', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(transferred_to_community.map((modTransferredToCommunityView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { modTransferredToCommunityView },
                        options: modTransferCommunityOptions,
                        getStorageInfo: get,
                        id: modTransferredToCommunityView.mod_transfer_community.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modTransferCommunityOptions.secondsBetweenPolls);
        }
        if (modAddAdminOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { added } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModAdd');
                yield (0, db_1.useDatabaseFunctions)('adminsAdded', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(added.map((addedAdminView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { addedAdminView },
                        options: modAddAdminOptions,
                        getStorageInfo: get,
                        upsert,
                        id: addedAdminView.mod_add.id
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modAddAdminOptions.secondsBetweenPolls);
        }
        if (modBanFromSiteOptions) {
            __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_runChecker).call(this, () => __awaiter(this, void 0, void 0, function* () {
                const { banned } = yield __classPrivateFieldGet(this, _LemmyBot_getModlogItems, "f").call(this, 'ModBan');
                yield (0, db_1.useDatabaseFunctions)('siteBans', (_a) => __awaiter(this, [_a], void 0, function* ({ get, upsert }) {
                    yield Promise.all(banned.map((banView) => __classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_handleEntry).call(this, {
                        entry: { banView },
                        options: modBanFromSiteOptions,
                        getStorageInfo: get,
                        id: banView.mod_ban.id,
                        upsert
                    })));
                }), __classPrivateFieldGet(this, _LemmyBot_dbFile, "f"));
            }), modBanFromSiteOptions.secondsBetweenPolls);
        }
    });
}, _LemmyBot_login = function _LemmyBot_login() {
    return __awaiter(this, void 0, void 0, function* () {
        if (__classPrivateFieldGet(this, _LemmyBot_credentials, "f")) {
            __classPrivateFieldGet(this, _LemmyBot_log, "f").call(this, 'Logging in');
            const loginRes = yield this.__httpClient__.login({
                password: __classPrivateFieldGet(this, _LemmyBot_credentials, "f").password,
                username_or_email: __classPrivateFieldGet(this, _LemmyBot_credentials, "f").username
            });
            __classPrivateFieldGet(this, _LemmyBot_log, "f").call(this, 'Logged in');
            this.__httpClient__.setHeaders({
                Authorization: `Bearer ${loginRes.jwt}`
            });
            __classPrivateFieldSet(this, _LemmyBot_isLoggedIn, true, "f");
            if (__classPrivateFieldGet(this, _LemmyBot_markAsBot, "f")) {
                __classPrivateFieldGet(this, _LemmyBot_log, "f").call(this, 'Marking account as bot account');
                yield this.__httpClient__
                    .saveUserSettings({
                    bot_account: true
                })
                    .catch(console.error);
            }
        }
    });
}, _LemmyBot_getCommunityIdsForAllowList = function _LemmyBot_getCommunityIdsForAllowList() {
    return __awaiter(this, void 0, void 0, function* () {
        yield Promise.allSettled(__classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_assignOptionsToMaps).call(this, __classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").allowList, 'allowMap').concat(__classPrivateFieldGet(this, _LemmyBot_instances, "m", _LemmyBot_assignOptionsToMaps).call(this, __classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").blockList, 'blockMap')));
    });
}, _LemmyBot_assignOptionsToMaps = function _LemmyBot_assignOptionsToMaps(list, map) {
    var _a;
    return ((_a = list === null || list === void 0 ? void 0 : list.map((instanceOptions) => __awaiter(this, void 0, void 0, function* () {
        if (typeof instanceOptions === 'string' &&
            !__classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f")[map].get(instanceOptions)) {
            __classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f")[map].set(instanceOptions, true);
        }
        else if (!__classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f")[map].get(instanceOptions.instance)) {
            __classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f")[map].set(instanceOptions.instance, new Set((yield Promise.allSettled(instanceOptions.communities.map((c) => __awaiter(this, void 0, void 0, function* () {
                try {
                    return yield __classPrivateFieldGet(this, _LemmyBot_botActions, "f").getCommunity({
                        name: `${c}@${instanceOptions.instance}`
                    });
                }
                catch (e) {
                    console.log(`Could not get !${c}@${instanceOptions
                        .instance}`);
                    throw e;
                }
            }))))
                .filter((c) => c.status === 'fulfilled')
                .map((c) => c.value
                .community_view.community.id)));
        }
    }))) !== null && _a !== void 0 ? _a : []);
}, _LemmyBot_handleEntry = function _LemmyBot_handleEntry(_a) {
    return __awaiter(this, arguments, void 0, function* ({ getStorageInfo, upsert, options, id, entry }) {
        var _b;
        const storageInfo = yield getStorageInfo(id);
        if ((0, helpers_1.shouldProcess)(storageInfo)) {
            const { get, preventReprocess, reprocess } = new reprocessHandler_1.default((_b = options === null || options === void 0 ? void 0 : options.minutesUntilReprocess) !== null && _b !== void 0 ? _b : __classPrivateFieldGet(this, _LemmyBot_defaultMinutesUntilReprocess, "f"));
            yield options.handle(Object.assign({ botActions: __classPrivateFieldGet(this, _LemmyBot_botActions, "f"), preventReprocess,
                reprocess, __httpClient__: this.__httpClient__ }, entry));
            yield upsert(id, get());
        }
    });
}, _LemmyBot_filterFromResponse = function _LemmyBot_filterFromResponse(response) {
    var _a, _b, _c, _d;
    if (((_b = (_a = __classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").allowList) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0) > 0) {
        return response.filter(({ community: { actor_id, id } }) => {
            var _a;
            const instance = (0, helpers_1.extractInstanceFromActorId)(actor_id);
            return (__classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f").allowMap.get(instance) === true ||
                ((_a = __classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f").allowMap.get(instance)) === null || _a === void 0 ? void 0 : _a.has(id)));
        });
    }
    else if (((_d = (_c = __classPrivateFieldGet(this, _LemmyBot_federationOptions, "f").blockList) === null || _c === void 0 ? void 0 : _c.length) !== null && _d !== void 0 ? _d : 0) > 0) {
        return response.filter((d) => {
            var _a;
            const instance = (0, helpers_1.extractInstanceFromActorId)(d.community.actor_id);
            return !(__classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f").blockMap.get(instance) === true ||
                ((_a = __classPrivateFieldGet(this, _LemmyBot_federationOptionMaps, "f").blockMap.get(instance)) === null || _a === void 0 ? void 0 : _a.has(d.community.id)));
        });
    }
    else {
        return response;
    }
}, _LemmyBot_performLoggedInBotAction = function _LemmyBot_performLoggedInBotAction(_a) {
    return __awaiter(this, arguments, void 0, function* ({ logMessage, action }) {
        __classPrivateFieldGet(this, _LemmyBot_log, "f").call(this, logMessage);
        if (__classPrivateFieldGet(this, _LemmyBot_isDryRun, "f")) {
            return Promise.reject();
        }
        try {
            return yield action();
        }
        catch (err) {
            if (err.error === 'not_logged_in') {
                __classPrivateFieldSet(this, _LemmyBot_isLoggedIn, false, "f");
            }
            throw err;
        }
    });
};
exports.default = LemmyBot;