Sign.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from PyQt5.QtCore import QThread, pyqtSignal
  2. from helpers.xmlhandler import XMLHandler
  3. import os
  4. class Sign(QThread):
  5. status_bar_signal = pyqtSignal(str)
  6. sign_button_signal = pyqtSignal(bool)
  7. progress_bar_signal = pyqtSignal(bool)
  8. message_signal = pyqtSignal(tuple)
  9. def __init__(self, parent, data):
  10. super(Sign, self).__init__(parent)
  11. self.data = data
  12. def run(self):
  13. if 'file' in self.data and self.sign_file(self.data['file']):
  14. self.change_status('XML successfully signed.', 'Signing successful')
  15. elif 'directory' in self.data and self.sign_arrange_directory(self.data['directory']):
  16. self.change_status('XML successfully signed and files arranged.', 'Signing & arranging successful')
  17. def sign_file(self, path):
  18. try:
  19. xml_file = XMLHandler(path, self.data['config']['xmlreftype'])
  20. if not xml_file.valid(self.data['config']['xmlschema']):
  21. self.change_status('XML file does not comply schema.', 'XML file error', False)
  22. xml_file.sign(self.data['config']['certificate'], self.data['password'])
  23. return xml_file
  24. except BaseException as e:
  25. self.change_status(str(e), 'Signing error', False)
  26. return None
  27. def sign_arrange_directory(self, path):
  28. files = list()
  29. extensions = list()
  30. xml_path = None
  31. for file in os.listdir(path):
  32. filename, extension = os.path.splitext(file)
  33. extension = extension.lower()
  34. extensions.append(extension)
  35. if extension == '.xml':
  36. if xml_path is None:
  37. xml_path = os.path.join(path, file)
  38. else:
  39. break
  40. files.append((file, extension))
  41. if len(extensions) != len(set(extensions)):
  42. self.change_status('There are multiple files with same extension in directory.', 'Arranging error', False)
  43. return False
  44. elif xml_path is None:
  45. self.change_status('There is no XML file in directory.', 'Signing error', False)
  46. return False
  47. xml_file = self.sign_file(xml_path)
  48. if not xml_file:
  49. return False
  50. general_filename = xml_file.get_general_filename()
  51. for file, extension in files:
  52. try:
  53. os.rename(os.path.join(path, file), os.path.join(path, general_filename + extension))
  54. except:
  55. self.change_status('Something went wrong with arranging files.', 'Arranging error', False)
  56. return False
  57. return True
  58. def change_status(self, message, status_msg, success=True):
  59. self.message_signal.emit((message, success))
  60. self.status_bar_signal.emit(status_msg)
  61. self.progress_bar_signal.emit(False)
  62. self.sign_button_signal.emit(True)