Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import EventEmitter from "events";
- import { AntiCaptcha } from "./common/services/captcha";
- import ILAProxy, { IProxyData, ProxyType } from "./common/net/proxy";
- import { IVKAccount, IVKPureAccount } from "./types";
- import {
- initDataStorage, DataStorage,
- getRandomString, checkConnection
- } from "./utils";
- import ILAServiceCompound from "./vk/services";
- import { validateAccount } from "./vk/providers/validate_account";
- import { Logger } from "@utils/logger";
- import { ITask } from "./vk/services/listener";
- type IlaEventType =
- "added-accounts" | "added-proxies" |
- "accounts-required" | "proxies-required" |
- "tasks-required" | "anticaptcha-required" |
- "auth-started" | "auth-stoped" | "auth-completed" |
- "auth-error" | "connection-failed" | "anticaptcha-updated";
- class ILAEventEmitter extends EventEmitter {
- public on = (event: IlaEventType, fn: (...args: any[]) => void) => super.on(event, fn);
- public emit = (event: IlaEventType, ...args: any[]) => super.emit(event, ...args);
- }
- export class Application extends ILAEventEmitter {
- private inited = false;
- private serverConnected = false;
- private storage: DataStorage;
- private services: ILAServiceCompound;
- private authHandler = {
- error: (error) => {
- Logger.error("[auth_error]:", error);
- this.emit("auth-error", error);
- },
- complete: (accounts) => {
- let invalidCount = 0;
- accounts.forEach(({ login, password, session }) => {
- const pure = { login, password };
- if (!session?.valid) {
- invalidCount++;
- return this.deleteAccount(pure);
- }
- const account = this.findAccount(pure) as (IVKAccount | undefined);
- if (!account) return;
- account.session = session;
- });
- this.storage.accounts.save();
- this.emit("auth-completed", {
- invalid: invalidCount,
- total: accounts.length
- });
- },
- started: count => this.emit("auth-started", count),
- stoped: count => this.emit("auth-stoped", count)
- }
- private listenerHandler = {
- started: (...args) => { Logger.log("Listener started event:", ...args) },
- stoped: (...args) => { Logger.log("Listener stoped event:", ...args) },
- error: (error) => { Logger.error("Listener error:", error) },
- "task-completed": (...args) => { Logger.log("Task completed:", ...args) }
- }
- public constructor() {
- super();
- this.services = new ILAServiceCompound();
- this.storage = initDataStorage();
- this.services.authenticator.setHandler((type, payload) => {
- if (!this.authHandler[type]) return Logger.warn("Unhandled authorization response type:", type);
- this.authHandler[type](payload);
- });
- this.services.listener.setHandler((type, payload) => {
- if (!this.listenerHandler[type]) return Logger.warn("Unhandled listener response type:", type);
- this.listenerHandler[type](payload);
- })
- }
- public get isConnectionEstabilished() {
- return this.serverConnected;
- }
- public async init() {
- if (this.inited) return Promise.resolve();
- await this.storage.read();
- const { systemProxy } = this.storage.cache.data.settings;
- globalThis.SYSTEM_PROXY_DATA = systemProxy;
- this.storage.on("error", error => Logger.error("Storage error:", error));
- this.storage.on("restored", (data: any) => Logger.log(`File "${data.file.name}" content restored.`));
- this.on("added-accounts", () => this.startAuthenticator());
- this.on("added-proxies", () => this.services.authenticator.setProxies(this.storage.proxies.data))
- this.on("anticaptcha-updated", key => this.services.authenticator.setAntiCaptchaKey(key));
- }
- public async start() {
- const { systemProxy } = this.getSettings();
- const result = await checkConnection(systemProxy && ILAProxy.from(systemProxy));
- if (!result) {
- this.serverConnected = false;
- Logger.warn("Failed connection to the vk.com, mail. System proxy required");
- return this.emit("connection-failed");
- }
- this.serverConnected = true;
- Logger.log("Success connection to the vk.com, mail.ru");
- }
- public stop() { }
- public reset() { }
- public getAuthorizationStatus() {
- return this.services.authenticator.isRunning;
- }
- public async startAuthenticator() {
- const {
- antiCaptchaKey
- } = this.getSettings();
- if (!this.serverConnected) {
- return this.emit("connection-failed");
- }
- const accounts = this.getAccounts({ authorized: false });
- if (!accounts.length) return;
- const proxies = this.storage.proxies.data;
- if (!proxies.length) {
- return this.emit("proxies-required");
- }
- if (!antiCaptchaKey) {
- return this.emit("anticaptcha-required");
- }
- Logger.log("Starting authenticator...");
- this.services.authenticator.setAntiCaptchaKey(antiCaptchaKey);
- this.services.authenticator.setProxies(proxies);
- this.services.authenticator.setAccounts(accounts);
- this.services.authenticator.start()
- .catch(error => this.emit("auth-error", error));
- return true;
- }
- public stopAuthenticator() {
- this.services.authenticator.stop();
- }
- public startListener() {
- const { tasks } = this.storage.cache.data;
- const accounts = this.getAccounts({ authorized: true });
- const proxies = this.storage.proxies.data;
- if (!this.serverConnected) {
- return this.emit("connection-failed");
- }
- if (!accounts.length) {
- return this.emit("accounts-required");
- }
- if (!tasks.length) {
- return this.emit("tasks-required");
- }
- if (!proxies.length) {
- return this.emit("proxies-required");
- }
- Logger.log("Listener starting...");
- const { listener } = this.services;
- listener.setTasks(tasks);
- listener.setAccounts(accounts);
- return listener.start();
- }
- public async stopListener() {
- const { listener } = this.services;
- await listener.stop();
- }
- public getListenerTasks() {
- return this.storage.cache.data.tasks;
- }
- public getListenerStatus() {
- return this.services.listener.isRunning;
- }
- public addAccountsString(text: string) {
- const pattern = /(\S+):(\S+)/;
- const dirtAccounts = text.trim().split("\n").map(line => {
- const result = line.match(pattern);
- if (!result) return false;
- const [, login, password] = result!;
- return { login, password };
- })
- const pureAccounts = dirtAccounts.filter(a => a) as IVKPureAccount[];
- this.addAccounts(pureAccounts);
- return {
- total: dirtAccounts.length,
- added: pureAccounts.length
- }
- }
- private addAccounts(elementOrArray: IVKPureAccount | IVKPureAccount[]) {
- const { accounts } = this.storage;
- let oldSize = accounts.data.length;
- (Array.isArray(elementOrArray))
- ? elementOrArray.forEach(this.addUniqueAccount.bind(this))
- : this.addUniqueAccount(elementOrArray);
- accounts.save();
- const newAccounts = accounts.data.slice(oldSize, accounts.data.length);
- this.emit("added-accounts", newAccounts);
- return this;
- }
- private addUniqueAccount(account: IVKPureAccount) {
- const accountsFile = this.storage.accounts;
- const result = this.findAccount(account);
- if (result) return false;
- this.normalizeAccount(account);
- accountsFile.data.push(account);
- return true;
- }
- private findAccount(account: IVKPureAccount, returnIndex = false) {
- const { data } = this.storage.accounts;
- const predicate = a => a.login == account.login && a.password == account.password;
- return returnIndex ? data.findIndex(predicate) : data.find(predicate);
- }
- private normalizeAccount(account: IVKAccount) {
- account.session = {
- cookies: {},
- valid: true
- }
- return account;
- }
- private deleteAccount(account: IVKPureAccount) {
- const index = this.findAccount(account, true) as number;
- if (index == -1) return false;
- this.storage.accounts.data.splice(index, 1);
- return true;
- }
- private deleteInvalidAccounts() {
- const invalidAccounts = this.getInvalidAccounts();
- const invalidCount = invalidAccounts.length;
- if (!invalidAccounts.length) return null;
- const deletedCount = invalidAccounts
- .map(this.deleteAccount.bind(this))
- .filter(status => status)
- .length;
- return Object.freeze({ invalidCount, deletedCount });
- }
- public clearAccounts() {
- this.storage.accounts.data = [];
- return this.storage.accounts.save();
- }
- public clearSessions() {
- const accountsFile = this.storage.accounts;
- const accounts = accountsFile.data;
- accounts.forEach(account => delete account.session);
- return accountsFile.save();
- }
- public validateAccounts(accounts = this.getAuthorizedAccounts()) {
- const pure = accounts.filter(validateAccount);
- return Promise.all(pure);
- }
- public getAccounts(filter?: { authorized?: boolean }): IVKAccount[] {
- if (!filter) return this.storage.accounts.data;
- if (filter.authorized != undefined) {
- return !filter.authorized
- ? this.getUnauthorizedAccounts()
- : this.getAuthorizedAccounts();
- }
- return this.storage.accounts.data;
- }
- private getUnauthorizedAccounts = (accounts = this.getAccounts()) => accounts.filter(account => this.isValidAccount(account) && !this.isAuthorizedAccount(account));
- private getInvalidAccounts = (accounts = this.getAccounts()) => accounts.filter(account => !this.isValidAccount(account));
- private getAuthorizedAccounts = (accounts = this.getAccounts()) => accounts.filter(this.isAuthorizedAccount);
- private isAuthorizedAccount = (account: IVKAccount) => account.session && account.session?.valid && account.session?.cookies?.base;
- private isValidAccount = (account: IVKAccount) => account.session?.valid;
- public addProxies(type: ProxyType, content: string) {
- const lines = content.trim().split("\n");
- const proxies = lines.map(line => {
- const proxy = ILAProxy.fromString(type, line).getProxyData();
- const finded = this.findProxy(proxy);
- return finded ? false : proxy;
- }).filter(proxy => proxy) as IProxyData[];
- this.storage.proxies.data = [
- ...this.getProxies(),
- ...proxies
- ];
- this.storage.proxies.save();
- this.emit("added-proxies");
- return true;
- }
- private findProxy(proxy: IProxyData) {
- return this.storage.proxies.data.find(a => {
- return a.address == proxy.address && a.port == proxy.port && a.type == proxy.type;
- });
- }
- public deleteProxy() { }
- public clearProxies() { }
- public getProxies() {
- return this.storage.proxies.data;
- }
- public validateProxy() { }
- public validateProxies() { }
- public addTask(data: any) {
- const task: ITask = {
- enable: true,
- id: getRandomString(16),
- monetize: true,
- performed: false,
- playlist: data.playlist,
- progress: {
- initial: data.playlist.listens,
- actual: data.playlist.listens,
- target: data.playlist.listens + data.totalCount
- },
- speed: 0
- }
- const cache = this.storage.cache.data;
- cache.tasks.push(task);
- this.storage.cache.save()
- .then(() => Logger.log("addTask(): cache saved..."))
- .catch(error => Logger.error("addTask(): cache saving error:", error));
- this.startListener();
- return;
- }
- public reloadTask() { }
- public reloadTasks() { }
- public deleteTask(id: string) {
- const { listener } = this.services;
- if (listener.isRunning) {
- return this.services.listener.deleteTask(id);
- }
- const cache = this.storage.cache.data
- const index = cache.tasks.findIndex(task => task.id == id);
- if (index == -1) {
- throw new Error("Task with specify id not found");
- }
- cache.tasks.splice(index, 1);
- return this.storage.cache.save();
- }
- public clearTasks() { }
- public getTasks() {
- return this.storage.cache.data.tasks
- }
- public validateTasks() { }
- public getHistory() {
- return this.storage.cache.data.tasksHistory;
- }
- public clearHistory() { }
- public async setAnticaptcha(key: string) {
- const { settings } = this.storage.cache.data;
- if (settings.antiCaptchaKey == key) return true;
- const valid = await AntiCaptcha.isValidKey(key);
- if (!valid) throw new Error("Key is invalid");
- AntiCaptcha.setKey(key);
- settings.antiCaptchaKey = key;
- this.storage.cache.save();
- this.emit("anticaptcha-updated", key);
- return true;
- }
- public getAnticaptcha() {
- return this.storage.cache.data.settings.antiCaptchaKey;
- }
- public getSettings() {
- const { cache } = this.storage;
- return cache.data.settings;
- }
- public async setSystemProxy(type: ProxyType, proxyString: string) {
- try {
- const { cache } = this.storage;
- const proxy = ILAProxy.fromString(type, proxyString);
- const connected = await checkConnection(proxy);
- if (!connected) return false;
- this.serverConnected = true;
- cache.data.settings.systemProxy = proxy.getProxyData();
- globalThis.SYSTEM_PROXY_DATA = proxy.getProxyData();
- return cache.save();
- } catch (error) {
- this.serverConnected = false;
- return false;
- }
- }
- public save() {
- return this.storage.save();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement