Skip to content

Commit

Permalink
Merge pull request #26 from aminekun90/dev
Browse files Browse the repository at this point in the history
Update v3.2.8
  • Loading branch information
aminekun90 authored Jul 17, 2024
2 parents 1c1f841 + a9ab982 commit 4f924a7
Show file tree
Hide file tree
Showing 7 changed files with 1,417 additions and 581 deletions.
5 changes: 5 additions & 0 deletions .hintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"extends": [
"development"
]
}
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
v20.9.0
v20.13.1
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ I recommand using this python publisher https://github.com/aminekun90/python_zer
- **Note that `mdns-listener-advanced` includes a bonjour publisher since `version 3.1.0`**

## Requirements
- Node 18 or later (we recommend using [NVM](https://github.com/nvm-sh/nvm)) this package is using Node v20
- Node 18 or later (we recommend using [NVM](https://github.com/nvm-sh/nvm)) this package is using Node v20.13.1 as of today



Expand Down
1,905 changes: 1,371 additions & 534 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "mdns-listener-advanced",
"version": "3.2.7",
"version": "3.2.8",
"description": "mDNS listener, add as many .local hostnames to your computer as you like.",
"author": "aminekun90",
"funding": [
Expand All @@ -13,11 +13,11 @@
"types": "dist/types/index.d.js",
"dependencies": {
"@types/multicast-dns": "^7.2.1",
"@types/uuid": "^9.0.1",
"@types/uuid": "^10.0.0",
"bonjour-service": "^1.2.1",
"multicast-dns": "^7.2.5",
"tslog": "^4.9.2",
"uuid": "^9.0.0"
"uuid": "^10.0.0"
},
"engines": {
"npm": ">=9.8.1",
Expand Down Expand Up @@ -72,7 +72,7 @@
"devDependencies": {
"@types/node": "^20.11.27",
"commitlint": "^19.0.3",
"eslint": "^8.52.0",
"eslint": "^9.7.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.1",
"husky": "^9.0.6",
Expand Down
67 changes: 30 additions & 37 deletions src/Core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,17 @@ import { EventEmitter } from 'events';
import { Device, DeviceBuffer, DeviceData, NPM_URL, Options, EmittedEvent } from './types';
import mDNS from 'multicast-dns';
import { Bonjour, ServiceConfig } from 'bonjour-service';
import { Logger } from "tslog";

import { Logger } from 'tslog';
import { v4 as uuidv4 } from 'uuid';

/**
* MDNS Advanced Core Class
*/
export class Core {
private hostnames: Array<string>;
private mdnsHostsFile: string | null | undefined;
private debugEnabled: boolean = false;
private disableListener: boolean = false;
private hostnames: string[];
private mdnsHostsFile?: string;
private debugEnabled: boolean;
private disableListener: boolean;
private error: boolean = false;

/**
Expand All @@ -31,13 +30,13 @@ export class Core {
hostsList?: string[] | null,
mdnsHostsPath?: string | null,
options?: Options,
private logger:Logger<any> = new Logger({name:'MDNS ADVANCED'}),
private logger: Logger<any> = new Logger({ name: 'MDNS ADVANCED' }),
private mdns = mDNS(),
private myEvent = new EventEmitter(),
private publisher = new Bonjour(),
private publisher = new Bonjour()
) {
this.hostnames = hostsList ?? [];
this.mdnsHostsFile = mdnsHostsPath;
this.mdnsHostsFile = mdnsHostsPath ?? undefined;
this.debugEnabled = !!options?.debug;
this.disableListener = !!options?.disableListener;
}
Expand All @@ -46,7 +45,7 @@ export class Core {
* Console debugging function
* @param {...any} args
*/
debug(...args: unknown[]) {
private debug(...args: unknown[]): void {
if (this.debugEnabled) {
this.logger.debug(...args);
}
Expand All @@ -56,20 +55,19 @@ export class Core {
* Console info function
* @param {...any} args
*/
info(...args: unknown[]) {
private info(...args: unknown[]): void {
this.logger.info(...args);
}

/**
* Initialize mdns
* Initialize mdns listener
* @private
*/
private __initListener() {
private __initListener(): void {
try {
this.hostnames = this.__getHosts()
.split('\n')
.map((name) => name.replace(/#.*/, '')) // Remove comments
.map((name) => name.trim()) // Trim lines
.map((name) => name.replace(/#.*/, '').trim()) // Remove comments and trim lines
.filter((name) => name.length > 0); // Remove empty lines
if (!this.hostnames.length) {
this.logger.warn('Hosts are empty');
Expand All @@ -87,15 +85,13 @@ export class Core {
*/
private __getHosts(): string {
if (this.mdnsHostsFile && existsSync(this.mdnsHostsFile)) {
return readFileSync(this.mdnsHostsFile, {
encoding: 'utf-8',
});
} else if (this.hostnames?.length) {
return this.hostnames?.join('\r\n');
return readFileSync(this.mdnsHostsFile, { encoding: 'utf-8' });
} else if (this.hostnames.length) {
return this.hostnames.join('\r\n');
} else {
this.mdnsHostsFile = platform().startsWith('win')
? process.env.HOMEPATH + '\\' + '.mdns-hosts'
: process.env.HOME + '/' + '.mdns-hosts';
? `${process.env.HOMEPATH}\\.mdns-hosts`
: `${process.env.HOME}/.mdns-hosts`;
if (existsSync(this.mdnsHostsFile)) {
return this.__getHosts();
}
Expand All @@ -106,7 +102,7 @@ export class Core {

/**
* Get Current Device IP
* @return {Array<string>}
* @return {string | undefined}
* @private
*/
private getLocalIpAddress(): string | undefined {
Expand All @@ -129,25 +125,25 @@ export class Core {
* @param name
*/
public publish(name: string) {
const options = {
const options: ServiceConfig = {
port: 3000,
name: name,
type: 'TXT',
txt: {
uuid: `"${uuidv4()}"`,
ipv4: JSON.stringify(this.getLocalIpAddress()),
},
} as ServiceConfig;
};
const bonjourService = this.publisher.publish(options);
this.info('A hostname have been published with options', options);
this.info('A hostname has been published with options', options);
this.debug(bonjourService);
return bonjourService;
}

/**
* Unpublish the publisher
* Unpublish all hosts
*/
public unpublishAll() {
public unpublishAll(): void {
this.publisher.unpublishAll();
this.info('All hostnames have been unpublished');
}
Expand All @@ -168,7 +164,7 @@ export class Core {
this.myEvent.on(EmittedEvent.ERROR, (e) => {
this.info(e.message);
});
const errorMessage = `An error occurred while trying to listen to mdns ! Report this error ${NPM_URL}`;
const errorMessage = `An error occurred while trying to listen to mdns! Report this error ${NPM_URL}`;
this.myEvent.emit(EmittedEvent.ERROR, new Error(errorMessage));
return this.myEvent;
}
Expand All @@ -179,11 +175,11 @@ export class Core {
}

/**
* Handle buffer data and transform them to a json object
* Handle buffer data and transform them to a JSON object
* @param dataBuffer
* @returns
*/
private handleBufferData(dataBuffer: Buffer) {
private handleBufferData(dataBuffer: Buffer): { [key: string]: string } {
const str = dataBuffer.toString('utf8');
const propertiesMatch = str.match(/(\w+)=("[^"]*"|\S+)/g);
const properties: { [key: string]: string } = {};
Expand All @@ -198,10 +194,9 @@ export class Core {

/**
* Handle mdns response
*
* @param response
*/
private handleResponse(response: { answers: Array<DeviceBuffer> }) {
private handleResponse(response: { answers: Array<DeviceBuffer> }): void {
const findHosts: Array<Device> = [];
this.debug('RESPONSE:', response);
this.myEvent.emit(EmittedEvent.RAW_RESPONSE, response);
Expand All @@ -223,16 +218,14 @@ export class Core {
}

/**
* Stop listening and kills the emmiter
* Stop listening and remove all listeners
* @public
*/
public stop() {
public stop(): void {
this.info('Stopping mdns listener...');
// fix mdns undefined sometimes
if (this.mdns?.removeAllListeners) {
this.mdns.removeAllListeners();
}
// fix myEvent undefined
if (this.myEvent?.removeAllListeners) {
this.myEvent.removeAllListeners();
}
Expand Down
9 changes: 5 additions & 4 deletions src/example.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import { Logger } from 'tslog';
import { Core } from './Core';
import { Device, EmittedEvent } from './types';
const ref = 'MyDevice2';
const mdns = new Core([ref], null, {
debug: false,
disableListener: false,
});

const logger = new Logger()
const event = mdns.listen();
mdns.publish(ref);
event.on(EmittedEvent.RESPONSE, (found_hostnames: Array<Device>) => {
mdns.info('found hostnames', found_hostnames);
logger.info('found hostnames', found_hostnames);
// mdns.stop();// To stop the listener
});
event.on(EmittedEvent.RAW_RESPONSE, (hosts: object) => {
mdns.info('raw response', hosts);
logger.info('raw response', hosts);
});
event.on(EmittedEvent.ERROR, (error: Error) => {
mdns.info('error', error);
logger.info('error', error);
// mdns.stop();// To stop the listener
});

0 comments on commit 4f924a7

Please sign in to comment.