forked from fogleman/FeedNotifier
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipc.py
336 lines (258 loc) · 8.75 KB
/
ipc.py
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
# -*- coding: utf-8 -*-
"""[summary]
Returns:
[type] -- [description]
"""
import functools
import logging
import socket
import socketserver
import sys
import time
import wx
import util
if sys.platform.startswith('win32'):
try:
import win32file
import win32pipe
except ModuleNotFoundError:
sys.exit("\n\tpip install pywin32 ...\n")
class CallbackContainer(object):
"""[summary]
Arguments:
object {[type]} -- [description]
"""
def __init__(self):
"""Initialize CallbackContainer class.
"""
self.callback = None
logging.debug("Return callback=%s", self.callback)
def __call__(self, message):
"""Making GUI method calls from non-GUI threads.
Any extra positional or keyword args are passed on to the callable
when it is called.
Arguments:
message {[type]} -- [description]
"""
if self.callback:
wx.CallAfter(self.callback, message)
logging.debug("Launch wx.CallAfter(self.callback, message)")
if sys.platform.startswith('win32'):
def init():
"""initialize the thread server
Returns:
[type] -- [description]
"""
logging.debug('initializing')
container = CallbackContainer()
message = '\n'.join(sys.argv[1:])
name = r'\\.\pipe\FeedNotifier_%s' % wx.GetUserId()
if client(name, message):
logging.debug("Initialized: return message='%s' and name='%s'", message, name)
return None, message
else:
logging.debug("Initialized: message='%s' and name='%s'", message, name)
logging.debug('Jump to util::start_thread()')
util.start_thread(server, name, container)
logging.debug('return of util::start_thread()')
return container, message
def server(name, callback_func):
"""[summary]
Arguments:
name {[type]} -- [description]
callback_func {[type]} -- [description]
"""
buffer = 4096
timeout = 1000
error = False
while True:
if error:
time.sleep(1)
error = False
handle = win32pipe.CreateNamedPipe(
name,
win32pipe.PIPE_ACCESS_INBOUND,
win32pipe.PIPE_TYPE_BYTE |
win32pipe.PIPE_READMODE_BYTE |
win32pipe.PIPE_WAIT,
win32pipe.PIPE_UNLIMITED_INSTANCES,
buffer,
buffer,
timeout,
None)
if handle == win32file.INVALID_HANDLE_VALUE:
error = True
continue
try:
if win32pipe.ConnectNamedPipe(handle) != 0:
error = True
else:
code, message = win32file.ReadFile(handle, buffer, None)
if code == 0:
callback_func(message)
else:
error = True
except Exception:
error = True
finally:
win32pipe.DisconnectNamedPipe(handle)
win32file.CloseHandle(handle)
def client(name, message):
"""[summary]
Arguments:
name {[type]} -- [description]
message {[type]} -- [description]
Returns:
[type] -- [description]
"""
try:
file = open(name, 'wb')
file.write(message)
file.close()
return True
except IOError:
return False
elif sys.platform.startswith('darwin'):
sys.exit('\n\tdarwin platform not soported\n')
elif sys.platform.startswith('linux'):
# sys.exit('\n\tlinux in not suported at time...\n')
def init():
"""initialize the thread server
Returns:
[type] -- [description]
"""
logging.debug(f'Initializing ipc')
container = CallbackContainer()
# print(f"Container: {container}") # FIXME: delete this
# print(f"Container: {type(container)}") # FIXME: delete this
# print(f"Container: {container.__doc__}") # FIXME: delete this
message = '\n'.join(sys.argv[1:])
name = r'\\.\pipe\FeedNotifier_%s' % wx.GetUserId()
# if client(name, message):
# print('ipc::init:win32 - Existen "message" y "name"')
# print('Salimos de ipc::init()::linux')
# return None, message
# else:
# print('ipc::init:win32 - No existen "message" y "name"')
# print('Salimos de ipc::init()::linux')
# # jump to util.py
# util.start_thread(server, name, container)
#
# return container, message
logging.debug(f'Initialized ipc')
def server(name, callback_func):
"""[summary]
Arguments:
name {[type]} -- [description]
callback_func {[type]} -- [description]
"""
buffer = 4096
timeout = 1000
error = False
while True:
if error:
time.sleep(1)
error = False
handle = win32pipe.CreateNamedPipe(
name,
win32pipe.PIPE_ACCESS_INBOUND,
win32pipe.PIPE_TYPE_BYTE |
win32pipe.PIPE_READMODE_BYTE |
win32pipe.PIPE_WAIT,
win32pipe.PIPE_UNLIMITED_INSTANCES,
buffer,
buffer,
timeout,
None)
if handle == win32file.INVALID_HANDLE_VALUE:
error = True
continue
try:
if win32pipe.ConnectNamedPipe(handle) != 0:
error = True
else:
code, message = win32file.ReadFile(handle, buffer, None)
if code == 0:
callback_func(message)
else:
error = True
except Exception:
error = True
finally:
win32pipe.DisconnectNamedPipe(handle)
win32file.CloseHandle(handle)
def client(name, message):
"""[summary]
Arguments:
name {[type]} -- [description]
message {[type]} -- [description]
Returns:
[type] -- [description]
"""
try:
file = open(name, 'wb')
file.write(message)
file.close()
return True
except IOError:
return False
else:
# import functools # FIXME: delete this
# import socket # FIXME: delete this
# import socketserver # FIXME: delete this
def init():
"""[summary]
Returns:
[type] -- [description]
"""
container = CallbackContainer()
message = '\n'.join(sys.argv[1:])
host, port = 'localhost', 31763
try:
server(host, port, container)
return container, message
except socket.error:
client(host, port, message)
return None, message
def server(host, port, callback_func):
"""[summary]
Arguments:
host {[type]} -- [description]
port {[type]} -- [description]
callback_func {[type]} -- [description]
"""
class Handler(socketserver.StreamRequestHandler):
"""[summary]
Arguments:
socketserver {[type]} -- [description]
"""
def __init__(self, callback_func, *args, **kwargs):
"""[summary]
Arguments:
callback_func {[type]} -- [description]
"""
self.callback_func = callback_func
socketserver.StreamRequestHandler.__init__(self,
*args,
**kwargs)
def handle(self):
"""[summary]
"""
data = self.rfile.readline().strip()
self.callback_func(data)
server = socketserver.TCPServer((host, port),
functools.partial(Handler,
callback_func))
util.start_thread(server.serve_forever)
def client(host, port, message):
"""[summary]
Arguments:
host {[type]} -- [description]
port {[type]} -- [description]
message {[type]} -- [description]
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
sock.send(message)
sock.close()
# EOF