Compare commits

...

7 Commits

Author SHA1 Message Date
a492b3bd72 Add buildToWeb run config 2023-05-05 10:38:23 +02:00
0e016438a1 Implement shared processors (processors that can be used on clients and centers) 2023-05-05 10:25:31 +02:00
5a5debb249 Refactor processors to reduce duplicate code 2023-05-05 10:17:55 +02:00
7d574e3162 Generify serialize 2023-05-05 10:00:31 +02:00
03716404f0 Fix issue where center set to echo would echo every message part
Now echo simply does not work with long messages
2023-05-02 13:09:00 +02:00
David Majdandžić
85dfc6f565 Revert IP change 2023-04-26 17:48:13 +02:00
David Majdandžić
9c755d3cda Add README 2023-04-24 16:35:52 +02:00
21 changed files with 314 additions and 167 deletions

19
.run/Build To Web.run.xml Normal file
View File

@@ -0,0 +1,19 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Build To Web" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="rsync -auzhvisP ./dist ../smsgw-tester-web/electron" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />
<option name="INDEPENDENT_SCRIPT_WORKING_DIRECTORY" value="true" />
<option name="SCRIPT_WORKING_DIRECTORY" value="$PROJECT_DIR$" />
<option name="INDEPENDENT_INTERPRETER_PATH" value="true" />
<option name="INTERPRETER_PATH" value="" />
<option name="INTERPRETER_OPTIONS" value="" />
<option name="EXECUTE_IN_TERMINAL" value="true" />
<option name="EXECUTE_SCRIPT_FILE" value="false" />
<envs />
<method v="2">
<option name="RunConfigurationTask" enabled="true" run_configuration_name="tsc" run_configuration_type="js.build_tools.npm" />
</method>
</configuration>
</component>

120
README.md Normal file
View File

