initial commit

This commit is contained in:
Fabio Di Stasio 2023-03-19 18:40:03 +01:00
commit 9f945c4b8f
90 changed files with 34458 additions and 0 deletions

27
.all-contributorsrc Normal file
View File

@ -0,0 +1,27 @@
{
"projectName": "mizar",
"projectOwner": "Fabio286",
"repoType": "github",
"repoHost": "https://github.com",
"files": [
"README.md"
],
"imageSize": 100,
"commit": false,
"commitConvention": "angular",
"contributors": [
{
"login": "Fabio286",
"name": "Fabio Di Stasio",
"avatar_url": "https://avatars.githubusercontent.com/u/31471771?v=4",
"profile": "https://fabiodistasio.it/",
"contributions": [
"code",
"translation",
"doc"
]
}
],
"contributorsPerLine": 7,
"skipCi": true
}

5
.eslintignore Normal file
View File

@ -0,0 +1,5 @@
node_modules
assets
out
dist
build

96
.eslintrc Normal file
View File

@ -0,0 +1,96 @@
{
"env": {
"browser": true,
"es6": true,
"node": true
},
"extends": [
"standard",
"plugin:@typescript-eslint/recommended",
"plugin:vue/vue3-recommended"
],
"parser": "vue-eslint-parser",
"parserOptions": {
"parser": "@typescript-eslint/parser",
"ecmaVersion": 9,
"sourceType": "module",
"requireConfigFile": false
},
"plugins": [
"vue",
"@typescript-eslint"
],
"rules": {
"space-infix-ops": "off",
"object-curly-newline": "off",
"indent": [
"error",
3,
{
"SwitchCase": 1
}
],
"linebreak-style": [
"error",
"unix"
],
"brace-style": [
"error",
"stroustrup"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"curly": [
"error",
"multi-or-nest"
],
"no-console": "off",
"no-undef": "off",
"vue/no-side-effects-in-computed-properties": "off",
"vue/multi-word-component-names": "off",
"vue/require-default-prop": "off",
"vue/comment-directive": "off",
"vue/no-v-html": "off",
"vue/html-indent": [
"error",
3,
{
"attribute": 1,
"baseIndent": 1,
"closeBracket": 0,
"ignores": []
}
],
"vue/max-attributes-per-line": [
"error",
{
"singleline": {
"max": 2
},
"multiline": {
"max": 1
}
}
],
"@typescript-eslint/member-delimiter-style": [
"warn",
{
"multiline": {
"delimiter": "semi",
"requireLast": true
},
"singleline": {
"delimiter": "semi",
"requireLast": false
}
}
],
"@typescript-eslint/no-var-requires": "off"
}
}

6
.gitattributes vendored Normal file
View File

@ -0,0 +1,6 @@
* text eol=lf
*.jpg binary
*.png binary
*.gif binary
*.ico binary
*.icns binary

10
.gitignore vendored Normal file
View File

@ -0,0 +1,10 @@
.DS_Store
dist
build
misc/*
!misc/.gitkeep
node_modules
thumbs.db
NOTES.md
*.txt
*.heapsnapshot

18
.stylelintrc Normal file
View File

@ -0,0 +1,18 @@
{
"extends": [
"stylelint-config-standard",
"stylelint-config-recommended-vue"
],
"fix": true,
"formatter": "verbose",
"plugins": [
"stylelint-scss"
],
"rules": {
"at-rule-no-unknown": null,
"no-descending-specificity": null,
"font-family-no-missing-generic-family-keyword": null,
"declaration-colon-newline-after": "always-multi-line"
},
"syntax": "scss"
}

7
.versionrc.json Normal file
View File

@ -0,0 +1,7 @@
{
"types": [
{"type":"feat","section":"Features"},
{"type":"perf","section":"Improvements"},
{"type":"fix","section":"Bug Fixes"}
]
}

133
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,133 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
fabio286@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within the
community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

100
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,100 @@
# Contributors Guide
Antares SQL is an application based on [Electron.js](https://www.electronjs.org/) that uses [Vue.js](https://vuejs.org/) and [Spectre.css](https://picturepan2.github.io/spectre/) as frontend frameworks.
For the build process it takes advantage of [electron-builder](https://www.electron.build/).
This application uses [Pinia🍍](https://pinia.vuejs.org/) as application state manager and [electron-store](https://github.com/sindresorhus/electron-store) to save the various settings on disc.
This guide aims to provide useful information and guidelines to everyone wants to contribute with this open-source project.
For every other question related to this project please [contact me](https://github.com/Fabio286).
## Project Structure
The main files of the application are located inside `src` folder and are groupped in three subfolders.
### `common`
This folder contains small libraries, classes and objects. The purpose of `common` folder is to group together utilities used by **renderer** and **main** processes.
Noteworthy is the `customizations` folder that contains clients related customizations. Those settings are merged with `default.js` that lists every option.
Client related customizations are stored on Pinia and can be accessed by `customizations` property of current workspace object, or importing `common/customizations`.
An use case of customizations object can be the following:
```js
computed: {
defaultEngine () {
if (this.workspace.customizations.engines)
return this.workspace.engines.find(engine => engine.isDefault).name;
return '';
}
}
```
In this case the computed property `defaultEngine` returns the default engine for MySQL client, or an empty string with PostgreSQL that doesn't have engines.
Customization properties are also useful **if some features are ready for one client but not others**.
### `main`
Inside this folder are located all files required by main process.
`ipc-handlers` subfolder includes all IPC handlers for events sent from renderer process.
`libs` subfolder includes classes related to clients and **query and connection logics**.
**Everything above client's class level should be "client agnostic"** with a neutral and uniformed api interface
### `renderer`
In this folder is located the structure of Vue frontend application.
## Build
The command to build Antares SQL locally is `npm run build`.
## Conventions
### Electron
- **kebab-case** for IPC event names.
### Vue
- **PascalCase** for file names (with .vue extension) and including components inside others (`<MyComponent/>`).
- "**Base**" prefix for [base component names](https://vuejs.org/v2/style-guide/#Base-component-names-strongly-recommended).
- "**The**" prefix for [single-instance component names](https://vuejs.org/v2/style-guide/#Single-instance-component-names-strongly-recommended).
- [Tightly coupled component names](https://vuejs.org/v2/style-guide/#Tightly-coupled-component-names-strongly-recommended).
- [Order of words in component names](https://vuejs.org/v2/style-guide/#Order-of-words-in-component-names-strongly-recommended).
- **kebab-case** in templates for property and event names.
### Code Style
The project includes [ESlint](https://eslint.org/) and [StyleLint](https://stylelint.io/) config files with style rules. I recommend to set the lint on-save option in your code editor.
Alternatively you can launch following commands to lint the project.
Check if all the style rules have been followed:
```console
npm run lint
```
Apply style rules globally if possible:
```console
npm run lint:fix
```
### Other recommendations
Please, use if possible **template literals** to compose strings and **avoid unnecessary dependencies**.
### Commits
The commit style adopted for this project is [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).
Basicly it's important to have **single scoped commits with a prefix** that follows this style because Antares SQL uses [standard-version](https://github.com/conventional-changelog/standard-version) to generate new releases and [CHANGELOG.md](https://github.com/Fabio286/antares/blob/master/CHANGELOG.md) file to track all notable changes.
For Visual Studio Code users may be useful [Conventional Commits](https://marketplace.visualstudio.com/items?itemName=vivaxy.vscode-conventional-commits) extension.
## Debug
**Debug mode**:
```console
npm run debug
```
After running the debug mode Antares will listen on port 9222 (main process) for a debugger.
On **Visual Studio Code** just launch "*Electron: Main*" configurations after running Antares in debug mode.

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
The MIT License (MIT)
Copyright (c) 2020 Fabio Di Stasio
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

22390
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

178
package.json Normal file
View File

@ -0,0 +1,178 @@
{
"name": "mizar",
"productName": "Mizar TCP Debugger",
"version": "1.0.0",
"description": "A TCP client/server debug tool",
"license": "MIT",
"scripts": {
"debug": "npm run rebuild:electron && npm run debug-runner",
"debug-runner": "node scripts/devRunner.js --remote-debug",
"compile": "npm run compile:main && npm run compile:workers && npm run compile:renderer",
"compile:main": "webpack --mode=production --config webpack.main.config.js",
"compile:workers": "webpack --mode=production --config webpack.workers.config.js",
"compile:renderer": "webpack --mode=production --config webpack.renderer.config.js",
"build": "cross-env NODE_ENV=production npm run compile && electron-builder --publish never",
"build:appx": "npm run build -- --win appx",
"rebuild:electron": "rimraf ./dist && npm run postinstall && npm run devtools:install",
"release": "standard-version",
"release:pre": "npm run release -- --prerelease alpha",
"devtools:install": "node scripts/devtoolsInstaller",
"postinstall": "electron-builder install-app-deps",
"test:e2e": "npm run compile && npm run test:e2e-dry",
"test:e2e-dry": "xvfb-maybe -- playwright test",
"lint": "eslint . --ext .js,.ts,.vue && stylelint \"./src/**/*.{css,scss,sass,vue}\"",
"lint:fix": "eslint . --ext .js,.ts,.vue --fix && stylelint \"./src/**/*.{css,scss,sass,vue}\" --fix",
"contributors:add": "all-contributors add",
"contributors:generate": "all-contributors generate"
},
"author": "Fabio Di Stasio <fabio286@gmail.com>",
"main": "./dist/main.js",
"mizar": {
"devtoolsId": "nhdogjmejiglipccpnnnanhbledajbpd"
},
"build": {
"appId": "com.fabio286.mizar",
"artifactName": "${productName}-${version}-${os}_${arch}.${ext}",
"asar": true,
"buildDependenciesFromSource": true,
"directories": {
"output": "build",
"buildResources": "assets"
},
"asarUnpack": "**\\*.{node,dll}",
"files": [
"dist/**/*",
"node_modules",
"package.json"
],
"win": {
"target": [
"nsis",
"portable"
]
},
"linux": {
"target": [
{
"target": "deb",
"arch": [
"x64",
"armv7l",
"arm64"
]
},
{
"target": "AppImage",
"arch": [
"x64",
"armv7l",
"arm64"
]
}
],
"icon": "assets/linux",
"category": "Development"
},
"appImage": {
"license": "./LICENSE",
"category": "Development"
},
"nsis": {
"license": "./LICENSE",
"installerIcon": "assets/icon.ico",
"uninstallerIcon": "assets/icon.ico",
"installerHeader": "assets/icon.ico"
},
"portable": {
"artifactName": "${productName}-${version}-portable.exe"
},
"appx": {
"displayName": "Antares SQL",
"backgroundColor": "transparent",
"showNameOnTiles": true,
"identityName": "62514FabioDiStasio.AntaresSQLClient",
"publisher": "CN=1A2729ED-865C-41D2-9038-39AE2A63AA52",
"applicationId": "FabioDiStasio.AntaresSQLClient"
},
"dmg": {
"contents": [
{
"x": 130,
"y": 220
},
{
"x": 410,
"y": 220,
"type": "link",
"path": "/Applications"
}
]
}
},
"dependencies": {
"@electron/remote": "~2.0.1",
"@mdi/font": "~7.1.96",
"@vueuse/core": "~8.7.5",
"electron-log": "~4.4.1",
"electron-store": "~8.1.0",
"electron-updater": "~4.6.5",
"electron-window-state": "~5.0.3",
"encoding": "~0.1.13",
"floating-vue": "~2.0.0-beta.20",
"moment": "~2.29.4",
"pinia": "~2.0.28",
"source-map-support": "~0.5.20",
"vue": "~3.2.45",
"vue-i18n": "~9.2.2"
},
"devDependencies": {
"@babel/eslint-parser": "~7.15.7",
"@babel/preset-env": "~7.15.8",
"@babel/preset-typescript": "~7.16.7",
"@playwright/test": "~1.28.1",
"@types/node": "~17.0.23",
"@typescript-eslint/eslint-plugin": "~5.18.0",
"@typescript-eslint/parser": "~5.18.0",
"@vue/compiler-sfc": "~3.2.33",
"all-contributors-cli": "~6.20.0",
"babel-loader": "~8.2.3",
"chalk": "~4.1.2",
"cross-env": "~7.0.2",
"css-loader": "~6.5.0",
"electron": "~22.0.3",
"electron-builder": "~22.10.3",
"eslint": "~7.32.0",
"eslint-config-standard": "~16.0.3",
"eslint-plugin-import": "~2.24.2",
"eslint-plugin-node": "~11.1.0",
"eslint-plugin-promise": "~5.2.0",
"eslint-plugin-vue": "~8.0.3",
"file-loader": "~6.2.0",
"html-webpack-plugin": "~5.5.0",
"mini-css-extract-plugin": "~2.4.5",
"node-loader": "~2.0.0",
"playwright": "~1.28.1",
"playwright-core": "~1.28.1",
"postcss-html": "~1.5.0",
"progress-webpack-plugin": "~1.0.12",
"rimraf": "~3.0.2",
"sass": "~1.42.1",
"sass-loader": "~12.3.0",
"standard-version": "~9.3.1",
"style-loader": "~3.3.1",
"stylelint": "~14.9.1",
"stylelint-config-recommended-vue": "~1.4.0",
"stylelint-config-standard": "~26.0.0",
"stylelint-scss": "~4.3.0",
"tree-kill": "~1.2.2",
"ts-loader": "~9.2.8",
"typescript": "~4.6.3",
"unzip-crx-3": "~0.2.0",
"vue-eslint-parser": "~8.3.0",
"vue-loader": "~16.8.3",
"webpack": "~5.72.0",
"webpack-cli": "~4.9.1",
"webpack-dev-server": "~4.11.1",
"xvfb-maybe": "~0.2.1"
}
}

