1
1
import json
2
2
3
- import requests # type: ignore
4
3
from qgis .core import QgsExpressionContextUtils , QgsProject , QgsVectorLayer
4
+ from qgis .PyQt .QtCore import QByteArray , QUrl
5
+ from qgis .PyQt .QtNetwork import QNetworkAccessManager , QNetworkProxy , QNetworkReply , QNetworkRequest
5
6
from qgis .PyQt .QtWidgets import QDialog , QMessageBox
6
7
from qgis .utils import iface
7
8
8
9
from arho_feature_template .core .update_plan import LandUsePlan , update_selected_plan
9
10
from arho_feature_template .gui .load_plan_dialog import LoadPlanDialog
10
11
from arho_feature_template .gui .serialize_plan import SerializePlan
11
12
from arho_feature_template .utils .db_utils import get_existing_database_connection_names
12
- from arho_feature_template .utils .misc_utils import get_active_plan_id , get_lambda_settings , handle_unsaved_changes
13
+ from arho_feature_template .utils .misc_utils import get_active_plan_id , get_settings , handle_unsaved_changes
13
14
14
15
15
16
class PlanManager :
16
17
HTTP_STATUS_OK = 200
17
18
18
19
def __init__ (self ):
20
+ # Init network manager
21
+ self .network_manager = QNetworkAccessManager ()
22
+ proxy_host , proxy_port , self .lambda_url = get_settings ()
23
+
24
+ # SOCKS5 Proxy
25
+ proxy = QNetworkProxy ()
26
+ proxy .setType (QNetworkProxy .Socks5Proxy )
27
+ proxy .setHostName (proxy_host )
28
+ proxy .setPort (int (proxy_port ))
29
+ self .network_manager .setProxy (proxy )
30
+
19
31
self .kaava_layer = self .get_layer_by_name ("Kaava" )
20
- lambda_host , lambda_port = get_lambda_settings ()
21
- self .lambda_url = f"https://{ lambda_host } :{ lambda_port } /v0/ryhti"
22
32
23
33
def get_layer_by_name (self , layer_name ):
24
34
"""Retrieve a layer by name from the project."""
@@ -119,8 +129,8 @@ def get_plan_json(self):
119
129
"""Serializes plan and plan outline to JSON"""
120
130
dialog = SerializePlan ()
121
131
if dialog .exec_ () == QDialog .Accepted :
122
- json_plan_path = dialog .plan_widget . filePath ()
123
- json_plan_outline_path = dialog .plan_outline_widget . filePath ()
132
+ json_plan_path = dialog .plan_path_edit . text ()
133
+ json_plan_outline_path = dialog .plan_outline_path_edit . text ()
124
134
125
135
plan_id = get_active_plan_id ()
126
136
@@ -129,43 +139,76 @@ def get_plan_json(self):
129
139
return
130
140
131
141
payload = {"action" : "get_plans" , "plan_uuid" : plan_id }
142
+ payload_bytes = QByteArray (json .dumps (payload ).encode ("utf-8" ))
143
+
144
+ request = QNetworkRequest (QUrl (self .lambda_url ))
145
+ request .setHeader (QNetworkRequest .ContentTypeHeader , "application/json" )
146
+
147
+ reply = self .network_manager .post (request , payload_bytes )
148
+
149
+ # Connect the finished signal to a lambda to pass extra arguments
150
+ reply .finished .connect (lambda : self ._handle_response (reply , json_plan_path , json_plan_outline_path ))
151
+
152
+ def _handle_response (self , reply : QNetworkReply , json_plan_path : str , json_plan_outline_path : str ):
153
+ """Handle the API response and process the plan and outline data."""
154
+ if reply .error () != QNetworkReply .NoError :
155
+ error_string = reply .errorString ()
156
+ QMessageBox .critical (None , "Virhe API kutsussa" , f"Virhe: { error_string } " )
157
+ return
158
+
159
+ try :
160
+ response_data = reply .readAll ().data ().decode ('utf-8' )
161
+ response_json = json .loads (response_data )
162
+
163
+ details = response_json .get ("details" )
164
+ if not details :
165
+ QMessageBox .warning (None , "Varoitus" , "Vastauksesta puuttuu 'details' kenttä." )
166
+ return
167
+
168
+ # Extract plan and write it to file
169
+ plan_id = get_active_plan_id ()
170
+ if not plan_id :
171
+ QMessageBox .critical (None , "Virhe" , "Ei aktiivista kaavaa." )
172
+ return
132
173
133
- try :
134
- response = requests .post (
135
- self .lambda_url , json = payload , headers = {"Content-Type" : "application/json" }, timeout = 15
174
+ plan_json = details .get (plan_id )
175
+ if not plan_json :
176
+ QMessageBox .warning (None , "Varoitus" , f"Aktiiviselle kaavalle (id: { plan_id } ) ei löydy tietoja." )
177
+ return
178
+
179
+ with open (json_plan_path , "w" , encoding = "utf-8" ) as full_file :
180
+ json .dump (plan_json , full_file , ensure_ascii = False , indent = 2 )
181
+
182
+ # Process the geographicalArea for the outline
183
+ geographical_area = plan_json .get ("geographicalArea" )
184
+ if geographical_area :
185
+ try :
186
+ # Build the structured outline JSON and write to file
187
+ outline_json = {
188
+ "type" : "Feature" ,
189
+ "properties" : {
190
+ "name" : "Example Polygon"
191
+ },
192
+ "srid" : geographical_area .get ("srid" ),
193
+ "geometry" : geographical_area .get ("geometry" ),
194
+ }
195
+
196
+ with open (json_plan_outline_path , "w" , encoding = "utf-8" ) as outline_file :
197
+ json .dump (outline_json , outline_file , ensure_ascii = False , indent = 2 )
198
+
199
+ QMessageBox .information (None , "Success" , "Kaava ja sen ulkorja tallennettu onnistuneesti." )
200
+ except KeyError as e :
201
+ QMessageBox .critical (
202
+ None ,
203
+ "Virhe" ,
204
+ f"'geographicalArea' ei sisällä vaadittuja tietoja: { e } " ,
205
+ )
206
+ else :
207
+ QMessageBox .warning (
208
+ None , "Varoitus" , "Kenttä 'geographicalArea' puuttuu kaavan tiedoista."
136
209
)
137
- if response .status_code == self .HTTP_STATUS_OK :
138
- response_json = response .json ()
139
-
140
- # Extract the "details" part for the full JSON
141
- details = response_json .get ("details" )
142
- if details :
143
- # Extract the plan_json
144
- plan_json = details .get (plan_id )
145
-
146
- if plan_json :
147
- with open (json_plan_path , "w" , encoding = "utf-8" ) as full_file :
148
- json .dump (plan_json , full_file , ensure_ascii = False , indent = 2 )
149
-
150
- # Extract and save the plan outline
151
- geographical_area = plan_json .get ("geographicalArea" )
152
- if geographical_area :
153
- with open (json_plan_outline_path , "w" , encoding = "utf-8" ) as outline_file :
154
- json .dump (
155
- {"geographicalArea" : geographical_area },
156
- outline_file ,
157
- ensure_ascii = False ,
158
- indent = 2 ,
159
- )
160
-
161
- else :
162
- QMessageBox .warning (
163
- None , "Warning" , "The geographicalArea field is missing in the plan details."
164
- )
165
- else :
166
- QMessageBox .warning (None , "Warning" , "No plan data found for the specified plan ID." )
167
- else :
168
- QMessageBox .warning (None , "Warning" , "No details found in the response JSON." )
169
-
170
- except requests .RequestException as e :
171
- QMessageBox .critical (None , "Request Error" , f"An error occurred: { e !s} " )
210
+ except json .JSONDecodeError as e :
211
+ QMessageBox .critical (None , "Virhe" , f"Vastaus JSON:in purkaminen epäonnistui: { e } " )
212
+
213
+ # Clean up the reply
214
+ reply .deleteLater ()
0 commit comments