@@ -0,0 +1,120 @@
# smsgw-tester-api
#### This application is meant to be used for performance or functionality testing smpp processing systems such as sms centers, clients or sms gateways.
The application is capable of hosting any number of smpp clients or centers. The centers automatically accept any smpp connections while the clients can be connected/bound/disconnected at will.
---
## General use
The api is meant to be used along with the [web application](https://github.com/PhatDave/smsgw-tester-web) but can also be used standalone via http requests. The request examples can be found in the insomnia export file (although they are outdated as of 1.0).
The web view consists of a Client and Center segment. Each entity has it's 3 parameters (for a client those are the url [the client connects to], the username and password, for the center those are the port [the center listens on], username and password) of which 2 are modifiable (username and password).
Each entity can be configured to send one smpp message or multiple smpp messages at a given rate (of messages per second).
Each entity also includes a live graph representing the incoming and outgoing traffic.
Each entity also supports a set of pre and post processors that in some way modify the incoming or outgoing pdu. These processors will be described in the processor segment.
Entities can also be deleted by **double clicking** the delete button.
Currently it is not possible to temporarily disable entities but this is planned for a future release (as of 1.0).
### Center modes of operation
Center entities are "special" in the sense that they can have a few different modes of operation.
As of 1.0 the following modes are implemented (and later described in the center postprocessor segment): "Debug", Echo and DeliveryReport.
- **Debug mode** (1.0)
- Only "Deliver\_sm Reply" is enabled, the center does not reply to messages with any other messages and only acknowledges the ones delivered to it.
- **Echo mode** (1.0)
- "Echo PDU" is enabled, the center replies to messages with a copy of the received message whose source and destination fields have been swapped.
- For example a center receiving a message (src:123, dst:321) will reply to it with a message (src:321, dst:123) where the text of the message is the same as the text of the received message.
- **Delivery Report mode** (1.0)
- "Delivery Receipt" is enabled, the center replies to messages with delivery report. You can learn more about delivery reports [here](https://smpp.org/smpp-delivery-receipt.html)
- Details of the implementation can be found in the last segment, Delivery Reports
Enabling multiple modes at once will have the center send more than one reply message at once. For example enabling echo mode and delivery report mode will have the center reply with an echo message and a delivery report at the same time.
---
## Processors
Processors handle the majority of this application's functionality. On the web application active processors are highlighted green and they can be toggled by clicking on the appropriate button.
Preprocessors generally do something with the message before it is sent while postprocessors generally reply to a message.
These are the available pre and post processors per entity:
### Client Preprocessors
#### Destination & Source Enumerator (1.0)
These processors append an incrementing 4 digit number to the end of either the source or destination. For example given a destination of "3851728381" and destinationEnumerator toggled on, sending 5 messages would have their destinations be:
- 38517283810000
- 38517283810001
- 38517283810002
- 38517283810003
- 38517283810004
The functionality is identical for source enumerator.
#### Delivery Receipt Request (1.0)
This preprocessor adds a field to the pdu (registered\_delivery) and sets it to 1. This signals to the smsc that a delivery report is requested to this message.
#### Long SMS (1.0)
With this preprocessor enabled the messages body is chopped up into segments based on the encoding and maximum size of an smpp message given that encoding and each segment is sent separately. (Message segment information is set in the form of udh)
**With this preprocessor disabled any message whose body exceeds the maximum smpp message size is truncated to size**.
### Center Preprocessors
None as of 1.0
### Client Postprocessors
#### Deliver\_sm Reply (1.0)
This postprocessor should never be disabled (unless you know what you're doing). It enables the client to reply to deliver\_sm pdus. (deliver\_sm -> deliver\_sm\_resp)
### Center Postprocessors
#### Bind Transciever Reply (1.0)
This postprocessor should never be disabled (unless you know what you're doing). It enables client authentication. (By replying to bind\_transceiver pdus)
#### Submit\_sm Reply (1.0)
This postprocessor should never be disabled (unless you know what you're doing). It enables the center to reply to submit\_sm pdus. (submit\_sm -> submit\_sm\_resp)
#### Enquire Link Reply (1.0)
This postprocessor should never be disabled (unless you know what you're doing). It replies to the clients "heartbeat" (the enquire\_link pdu). (enquire\_link -> enquire\_link\_resp)
#### Echo PDU (1.0)
This is the first "real" postprocessor for center entities. It is one of 3 (as of 1.0) choices of center operation.
The "Echo" mode of operation has the center reply to any submit\_sm with a deliver\_sm whose message body is the same (as the submit\_sm) and source and destination swapped.
For example, sending a submit\_sm with the source of "1234" and a destination of "4321" and text of "test123" will have the center reply with a deliver\_sm with the source of "4321" and destination of "1234" with the text "test123".
#### Delivery Receipt (1.0)
The "most important" postprocessor for an smsc the delivery receipt postprocessor handles generating and sending delivery reports. You can read more about delivery reports in the Delivery Reports section.
---
## Delivery Reports
Upon receiving a submit_sm on the center whose "Delivery Receipt" postprocessor has been enabled it:
- Checks whether the pdus "registered_delivery" field is set
- Generates a delivery report in the form of `id:<messageId> sub:001 dlvrd:001 submit date:<date> done date:<date> stat:DELIVERD err:000 text:`
- The messageId here is the one id returned in the submit_sm_resp
- The date is simply the current date as of generation of the DR
- Sets the newly generated pdu esm class to 04
- Sends the pdu (delivery report) back to the client

View File

@@ -43,9 +43,9 @@ export default class Center extends SmppSession {
this._defaultSingleJob = Job.createEmptySingle('deliver_sm');
this._defaultMultipleJob = Job.createEmptyMultiple('deliver_sm');
ProcessorManager.attachProcessor(this, ProcessorManager.getProcessor(SubmitSmReplyProcessor.name));
ProcessorManager.attachProcessor(this, ProcessorManager.getProcessor(BindTranscieverReplyProcessor.name));
ProcessorManager.attachProcessor(this, ProcessorManager.getProcessor(EnquireLinkReplyProcessor.name));
ProcessorManager.attachProcessors(this, ProcessorManager.getProcessors(SubmitSmReplyProcessor.name));
ProcessorManager.attachProcessors(this, ProcessorManager.getProcessors(BindTranscieverReplyProcessor.name));
ProcessorManager.attachProcessors(this, ProcessorManager.getProcessors(EnquireLinkReplyProcessor.name));
this.logger = new Logger(`Center-${id}`);
@@ -148,20 +148,9 @@ export default class Center extends SmppSession {
this.server.close();
}
serialize(): object {
return {
id: this._id,
port: this.port,
username: this._username,
password: this._password,
status: this._status,
defaultSingleJob: this._defaultSingleJob.serialize(),
defaultMultipleJob: this._defaultMultipleJob.serialize(),
preprocessors: this.processors.Preprocessor.map((p: PduProcessor) => p.serialize()),
postprocessors: this.processors.Postprocessor.map((p: PduProcessor) => p.serialize()),
availablePreprocessors: ProcessorManager.getPreprocessorsForType(this.constructor.name).map((p: PduProcessor) => p.serialize()),
availablePostprocessors: ProcessorManager.getPostprocessorsForType(this.constructor.name).map((p: PduProcessor) => p.serialize()),
};
postSerialize(obj: any): object {
obj.port = this.port;
return obj;
}
updateStatus(): void {
@@ -220,4 +209,4 @@ export default class Center extends SmppSession {
this.pendingSessions = this.pendingSessions.filter((s: any) => s !== session);
this.updateStatus();
}
}
}

View File

@@ -42,7 +42,7 @@ export default class Client extends SmppSession {
this._defaultSingleJob = Job.createEmptySingle('submit_sm');
this._defaultMultipleJob = Job.createEmptyMultiple('submit_sm');
ProcessorManager.attachProcessor(this, ProcessorManager.getProcessor(DeliverSmReplyProcessor.name));
ProcessorManager.attachProcessors(this, ProcessorManager.getProcessors(DeliverSmReplyProcessor.name));
this.logger = new Logger(`Client-${id}`);
}
@@ -116,21 +116,9 @@ export default class Client extends SmppSession {
});
}
serialize(): object {
// TODO: Generify this further by moving it to smpp session and creating a... "postSerialize" that is abstract
return {
id: this._id,
url: this.url,
username: this._username,
password: this._password,
status: this._status,
defaultSingleJob: this._defaultSingleJob.serialize(),
defaultMultipleJob: this._defaultMultipleJob.serialize(),
preprocessors: this.processors.Preprocessor.map((p: PduProcessor) => p.serialize()),
postprocessors: this.processors.Postprocessor.map((p: PduProcessor) => p.serialize()),
availablePreprocessors: ProcessorManager.getPreprocessorsForType(this.constructor.name).map((p: PduProcessor) => p.serialize()),
availablePostprocessors: ProcessorManager.getPostprocessorsForType(this.constructor.name).map((p: PduProcessor) => p.serialize()),
};
postSerialize(obj: any): object {
obj.url = this.url;
return obj;
}
close(): Promise<void> {
@@ -292,4 +280,4 @@ export default class Client extends SmppSession {
reject(errorMessage);
}
}
}
}

View File

@@ -31,16 +31,16 @@ export default class CenterRequestHandler extends RequestHandler {
doAddProcessor(req: any, res: any): void {
this.sessionManager.getSession(req.params.id).then((session: SmppSession) => {
let processor: PduProcessor = ProcessorManager.getProcessor(req.body.name);
ProcessorManager.attachProcessor(session, processor);
let processors: PduProcessor[] = ProcessorManager.getProcessors(req.body.name);
ProcessorManager.attachProcessors(session, processors);
res.send(session.serialize());
}, this.handleSessionNotFound.bind(this, req, res));
}
doRemoveProcessor(req: any, res: any): void {
this.sessionManager.getSession(req.params.id).then((session: SmppSession) => {
let processor: PduProcessor = ProcessorManager.getProcessor(req.body.name);
ProcessorManager.detachProcessor(session, processor);
let processors: PduProcessor[] = ProcessorManager.getProcessors(req.body.name);
ProcessorManager.detachProcessors(session, processors);
res.send(session.serialize());
}, this.handleSessionNotFound.bind(this, req, res));
}
@@ -62,4 +62,4 @@ export default class CenterRequestHandler extends RequestHandler {
doBind(req: any, res: any): void {
throw new Error("Method not implemented.");
}
}
}

View File

@@ -31,16 +31,16 @@ export default class ClientRequestHandler extends RequestHandler {
doAddProcessor(req: any, res: any): void {
this.sessionManager.getSession(req.params.id).then((session: SmppSession) => {
let processor: PduProcessor = ProcessorManager.getProcessor(req.body.name);
ProcessorManager.attachProcessor(session, processor);
let processors: PduProcessor[] = ProcessorManager.getProcessors(req.body.name);
ProcessorManager.attachProcessors(session, processors);
res.send(session.serialize());
}, this.handleSessionNotFound.bind(this, req, res));
}
doRemoveProcessor(req: any, res: any): void {
this.sessionManager.getSession(req.params.id).then((session: SmppSession) => {
let processor: PduProcessor = ProcessorManager.getProcessor(req.body.name);
ProcessorManager.detachProcessor(session, processor);
let processors: PduProcessor[] = ProcessorManager.getProcessors(req.body.name);
ProcessorManager.detachProcessors(session, processors);
res.send(session.serialize());
}, this.handleSessionNotFound.bind(this, req, res));
}
@@ -80,4 +80,4 @@ export default class ClientRequestHandler extends RequestHandler {
}));
}, this.handleSessionNotFound.bind(this, req, res));
}
}
}