131
scripts/devRunner.js Normal file
View File

@ -0,0 +1,131 @@
process.env.NODE_ENV = 'development';
// process.env.ELECTRON_ENABLE_LOGGING = true
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = false;
const chalk = require('chalk');
const electron = require('electron');
const webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const kill = require('tree-kill');
const path = require('path');
const { spawn } = require('child_process');
const mainConfig = require('../webpack.main.config');
const rendererConfig = require('../webpack.renderer.config');
const workersConfig = require('../webpack.workers.config');
let electronProcess = null;
let manualRestart = null;
const remoteDebugging = process.argv.includes('--remote-debug');
if (remoteDebugging) {
// disable devtools open in electron
process.env.RENDERER_REMOTE_DEBUGGING = true;
}
async function killElectron (pid) {
return new Promise((resolve, reject) => {
if (pid) {
kill(pid, 'SIGKILL', err => {
if (err) reject(err);
resolve();
});
}
else
resolve();
});
}
async function restartElectron () {
console.log(chalk.gray('\nStarting electron...'));
const { pid } = electronProcess || {};
await killElectron(pid);
electronProcess = spawn(electron, [
path.join(__dirname, '../dist/main.js'),
// '--enable-logging', // Enable to show logs from all electron processes
remoteDebugging ? '--inspect=9222' : '',
remoteDebugging ? '--remote-debugging-port=9223' : ''
]);
electronProcess.stdout.on('data', data => {
console.log(chalk.white(data.toString()));
});
electronProcess.stderr.on('data', data => {
console.error(chalk.red(data.toString()));
});
electronProcess.on('exit', () => {
if (!manualRestart) process.exit(0);
});
}
function startMain () {
const webpackSetup = webpack([mainConfig, workersConfig]);
webpackSetup.compilers.forEach((compiler) => {
const { name } = compiler;
switch (name) {
case 'workers':
compiler.hooks.afterEmit.tap('afterEmit', async () => {
console.log(chalk.gray(`\nCompiled ${name} script!`));
console.log(
chalk.gray(`\nWatching file changes for ${name} script...`)
);
});
break;
case 'main':
default:
compiler.hooks.afterEmit.tap('afterEmit', async () => {
console.log(chalk.gray(`\nCompiled ${name} script!`));
manualRestart = true;
await restartElectron();
setTimeout(() => {
manualRestart = false;
}, 2500);
console.log(
chalk.gray(`\nWatching file changes for ${name} script...`)
);
});
break;
}
});
webpackSetup.watch({ aggregateTimeout: 500 }, err => {
if (err) console.error(chalk.red(err));
});
}
function startRenderer (callback) {
const compiler = webpack(rendererConfig);
const { name } = compiler;
compiler.hooks.afterEmit.tap('afterEmit', () => {
console.log(chalk.gray(`\nCompiled ${name} script!`));
console.log(chalk.gray(`\nWatching file changes for ${name} script...`));
});
const server = new WebpackDevServer(compiler, {
port: 9080,
client: {
overlay: true,
logging: 'warn'
}
});
server.startCallback(err => {
if (err) console.error(chalk.red(err));
callback();
});
}
startRenderer(startMain);

