-
Notifications
You must be signed in to change notification settings - Fork 0
/
GlpiClient.py
3035 lines (2284 loc) · 116 KB
/
GlpiClient.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
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
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# MODULES
from vars import *
from functions import *
import requests
import json
import base64
import os
from os import listdir
from os.path import isfile,join
import glob
import sys
import shutil
from distutils.dir_util import copy_tree
import logging
import random
import string
import ntpath
from time import strftime
import wget
import markdownify
#PIC ATTACH CODE
#doesn't work on winXP
from PIL import ImageGrab
from PyQt5.QtWidgets import QWidget, QSystemTrayIcon, QAction, QMenu, QLabel, QLineEdit, QCheckBox, QPushButton, \
QGridLayout, QMainWindow, QDesktopWidget, QTableWidget, QDateTimeEdit, QAbstractItemView, QTableWidgetItem, \
QAbstractScrollArea, QHeaderView, QMessageBox, QPlainTextEdit, QApplication, QFileDialog, QComboBox, QVBoxLayout
from PyQt5.QtCore import Qt, QCoreApplication, QTimer, QDate
from PyQt5.QtGui import QIcon, QFont, QPixmap, QWindow
# spinner module (from file "waitingspinnerwidget.py")
from waitingspinnerwidget import QtWaitingSpinner
# check if app already running (from file "singleinstance.py")
#from singleinstance import singleinstance
from sys import exit
# APP START
# gettext multilang init
_ = translate.gettext
translate.install()
# get client app ip and hostname
clientIp = clientIpGet()
clientHostname = clientHostnameGet()
# singleinstance var (for single app run check)
myAppAlreadyRunning = singleinstance()
# NOT FOR WinXP
# # enc
# def encrypt(message: bytes, key: bytes) -> bytes:
# return Fernet(key).encrypt(message)
#
# # decr
# def decrypt(token: bytes, key: bytes) -> bytes:
# return Fernet(key).decrypt(token)
# debug
print("Client IP: " + str(clientIp))
print("Client Hostname: " + str(clientHostname))
# check if auth.ini exists
if os.path.exists(configAuthPath):
print(_("auth.ini exists!"))
# if auth.ini exists
if os.path.isfile(configAuthPath):
print(_("auth.ini is a file!"))
else:
print(_("auth.ini is a directory! delete directory auth.ini"))
shutil.rmtree(configAuthPath)
print(_("Create auth.ini"))
# create auth.ini
content = ["[auth]", "checkboxrememberloginchecked = 1"]
file = open(configAuthPath, "w")
for index in content:
file.write(index + '\n')
file.close()
# if auth.ini DOESN'T exist
else:
print("auth.ini doesn't exist! create auth.ini")
# create auth.ini
content = ["[auth]", "checkboxrememberloginchecked = 1"]
file = open(configAuthPath, "w")
for index in content:
file.write(index + '\n')
file.close()
# auth.ini read
configAuth = configparser.ConfigParser()
configAuth.read(configAuthPath, encoding="utf8")
# # debug show sessionToken
# def show(event):
# print(sessionToken)
# AUTH WIN
class AuthWin(QWidget):
def __init__(self):
super().__init__()
self.AuthWinInitUI()
def onTrayIconActivated(self, reason):
self.activateWindow()
self.show()
self.setWindowState(Qt.WindowNoState)
# if reason == 1:
# print("onTrayIconActivated:", reason)
# self.activateWindow()
# self.show()
#
# if reason == 2 or 3:
# print("onTrayIconActivated:", reason)
# self.activateWindow()
# self.show()
# def disambiguateTimerTimeout(self):
# print("Tray icon single clicked")
# method initUI create GUI
def AuthWinInitUI(self):
super().__init__()
# create authwin
self.setFixedSize(450, 250)
self.center()
self.setWindowTitle(appName)
self.setWindowIcon(QIcon('img/ico.png'))
# check if another instance of the same program running
if myAppAlreadyRunning.alreadyrunning():
# if checked checkbox hideAppWindowToTrayOnClose(1) in config file
# MessageBox "The program is already running"
if hideAppWindowToTrayOnClose == "1":
print("Another instance of this program is already running")
QMessageBox.about(self, appName, _("The program is already running"))
exit(0)
# if checked checkbox hideAppWindowToTrayOnClose(0) in config file
# maximize app from panel
if hideAppWindowToTrayOnClose == "0":
w = WindowMgr()
w.find_window_wildcard("GlpiClient")
w.set_foreground()
exit(0)
# no app running, safe to continue...
print("No another instance is running, can continue here")
self.activateWindow()
# init QSystemTrayIcon
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(QIcon("img\ico.png"))
self.tray_icon.setToolTip(appName)
settings_action = QAction(_("Settings"), self)
settings_action.triggered.connect(self.settingsWinShow)
about_action = QAction(_("About..."), self)
about_action.triggered.connect(self.aboutWinShow)
quit_action = QAction(_("Quit"), self)
quit_action.triggered.connect(self.appClose)
tray_menu = QMenu()
tray_menu.addAction(settings_action)
tray_menu.addAction(about_action)
tray_menu.addAction(quit_action)
self.tray_icon.setContextMenu(tray_menu)
self.tray_icon.show()
self.tray_icon.activated.connect(self.onTrayIconActivated)
# head label
authHeadLabel = QLabel(self)
authHeadLabel.setText(_("Authorization"))
# head font
authHeadLabelFont = QFont("Arial", 16, QFont.Bold)
authHeadLabel.setFont(authHeadLabelFont)
# get checkbox REMEMBER LOGIN status
checkboxRememberLoginChecked = configAuth.get("auth", "checkboxrememberloginchecked")
# login label create
loginLabel = QLabel(self)
loginLabel.setText(_("Login"))
# login entry create
self.loginEntry = QLineEdit(self)
try:
# read login from config file
self.loginEntry.setText(configAuth.get("auth", "login"))
except Exception:
print(_("Login doesn't exist in auth.ini"))
self.loginEntry.setText("")
pass
# pass label create
passLabel = QLabel(self)
passLabel.setText(_("Password"))
# pass entry create
self.passEntry = QLineEdit(self)
self.passEntry.setEchoMode(QLineEdit.Password)
try:
# NOT FOR WinXP
# # get ENC PASS from config & decr it
# userPassDecr = decrypt((bytes(configAuth.get("auth", "password"), "utf-8")), encKey).decode()
#
# # set decr pass to pass entry
# self.passEntry.setText(userPassDecr)
# get pass from config
userPass = configAuth.get("auth", "password")
# put password to window filled
self.passEntry.setText(userPass)
except Exception:
print(_("Password doesn't exist in auth.ini"))
self.passEntry.setText("")
pass
# add checkbox REMEMBER LOGIN
self.checkboxRememberLogin = QCheckBox(_("Remember Login and Password"), self)
# if checked checkbox REMEMBER LOGIN IS TRUE(1) in config file
if checkboxRememberLoginChecked == "1":
# check checkboxRememberLogin
self.checkboxRememberLogin.setChecked(True)
if checkboxRememberLoginChecked == "0":
# UNcheck checkboxRememberLogin
self.checkboxRememberLogin.setChecked(False)
# auth error label
self.authErrorLabel = QLabel(self)
self.authErrorLabel.setText('')
self.authErrorLabel.setStyleSheet('color: red')
# login button create
self.loginButton = QPushButton(_("Sign in"), self)
self.loginButton.setFixedSize(150, 30)
self.loginButton.clicked.connect(self.auth)
# create grid of widgets
grid = QGridLayout()
grid.setSpacing(10)
# auth label
grid.addWidget(authHeadLabel, 0, 0, 1, 4)
authHeadLabel.setAlignment(Qt.AlignCenter)
authHeadLabel.setMinimumHeight(80)
grid.addWidget(loginLabel, 1, 1)
loginLabel.setAlignment(Qt.AlignCenter)
grid.addWidget(self.loginEntry, 1, 2)
self.loginEntry.setMaximumWidth(150)
grid.addWidget(passLabel, 2, 1)
passLabel.setAlignment(Qt.AlignCenter)
grid.addWidget(self.passEntry, 2, 2)
self.passEntry.setMaximumWidth(150)
grid.addWidget(self.checkboxRememberLogin, 3, 0, 1, 4, alignment=Qt.AlignCenter)
grid.addWidget(self.authErrorLabel, 4, 0, 1, 4)
self.authErrorLabel.setAlignment(Qt.AlignCenter)
grid.addWidget(self.loginButton, 5, 1, 2, 2, alignment=Qt.AlignCenter)
self.setLayout(grid)
# show mainwin
self.show()
# if checked checkbox hideAppWindowToTrayAtStartup(1) in config file
if hideAppWindowToTrayAtStartup == "1":
# hide (minimize) appWindow to tray at startup
if hideAppWindowToTrayOnClose == "1":
self.hide()
# minimize window to windows panel
if hideAppWindowToTrayOnClose == "0":
self.setWindowState(self.windowState() | QWindow.Minimized)
def center(self):
qr = self.frameGeometry()
cp = QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
# auth
def auth(self):
# global vars are visible in all parts of code
global sessionToken
global userName
global userFirstname
global userRealname
global userId
# gui auth - get vars from entries
userLogin = self.loginEntry.text()
userPass = self.passEntry.text()
# debug
print(userLogin)
print(userPass)
# create crypt phrase of logg+pass for Basic Auth
loginPassPairString = (userLogin + ':' + userPass)
loginPassPairBytes = loginPassPairString.encode("utf-8")
encLoginPassPair = base64.b64encode(loginPassPairBytes)
# convert loginPassPairBytes to Str
encLoginPassPair = encLoginPassPair.decode("utf-8")
# debug
# print(encLoginPassPair)
#####
## INIT SESSION, GET sessionToken
#####
# request headers sessionInit over crypt log/pass
headersSession = {'Content-Type': 'application/json',
'Authorization': 'Basic ' + encLoginPassPair,
'App-Token': appToken,
}
# request headers sessionInit over crypt userToken
# headersSession = {'Content-Type': 'application/json',
# 'Authorization': 'user_token ' + userToken,
# 'App-Token': appToken,
# }
# try login to server
try:
# request session init
responseSessionInit = requests.get(glpiApiBaseUrl + '/initSession', headers=headersSession)
# write to var all json with sessionToken
# pycharm 2018 x32 python 3.4
sessionTokenJson = responseSessionInit.json()
# pycharm 2019 x64 python 3.7
#sessionTokenJson = json.loads(responseSessionInit.content)
# debug
print(type(sessionTokenJson).__name__)
# check if sessionTokenJson correct type DICT or not
if not (type(sessionTokenJson).__name__ == 'dict'):
print(_("sessionTokenJson is NOT correct"))
self.authErrorLabel.setText(_("Auth error"))
# if json not DICT - exit func
return
# if json is DICT - go on auth
else:
print(_("sessionTokenJson is correct"))
# debug
print(sessionTokenJson)
# get sessionToken from json with sessionToken
sessionToken = sessionTokenJson['session_token']
# check if sessionTokenJson empty or not
if not sessionToken:
print(_("Auth error. 'session_token' not found"))
else:
print(_("Auth success. 'session_token' found"))
# debug
print(sessionToken)
# if checkbox REMEMBER LOGIN is checked - write login to config file
if self.checkboxRememberLogin.isChecked():
# enc pass
#userPassEnc = encrypt(userPass.encode(), encKey)
# remember user login & enc pass in config file
configAuth.set("auth", "login", userLogin)
configAuth.set("auth", "password", userPass)
configAuth.set("auth", "checkboxrememberloginchecked", "1")
# NOT FOR WinXP
#configAuth.set("auth", "password", str(userPass, "utf-8"))
# write configAuth file
with open(configAuthPath, "w", encoding="utf-8") as config_file:
configAuth.write(config_file)
# if checkbox REMEMBER LOGIN is UNchecked - remove login from config file
else:
# REMOVE user login from config file
configAuth.set("auth", "login", "")
configAuth.set("auth", "password", "")
configAuth.set("auth", "checkboxrememberloginchecked", "0")
# write configAuth file
with open(configAuthPath, "w", encoding="utf-8") as config_file:
configAuth.write(config_file)
# get user data
# get userName from gui entry
userName = userLogin
print(userName)
# request headers
headersGet = {'Content-Type': 'application/json',
'Session-Token': sessionToken,
'App-Token': appToken,
}
# GET FULLSESSION (all auth user's vars)
# request fullsession
responseFullsessionGet = requests.get(glpiApiBaseUrl + '/getFullSession', headers=headersGet)
# write to var all json-fullsession
# pycharm 2018 x32 python 3.4
fullsessionJson = responseFullsessionGet.json()
# pycharm 2019 x64 python 3.7
#fullsessionJson = json.loads(responseFullsessionGet.content)
# debug
print(fullsessionJson)
# get user's firstname and secondname
userFirstname = fullsessionJson['session']['glpifirstname']
userRealname = fullsessionJson['session']['glpirealname']
userId = fullsessionJson['session']['glpiID']
print('\r')
print(userFirstname, userRealname)
# hide autwin, show mainwin
self.destroy()
self.exec_ = MainWin()
self.tray_icon.hide()
# pass if no connection to server
except Exception as e:
self.authErrorLabel.setText(_("Connection error"))
logging.error('Error at %s', 'division', exc_info=e)
pass
# exit with filled vars
return sessionToken, headersSession, userName, userFirstname, userRealname # authStatusLabel
# press Enter to auth
def keyPressEvent(self, event):
key = event.key()
if key == Qt.Key_Enter or key == Qt.Key_Return:
self.auth()
def closeEvent(self, event):
event.ignore()
# HIDE (MINIMIZE) APP TO TRAY ON CLOSE
# if checked checkbox hideAppWindowToTrayOnClose(1) in config file
if hideAppWindowToTrayOnClose == "1":
self.hide()
self.tray_icon.showMessage(
appName,
appName + " " + "is minimized to the system tray",
#QSystemTrayIcon.Information,
2000
)
# minimize window to windows panel
if hideAppWindowToTrayOnClose == "0":
self.setWindowState(self.windowState() | QWindow.Minimized)
# about button
def aboutWinShow(self):
self.exec_ = AboutWin()
# settings button
def settingsWinShow(self):
self.exec_ = SettingsWin()
# app close func
def appClose(self):
self.tray_icon.hide()
QCoreApplication.instance().quit()
# debug
print(sessionToken)
# if session token EXISTS
#if not sessionToken or adminSessionToken is None:
# sessionKillCommon()
# kill session common func
sessionKillCommon()
# main win
class MainWin(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
# update app
def appUpdate(self):
# spinner = QtWaitingSpinner(self, True, True, Qt.ApplicationModal)
# spinner.start() # starts spinning
# self.statusbar.showMessage('Программа обновляется. Это займет несколько секунд...')
#
# transport = paramiko.Transport((sftpServerHost, int(sftpServerPort)))
# transport.connect(username=sftpServerUser, password=sftpServerPass)
#
# sftp = paramiko.SFTPClient.from_transport(transport)
# sftp.get(sftpServerRootPath + "glpiClient/glpiClient.exe", "update/glpiClient.exe")
#
# sftp.close()
#
# self.statusbar.showMessage('')
# spinner.stop()
#
# # close app after update
# sessionKillCommon()
# subprocess.call([r'updater.cmd'])
if os.path.exists(updateDirPath):
# print("Update exists!")
if os.path.isfile(updateDirPath):
# print("Update is not a directory! Remove file Update")
os.remove(updateDirPath, dir_fd=None)
else:
# print("Update is a directory! Remove directory Update")
shutil.rmtree(updateDirPath)
# print("Create directory Update")
os.mkdir(updateDirPath, mode=0o777, dir_fd=None)
else:
# print("Update DOESN'T exist! Create directory Update")
os.mkdir(updateDirPath, mode=0o777, dir_fd=None)
if os.path.exists(updateAppDirPath):
# print("./update/HelpdeskClient exists!")
if os.path.isfile(updateAppDirPath):
# print("./update/HelpdeskClient is not a directory! Remove file ./update/HelpdeskClient")
os.remove(updateAppDirPath, dir_fd=None)
else:
# print("./update/HelpdeskClient is a directory! Remove directory ./update/HelpdeskClient")
shutil.rmtree(updateAppDirPath)
# print("Create directory ./update/HelpdeskClient")
os.mkdir(updateAppDirPath, mode=0o777, dir_fd=None)
else:
# print("./update/HelpdeskClient DOESN'T exist! Create directory ./update/HelpdeskClient")
os.mkdir(updateAppDirPath, mode=0o777, dir_fd=None)
if os.path.exists(updateConfigDirPath):
# print("config exists!")
if os.path.isfile(updateConfigDirPath):
# print("config is not a directory! Remove file config")
os.remove(updateConfigDirPath, dir_fd=None)
else:
# print("config is a directory! Remove directory config")
shutil.rmtree(updateConfigDirPath)
# print("Create directory config")
os.mkdir(updateConfigDirPath, mode=0o777, dir_fd=None)
else:
# print("config DOESN'T exist! Create directory config")
os.mkdir(updateConfigDirPath, mode=0o777, dir_fd=None)
try:
# update updater from ftp
wget.download(
"ftp://" + ftpServerUser + ":" + ftpServerPass + "@" + ftpServerHost + ":" + ftpServerPort + ftpPath + appDirName + "/" + updaterExeFile,
out=updateAppDirPath)
# update config from ftp
wget.download(
"ftp://" + ftpServerUser + ":" + ftpServerPass + "@" + ftpServerHost + ":" + ftpServerPort + ftpPath + appDirName + "/config/" + configFileName,
out=updateConfigDirPath)
# kill session
sessionKillCommon()
try:
copy_tree(updateAppDirPath, "")
except Exception as e:
print(_("Failed to download an update"))
QMessageBox.about(self, appName, _("Failed to download an update"))
logging.error('Error at %s', 'division', exc_info=e)
# start updater
os.startfile(updaterExeFile)
# close main app
self.appClose()
except Exception as e:
print(_("Failed to download an update"))
QMessageBox.about(self, appName, _("Failed to download an update"))
logging.error('Error at %s', 'division', exc_info=e)
# close main app
self.appClose()
# TIMER RUNNING IN BACKGROUND
def Time(self):
# debug TICKS OUTPUT IN CONSOLE EVERY SECONDS - IT'S ANNOYING
#print(strftime("%H" + ":" + "%M" + ":" + "%S"))
# # check update every hour & update if there's new version
# if strftime("%M" + ":" + "%S") == "00:00":
# print("HOUR!")
# appVersionCheck()
# if updateMode == 1:
# self.appUpdate()
# LOGOUT at 00:00:00
if strftime("%H" + ":" + "%M" + ":" + "%S") == "00:00:00" or \
strftime("%H" + ":" + "%M" + ":" + "%S") == "00:00:01" or \
strftime("%H" + ":" + "%M" + ":" + "%S") == "00:00:02":
print("MIDNIGHT!")
self.sessionKill()
def onTrayIconActivated(self, reason):
self.activateWindow()
self.show()
self.setWindowState(Qt.WindowNoState)
# if reason == 1:
# print("onTrayIconActivated:", reason)
# self.activateWindow()
# self.show()
#
# if reason == 2 or 3:
# print("onTrayIconActivated:", reason)
# self.activateWindow()
# self.show()
def initUI(self):
QMainWindow.__init__(self)
# check actual app version
appVersionActual = appVersionCheck()
# remoteUpdateMarkerCheck
remoteUpdateMarker = remoteUpdateMarkerCheck()
global updateMode
# if there's new version and remoteUpdateMarker = 1 - enter updateMode
if (float(appVersionActual) > float(appVersion)) and int(remoteUpdateMarker) == 1:
updateMode = 1
else:
updateMode = 0
# debug
print("updateMode: " + str(updateMode))
print("appAutoUpdate: " + str(appAutoUpdate))
self.timer = QTimer(self)
self.timer.timeout.connect(self.Time)
self.timer.start(1000)
# init QSystemTrayIcon
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(QIcon("img\ico.png"))
# popup on trayicon hover
self.tray_icon.setToolTip(appName)
settings_action = QAction(_("Settings"), self)
settings_action.triggered.connect(self.settingsWinShow)
about_action = QAction(_("About..."), self)
about_action.triggered.connect(self.aboutWinShow)
quit_action = QAction(_("Quit"), self)
quit_action.triggered.connect(self.appClose)
tray_menu = QMenu()
tray_menu.addAction(settings_action)
tray_menu.addAction(about_action)
tray_menu.addAction(quit_action)
self.tray_icon.setContextMenu(tray_menu)
self.tray_icon.show()
self.tray_icon.activated.connect(self.onTrayIconActivated)
# create mainwin
# disable resize win
#self.setFixedSize(900, 700)
# enable resize win
self.setMinimumSize(700, 450)
self.center()
self.setWindowTitle(appName)
self.setWindowIcon(QIcon('img\ico.png'))
# status bar
self.statusbar = self.statusBar()
self.statusbar.setStyleSheet("QStatusBar{padding:8px;background:rgba(0,0,0,0);color:black;font-weight:bold;}")
self.statusbar.showMessage('')
# CENTRAL WIDGET
# self.setMinimumSize(QSize(480, 80)) # set window ышяу - disable windows expand
# self.setWindowTitle("Работа с QTableWidget") # set window header
central_widget = QWidget(self) # create central widget
self.setCentralWidget(central_widget) # set central widget
# create QGridLayout
grid_layout = QGridLayout()
grid_layout.setSpacing(10)
central_widget.setLayout(grid_layout)
# login label create
userNameLabel = QLabel(self)
userNameLabel.setText(
userFirstname + ' ' + userRealname + ' ' + '(' + userName + ')')
# logout button create
self.logoutButton = QPushButton(_("Sign out"), self)
self.logoutButton.setFixedSize(80, 30)
self.logoutButton.clicked.connect(self.sessionKill)
# add ticket button
self.ticketAddButton = QPushButton(_("Create new ticket"), self)
self.ticketAddButton.setFixedSize(250, 30)
self.ticketAddButton.clicked.connect(self.addTicketWinShow)
# mytickets head label
myticketsHeadLabel = QLabel(self)
myticketsHeadLabel.setText(_("My tickets"))
# head font
myticketsHeadLabelFont = QFont("Arial", 16, QFont.Bold)
myticketsHeadLabel.setFont(myticketsHeadLabelFont)
# add checkbox OPENTICKETS
self.checkboxTicketsOpen = QCheckBox(_("Open tickets only"), self)
self.checkboxTicketsOpen.setChecked(True)
# label FROM
self.myticketsDateFromLabel = QLabel(self)
self.myticketsDateFromLabel.setText(_("From"))
# DATEFROM widget
self.dateFromWidget = QDateTimeEdit(QDate.currentDate().addMonths(-3), self)
self.dateFromWidget.setCalendarPopup(True)
self.dateFromWidget.setMinimumDate(QDate(1970, 1, 1))
self.dateFromWidget.setMaximumDate(QDate(2099, 12, 31))
self.dateFromWidget.setDisplayFormat("yyyy-MM-dd")
def getDateFrom():
global dateFromStr
dateFrom = self.dateFromWidget.date()
dateFromStr = str(dateFrom.toPyDate())
print(type(dateFromStr))
print(dateFromStr)
# debug
# # A push button
# btn_get = QPushButton("Get Date From", self)
# btn_get.move(100, 250)
# btn_get.clicked.connect(getDateFrom)
# label TO
self.myticketsDateToLabel = QLabel(self)
self.myticketsDateToLabel.setText(_("To"))
# DATETO widget
self.dateToWidget = QDateTimeEdit(QDate.currentDate(), self)
self.dateToWidget.setCalendarPopup(True)
self.dateToWidget.setMinimumDate(QDate(1970, 1, 1))
self.dateToWidget.setMaximumDate(QDate(2099, 12, 31))
self.dateToWidget.setDisplayFormat("yyyy-MM-dd")
# DATETO func
def getDateTo():
global dateToStr
dateTo = self.dateToWidget.date()
dateToStr = str(dateTo.toPyDate())
print(type(dateToStr))
print(dateToStr)
# debug
# # A push button
# btn_get = QPushButton("Get Date To", self)
# btn_get.move(100, 450)
# btn_get.clicked.connect(getDateTo)
# # add DATEFROM button
# self.ticketDateFromButton = QPushButton('...', self)
# self.ticketDateFromButton.setFixedSize(30, 30)
# self.ticketDateFromButton.clicked.connect(self.calendarShow)
################
# GET tickets list
def getTicketsList():
# if update mode ON - update app on ticket list renew
if updateMode == 1 and appAutoUpdate == "1":
self.appUpdate()
spinner = QtWaitingSpinner(self, True, True, Qt.ApplicationModal)
spinner.start() # starts spinning
#self.exec_ = SpinnerWin()
self.statusbar.showMessage(_("Loading..."))
# get date from & to
getDateFrom()
getDateTo()
# debug
print("dateFrom: " + dateFromStr)
print("dateTo: " + dateToStr)
# if checked checkbox OPENTICKETS show only UNRESOLVED tickets
if self.checkboxTicketsOpen.isChecked():
ticketSearchStatus = "notold"
# if UNchecked checkbox OPENTICKETS show ALL tickets
else:
ticketSearchStatus = "all"
# request headers
headersGet = {'Content-Type': 'application/json',
'Session-Token': sessionToken,
'App-Token': appToken,
}
# request
responseMyTicketsGet = requests.get(
glpiApiBaseUrl + '/search/Ticket?'
'is_deleted=0&'
'as_map=0&'
'range=0-999999&'
'criteria[0][field]=12&criteria[0][searchtype]=equals&criteria[0][value]=' + ticketSearchStatus + '&'
'criteria[6][link]=AND&'
#'criteria[2][field]=15&criteria[2][searchtype]=morethan&_select_criteria[2][value]=0&_criteria[2][value]=2019-06-06+00%3A00&criteria[2][value]=2019-06-06+00%3A00&'
'criteria[2][field]=15&criteria[2][searchtype]=morethan&_select_criteria[2][value]=0&_criteria[2][value]=' + dateFromStr + '+00%3A00&criteria[2][value]=' + dateFromStr + '+00%3A00&'
'criteria[6][link]=AND&'
'criteria[7][field]=15&criteria[7][searchtype]=lessthan&_select_criteria[7][value]=0&_criteria[7][value]=' + dateToStr + '+23%3A59&criteria[7][value]=' + dateToStr + '+23%3A59&'
'criteria[6][link]=AND&'
'criteria[6][field]=22&criteria[6][searchtype]=equals&criteria[6][value]=' + str(userId),
headers=headersGet)
# debug
# print(responseMyTicketsGet)
# pycharm 2018 x32 python 3.4
myTicketsListJson = responseMyTicketsGet.json()
# debug
print(myTicketsListJson)
print(type(myTicketsListJson))
# if success getting json dict with user's tickets
if type(myTicketsListJson).__name__ == 'dict':
# if user have 0 tickets
if myTicketsListJson['totalcount'] == 0:
print(_("You have no tickets"))
# TABLE WITH NO TICKETS
table = QTableWidget(self)
table.setColumnCount(1)
header = table.horizontalHeader()
header.setStretchLastSection(True)
# set table's headers
table.setHorizontalHeaderLabels([_("Tickets not found")])
# set header's alignment
table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)
# if a user has >0 tickets
if myTicketsListJson['totalcount'] > 0:
myTicketsList = myTicketsListJson['data']
myTicketsCount = len(myTicketsList)
# debug
print(userId)
################
################
# TABLE OF TICKETS
table = QTableWidget(self) # create table
table.setColumnCount(4) # set quantity of columns
table.setRowCount(myTicketsCount) # and one string in table
table.setEditTriggers(QTableWidget.NoEditTriggers) # disable edit cells
table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) # smooth scroll
table.setSelectionBehavior(QTableWidget.SelectRows) # select full row instead of one cell
table.verticalHeader().setVisible(False) # hide vertical headers (number of row)
# headers of table style
table.horizontalHeader().setStyleSheet("""
QHeaderView::section {padding: 8px; background-color: lightgrey; border: 1px; }
""")
header = table.horizontalHeader()
# SORT BY TABLE HEADER CLICK
table.setSortingEnabled(True)
# stretch last column
#header.setStretchLastSection(True)
# resize width of ALL columns to content
#header.setSectionResizeMode(QHeaderView.ResizeToContents)
# headers of table
itemTableHeaderId = QTableWidgetItem('ID')
#itemTableHeaderId.setBackground(QColor(255, 255, 0))
itemTableHeaderId.setToolTip(_("Ticket ID"))
itemTableHeaderId.setFont(QFont("Arial", 10, QFont.Bold))
table.setHorizontalHeaderItem(0, itemTableHeaderId)
header.setSectionResizeMode(0, QHeaderView.ResizeToContents) # resize column to contents
itemTableHeaderCreateDate = QTableWidgetItem(_("Creation date"))
itemTableHeaderCreateDate.setToolTip(_("Ticket creation date and time"))
table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)
itemTableHeaderCreateDate.setFont(QFont("Arial", 10, QFont.Bold))
table.setHorizontalHeaderItem(1, itemTableHeaderCreateDate)
header.setSectionResizeMode(1, QHeaderView.ResizeToContents) # resize column to contents
itemTableHeaderName = QTableWidgetItem(_("Name"))
#itemTableHeaderName.ResizeToContents
itemTableHeaderName.setToolTip(_("Ticket name"))
itemTableHeaderName.setFont(QFont("Arial", 10, QFont.Bold))
table.setHorizontalHeaderItem(2, itemTableHeaderName)
header.setSectionResizeMode(2, QHeaderView.Stretch) # stretch column
itemTableHeaderStatus = QTableWidgetItem(_("Status"))
itemTableHeaderStatus.setToolTip(_("Ticket status"))
itemTableHeaderStatus.setFont(QFont("Arial", 10, QFont.Bold))
table.setHorizontalHeaderItem(3, itemTableHeaderStatus)
header.setSectionResizeMode(3, QHeaderView.ResizeToContents) # resize column to contents
# fill table with mytickets
for myTicketJson in range(myTicketsCount):
myTicket = (myTicketsList[myTicketJson])
# ticket id
myTicketId = myTicket['2']
# ticket name
myTicketName = myTicket['1']
# ticket create date