Skip to content

Commit

Permalink
Merge pull request #473 from manuc66/feature/manage_path
Browse files Browse the repository at this point in the history
Improve file path management
  • Loading branch information
manuc66 authored May 17, 2022
2 parents 827582f + c80145e commit 6fc3917
Show file tree
Hide file tree
Showing 9 changed files with 212 additions and 34 deletions.
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"scripts": {
"start": "ts-node src/index.ts",
"build": "tsc -p .",
"built-start": "tsc -p . && node --trace-warnings ./dist/index.js",
"start-dev": "nodemon",
"prepublishOnly": "tsc -p ./ --outDir dist/",
"prettier": "prettier --write \"src/**/*.ts\"",
Expand Down Expand Up @@ -51,7 +52,9 @@
"@types/mocha": "^9.1.1",
"@types/node": "^17.0.8",
"@types/xml2js": "^0.4.9",
"@types/chai-string": "^1.4.2",
"chai": "^4.3.6",
"chai-string": "^1.5.0",
"codecov": "^3.8.3",
"eslint": "^8.15.0",
"mocha": "^10.0.0",
Expand Down
4 changes: 4 additions & 0 deletions root/app.sh
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ if [ ! -z "$PATTERN" ]; then
ARGS="${ARGS} -p ${PATTERN}"
fi

if [ ! -z "$TEMP_DIR" ]; then
ARGS="${ARGS} -t ${TEMP_DIR}"
fi

if [ ! -z "$CMDLINE" ]; then
ARGS="${ARGS} ${CMDLINE}"
fi
Expand Down
33 changes: 22 additions & 11 deletions src/HPApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ let printerIP = "192.168.1.11";
let debug = false;
let callCount = 0;


export default class HPApi {
static setPrinterIP(ip: string) {
printerIP = ip;
Expand All @@ -36,7 +35,11 @@ export default class HPApi {
debug = dbg;
}

private static logDebug(callId: number, isRequest: boolean, msg: object | string) {
private static logDebug(
callId: number,
isRequest: boolean,
msg: object | string
) {
if (debug) {
const id = String(callId).padStart(4, "0");
const content = typeof msg === "string" ? msg : JSON.stringify(msg);
Expand Down Expand Up @@ -132,22 +135,31 @@ export default class HPApi {
}
}

static async removeDestination(walkupScanDestination: WalkupScanDestination) {
let urlInfo = new URL(walkupScanDestination.resourceURI);
static async removeDestination(
walkupScanDestination: WalkupScanDestination | WalkupScanToCompDestination
) {

if (urlInfo.pathname === null) {
throw new Error(
`invalid walkupScanDestination.resourceURI: ${walkupScanDestination.resourceURI}`
);
let path: string;

if (walkupScanDestination.resourceURI.startsWith("http")) {
let urlInfo = new URL(walkupScanDestination.resourceURI);
if (urlInfo.pathname === null) {
throw new Error(
`invalid walkupScanDestination.resourceURI: ${walkupScanDestination.resourceURI}`
);
}
path = urlInfo.pathname;
} else {
path = walkupScanDestination.resourceURI;
}

const response = await HPApi.callAxios({
baseURL: `http://${printerIP}`,
url: urlInfo.pathname,
url: path,
method: "DELETE",
responseType: "text",
});
if (response.status === 204) {
if (response.status === 204 || response.status == 200) {
return true;
} else {
throw response;
Expand Down Expand Up @@ -312,7 +324,6 @@ export default class HPApi {
}
}


static async downloadPage(
binaryURL: string,
destination: string
Expand Down
60 changes: 47 additions & 13 deletions src/PathHelper.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,77 @@
import path from "path";
import dateformat from "dateformat";
import fs from "fs/promises";
const { promises: Fs } = require("fs");
const fs = require("fs");
import os from "os";

export default class PathHelper {
static getFileForPage(
folder: string,
scanCount: number,
currentPageNumber: number,
filePattern : string | undefined,
filePattern: string | undefined,
extension: string
): string {

if (filePattern) {
return path.join(folder, `${dateformat(new Date(), filePattern)}.${extension}`);
return path.join(
folder,
`${dateformat(new Date(), filePattern)}.${extension}`
);
}

return path.join(
folder,
`scan${scanCount}_page${currentPageNumber}.${extension}`
);
}

static makeUnique(filePath: string): string {
if (!fs.existsSync(filePath)) {
return filePath;
}

return path.join(folder, `scan${scanCount}_page${currentPageNumber}.${extension}`);
let parsed = path.parse(filePath);
let tryName = `${parsed.dir}${path.sep}${parsed.name}${dateformat(
new Date(),
"yyyymmdd"
)}${parsed.ext}`;
if (!fs.existsSync(tryName)) {
return tryName;
}

parsed = path.parse(tryName);
let i = "a";
while (i <= "z") {
tryName = `${parsed.dir}${path.sep}${parsed.name}_${i}${parsed.ext}`;
if (!fs.existsSync(tryName)) {
return tryName;
}
i = String.fromCharCode(i.charCodeAt(0) + 1);
}
throw new Error(
`Can not create unique file: ${filePath} iterated until: ${tryName}`
);
}

static getFileForScan(
folder: string,
scanCount: number,
filePattern : string | undefined,
filePattern: string | undefined,
extension: string
): string {

if (filePattern) {
return path.join(folder, `${dateformat(new Date(), filePattern)}.${extension}`);
return path.join(
folder,
`${dateformat(new Date(), filePattern)}.${extension}`
);
}

return path.join(folder, `scan${scanCount}.${extension}`);
}

static async getOutputFolder(folder: string | undefined) {
if (!folder) {
folder = await fs.mkdtemp(
path.join(os.tmpdir(), "scan-to-pc")
);
static async getOutputFolder(folder?: string | undefined): Promise<string> {
if (typeof folder !== "string") {
return Fs.mkdtemp(path.join(os.tmpdir(), "scan-to-pc"));
}
return folder;
}
Expand Down
36 changes: 29 additions & 7 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,14 @@ async function handleProcessingState(
job.binaryURL
);

const destinationFilePath = PathHelper.getFileForPage(
let destinationFilePath = PathHelper.getFileForPage(
folder,
scanCount,
currentPageNumber,
program.opts().pattern,
"jpg"
);
destinationFilePath = PathHelper.makeUnique(destinationFilePath);
const filePath = await HPApi.downloadPage(
job.binaryURL,
destinationFilePath
Expand Down Expand Up @@ -380,12 +381,13 @@ async function mergeToPdf(
scanCount: number,
scanJobContent: ScanContent
) {
const pdfFilePath = PathHelper.getFileForScan(
let pdfFilePath = PathHelper.getFileForScan(
folder,
scanCount,
program.opts().pattern,
"pdf"
);
pdfFilePath = PathHelper.makeUnique(pdfFilePath);
await createPdfFrom(scanJobContent, pdfFilePath);
scanJobContent.elements.forEach((e) => fs.unlink(e.path));
return pdfFilePath;
Expand Down Expand Up @@ -417,6 +419,7 @@ function displayJpegScan(scanJobContent: ScanContent) {
async function saveScan(
event: Event,
folder: string,
tempFolder: string,
scanCount: number
): Promise<void> {
if (event.compEventURI) {
Expand All @@ -434,8 +437,19 @@ async function saveScan(
console.log("Selected shortcut: " + destination.shortcut);

const contentType = destination.getContentType();
const toPdf =
destination.shortcut === "SavePDF" || destination.shortcut === "EmailPDF";
let toPdf: boolean;
let destinationFolder: string;
if (
destination.shortcut === "SavePDF" ||
destination.shortcut === "EmailPDF"
) {
toPdf = true;
destinationFolder = tempFolder;
console.log(`Scan will be converted to pdf, using ${destinationFolder} as temp scan output directory for individual pages`);
} else {
toPdf = false;
destinationFolder = folder;
}

const isDuplex =
destination.scanPlexMode != null && destination.scanPlexMode != "Simplex";
Expand All @@ -457,7 +471,7 @@ async function saveScan(
await executeScanJobs(
scanJobSettings,
inputSource,
folder,
destinationFolder,
scanCount,
scanJobContent,
event
Expand All @@ -480,6 +494,11 @@ async function init() {
const folder = await PathHelper.getOutputFolder(program.opts().directory);
console.log(`Target folder: ${folder}`);

const tempFolder = await PathHelper.getOutputFolder(
program.opts().tempDirectory
);
console.log(`Temp folder: ${tempFolder}`);

let scanCount = 0;

let keepActive = true;
Expand All @@ -494,7 +513,7 @@ async function init() {

scanCount++;
console.log(`Scan event captured, saving scan #${scanCount}`);
await saveScan(event, folder, scanCount);
await saveScan(event, folder, tempFolder, scanCount);
} catch (e) {
errorCount++;
console.error(e);
Expand Down Expand Up @@ -550,6 +569,10 @@ async function main() {
"-d, --directory <dir>",
"Directory where scans are saved (defaults to /tmp/scan-to-pc<random>)"
);
program.option(
"-t, --temp-directory <dir>",
"Temp directory used for processing (defaults to /tmp/scan-to-pc<random>)"
);
program.option(
"-p, --pattern <pattern>",
'Pattern for filename (i.e. "scan"_dd.mm.yyyy_hh:MM:ss, without this its scanPage<number>)'
Expand All @@ -558,7 +581,6 @@ async function main() {
program.parse(process.argv);

let ip = program.opts().address || "192.168.1.53";
//let ip = program.opts().address || "192.168.1.30" ;
if (!ip) {
ip = await findOfficejetIp();
}
Expand Down
1 change: 0 additions & 1 deletion test/EtagEventTable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { describe } from "mocha";
import { expect } from "chai";
import path from "path";
import * as fs from "fs/promises";
import HPApi from "../src/HPApi";
import EventTable from "../src/EventTable";
import { EtagEventTable } from "../src/EventTable";

Expand Down
Loading

0 comments on commit 6fc3917

Please sign in to comment.