View File

@ -0,0 +1,49 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
const fs = require('fs');
const path = require('path');
const https = require('https');
const unzip = require('unzip-crx-3');
const { antares } = require('../package.json');
const extensionID = antares.devtoolsId;
const destFolder = path.resolve(__dirname, `../misc/${extensionID}`);
const filePath = path.resolve(__dirname, `${destFolder}${extensionID}.crx`);
const fileUrl = `https://clients2.google.com/service/update2/crx?response=redirect&acceptformat=crx2,crx3&x=id%3D${extensionID}%26uc&prodversion=32`;
const fileStream = fs.createWriteStream(filePath);
const downloadFile = url => {
return new Promise((resolve, reject) => {
const request = https.get(url);
request.on('response', response => {
if (response.statusCode && response.statusCode >= 300 && response.statusCode < 400 && response.headers.location) {
return downloadFile(response.headers.location)
.then(resolve)
.catch(reject);
}
response.pipe(fileStream);
response.on('close', () => {
console.log('Devtools download completed!');
resolve();
});
response.on('error', reject);
});
request.on('error', reject);
request.end();
});
};
(async () => {
try {
await downloadFile(fileUrl);
await unzip(filePath, destFolder);
fs.unlinkSync(filePath);
fs.unlinkSync(`${destFolder}/package.json`);// <- Avoid to display annoyng npm script in vscode
}
catch (error) {
console.log(error);
}
})();

