Adam Cseresznye commited on
Commit
3785a98
·
1 Parent(s): 5ec7a4f

Switch contact form from Formspree to Web3Forms

Browse files
Files changed (2) hide show
  1. config/config.py +4 -7
  2. ui/pages.py +46 -29
config/config.py CHANGED
@@ -24,8 +24,7 @@ logger.add(lambda msg: print(msg, end=""), level=LOG_LEVEL)
24
  # ============================================================================
25
  # Contact Form Configuration (Formspree)
26
  # ============================================================================
27
- FORMSPREE_URL = os.getenv("FORMSPREE_URL")
28
-
29
  # ============================================================================
30
  # Semantic Scholar API Configuration
31
  # ============================================================================
@@ -99,12 +98,10 @@ def validate_config() -> None:
99
  "help": "Get free key at https://console.groq.com/keys",
100
  },
101
  }
102
- if FORMSPREE_URL:
103
- logger.info("✓ Contact form configured (Formspree)")
104
  else:
105
- logger.warning(
106
- "⚠️ Contact form URL missing. Submissions will only log to console."
107
- )
108
 
109
  missing = []
110
  empty_values = []
 
24
  # ============================================================================
25
  # Contact Form Configuration (Formspree)
26
  # ============================================================================
27
+ WEB3FORMS_ACCESS_KEY = os.getenv("WEB3FORMS_ACCESS_KEY")
 
28
  # ============================================================================
29
  # Semantic Scholar API Configuration
30
  # ============================================================================
 
98
  "help": "Get free key at https://console.groq.com/keys",
99
  },
100
  }
101
+ if WEB3FORMS_ACCESS_KEY:
102
+ logger.info("✓ Contact form configured (Web3Forms)")
103
  else:
104
+ logger.warning("⚠️ Web3Forms key missing. Submissions will log to console.")
 
 
105
 
106
  missing = []
107
  empty_values = []
ui/pages.py CHANGED
@@ -18,7 +18,7 @@ from ui.components import (
18
  from ui.policies import PRIVACY_POLICY, TERMS_OF_SERVICE
19
  from ui.constants import POSTHOG_SCRIPT, KOFI_WIDGET
20
  import httpx
21
- from config.config import FORMSPREE_URL
22
 
23
  # Path to logo directory
24
  LOGO_DIR = (
@@ -139,53 +139,70 @@ def init_ui(fastapi_app):
139
  c_msg = ui.textarea("Message").classes("w-full").props("outlined dense")
140
 
141
  async def handle_contact_submit():
 
142
  if not c_name.value or not c_email.value or not c_msg.value:
143
  ui.notify("Please fill out all fields", type="warning")
144
  return
145
 
146
- # Disable button to prevent double-submit
147
  submit_btn.disable()
148
 
149
  try:
150
- # 1. Check if configured
151
- if not FORMSPREE_URL:
152
- logger.warning("FORMSPREE_URL missing. Logging to console.")
153
- logger.info(
154
- f"📩 Contact | Name: {c_name.value} | Email: {c_email.value} | Msg: {c_msg.value}"
155
- )
156
  ui.notify(
157
  "Message logged (Service not configured).", type="info"
158
  )
159
  else:
160
- # 2. Send to Formspree
 
 
161
  payload = {
162
- "email": c_email.value, # Formspree uses this for Reply-To
163
  "name": c_name.value,
 
164
  "message": c_msg.value,
 
 
165
  }
166
 
167
- async with httpx.AsyncClient() as client:
168
- response = await client.post(
169
- FORMSPREE_URL, json=payload, timeout=10.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  )
171
-
172
- if response.status_code == 200:
173
- ui.notify(
174
- "Message sent! We'll be in touch.",
175
- type="positive",
176
- )
177
- else:
178
- logger.error(f"Formspree Error: {response.text}")
179
- raise Exception("Failed to send message")
180
-
181
- # 3. Cleanup
182
- contact_dialog.close()
183
- c_name.value = ""
184
- c_email.value = ""
185
- c_msg.value = ""
186
 
187
  except Exception as e:
188
- logger.error(f"Contact form failed: {e}")
189
  ui.notify(
190
  "An error occurred. Please try again later.",
191
  type="negative",
 
18
  from ui.policies import PRIVACY_POLICY, TERMS_OF_SERVICE
19
  from ui.constants import POSTHOG_SCRIPT, KOFI_WIDGET
20
  import httpx
21
+ from config.config import WEB3FORMS_ACCESS_KEY
22
 
23
  # Path to logo directory
24
  LOGO_DIR = (
 
139
  c_msg = ui.textarea("Message").classes("w-full").props("outlined dense")
140
 
141
  async def handle_contact_submit():
142
+ # 1. Validate inputs (Python side)
143
  if not c_name.value or not c_email.value or not c_msg.value:
144
  ui.notify("Please fill out all fields", type="warning")
145
  return
146
 
 
147
  submit_btn.disable()
148
 
149
  try:
150
+ if not WEB3FORMS_ACCESS_KEY:
151
+ logger.warning("WEB3FORMS_ACCESS_KEY missing.")
 
 
 
 
152
  ui.notify(
153
  "Message logged (Service not configured).", type="info"
154
  )
155
  else:
156
+ import json
157
+
158
+ # 2. Prepare Payload
159
  payload = {
160
+ "access_key": WEB3FORMS_ACCESS_KEY,
161
  "name": c_name.value,
162
+ "email": c_email.value,
163
  "message": c_msg.value,
164
+ "subject": f"Necthrall Contact: {c_name.value}",
165
+ "botcheck": False,
166
  }
167
 
168
+ # 3. Construct JavaScript fetch (Client-side execution)
169
+ # We use json.dumps ensures safe serialization of user input
170
+ js_code = f"""
171
+ const response = await fetch('https://api.web3forms.com/submit', {{
172
+ method: 'POST',
173
+ headers: {{
174
+ 'Content-Type': 'application/json',
175
+ 'Accept': 'application/json'
176
+ }},
177
+ body: JSON.stringify({json.dumps(payload)})
178
+ }});
179
+ return await response.json();
180
+ """
181
+
182
+ # 4. Run JS in the user's browser and await the result
183
+ result = await ui.run_javascript(js_code, timeout=15.0)
184
+
185
+ if result and result.get("success"):
186
+ ui.notify(
187
+ result.get("message", "Message sent!"),
188
+ type="positive",
189
  )
190
+ # Clear form only on success
191
+ contact_dialog.close()
192
+ c_name.value = ""
193
+ c_email.value = ""
194
+ c_msg.value = ""
195
+ else:
196
+ error_msg = (
197
+ result.get("message", "Unknown error")
198
+ if result
199
+ else "No response"
200
+ )
201
+ logger.error(f"Web3Forms JS Error: {result}")
202
+ ui.notify(f"Failed: {error_msg}", type="negative")
 
 
203
 
204
  except Exception as e:
205
+ logger.error(f"Contact form exception: {e}")
206
  ui.notify(
207
  "An error occurred. Please try again later.",
208
  type="negative",