View File

@@ -9,7 +9,7 @@ const bodyParser = require("body-parser");
const compression = require("compression");
const zlib = require("zlib");
const SERVER_PORT: number = Number(process.env.SERVER_PORT) || 80;
const SERVER_PORT: number = Number(process.env.SERVER_PORT) || 8190;
export default class HttpServer {
private readonly clientRequestHandler: RequestHandler;
@@ -83,4 +83,4 @@ export default class HttpServer {
this.logger.log1(`HTTPServer listening at http://localhost:${SERVER_PORT}`)
}.bind(this));
}
}
}

View File

@@ -6,12 +6,26 @@ export default abstract class PduProcessor {
readonly sessionType: string;
readonly name: string = this.constructor.name;
readonly logger: Logger = new Logger(`PduProcessor: ${this.name}`);
abstract applicableCommands: string[];
constructor(type: string) {
this.sessionType = type;
}
abstract processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any>;
protected pduDoesApply(pdu: any): boolean {
if (pdu.command) {
return this.applicableCommands.includes(pdu.command);
}
return false;
}
protected abstract doProcess(session: any, pdu: any, entity?: SmppSession | undefined): any;
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): any {
if (this.pduDoesApply(pdu)) {
return this.doProcess(session, pdu, entity);
}
}
serialize(): object {
return {
@@ -20,4 +34,4 @@ export default abstract class PduProcessor {
type: this.type
};
}
}
}

