Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

refactor: remove a interface do processo principal #304

Merged
merged 3 commits into from
Jun 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions browser/events/dev.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
import { ipcRenderer } from 'electron';
import { RendererProcessError } from '$renderer/error';
import { ipcInvoke } from '$renderer/ipc';
import { ipcInvoke, ipcOn } from '$renderer/ipc';

export async function setDevEvents() {
const isDev = await ipcInvoke('is-dev');
const isDev = await ipcInvoke('app:is-dev');
if (!isDev) return;

// A callback desse evento varia conforme o que está sendo testado no momento.
ipcRenderer.on('dev:magic', () => {
ipcOn('dev:magic', () => {
console.log('It\'s dev magic!');
mockRendererProcessError();
});

ipcRenderer.on('dev:mock-captcha', () => mockCaptcha());
ipcRenderer.on('dev:mock-error', () => mockRendererProcessError());
ipcOn('dev:mock-captcha', () => mockCaptcha());
ipcOn('dev:mock-error', () => mockRendererProcessError());
};

function mockCaptcha() {
Expand Down
12 changes: 4 additions & 8 deletions browser/events/ipc-tribal.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
import { ipcRenderer } from 'electron';
import { BrowserError } from '$browser/error';
import { ipcSend } from '$renderer/ipc';
import { ipcOn, ipcSend } from '$renderer/ipc';
import { IpcTribal } from '$ipc/interface';
import {
useAresStore,
useFeaturesStore,
useGroupsStore,
usePlayerStore,
useCurrentVillageStore
} from '$renderer/stores';

export function setIpcTribalEvents() {
const aresStore = useAresStore();
const featuresStore = useFeaturesStore();
const groupsStore = useGroupsStore();
const playerStore = usePlayerStore();
const currentVillageStore = useCurrentVillageStore();

ipcRenderer.on('get-game-data', async () => {
ipcOn('get-game-data', async () => {
try {
const gameData = await IpcTribal.invoke('get-game-data');
if (!gameData) return;

ipcSend('ipc-tribal:update-game-data', gameData);
if (!gameData) return;

aresStore.$patch(gameData.ares);
featuresStore.$patch(gameData.features);
groupsStore.$patch(gameData.groups);
playerStore.$patch(gameData.player);
currentVillageStore.$patch(gameData.currentVillage);

Expand Down
15 changes: 0 additions & 15 deletions browser/events/plunder/config.ts

This file was deleted.

7 changes: 3 additions & 4 deletions browser/events/plunder/index.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { ipcRenderer } from 'electron';
import { ipcOn } from '$renderer/ipc';
import { usePlunderConfigStore } from '$renderer/stores/plunder';
import { setPlunderConfigEvents } from '$browser/events/plunder/config';
import { setPlunderNavigationEvents } from '$browser/events/plunder/navigation';

export function setPlunderEvents() {
setPlunderConfigEvents();
setPlunderNavigationEvents();

const plunderConfigStore = usePlunderConfigStore();

ipcRenderer.on('plunder:stop', () => (plunderConfigStore.active = false));
ipcOn('plunder:stop', () => (plunderConfigStore.active = false));
ipcOn('plunder:patch-config', (_e, config: PlunderConfigType) => plunderConfigStore.$patch(config));
};
6 changes: 3 additions & 3 deletions browser/events/plunder/navigation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { ipcRenderer } from 'electron';
import { watch } from 'vue';
import { ipcOn } from '$renderer/ipc';
import { usePlunderConfigStore } from '$renderer/stores/plunder';

export function setPlunderNavigationEvents() {
Expand All @@ -11,10 +11,10 @@ export function setPlunderNavigationEvents() {
eventTarget.dispatchEvent(new Event('cancel'));
});

ipcRenderer.on('plunder:set-navigation-timer', (_e, url: string, delay: number) => {
ipcOn('plunder:set-navigation-timer', (_e, url: string, delay: number) => {
if (!config.active) return;

// Não é preciso remover o listener se a navegacao for bem sucedida.
// Não é preciso remover o listener se a navegação for bem sucedida.
const timeout = setTimeout(() => location.assign(url), delay);
eventTarget.addEventListener('cancel', () => clearTimeout(timeout), { once: true });
});
Expand Down
7 changes: 5 additions & 2 deletions browser/lib/plunder/attack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,12 @@ function sendAttack(button: HTMLAnchorElement) {
*/
export async function sendAttackFromPlace(units: PlaceUnitsAmount): Promise<boolean> {
try {
const isArcherWorld = await ipcInvoke('game:is-archer-world');
const isArcherWorld = await ipcInvoke('world:is-archer-world');
if (typeof isArcherWorld !== 'boolean') {
throw new PlunderError('Could not determine if world is archer world.');
};

const commandForm = document.queryAndAssert('#command-data-form[action*="place" i]');

for (const [key, value] of Object.entries(units)) {
if (!isArcherWorld && /archer/.test(key)) continue;
assertInteger(value, `Expected integer value for ${key}, but got ${value}.`);
Expand Down
7 changes: 3 additions & 4 deletions browser/lib/plunder/templates.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { computed, nextTick, ref } from 'vue';
import { ipcRenderer } from 'electron';
import { Kronos } from '@tb-dev/kronos';
import { assertInteger, isInteger } from '$common/guards';
import { useUnitsStore } from '$renderer/stores/units';
import { assertFarmUnit } from '$common/guards';
import { PlunderError } from '$browser/error';
import { ipcInvoke } from '$renderer/ipc';
import { ipcInvoke, ipcOn } from '$renderer/ipc';
import type { usePlunderConfigStore } from '$renderer/stores';
import type { PlunderTargetInfo } from '$browser/lib/plunder/targets';

Expand Down Expand Up @@ -63,12 +62,12 @@ export class PlunderTemplate {
/** Representa todos os modelos de saque. */
const allTemplates = new Map<string, PlunderTemplate>();

ipcRenderer.on('custom-plunder-template-saved', async (_e, template: CustomPlunderTemplateType) => {
ipcOn('custom-plunder-template-saved', async (_e, template: CustomPlunderTemplateType) => {
const plunderTemplate = await parseCustomPlunderTemplate(template);
allTemplates.set(plunderTemplate.type, plunderTemplate);
});

ipcRenderer.on('custom-plunder-template-destroyed', (_e, template: CustomPlunderTemplateType) => {
ipcOn('custom-plunder-template-destroyed', (_e, template: CustomPlunderTemplateType) => {
const templateInMap = allTemplates.get(template.type);
if (templateInMap && templateInMap.alias === template.alias) {
allTemplates.delete(templateInMap.type);
Expand Down
6 changes: 3 additions & 3 deletions browser/router/guards/plunder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ import { nextTick } from 'vue';
import { storeToRefs } from 'pinia';
import { until } from '@vueuse/core';
import { getPlunderInfo, updatePlunderConfig } from '$browser/lib/plunder/data';
import { useCurrentVillageStore, usePlunderStore, usePlunderConfigStore, useGroupsStore } from '$renderer/stores';
import { useAresStore, useCurrentVillageStore, usePlunderStore, usePlunderConfigStore } from '$renderer/stores';
import { ipcInvoke, ipcSend } from '$renderer/ipc';
import { BrowserRouterError } from '$browser/error';
import type { Router } from 'vue-router';

export function setPlunderNavigationGuards(router: Router) {
const aresStore = useAresStore();
const plunderStore = usePlunderStore();
const plunderConfigStore = usePlunderConfigStore();
const currentVillageStore = useCurrentVillageStore();
const groupsStore = useGroupsStore();

const { groupId: currentGroupId } = storeToRefs(aresStore);
const { page: plunderPage } = storeToRefs(plunderStore);
const { active: isPlunderActive, plunderGroupId, groupAttack } = storeToRefs(plunderConfigStore);
const { id: currentVillageId } = storeToRefs(currentVillageStore);
const { groupId: currentGroupId } = storeToRefs(groupsStore);

router.beforeEach(async (to) => {
try {
Expand Down
9 changes: 8 additions & 1 deletion common/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,19 @@ export const enum WebsiteUrl {
};

export const enum Dimensions {
/** Altura do container do menu superior. */
TopContainerHeight = 80
};

export const enum ErrorLogFile {
/** Erros propriamente capturados e registrados no banco de dados. */
All = 'error.log',
/**
* Erros capturados e registrados em algum dos processos filhos.
* @see https://www.electronjs.org/docs/latest/api/utility-process
*/
ChildProcess = 'child-process-error.log',
/** Se o Ares falhar em capturar um erro, ele será registrado diretamente no arquivo. */
Uncaught = 'uncaught-error.log'
};

Expand All @@ -76,7 +83,7 @@ export const allUnits = ['spear', 'sword', 'axe', 'archer', 'spy', 'light', 'mar
export const months = ['jan', 'fev', 'mar', 'abr', 'mai', 'jun', 'jul', 'ago', 'set', 'out', 'nov', 'dez'] as const;

// Mapas.
// TO DO: transformar em JSON.
// TODO: transformar em JSON.
export const unitsToDestroyWall = {
'0': {
spear: 0,
Expand Down
3 changes: 3 additions & 0 deletions common/regex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ export const worldRegex = /^(br|en|nl|pt|uk|us)([cps](?![cps]))*\d+$/;
export const aliasRegex = /^(br|en|nl|pt|uk|us)([cps](?![cps]))*\d+_/;
export const unitsRegex = /(spear|sword|axe|archer|spy|light|heavy|ram|catapult|knight|snob|militia)/;

/** Escopos do IPC. */
export const scopeRegex = /^\w+(?:-\w+)*:\w+(?:-\w+)*/;

export const gameOriginRegex = /tribalwars\.(com?\.)?(br|net|nl|pt|uk|us)/;
export const tbOriginRegex = /tb\.dev\.br/;
export const githubOriginRegex = /github\.com/;
Expand Down
48 changes: 48 additions & 0 deletions common/templates/plunder.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,51 @@
export class DefaultPlunderConfig implements PlunderConfigType {
// Painel
readonly active = false;
readonly ignoreWall = false;
readonly destroyWall = false;
readonly groupAttack = false;
readonly useC = false;
readonly ignoreDelay = false;
readonly blindAttack = false;

// Ataque
readonly maxDistance = 20;
readonly ignoreOlderThan = 10;
readonly attackDelay = 200;
readonly resourceRatio = 0.8;
readonly blindAttackPattern = 'smaller';

// Modelo C
readonly useCPattern = 'normal';
readonly maxDistanceC = 10;
readonly ignoreOlderThanC = 5;
readonly useCWhenResourceRatioIsBiggerThan = 3;

// Grupo
readonly plunderGroupId = null;
readonly fieldsPerWave = 10;
readonly villageDelay = 2000;

// Muralha
readonly wallLevelToIgnore = 1;
readonly wallLevelToDestroy = 1;
readonly destroyWallMaxDistance = 20;

// Outros
readonly minutesUntilReload = 10;
readonly plunderedResourcesRatio = 1;
readonly pageDelay = 2000;
};

export class DefaultPlunderHistory implements PlunderHistoryType {
readonly wood = 0;
readonly stone = 0;
readonly iron = 0;
readonly attackAmount = 0;
readonly destroyedWalls = 0;
readonly villages = {};
};

export abstract class PlunderAttack implements PlunderAttackLog {
// Já incluso o ataque enviado.
readonly attackAmount: number = 1;
Expand Down
5 changes: 3 additions & 2 deletions electron/database/models/game/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { InferAttributes, InferCreationAttributes } from 'sequelize';

export class VillageGroups extends Model<InferAttributes<VillageGroups>, InferCreationAttributes<VillageGroups>> implements VillageGroupsType {
declare readonly id: UserAlias;
declare allGroups: VillageGroup[];
declare readonly allGroups: VillageGroup[];
};

VillageGroups.init({
Expand All @@ -24,6 +24,7 @@ VillageGroups.init({

allGroups: {
type: DataTypes.JSON,
allowNull: false
allowNull: false,
defaultValue: []
}
}, { sequelize, tableName: 'village_groups', timestamps: true });
14 changes: 9 additions & 5 deletions electron/database/models/plunder/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { DataTypes, Model } from 'sequelize';
import { sequelize } from '$electron/database';
import { assertUserAlias } from '$common/guards';
import { DatabaseError } from '$electron/error';
import { usePlunderHistoryStore } from '$electron/stores';
import type { CreationOptional, InferAttributes, InferCreationAttributes } from 'sequelize';
import type { usePlunderHistoryStore } from '$electron/interface';

export class PlunderHistory extends Model<InferAttributes<PlunderHistory>, InferCreationAttributes<PlunderHistory>> implements PlunderHistoryType {
declare readonly id: UserAlias;
Expand All @@ -14,12 +14,16 @@ export class PlunderHistory extends Model<InferAttributes<PlunderHistory>, Infer
declare readonly destroyedWalls: number;
declare readonly villages: CreationOptional<PlunderHistoryType['villages']>;

public static async saveHistory(alias: UserAlias, plunderHistoryStore: ReturnType<typeof usePlunderHistoryStore>) {
public static async saveHistory(alias: UserAlias) {
try {
// Na store, `villages` é um proxy, então é necessário clonar o objeto antes de salvá-lo.
const villages = { ...plunderHistoryStore.villages };
const plunderHistoryStore = usePlunderHistoryStore();
const villages = plunderHistoryStore.unproxifyVillages();
await sequelize.transaction(async () => {
await PlunderHistory.upsert({ id: alias, ...plunderHistoryStore, villages });
await PlunderHistory.upsert({
id: alias,
...plunderHistoryStore.$raw({ actions: false }),
villages
});
});

} catch (err) {
Expand Down
20 changes: 15 additions & 5 deletions electron/electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,18 @@ import { sequelize } from '$electron/database';
import { setEvents } from '$electron/events/index';
import { appIcon, panelHtml, uiHtml, browserJs } from '$electron/utils/files';
import { setBrowserViewAutoResize } from '$electron/utils/view';
import { setEnv } from '$electron/env';
import { MainProcessError } from '$electron/error';
import { setEnv } from '$electron/utils/env';
import { Dimensions } from '$common/constants';
import { isUserAlias } from '$common/guards';
import { getGameRegionUrl } from '$common/helpers';
import { appConfig } from '$electron/stores';
import { PlunderHistory, useBrowserViewStore, useCacheStore, usePlunderHistoryStore } from '$electron/interface';
import { useBrowserViewStore, useCacheStore } from '$electron/stores';
import { PlunderHistory } from '$electron/database/models';
import { MainProcessError } from '$electron/error';
import { errorHandler } from '$electron/utils/error-handler';
import { showDebug } from '$electron/modules';

MainProcessError.catch = errorHandler;
setEnv();

function createWindow() {
Expand Down Expand Up @@ -102,7 +106,13 @@ function createWindow() {
mainWindow.on('system-context-menu', (e) => e.preventDefault());
panelWindow.on('system-context-menu', (e) => e.preventDefault());

mainWindow.once('ready-to-show', () => mainWindow.show());
mainWindow.once('ready-to-show', () => {
mainWindow.show();
if (appConfig.get('advanced').debug) {
showDebug();
mainWindow.focus();
};
});

panelWindow.once('ready-to-show', () => {
const panelBounds = appConfig.get('panel').bounds;
Expand All @@ -125,7 +135,7 @@ app.once('will-quit', async (e) => {
e.preventDefault();
const cacheStore = useCacheStore();
if (isUserAlias(cacheStore.userAlias)) {
await PlunderHistory.saveHistory(cacheStore.userAlias, usePlunderHistoryStore());
await PlunderHistory.saveHistory(cacheStore.userAlias);
};
} catch (err) {
await MainProcessError.log(err);
Expand Down
2 changes: 1 addition & 1 deletion electron/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class MainProcessError extends AresError {

/** Emite um erro falso no processo principal para fins de teste. */
public static mock() {
const error = new this('Isso é um teste.');
const error = new this('This is a mock error.');
this.catch(error);
};

Expand Down
Loading