diff --git a/bin/txms b/bin/txms index d789a85..3dec311 100644 --- a/bin/txms +++ b/bin/txms @@ -53,8 +53,11 @@ function run(typ, value, loc) { } else if (typ === 'mms') { const mms = txms.mms(true, value); process.stdout.write(`${mms}\n`); + } else if (typ === 'download' || typ === 'dl') { + txms.downloadMessage(value, loc); + process.stdout.write(`TxMS downloaded as file\n`); } else { - throw new Error('Invalid type specified. Use "encode", "decode", "getendpoint", "sms", or "mms".'); + throw new Error('Invalid type specified.'); } process.exit(0); } catch (err) { diff --git a/package.json b/package.json index ddc5c18..312189e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "txms.js", - "version": "1.2.3", + "version": "1.2.4", "description": "Transaction messaging service protocol", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/index.ts b/src/index.ts index c16657a..5a1330a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,3 +1,5 @@ +import fs from 'fs'; + export interface Transport { encode(hex: string): string; decode(data: string): string; @@ -5,6 +7,7 @@ export interface Transport { sms(number?: boolean | string | number | Array, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string; mms(number?: boolean | string | number | Array, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string; generateMessageUri(type: 'sms' | 'mms', number?: boolean | string | number | Array, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string; + downloadMessage(hex: string, optionalFilename?: string): void; } export interface Error extends globalThis.Error { @@ -39,6 +42,14 @@ export function addCountry(networkId: number | string, countryCode: string, phon countries[networkKey][countryCode] = phoneNumbers; } +function slugify(str: string): string { + return str + .toLowerCase() + .replace(/[^\w\s-]/g, '') + .replace(/[\s_-]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + const txms: Transport = { encode(hex: string): string { let data = ''; @@ -156,6 +167,21 @@ const txms: Transport = { } return endpoint ? `${type}:${endpoint}${encodedMessage ? `${platform === 'ios' ? '&' : '?'}body=${encodedMessage}` : ''}` : `${type}:${platform === 'ios' ? '&' : '?'}body=${encodedMessage}`; + }, + + downloadMessage(hex: string, optionalFilename?: string): void { + const encodedMessage = this.encode(hex); + + let filename: string; + const cleanedHex = hex.startsWith('0x') ? hex.slice(2) : hex; + const first6 = cleanedHex.slice(0, 6); + const last6 = cleanedHex.slice(-6); + filename = `${first6}${last6}.txms.txt`; + if (optionalFilename) { + filename = `${slugify(filename)}.txms.txt`; + } + const buffer = Buffer.from(encodedMessage, 'utf16le').swap16(); + fs.writeFileSync(filename, buffer); } };