View File

@@ -4,42 +4,42 @@ import Postprocessor from "../Postprocessor";
const smpp = require("smpp");
export default class BindTranscieverReplyProcessor extends Postprocessor {
applicableCommands: string[] = ['bind_transceiver'];
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: Center | undefined): Promise<any> {
doProcess(session: any, pdu: any, entity?: Center | undefined): Promise<any> {
return new Promise((resolve, reject) => {
if (!!pdu.command && pdu.command === 'bind_transceiver') {
if (!entity) {
reject();
}
if (!entity) {
reject();
}
this.logger.log1(`Center-${entity?.id} got a bind_transciever with system_id ${pdu.system_id} and password ${pdu.password}`);
session.pause();
if (pdu.system_id === entity?.username && pdu.password === entity?.password) {
this.logger.log1(`Center-${entity?.id} client connection successful`);
if (pdu.response) {
entity?.doSendPdu(pdu.response(), session);
}
session.resume();
// @ts-ignore
entity?.pendingSessions = entity?.pendingSessions.filter((s) => s !== session);
entity?.sessions.push(session);
entity?.updateStatus();
} else {
this.logger.log1(`Center-${entity?.id} client connection failed, invalid credentials (expected: ${entity?.username}, ${entity?.password})`);
if (pdu.response) {
entity?.doSendPdu(pdu.response({
command_status: smpp.ESME_RBINDFAIL
}), session);
}
// @ts-ignore
entity?.pendingSessions = entity?.pendingSessions.filter((s) => s !== session);
entity?.updateStatus();
session.close();
this.logger.log1(`Center-${entity?.id} got a bind_transceiver with system_id ${pdu.system_id} and password ${pdu.password}`);
session.pause();
if (pdu.system_id === entity?.username && pdu.password === entity?.password) {
this.logger.log1(`Center-${entity?.id} client connection successful`);
if (pdu.response) {
entity?.doSendPdu(pdu.response(), session);
}
session.resume();
// @ts-ignore
entity?.pendingSessions = entity?.pendingSessions.filter((s) => s !== session);
entity?.sessions.push(session);
entity?.updateStatus();
} else {
this.logger.log1(`Center-${entity?.id} client connection failed, invalid credentials (expected: ${entity?.username}, ${entity?.password})`);
if (pdu.response) {
entity?.doSendPdu(pdu.response({
command_status: smpp.ESME_RBINDFAIL
}), session);
}
// @ts-ignore
entity?.pendingSessions = entity?.pendingSessions.filter((s) => s !== session);
entity?.updateStatus();
session.close();
}
});
}
}
}

View File

@@ -5,13 +5,14 @@ import Postprocessor from "../Postprocessor";
const smpp = require("smpp");
export default class DeliveryReceiptProcessor extends Postprocessor {
applicableCommands: string[] = ['submit_sm'];
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!!pdu.command && pdu.command === "submit_sm" && pdu.registered_delivery) {
if (pdu.registered_delivery) {
let drMessage: string = "";
let date: string = new Date().toISOString().replace(/T/, '').replace(/\..+/, '').replace(/-/g, '').replace(/:/g, '').substring(2, 12);
@@ -39,8 +40,4 @@ export default class DeliveryReceiptProcessor extends Postprocessor {
}
});
}
private padLeft(str: string, pad: string, length: number): string {
return (new Array(length + 1).join(pad) + str).slice(-length);
}
}
}

