Skip to content

Commit

Permalink
feat: add isComplete function (#13)
Browse files Browse the repository at this point in the history
* getJobId and isPrintComplete

* getJobId tests

* extend try-catch

* we don't ask questions here

* more tests

* undo some formatting

* deleted some stuff I shouldn't have

* tabs to spaces

* update index.ts

* messed up the exports order (:

* a few nits

* Undo changes to print fn

* remove stale non-null assertions

* format with prettier

* update tests & remove comments

* order

* fix condition

* fix tests and read stdout as expected

* Update parse-response.ts

* readme

* update readme
  • Loading branch information
ppivanov authored and artiebits committed Aug 22, 2023
1 parent 44080f1 commit 72ce461
Show file tree
Hide file tree
Showing 7 changed files with 190 additions and 4 deletions.
36 changes: 34 additions & 2 deletions README.md
Expand Up @@ -14,7 +14,8 @@ A utility for Unix-like operating systems to print files from Node.js and Electr
- [Basic Usage](#basic-usage)
- [Installation](#installation)
- [API](#api)
- [`print(pdf, printer, options) => Promise<void>`](#printpdf-printer-options--promisevoid)
- [`print(pdf, printer, options) => Promise<{stdout, stderr}>`](#printpdf-printer-options--promisevoid)
- [`isPrintComplete(printResponse) => Promise<boolean>`](#isprintcompleteprintresponse--promiseboolean)
- [`getPrinters() => Promise<Printer[]>`](#getprinters--promiseprinter)
- [`getDefaultPrinter() => Promise<Printer | null>`](#getdefaultprinter--promiseprinter--null)
- [License](#license)
Expand Down Expand Up @@ -61,7 +62,7 @@ A function to print a file to a printer.

**Returns**

`Promise<void>`.
`Promise<{stdout: string | null, stderr: string | null}>`.

To print a file to the default printer:

Expand Down Expand Up @@ -94,6 +95,37 @@ const options = ["-o landscape", "-o fit-to-page", "-o media=A4"];
print("assets/file.jpg", printer, options).then(console.log);
```

### `isPrintComplete(printResponse) => Promise<boolean>`

**Arguments**

| Argument | Type | Optional | Description |
| ------------- | :---------------------------------------: | -------- | ------------------------------ |
| printResponse | <code>{stdout: string &#124; null}</code> | Required | Promise returned from [`print`](#printpdf-printer-options--promisevoid). |

**Returns**

`Promise<boolean>`: False if the job is on the queue or `stdout` is null, true otherwise.

**Examples**

```javascript
import { isComplete } from 'unix-print';

const fileToPrint = 'assets/file.pdf';
const printJob = print(fileToPrint);

async function waitForPrintCompletion(printJob) {
while (!await isPrintComplete(printJob)) {
// Wait a bit before checking again (to avoid constant checks)
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second
}
console.log('Job complete');
}

await waitForPrintCompletion(printJob);
```

### `getPrinters() => Promise<Printer[]>`

**Returns**
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
@@ -1,3 +1,4 @@
export { default as print } from "./print/print";
export { default as getDefaultPrinter } from "./get-default-printer/get-default-printer";
export { default as getPrinters } from "./get-printers/get-printers";
export { default as isPrintComplete } from "./utils/parse-response";
4 changes: 3 additions & 1 deletion src/print/print.spec.ts
Expand Up @@ -9,7 +9,9 @@ jest.mock("../utils/exec-async");
beforeEach(() => {
// override the implementations
existsSync.mockImplementation(() => true);
execAsync.mockImplementation(() => Promise.resolve());
execAsync.mockImplementation(() =>
Promise.resolve({ stdout: "request id is myDummyPrinter-15 (1 file(s))" })
);
});

afterEach(() => {
Expand Down
3 changes: 2 additions & 1 deletion src/print/print.ts
@@ -1,11 +1,12 @@
import fs from "fs";
import { ExecResponse } from "../types";
import execAsync from "../utils/exec-async";

export default async function print(
file: string,
printer?: string,
options?: string[]
): Promise<void> {
): Promise<ExecResponse> {
if (!file) throw "No file specified";
if (!fs.existsSync(file)) throw "No such file";

Expand Down
5 changes: 5 additions & 0 deletions src/types.ts
Expand Up @@ -5,3 +5,8 @@ export interface Printer {
alerts: string | null;
connection: string | null;
}

export interface ExecResponse {
stdout: string | null;
stderr: string | null;
}
83 changes: 83 additions & 0 deletions src/utils/parse-response.spec.ts
@@ -0,0 +1,83 @@
import execAsync from '../utils/exec-async';
import { getRequestId, default as isPrintComplete } from './parse-response';

jest.mock('../utils/exec-async');
jest.mock('../get-default-printer/get-default-printer');

const queuedStdout = `lp0-39 username 15360 Mon 12 Jun 2023 21:09:48`;

describe('getRequestId', () => {
it('returns the job id', async () => {
const response = { stdout: 'request id is myDummyPrinter-15 (1 file(s))', stderr: null };
const expected = 'myDummyPrinter-15';

expect(getRequestId(response)).toEqual(expected);
});

it('returns -1 on weird input', async () => {
const response = { stdout: 'printer is offline or something/manually passing stuff', stderr: null };
const expected = null;

expect(getRequestId(response)).toEqual(expected);
});

it('returns -1 when response is empty', async () => {
const response = { stdout: '', stderr: null };
const expected = null;

expect(getRequestId(response)).toEqual(expected);
});

it('returns -1 when response is null', async () => {
const response = { stdout: null, stderr: null };
const expected = null;

expect(getRequestId(response)).toEqual(expected);
});
});

describe('isPrintComplete', () => {
beforeEach(() => {
execAsync.mockImplementationOnce(() => Promise.resolve({ stdout: queuedStdout }));
});

afterEach(() => {
// restore the original implementation.
execAsync.mockRestore();
});

it('job is still on the queue', async () => {
const printResponse = { stdout: 'request id is lp0-39 (1 file(s))', stderr: null };

const result = isPrintComplete(printResponse);

await expect(result).resolves.toEqual(false);
expect(execAsync).toBeCalledWith(`lpstat -o lp0`);
});

it('job is not on the queue', async () => {
const printResponse = { stdout: 'request id is lp0-12 (1 file(s))', stderr: null };

const result = isPrintComplete(printResponse);

await expect(result).resolves.toEqual(true);
});

it('nothing on the queue', async () => {
const printResponse = { stdout: 'request id is lp0-39 (1 file(s))', stderr: null };
execAsync.mockRestore();
execAsync.mockImplementationOnce(() => Promise.resolve({ stdout: '' }));

const result = isPrintComplete(printResponse);

await expect(result).resolves.toEqual(true);
});

it("getJobId didn't work", async () => {
const printResponse = { stdout: 'printer is offline or something/manually passing stuff', stderr: null };

const result = isPrintComplete(printResponse);

await expect(result).resolves.toEqual(false);
});
});
62 changes: 62 additions & 0 deletions src/utils/parse-response.ts
@@ -0,0 +1,62 @@
import { ExecResponse } from "../types";
import execAsync from "./exec-async";

async function isPrintComplete(printResponse: ExecResponse) {
const requestId = getRequestId(printResponse);
if (!requestId) {
return false;
}

const args = new Array<string>();
const { printer } = splitRequestId(requestId);
if (printer) {
args.push("-o", printer);
}

const { stdout } = await execAsync(`lpstat ${args.join(" ")}`);

if (!stdout) {
return true;
}

try {
const lines = stdout.split("\n");
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes(requestId)) {
return false; // still printing if on the queue
}
}

return true;
} catch (err) {
return true;
}
}

export function getRequestId(printResponse: ExecResponse) {
const res = printResponse.stdout;
if (res) {
try {
const requestId = res.split(" ")[3];

return printerNameRegex.test(requestId) ? requestId : null;
} catch (err) {
return null;
}
}

return null;
}

function splitRequestId(requestId: string) {
const splitByHyphen = requestId.split("-");
const jobId = splitByHyphen[splitByHyphen.length - 1];

const printer = requestId.slice(0, requestId.length - (jobId.length + 1)); // substring only the name and exclude the jobId + the hyphen

return { jobId, printer };
}

const printerNameRegex = /^[\w\.\/_@.\/@#$&+-]+-[0-9]+$/;

export default isPrintComplete;

0 comments on commit 72ce461

Please sign in to comment.