408
src/main/libs/Sender.js Normal file
View File

@ -0,0 +1,408 @@
'use strict';
const net = require('net');
const fs = require('fs');
class Sender {
/**
*Creates an instance of Sender.
* @param {*} process Processo dove inviare i log
* @memberof Sender
*/
constructor (process) {
this.process = process;
this.closeOnEcho = true;
this.persistentConnection = false;
this.nMsgs = 0;
this.tMin = 0;
this.tMax = 0;
this.nClients = 1;
this.trace = false;
this.alertReset = false;
this.hexMsg = false;
this.nConnected = 0;
this.nClosed = 0;
this.nTryConnect = 0;
this.nReceived = [];
this.nSent = 0;
this.timeStart = new Date();
this.hosts = [];
this.messages = [];
this.nHostClients = [];
this.nHostBytes = [];
this.nHostMsgs = [];
this.storagePath = '';
}
/**
* Setta gli hosts
*
* @param {*} hosts
* @memberof Sender
*/
setHosts (hosts) {
this.hosts = hosts;
}
/**
* Setta i parametri del messaggio
*
* @param {*} params
* @memberof Sender
*/
setParams (params) {
this.closeOnEcho = params.closeOnEcho;
this.persistentConnection = params.persistentConnection;
this.nMsgs = params.nMsgs;
this.tMin = params.tMin;
this.tMax = params.tMax;
this.nClients = params.nClients;
this.trace = params.trace;
this.alertReset = params.alertReset;
this.loop = params.loop;
}
/**
* Setta il percorso della cartella storage
*
* @param {string} storagePath
* @memberof Sender
*/
setStoragePath (storagePath) {
this.storagePath = storagePath;
}
/**
* Carica i messaggi in memoria
*
* @memberof Sender
*/
loadMessages () {
let self = this;
if (self.trace) this.sendLog('Lettura dei messaggi');
let messages = fs.readFileSync(`${self.storagePath}/storage/clientMessages.json`);
messages = JSON.parse(messages);
this.messages = messages.filter((message) => {
return message.enabled === true;
});
if (self.trace) this.sendLog(`Messaggi caricari: ${this.messages.length}`);
}
/**
* Invia i log al render process
*
* @param {string} message Messaggio del log
* @param {string} [color=''] Colore del log (green, yellow, red)
* @memberof Sender
*/
sendLog (message, color = '') {
let log = {
event: 'log',
content: { message, color }
};
this.process.send(log);
}
/** Restituisce un messaggio casuale */
randMsg () {
let self = this;
if (self.messages.length > 0) {
let index = Math.floor((Math.random() * (self.messages.length)));
let msg;
switch (self.messages[index].format) {
case 'ascii':
msg = Buffer.from(self.messages[index].message, 'ascii');
break;
case 'hex':
msg = Buffer.from(self.messages[index].message.replace(/\s|0x/g, ''), 'hex');
break;
case 'binary':
msg = Buffer.from(self.messages[index].message.replace(/\s/g, ''), 'binary');
break;
}
return msg;
}
else return 'Nessun messaggio specificato';
};
/**
* Istanzia i client e invia i messaggi
*
* @param {*} params Parametri dei client
* @memberof Sender
*/
startFullTest (callback) {
let self = this;
/** Carica in memoria i messaggi */
self.loadMessages();
/** Applica uno sleep */
function delay () {
let wait = Math.floor((Math.random() * self.tMax) + self.tMin);
return new Promise(resolve => setTimeout(resolve, wait));
}
for (let x = 0; x < self.hosts.length; x++) { // hosts for
let params = self.hosts[x];
self.hosts[x].clients = [];
self.nHostClients[x] = 0;
self.nHostMsgs[x] = self.nHostMsgs[x] === undefined ? 0 : self.nHostMsgs[x];
self.nHostBytes[x] = self.nHostBytes[x] === undefined ? 0 : self.nHostBytes[x];
self.nReceived[x] = self.nReceived[x] === undefined ? 0 : self.nReceived[x];
for (let i = 0; i < self.nClients; i++) { // clients for
self.hosts[x].clients[i] = new net.Socket();
let client = self.hosts[x].clients[i];
let clientId = i + 1;
try {
client.connect(params, () => {
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} aperto`);
self.nHostClients[x]++;
(async () => {
for (let i = 0; i < self.nMsgs; i++) { // msg for
await delay();
let msg = self.randMsg();
client.write(msg, err => {
if (err)
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\nErrore messaggio: ${err}`, 'red');
else {
self.nSent++;
self.nHostMsgs[x]++;
self.nHostBytes[x] += msg.length;
}
});
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} messaggio #${i + 1}`);
if (i + 1 === self.nMsgs && !self.closeOnEcho && !self.persistentConnection) client.end();
}// <- msg for
})();
});
}
catch (err) {
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\n${err}`, 'red');
}
client.on('connect', err => {
self.nTryConnect++;
if (err)
self.sendLog(`Errore connessione #${clientId} su ${params.host}:${params.port}:\n${err}`, 'red');
else
self.nConnected++;
// if (self.nConnected === (self.nClients * self.hosts.length)) self.getReport();
});
client.on('data', data => {
self.nReceived[x]++;
if (self.closeOnEcho)
client.end();
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} risposta: ${data}`);
});
client.on('close', () => {
self.nClosed++;
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} chiuso`);
// Misura tempo esecuzione
if (self.nClosed === self.nTryConnect) {
if (!self.loop) self.getConsoleReports();
callback();
}
});
client.on('error', err => {
switch (err.code) {
case 'ECONNRESET':
if (self.alertReset)
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\n${err}`, 'yellow');
break;
default:
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\n${err}`, 'red');
}
});
}// <- clients for
}// <- hosts for
}
/**
* Connette i client per il test a step
*
* @param {*} callback
* @memberof Sender
*/
connectClients (callback) {
let self = this;
for (let x = 0; x < self.hosts.length; x++) { // hosts for
let params = self.hosts[x];
self.hosts[x].clients = [];
self.nHostMsgs[x] = 0;
self.nHostBytes[x] = 0;
self.nHostClients[x] = 0;
self.nReceived[x] = 0;
for (let i = 0; i < self.nClients; i++) { // clients for
self.hosts[x].clients[i] = new net.Socket();
let client = self.hosts[x].clients[i];
let clientId = i + 1;
try {
client.connect(params, () => {
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} aperto`);
self.nHostClients[x]++;
});
}
catch (err) {
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\n${err}`, 'red');
}
client.on('connect', err => {
self.nTryConnect++;
if (err)
self.sendLog(`Errore connessione #${clientId} su ${params.host}:${params.port}:\n${err}`, 'red');
else
self.nConnected++;
// if (self.nConnected === (self.nClients * self.hosts.length)) self.getReport();
if ((self.nClients * self.hosts.length) === self.nTryConnect) callback();
});
client.on('data', data => {
self.nReceived[x]++;
if (self.closeOnEcho)
client.end();
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} risposta: ${data}`);
});
client.on('close', () => {
self.nClosed++;
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} chiuso`);
});
client.on('error', err => {
switch (err.code) {
case 'ECONNRESET':
if (self.alertReset)
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\n${err}`, 'yellow');
break;
default:
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\n${err}`, 'red');
}
});
}// <- clients for
}// <- hosts for
}
/**
* Invia i messaggi nella modalità a step
*
* @param {*} callback
* @memberof Sender
*/
sendMessages (callback) {
let self = this;
/** Carica in memoria i messaggi */
self.loadMessages();
self.nSent = 0;
/** Applica uno sleep */
function delay () {
let wait = Math.floor((Math.random() * self.tMax) + self.tMin);
return new Promise(resolve => setTimeout(resolve, wait));
}
for (let x = 0; x < self.hosts.length; x++) { // hosts for
for (let i = 0; i < self.hosts[x].clients.length; i++) { // clients for
let client = self.hosts[x].clients[i];
let params = self.hosts[x];
let clientId = i + 1;
(async () => {
for (let i = 0; i < self.nMsgs; i++) { // msg for
await delay();
let msg = self.randMsg();
client.write(msg, err => {
if (err)
self.sendLog(`Socket #${clientId} su ${params.host}:${params.port}:\nErrore messaggio: ${err}`, 'red');
else {
self.nSent++;
self.nHostMsgs[x]++;
self.nHostBytes[x] += msg.length;
if ((self.nMsgs * self.hosts.length * self.nClients) === self.nSent) callback();
}
});
if (self.trace) self.sendLog(`Socket #${clientId} su ${params.host}:${params.port} messaggio #${i + 1}`);
}// <- msg for
})();
}// <- clients for
}// <- hosts for
}
/** Genera il report su console */
getConsoleReports () {
let self = this;
let end = new Date() - self.timeStart;
let report = `Durata del test: ${end}ms`;
self.sendLog(report, 'green');
}
stopClients (callback) {
let self = this;
for (let x = 0; x < self.hosts.length; x++) {
for (let i = 0; i < self.hosts[x].clients.length; i++)
self.hosts[x].clients[i].end();
}
self.getConsoleReports();
callback();
}
getReports () {
let self = this;
let reportList = [];
for (let i = 0; i < self.hosts.length; i++) {
let report = {
host: `${self.hosts[i].host}:${self.hosts[i].port}`,
sockets: self.nHostClients[i],
data: self.nHostBytes[i],
messages: self.nHostMsgs[i],
received: self.nReceived[i]
};
reportList.push(report);
if ((i + 1) === self.hosts.length) {
let rep = {
event: 'report',
content: reportList
};
self.process.send(rep);
}
}
}
resetReports () {
let self = this;
for (let i = 0; i < self.hosts.length; i++) {
self.nHostBytes[i] = 0;
self.nHostMsgs[i] = 0;
self.nHostClients[i] = 0;
self.nReceived[i] = 0;
}
}
}
module.exports = Sender;

