forked from NTUOSC/ntu-scanner-py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
461 lines (381 loc) · 14.6 KB
/
main.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
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
import sys
import os
import time
import json
import threading
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, Gio, GLib
from card_reader import CardReader, CardReaderException
import requests
from requests.exceptions import ConnectTimeout
# from requests_futures.sessions import FuturesSession
# from session.sessions import FuturesSession
from session import FuturesSession
session = FuturesSession()
G_API_PATH = 'https://home.ntuosc.org/go'
G_TOKEN_SAVE_PATH = './TOKEN.txt'
GC_VOTER_INFO_CAN_VOTE = '''<span color="#388e3c">學號 <b>{r[stuid]}</b>
身份別:<b>{r[stutype]}</b>
選區:<b>{r[college]}</b> {mod}
原學系代碼:{r[dptcode]}
驗證通過
</span>
'''
GC_VOTER_INFO_CANNOT_VOTE = '''<span color="#f44336">學號 <b>{r[stuid]}</b>
身份別:<b>{r[stutype]}</b>
選區:{r[college]}
原學系代碼:{r[dptcode]}
驗證失敗!"{msg}"
</span>
'''
GC_VOTER_INFO_ERROR = '<span color="red">不具投票身份:<b>{}</b></span>'
'''
Given the college (學院代碼), return the string (i.e. 選票別) that is attached
after the string...
'''
def getModifier(college):
groupA = ['法學院', '文學院', '社會科學院', '生物資源暨農學院', '生命科學院']
groupB = ['理學院', '醫學院', '工學院', '管理學院', '電機資訊學院']
if college in groupA:
return '(A)'
if college in groupB:
return '(B)'
return ''
'''
API wrappers; should be wrapped as a class though
'''
def queryPing(token, callback=None, **kwargs):
return session.get(G_API_PATH + '/ping',
params={ 'token': token },
background_callback=callback,
**kwargs)
def queryQuery(params, callback=None, **kwargs):
return session.get(G_API_PATH + '/query',
params=params,
background_callback=callback,
**kwargs)
def queryCommit(paraPair, callback=None, **kwargs):
token, tx = paraPair
return session.post(G_API_PATH + '/commit',
params={ 'token': token },
data={ 'tx': tx },
background_callback=callback,
**kwargs)
'''
other thread; should be wrapped (ry
'''
def startHealthCheck(app):
fstr = '%H:%M:%S'
label = app.get('last_sync_ts')
def setLoadStr():
label.set_text('...' + label.get_text())
def pingPeriodic():
while True:
if app._entryCode: break
time.sleep(5)
print('Health check started')
while True:
areq = queryPing(app._entryCode, None, timeout=3)
GLib.idle_add(setLoadStr)
try:
resp = areq.result()
timestr = time.strftime(fstr)
data = resp.json()
result = ''
if data['ok']:
result = '成功'
else:
result = '失敗: {}'.format(data['msg'])
GLib.idle_add(label.set_text, timestr + ' ' + result)
except ConnectTimeout:
timestr = time.strftime(fstr)
GLib.idle_add(label.set_text, timestr + ' 逾時')
except:
timestr = time.strftime(fstr)
GLib.idle_add(label.set_text, timestr + ' 錯誤')
# XXX: should add some randomness
time.sleep(14)
thr = threading.Thread(target=pingPeriodic)
thr.daemon = True
thr.start()
return thr
'''
The main application
'''
class Application(Gtk.Application):
builder = None
cardReader = None
def __init__(self, *args, **kwargs):
super().__init__(*args,
application_id='org.ntusc106vote.scanner',
flags=Gio.ApplicationFlags.FLAGS_NONE,
**kwargs)
self.window = None
self._generalStatusCtxId = None
self._entryCode = ''
self._clientInfo = None
self._card_sec = None
self._card_serial = None
self._tx = None
def do_startup(self, *args):
Gtk.Application.do_startup(self)
builder = Gtk.Builder()
builder.add_from_file('ui.glade')
builder.connect_signals(self)
self.builder = builder
screen = Gdk.Screen.get_default()
provider = Gtk.CssProvider()
provider.load_from_path('./scanner.css')
Gtk.StyleContext.add_provider_for_screen(
screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
settings = Gtk.Settings.get_for_screen(screen)
settings.set_property('gtk-font-name', '微軟正黑體')
def do_activate(self):
window = self.get('app_window')
window.show()
self.window = window
try:
# use cred. saved locally
with open(G_TOKEN_SAVE_PATH, 'r') as f:
self._entryCode = f.read().strip()
queryPing(self._entryCode, self.cbLoadClientInfo)
except OSError as err:
# ask to login
loginDialog = self.get('login_dialog')
response = loginDialog.run()
if response <= 0: # destroy = -4
exit(0)
loginDialog.close()
timerThread = startHealthCheck(app)
self._generalStatusCtxId = (self.get('general_status')
.get_context_id('general'))
self.setStuidEntryEditability(False)
self.tryInitCardReader()
# custom utility functions
def get(self, name):
return self.builder.get_object(name)
def _updateStatus(self, text):
self.get('general_status').push(self._generalStatusCtxId, text)
# aux. functions / callbacks
def cbLoadClientInfo(self, _, err, resp):
try:
if err:
print(err)
data = resp.json()
if data['ok']:
self._clientInfo = data['client']
else:
self._clientInfo = {}
GLib.idle_add(self.updateClientInfo)
except Exception as err:
print('error in cbLoadClientInfo:', err)
def cbLoadVoterInfo(self, _, err, resp):
try:
def recoverUI():
self.get('entry_cardid').set_sensitive(True)
self.get('button_start_auth').set_sensitive(True)
if err:
GLib.idle_add(self.get('status').set_text, '連線逾時')
GLib.idle_add(recoverUI)
return
canVote = False
data = resp.json()
if data['ok']:
if data['can_vote']:
voterInfo = GC_VOTER_INFO_CAN_VOTE
canVote = True
self._tx = data['tx']
else:
voterInfo = GC_VOTER_INFO_CANNOT_VOTE
voterInfo = voterInfo.format(
r=data['result'],
mod=getModifier(data['result']['college']),
msg=data['msg'])
else:
voterInfo = GC_VOTER_INFO_ERROR
voterInfo = voterInfo.format(data['msg'])
GLib.idle_add(recoverUI)
GLib.idle_add(self.updateVoterInfo, canVote, voterInfo)
except Exception as err:
print('error in cbLoadVoterInfo:', err)
def cbLoadCommitResult(self, _, err, resp):
try:
def recoverUI():
self.get('button_commit').set_sensitive(True)
self.get('button_forgive').set_sensitive(True)
if err:
GLib.idle_add(self._updateStatus, '領票失敗,請回報選務中心')
GLib.idle_add(recoverUI)
return
data = resp.json()
GLib.idle_add(self.updateCommitResult, data)
GLib.idle_add(recoverUI)
except Exception as err:
print('error in cbLoadCommitResult:', err)
def updateClientInfo(self):
# set client name based on client info received
text = '票點:' + self._clientInfo.get('name', '??')
self.get('client_name').set_text(text)
def setStuidEntryEditability(self, yes):
inst = self.get('entry_cardid')
inst.set_editable(yes)
if yes:
inst.set_icon_from_icon_name(
Gtk.EntryIconPosition.PRIMARY, 'gtk-edit')
else:
inst.set_icon_from_icon_name(
Gtk.EntryIconPosition.PRIMARY, 'emblem-readonly')
def switchAuthMode(self, isAuthByCard):
ctxB1 = self.get('button_scan_card').get_style_context()
ctxB2 = self.get('button_manual_input').get_style_context()
if isAuthByCard is None:
# set back to initial state
ctxB1.remove_class('active')
ctxB2.remove_class('active')
self.setStuidEntryEditability(False)
elif isAuthByCard:
ctxB1.add_class('active')
ctxB2.remove_class('active')
self.setStuidEntryEditability(False)
else:
ctxB1.remove_class('active')
ctxB2.add_class('active')
self.setStuidEntryEditability(True)
self.get('entry_cardid').set_text('')
self.get('entry_cardid').set_sensitive(True)
self.get('status').set_text('')
def tryInitCardReader(self):
statusIcon = self.get('client_status')
try:
self.cardReader = CardReader()
except RuntimeError:
statusIcon.set_tooltip_markup('找不到讀卡機,請檢查是否妥善連接')
except Exception as err:
# discard the object QQ
self.cardReader = None
statusIcon.set_tooltip_markup('讀卡機初始化失敗,請關閉程式後再試一次')
print('Card reader general failure', err)
iconName = 'emblem-default'
if self.cardReader is None:
iconName = 'emblem-important'
self.get('client_status').set_from_icon_name(iconName, -1)
def updateVoterInfo(self, yes, info):
self.get('voter_info').set_markup(info)
self.get('button_commit').set_sensitive(yes)
stack = self.get('view_stack')
stack.set_visible_child(stack.get_children()[1])
def updateCommitResult(self, data):
if data['ok']:
msgbox = Gtk.MessageDialog(self.window, Gtk.DialogFlags.MODAL,
Gtk.MessageType.INFO, Gtk.ButtonsType.OK,
'領票程序結束 (成功)')
msgbox.format_secondary_text('真是謝天謝地 <(_ _)>')
self._updateStatus('領票程序完成!')
else:
msgbox = Gtk.MessageDialog(self.window, Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR, Gtk.ButtonsType.OK,
'領票失敗,請重新驗證')
msgbox.format_secondary_text('{}\n若持續發生,請回報選務中心'.format(data['msg']))
self._updateStatus('領票程序結束 (失敗)')
msgbox.run()
msgbox.close()
self.onForgive(None)
# event handlers
def appQuit(self, *args):
Gtk.main_quit(*args)
def dialogLogin(self, *args):
dialog = self.get('login_dialog')
def makeMsgbox(msgPri, msgSec=''):
msgbox = Gtk.MessageDialog(dialog, Gtk.DialogFlags.MODAL,
Gtk.MessageType.ERROR, Gtk.ButtonsType.OK,
msgPri)
msgbox.format_secondary_text(msgSec)
msgbox.run()
msgbox.close()
def loginCallback(sess, err, resp):
GLib.idle_add(dialog.set_sensitive, True)
try:
data = resp.json()
print(data)
except:
GLib.idle_add(makeMsgbox,
'未預期的錯誤狀況', '請將以下文字回報選務中心:\n{}'.format(resp.text))
return
if data['ok']:
self._clientInfo = data['client']
self._entryCode = entryCode
GLib.idle_add(self.updateClientInfo)
with open(G_TOKEN_SAVE_PATH, 'w') as f:
f.write(entryCode)
# close the window (>0: success)
dialog.emit('response', 1)
else:
GLib.idle_add(makeMsgbox,
'認證失敗:{} ({})'.format(data['msg'], resp.status_code), '請再次確認授權碼')
dialog.set_sensitive(False)
entryCode = self.get('entry_code').get_text()
queryPing(entryCode, loginCallback)
def onStartReadCard(self, *args):
self.switchAuthMode(True)
if self.cardReader is None:
self.tryInitCardReader()
reader = self.cardReader
if reader is None:
self.get('status').set_text('讀卡失敗 QAQ')
return
try:
data = reader.readCard()
except CardReaderException as err:
self._updateStatus(err.__repr__())
self.get('status').set_text('讀卡失敗 QAQ')
raise
reader.beep(15)
text = data.value.decode('utf-8')
cardId, cardSerial = text[:9], text[9:11].strip()
self._card_sec = str(reader.last_snr) + '|' + repr(data.raw)
self.get('entry_cardid').set_text(cardId)
self._card_serial = cardSerial
def onStartBypass(self, *args):
self.switchAuthMode(False)
self.get('entry_cardid').grab_focus()
self._card_serial = None
def getVoterInfo(self, *args):
cardId = self.get('entry_cardid').get_text()
cardSerial = self._card_serial
if not len(cardId):
self.get('status').set_text('學號欄位為空')
return
self.get('status').set_text('驗證身份中')
self.get('entry_cardid').set_sensitive(False)
self.get('button_start_auth').set_sensitive(False)
reqObj = {
'token': self._entryCode,
'stuid': cardId,
'card_sec': self._card_sec
}
if cardSerial is None:
reqObj['bypass_serial'] = '1'
else:
reqObj['serial'] = cardSerial
req = queryQuery(reqObj, self.cbLoadVoterInfo, timeout=10)
def onForgive(self, *args):
stack = self.get('view_stack')
stack.set_visible_child(stack.get_children()[0])
self.switchAuthMode(None)
def onCommit(self, *args):
tx = self._tx
self._tx = None
self._updateStatus('送出領票請求...')
self.get('button_commit').set_sensitive(False)
self.get('button_forgive').set_sensitive(False)
queryCommit((self._entryCode, tx), self.cbLoadCommitResult, timeout=20)
if __name__ == '__main__':
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = Application()
app.run(sys.argv)
Gtk.main()
# if the main loop exits (i.e. closing the main window),
# give up all other threads
exit(0)