View File

@@ -4,13 +4,15 @@ import Postprocessor from "../Postprocessor";
const smpp = require("smpp");
export default class EchoPduProcessor extends Postprocessor {
applicableCommands: string[] = ['submit_sm'];
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!!pdu.command && pdu.command === "submit_sm") {
// Temporary (?) safeguard against echoing long sms
if (!pdu.short_message.udh) {
let echoPdu = new smpp.PDU('deliver_sm', {...pdu});
echoPdu.source_addr = pdu.destination_addr;
echoPdu.destination_addr = pdu.source_addr;
@@ -19,4 +21,4 @@ export default class EchoPduProcessor extends Postprocessor {
}
});
}
}
}

View File

@@ -2,16 +2,16 @@ import SmppSession from "../../../SmppSession";
import Postprocessor from "../Postprocessor";
export default class EnquireLinkReplyProcessor extends Postprocessor {
applicableCommands: string[] = ['enquire_link'];
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise((resolve, reject) => {
if (!!pdu.command && pdu.command === 'enquire_link') {
entity?.doSendPdu(pdu.response(), session);
resolve(pdu);
}
entity?.doSendPdu(pdu.response(), session);
resolve(pdu);
});
}
}
}

View File

@@ -3,22 +3,20 @@ import SmppSession from "../../../SmppSession";
import Postprocessor from "../Postprocessor";
export default class SubmitSmReplyProcessor extends Postprocessor {
applicableCommands: string[] = ['submit_sm'];
private messageIdIterator: number = 0;
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise((resolve, reject) => {
if (!!pdu.command && pdu.command === 'submit_sm') {
// Add an ID here!
let response = pdu.response();
response.message_id = this.messageIdIterator++;
MessageIdManager.addMessageId(pdu, response.message_id);
entity?.doSendPdu(response, session);
resolve(pdu);
}
let response = pdu.response();
response.message_id = this.messageIdIterator++;
MessageIdManager.addMessageId(pdu, response.message_id);
entity?.doSendPdu(response, session);
resolve(pdu);
});
}
}
}

