def ifNotExCreate(directory): """ If does not exists dir, create it. @param directory: directory to check and create """ if (not os.path.exists(AppSettings.decodePath(directory))): # missing data dir logging.info("creating dir: '%s'", directory) os.makedirs(AppSettings.decodePath(directory))
def readFile(self, file_path): """ Read file binary. Return read data. @param file_path: path to file @return: on succes binary data, else None """ data = None f = None try: logging.info("reading file: %s", file_path) f = open(AppSettings.decodePath(file_path), "rb") data = f.read() logging.info("file size: %i", len(data)) except IOError as e: logging.exception(e) raise e except: # all other exceptions logging.exception("exception, file: %s", file_path) raise "exception, file: " + file_path finally: if (f): f.close() return data
def logIn(self): """ Read input lines and login user if possible. """ logging.debug("logging user ...") try: path = AppSettings.readDbFilePath() self.__db_ctrl.connectDB(path) login_ctrl = LoginController(self.__db_ctrl) username = AppSettings.USER_NAME master = str(self._passwd.text().toUtf8()) logged_user = login_ctrl.logInUser(username, master) if (logged_user): self.signalSuccessfullyLogged.emit(QtCore.QString.fromUtf8(username), QtCore.QString.fromUtf8(master)) self.close() else: # sleep for a while time.sleep(AppSettings.WRONG_PASWD_SLEEP) # show message QtGui.QMessageBox(QtGui.QMessageBox.Critical, tr("Wrong credentials!"), tr("Username or password are wrong.")).exec_() except Exception as e: InfoMsgBoxes.showErrorMsg(e)
def readImage(self, path): """ Reads image and prepare it for SQLite db. @param path: path to image @return: BLOB type """ img = None icon = None # open and read icon try: logging.debug("reading icon image from path: %s", path) img = open(AppSettings.decodePath(path), "rb") icon = img.read() icon = sqlite3.Binary(icon) except IOError as e: logging.exception(e) raise e finally: if img: img.close() return icon
def loadTranslation(lang): """ Load translation from file. """ f = None try: f = open(AppSettings.decodePath(AppSettings.TRANS_PATH + lang + AppSettings.TRANS_SUFFIX)) lines = f.readlines() tmp = {} for i in range(0, len(lines) - 1): if (i % 2 == 0): logging.info(lines[i]) # create key and value, remove last \n character and decode to utf8 key = str(lines[i][:len(lines[i]) - 1]).decode('utf-8') value = str(lines[i + 1][:len(lines[i + 1]) - 1]).decode('utf-8') logging.debug("key: '%s', value: '%s'", key, value) tmp[key] = value TRANSLATION[lang] = tmp except IOError as e: logging.exception(e) raise e finally: if (f): f.close
def selectDB(self): """ Select database file. """ dir_path = AppSettings.APP_ABS_ROOT + AppSettings.DEFAULT_DB file_path = QtGui.QFileDialog.getOpenFileName(self, tr("Select database"), QtCore.QString.fromUtf8(dir_path)) if (not file_path.isEmpty()): db_path = str(file_path.toUtf8()) logging.debug("database file path: %s", db_path) # write to setting file AppSettings.writeDbFilePath(db_path) self.enLogIn() else: logging.debug("database not selected")
def main(): app = QtGui.QApplication(sys.argv) logging.info("Absolute app root: '%s'", AppSettings.APP_ABS_ROOT) # set application icon app.setWindowIcon(QtGui.QIcon(AppSettings.APP_ICON_PATH)) # create neccessary paths if missing ifNotExCreate(AppSettings.TMP_PATH) ifNotExCreate(AppSettings.BACKUP_PATH) ifNotExCreate(AppSettings.DATA_PATH) ifNotExCreate(AppSettings.DB_PATH) ifNotExCreate(AppSettings.ICONS_PATH) # preapare languages AppSettings.writeLanguage("sk") AppSettings.LANG = AppSettings.readLanguage() TransController.loadTranslation("sk") TransController.loadTranslation("en") # DB controller instance db_con = DbController() # login dialog instance login_dialog = LoginDialog(db_con) db_path = AppSettings.readDbFilePath() logging.info("DB path: '%s'", db_path) if (not os.path.exists(AppSettings.decodePath(db_path))): # if default DB file doesnt exists, run create DB dialog login_dialog.enLogIn(False) else: # leave only last 10 backups backups = sorted(os.listdir(AppSettings.BACKUP_PATH), reverse=True) if len(backups) >= 10: for i in range(9, len(backups)): os.remove(AppSettings.BACKUP_PATH + backups[i]) # first backup database backup_file = AppSettings.BACKUP_PATH + time.strftime("%Y-%m-%dT%H:%M:%S_", time.localtime()) + os.path.basename(db_path) logging.info("backup file: '%s'", backup_file) shutil.copyfile(AppSettings.decodePath(db_path), AppSettings.decodePath(backup_file)) login_dialog.show() w = MainWindow(db_con) # when succesfully logged load main window login_dialog.signalSuccessfullyLogged.connect(w.setUserReloadShow) sys.exit(app.exec_())
def createDB(self): """ Create DB file and new user with master password. """ db_path = str(self._db_file_path.text().toUtf8()) logging.debug("creating new DB: '%s'", db_path) # write to setting file AppSettings.writeDbFilePath(db_path) self.__db_ctrl.connectDB(db_path) self.__db_ctrl.createTables() self.__db_ctrl.insertDefRows() logging.debug("inserting user to DB: '%s'", AppSettings.USER_NAME) master = str(self._passwd.text().toUtf8()) user = UserController(self.__db_ctrl) user.insertUser(AppSettings.USER_NAME, master) self.signalDbCreated.emit() self.close()
def closeEvent(self, event): """ Do matters on close event. In example delete clipboard. """ logging.debug("deleting clipboard") QtGui.QApplication.clipboard().clear() try: logging.info("removing tmp dir: '%s'", AppSettings.TMP_PATH) # remove tmp files shutil.rmtree(AppSettings.decodePath(AppSettings.TMP_PATH)) except Exception as e: logging.exception(e) InfoMsgBoxes.showErrorMsg(e)
def writeFile(self, file_path): """ Write file to disk. @param file_path: file to write """ f = None try: f = open(AppSettings.decodePath(file_path), "wb") f.write(self._attachment_data) except IOError as e: logging.exception(e) raise e except: logging.exception("exception writting file: %s", file_path) raise e finally: if (f): f.close()
def _ui_initial_list(self): appsettings = AppSettings() if appsettings.Data["repository"] == "inmemory": self._serviceStudents.create_init_studs() self._serviceDisciplines.create_init_discs() self._serviceGrades.create_init_grades()
@author: flavi ''' from validare.validatoare import ValidatorStudent, ValidatorDiscipline, ValidatorGrade from infrastructure.repos import Repo from business.services import ServiceStudents, ServiceDisciplines, ServiceGrades from presentation.ui import Console from business.services import ServiceUndo from AppSettings import * from infrastructure.RepoTextFile import StudentTextFileRepo, DisciplineTextFileRepo, GradesTextFileRepo from infrastructure.RepoBinaryFile import BinaryFileRepo from infrastructure.JSONFile import JSONRepo validatorStudent = ValidatorStudent() validatorDiscipline = ValidatorDiscipline() validatorGrade = ValidatorGrade() appsettings = AppSettings() if appsettings.Data["repository"] == "inmemory": repoStudents = Repo() repoDisciplines = Repo() repoGrades = Repo() elif appsettings.Data["repository"] == "textfiles": repoStudents = StudentTextFileRepo(appsettings.Data["student"]) repoDisciplines = DisciplineTextFileRepo(appsettings.Data["discipline"]) repoGrades = GradesTextFileRepo(appsettings.Data["grade"]) elif appsettings.Data["repository"] == "binaryfile": repoStudents = BinaryFileRepo(appsettings.Data["student"]) repoDisciplines = BinaryFileRepo(appsettings.Data["discipline"]) repoGrades = BinaryFileRepo(appsettings.Data["grade"]) elif appsettings.Data["repository"] == "json": repoStudents = JSONRepo(appsettings.Data["student"]) repoDisciplines = JSONRepo(appsettings.Data["discipline"])
def initUI(self): """ Initialize UI components. """ self.setWindowTitle(tr("Log in: ") + QtCore.QString.fromUtf8(os.path.basename(AppSettings.readDbFilePath()))) self.setFixedSize(500, 100) # create main grid layout layout_gl = QtGui.QGridLayout() self.setLayout(layout_gl) # labels # username_label = QtGui.QLabel("<b>" + tr("Username:"******"</b>") passwd_label = QtGui.QLabel("<b>" + tr("Password:"******"</b>") # add to layout # layout_gl.addWidget(username_label, 0, 0) layout_gl.addWidget(passwd_label, 0, 0) # self._username = QtGui.QLineEdit() # layout_gl.addWidget(self._username, 0, 1) self._passwd = QtGui.QLineEdit() # hide password self._passwd.setEchoMode(QtGui.QLineEdit.Password) # password layout passwd_hl = QtGui.QHBoxLayout() # add password edit line to layout passwd_hl.addWidget(self._passwd) # password visibility check box self._show_passwd_check = QtGui.QCheckBox(tr("Show")) self._show_passwd_check.setChecked(False) passwd_hl.addWidget(self._show_passwd_check) layout_gl.addLayout(passwd_hl, 0, 1) # create buttons self._button_box = QtGui.QDialogButtonBox() self.__login_button = QtGui.QPushButton(tr("&Log In")) self.__login_button.setEnabled(False) self.__close_button = QtGui.QPushButton(tr("&Close")) self._button_box.addButton(self.__login_button, QtGui.QDialogButtonBox.AcceptRole) self._button_box.addButton(self.__close_button, QtGui.QDialogButtonBox.RejectRole) # layout_gl.addWidget(self._button_box, 1, 1) # db button layout db_buttons_hl = QtGui.QHBoxLayout() self.__open_db = QtGui.QPushButton(tr("Open Database")) self.__create_db = QtGui.QPushButton(tr("Create Database")) db_buttons_hl.addWidget(self.__open_db) db_buttons_hl.addWidget(self.__create_db) db_buttons_hl.addWidget(self._button_box) layout_gl.addLayout(db_buttons_hl, 1, 0, 1, 2)
def enLogIn(self, b = True): """ Enable or disable password input, show checkbox and login button. """ logging.debug("enabling login: %s", b) self._passwd.setEnabled(b) self._show_passwd_check.setEnabled(b) self.__login_button.setEnabled(b) if (not b): self.setWindowTitle(tr("Database not selected.")) else: self.setWindowTitle(tr("Log in: ") + QtCore.QString.fromUtf8(os.path.basename(AppSettings.readDbFilePath())))