Skip to content

Commit 93d94e1

Browse files
Merge pull request #33 from bchainhub/update/feature-download-04
Updated download function
2 parents e9bb391 + d8fd3ea commit 93d94e1

File tree

4 files changed

+67
-31
lines changed

4 files changed

+67
-31
lines changed

README.md

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,9 @@ The library is designed to be compatible with both module systems, so you can ch
145145
- `getEndpoint(network?: number | string, countriesList?: string | Array<string>): { [key: string]: Array<string> }` — Get an object of SMS endpoints (phone numbers) per country.
146146
- `sms(number?: boolean | string | number | Array<string>, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string` — Create an SMS URI based on the provided parameters.
147147
- `mms(number?: boolean | string | number | Array<string>, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string` — Create an MMS URI based on the provided parameters.
148-
- `downloadMessage(hex: string, optionalFilename?: string): Promise<string>` — Download a file with the encoded content as `.txms.txt` file in your working directory.
148+
- `downloadMessage(hex: string | string[], optionalFilename?: string): Promise<string>` — Download a file with the encoded content as `.txms.txt` file in your working directory. You can provide one hex transaction or an array of transactions (`.batch` will be prepended to suffix if batch is chosen and optional name not defined).
149+
150+
Note: The `downloadMessage` function is asynchronous and returns a Promise. You can use the `await` keyword to wait for the Promise to resolve. The function will download a file with the encoded content as a `(.batch).txms.txt` file in your working directory. You can optionally provide a filename as the second parameter. It is designed to be used in Node.js environments as well as Browser. It is not designed to download high amount of files. if you prefer to do your own download flow, you can use the `encode` function and save the result to a file.
149151

150152
### Parameters
151153

@@ -157,6 +159,7 @@ The library is designed to be compatible with both module systems, so you can ch
157159
- `message` = the SMS message content.
158160
- `encodeMessage` (default: `true`) = whether to encode the message before using `encodeURIComponent`.
159161
- `platform` = the platform to use for the SMS URI. Currently supported: `ios`, `global`. Default: `global`. `ios` uses the `&body=`, while `global` uses the `?` for `?body=` parameter.
162+
- `optionalFilename` = the optional filename for the downloaded file suffixed with `.txms.txt`. Filename is slugified.
160163

161164
## CLI
162165

@@ -169,17 +172,17 @@ npm i -g txms.js
169172
### Getting started
170173

171174
```bash
172-
txms {type} {value} {location}
175+
txms {type} {value} {value1}
173176
```
174177

175-
- type: `encode` (`e`), `decode` (`d`), `getendpoint` (`g`), `sms`, `mms`, `download` (`dl`)
176-
- value: message; network for getendpoint
177-
- location: ISO 3166 Alpha-2 country/ies code/s for getendpoint
178+
- type: `version` (`v`), `encode` (`e`), `decode` (`d`), `getendpoint` (`g`), `sms`, `mms`, `download` (`dl`)
179+
- value: 1st parameter for the type
180+
- value1: 2nd parameter for the type
178181

179182
### Piping
180183

181184
```bash
182-
echo {value} | txms {type} {location}
185+
echo {value} | txms {type} {value1}
183186
```
184187

185188
## Extending Aliases and Countries
@@ -276,7 +279,7 @@ One MMS has 1600 characters. The MMS text limit is 5000 characters. MMS object h
276279

277280
To send MMS, you can use two options:
278281

279-
- You can place the content as text document with extension `.txms` and send it to the same number. Each transaction can be divided with new line. You can place multiple `txms` files in one MMS.
282+
- You can place the content as text document (text/plain) with extension `.txms.txt` and send it to the same number. Each transaction can be divided with new line. You can place multiple `txms` files into one MMS.
280283
- Place transaction(s) in the text message body and send it to the same number. Each transaction can be divided with new line.
281284

282285
MMS has about the same price as SMS (in Slovakia), but the downside is that smartphone should have enabled the MMS service and the data are stored on 3rd party server.
@@ -290,19 +293,19 @@ You're welcome to contribute in any capacity.
290293
We welcome:
291294

