-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqfit_config_dialog.py
More file actions
363 lines (311 loc) · 15.2 KB
/
qfit_config_dialog.py
File metadata and controls
363 lines (311 loc) · 15.2 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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
"""Dedicated configuration dialog for persistent qfit plugin settings.
This dialog is the second step toward separating setup concerns
(Strava/Mapbox credentials and connection checks) from the day-to-day activity
workflow in the main dock widget. It intentionally avoids visualization-
specific Mapbox styling options, which belong in the main map workflow.
"""
import logging
from qgis.PyQt.QtCore import Qt, QUrl
from qgis.PyQt.QtGui import QDesktopServices
from qgis.PyQt.QtWidgets import (
QApplication,
QDialog,
QDialogButtonBox,
QFormLayout,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QMessageBox,
QPushButton,
QVBoxLayout,
QWidget,
)
from .activities.application.sync_controller import SyncController
from .configuration.application.config_connection_service import (
build_mapbox_connection_test_request,
build_strava_connection_test_request,
validate_mapbox_connection_request,
validate_strava_connection_request,
)
from .configuration.application.config_status import mapbox_status_text, strava_status_text
from .configuration.application.settings_port import SettingsPort
from .configuration.application.settings_service import SettingsService
from .configuration.application.ui_settings_binding import (
UIFieldBinding,
load_bindings,
save_bindings,
)
from .providers.domain.provider import ProviderError
from .providers.infrastructure.strava_client import StravaClient
from .ui.widgets import make_password_line_edit
logger = logging.getLogger(__name__)
_NOT_TESTED_LABEL = "Not tested"
_OAUTH_NOT_STARTED_LABEL = "Not started"
class QfitConfigDialog(QDialog):
"""Editable configuration dialog for qfit plugin connection settings.
Allows the user to view and edit Strava credentials plus the Mapbox
access token, run the Strava OAuth helper flow, and test provider
connections before saving. Changes are persisted to QSettings on save.
"""
def __init__(
self,
settings_service: SettingsPort | None = None,
sync_controller: SyncController | None = None,
cache: object | None = None,
parent: QWidget | None = None,
):
super().__init__(parent)
self._settings = settings_service or SettingsService()
self._sync_controller = sync_controller or SyncController()
self._cache = cache
self.setWindowTitle("qfit — Configuration")
self.setMinimumWidth(420)
self._build_ui()
self._bindings = self._make_bindings()
self._load()
# -- UI construction -----------------------------------------------------
def _build_ui(self) -> None:
layout = QVBoxLayout(self)
layout.addWidget(self._build_strava_group())
layout.addWidget(self._build_mapbox_group())
layout.addStretch()
self._button_box = QDialogButtonBox(
QDialogButtonBox.Save | QDialogButtonBox.Close,
)
self._button_box.button(QDialogButtonBox.Save).clicked.connect(self._save)
self._button_box.rejected.connect(self.close)
layout.addWidget(self._button_box)
def _build_strava_group(self) -> QGroupBox:
group = QGroupBox("Strava connection")
form = QFormLayout(group)
self._strava_status_label = QLabel()
self._strava_status_label.setObjectName("stravaStatusLabel")
self._strava_status_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
form.addRow("Status:", self._strava_status_label)
self._client_id_edit = QLineEdit()
self._client_id_edit.setObjectName("cfgClientIdEdit")
self._client_id_edit.setPlaceholderText("Strava application client ID")
form.addRow("Client ID:", self._client_id_edit)
self._client_secret_edit = make_password_line_edit(
placeholder_text="Strava application client secret",
)
self._client_secret_edit.setObjectName("cfgClientSecretEdit")
form.addRow("Client secret:", self._client_secret_edit)
self._redirect_uri_edit = QLineEdit()
self._redirect_uri_edit.setObjectName("cfgRedirectUriEdit")
form.addRow("Redirect URI:", self._redirect_uri_edit)
self._oauth_help_label = QLabel(
"Use qfit's OAuth helper below to generate the refresh token. Do not paste the token shown on the Strava API application page."
)
self._oauth_help_label.setObjectName("stravaOAuthHelpLabel")
self._oauth_help_label.setWordWrap(True)
self._oauth_help_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
form.addRow("", self._oauth_help_label)
self._authorization_code_edit = QLineEdit()
self._authorization_code_edit.setObjectName("cfgAuthorizationCodeEdit")
self._authorization_code_edit.setPlaceholderText(
"Paste the code returned by Strava after approval"
)
form.addRow("Authorization code:", self._authorization_code_edit)
oauth_button_row = QWidget(group)
oauth_button_layout = QHBoxLayout(oauth_button_row)
oauth_button_layout.setContentsMargins(0, 0, 0, 0)
oauth_button_layout.setSpacing(6)
self._open_authorize_button = QPushButton("Open Strava authorize page")
self._open_authorize_button.setObjectName("cfgOpenAuthorizeButton")
self._open_authorize_button.clicked.connect(self._open_strava_authorize_page)
oauth_button_layout.addWidget(self._open_authorize_button)
self._exchange_code_button = QPushButton("Exchange code")
self._exchange_code_button.setObjectName("cfgExchangeCodeButton")
self._exchange_code_button.clicked.connect(self._exchange_strava_code)
oauth_button_layout.addWidget(self._exchange_code_button)
oauth_button_layout.addStretch(1)
form.addRow("", oauth_button_row)
self._strava_oauth_status_label = QLabel(_OAUTH_NOT_STARTED_LABEL)
self._strava_oauth_status_label.setObjectName("stravaOAuthStatusLabel")
self._strava_oauth_status_label.setWordWrap(True)
self._strava_oauth_status_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
form.addRow("OAuth helper:", self._strava_oauth_status_label)
self._refresh_token_edit = make_password_line_edit(
placeholder_text="Generated by qfit's OAuth flow, not the Strava app page",
)
self._refresh_token_edit.setObjectName("cfgRefreshTokenEdit")
form.addRow("Refresh token:", self._refresh_token_edit)
self._strava_test_status_label = QLabel(_NOT_TESTED_LABEL)
self._strava_test_status_label.setObjectName("stravaTestStatusLabel")
self._strava_test_status_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
form.addRow("Last test:", self._strava_test_status_label)
self._test_strava_button = QPushButton("Test connection")
self._test_strava_button.setObjectName("testStravaConnectionButton")
self._test_strava_button.clicked.connect(self._test_strava)
form.addRow("", self._test_strava_button)
return group
def _build_mapbox_group(self) -> QGroupBox:
group = QGroupBox("Mapbox connection")
form = QFormLayout(group)
self._mapbox_status_label = QLabel()
self._mapbox_status_label.setObjectName("mapboxStatusLabel")
self._mapbox_status_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
form.addRow("Status:", self._mapbox_status_label)
self._mapbox_token_edit = make_password_line_edit(
placeholder_text="pk.eyJ1Ijo...",
)
self._mapbox_token_edit.setObjectName("cfgMapboxTokenEdit")
form.addRow("Access token:", self._mapbox_token_edit)
self._mapbox_test_status_label = QLabel(_NOT_TESTED_LABEL)
self._mapbox_test_status_label.setObjectName("mapboxTestStatusLabel")
self._mapbox_test_status_label.setTextInteractionFlags(Qt.TextSelectableByMouse)
form.addRow("Last test:", self._mapbox_test_status_label)
self._test_mapbox_button = QPushButton("Test connection")
self._test_mapbox_button.setObjectName("testMapboxConnectionButton")
self._test_mapbox_button.clicked.connect(self._test_mapbox)
form.addRow("", self._test_mapbox_button)
return group
# -- Data load / save ----------------------------------------------------
def _make_bindings(self) -> list[UIFieldBinding]:
"""Build the explicit UI field → settings key mapping for this dialog."""
return [
UIFieldBinding(
"client_id", "",
lambda w=self._client_id_edit: w.text().strip(),
self._client_id_edit.setText,
),
UIFieldBinding(
"client_secret", "",
lambda w=self._client_secret_edit: w.text().strip(),
self._client_secret_edit.setText,
),
UIFieldBinding(
"redirect_uri", StravaClient.DEFAULT_REDIRECT_URI,
lambda w=self._redirect_uri_edit: w.text().strip(),
self._redirect_uri_edit.setText,
),
UIFieldBinding(
"refresh_token", "",
lambda w=self._refresh_token_edit: w.text().strip(),
self._refresh_token_edit.setText,
),
UIFieldBinding(
"mapbox_access_token", "",
lambda w=self._mapbox_token_edit: w.text().strip(),
self._mapbox_token_edit.setText,
),
]
def _load(self) -> None:
"""Read current settings and populate all fields."""
load_bindings(self._bindings, self._settings)
self._authorization_code_edit.clear()
self._refresh_status_labels()
self._strava_oauth_status_label.setText(_OAUTH_NOT_STARTED_LABEL)
self._strava_test_status_label.setText(_NOT_TESTED_LABEL)
self._mapbox_test_status_label.setText(_NOT_TESTED_LABEL)
def _save(self) -> None:
"""Persist edited fields to QSettings and refresh status labels."""
save_bindings(self._bindings, self._settings)
self._refresh_status_labels()
def _refresh_status_labels(self) -> None:
self._strava_status_label.setText(strava_status_text(self._settings))
self._mapbox_status_label.setText(mapbox_status_text(self._settings))
def _redirect_uri(self) -> str:
return self._redirect_uri_edit.text().strip() or StravaClient.DEFAULT_REDIRECT_URI
def _open_strava_authorize_page(self) -> None:
self._save()
try:
authorize_request = self._sync_controller.build_authorize_request(
client_id=self._client_id_edit.text().strip(),
client_secret=self._client_secret_edit.text().strip(),
refresh_token=self._refresh_token_edit.text().strip(),
cache=self._cache,
redirect_uri=self._redirect_uri(),
)
url = self._sync_controller.build_authorize_url(authorize_request)
if not QDesktopServices.openUrl(QUrl(url)):
clipboard = QApplication.clipboard()
if clipboard is not None:
clipboard.setText(url)
self._show_info(
"Open Strava authorize page manually",
"qfit could not open the browser automatically. The authorization URL was copied to your clipboard.\n\nOpen this URL in a browser and continue the flow there:\n\n{url}".format(
url=url
),
)
self._strava_oauth_status_label.setText(
"Could not open browser automatically. Authorization URL copied to clipboard."
)
return
self._strava_oauth_status_label.setText(
"Strava authorization opened in your browser. Approve access, copy the returned code, then paste it here and click Exchange code."
)
except ProviderError as exc:
self._show_error("Strava authorization failed", str(exc))
self._strava_oauth_status_label.setText(
"Could not start the Strava authorization flow"
)
def _exchange_strava_code(self) -> None:
self._save()
authorization_code = self._authorization_code_edit.text().strip()
if not authorization_code:
self._show_error(
"Missing authorization code",
"Paste the code returned by Strava first.",
)
self._strava_oauth_status_label.setText(
"Paste the returned Strava code before exchanging it."
)
return
try:
exchange_request = self._sync_controller.build_exchange_code_request(
client_id=self._client_id_edit.text().strip(),
client_secret=self._client_secret_edit.text().strip(),
refresh_token=self._refresh_token_edit.text().strip(),
cache=self._cache,
authorization_code=authorization_code,
redirect_uri=self._redirect_uri(),
)
payload = self._sync_controller.exchange_code_for_tokens(exchange_request)
refresh_token = payload["refresh_token"]
self._refresh_token_edit.setText(refresh_token)
self._authorization_code_edit.clear()
self._save()
athlete = payload.get("athlete") or {}
athlete_name = " ".join(
part for part in [athlete.get("firstname"), athlete.get("lastname")] if part
).strip()
if athlete_name:
self._strava_oauth_status_label.setText(
"Strava connected for {name}. Refresh token saved locally in QGIS settings.".format(
name=athlete_name
)
)
else:
self._strava_oauth_status_label.setText(
"Strava refresh token saved locally in QGIS settings."
)
self._strava_test_status_label.setText(_NOT_TESTED_LABEL)
except ProviderError as exc:
self._show_error("Token exchange failed", str(exc))
self._strava_oauth_status_label.setText(
"Could not exchange the Strava authorization code"
)
def _test_strava(self) -> None:
request = build_strava_connection_test_request(
self._client_id_edit.text(),
self._client_secret_edit.text(),
self._refresh_token_edit.text(),
)
result = validate_strava_connection_request(request)
self._strava_test_status_label.setText(result.message)
def _test_mapbox(self) -> None:
request = build_mapbox_connection_test_request(self._mapbox_token_edit.text())
result = validate_mapbox_connection_request(request)
self._mapbox_test_status_label.setText(result.message)
def _show_info(self, title: str, message: str) -> None:
QMessageBox.information(self, title, message)
def _show_error(self, title: str, message: str) -> None:
QMessageBox.critical(self, title, message)
# -- Visibility ----------------------------------------------------------
def showEvent(self, event) -> None: # noqa: N802
"""Reload settings every time the dialog becomes visible."""
super().showEvent(event)
self._load()