Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

integrations: Fix jotform integration to receive files.

Varun-Kolanue8364d8edd79
diff --git a/zerver/webhooks/jotform/fixtures/response.multipart b/zerver/webhooks/jotform/fixtures/response.multipart
index ff39612f5f3..2991a41aa8f 100644
--- a/zerver/webhooks/jotform/fixtures/response.multipart
+++ b/zerver/webhooks/jotform/fixtures/response.multipart
@@ -65,7 +65,7 @@ Content-Disposition: form-data; name="customBody"
--------------------------J1JNT4vbVO4FCC1qLG4HSv
Content-Disposition: form-data; name="rawRequest"
-{"slug":"submit\/243231271343446","jsExecutionTracker":"build-date-1732271172685=>init-started:1732615894703=>validator-called:1732615894706=>validator-mounted-false:1732615894706=>init-complete:1732615894707=>onsubmit-fired:1732615897940=>observerSubmitHandler_received-submit-event:1732615897941=>submit-validation-passed:1732615897942=>observerSubmitHandler_validation-passed-submitting-form:1732615897944","submitSource":"form","buildDate":"1732271172685","uploadServerUrl":"https:\/\/upload.jotform.com\/upload","eventObserver":"1","q3_studentsName":{"first":"Niloth","last":"P"},"q33_typeOf":"Online Tutoring","q34_subjectFor":"Math","q35_grade":"12","q28_appointment":{"implementation":"new","date":"","duration":"60","timezone":"Asia\/Calcutta (GMT+06:30)"},"timeToSubmit":"3","preview":"true","validatedNewRequiredFieldIDs":"{\"new\":1}","path":"\/submit\/243231271343446"}
+{"slug":"submit\/243231271343446","jsExecutionTracker":"build-date-1732271172685=>init-started:1732615894703=>validator-called:1732615894706=>validator-mounted-false:1732615894706=>init-complete:1732615894707=>onsubmit-fired:1732615897940=>observerSubmitHandler_received-submit-event:1732615897941=>submit-validation-passed:1732615897942=>observerSubmitHandler_validation-passed-submitting-form:1732615897944","submitSource":"form","buildDate":"1732271172685","uploadServerUrl":"https:\/\/upload.jotform.com\/upload","eventObserver":"1","q3_studentsName":{"first":"Niloth","last":"P"},"q33_typeOf":"Online Tutoring","q34_subjectFor":"Math","q35_grade":"12","q27_priorTutoring":"No","q28_appointment":{"implementation":"new","date":"","duration":"60","timezone":"Asia\/Calcutta (GMT+06:30)"},"q15_date":{"month":"","day":"","year":""},"q19_table":{"colIds":"[\"0\",\"1\",\"2\",\"3\"]","rowIds":"[\"0\",\"1\",\"2\",\"3\"]"},"timeToSubmit":"3","temp_upload":{"q5_identityProof":["Student_ID_!#$&'()*+,-.;=@[]^_`{}~ .png#jotformfs-e4f4ece4d0a90#01940839-37f4-7a46-9b4e-71107f08774a", "Driving.license.png#jotformfs-e4f4ece4d0a90#01940839-37f4-7a46-9b4e-71107f08774a"], "q6_reports":["Report Card.pdf#jotformfs-e4f4ece4d0a90#01940839-37f4-7a46-9b4e-71107f08774a"]},"file_server":"jotforms-e4f4ece4d0a90#01940839-37f4-7a46-9b4e-71107f08774a","preview":"true","validatedNewRequiredFieldIDs":"{\"new\":1}","path":"\/submit\/243231271343446","q7_description":"","identityProof":["https:\/\/www.jotform.com\/uploads\/UserNiloth\/243231271343446\/6111139644845227683\/Student_ID_%21_%24%26%27%28%29_%2C-.%3B%3D%40%5B%5D%5E_%60%7B%7D~%20.png","https:\/\/www.jotform.com\/uploads\/UserNiloth\/243231271343446\/6111139644845227684\/Driving.license.png"],"reports":["https:\/\/www.jotform.com\/uploads\/UserNiloth\/243231271343446\/6111139644845227685\/Report%20Card.pdf"]}
--------------------------J1JNT4vbVO4FCC1qLG4HSv
Content-Disposition: form-data; name="fromTable"
@@ -77,7 +77,7 @@ Content-Disposition: form-data; name="appID"
--------------------------J1JNT4vbVO4FCC1qLG4HSv
Content-Disposition: form-data; name="pretty"
-Student's Name:Niloth P, Type of Tutoring:Online Tutoring, Subject for Tutoring:Math, Grade:12
+Student's Name:Niloth P, Type of Tutoring:Online Tutoring, Subject for Tutoring:Math, Grade:12, Prior Tutoring?:No, Identity Proof:Student_ID_!_$&'()_,-.;=@[]^_`{}~ .png Driving.license.png, Reports:Report Card.pdf
--------------------------J1JNT4vbVO4FCC1qLG4HSv
Content-Disposition: form-data; name="unread"
diff --git a/zerver/webhooks/jotform/tests.py b/zerver/webhooks/jotform/tests.py
index 8c4472b5909..fc8650af7d9 100644
--- a/zerver/webhooks/jotform/tests.py
+++ b/zerver/webhooks/jotform/tests.py
@@ -15,7 +15,12 @@ class JotformHookTests(WebhookTestCase):
* **Student's Name**: Niloth P
* **Type of Tutoring**: Online Tutoring
* **Subject for Tutoring**: Math
-* **Grade**: 12""".strip()
+* **Grade**: 12
+* **Prior Tutoring?** No
+
+* **Identity Proof**: [Student_ID_!_$&'()_,-.;=@[]^_`{}~ .png](https://www.jotform.com/uploads/UserNiloth/243231271343446/6111139644845227683/Student_ID_%21_%24%26%27%28%29_%2C-.%3B%3D%40%5B%5D%5E_%60%7B%7D~%20.png), [Driving.license.png](https://www.jotform.com/uploads/UserNiloth/243231271343446/6111139644845227684/Driving.license.png)
+
+* **Reports**: [Report Card.pdf](https://www.jotform.com/uploads/UserNiloth/243231271343446/6111139644845227685/Report%20Card.pdf)""".strip()
self.check_webhook(
"response",
diff --git a/zerver/webhooks/jotform/view.py b/zerver/webhooks/jotform/view.py
index c5c0284417d..c3d20afefa1 100644
--- a/zerver/webhooks/jotform/view.py
+++ b/zerver/webhooks/jotform/view.py
@@ -1,5 +1,9 @@
# Webhooks for external integrations.
+import json
+from typing import Any
+from urllib.parse import unquote
+
from django.http import HttpRequest, HttpResponse
from django.utils.translation import gettext as _
@@ -11,6 +15,46 @@ from zerver.lib.webhooks.common import check_send_webhook_message
from zerver.models import UserProfile
+def format_uploaded_file_links(file_question_value: str, file_url_mappings: dict[str, str]) -> str:
+ words = file_question_value.split()
+ url_markdown_list = []
+ current_file_name_words = []
+ for word in words:
+ current_file_name_words.append(word)
+
+ # Greedy approach to find the filenames in file_url_mappings.
+ potential_file_name = " ".join(current_file_name_words)
+ if potential_file_name in file_url_mappings:
+ file_url = file_url_mappings.get(potential_file_name)
+ url_markdown_list.append(f"[{potential_file_name}]({file_url})")
+ current_file_name_words = []
+
+ return ", ".join(url_markdown_list)
+
+
+def is_non_file_upload_question_with_response(field: str, raw_request: dict[str, Any]) -> bool:
+ field_value = raw_request.get(field)
+ return bool(
+ field
+ and field[0] == "q"
+ and field_value
+ and (
+ isinstance(field_value, str)
+ or (
+ isinstance(field_value, dict)
+ # Non-empty Appointment, Date fields
+ and "" not in field_value.values()
+ # Non-empty Input Table field
+ and not (
+ len(field_value) == 2 and "colIds" in field_value and "rowIds" in field_value
+ )
+ )
+ # Multiple choice questions
+ or isinstance(field_value, list)
+ )
+ )
+
+
@webhook_view("Jotform")
@typed_endpoint_without_parameters
def api_jotform_webhook(
@@ -24,12 +68,42 @@ def api_jotform_webhook(
if not topic_name or not fields:
raise JsonableError(_("Unable to handle Jotform payload"))
+ raw_request = json.loads(payload.get("rawRequest", "{}"))
+ url_mappings = {}
+ if raw_request.get("temp_upload"):
+ upload_keys = raw_request.get("temp_upload").keys()
+ file_questions_keys = [key.split("_", 1)[-1] for key in upload_keys]
+ url_mappings = {
+ unquote(url.split("/")[-1]): url
+ for key in file_questions_keys
+ for url in raw_request.get(key, [])
+ }
+
+ # File upload questions are in raw_request["temp_upload"].
+ # So, the other questions are the keys in raw_request starting
+ # with "q". We exclude any questions with a zero length value,
+ # because they are not in the "pretty" data of the payload.
+ count_non_file_upload_questions = len(
+ [
+ field
+ for field in raw_request
+ if is_non_file_upload_question_with_response(field, raw_request)
+ ]
+ )
+
form_response = ""
- for field in fields:
+ for index, field in enumerate(fields):
label, value = field.split(":", 1)
- # TODO: Add fixtures and tests for question-like fields and files
separator = " " if label.endswith("?") else ": "
+
+ # File upload fields are last in the "pretty" payload data.
+ if index >= count_non_file_upload_questions:
+ value = format_uploaded_file_links(value, url_mappings)
+ # We add a new line so that image files are rendered
+ # correctly in the message.
+ form_response += "\n"
form_response += f"* **{label}**{separator}{value}\n"
+
message = form_response.strip()
check_send_webhook_message(request, user_profile, topic_name, message)