Repository navigation
Expand file tree
/
Copy pathutils.js
More file actions
970 lines (906 loc) · 27.7 KB
/
Copy pathutils.js
File metadata and controls
970 lines (906 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
const os = require("os");
const path = require("path");
const fs = require("fs");
const childProcess = require("child_process");
const { app, Notification, dialog, clipboard, shell } = require("electron");
const address = require("address");
const ipp = require("ipp");
const { machineIdSync } = require("node-machine-id");
const Store = require("electron-store");
const { v7: uuidv7 } = require("uuid");
/**
* win32-pdf-printer 的 paper-size-info.exe 会被 electron-builder 解压到 app.asar.unpacked。
* 运行环境下它仍然使用 app.asar 路径,导致文件不存在。这里提前重写 child_process 的执行路径。
*/
function patchWin32PdfPrinterBinPath() {
if (process.platform !== "win32" || !app.isPackaged) return;
const pattern = /app\.asar([\\/])(?=node_modules[\\/]win32-pdf-printer[\\/]paper-size-info\.exe)/i;
const unpackedSegment = "app.asar.unpacked";
const unpackedBin = path.join(
process.resourcesPath,
unpackedSegment,
"node_modules",
"win32-pdf-printer",
"paper-size-info.exe",
);
if (!fs.existsSync(unpackedBin)) return;
const rewriteCommand = (command) => {
if (typeof command !== "string" || !pattern.test(command)) return command;
if (command.includes(unpackedSegment)) return command;
const replaced = command.replace(pattern, `${unpackedSegment}$1`);
// 仅包裹 exe 路径,避免把参数一起包进引号导致命令解析失败
const unpackedBinNormalized = unpackedBin.replace(/\\/g, "/");
const quoteIfNeeded = (exePath) =>
exePath.includes(" ") ? `"${exePath}"` : exePath;
if (
replaced.startsWith(`"${unpackedBin}"`) ||
replaced.startsWith(`"${unpackedBinNormalized}"`)
) {
return replaced;
}
if (replaced === unpackedBin || replaced === unpackedBinNormalized) {
return quoteIfNeeded(replaced);
}
if (replaced.startsWith(unpackedBin + " ")) {
return `${quoteIfNeeded(unpackedBin)}${replaced.slice(unpackedBin.length)}`;
}
if (replaced.startsWith(unpackedBinNormalized + " ")) {
return `${quoteIfNeeded(unpackedBinNormalized)}${replaced.slice(
unpackedBinNormalized.length,
)}`;
}
return replaced;
};
const wrap = (original) =>
function patched(command, ...args) {
return original.call(childProcess, rewriteCommand(command), ...args);
};
childProcess.execFile = wrap(childProcess.execFile);
childProcess.exec = wrap(childProcess.exec);
childProcess.execSync = wrap(childProcess.execSync);
const spawn = childProcess.spawn;
childProcess.spawn = function(command, ...args) {
return spawn.call(childProcess, rewriteCommand(command), ...args);
};
const spawnSync = childProcess.spawnSync;
childProcess.spawnSync = function(command, ...args) {
return spawnSync.call(childProcess, rewriteCommand(command), ...args);
};
}
patchWin32PdfPrinterBinPath();
const { getPaperSizeInfo, getPaperSizeInfoAll } = require("win32-pdf-printer");
const db = require("./database");
let buildInfo = {};
const buildInfoPath = path.join(__dirname, "../build-info.json");
if (fs.existsSync(buildInfoPath)) {
buildInfo = require(buildInfoPath);
}
Store.initRenderer();
const schema = {
mainTitle: {
type: "string",
default: "Electron-hiprint",
},
nickName: {
type: "string",
default: "",
},
openAtLogin: {
type: "boolean",
default: true,
},
openAsHidden: {
type: "boolean",
default: true,
},
connectTransit: {
type: "boolean",
default: false,
},
transitUrl: {
type: "string",
default: "",
},
transitToken: {
type: "string",
default: "",
},
allowNotify: {
type: "boolean",
default: true,
},
closeType: {
type: "string",
enum: ["tray", "quit"],
default: "tray",
},
port: {
type: "number",
minimum: 10000,
default: 17521,
},
token: {
type: "string",
default: "",
},
pluginVersion: {
type: "string",
default: "0.0.60",
},
logPath: {
type: "string",
default: app.getPath("logs"),
},
pdfPath: {
type: "string",
default: app.getPath("temp"),
},
defaultPrinter: {
type: "string",
default: "",
},
disabledGpu: {
type: "boolean",
default: false,
},
rePrint: {
type: "boolean",
default: true,
},
};
const store = new Store({ schema });
/**
* @description: 获取当前系统 IP 地址
* @return {String}
*/
function addressIp() {
return address.ip();
}
/**
* @description: 获取当前系统 IPV6 地址
* @return {String}
*/
function addressIpv6() {
return address.ipv6();
}
/**
* @description: 获取当前系统 MAC 地址
* @return {String}
*/
function addressMac() {
return new Promise((resolve) => {
address.mac(function(err, addr) {
if (err) {
resolve(err);
} else {
resolve(addr);
}
});
});
}
/**
* @description: 获取当前系统 IP、IPV6、MAC 地址
* @return {Object}
*/
function addressAll() {
return new Promise((resolve) => {
address.mac(function(err, mac) {
if (err) {
resolve({ ip: address.ip(), ipv6: address.ipv6(), mac: err });
} else {
resolve({ ip: address.ip(), ipv6: address.ipv6(), mac });
}
});
});
}
/**
* @description: address 方法重写
* @return {Object}
*/
const _address = {
ip: addressIp,
ipv6: addressIpv6,
mac: addressMac,
all: addressAll,
};
/**
* @description: 检查分片任务实例,用于自动删除超时分片信息
*/
const watchTaskInstance = generateWatchTask(
() => global.PRINT_FRAGMENTS_MAPPING,
)();
/**
* @description: 尝试获取客户端唯一id,依赖管理员权限与注册表读取
* @return {string}
*/
function getMachineId() {
try {
return machineIdSync({ original: true });
} catch (error) {
// 若获取失败,也可以使用 UUID 代替,需要单独存储 首次创建 后续读取
// 默认返回空 表示读不到就好
return "";
}
}
/**
* @description: 抛出当前客户端信息,提供更多有价值的信息,逐步替换原有 address
* @param {io.Socket} socket
* @return {void}
*/
function emitClientInfo(socket) {
_address.mac().then((mac) => {
socket.emit("clientInfo", {
hostname: os.hostname(), // 主机名
version: app.getVersion(), // 版本号
platform: process.platform, // 平台
arch: process.arch, // 系统架构
mac: mac, // mac 地址
ip: _address.ip(), // ip 地址
ipv6: _address.ipv6(), // ipv6 地址
clientUrl: `http://${_address.ip()}:${store.get("port") || 17521}`, // 客户端地址
machineId: getMachineId(), // 客户端唯一id
nickName: store.get("nickName"), // 客户端昵称
});
});
}
/**
* 生成检查分片任务的闭包函数
* @param {Object} getCheckTarget 获取校验对象,最后会得到global.PRINT_FRAGMENTS_MAPPING
* @returns {Function}
*/
function generateWatchTask(getCheckTarget) {
// 记录当前检查任务是否开启,避免重复开启任务
let isWatching = false;
/**
* @description: 检查分片任务实例创建函数
* @param {Object} config 检查参数,根据实际情况调整
* @param {number} [config.checkInterval=5] 执行内存检查的时间间隔,单位分钟
* @param {number} [config.expire=10] 分片信息过期时间,单位分钟,不应过小
*/
return function generateWatchTaskInstance(config = {}) {
// 合并用户和默认配置
const realConfig = Object.assign(
{
checkInterval: 5, // 默认检查间隔
expire: 10, // 默认过期时间
},
config,
);
return {
startWatch() {
if (isWatching) return;
this.createWatchTimeout();
},
createWatchTimeout() {
// 更新开关状态
isWatching = true;
return setTimeout(
this.clearFragmentsWhichIsExpired.bind(this),
realConfig.checkInterval * 60 * 1000,
);
},
clearFragmentsWhichIsExpired() {
const checkTarget = getCheckTarget();
const currentTimeStamp = Date.now();
Object.entries(checkTarget).map(([id, fragmentInfo]) => {
// 获取任务最后更新时间
const { updateTime } = fragmentInfo;
// 任务过期时,清除任务信息释放内存
if (currentTimeStamp - updateTime > realConfig.expire * 60 * 1000) {
delete checkTarget[id];
}
});
// 获取剩余任务数量
const printTaskCount = Object.keys(checkTarget).length;
// 还有打印任务,继续创建检查任务
if (printTaskCount) this.createWatchTimeout();
// 更新开关状态
else isWatching = false;
},
};
};
}
/**
* SQLite bound-parameter limit
*/
const SQLITE_MAX_VARIABLE_NUMBER = 999;
/**
* @description: 查询打印状态,按 templateIds 过滤打印记录并通过回调返回结果;
* templateIds 为空时返回最近 20 条记录
* @param {Array<String>|*} templateIds 模板id列表,为空时查询最近 20 条
* @param {Function} onSuccess 查询成功回调,参数为 rows
* @param {Function} onError 查询失败回调,参数为 err
* @return {void}
*/
function queryPrintStatus(templateIds, onSuccess, onError) {
const baseSelect =
"SELECT id, timestamp, socketId, clientType, printer, templateId, pageNum, status, rePrintAble, errorMessage FROM print_logs";
const orderBy = " ORDER BY timestamp DESC, id DESC";
// Empty templateIds → return latest 20 records
if (!Array.isArray(templateIds) || templateIds.length === 0) {
db.all(`${baseSelect}${orderBy} LIMIT 20`, [], (err, rows) => {
if (err) onError(err);
else onSuccess(rows);
});
return;
}
// Enforce SQLite bound-parameter limit
if (templateIds.length > SQLITE_MAX_VARIABLE_NUMBER) {
onError(
new Error(
`templateIds 长度超过限制,最多支持 ${SQLITE_MAX_VARIABLE_NUMBER} 个 / templateIds exceeds limit, max ${SQLITE_MAX_VARIABLE_NUMBER}`,
),
);
return;
}
const placeholders = templateIds.map(() => "?").join(",");
db.all(
`${baseSelect} WHERE templateId IN (${placeholders})${orderBy}`,
templateIds,
(err, rows) => {
if (err) onError(err);
else onSuccess(rows);
},
);
}
/**
* @description: 作为本地服务端时绑定的 socket 事件
* @param {*} server
* @return {void}
*/
function initServeEvent(server) {
// 必须传入实体
if (!server) return false;
/**
* @description: 校验 token
*/
server.use((socket, next) => {
const token = store.get("token");
if (token && token !== socket.handshake.auth.token) {
console.log(
`==> 插件端 Authentication error: ${socket.id}, token: ${socket.handshake.auth.token}`,
);
const err = new Error("Authentication error");
err.data = {
content: "Token 错误",
};
next(err);
} else {
next();
}
});
/**
* @description: 新的 web client 连入,绑定 socket 事件
*/
server.on("connect", async (socket) => {
console.log(`==> 插件端 New Connected: ${socket.id}`);
// 通知渲染进程已连接
MAIN_WINDOW.webContents.send(
"serverConnection",
server.engine.clientsCount,
);
// 判断是否允许通知
if (store.get("allowNotify")) {
// 弹出连接成功通知
const notification = new Notification({
title: "新的连接",
body: `已建立新的连接,当前连接数:${server.engine.clientsCount}`,
});
// 显示通知
notification.show();
}
// 向 client 发送打印机列表
socket.emit(
"printerList",
await MAIN_WINDOW.webContents.getPrintersAsync(),
);
// 向 client 发送客户端信息
emitClientInfo(socket);
/**
* @description: client 请求客户端信息
*/
socket.on("getClientInfo", () => {
console.log(`插件端 ${socket.id}: getClientInfo`);
emitClientInfo(socket);
});
/**
* @description: client请求 address ,获取本机 IP、IPV6、MAC 地址
* @description: addressType 为 null 时,返回所有地址
* @description: 逐步废弃该 api
* @param {String} addressType ip、ipv6、mac、all === null
*/
socket.on("address", (addressType) => {
console.log(
`插件端 ${socket.id}: get address(${addressType || "未指定类型"})`,
);
switch (addressType) {
case "ip":
case "ipv6":
socket.emit("address", addressType, _address[addressType]());
break;
case "dns":
case "interface":
case "vboxnet":
// 用处不大的几个信息,直接废弃
socket.emit("address", addressType, null, "This type is removed.");
break;
default:
addressType = addressType === "mac" ? "mac" : "all";
_address[addressType]().then((res) => {
socket.emit("address", addressType, res);
});
break;
}
});
/**
* @description: client 请求刷新打印机列表
*/
socket.on("refreshPrinterList", async () => {
console.log(`插件端 ${socket.id}: refreshPrinterList`);
socket.emit(
"printerList",
await MAIN_WINDOW.webContents.getPrintersAsync(),
);
});
/**
* @description: client 获取打印机纸张信息
*/
socket.on("getPaperSizeInfo", (printer) => {
console.log(`插件端 ${socket.id}: getPaperSizeInfo`);
if (process.platform === "win32") {
const printerName =
typeof printer === "string"
? printer
: printer && typeof printer.printer === "string"
? printer.printer
: "";
let paper = getPaperSizeInfoAll();
if (printerName) {
paper = paper.find((item) => item.PrinterName === printerName) || null;
}
paper && socket.emit("paperSizeInfo", paper);
}
});
/**
* @description: client 调用 ipp 打印 详见:https://www.npmjs.com/package/ipp
*/
socket.on("ippPrint", (options) => {
console.log(`插件端 ${socket.id}: ippPrint`);
try {
const { url, opt, action, message } = options;
let printer = ipp.Printer(url, opt);
socket.emit("ippPrinterConnected", printer);
let msg = Object.assign(
{
"operation-attributes-tag": {
"requesting-user-name": "hiPrint",
},
},
message,
);
// data 必须是 Buffer 类型
if (msg.data && !Buffer.isBuffer(msg.data)) {
if ("string" === typeof msg.data) {
msg.data = Buffer.from(msg.data, msg.encoding || "utf8");
} else {
msg.data = Buffer.from(msg.data);
}
}
/**
* action: Get-Printer-Attributes 获取打印机支持参数
* action: Print-Job 新建打印任务
* action: Cancel-Job 取消打印任务
*/
printer.execute(action, msg, (err, res) => {
socket.emit(
"ippPrinterCallback",
err ? { type: err.name, msg: err.message } : null,
res,
);
});
} catch (error) {
console.log(`插件端 ${socket.id}: ippPrint error: ${error.message}`);
socket.emit("ippPrinterCallback", {
type: error.name,
msg: error.message,
});
}
});
/**
* @description: client ipp request 详见:https://www.npmjs.com/package/ipp
*/
socket.on("ippRequest", (options) => {
console.log(`插件端 ${socket.id}: ippRequest`);
try {
const { url, data } = options;
let _data = ipp.serialize(data);
ipp.request(url, _data, (err, res) => {
socket.emit(
"ippRequestCallback",
err ? { type: err.name, msg: err.message } : null,
res,
);
});
} catch (error) {
console.log(`插件端 ${socket.id}: ippRequest error: ${error.message}`);
socket.emit("ippRequestCallback", {
type: error.name,
msg: error.message,
});
}
});
/**
* @description: client 常规打印任务
*/
socket.on("news", (data) => {
if (data) {
PRINT_RUNNER.add((done) => {
data.socketId = socket.id;
data.taskId = uuidv7();
data.clientType = "local";
PRINT_WINDOW.webContents.send("print-new", data);
MAIN_WINDOW.webContents.send("printTask", true);
PRINT_RUNNER_DONE[data.taskId] = done;
});
}
});
/**
* @description: client 分批打印任务
*/
socket.on("printByFragments", (data) => {
if (data) {
const { total, index, htmlFragment, id } = data;
const currentInfo =
PRINT_FRAGMENTS_MAPPING[id] ||
(PRINT_FRAGMENTS_MAPPING[id] = {
total,
fragments: [],
count: 0,
updateTime: 0,
});
// 添加片段信息
currentInfo.fragments[index] = htmlFragment;
// 计数
currentInfo.count++;
// 记录更新时间
currentInfo.updateTime = Date.now();
// 全部片段已传输完毕
if (currentInfo.count === currentInfo.total) {
// 清除全局缓存
delete PRINT_FRAGMENTS_MAPPING[id];
// 合并全部打印片段信息
data.html = currentInfo.fragments.join("");
// 添加打印任务
PRINT_RUNNER.add((done) => {
data.socketId = socket.id;
data.taskId = uuidv7();
data.clientType = "local";
PRINT_WINDOW.webContents.send("print-new", data);
MAIN_WINDOW.webContents.send("printTask", true);
PRINT_RUNNER_DONE[data.taskId] = done;
});
}
// 开始检查任务
watchTaskInstance.startWatch();
}
});
socket.on("render-print", (data) => {
if (data) {
RENDER_RUNNER.add((done) => {
data.socketId = socket.id;
data.taskId = uuidv7();
data.clientType = "local";
RENDER_WINDOW.webContents.send("print", data);
RENDER_RUNNER_DONE[data.taskId] = done;
});
}
});
socket.on("render-jpeg", (data) => {
if (data) {
RENDER_RUNNER.add((done) => {
data.socketId = socket.id;
data.taskId = uuidv7();
data.clientType = "local";
RENDER_WINDOW.webContents.send("png", data);
RENDER_RUNNER_DONE[data.taskId] = done;
});
}
});
socket.on("render-pdf", (data) => {
if (data) {
RENDER_RUNNER.add((done) => {
data.socketId = socket.id;
data.taskId = uuidv7();
data.clientType = "local";
RENDER_WINDOW.webContents.send("pdf", data);
RENDER_RUNNER_DONE[data.taskId] = done;
});
}
});
/**
* @description: client 查询打印状态
* @param {Object} data
* @param {Array<String>} [data.templateIds] 模板id列表,为空时返回最近 20 条记录
*/
socket.on("getPrintStatus", (data) => {
console.log(`插件端 ${socket.id}: getPrintStatus`);
queryPrintStatus(
data && Array.isArray(data.templateIds) ? data.templateIds : [],
(rows) => socket.emit("printStatus", rows),
(err) => {
console.error(`插件端 ${socket.id}: getPrintStatus error: ${err.message}`);
socket.emit("printStatusError", { msg: err.message });
},
);
});
/**
* @description: client 断开连接
*/
socket.on("disconnect", () => {
console.log(`==> 插件端 Disconnect: ${socket.id}`);
MAIN_WINDOW?.webContents?.send(
"serverConnection",
server.engine.clientsCount,
);
});
});
}
/**
* @description: 作为客户端连接中转服务时绑定的 socket 事件
* @return {void}
*/
function initClientEvent() {
// 作为客户端连接中转服务时只有一个全局 client
var client = global.SOCKET_CLIENT;
/**
* @description: 连接中转服务成功,绑定 socket 事件
*/
client.on("connect", async () => {
console.log(`==> 中转服务 Connected Transit Server: ${client.id}`);
// 通知渲染进程已连接
MAIN_WINDOW.webContents.send("clientConnection", true);
// 判断是否允许通知
if (store.get("allowNotify")) {
// 弹出连接成功通知
const notification = new Notification({
title: "已连接中转服务器",
body: `已连接至中转服务器【${store.get("transitUrl")}】,即刻开印!`,
});
// 显示通知
notification.show();
}
// 向 中转服务 发送打印机列表
client.emit(
"printerList",
await MAIN_WINDOW.webContents.getPrintersAsync(),
);
// 向 中转服务 发送客户端信息
emitClientInfo(client);
});
/**
* @description: 中转服务 请求客户端信息
*/
client.on("getClientInfo", () => {
console.log(`中转服务 ${client.id}: getClientInfo`);
emitClientInfo(client);
});
/**
* @description: 中转服务 请求刷新打印机列表
*/
client.on("refreshPrinterList", async () => {
console.log(`中转服务 ${client.id}: refreshPrinterList`);
client.emit(
"printerList",
await MAIN_WINDOW.webContents.getPrintersAsync(),
);
});
/**
* @description: 中转服务 调用 ipp 打印 详见:https://www.npmjs.com/package/ipp
*/
client.on("ippPrint", (options) => {
console.log(`中转服务 ${client.id}: ippPrint`);
try {
const { url, opt, action, message, replyId } = options;
let printer = ipp.Printer(url, opt);
client.emit("ippPrinterConnected", { printer, replyId });
let msg = Object.assign(
{
"operation-attributes-tag": {
"requesting-user-name": "hiPrint",
},
},
message,
);
// data 必须是 Buffer 类型
if (msg.data && !Buffer.isBuffer(msg.data)) {
if ("string" === typeof msg.data) {
msg.data = Buffer.from(msg.data, msg.encoding || "utf8");
} else {
msg.data = Buffer.from(msg.data);
}
}
/**
* action: Get-Printer-Attributes 获取打印机支持参数
* action: Print-Job 新建打印任务
* action: Cancel-Job 取消打印任务
*/
printer.execute(action, msg, (err, res) => {
client.emit(
"ippPrinterCallback",
err ? { type: err.name, msg: err.message, replyId } : { replyId },
res,
);
});
} catch (error) {
console.log(`中转服务 ${client.id}: ippPrint error: ${error.message}`);
client.emit("ippPrinterCallback", {
type: error.name,
msg: error.message,
replyId,
});
}
});
/**
* @description: 中转服务 ipp request 详见:https://www.npmjs.com/package/ipp
*/
client.on("ippRequest", (options) => {
console.log(`中转服务 ${client.id}: ippRequest`);
try {
const { url, data, replyId } = options;
let _data = ipp.serialize(data);
ipp.request(url, _data, (err, res) => {
client.emit(
"ippRequestCallback",
err ? { type: err.name, msg: err.message, replyId } : { replyId },
res,
);
});
} catch (error) {
console.log(`中转服务 ${client.id}: ippRequest error: ${error.message}`);
client.emit("ippRequestCallback", {
type: error.name,
msg: error.message,
replyId,
});
}
});
/**
* @description: 中转服务 常规打印任务
*/
client.on("news", (data) => {
if (data) {
PRINT_RUNNER.add((done) => {
data.socketId = client.id;
data.taskId = uuidv7();
data.clientType = "transit";
PRINT_WINDOW.webContents.send("print-new", data);
MAIN_WINDOW.webContents.send("printTask", true);
PRINT_RUNNER_DONE[data.taskId] = done;
});
}
});
client.on("render-print", (data) => {
if (data) {
RENDER_RUNNER.add((done) => {
data.socketId = client.id;
data.taskId = uuidv7();
data.clientType = "transit";
RENDER_WINDOW.webContents.send("print", data);
RENDER_RUNNER_DONE[data.taskId] = done;
});
}
});
client.on("render-jpeg", (data) => {
if (data) {
RENDER_RUNNER.add((done) => {
data.socketId = client.id;
data.taskId = uuidv7();
data.clientType = "transit";
RENDER_WINDOW.webContents.send("png", data);
RENDER_RUNNER_DONE[data.taskId] = done;
});
}
});
client.on("render-pdf", (data) => {
if (data) {
RENDER_RUNNER.add((done) => {
data.socketId = client.id;
data.taskId = uuidv7();
data.clientType = "transit";
RENDER_WINDOW.webContents.send("pdf", data);
RENDER_RUNNER_DONE[data.taskId] = done;
});
}
});
/**
* @description: 中转服务 查询打印状态
* @param {Object} data
* @param {Array<String>} [data.templateIds] 模板id列表,为空时返回最近 20 条记录
*/
client.on("getPrintStatus", (data) => {
console.log(`中转服务 ${client.id}: getPrintStatus`);
queryPrintStatus(
data && Array.isArray(data.templateIds) ? data.templateIds : [],
(rows) => client.emit("printStatus", rows),
(err) => {
console.error(`中转服务 ${client.id}: getPrintStatus error: ${err.message}`);
client.emit("printStatusError", { msg: err.message });
},
);
});
/**
* @description: 中转服务 断开连接
*/
client.on("disconnect", () => {
console.log(`==> 中转服务 Disconnect: ${client.id}`);
MAIN_WINDOW.webContents.send("clientConnection", false);
});
}
/**
* @description: 打印机状态码 十进制 -> 十六进制, 返回对应的详细错误信息, 详见:https://github.com/mlmdflr/win32-pdf-printer/blob/51f7a9b3687e260a7d83ea467b22b374fb153b52/paper-size-info/Status.cs
* @param { String } printerName 打印机名称
* @return { Object { StatusMsg: String // 打印机状态详情信息 } }
*/
function getCurrentPrintStatusByName(printerName) {
if (process.platform === "win32") {
const { StatusMsg } = getPaperSizeInfoAll().find(
(item) => item.PrinterName === printerName,
) || { StatusMsg: "未找到打印机" };
return {
StatusMsg,
};
}
return { StatusMsg: "非Windows系统, 暂不支持" };
}
function showAboutDialog() {
const detail = `版本: ${app.getVersion()}
提交: ${buildInfo.commitId}
日期: ${buildInfo.commitDate}
Electron: ${process.versions.electron}
Chromium: ${process.versions.chrome}
Node.js: ${process.versions.node}
V8: ${process.versions.v8}
OS: ${os.type()} ${os.arch()} ${os.release()}`.trim();
const title = store.get("mainTitle") || "Electron-hiprint";
dialog
.showMessageBox({
title: `关于 ${title}`,
message: title,
type: "info",
buttons: ["反馈", "复制", "确定"],
noLink: true,
defaultId: 0,
detail,
cancelId: 2,
normalizeAccessKeys: true,
})
.then((result) => {
if (result.response === 0) {
const issuesUrl = new URL(
`https://github.com/CcSimple/electron-hiprint/issues/new`,
);
issuesUrl.searchParams.set(
"title",
`[反馈][${app.getVersion()}] 在此处完善反馈标题`,
);
const issuesBody = `## 问题描述
请在此处详细描述你遇到的问题
## 版本信息
${detail}`;
issuesUrl.searchParams.set("body", issuesBody);
shell.openExternal(issuesUrl.href);
}
if (result.response === 1) {
clipboard.writeText(detail);
}
});
}
module.exports = {
store,
address: _address,
initServeEvent,
initClientEvent,
getCurrentPrintStatusByName,
getMachineId,
showAboutDialog,
};