292295
- Forking [this repository](https://github.com/bchainhub/txms.js/fork)
296+
- Starring [this repository](https://github.com/bchainhub/txms.js/stargazers)
293297
- Opening a [pull request](https://github.com/bchainhub/txms.js/pulls)
294298
- Creating your own [SMS endpoint](#sms-endpoint)
295299
- Sending us some Øres / ₡ores: [cb7147879011ea207df5b35a24ca6f0859dcfb145999](https://blockindex.net/address/cb7147879011ea207df5b35a24ca6f0859dcfb145999)
296-
- Starring this repository
297300

298-
To contribute, please follow the steps:
301+
### To Contribute, Please Follow These Steps
299302

300-
1. Fork the repository.
303+
1. [Fork the repository](https://github.com/bchainhub/txms.js/fork).
301304
2. Create a new branch.
302305
3. Make your changes.
303306
4. Commit your changes.
304307
5. Push your changes.
305-
6. Open a pull request.
308+
6. [Open a pull request](https://github.com/bchainhub/txms.js/pulls).
306309

307310
Please ensure your code is well-documented and follows the project's coding standards.
308311

bin/txms

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@ import txms from '../dist/index.js';
55
if (process.stdin.isTTY) {
66
const typ = process.argv[2];
77
const value = process.argv[3];
8-
const loc = process.argv[4];
8+
const value1 = process.argv[4];
99

10-
run(typ, value, loc);
10+
run(typ, value, value1);
1111
} else {
1212
let content = '';
1313
process.stdin.setEncoding('utf8');
@@ -19,33 +19,38 @@ if (process.stdin.isTTY) {
1919

2020
let value = content;
2121
let typ = process.argv[2];
22-
let loc = process.argv[3];
22+
let value1 = process.argv[3];
2323

2424
if (!content) {
2525
value = process.argv[2];
2626
typ = process.argv[3];
27-
loc = process.argv[4];
27+
value1 = process.argv[4];
2828
}
2929

30-
run(typ, value, loc);
30+
run(typ, value, value1);
3131
});
3232
}
3333

34-
function run(typ, value, loc) {
34+
function run(typ, value, value1) {
3535
if (!value) {
3636
process.stderr.write('value is required\n');
3737
process.exit(1);
3838
}
3939

4040
try {
41-
if (typ === 'encode' || typ === 'e') {
41+
if (typ === 'version' || typ === 'v') {
42+
const packageJsonPath = join(__dirname, '../package.json');
43+
const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
44+
const version = packageJson.version;
45+
process.stdout.write(`TxMS version: ${version}\n`);
46+
} else if (typ === 'encode' || typ === 'e') {
4247
const encoded = txms.encode(value);
4348
process.stdout.write(`${encoded}\n`);
4449
} else if (typ === 'decode' || typ === 'd') {
4550
const decoded = txms.decode(value);
4651
process.stdout.write(`${decoded}\n`);
4752
} else if (typ === 'getendpoint' || typ === 'g') {
48-
const endpoint = txms.getEndpoint(value, loc);
53+
const endpoint = txms.getEndpoint(value, value1);
4954
process.stdout.write(`${JSON.stringify(endpoint, null, 2)}\n`);
5055
} else if (typ === 'sms') {
5156
const sms = txms.sms(true, value);
@@ -54,8 +59,13 @@ function run(typ, value, loc) {
5459
const mms = txms.mms(true, value);
5560
process.stdout.write(`${mms}\n`);
5661
} else if (typ === 'download' || typ === 'dl') {
57-
const filename = txms.downloadMessage(value, loc);
58-
process.stdout.write(`TxMS file was downloaded as "${filename}" in your working directory.\n`);
62+
txms.downloadMessage(value, value1).then((filename) => {
63+
process.stdout.write(`TxMS file was downloaded as "${filename}" in your working directory.\n`);
64+
process.exit(0);
65+
}).catch((err) => {
66+
process.stderr.write(`${err.message}\n`);
67+
process.exit(1);
68+
});
5969
} else {
6070
throw new Error('Invalid type specified.');
6171
}

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "txms.js",
3-
"version": "1.2.6",
3+
"version": "1.2.7",
44
"description": "Transaction messaging service protocol",
55
"main": "dist/index.js",
66
"types": "dist/index.d.ts",

src/index.ts

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ export interface Transport {
55
sms(number?: boolean | string | number | Array<string>, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string;
66
mms(number?: boolean | string | number | Array<string>, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string;
77
generateMessageUri(type: 'sms' | 'mms', number?: boolean | string | number | Array<string>, message?: string, network?: number | string, encodeMessage?: boolean, platform?: string): string;
8-
downloadMessage(hex: string, optionalFilename?: string): Promise<string>;
8+
downloadMessage(hex: string | string[], optionalFilename?: string): Promise<string>;
99
}
1010

1111
export interface Error extends globalThis.Error {
@@ -167,37 +167,60 @@ const txms: Transport = {
167167
return endpoint ? `${type}:${endpoint}${encodedMessage ? `${platform === 'ios' ? '&' : '?'}body=${encodedMessage}` : ''}` : `${type}:${platform === 'ios' ? '&' : '?'}body=${encodedMessage}`;
168168
},
169169

170-
async downloadMessage(hex: string, optionalFilename?: string): Promise<string> {
171-
const encodedMessage = this.encode(hex);
170+
async downloadMessage(hex: string | string[], optionalFilename?: string): Promise<string> {
171+
// If hex is an array, join the encoded messages with newlines
172+
const encodedMessage = Array.isArray(hex)
173+
? hex.map(h => this.encode(h)).join('\n')
174+
: this.encode(hex);
172175

173176
let filename: string;
174-
const cleanedHex = hex.startsWith('0x') ? hex.slice(2) : hex;
177+
// Use the first hex string for filename derivation, regardless of array or string input
178+
const cleanedHex = (Array.isArray(hex) ? hex[0] : hex).toLowerCase().startsWith('0x')
179+
? (Array.isArray(hex) ? hex[0] : hex).slice(2)
180+
: (Array.isArray(hex) ? hex[0] : hex);
175181
if (cleanedHex.length < 12) {
176-
filename = `${cleanedHex}.txms.txt`;
182+
filename = cleanedHex;
177183
} else {
178184
const first6 = cleanedHex.slice(0, 6);
179185
const last6 = cleanedHex.slice(-6);
180-
filename = `${first6}${last6}.txms.txt`;
186+
filename = `${first6}${last6}`;
181187
}
182188

189+
// If the input is an array with more than one item and no optional filename, append .batch
190+
if (Array.isArray(hex) && hex.length > 1 && !optionalFilename) {
191+
filename = `${filename}.batch`;
192+
}
193+
194+
// Final filename composition
183195
if (optionalFilename) {
184196
filename = `${slugify(optionalFilename)}.txms.txt`;
197+
} else {
198+
filename = `${filename}.txms.txt`;
185199
}
186200

201+
// Node.js environment check
202+
/* eslint-disable no-undef */
187203
if (typeof process !== 'undefined' && process.versions && process.versions.node) {
204+
// Node.js: Use 'fs' to write the file
188205
const fs = await import('fs');
189206
fs.writeFileSync(filename, encodedMessage);
190-
} else {
207+
} else if (typeof window !== 'undefined' && typeof Blob !== 'undefined' && typeof document !== 'undefined') {
208+
// Browser environment
191209
const blob = new Blob([encodedMessage], { type: 'text/plain;charset=utf-16' });
192-
193210
const link = document.createElement('a');
194211
link.href = URL.createObjectURL(blob);
195212
link.download = filename;
196-
link.click();
213+
document.body.appendChild(link); // Append link to body
214+
link.click(); // Trigger download
215+
document.body.removeChild(link); // Clean up
216+
} else {
217+
throw new Error('Unsupported environment');
197218
}
219+
/* eslint-enable no-undef */
198220

199221
return filename;
200222
}
223+
201224
};
202225

203226
export default txms;

0 commit comments

Comments
 (0)