From ab116db66cd56818db92d7b54dc22ecaefba0565 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Mon, 16 Aug 2021 08:27:58 +0700 Subject: [PATCH 01/21] test --- test.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 test.txt diff --git a/test.txt b/test.txt new file mode 100644 index 0000000..e69de29 From ceb663c2e244745d54b425b34ad2c214808e1d24 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Mon, 16 Aug 2021 08:29:54 +0700 Subject: [PATCH 02/21] Renamed MyWindow to MainWindow, TRND.ui to main_window.ui, window.py to main_window.py --- data/{TRND.ui => main_window.ui} | 0 libs/{window.py => main_window.py} | 6 +++--- main.py | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) rename data/{TRND.ui => main_window.ui} (100%) rename libs/{window.py => main_window.py} (99%) diff --git a/data/TRND.ui b/data/main_window.ui similarity index 100% rename from data/TRND.ui rename to data/main_window.ui diff --git a/libs/window.py b/libs/main_window.py similarity index 99% rename from libs/window.py rename to libs/main_window.py index af2ddd4..d9e82c3 100644 --- a/libs/window.py +++ b/libs/main_window.py @@ -18,10 +18,10 @@ from libs.wiki_parser import get_data_from_wiki -class MyWindow(QMainWindow): +class MainWindow(QMainWindow): def __init__(self): - super(MyWindow, self).__init__() - uic.loadUi('data/TRND.ui', self) + super(MainWindow, self).__init__() + uic.loadUi('data/main_window.ui', self) self.date_format_str = '%d.%m.%Y %X' self.updateCheckTimeout = 60 diff --git a/main.py b/main.py index c8b0cf0..7049cc8 100644 --- a/main.py +++ b/main.py @@ -7,7 +7,7 @@ from PyQt5.QtWidgets import QApplication from qt_material import apply_stylesheet -from libs.window import MyWindow +from libs.main_window import MainWindow def init_environ(): @@ -54,7 +54,7 @@ def main(): app.installTranslator(translator) apply_theme(app) - window = MyWindow() + window = MainWindow() window.show() sys.exit(app.exec_()) From c05efd09742274551a7d81c757b47f03e2d0412a Mon Sep 17 00:00:00 2001 From: MangriMen Date: Mon, 16 Aug 2021 08:31:11 +0700 Subject: [PATCH 03/21] remove test --- test.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 test.txt diff --git a/test.txt b/test.txt deleted file mode 100644 index e69de29..0000000 From 27f94442dce9de99d16b326984fc5002b9ef74d3 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Thu, 19 Aug 2021 05:43:39 +0700 Subject: [PATCH 04/21] =?UTF-8?q?Removed=20'=D0=9F=D0=BE=D1=81=D0=BB=D0=B5?= =?UTF-8?q?=D0=B4=D0=BD=D1=8F=D1=8F=20=D0=B2=D0=B5=D1=80=D1=81=D0=B8=D1=8F?= =?UTF-8?q?'=20from=20teUpdateChangeList,=20now=20caching=20all=20versions?= =?UTF-8?q?=20to=20string=20and=20setting=20text=20with=20setMarkdown?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/main_window.py | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/libs/main_window.py b/libs/main_window.py index d9e82c3..a06c75a 100644 --- a/libs/main_window.py +++ b/libs/main_window.py @@ -295,16 +295,11 @@ def check_new_version(self, sender='timer'): str(response['error_msg'])) return - self.teUpdateChangeList.setText('Последняя версия: ' + response['data'][0]['tag_name']) - self.teUpdateChangeList.append('') - indent = ' ' + changelogStr = '' for version in response['data']: - self.teUpdateChangeList.append(version['name']) - if version['body']: - body = indent + version['body'].replace('\n', '\n' + indent) - else: - body = indent + 'Description not found' - self.teUpdateChangeList.append(body) + body = version['body'] or '        Описание отсутствует' + changelogStr += ''.join(['### ', version['name'], '\n', body, '\n\n']) + self.teUpdateChangeList.setMarkdown(changelogStr) if float(response['data'][0]['tag_name']) > float(os.environ.get('VERSION_NOW')): self.tabWidgetMain.setTabText(2, self.tabUpdate.accessibleName() + ' (новая версия)') From f045e32ff1b0ee45ff559b1f2c93862978a9b387 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Thu, 19 Aug 2021 06:01:35 +0700 Subject: [PATCH 05/21] Fixed font size on progressNow title --- data/main_window.ui | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/data/main_window.ui b/data/main_window.ui index b21ed27..5249876 100644 --- a/data/main_window.ui +++ b/data/main_window.ui @@ -34,7 +34,7 @@ - 0 + 1 false @@ -365,7 +365,7 @@ - 8 + 10 75 true @@ -390,7 +390,7 @@ - 8 + 10 75 true From cdae286bd31672d9c958bd0c31ff93edf0099c70 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Thu, 19 Aug 2021 06:13:44 +0700 Subject: [PATCH 06/21] Changed font size and style of progressbar titles and version title --- data/main_window.ui | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/data/main_window.ui b/data/main_window.ui index 5249876..314456b 100644 --- a/data/main_window.ui +++ b/data/main_window.ui @@ -365,13 +365,13 @@ - 10 + 11 75 true - ВСЕГО: + Всего: @@ -390,7 +390,7 @@ - 10 + 11 75 true @@ -405,7 +405,7 @@ 1 - СЕЙЧАС: + Сейчас: Qt::AutoText @@ -425,7 +425,7 @@ - 10 + 12 75 true @@ -689,19 +689,19 @@ - 165 + 0 0 - 10 + 12 75 true - ВЕРСИЯ ПРИЛОЖЕНИЯ: + Версия: @@ -709,11 +709,14 @@ - 10 + 12 75 true + + + TextLabel From f41327ce7184cc28ced3b63025cf5eff0b813dcd Mon Sep 17 00:00:00 2001 From: MangriMen Date: Thu, 19 Aug 2021 07:59:28 +0700 Subject: [PATCH 07/21] Added func to get wiki last data pages edit time with fandom API --- libs/wiki_parser.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/libs/wiki_parser.py b/libs/wiki_parser.py index e3809f1..bbff30c 100644 --- a/libs/wiki_parser.py +++ b/libs/wiki_parser.py @@ -1,4 +1,5 @@ import datetime +import json import math import time @@ -7,6 +8,35 @@ from libs import utils +def check_data_pages_update(): + URL = 'https://escapefromtarkov.fandom.com/ru/api.php?' + PARAMS = { + "action": "query", + "prop": "revisions", + "titles": "Оружие|Оружейные части и моды", + "rvprop": "timestamp", + "formatversion": "2", + "format": "json" + } + + try: + response = requests.get(url=URL, params=PARAMS) + response.raise_for_status() + response = response.json() + except requests.exceptions.RequestException: + response = None + except json.JSONDecodeError: + response = None + + try: + lastPageEdit = dict() + lastPageEdit['weapons'] = response['query']['pages'][0]['revisions'][0]['timestamp'] + lastPageEdit['mods'] = response['query']['pages'][1]['revisions'][0]['timestamp'] + except KeyError: + lastPageEdit = '' + return lastPageEdit + + def get_data_from_wiki(worker_, dict_): def showError(): worker_.error.emit( From d019e3e57230745ba2e6cc1d25726001444684a0 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Thu, 19 Aug 2021 08:00:48 +0700 Subject: [PATCH 08/21] Added a function to check whether the data needs to be updated or not, and added a notification about this --- libs/main_window.py | 46 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/libs/main_window.py b/libs/main_window.py index a06c75a..cc409f5 100644 --- a/libs/main_window.py +++ b/libs/main_window.py @@ -1,3 +1,4 @@ +import datetime import os import random import re @@ -15,7 +16,7 @@ from libs import utils from libs.qt_extends import JsonModel, ThreadController, showDetailedError -from libs.wiki_parser import get_data_from_wiki +from libs.wiki_parser import get_data_from_wiki, check_data_pages_update class MainWindow(QMainWindow): @@ -32,6 +33,8 @@ def __init__(self): self.data_thread = None self.jsonData = None self.isUpdateQuestion = True + self.isDataWeaponsUpdateQuestion = True + self.isDataModsUpdateQuestion = True self.twMainModel = JsonModel() self.twRandomModel = JsonModel() @@ -280,10 +283,44 @@ def start_update_restrict_timeout(self): self.updateTimeoutTimer.setUpdateInterval(1000) self.updateTimeoutTimer.start() + @pyqtSlot() + def notify_about_data_pages_update(self): + if not (lastPageEdit := check_data_pages_update()): + return + lastDataUpdateTime = dict() + for type_ in lastPageEdit: + try: + lastPageEdit[type_] = datetime.datetime.fromisoformat(lastPageEdit[type_].replace('Z', '')) + lastDataUpdateTime[type_] = datetime.datetime.fromisoformat(self.jsonData[type_ + 'LastUpdate']) + except KeyError: + pass + except ValueError: + pass + else: + if (self.isDataWeaponsUpdateQuestion and type_ == 'weapons')\ + or (self.isDataModsUpdateQuestion and type_ == 'mods'): + if lastPageEdit[type_] > lastDataUpdateTime[type_]: + typeTitle = 'оружия' if type_ == 'weapons' else 'модов' + res = QMessageBox.information(self, 'Новая версия ' + typeTitle, + 'Доступна новая версия ' + typeTitle + + '. Обновить?', + (QMessageBox.Ok | QMessageBox.Cancel)) + if type_ == 'weapons': + self.isDataWeaponsUpdateQuestion = False + elif type_ == 'mods': + self.isDataModsUpdateQuestion = False + + if res == QMessageBox.Ok: + self.tabWidgetMain.setCurrentWidget(self.tabData) + self.update_data(type_) + return + @pyqtSlot(str) def check_new_version(self, sender='timer'): if sender == 'button': self.start_update_restrict_timeout() + elif sender == 'timer': + self.notify_about_data_pages_update() response = utils.get_update_info(self.githubLinkLastRelease) @@ -407,7 +444,7 @@ def stop_process(): dlg.setCancelButton(btnCancel) btnCancel.hide() - dlg.setFixedSize(dlg.width()*1.5, dlg.height()) + dlg.setFixedSize(dlg.width() * 1.5, dlg.height()) dlg.canceled.connect(self.update_thread.stop) dlg.show() @@ -417,7 +454,7 @@ def stop_process(): self.update_thread.worker.progress.connect(dlg.setValue) self.update_thread.worker.progress.connect(lambda value: self.taskbarProgress.setValue( - (int(value) / int(total_length))*100)) + (int(value) / int(total_length)) * 100)) self.update_thread.worker.progress.connect(lambda value: lblText.setText(str(int(value / 1024)) + ' КБ / ' + total_length_display)) self.update_thread.thread.finished.connect(stop_process) @@ -446,6 +483,7 @@ def finish(main): main.lblProgress.setText("") main.update_json() main.taskbarProgress.hide() + self.notify_about_data_pages_update() if self.data_thread and self.data_thread.isRunning: self.data_thread.stop() @@ -523,7 +561,7 @@ def custom_tree_view_replace_random(self, index_): clickedRowText = self.twRandomModel.itemFromIndex(index_).text() pathToRootList = list() - while (item := self.twRandomModel.itemFromIndex(index_)) is not None\ + while (item := self.twRandomModel.itemFromIndex(index_)) is not None \ and (index_ := index_.parent()) is not None: pathToRootList.append(item.text()) pathToRootList.reverse() From a1eaa123b403d8b690ab4204354a4ecc3560965d Mon Sep 17 00:00:00 2001 From: MangriMen Date: Thu, 19 Aug 2021 08:16:42 +0700 Subject: [PATCH 09/21] Added data clearing in the temporary dictionary before updating --- libs/wiki_parser.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/libs/wiki_parser.py b/libs/wiki_parser.py index bbff30c..ad4b903 100644 --- a/libs/wiki_parser.py +++ b/libs/wiki_parser.py @@ -63,7 +63,11 @@ def showError(): secondLevelFormatStr = '%8s%s' thirdLevelFormatStr = '%12s%s' - outDict = utils.validate_data(dict_['jsonData']) + outDict = dict_['jsonData'].copy() + outDict.pop(dict_['type'], None) + if dict_['type'] == mods: + outDict.pop(modsConflicts, None) + outDict = utils.validate_data(outDict) downloadTime = time.perf_counter() if dict_['type'] == weapons or dict_['type'] == mods: From a483977af5a6d88fd1eae3808c5858f929f7bbd4 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 06:17:27 +0700 Subject: [PATCH 10/21] Added new tab and all elements --- data/main_window.ui | 107 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) diff --git a/data/main_window.ui b/data/main_window.ui index 314456b..db3d5b7 100644 --- a/data/main_window.ui +++ b/data/main_window.ui @@ -296,6 +296,113 @@ + + + Оружие и моды + + + + + + QLayout::SetDefaultConstraint + + + + + 0 + + + + + + 0 + 25 + + + + + 11 + 75 + true + + + + ПОИСК: + + + + + + + + 12 + + + + + + + + + + false + + + + + + + + + 0 + + + + + 0 + + + + + + 0 + 25 + + + + + 11 + 75 + true + + + + ПОИСК: + + + + + + + + 12 + + + + + + + + + + false + + + + + + + Данные From 7af28b30eb995671dca838d01617cb4789bba47a Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 06:18:05 +0700 Subject: [PATCH 11/21] Filled twPartsWeapons by twMain model, twPartsMods by new model filled by json self.jsonData['mods'] --- libs/main_window.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libs/main_window.py b/libs/main_window.py index cc409f5..95f2d13 100644 --- a/libs/main_window.py +++ b/libs/main_window.py @@ -82,6 +82,7 @@ def __init__(self): self.twRandom.setItemsExpandable(False) self.twRandom.customContextMenuRequested.connect(self.custom_tree_view_context_menu) self.twRandom.setContextMenuPolicy(Qt.CustomContextMenu) + self.twPartsWeapons.setModel(self.twMainModel) self.tabWidgetMain.setCurrentWidget(self.tabMain) self.lblVersion.setText(os.environ.get('VERSION_NOW')) @@ -100,6 +101,10 @@ def __init__(self): self.update_json() self.check_new_version() + modsJsonModel = JsonModel() + modsJsonModel.fillModel(self.jsonData['mods']) + self.twPartsMods.setModel(modsJsonModel) + @pyqtSlot() def import_json(self): pathToJson = QFileDialog().getOpenFileName(self, 'Import JSON', '/', "json(*.json);; all(*.*)")[0] From 855f7658f688125e0fc1221550c6ddb460b6e914 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 06:41:39 +0700 Subject: [PATCH 12/21] =?UTF-8?q?Added=20splitter=20and=20replaced=20'?= =?UTF-8?q?=D0=9F=D0=BE=D0=B8=D1=81=D0=BA'=20by=20'=D0=9E=D1=80=D1=83?= =?UTF-8?q?=D0=B6=D0=B8=D0=B5',=20'=D0=9C=D0=BE=D0=B4'=20respectively?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- data/main_window.ui | 176 +++++++++++++++++++++++--------------------- 1 file changed, 93 insertions(+), 83 deletions(-) diff --git a/data/main_window.ui b/data/main_window.ui index db3d5b7..4c7f4a0 100644 --- a/data/main_window.ui +++ b/data/main_window.ui @@ -22,7 +22,7 @@ - + @@ -300,106 +300,116 @@ Оружие и моды - - - - - QLayout::SetDefaultConstraint + + + + + Qt::Horizontal - - - - 0 + + 15 + + + + + QLayout::SetDefaultConstraint - - - - 0 - 25 - - - - - 11 - 75 - true - - - - ПОИСК: + + + 0 - + + + + + 0 + 25 + + + + + 11 + 75 + true + + + + ОРУЖИЕ: + + + + + + + + 12 + + + + + - - - - 12 - - + + + false + - - - - - false - - - - - - - - - 0 - - - - + + + + 0 - - - - 0 - 25 - - - - - 11 - 75 - true - - - - ПОИСК: + + + 0 - + + + + + 0 + 25 + + + + + 11 + 75 + true + + + + МОД: + + + + + + + + 12 + + + + + - - - - 12 - - + + + false + - - - - - false - - - - + + From 2ed6412821fdfc72b83d9fca315bedef942ae021 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 06:45:18 +0700 Subject: [PATCH 13/21] Renamed find_and_display_weapons to find_and_display_rows, added tree view and standard model for this tree view in arguments, unified to find in any tree view --- libs/main_window.py | 44 +++++++++++++++++++++++++++++++------------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/libs/main_window.py b/libs/main_window.py index 95f2d13..8144bc8 100644 --- a/libs/main_window.py +++ b/libs/main_window.py @@ -10,8 +10,9 @@ from PyQt5 import uic from PyQt5.Qt import QDesktopServices, QUrl, QMenu, QApplication from PyQt5.QtCore import Qt, QTimer, QTimeLine, pyqtSlot, QPoint -from PyQt5.QtGui import QColor, QFont -from PyQt5.QtWidgets import QMainWindow, QFileDialog, QMessageBox, QProgressDialog, QPushButton, QLabel, QProgressBar +from PyQt5.QtGui import QColor, QFont, QStandardItemModel +from PyQt5.QtWidgets import QMainWindow, QFileDialog, QMessageBox, QProgressDialog, QPushButton, QLabel, QProgressBar, \ + QTreeView from PyQt5 import QtWinExtras from libs import utils @@ -38,6 +39,7 @@ def __init__(self): self.twMainModel = JsonModel() self.twRandomModel = JsonModel() + self.twPartsModsModel = JsonModel() self.updateTimer = QTimer() self.updateTimeoutTimer = QTimeLine() @@ -46,7 +48,21 @@ def __init__(self): self.btnClearData.clicked.connect(self.clear_json) self.btnRandomWeapon.clicked.connect(self.random_weapon) self.btnUpdateApp.clicked.connect(self.update_app) - self.leFind.textChanged[str].connect(self.find_and_display_weapons) + self.leFind.textChanged.connect(lambda value: self.find_and_display_rows( + value, + self.twMain, + self.twMainModel + )) + self.lePartsWeaponsFind.textChanged.connect(lambda value: self.find_and_display_rows( + value, + self.twPartsWeapons, + self.twMainModel + )) + self.lePartsModsFind.textChanged.connect(lambda value: self.find_and_display_rows( + value, + self.twPartsMods, + self.twPartsModsModel + )) self.btnCheckNewVersion.clicked.connect(lambda: self.check_new_version('button')) self.btnGithubLink.clicked.connect(lambda: QDesktopServices.openUrl(QUrl(self.githubLink))) self.btnUpdateWeapons.clicked.connect(lambda: self.update_data('weapons')) @@ -83,6 +99,7 @@ def __init__(self): self.twRandom.customContextMenuRequested.connect(self.custom_tree_view_context_menu) self.twRandom.setContextMenuPolicy(Qt.CustomContextMenu) self.twPartsWeapons.setModel(self.twMainModel) + self.twPartsMods.setModel(self.twPartsModsModel) self.tabWidgetMain.setCurrentWidget(self.tabMain) self.lblVersion.setText(os.environ.get('VERSION_NOW')) @@ -101,10 +118,6 @@ def __init__(self): self.update_json() self.check_new_version() - modsJsonModel = JsonModel() - modsJsonModel.fillModel(self.jsonData['mods']) - self.twPartsMods.setModel(modsJsonModel) - @pyqtSlot() def import_json(self): pathToJson = QFileDialog().getOpenFileName(self, 'Import JSON', '/', "json(*.json);; all(*.*)")[0] @@ -144,23 +157,28 @@ def update_json(self): self.twMain.setModel(self.twMainModel) self.twMain.setCurrentIndex(self.twMainModel.createIndex(0, 0)) - @pyqtSlot(str) - def find_and_display_weapons(self, query): + self.twPartsWeapons.setModel(self.twMainModel) + + self.twPartsModsModel.fillModel(self.jsonData['mods']) + self.twPartsMods.setModel(self.twPartsModsModel) + + @pyqtSlot(str, QTreeView, QStandardItemModel) + def find_and_display_rows(self, query, treeView_, standardModel_): if query == '': - self.twMain.setModel(self.twMainModel) + treeView_.setModel(standardModel_) return - if self.twMainModel.rowCount == 0: + if standardModel_.rowCount == 0: return searchModel = JsonModel() - for item in self.twMainModel.findItems(query, Qt.MatchContains): + for item in standardModel_.findItems(query, Qt.MatchContains): item_clone = item.clone() searchModel.appendRow(item_clone) JsonModel.copyItemWithChildren(item_clone, item) - self.twMain.setModel(searchModel) + treeView_.setModel(searchModel) @pyqtSlot() def create_random_weapon(self, randomJson_, key_, json_, isEmpty_=False): From 0fc9e3be92b15c64e729feb2bcf41aaa9beaca89 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 06:53:47 +0700 Subject: [PATCH 14/21] Now setting text by self.tabWidgetMain.indexOf(tab) instead of hardcoded index --- data/main_window.ui | 8 ++++---- libs/main_window.py | 5 +++-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/data/main_window.ui b/data/main_window.ui index 4c7f4a0..b12ec3f 100644 --- a/data/main_window.ui +++ b/data/main_window.ui @@ -34,7 +34,7 @@ - 1 + 0 false @@ -54,7 +54,7 @@ - + 0 @@ -302,7 +302,7 @@ - + Qt::Horizontal @@ -463,7 +463,7 @@ - + diff --git a/libs/main_window.py b/libs/main_window.py index 8144bc8..ee35308 100644 --- a/libs/main_window.py +++ b/libs/main_window.py @@ -362,7 +362,8 @@ def check_new_version(self, sender='timer'): self.teUpdateChangeList.setMarkdown(changelogStr) if float(response['data'][0]['tag_name']) > float(os.environ.get('VERSION_NOW')): - self.tabWidgetMain.setTabText(2, self.tabUpdate.accessibleName() + ' (новая версия)') + self.tabWidgetMain.setTabText(self.tabWidgetMain.indexOf(self.tabUpdate), self.tabUpdate.accessibleName() + + '(новая версия)') if (sender == 'timer' and self.isUpdateQuestion) or self.tabWidgetMain.currentWidget() == self.tabUpdate: if sender == 'timer': message = 'Перейти на страницу обновления?' @@ -380,7 +381,7 @@ def check_new_version(self, sender='timer'): else: if sender == 'button': QMessageBox.information(self, 'Обновление', 'Установлена последняя версия.', QMessageBox.Ok) - self.tabWidgetMain.setTabText(2, self.tabUpdate.accessibleName()) + self.tabWidgetMain.setTabText(self.tabWidgetMain.indexOf(self.tabUpdate), self.tabUpdate.accessibleName()) @pyqtSlot() def update_app(self): From aa8afc34cf2a2bac36c0886556af5b6fd9c31825 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 08:15:05 +0700 Subject: [PATCH 15/21] Added logger initialization in main --- main.py | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/main.py b/main.py index 7049cc8..65de89f 100644 --- a/main.py +++ b/main.py @@ -1,6 +1,9 @@ +import datetime import os import platform import sys +import logging +from pathlib import Path from PyQt5 import QtGui from PyQt5.QtCore import QTranslator @@ -42,9 +45,49 @@ def apply_theme(app): app.setStyleSheet(app.styleSheet() + file.read().format(**os.environ)) +def init_logger(): + if getattr(sys, 'frozen', False): + programDir = sys.executable + else: + programDir = os.path.dirname(os.path.abspath(__file__)) + logger = logging.getLogger('TRND') + logger.setLevel(logging.INFO) + + formatter_ = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') + logsPath = os.path.abspath(programDir + '/logs/') + filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + '.log' + fullPath = os.path.join(logsPath, filename) + + Path(logsPath).mkdir(parents=True, exist_ok=True) + + filesCount = len(os.listdir(logsPath)) + + def clear_dir(directory): + directory = Path(directory) + for item in directory.iterdir(): + if item.is_dir(): + clear_dir(item) + else: + item.unlink() + + if filesCount > 10: + clear_dir(logsPath) + + try: + fileHandler = logging.FileHandler(fullPath) + except PermissionError: + pass + else: + fileHandler.setFormatter(formatter_) + + logger.addHandler(fileHandler) + logger.info('Program started') + + def main(): suppress_qt_warnings() init_environ() + init_logger() app = QApplication(sys.argv) @@ -61,4 +104,4 @@ def main(): if __name__ == '__main__': - main() + main() \ No newline at end of file From 2f773737dc76bfe9f58938007f1ffd286b3b0585 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 08:22:16 +0700 Subject: [PATCH 16/21] Added a logger to modules and a small example --- libs/main_window.py | 3 +++ libs/wiki_parser.py | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/libs/main_window.py b/libs/main_window.py index ee35308..4e3e7a2 100644 --- a/libs/main_window.py +++ b/libs/main_window.py @@ -1,4 +1,5 @@ import datetime +import logging import os import random import re @@ -118,6 +119,8 @@ def __init__(self): self.update_json() self.check_new_version() + self.logger = logging.getLogger('TRND.main_window') + @pyqtSlot() def import_json(self): pathToJson = QFileDialog().getOpenFileName(self, 'Import JSON', '/', "json(*.json);; all(*.*)")[0] diff --git a/libs/wiki_parser.py b/libs/wiki_parser.py index ad4b903..e83e03c 100644 --- a/libs/wiki_parser.py +++ b/libs/wiki_parser.py @@ -1,5 +1,6 @@ import datetime import json +import logging import math import time @@ -49,6 +50,8 @@ def showError(): urlMods = 'https://escapefromtarkov.fandom.com/ru/wiki/%D0%9E%D1%80%D1%83%D0%B6%D0%B5%D0%B9%D0%BD%D1%8B%D0%B5_' \ '%D1%87%D0%B0%D1%81%D1%82%D0%B8_%D0%B8_%D0%BC%D0%BE%D0%B4%D1%8B ' + logger = logging.getLogger('TRND.wiki_parser') + weapons = 'weapons' mods = 'mods' modsConflicts = 'modsConflicts' @@ -69,6 +72,7 @@ def showError(): outDict.pop(modsConflicts, None) outDict = utils.validate_data(outDict) + logger.info("Started " + dict_['type'] + " update") downloadTime = time.perf_counter() if dict_['type'] == weapons or dict_['type'] == mods: minF = 0 @@ -92,6 +96,7 @@ def showError(): html = requests.get(queryPage) html.raise_for_status() except requests.exceptions.RequestException as err: + logger.error(err) showError() return @@ -137,6 +142,7 @@ def showError(): r = requests.get(site + a_.get('href')) r.raise_for_status() except requests.exceptions.RequestException as err: + logger.error(err) showError() return @@ -214,6 +220,8 @@ def showError(): if modLinkStr not in outDict[dict_['type']][weaponNameStr]: outDict[dict_['type']][weaponNameStr].append(modLinkStr) + logger.info(dict_['type'] + " update completed") + elapsed = time.perf_counter() - downloadTime elapsedStr = ("--- %.f minutes %.f seconds ---" % ((elapsed / 60), elapsed % 60)) worker_.display_text.emit(elapsedStr) From 7d4276c1aa8b84399e32e00ec736aa5897ad44bb Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 08:36:30 +0700 Subject: [PATCH 17/21] Fixed end of main.py --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 65de89f..708d9b5 100644 --- a/main.py +++ b/main.py @@ -104,4 +104,4 @@ def main(): if __name__ == '__main__': - main() \ No newline at end of file + main() From 54d70e07de8995f8c1c5243e51aae771e492e847 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 08:53:30 +0700 Subject: [PATCH 18/21] Change sys.executable to os.path.dirname(sys.executable) --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 708d9b5..7088262 100644 --- a/main.py +++ b/main.py @@ -47,7 +47,7 @@ def apply_theme(app): def init_logger(): if getattr(sys, 'frozen', False): - programDir = sys.executable + programDir = os.path.dirname(sys.executable) else: programDir = os.path.dirname(os.path.abspath(__file__)) logger = logging.getLogger('TRND') From 4d1e478284a7e91a4b8cf7a28c21ebf66b442b9a Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 09:15:18 +0700 Subject: [PATCH 19/21] Moved logs folder to appdata/TRND/ --- main.py | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/main.py b/main.py index 7088262..c275c04 100644 --- a/main.py +++ b/main.py @@ -19,11 +19,12 @@ def init_environ(): # Adding path to internal json if platform.system() == 'Windows': - os.environ['DATAFOLDER'] = os.environ.get('APPDATA') + '\\TRND\\' - os.environ['DATAFILE'] = os.environ.get('APPDATA') + '\\TRND\\data.json' + os.environ['DATAFOLDER'] = os.path.join(os.environ.get('APPDATA'), 'TRND') else: - os.environ['DATAFOLDER'] = os.environ.get('HOME') + '/.trnd/' - os.environ['DATAFILE'] = os.environ.get('HOME') + '/.trnd/data.json' + os.environ['DATAFOLDER'] = os.path.join(os.environ.get('HOME'), '.trnd') + + os.environ['DATAFILE'] = os.path.join(os.environ.get('DATAFOLDER'), 'data.json') + os.environ['LOGSFOLDER'] = os.path.join(os.environ.get('DATAFOLDER'), 'logs') if not os.path.exists(os.environ.get('DATAFOLDER')): os.makedirs(os.environ.get('DATAFOLDER')) @@ -46,15 +47,11 @@ def apply_theme(app): def init_logger(): - if getattr(sys, 'frozen', False): - programDir = os.path.dirname(sys.executable) - else: - programDir = os.path.dirname(os.path.abspath(__file__)) logger = logging.getLogger('TRND') logger.setLevel(logging.INFO) formatter_ = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') - logsPath = os.path.abspath(programDir + '/logs/') + logsPath = os.path.abspath(os.environ.get('LOGSFOLDER')) filename = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") + '.log' fullPath = os.path.join(logsPath, filename) From 8a0957157d744bb643337714440eb1c5533c4bdc Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 09:19:33 +0700 Subject: [PATCH 20/21] Beautify main and moved initialization in init functions --- main.py | 41 ++++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/main.py b/main.py index c275c04..c0b659c 100644 --- a/main.py +++ b/main.py @@ -13,6 +13,13 @@ from libs.main_window import MainWindow +def suppress_qt_warnings(): + os.environ["QT_DEVICE_PIXEL_RATIO"] = "0" + os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" + os.environ["QT_SCREEN_SCALE_FACTORS"] = "1" + os.environ["QT_SCALE_FACTOR"] = "1" + + def init_environ(): if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'): os.chdir(sys._MEIPASS) @@ -32,20 +39,6 @@ def init_environ(): os.environ['VERSION_NOW'] = '0.16' -def suppress_qt_warnings(): - os.environ["QT_DEVICE_PIXEL_RATIO"] = "0" - os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1" - os.environ["QT_SCREEN_SCALE_FACTORS"] = "1" - os.environ["QT_SCALE_FACTOR"] = "1" - - -def apply_theme(app): - QtGui.QFontDatabase.addApplicationFont("data/Roboto-Regular.ttf") - apply_stylesheet(app, theme="data/tarkov_theme.xml") - with open('data/additional_style.css') as file: - app.setStyleSheet(app.styleSheet() + file.read().format(**os.environ)) - - def init_logger(): logger = logging.getLogger('TRND') logger.setLevel(logging.INFO) @@ -81,6 +74,19 @@ def clear_dir(directory): logger.info('Program started') +def init_translator(app): + translator = QTranslator(app) + translator.load("data/qtbase_ru.qm") + app.installTranslator(translator) + + +def init_theme(app): + QtGui.QFontDatabase.addApplicationFont("data/Roboto-Regular.ttf") + apply_stylesheet(app, theme="data/tarkov_theme.xml") + with open('data/additional_style.css') as file: + app.setStyleSheet(app.styleSheet() + file.read().format(**os.environ)) + + def main(): suppress_qt_warnings() init_environ() @@ -88,11 +94,8 @@ def main(): app = QApplication(sys.argv) - translator = QTranslator(app) - translator.load("data/qtbase_ru.qm") - - app.installTranslator(translator) - apply_theme(app) + init_translator(app) + init_theme(app) window = MainWindow() window.show() From ba1ab3dd1cfe13bbdb32c00a4e99abce7394e072 Mon Sep 17 00:00:00 2001 From: MangriMen Date: Fri, 20 Aug 2021 09:24:51 +0700 Subject: [PATCH 21/21] Version changed to 0.17 --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index c0b659c..f63eadd 100644 --- a/main.py +++ b/main.py @@ -36,7 +36,7 @@ def init_environ(): if not os.path.exists(os.environ.get('DATAFOLDER')): os.makedirs(os.environ.get('DATAFOLDER')) - os.environ['VERSION_NOW'] = '0.16' + os.environ['VERSION_NOW'] = '0.17' def init_logger():