143
src/main/libs/Server.js Normal file
View File

@ -0,0 +1,143 @@
'use strict';
const net = require('net');
class Server {
constructor (process) {
this.process = process;
this.trace = false;
this.echo = false;
this.alertReset = false;
this.ports = [];
this.server = [];
this.nBytes = [];
this.nMsgs = [];
}
/**
* Setta le porte
*
* @param {*} ports
* @memberof Server
*/
setPorts (ports) {
this.ports = ports;
}
/**
* Invia i log al render process
*
* @param {string} message Messaggio del log
* @param {string} [color=''] Colore del log (green, yellow, red)
* @memberof Server
*/
sendLog (message, color = '') {
let log = {
event: 'log',
content: { message, color }
};
this.process.send(log);
}
startServer (params) {
let self = this;
self.trace = params.trace;
self.echo = params.echo;
self.alertReset = params.alertReset;
for (let i = 0; i < self.ports.length; i++) {
let port = self.ports[i].port;
self.server[i] = net.createServer();
self.nBytes[i] = 0;
self.nMsgs[i] = 0;
self.server[i].on('connection', socket => {
if (self.trace) self.sendLog(`Client connesso su porta ${port}`);
socket.on('data', msg => {
let msgString = msg.toString();
if (self.echo) socket.write(msg);
self.nBytes[i] += msg.length;
self.nMsgs[i]++;
if (self.trace) self.sendLog(`Messaggio ricevuto su porta ${port}: ${msgString}`);
});// <- socket data
socket.on('end', () => {
if (self.trace) self.sendLog(`Client disconnesso su porta ${port}`);
});
socket.on('error', (err) => {
switch (err.code) {
case 'ECONNRESET':
if (self.alertReset)
self.sendLog(`Errore client su porta ${port}: \n${err}`, 'yellow');
else
if (self.trace) self.sendLog(`Client disconnesso su porta ${port}`);
break;
default:
self.sendLog(`Errore client su porta ${port}: \n${err}`, 'red');
}
});
});// <- server
self.server[i].on('error', err => {
self.sendLog(`Errore server su porta ${port}: \n${err}`, 'red');
});
self.server[i].listen(port, () => {
self.sendLog(`In ascolto sulla porta ${port}`);
});
}
}
stopServer (callback) {
let self = this;
(async () => {
for (let i = 0; i < self.server.length; i++) {
await self.server[i].close(function () {
self.server[i].unref();
});
}
callback();
})();
}
getReports () {
let self = this;
let reportList = [];
for (let i = 0; i < self.server.length; i++) {
let report = {
port: self.server[i].address().port,
sockets: null,
data: self.nBytes[i],
messages: self.nMsgs[i]
};
self.server[i].getConnections((err, nSockets) => {
if (err) self.sendLog(`Errore report: \n${err}`, 'red');
report.sockets = nSockets;
reportList.push(report);
if ((i + 1) === self.server.length) {
let rep = {
event: 'report',
content: reportList
};
self.process.send(rep);
}
});
}
}
resetReports () {
let self = this;
for (let i = 0; i < self.server.length; i++) {
self.nBytes[i] = 0;
self.nMsgs[i] = 0;
}
}
}
module.exports = Server;

