Minor refactoring work

This commit is contained in:
David Majdandžić
2023-03-30 18:11:12 +02:00
parent 2374cba341
commit 10cf382d00
12 changed files with 139 additions and 405 deletions

View File

@@ -1,30 +0,0 @@
// @ts-ignore
const Websocket = require('ws');
const ws = new Websocket('ws://localhost:8191');
ws.on('open', function open() {
ws.send('something');
});
interface Animal {
doNoise(): void;
}
class Dog implements Animal {
doNoise(): void {
console.log("woof");
}
}
class Cat implements Animal {
doNoise(): void {
console.log("meow");
}
}
const dog = new Dog();
dog.doNoise();
const cat = new Cat();
cat.doNoise();
let animals: Animal[] = [dog, cat];
animals.forEach(animal => animal.doNoise());

View File

@@ -14,16 +14,15 @@ export class Center extends SmppSession {
"CONNECTING", "CONNECTING",
"CONNECTED", "CONNECTED",
]; ];
_username: string;
id: number; _password: string;
username: string; _id: number;
password: string; _status: string = this.STATUS[0];
status: string = this.STATUS[0]; _defaultSingleJob: Job;
_defaultMultipleJob: Job;
port: number; port: number;
pduProcessors: PduProcessor[] = []; pduProcessors: PduProcessor[] = [];
defaultSingleJob!: Job;
defaultMultipleJob!: Job;
readonly logger: Logger; readonly logger: Logger;
private pendingSessions: any[] = []; private pendingSessions: any[] = [];
private sessions: any[] = []; private sessions: any[] = [];
@@ -32,13 +31,13 @@ export class Center extends SmppSession {
constructor(id: number, port: number, username: string, password: string) { constructor(id: number, port: number, username: string, password: string) {
super(); super();
this.id = id; this._id = id;
this.username = username; this._username = username;
this.password = password; this._password = password;
this.port = port; this.port = port;
this.defaultSingleJob = Job.createEmptySingle(); this._defaultSingleJob = Job.createEmptySingle();
this.defaultMultipleJob = Job.createEmptyMultiple(); this._defaultMultipleJob = Job.createEmptyMultiple();
this.logger = new Logger(`Center-${id}`); this.logger = new Logger(`Center-${id}`);
@@ -49,9 +48,9 @@ export class Center extends SmppSession {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.validateSessions(reject); this.validateSessions(reject);
if (!job.count || !job.perSecond) { if (!job.count || !job.perSecond) {
reject(`Center-${this.getId()} sendMultiple failed: invalid job, missing fields`); reject(`Center-${this.id} sendMultiple failed: invalid job, missing fields`);
} }
this.logger.log1(`Center-${this.getId()} sending multiple messages: ${JSON.stringify(job)}`); this.logger.log1(`Center-${this.id} sending multiple messages: ${JSON.stringify(job)}`);
let counter = 0; let counter = 0;
let previousUpdateCounter = 0; let previousUpdateCounter = 0;
@@ -82,7 +81,7 @@ export class Center extends SmppSession {
if (!force) { if (!force) {
this.validateSessions(reject); this.validateSessions(reject);
} }
this.logger.log5(`Center-${this.getId()} sending PDU: ${JSON.stringify(pdu)}`); this.logger.log5(`Center-${this.id} sending PDU: ${JSON.stringify(pdu)}`);
this.getNextSession().send(pdu, (replyPdu: any) => { this.getNextSession().send(pdu, (replyPdu: any) => {
resolve(replyPdu); resolve(replyPdu);
}); });
@@ -98,7 +97,7 @@ export class Center extends SmppSession {
close(): Promise<void> { close(): Promise<void> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
this.logger.log1(`Center-${this.getId()} closing active connections`); this.logger.log1(`Center-${this.id} closing active connections`);
this.server.close(); this.server.close();
this.setStatus(0); this.setStatus(0);
resolve(); resolve();
@@ -138,10 +137,10 @@ export class Center extends SmppSession {
} }
private eventBindTransceiver(session: any, pdu: PDU) { private eventBindTransceiver(session: any, pdu: PDU) {
this.logger.log1(`Center-${this.getId()} got a bind_transciever with system_id ${pdu.system_id} and password ${pdu.password}`); this.logger.log1(`Center-${this.id} got a bind_transciever with system_id ${pdu.system_id} and password ${pdu.password}`);
session.pause(); session.pause();
if (pdu.system_id === this.username && pdu.password === this.password) { if (pdu.system_id === this.username && pdu.password === this.password) {
this.logger.log1(`Center-${this.getId()} client connection successful`); this.logger.log1(`Center-${this.id} client connection successful`);
if (pdu.response) { if (pdu.response) {
session.send(pdu.response()); session.send(pdu.response());
} }
@@ -150,7 +149,7 @@ export class Center extends SmppSession {
this.sessions.push(session); this.sessions.push(session);
this.updateStatus(); this.updateStatus();
} else { } else {
this.logger.log1(`Center-${this.getId()} client connection failed, invalid credentials (expected: ${this.username}, ${this.password})`); this.logger.log1(`Center-${this.id} client connection failed, invalid credentials (expected: ${this.username}, ${this.password})`);
if (pdu.response) { if (pdu.response) {
session.send(pdu.response({ session.send(pdu.response({
command_status: smpp.ESME_RBINDFAIL command_status: smpp.ESME_RBINDFAIL
@@ -163,7 +162,7 @@ export class Center extends SmppSession {
} }
private eventSessionConnected(session: any): void { private eventSessionConnected(session: any): void {
this.logger.log1(`A client connected to center-${this.getId()}`); this.logger.log1(`A client connected to center-${this.id}`);
this.pendingSessions.push(session); this.pendingSessions.push(session);
session.on('close', this.eventSessionClose.bind(this, session)); session.on('close', this.eventSessionClose.bind(this, session));
session.on('error', this.eventSessionError.bind(this, session)); session.on('error', this.eventSessionError.bind(this, session));
@@ -174,11 +173,11 @@ export class Center extends SmppSession {
} }
private eventSessionError(session: any): void { private eventSessionError(session: any): void {
this.logger.log1(`A client encountered an error on center-${this.getId()}`); this.logger.log1(`A client encountered an error on center-${this.id}`);
} }
private eventSessionClose(session: any): void { private eventSessionClose(session: any): void {
this.logger.log1(`A client disconnected from center-${this.getId()}`); this.logger.log1(`A client disconnected from center-${this.id}`);
this.sessions = this.sessions.filter((s: any) => s !== session); this.sessions = this.sessions.filter((s: any) => s !== session);
this.nextSession = 0; this.nextSession = 0;
this.pendingSessions = this.pendingSessions.filter((s: any) => s !== session); this.pendingSessions = this.pendingSessions.filter((s: any) => s !== session);

View File

@@ -16,7 +16,6 @@ export class CenterSessionManager extends SessionManager {
constructor() { constructor() {
super(); super();
this.setup(); this.setup();
// super.eventEmitter.on(super.SESSION_ADDED_EVENT, (session: SmppSession) => this.eventEmitter.emit(this.SESSION_ADDED_EVENT, session));
} }
comparatorFn: (arg: any, session: SmppSession) => boolean = (arg: any, session: SmppSession) => (session as Center).getPort() === arg; comparatorFn: (arg: any, session: SmppSession) => boolean = (arg: any, session: SmppSession) => (session as Center).getPort() === arg;

View File

@@ -20,32 +20,30 @@ export class Client extends SmppSession {
"BUSY", "BUSY",
] ]
id: number;
username: string;
password: string;
status: string = this.STATUS[0];
url: string; url: string;
_username: string;
_password: string;
_id: number;
_status: string = this.STATUS[0];
_defaultSingleJob: Job;
_defaultMultipleJob: Job;
pduProcessors: PduProcessor[] = []; pduProcessors: PduProcessor[] = [];
defaultSingleJob!: Job;
defaultMultipleJob!: Job;
readonly logger: Logger; readonly logger: Logger;
private session?: any; private session?: any;
private connectPromise: PersistentPromise | null = null; private connectPromise: PersistentPromise | null = null;
private bindPromise: PersistentPromise | null = null; private bindPromise: PersistentPromise | null = null;
private closePromise: PersistentPromise | null = null; private closePromise: PersistentPromise | null = null;
// TODO: Implement close promise
// Apparently the sessions are not closed on a dime but instead a .close() call causes eventSessionClose
constructor(id: number, url: string, username: string, password: string) { constructor(id: number, url: string, username: string, password: string) {
super(); super();
this.id = id; this._id = id;
this.username = username; this._username = username;
this.password = password; this._password = password;
this.url = url; this.url = url;
this.defaultSingleJob = Job.createEmptySingle(); this._defaultSingleJob = Job.createEmptySingle();
this.defaultMultipleJob = Job.createEmptyMultiple(); this._defaultMultipleJob = Job.createEmptyMultiple();
this.logger = new Logger(`Client-${id}`); this.logger = new Logger(`Client-${id}`);
} }
@@ -53,16 +51,16 @@ export class Client extends SmppSession {
doConnect(): PersistentPromise { doConnect(): PersistentPromise {
this.connectPromise = new PersistentPromise((resolve, reject) => { this.connectPromise = new PersistentPromise((resolve, reject) => {
if (this.status !== this.STATUS[0]) { if (this.status !== this.STATUS[0]) {
let errorString = `Client-${this.getId()} already connected`; let errorString = `Client-${this.id} already connected`;
this.logger.log1(errorString); this.logger.log1(errorString);
reject(errorString); reject(errorString);
return; return;
} }
this.logger.log1(`Client-${this.getId()} connecting to ${this.url}`); this.logger.log1(`Client-${this.id} connecting to ${this.url}`);
this.setStatus(1); this.setStatus(1);
this.connectSession().then(resolve, ((err: any) => { this.connectSession().then(resolve, ((err: any) => {
this.logger.log1(`Client-${this.getId()} connection failed: ${err}`); this.logger.log1(`Client-${this.id} connection failed: ${err}`);
this.setStatus(0); this.setStatus(0);
this.session.close(); this.session.close();
reject(err); reject(err);
@@ -86,13 +84,13 @@ export class Client extends SmppSession {
connectAndBind(): Promise<void> { connectAndBind(): Promise<void> {
return this.doConnect().then(this.doBind.bind(this), (error) => { return this.doConnect().then(this.doBind.bind(this), (error) => {
this.logger.log1(`Client-${this.getId()} connectAndBind failed: ${error}`); this.logger.log1(`Client-${this.id} connectAndBind failed: ${error}`);
}); });
} }
serialize(): object { serialize(): object {
return { return {
id: this.getId(), id: this.id,
url: this.url, url: this.url,
username: this.username, username: this.username,
password: this.password, password: this.password,
@@ -104,7 +102,7 @@ export class Client extends SmppSession {
} }
close(): Promise<void> { close(): Promise<void> {
this.logger.log1(`Client-${this.getId()} closing connection`); this.logger.log1(`Client-${this.id} closing connection`);
return Promise.resolve(this.session.close()); return Promise.resolve(this.session.close());
} }
@@ -114,7 +112,7 @@ export class Client extends SmppSession {
this.validateSession(reject); this.validateSession(reject);
this.validateBound(reject); this.validateBound(reject);
} }
this.logger.log5(`Client-${this.getId()} sending PDU: ${JSON.stringify(pdu)}`); this.logger.log5(`Client-${this.id} sending PDU: ${JSON.stringify(pdu)}`);
this.session.send(pdu, (replyPdu: object) => resolve(replyPdu)); this.session.send(pdu, (replyPdu: object) => resolve(replyPdu));
}); });
} }
@@ -124,9 +122,9 @@ export class Client extends SmppSession {
this.validateSession(reject); this.validateSession(reject);
this.validateBound(reject); this.validateBound(reject);
if (!job.count || !job.perSecond) { if (!job.count || !job.perSecond) {
reject(`Client-${this.getId()} sendMultiple failed: invalid job, missing fields`); reject(`Client-${this.id} sendMultiple failed: invalid job, missing fields`);
} }
this.logger.log1(`Client-${this.getId()} sending multiple messages: ${JSON.stringify(job)}`); this.logger.log1(`Client-${this.id} sending multiple messages: ${JSON.stringify(job)}`);
this.setStatus(4); this.setStatus(4);
@@ -162,7 +160,7 @@ export class Client extends SmppSession {
private connectSession(): Promise<void> { private connectSession(): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
this.validateFields(reject); this.validateFields(reject);
this.logger.log1(`Client-${this.getId()} connecting to ${this.url}`); this.logger.log1(`Client-${this.id} connecting to ${this.url}`);
this.session = smpp.connect({ this.session = smpp.connect({
url: this.url, auto_enquire_link_period: AUTO_ENQUIRE_LINK_PERIOD, url: this.url, auto_enquire_link_period: AUTO_ENQUIRE_LINK_PERIOD,
@@ -174,7 +172,7 @@ export class Client extends SmppSession {
} }
private eventSessionConnected(): void { private eventSessionConnected(): void {
this.logger.log1(`Client-${this.getId()} connected to ${this.url}`); this.logger.log1(`Client-${this.id} connected to ${this.url}`);
this.setStatus(2); this.setStatus(2);
if (this.connectPromise) { if (this.connectPromise) {
this.connectPromise.resolve(); this.connectPromise.resolve();
@@ -182,26 +180,26 @@ export class Client extends SmppSession {
} }
private eventSessionError(pdu: PDU): void { private eventSessionError(pdu: PDU): void {
this.logger.log1(`Client-${this.getId()} error on ${this.url}`); this.logger.log1(`Client-${this.id} error on ${this.url}`);
this.setStatus(0); this.setStatus(0);
this.rejectPromises(); this.rejectPromises();
} }
private eventSessionClose(): void { private eventSessionClose(): void {
this.logger.log1(`Client-${this.getId()} closed on ${this.url}`); this.logger.log1(`Client-${this.id} closed on ${this.url}`);
this.setStatus(0); this.setStatus(0);
this.rejectPromises(); this.rejectPromises();
} }
private eventBindReply(pdu: PDU): void { private eventBindReply(pdu: PDU): void {
if (pdu.command_status === 0) { if (pdu.command_status === 0) {
this.logger.log1(`Client-${this.getId()} bound to ${this.url}`); this.logger.log1(`Client-${this.id} bound to ${this.url}`);
this.setStatus(4); this.setStatus(4);
if (this.bindPromise) { if (this.bindPromise) {
this.bindPromise.resolve(); this.bindPromise.resolve();
} }
} else { } else {
this.logger.log1(`Client-${this.getId()} bind failed to ${this.url}`); this.logger.log1(`Client-${this.id} bind failed to ${this.url}`);
this.setStatus(2); this.setStatus(2);
if (this.bindPromise) { if (this.bindPromise) {
this.bindPromise.reject(pdu); this.bindPromise.reject(pdu);
@@ -223,17 +221,17 @@ export class Client extends SmppSession {
private validateFields(reject: (reason?: any) => void) { private validateFields(reject: (reason?: any) => void) {
if (!this.url) { if (!this.url) {
let error = `Client-${this.getId()} has no url set`; let error = `Client-${this.id} has no url set`;
this.logger.log1(error); this.logger.log1(error);
reject(error); reject(error);
} }
if (!this.username) { if (!this.username) {
let error = `Client-${this.getId()} has no username set`; let error = `Client-${this.id} has no username set`;
this.logger.log1(error); this.logger.log1(error);
reject(error); reject(error);
} }
if (!this.password) { if (!this.password) {
let error = `Client-${this.getId()} has no password set`; let error = `Client-${this.id} has no password set`;
this.logger.log1(error); this.logger.log1(error);
reject(error); reject(error);
} }
@@ -241,7 +239,7 @@ export class Client extends SmppSession {
private validateSession(reject: (reason?: any) => void) { private validateSession(reject: (reason?: any) => void) {
if (!this.session) { if (!this.session) {
let errorMessage = `Client-${this.getId()} session is not defined`; let errorMessage = `Client-${this.id} session is not defined`;
this.logger.log1(errorMessage); this.logger.log1(errorMessage);
reject(errorMessage); reject(errorMessage);
} }
@@ -249,7 +247,7 @@ export class Client extends SmppSession {
private validateBound(reject: (reason?: any) => void) { private validateBound(reject: (reason?: any) => void) {
if (this.status !== this.STATUS[4]) { if (this.status !== this.STATUS[4]) {
let errorMessage = `Client-${this.getId()} is not bound`; let errorMessage = `Client-${this.id} is not bound`;
this.logger.log1(errorMessage); this.logger.log1(errorMessage);
reject(errorMessage); reject(errorMessage);
} }

View File

@@ -10,14 +10,12 @@ export default class ClientSessionManager extends SessionManager {
ManagedSessionClass: typeof Client = Client; ManagedSessionClass: typeof Client = Client;
sessionId: number = 0; sessionId: number = 0;
sessions: Client[] = []; sessions: Client[] = [];
// Identifier is used in websockets to identify the type of session this manager manages
identifier: string = "client"; identifier: string = "client";
readonly logger: Logger = new Logger("ClientSessionManager"); readonly logger: Logger = new Logger("ClientSessionManager");
constructor() { constructor() {
super(); super();
this.setup(); this.setup();
// super.eventEmitter.on(super.SESSION_ADDED_EVENT, (session: SmppSession) => this.eventEmitter.emit(this.SESSION_ADDED_EVENT, session));
} }
comparatorFn: (arg: any, session: SmppSession) => boolean = (arg: any, session: SmppSession) => (session as Client).getUrl() === arg; comparatorFn: (arg: any, session: SmppSession) => boolean = (arg: any, session: SmppSession) => (session as Client).getUrl() === arg;

View File

@@ -10,8 +10,8 @@ const bodyParser = require("body-parser");
const SERVER_PORT: number = Number(process.env.SERVER_PORT) || 8190; const SERVER_PORT: number = Number(process.env.SERVER_PORT) || 8190;
export class HttpServer { export class HttpServer {
private clientRequestHandler: RequestHandler; private readonly clientRequestHandler: RequestHandler;
private centerRequestHandler: RequestHandler; private readonly centerRequestHandler: RequestHandler;
private app: any; private app: any;
private server: any; private server: any;
@@ -24,8 +24,8 @@ export class HttpServer {
this.app = express(); this.app = express();
this.app.use(bodyParser.json()); this.app.use(bodyParser.json());
let clientApiPath = 'ClientEntity'; let clientApiPath: string = 'ClientEntity';
let centerApiPath = 'CenterEntity'; let centerApiPath: string = 'CenterEntity';
this.app.get(`/api/${clientApiPath}`, this.clientRequestHandler.doGet.bind(this.clientRequestHandler)); this.app.get(`/api/${clientApiPath}`, this.clientRequestHandler.doGet.bind(this.clientRequestHandler));
this.app.post(`/api/${clientApiPath}`, this.clientRequestHandler.doPost.bind(this.clientRequestHandler)); this.app.post(`/api/${clientApiPath}`, this.clientRequestHandler.doPost.bind(this.clientRequestHandler));

View File

@@ -23,10 +23,10 @@ export abstract class RequestHandler {
this.sessionManager.getSession(req.params.id).then((session: SmppSession) => { this.sessionManager.getSession(req.params.id).then((session: SmppSession) => {
this.logger.log1(`Session found with ID ${req.params.id}`) this.logger.log1(`Session found with ID ${req.params.id}`)
if (!!req.body.username && req.body.username !== session.username) { if (!!req.body.username && req.body.username !== session.username) {
session.setUsername(req.body.username); session.username = req.body.username;
} }
if (!!req.body.password && req.body.password !== session.password) { if (!!req.body.password && req.body.password !== session.password) {
session.setPassword(req.body.password); session.password = req.body.password;
} }
res.send(session.serialize()); res.send(session.serialize());
}, this.handleSessionNotFound.bind(this, req, res)); }, this.handleSessionNotFound.bind(this, req, res));
@@ -34,7 +34,7 @@ export abstract class RequestHandler {
doConfigureSingleJob(req: any, res: any): void { doConfigureSingleJob(req: any, res: any): void {
this.sessionManager.getSession(Number(req.params.id)).then((session: SmppSession) => { this.sessionManager.getSession(Number(req.params.id)).then((session: SmppSession) => {
let job: Job = session.getDefaultSingleJob(); let job: Job = session.defaultSingleJob;
job.update(req); job.update(req);
this.logger.log1(`Updating default job on session with ID ${req.params.id}`); this.logger.log1(`Updating default job on session with ID ${req.params.id}`);
res.send(session.serialize()); res.send(session.serialize());
@@ -71,7 +71,7 @@ export abstract class RequestHandler {
doConfigureManyJob(req: any, res: any): void { doConfigureManyJob(req: any, res: any): void {
this.sessionManager.getSession(req.params.id).then((session: SmppSession) => { this.sessionManager.getSession(req.params.id).then((session: SmppSession) => {
let job: Job = session.getDefaultMultipleJob(); let job: Job = session.defaultMultipleJob;
job.update(req); job.update(req);
this.logger.log1(`Updating default job on session with ID ${req.params.id}`) this.logger.log1(`Updating default job on session with ID ${req.params.id}`)
res.send(session.serialize()); res.send(session.serialize());
@@ -144,6 +144,7 @@ export abstract class RequestHandler {
abstract doAddProcessor(req: any, res: any): void; abstract doAddProcessor(req: any, res: any): void;
abstract doRemoveProcessor(req: any, res: any): void; abstract doRemoveProcessor(req: any, res: any): void;
handleSessionNotFound(req: any, res: any): void { handleSessionNotFound(req: any, res: any): void {
let error = `No session found with ID ${req.params.id}`; let error = `No session found with ID ${req.params.id}`;
this.logger.log1(error); this.logger.log1(error);

View File

@@ -4,10 +4,10 @@ import {SmppSession} from "../SmppSession";
export abstract class PduProcessor { export abstract class PduProcessor {
static processors: PduProcessor[] = []; static processors: PduProcessor[] = [];
private static logger: Logger = new Logger("PduProcessor");
abstract readonly serverSessionType: string; abstract readonly serverSessionType: string;
readonly name: string = this.constructor.name; readonly name: string = this.constructor.name;
readonly logger: Logger = new Logger(`PduProcessor: ${this.name}`); readonly logger: Logger = new Logger(`PduProcessor: ${this.name}`);
private static logger: Logger = new Logger("PduProcessor");
static getProcessor(name: string): PduProcessor { static getProcessor(name: string): PduProcessor {
this.logger.log1(`Looking for processor with name ${name}...`); this.logger.log1(`Looking for processor with name ${name}...`);
@@ -22,19 +22,19 @@ export abstract class PduProcessor {
} }
static attachProcessor(session: SmppSession, processor: PduProcessor): void { static attachProcessor(session: SmppSession, processor: PduProcessor): void {
this.logger.log1(`Trying to attach processor ${processor.name} to session ${session.constructor.name}-${session.getId()}`); this.logger.log1(`Trying to attach processor ${processor.name} to session ${session.constructor.name}-${session.id}`);
if (PduProcessor.areCompatible(session, processor)) { if (PduProcessor.areCompatible(session, processor)) {
session.addPduProcessor(processor); session.addPduProcessor(processor);
} }
} }
static detachProcessor(session: SmppSession, processor: PduProcessor): void { static detachProcessor(session: SmppSession, processor: PduProcessor): void {
this.logger.log1(`Trying to detach processor ${processor.name} from session ${session.constructor.name}-${session.getId()}`); this.logger.log1(`Trying to detach processor ${processor.name} from session ${session.constructor.name}-${session.id}`);
session.removePduProcessor(processor); session.removePduProcessor(processor);
} }
static areCompatible(session: SmppSession, processor: PduProcessor): boolean { static areCompatible(session: SmppSession, processor: PduProcessor): boolean {
this.logger.log1(`Checking compatibility between session ${session.constructor.name}-${session.getId()} and processor ${processor.name}`); this.logger.log1(`Checking compatibility between session ${session.constructor.name}-${session.id} and processor ${processor.name}`);
return session.constructor.name === processor.serverSessionType; return session.constructor.name === processor.serverSessionType;
} }

View File

@@ -20,9 +20,9 @@ export abstract class SessionManager {
addSession(session: SmppSession): Promise<void> { addSession(session: SmppSession): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
this.logger.log1(`Adding session with id ${session.getId()}`); this.logger.log1(`Adding session with id ${session.id}`);
this.sessions.push(session); this.sessions.push(session);
this.eventEmitter.emit(this.SESSION_ADDED_EVENT, session.getId()); this.eventEmitter.emit(this.SESSION_ADDED_EVENT, session.id);
resolve(); resolve();
}); });
} }
@@ -37,8 +37,8 @@ export abstract class SessionManager {
removeSession(session: SmppSession): Promise<void> { removeSession(session: SmppSession): Promise<void> {
return new Promise<void>((resolve, reject) => { return new Promise<void>((resolve, reject) => {
this.logger.log1(`Removing session with id ${session.getId()}`); this.logger.log1(`Removing session with id ${session.id}`);
this.sessions = this.sessions.filter(s => s.getId() !== session.getId()); this.sessions = this.sessions.filter(s => s.id !== session.id);
resolve(); resolve();
}); });
} }
@@ -46,7 +46,7 @@ export abstract class SessionManager {
getSession(id: number): Promise<SmppSession> { getSession(id: number): Promise<SmppSession> {
return new Promise<SmppSession>((resolve, reject) => { return new Promise<SmppSession>((resolve, reject) => {
this.logger.log1(`Looking for session with id ${id}...`); this.logger.log1(`Looking for session with id ${id}...`);
let session: SmppSession | undefined = this.sessions.find(s => s.getId() == id); let session: SmppSession | undefined = this.sessions.find(s => s.id == id);
if (session) { if (session) {
this.logger.log1(`Found session with id ${id}`); this.logger.log1(`Found session with id ${id}`);
resolve(session); resolve(session);
@@ -65,8 +65,8 @@ export abstract class SessionManager {
this.logger.log1(`Loaded ${loadedSessions.length} clients from ${this.StorageFile}`); this.logger.log1(`Loaded ${loadedSessions.length} clients from ${this.StorageFile}`);
loadedSessions.forEach(session => { loadedSessions.forEach(session => {
this.createSession(session.url || session.port, session.username, session.password).then((sessionObj: SmppSession) => { this.createSession(session.url || session.port, session.username, session.password).then((sessionObj: SmppSession) => {
sessionObj.setDefaultSingleJob(Job.deserialize(session.defaultSingleJob)); sessionObj.defaultSingleJob = Job.deserialize(session.defaultSingleJob);
sessionObj.setDefaultMultipleJob(Job.deserialize(session.defaultMultipleJob)); sessionObj.defaultMultipleJob = Job.deserialize(session.defaultMultipleJob);
}); });
}); });
} catch (e) { } catch (e) {

View File

@@ -14,16 +14,7 @@ export abstract class SmppSession {
MESSAGE_SEND_COUNTER_UPDATE_EVENT: "MESSAGE_SEND_COUNTER_UPDATE_EVENT", MESSAGE_SEND_COUNTER_UPDATE_EVENT: "MESSAGE_SEND_COUNTER_UPDATE_EVENT",
}; };
abstract STATUS: string[]; abstract STATUS: string[];
abstract id: number;
abstract username: string;
abstract password: string;
abstract status: string;
abstract pduProcessors: PduProcessor[]; abstract pduProcessors: PduProcessor[];
abstract defaultSingleJob: Job;
abstract defaultMultipleJob: Job;
readonly UPDATE_WS: string = "UPDATE_WS"; readonly UPDATE_WS: string = "UPDATE_WS";
readonly eventEmitter: EventEmitter = new EventEmitter(); readonly eventEmitter: EventEmitter = new EventEmitter();
readonly logger: Logger = new Logger(`SmppSession`); readonly logger: Logger = new Logger(`SmppSession`);
@@ -38,6 +29,66 @@ export abstract class SmppSession {
this.eventEmitter.on(this.EVENT.MESSAGE_SEND_COUNTER_UPDATE_EVENT, (count: number) => this.updateWs(this.EVENT.MESSAGE_SEND_COUNTER_UPDATE_EVENT, [count])); this.eventEmitter.on(this.EVENT.MESSAGE_SEND_COUNTER_UPDATE_EVENT, (count: number) => this.updateWs(this.EVENT.MESSAGE_SEND_COUNTER_UPDATE_EVENT, [count]));
} }
abstract _username: string;
set username(username: string) {
this._username = username;
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
abstract _password: string;
set password(password: string) {
this._password = password;
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
abstract _id: number;
get id(): number {
return this._id;
}
abstract _status: string;
get status(): string {
return this._status;
}
set status(status: string) {
this._status = status;
this.eventEmitter.emit(this.EVENT.STATUS_CHANGED, this.status);
}
abstract _defaultSingleJob: Job;
get defaultSingleJob(): Job {
return this._defaultSingleJob;
}
set defaultSingleJob(job: Job) {
this._defaultSingleJob = job;
job.on(Job.STATE_CHANGED, this.eventJobUpdated);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
abstract _defaultMultipleJob: Job;
get defaultMultipleJob(): Job {
return this._defaultMultipleJob;
}
set defaultMultipleJob(job: Job) {
this._defaultMultipleJob = job;
job.on(Job.STATE_CHANGED, this.eventJobUpdated);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
setStatus(statusIndex: number) {
this._status = this.STATUS[statusIndex];
this.eventEmitter.emit(this.EVENT.STATUS_CHANGED, this.status);
}
abstract sendPdu(pdu: object, force?: boolean): Promise<object>; abstract sendPdu(pdu: object, force?: boolean): Promise<object>;
sendSingle(job: Job): Promise<object> { sendSingle(job: Job): Promise<object> {
@@ -92,45 +143,6 @@ export abstract class SmppSession {
this.eventEmitter.emit(this.UPDATE_WS, message); this.eventEmitter.emit(this.UPDATE_WS, message);
} }
getDefaultSingleJob(): Job {
return this.defaultSingleJob;
}
setDefaultSingleJob(job: Job): void {
this.defaultSingleJob = job;
job.on(Job.STATE_CHANGED, this.eventJobUpdated);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
getDefaultMultipleJob(): Job {
return this.defaultMultipleJob;
}
setDefaultMultipleJob(job: Job): void {
this.defaultMultipleJob = job;
job.on(Job.STATE_CHANGED, this.eventJobUpdated);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
getId(): number {
return this.id;
}
setStatus(statusIndex: number): void {
this.status = this.STATUS[statusIndex];
this.eventEmitter.emit(this.EVENT.STATUS_CHANGED, this.status);
}
setUsername(username: string): void {
this.username = username;
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
setPassword(password: string): void {
this.password = password;
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
eventJobUpdated(): void { eventJobUpdated(): void {
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize()); this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
} }
@@ -138,16 +150,16 @@ export abstract class SmppSession {
addPduProcessor(pduProcessor: PduProcessor): void { addPduProcessor(pduProcessor: PduProcessor): void {
if (this.pduProcessors.indexOf(pduProcessor) === -1) { if (this.pduProcessors.indexOf(pduProcessor) === -1) {
this.pduProcessors.push(pduProcessor); this.pduProcessors.push(pduProcessor);
this.logger.log1(`Adding PDU processor: ${pduProcessor.constructor.name}-${this.getId()}, now active: ${this.pduProcessors.length} processors`); this.logger.log1(`Adding PDU processor: ${pduProcessor.constructor.name}-${this.id}, now active: ${this.pduProcessors.length} processors`);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize()); this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
} else { } else {
this.logger.log1(`PDU processor: ${pduProcessor.constructor.name}-${this.getId()} already attached to session`); this.logger.log1(`PDU processor: ${pduProcessor.constructor.name}-${this.id} already attached to session`);
} }
} }
removePduProcessor(pduProcessor: PduProcessor): void { removePduProcessor(pduProcessor: PduProcessor): void {
this.pduProcessors = this.pduProcessors.splice(this.pduProcessors.indexOf(pduProcessor), 1); this.pduProcessors = this.pduProcessors.splice(this.pduProcessors.indexOf(pduProcessor), 1);
this.logger.log1(`Removing PDU processor: ${pduProcessor.constructor.name}-${this.getId()}, now active: ${this.pduProcessors.length} processors`); this.logger.log1(`Removing PDU processor: ${pduProcessor.constructor.name}-${this.id}, now active: ${this.pduProcessors.length} processors`);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize()); this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
} }

View File

@@ -47,246 +47,4 @@ export class WSServer {
this.logger.log1("Connection closed"); this.logger.log1("Connection closed");
this.unknownClients.splice(this.unknownClients.indexOf(ws), 1); this.unknownClients.splice(this.unknownClients.indexOf(ws), 1);
} }
// constructor() {
// // @ts-ignore
// this.server = new WebSocket.Server({port: WS_SERVER_PORT});
// this.logger = new Logger("WSServer");
// this.server.on('connection', this.onConnection.bind(this));
// this.logger.log1(`WSServer listening at ws://localhost:${WS_SERVER_PORT}`);
// }
// onConnection(ws: WebSocket) {
// this.logger.log1("New connection");
// this.unknownClients.push(ws);
// ws.on('message', this.onMessage.bind(this, ws));
// ws.on('close', this.onClose.bind(this, ws));
// }
//
// addClient(ws, type, sessionId) {
// if (!this.clients[type]) {
// this.clients[type] = {};
// }
// if (!this.clients[type][sessionId]) {
// this.clients[type][sessionId] = [];
// }
// this.logger.log1(`Adding client ${ws.id} to ${type} session ${sessionId}`);
//
// if (type === "client") {
// if (this.listenersAlreadySetup.indexOf(`client-${sessionId}`) === -1) {
// let session = clientSessionManager.getSession(sessionId);
// if (!!session) {
// this.logger.log1(`Setting up listeners for client session ${sessionId}`);
// session.on(ClientSession.STATUS_CHANGED_EVENT, this.onClientSessionStatusChange.bind(this, sessionId));
// session.on(ClientSession.ANY_PDU_EVENT, this.onClientSessionPdu.bind(this, sessionId));
// session.on(ClientSession.MESSAGE_SEND_COUNTER_UPDATE_EVENT, this.onClientMessageCounterUpdate.bind(this, sessionId));
// }
// this.listenersAlreadySetup.push(`client-${sessionId}`);
// } else {
// this.logger.log1(`Listeners for client session ${sessionId} already set up`);
// }
// } else if (type === "center") {
// if (this.listenersAlreadySetup.indexOf(`center-${sessionId}`) === -1) {
// let session = centerSessionManager.getSession(sessionId);
// if (!!session) {
// this.logger.log1(`Setting up listeners for center session ${sessionId}`);
// session.on(CenterSession.STATUS_CHANGED_EVENT, this.onCenterStatusChange.bind(this, sessionId));
// session.on(CenterSession.ANY_PDU_EVENT, this.onCenterServerPdu.bind(this, sessionId));
// session.on(CenterSession.MODE_CHANGED_EVENT, this.onCenterModeChanged.bind(this, sessionId));
// session.on(CenterSession.SESSION_CHANGED_EVENT, this.onCenterSessionsChanged.bind(this, sessionId));
// session.on(ClientSession.MESSAGE_SEND_COUNTER_UPDATE_EVENT, this.onCenterMessageCounterUpdate.bind(this, sessionId));
// }
// this.listenersAlreadySetup.push(`center-${sessionId}`);
// } else {
// this.logger.log1(`Listeners for center session ${sessionId} already set up`);
// }
// }
//
// this.clients[type][sessionId].push(ws);
// this.logger.log1(`Now active ${this.clients[type][sessionId].length} clients in session ID: ${sessionId} of type ${type}`);
// }
//
// onMessage(ws, message) {
// this.logger.log1("New message");
// message = String(message);
// let data = message.split(":");
// let type = data[0];
// let sessionId = data[1];
//
// this.logger.log1(`Moving client to session ID: ${sessionId} of type ${type}`);
// delete this.unknownClients[ws];
// this.unknownClients = this.unknownClients.filter(Boolean);
//
// this.addClient(ws, type, sessionId);
// this.logger.log1(`Now active ${this.clients[type][sessionId].length} clients in session ID: ${sessionId} of type ${type}`);
// }
//
// onClose(ws) {
// this.removeClient(ws);
// // this.logger.log6(this.clients);
// this.logger.log1("Connection closed");
// }
//
// removeClient(ws) {
// this.clients.client = this.removeFromArray(this.clients.client, ws);
// this.clients.center = this.removeFromArray(this.clients.center, ws);
// }
//
// removeFromArray(array, element) {
// for (let sessionId in array) {
// let index = array[sessionId].indexOf(element);
// if (index > -1) {
// delete array[sessionId][index];
// }
// array[sessionId] = array[sessionId].filter(Boolean);
// if (array[sessionId].length === 0) {
// delete array[sessionId];
// }
// }
// return array;
// }
//
// onClientSessionStatusChange(sessionId, newStatus) {
// this.logger.log1(`Session with ID ${sessionId} changed`);
// let payload = {
// objectType: "client",
// type: 'status',
// sessionId: sessionId,
// value: newStatus
// }
// let clients = this.clients["client"][sessionId];
// if (!!clients) {
// this.logger.log1(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
//
// onClientSessionPdu(sessionId, pdu) {
// // TODO: Maybe move this to an "ignored" array against who the pdu.command is compared
// if (pdu.command === 'enquire_link_resp' || pdu.command === 'enquire_link') {
// return;
// }
// let clients = this.clients["client"][sessionId];
// if (!!clients) {
// this.logger.log2(`Session with ID ${sessionId} fired PDU`);
// let payload = {
// objectType: "client",
// type: 'pdu',
// sessionId: sessionId,
// value: pdu
// }
// this.logger.log2(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
//
// onClientMessageCounterUpdate(sessionId, counter) {
// this.logger.log2(`Session with ID ${sessionId} updating message send counter`);
// let payload = {
// objectType: "client",
// type: 'counterUpdate',
// sessionId: sessionId,
// value: counter
// }
// let clients = this.clients["client"][sessionId];
// if (!!clients) {
// this.logger.log2(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
//
// onCenterStatusChange(sessionId, newStatus) {
// this.logger.log1(`Session with ID ${sessionId} changed`);
// let payload = {
// objectType: "center",
// type: 'status',
// sessionId: sessionId,
// value: newStatus
// }
// let clients = this.clients["center"][sessionId];
// if (!!clients) {
// this.logger.log1(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
//
// onCenterServerPdu(sessionId, pdu) {
// if (pdu.command === 'enquire_link_resp' || pdu.command === 'enquire_link') {
// return;
// }
// let clients = this.clients["center"][sessionId];
// if (!!clients) {
// this.logger.log2(`Session with ID ${sessionId} fired PDU`);
// let payload = {
// objectType: "center",
// type: 'pdu',
// sessionId: sessionId,
// value: pdu
// }
// this.logger.log2(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
//
// onCenterModeChanged(sessionId, newMode) {
// this.logger.log1(`Session with ID ${sessionId} changed`);
// let payload = {
// objectType: "center",
// type: 'mode',
// sessionId: sessionId,
// value: newMode,
// text: CenterMode[newMode]
// }
// let clients = this.clients["center"][sessionId];
// if (!!clients) {
// this.logger.log1(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
//
// onCenterSessionsChanged(sessionId, newSession) {
// this.logger.log1(`Session with ID ${sessionId} changed`);
// let payload = {
// objectType: "center",
// type: 'sessions',
// sessionId: sessionId,
// value: newSession
// }
// let clients = this.clients["center"][sessionId];
// if (!!clients) {
// this.logger.log1(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
//
// onCenterMessageCounterUpdate(sessionId, counter) {
// this.logger.log2(`Session with ID ${sessionId} updating message send counter`);
// let payload = {
// objectType: "center",
// type: 'counterUpdate',
// sessionId: sessionId,
// value: counter
// }
// let clients = this.clients["center"][sessionId];
// if (!!clients) {
// this.logger.log2(`Broadcasting session with ID ${sessionId} to ${clients.length} clients`);
// clients.forEach(client => {
// client.send(JSON.stringify(payload));
// });
// }
// }
} }

View File

@@ -9,7 +9,6 @@ import {WSServer} from "./WS/WSServer";
const {PDU} = require("smpp"); const {PDU} = require("smpp");
// TODO: Add support for encodings // TODO: Add support for encodings
// TODO: Implement some sort of metrics on frontend by counting the pdus
let logger = new Logger("main"); let logger = new Logger("main");
@@ -29,7 +28,7 @@ function cleanup(): void {
process.exit(0); process.exit(0);
} }
// process.on('exit', cleanup); process.on('exit', cleanup);
// process.on('SIGINT', cleanup); process.on('SIGINT', cleanup);
// process.on('SIGUSR1', cleanup); process.on('SIGUSR1', cleanup);
// process.on('SIGUSR2', cleanup); process.on('SIGUSR2', cleanup);