-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument_editor_model.py
More file actions
243 lines (184 loc) · 8.36 KB
/
document_editor_model.py
File metadata and controls
243 lines (184 loc) · 8.36 KB
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
import docx
import logging
import keyring
import requests
from pathlib import Path
from api.api_client import APIClient
from utils.app_paths import get_app_data_dir, get_local_data_dir
from utils.file_utils import load_config, read_json
class DocumentEditorModel:
def __init__(
self,
category_id: int = None,
document_data: dict = None,
pages: list[dict] = None
) -> None:
self.category_id = category_id
self.document_data = document_data if document_data is not None else {}
self.pages = pages if pages is not None else []
self.pending_files = []
self.config_data = load_config()
# Constants
self.APP_DIR = get_app_data_dir()
self.LOCAL_DIR = get_local_data_dir()
self.LOCAL_DIR_LAST_LOGGED = self.LOCAL_DIR / "last_logged.json"
# API Client Initialization
self.api = APIClient(base_url=self.config_data.get("base_url", None))
self.is_document_edited = False
def import_from_docx(self, file_path: str) -> list[dict]:
"""Imports pages from a Word document."""
doc = docx.Document(file_path)
pages = []
for table in doc.tables:
if not table.rows:
continue
# Check headers in the first row
headers = [cell.text.strip() for cell in table.rows[0].cells]
if len(headers) != 2:
continue
# Flexible header search
headers_map = {h.lower(): i for i, h in enumerate(headers)}
name_synonyms = ["наименование", "название", "имя", "name", "title"]
code_synonyms = ["код", "шифр", "обозначение", "code", "designation"]
name_index = next((headers_map[s] for s in name_synonyms if s in headers_map), -1)
code_index = next((headers_map[s] for s in code_synonyms if s in headers_map), -1)
if name_index != -1 and code_index != -1:
# Iterate over data rows
for row in table.rows[1:]:
cells = row.cells
if len(cells) > max(name_index, code_index):
name_text = cells[name_index].text.strip()
code_text = cells[code_index].text.strip()
pages.append({
"id": None, # New page has no ID
"name": name_text,
"designation": code_text
})
# Stop after finding and processing the first valid table
if pages:
break
return pages
def export_to_docx(
self,
path: str,
filename: str,
data: dict = None
) -> None:
"""Exports the document data to a Word document.
Args:
path: The path to save the Word document.
filename: The name of the Word document.
data: The document data as a dictionary.
"""
doc = docx.Document()
if data:
code = data.get("code", "")
name = data.get("name", "")
pages = data.get("pages", [])
else:
code = self.document_data.get("code", "")
name = self.document_data.get("name", "")
pages = self.pages
pages.sort(key=lambda x: x.get("order_index", 0))
doc.add_heading(f"{code} - {name}", 1)
table = doc.add_table(rows=1, cols=2)
table.style = 'Table Grid'
hdr_cells = table.rows[0].cells
hdr_cells[0].text = 'Наименование'
hdr_cells[1].text = 'Код'
for page in pages:
row_cells = table.add_row().cells
row_cells[0].text = str(page.get("name", "") or "")
row_cells[1].text = str(page.get("designation", "") or "")
full_path = Path(path) / filename
doc.save(str(full_path))
def download_file(self, file_id: int, save_path: str) -> None:
"""Downloads a file."""
self._make_authorized_request(self.api.download_file, file_id=file_id, destination_path=save_path)
def upload_file(self, file_path: str) -> dict:
"""Uploads a file to the current document."""
doc_id = self.document_data.get("id")
if doc_id is None:
raise ValueError("Сначала сохраните документ перед загрузкой файлов.")
return self._make_authorized_request(self.api.upload_file, document_id=doc_id, file_path=file_path)
def add_pending_file(self, file_path: str) -> None:
"""Adds a file to the pending upload list."""
if file_path not in self.pending_files:
self.pending_files.append(file_path)
def remove_pending_file(self, file_path: str) -> None:
"""Removes a file from the pending upload list."""
if file_path in self.pending_files:
self.pending_files.remove(file_path)
def upload_pending_files(self) -> None:
"""Uploads all pending files."""
errors = []
for file_path in list(self.pending_files):
try:
self.upload_file(file_path)
self.pending_files.remove(file_path)
except Exception as e:
errors.append(f"Не удалось загрузить {Path(file_path).name}: {e}")
if errors:
raise Exception("\n".join(errors))
def delete_file(self, file_id: int) -> None:
"""Deletes a file from the document."""
self._make_authorized_request(self.api.delete_file, file_id=file_id)
def delete_document(self) -> None:
self._make_authorized_request(
self.api.delete_document,
document_id=self.document_data.get("id")
)
def save_document(self, data: dict) -> None:
doc_id = self.document_data.get("id")
if doc_id is None:
data["category_id"] = self.category_id
response = self._make_authorized_request(self.api.create_document, data=data)
self.document_data = response
else:
self._make_authorized_request(self.api.update_document, document_id=doc_id, data=data)
# ====================
# Model Methods
# ====================
def _get_user_token(self) -> str | None:
last_logged = read_json(self.LOCAL_DIR_LAST_LOGGED)
if not isinstance(last_logged, dict):
return None
user_id = last_logged.get("user_id")
if user_id in (None, ""):
return None
access_token = keyring.get_password(
service_name="Documents Exp",
username=f"access_token_{user_id}"
)
return access_token
def _make_authorized_request(self, api_method, **kwargs):
"""Executes an API request with automatic token refresh on 401."""
try:
token = self._get_user_token()
return api_method(token=token, **kwargs)
except requests.exceptions.HTTPError as e:
if e.response is not None and e.response.status_code == 401:
logging.info("Access token expired. Refreshing...")
if self._refresh_tokens():
token = self._get_user_token()
return api_method(token=token, **kwargs)
raise e
def _refresh_tokens(self) -> bool:
"""Refreshes tokens using the stored refresh token."""
try:
last_logged = read_json(self.LOCAL_DIR_LAST_LOGGED)
if not isinstance(last_logged, dict):
return False
user_id = last_logged.get("user_id")
if user_id in (None, ""):
return False
refresh_token = keyring.get_password("Documents Exp", f"refresh_token_{user_id}")
if not refresh_token:
return False
tokens = self.api.refresh(refresh_token)
keyring.set_password("Documents Exp", f"access_token_{user_id}", tokens["access_token"])
keyring.set_password("Documents Exp", f"refresh_token_{user_id}", tokens["refresh_token"])
return True
except Exception as e:
logging.error(f"Failed to refresh tokens: {e}")
return False