230
src/main/main.ts Normal file
View File

@ -0,0 +1,230 @@
import { app, BrowserWindow, nativeImage, ipcMain } from 'electron';
import * as fs from 'fs';
import * as path from 'path';
import * as Store from 'electron-store';
import { ChildProcess, fork, Serializable } from 'child_process';
import * as windowStateKeeper from 'electron-window-state';
import * as remoteMain from '@electron/remote/main';
// import ipcHandlers from './ipc-handlers';
Store.initRenderer();
const settingsStore = new Store({ name: 'settings' });
const appTheme = settingsStore.get('application_theme');
const isDevelopment = process.env.NODE_ENV !== 'production';
const isMacOS = process.platform === 'darwin';
const isLinux = process.platform === 'linux';
const isWindows = process.platform === 'win32';
const gotTheLock = app.requestSingleInstanceLock();
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
// global reference to mainWindow (necessary to prevent window from being garbage collected)
let mainWindow: BrowserWindow;
let mainWindowState: windowStateKeeper.State;
async function createMainWindow () {
const icon = require('../renderer/assets/icons/icon.png');
const window = new BrowserWindow({
width: mainWindowState.width,
height: mainWindowState.height,
x: mainWindowState.x,
y: mainWindowState.y,
minWidth: 900,
minHeight: 550,
show: !isWindows,
title: 'Mizar',
icon: nativeImage.createFromDataURL(icon.default),
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
devTools: isDevelopment,
spellcheck: false
},
autoHideMenuBar: true,
titleBarStyle: isLinux ? 'default' :'hidden',
titleBarOverlay: isWindows
? {
color: appTheme === 'dark' ? '#3f3f3f' : '#fff',
symbolColor: appTheme === 'dark' ? '#fff' : '#000',
height: 30
}
: false,
trafficLightPosition: isMacOS ? { x: 10, y: 8 } : undefined,
backgroundColor: '#1d1d1d'
});
mainWindowState.manage(window);
window.on('moved', saveWindowState);
remoteMain.enable(window.webContents);
try {
if (isDevelopment)
await window.loadURL('http://localhost:9080');
else {
const indexPath = path.resolve(__dirname, 'index.html');
await window.loadFile(indexPath);
}
}
catch (err) {
console.log(err);
}
window.on('closed', () => {
window.removeListener('moved', saveWindowState);
mainWindow = null;
});
return window;
}
if (!gotTheLock) app.quit();
else {
require('@electron/remote/main').initialize();
// Initialize ipcHandlers
// ipcHandlers();
ipcMain.on('refresh-theme-settings', () => {
const appTheme = settingsStore.get('application_theme');
if (isWindows && mainWindow) {
mainWindow.setTitleBarOverlay({
color: appTheme === 'dark' ? '#3f3f3f' : '#fff',
symbolColor: appTheme === 'dark' ? '#fff' : '#000'
});
}
});
ipcMain.on('change-window-title', (_, title: string) => {
if (mainWindow) mainWindow.setTitle(title);
});
// quit application when all windows are closed
app.on('window-all-closed', () => {
// on macOS it is common for applications to stay open until the user explicitly quits
if (!isMacOS) app.quit();
});
app.on('activate', async () => {
// on macOS it is common to re-create a window even after all windows have been closed
if (mainWindow === null)
mainWindow = await createMainWindow();
});
// create main BrowserWindow when electron is ready
app.on('ready', async () => {
mainWindowState = windowStateKeeper({
defaultWidth: 1024,
defaultHeight: 800
});
mainWindow = await createMainWindow();
if (isWindows)
mainWindow.show();
// if (isDevelopment)
// mainWindow.webContents.openDevTools();
process.on('uncaughtException', error => {
mainWindow.webContents.send('unhandled-exception', error);
});
process.on('unhandledRejection', error => {
mainWindow.webContents.send('unhandled-exception', error);
});
});
app.on('browser-window-created', (event, window) => {
if (isDevelopment) {
const { mizar } = require('../../package.json');
const extensionPath = path.resolve(__dirname, `../../misc/${mizar.devtoolsId}`);
window.webContents.session.loadExtension(extensionPath, { allowFileAccess: true }).catch(console.error);
}
});
}
// Server
let serverProcess: ChildProcess;
ipcMain.on('startServer', (event, { params, ports }) => {
event.sender.send('serverLog', { message: 'Server avviato', color: '' });
serverProcess = fork(isDevelopment ? './dist/serverProcess.js' : path.resolve(__dirname, './serverProcess.js'), [], {
execArgv: isDevelopment ? ['--inspect=9224'] : undefined
});
const message = {
event: 'start',
params,
ports
};
serverProcess.send(message);
serverProcess.on('message', (message: Serializable & {event: string; content: string}) => {
if (!mainWindow) return;
switch (message.event) {
case 'log':
mainWindow.webContents.send('serverLog', message.content);
break;
case 'report':
mainWindow.webContents.send('reportServerList', message.content);