View File

@@ -2,16 +2,16 @@ import SmppSession from "../../../SmppSession";
import Postprocessor from "../Postprocessor";
export default class DeliverSmReplyProcessor extends Postprocessor {
applicableCommands: string[] = ['deliver_sm'];
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise((resolve, reject) => {
if (!!pdu.command && pdu.command === 'deliver_sm') {
entity?.doSendPdu(pdu.response(), session);
resolve(pdu);
}
entity?.doSendPdu(pdu.response(), session);
resolve(pdu);
});
}
}
}

View File

@@ -2,17 +2,15 @@ import SmppSession from "../../../SmppSession";
import Preprocessor from "../Preprocessor";
export default class DeliveryReceiptRequestProcessor extends Preprocessor {
private iterator: number = 0;
applicableCommands: string[] = ['submit_sm'];
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!!pdu.command && pdu.command === "submit_sm") {
pdu.registered_delivery = 1;
}
pdu.registered_delivery = 1;
});
}
}
}

View File

@@ -2,13 +2,14 @@ import SmppSession from "../../../SmppSession";
import Preprocessor from "../Preprocessor";
export default class DestinationEnumeratorProcessor extends Preprocessor {
applicableCommands: string[] = ['submit_sm', 'deliver_sm'];
private iterator: number = 0;
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!!pdu.destination_addr) {
pdu.destination_addr = pdu.destination_addr + this.padLeft(String(this.iterator++), '0', 5);
@@ -19,4 +20,4 @@ export default class DestinationEnumeratorProcessor extends Preprocessor {
private padLeft(str: string, pad: string, length: number): string {
return (new Array(length + 1).join(pad) + str).slice(-length);
}
}
}

View File

@@ -5,6 +5,7 @@ import Preprocessor from "../Preprocessor";
const smpp = require('smpp');
export default class LongSmsProcessor extends Preprocessor {
applicableCommands: string[] = ['submit_sm', 'deliver_sm'];
static readonly maxMessageSizeBits = 1072;
private iterator: number = 0;
@@ -47,7 +48,7 @@ export default class LongSmsProcessor extends Preprocessor {
return characterSizeBits;
}
processPdu(session: any, pdu: PDU, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: PDU, entity?: SmppSession | undefined): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!!pdu.short_message) {
let characterSizeBits: number = LongSmsProcessor.getCharacterSizeForEncoding(pdu);
@@ -83,4 +84,4 @@ export default class LongSmsProcessor extends Preprocessor {
}
});
}
}
}

View File

