forked from pompushko/alfaromeostickerbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEperHandler.py
300 lines (248 loc) · 11.2 KB
/
EperHandler.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
import httpx
import asyncio
import re
import json
from typing import Optional, Dict, Any
from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.units import mm
from datetime import datetime
from io import BytesIO
session_id = ""
headers = {
'Content-Type': 'text/plain',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
cookies = {
'DRIVE': '',
'loginTypeCookie': 'UPRS',
'EP_MKT': '023',
'gig_bootstrap_4_orFmUKH1TrnP0kMf3hryrA': 'login-ra_ver4',
'gig_llu': '',
'gig_llp': '',
'ga_NQRXPBM53J': 'GS1.1.1716315659.51.1.1716316203.0.0.0',
'dtCookie': '',
'AKA_A2': 'A',
'_gid': 'GA1.2.924781583.1735413322',
'_ga_7FSXK7VK1F': 'GS1.1.1735413329.64.1.1735413523.14.0.0',
'_ga': 'GA1.2.1628127437.1702652518',
'JSESSIONID': '',
'EPERUIDC': '',
'DWRSESSIONID': '',
'LANGUAGE': '3',
'GUI_LANG': '3',
'EKV': ''
}
class FiatPartsClient:
def __init__(self, headers: dict, cookies: dict):
self.base_url = "https://eper.parts.fiat.com/dwr/call/plaincall"
self.headers = headers
self.cookies = cookies
def _create_configuration_payload(self, vin: str, session_id: str) -> dict:
return {
'callCount': '1',
'windowName': '',
'c0-scriptName': 'MVSManager',
'c0-methodName': 'getVinConfiguration',
'c0-id': '0',
'c0-param0': 'string:R',
'c0-param1': 'string:3',
'c0-param2': f'string:{vin}',
'c0-param3': 'string:',
'c0-param4': 'string:DEFAULT',
'batchId': '1',
'instanceId': '0',
'page': '/navi?EU=1&COUNTRY=023&RMODE=DEFAULT&SBMK=R&MAKE=R&LANGUAGE=3&GUI_LANG=3&SAVE_PARAM=LANGUAGE',
'scriptSessionId': session_id
}
def _create_alestimento_payload(self, catalog_code: str, vin: str, session_id: str) -> dict:
return {
'callCount': '1',
'windowName': '',
'c0-scriptName': 'MVSManager',
'c0-methodName': 'getVinAlestimento',
'c0-id': '0',
'c0-param0': f'string:{catalog_code}',
'c0-param1': 'string:3',
'c0-param2': f'string:{vin}',
'c0-param3': 'string:',
'batchId': '1',
'instanceId': '0',
'page': '/navi?EU=1&COUNTRY=023&RMODE=DEFAULT&SBMK=R&MAKE=R&LANGUAGE=3&GUI_LANG=3&SAVE_PARAM=LANGUAGE',
'scriptSessionId': session_id
}
def _parse_dwr_response(self, response_text: str) -> Optional[Dict[str, Any]]:
try:
pattern = r'r\.handleCallback\("[^"]+",\s*"[^"]+",\s*(\[.*?\])\);'
match = re.search(pattern, response_text)
if match:
json_str = match.group(1)
json_str = json_str.replace("\\'", "'")
json_str = re.sub(r'\\",', '",', json_str)
json_str = re.sub(r'\\"}', '"}', json_str)
json_str = re.sub(r'\\(?!["\\/bfnrt])', '', json_str)
json_str = re.sub(r'([{,])\s*([a-zA-Z0-9_]+):', r'\1"\2":', json_str)
try:
data = json.loads(json_str)
return data if data else None
except json.JSONDecodeError as e:
print(f"Ошибка парсинга JSON после обработки: {e}")
print(f"На позиции {e.pos}:")
start = max(0, e.pos - 50)
end = min(len(json_str), e.pos + 50)
print(f"Контекст ошибки: ...{json_str[start:end]}...")
print(f"Полная строка JSON: {json_str}") # Добавим для отладки
return None
except Exception as e:
print(f"Общая ошибка парсинга: {e}")
return None
async def get_vin_configuration(self, vin: str, session_id: str) -> Optional[Dict[str, Any]]:
url = f"{self.base_url}/MVSManager.getVinConfiguration.dwr"
payload = self._create_configuration_payload(vin, session_id)
async with httpx.AsyncClient() as client:
response = await client.post(url, headers=self.headers, data=payload, cookies=self.cookies)
return self._parse_dwr_response(response.text)
async def get_vin_alestimento(self, catalog_code: str, vin: str, session_id: str) -> Optional[Dict[str, Any]]:
url = f"{self.base_url}/MVSManager.getVinAlestimento.dwr"
payload = self._create_alestimento_payload(catalog_code, vin, session_id)
async with httpx.AsyncClient() as client:
response = await client.post(url, headers=self.headers, data=payload, cookies=self.cookies)
return self._parse_dwr_response(response.text)
async def get_full_vin_info(self, vin: str, session_id: str) -> dict:
config_data = await self.get_vin_configuration(vin, session_id)
if not config_data:
raise Exception("Не удалось получить конфигурацию VIN")
catalog_code = config_data[0].get('catalogCode')
if not catalog_code:
raise Exception("Не удалось получить catalogCode из конфигурации")
alestimento_data = await self.get_vin_alestimento(catalog_code, vin, session_id)
return {
"configuration": config_data,
"alestimento": alestimento_data
}
class FiatPartsPDFGenerator:
def __init__(self):
try:
pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))
except:
print("Шрифт Arial не найден, используем стандартный шрифт")
self.styles = getSampleStyleSheet()
self.style_header = ParagraphStyle(
'CustomHeader',
parent=self.styles['Heading1'],
fontName='Arial',
fontSize=14,
spaceAfter=30,
alignment=1
)
def create_pdf(self, data: dict) -> bytes:
buffer = BytesIO()
doc = SimpleDocTemplate(
buffer,
pagesize=A4,
rightMargin=20*mm,
leftMargin=20*mm,
topMargin=20*mm,
bottomMargin=20*mm
)
elements = []
title = Paragraph(f"Отчет по VIN: {data['configuration'][0].get('vin', 'Н/Д')}", self.style_header)
elements.append(title)
if data.get('configuration'):
elements.extend(self._create_configuration_table(data['configuration']))
if data.get('alestimento'):
elements.extend(self._create_alestimento_table(data['alestimento']))
doc.build(elements)
pdf_bytes = buffer.getvalue()
buffer.close()
return pdf_bytes
def _create_configuration_table(self, config_data):
elements = []
section_title = Paragraph("Конфигурация автомобиля", self.style_header)
elements.append(section_title)
table_data = []
headers = ['Параметр', 'Значение']
table_data.append(headers)
if config_data and len(config_data) > 0:
config = config_data[0]
important_fields = [
('vin', 'VIN'),
('catalogCode', 'Код каталога'),
('model', 'Модель'),
('version', 'Версия'),
('engineCode', 'Код двигателя'),
('productionDate', 'Дата производства')
]
for field, title in important_fields:
if field in config:
table_data.append([title, str(config.get(field, 'Н/Д'))])
table = Table(table_data, colWidths=[200, 300])
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Arial'),
('FONTSIZE', (0, 0), (-1, 0), 12),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.white),
('TEXTCOLOR', (0, 1), (-1, -1), colors.black),
('FONTNAME', (0, 1), (-1, -1), 'Arial'),
('FONTSIZE', (0, 1), (-1, -1), 10),
('GRID', (0, 0), (-1, -1), 1, colors.black),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
('WORDWRAP', (0, 0), (-1, -1), True),
('PADDING', (0, 0), (-1, -1), 6),
]))
elements.append(table)
return elements
def _create_alestimento_table(self, alestimento_data):
elements = []
section_title = Paragraph("Дополнительная информация", self.style_header)
elements.append(section_title)
table_data = []
headers = ['Код', 'Описание', 'Значение']
table_data.append(headers)
if isinstance(alestimento_data, list):
for item in alestimento_data:
if isinstance(item, dict):
code = item.get('code', 'Н/Д')
description = item.get('description', 'Н/Д')
value = item.get('value', 'Н/Д')
description_paragraph = Paragraph(
description,
ParagraphStyle(
'Description',
parent=self.styles['Normal'],
fontSize=10,
leading=12,
wordWrap='CJK'
)
)
table_data.append([code, description_paragraph, value])
table = Table(
table_data,
colWidths=[100, 300, 100],
rowHeights=[30] + [None] * (len(table_data) - 1)
)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
('FONTNAME', (0, 0), (-1, 0), 'Arial'),
('FONTSIZE', (0, 0), (-1, 0), 12),
('BOTTOMPADDING', (0, 0), (-1, 0), 12),
('BACKGROUND', (0, 1), (-1, -1), colors.white),
('TEXTCOLOR', (0, 1), (-1, -1), colors.black),
('FONTNAME', (0, 1), (-1, -1), 'Arial'),
('FONTSIZE', (0, 1), (-1, -1), 10),
('GRID', (0, 0), (-1, -1), 1, colors.black),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('PADDING', (0, 0), (-1, -1), 6),
]))
elements.append(table)
return elements