-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathprintServer.py
More file actions
221 lines (205 loc) · 8.26 KB
/
printServer.py
File metadata and controls
221 lines (205 loc) · 8.26 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
#!/usr/bin/env
# -*- coding: utf-8 -*-
"""
We could use RedMon to redirect a port to a program, but the idea of
this file is to bypass that.
Instead, we simply set up a loopback ip and act like a network printer.
"""
import typing
import os
import time
import socket
import atexit
import select
from virtualPrinter.windowsPrinters import WindowsPrinters
PrintCallbackDocType=typing.Any
PrintCallbackFunctionType=typing.Callable[[
PrintCallbackDocType, # doc
typing.Optional[str], # title
typing.Optional[str], # author
typing.Optional[str] # filename
],None
]
class PrintServer:
"""
We could use RedMon to redirect a port to a program, but the idea of
this file is to bypass that.
Instead, we simply set up a loopback ip and act like a network printer.
"""
def __init__(self,
printerName:str='My Virtual Printer',
ip:str='127.0.0.1',port:typing.Union[None,int,str]=None,
autoInstallPrinter:bool=True,
printCallbackFn:typing.Optional[PrintCallbackFunctionType]=None):
"""
You can do an ip other than 127.0.0.1 (localhost), but really
a better way is to install the printer and use windows sharing.
If you choose another port, you need to right click on your printer
and go into properties->Ports->Configure Port
and then change the port number.
autoInstallPrinter is used to install the printer in the OS
(currently only supports Windows)
printCallbackFn is a function to be called with received print data
if it is None, then will save it out to a file.
"""
self.ip:str=ip
if port is None:
port=0 # meaning, "any unused port"
self.port:int=int(port)
self.buffersize:int=20 # Normally 1024, but we want fast response
self.autoInstallPrinter:bool=autoInstallPrinter
self.printerName:str=printerName
self.running:bool=False
self.keepGoing:bool=False
self.osPrinterManager:typing.Optional[WindowsPrinters]=None
self.printerPortName:typing.Optional[str]=None
self.printCallbackFn:typing.Optional[
PrintCallbackFunctionType]=printCallbackFn
def __del__(self):
"""
Do some clean up when object is deleted
"""
if self: # this will always be called on program exit,
# so may come in again if the object is already deleted
if self.autoInstallPrinter:
self._uninstallPrinter()
def _installPrinter(self,ip:str,port:int)->None:
"""
Install the printer to the ip address
"""
atexit.register(self.__del__) # ensure that __del__ always
# gets called when the program exits
if os.name=='nt':
self.osPrinterManager=WindowsPrinters()
self.printerPortName=self.printerName+' Port'
makeDefault=False
comment='Virtual printer created in Python'
self.osPrinterManager.addPrinter(self.printerName,ip,port,
self.printerPortName,makeDefault,comment)
else:
print('WARN: Auto install not implemented for os {os.name}')
def _uninstallPrinter(self)->None:
"""
remove the printer
"""
if self.osPrinterManager:
self.osPrinterManager.removePrinter(self.printerName)
self.osPrinterManager.removePort(self.printerPortName)
def run(self)->None:
"""
server mainloop
"""
if self.running:
return
self.running=True
self.keepGoing=True
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((self.ip,self.port))
ip,port=sock.getsockname()
print(f'Opening {ip}:{port}')
if self.autoInstallPrinter:
self._installPrinter(ip,port)
#sock.setblocking(0)
sock.listen(1)
newWay=True
buf:typing.List[str]
while self.keepGoing:
print('\nListening for incoming print job...')
while self.keepGoing: # let select() yield some time to this thread
# so we can detect ctrl+c and keep change
inputready,outputready,exceptready= \
select.select([sock],[],[],1.0)
_=outputready
_=exceptready
if sock in inputready:
break
if not self.keepGoing:
continue
print('Incoming job... spooling...')
conn,addr=sock.accept()
_=addr # not used for now
# could be interesting for remote prints tho
if self.printCallbackFn is None:
with open('I_printed_this.ps','wb') as f:
while True:
raw=conn.recv(self.buffersize)
if not raw:
break
f.write(raw)
f.flush()
elif newWay:
buf=[]
while True:
raw=conn.recv(self.buffersize)
if not raw:
break
data=raw.decode('utf-8',errors='ignore')
buf.append(data)
combinedBuf=''.join(buf)
# get whatever meta info we can
author=None
title=None
filename=None
header='@'+combinedBuf.split('%!PS-',1)[0].split('@',1)[1]
#print header
for line in header.split('\n'):
line=line.strip()
if line.startswith('@PJL JOB NAME='):
n=line.split('"',1)[1].rsplit('"',1)[0]
if os.path.isfile(n):
filename=n
else:
title=n
elif line.startswith('@PJL COMMENT'):
params=line.split('"',1)[1].rsplit('"',1)[0].split(';')
for param in params:
kv=param.split(':',1)
if len(kv)>1:
kv[0]=kv[0].strip().lower()
kv[1]=kv[1].strip()
if kv[0]=='username':
author=kv[1]
elif kv[0]=='app filename':
if title is None:
if os.path.isfile(kv[1]):
filename=kv[1]
else:
title=kv[1]
if title is None and filename is not None:
title=filename.rsplit(os.sep,1)[-1].split('.',1)[0]
self.printCallbackFn(buf,title,author,filename)
else:
buf=[]
printjobHeader=[]
fillingBuf=False
while True:
raw=conn.recv(self.buffersize)
if not raw:
break
data=raw.decode('utf-8',errors='ignore')
if not fillingBuf:
i=data.find('%!PS-')
if i<0:
printjobHeader.append(data)
elif i==0:
buf.append(data)
fillingBuf=True
else:
printjobHeader.append(data[0:i])
buf.append(data[i:])
fillingBuf=True
else:
buf.append(data)
if buf:
self.printCallbackFn(''.join(buf),None,None,None)
conn.close()
time.sleep(0.1)
if __name__=='__main__':
import sys
port=9001
ip='127.0.0.1'
runit=True
for arg in sys.argv[1:]:
pass # TODO: do args
ps=PrintServer(ip=ip,port=port)
ps.run()