@@ -2,13 +2,14 @@ import SmppSession from "../../../SmppSession";
import Preprocessor from "../Preprocessor";
export default class SourceEnumeratorProcessor extends Preprocessor {
applicableCommands: string[] = ['submit_sm', 'deliver_sm'];
private iterator: number = 0;
constructor(type: string) {
super(type);
}
processPdu(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
protected doProcess(session: any, pdu: any, entity?: SmppSession | undefined): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!!pdu.source_addr) {
pdu.source_addr = pdu.source_addr + this.padLeft(String(this.iterator++), '0', 5);
@@ -19,4 +20,4 @@ export default class SourceEnumeratorProcessor extends Preprocessor {
private padLeft(str: string, pad: string, length: number): string {
return (new Array(length + 1).join(pad) + str).slice(-length);
}
}
}

View File

@@ -35,6 +35,8 @@ export default class ProcessorManager {
ProcessorManager.preprocessors = [
new DestinationEnumeratorProcessor(Client.name),
new SourceEnumeratorProcessor(Client.name),
new DestinationEnumeratorProcessor(Center.name),
new SourceEnumeratorProcessor(Center.name),
new DeliveryReceiptRequestProcessor(Client.name),
new LongSmsProcessor(Client.name)
];
@@ -44,28 +46,42 @@ export default class ProcessorManager {
return this.preprocessors.concat(this.postprocessors);
}
static getProcessor(name: string): PduProcessor {
static getProcessors(name: string): PduProcessor[] {
this.logger.log1(`Looking for processor with name ${name}...`);
let pduProcessor: PduProcessor | undefined = this.processors.find((processor: PduProcessor) => processor.name === name);
if (pduProcessor) {
this.logger.log1(`Found processor with name ${name}`);
return pduProcessor;
} else {
this.logger.log1(`Processor with name ${name} not found`);
return this.processors[0];
let pduProcessors: PduProcessor[] = this.processors.filter((processor: PduProcessor) => processor.name === name);
this.logger.log1(`Found ${pduProcessors.length} processor(s) with name ${name}`);
return pduProcessors;
}
static attachProcessors(session: SmppSession, processors: PduProcessor[]): void {
this.logger.log1(`Trying to attach processor ${processors.toString()} to session ${session.constructor.name}-${session.id}`);
for (const processor of processors) {
if (this.areCompatible(session, processor)) {
// This could be done a little better but this is OK for now
switch (processor.type) {
case Preprocessor.name:
session.attachPreprocessor(processor);
break;
case Postprocessor.name:
session.attachPostprocessor(processor);
break;
default:
this.logger.log1(`Processor ${processor.name} is not a preprocessor or a postprocessor`);
break;
}
}
}
}
static attachProcessor(session: SmppSession, processor: PduProcessor): void {
this.logger.log1(`Trying to attach preprocessor ${processor.name} to session ${session.constructor.name}-${session.id}`);
if (this.areCompatible(session, processor)) {
// This could be done a little better but this is OK for now
static detachProcessors(session: SmppSession, processors: PduProcessor[]): void {
this.logger.log1(`Trying to detach processors ${processors.toString()} from session ${session.constructor.name}-${session.id}`);
for (const processor of processors) {
switch (processor.type) {
case Preprocessor.name:
session.attachPreprocessor(processor);
session.detachPreprocessor(processor);
break;
case Postprocessor.name:
session.attachPostprocessor(processor);
session.detachPostprocessor(processor);
break;
default:
this.logger.log1(`Processor ${processor.name} is not a preprocessor or a postprocessor`);
@@ -74,21 +90,6 @@ export default class ProcessorManager {
}
}
static detachProcessor(session: SmppSession, processor: PduProcessor): void {
this.logger.log1(`Trying to detach processor ${processor.name} from session ${session.constructor.name}-${session.id}`);
switch (processor.type) {
case Preprocessor.name:
session.detachPreprocessor(processor);
break;
case Postprocessor.name:
session.detachPostprocessor(processor);
break;
default:
this.logger.log1(`Processor ${processor.name} is not a preprocessor or a postprocessor`);
break;
}
}
static areCompatible(session: SmppSession, processor: PduProcessor): boolean {
this.logger.log1(`Checking compatibility between session ${session.constructor.name}-${session.id} and processor ${processor.name}`);
return session.constructor.name === processor.sessionType;
@@ -105,4 +106,4 @@ export default class ProcessorManager {
static getPostprocessorsForType(type: string): PduProcessor[] {
return this.postprocessors.filter((processor: PduProcessor) => processor.sessionType === type);
}
}
}

View File

@@ -74,13 +74,12 @@ export default abstract class SessionManager {
let loadedProcessors: PduProcessor[] = session.preprocessors.concat(session.postprocessors);
sessionObj.appliedProcessors.forEach((processor: PduProcessor) => {
if (!loadedProcessors.find(p => p.name === processor.name)) {
ProcessorManager.detachProcessor(sessionObj, processor);
}
let processorsToDetach: PduProcessor[] = loadedProcessors.filter(p => p.name === processor.name);
ProcessorManager.detachProcessors(sessionObj, processorsToDetach);
});
loadedProcessors.forEach((processor: PduProcessor) => {
if (!sessionObj.appliedProcessors.find(p => p.name === processor.name)) {
ProcessorManager.attachProcessor(sessionObj, ProcessorManager.getProcessor(processor.name));
ProcessorManager.attachProcessors(sessionObj, ProcessorManager.getProcessors(processor.name));
}
});
});
@@ -142,4 +141,4 @@ export default abstract class SessionManager {
}
});
}
}
}

View File

@@ -6,6 +6,7 @@ import PduProcessor from "./PDUProcessor/PduProcessor";
import Postprocessor from "./PDUProcessor/Postprocessor/Postprocessor";
import LongSmsProcessor from "./PDUProcessor/Preprocessor/Client/LongSmsProcessor";
import Preprocessor from "./PDUProcessor/Preprocessor/Preprocessor";
import ProcessorManager from "./PDUProcessor/ProcessorManager";
const NanoTimer = require("nanotimer");
const smpp = require("smpp");
@@ -115,11 +116,11 @@ export default abstract class SmppSession {
doSendPdu(pdu: PDU, session: any): Promise<any> {
return new Promise<any>((resolve, reject) => {
// let characterSizeBits: number = LongSmsProcessor.getCharacterSizeForEncoding(pdu);
// let maxMessageLength: number = LongSmsProcessor.maxMessageSizeBits / characterSizeBits;
// if (!!pdu.short_message && pdu.short_message.length > maxMessageLength) {
// pdu.short_message = pdu.short_message.substring(0, maxMessageLength);
// }
let characterSizeBits: number = LongSmsProcessor.getCharacterSizeForEncoding(pdu);
let maxMessageLength: number = LongSmsProcessor.maxMessageSizeBits / characterSizeBits;
if (!!pdu.short_message && pdu.short_message.length > maxMessageLength) {
pdu.short_message = pdu.short_message.substring(0, maxMessageLength);
}
session.send(pdu, (reply: any) => resolve(reply));
this.eventEmitter.emit(this.EVENT.ANY_PDU_TX, pdu);
});
@@ -149,7 +150,23 @@ export default abstract class SmppSession {
abstract close(): Promise<void>;
abstract serialize(): object;
serialize(): object {
let obj = {
id: this._id,
username: this._username,
password: this._password,
status: this._status,
defaultSingleJob: this._defaultSingleJob.serialize(),
defaultMultipleJob: this._defaultMultipleJob.serialize(),
preprocessors: this.processors.Preprocessor.map((p: PduProcessor) => p.serialize()),
postprocessors: this.processors.Postprocessor.map((p: PduProcessor) => p.serialize()),
availablePreprocessors: ProcessorManager.getPreprocessorsForType(this.constructor.name).map((p: PduProcessor) => p.serialize()),
availablePostprocessors: ProcessorManager.getPostprocessorsForType(this.constructor.name).map((p: PduProcessor) => p.serialize()),
};
return this.postSerialize(obj);
}
abstract postSerialize(obj: object): object;
on(event: string, callback: (...args: any[]) => void): void {
this.eventEmitter.on(event, callback);
@@ -210,9 +227,11 @@ export default abstract class SmppSession {
}
private detachProcessor(processor: PduProcessor, array: PduProcessor[]): void {
array.splice(array.indexOf(processor), 1);
this.logger.log1(`Detaching PDU processor: ${processor.constructor.name}-${this.id}, now active: ${array.length} processors`);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
if (array.indexOf(processor) >= 0) {
array.splice(array.indexOf(processor), 1);
this.logger.log1(`Detaching PDU processor: ${processor.constructor.name}-${this.id}, now active: ${array.length} processors`);
this.eventEmitter.emit(this.EVENT.STATE_CHANGED, this.serialize());
}
}
private attachProcessor(processor: PduProcessor, array: PduProcessor[]): void {
@@ -224,4 +243,4 @@ export default abstract class SmppSession {
this.logger.log1(`PDU processor: ${processor.constructor.name}-${this.id} already attached to session`);
}
}
}
}