Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow custom XForm uploads, in addition to XLSForms #1294

Merged
merged 1 commit into from
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 28 additions & 31 deletions src/backend/app/central/central_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,45 +357,42 @@ def download_submissions(
return fixed.splitlines()


async def test_form_validity(xform_content: str, form_type: str):
async def test_form_validity(xform_content: bytes, form_type: str):
"""Validate an XForm.

Args:
xform_content (str): form to be tested
form_type (str): type of form (xls or xlsx).
"""
try:
xlsform_path = f"/tmp/validate_form.{form_type}"
outfile = "/tmp/outfile.xml"

with open(xlsform_path, "wb") as f:
f.write(xform_content)

xls2xform_convert(xlsform_path=xlsform_path, xform_path=outfile, validate=False)

namespaces = {
"h": "http://www.w3.org/1999/xhtml",
"odk": "http://www.opendatakit.org/xforms",
"xforms": "http://www.w3.org/2002/xforms",
}

with open(outfile, "r") as xml:
data = xml.read()

root = ElementTree.fromstring(data)
instances = root.findall(".//xforms:instance[@src]", namespaces)

geojson_list = []
for inst in instances:
try:
if "src" in inst.attrib:
if (inst.attrib["src"].split("."))[1] == "geojson":
parts = (inst.attrib["src"].split("."))[0].split("/")
geojson_name = parts[-1]
geojson_list.append(geojson_name)
except Exception:
continue
if form_type != "xml":
# Write xform_content to a temporary file
with open(f"/tmp/xform_temp.{form_type}", "wb") as f:
f.write(xform_content)
else:
with open(f"/tmp/xlsform.{form_type}", "wb") as f:
f.write(xform_content)
# Convert XLSForm to XForm
xls2xform_convert(
xlsform_path="/tmp/xlsform.xls",
xform_path="/tmp/xform_temp.xml",
validate=False,
)

# Parse XForm
namespaces = {"xforms": "http://www.w3.org/2002/xforms"}
tree = ElementTree.parse("/tmp/xform_temp.xml")
root = tree.getroot()

# Extract geojson filenames
geojson_list = [
os.path.splitext(inst.attrib["src"].split("/")[-1])[0]
for inst in root.findall(".//xforms:instance[@src]", namespaces)
if inst.attrib.get("src", "").endswith(".geojson")
]

return {"required media": geojson_list, "message": "Your form is valid"}

except Exception as e:
return JSONResponse(
content={"message": "Your form is invalid", "possible_reason": str(e)},
Expand Down
1 change: 1 addition & 0 deletions src/backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@

# Add sentry tracing only in prod
if not settings.DEBUG:
log.info("Adding Sentry tracing")
sentry_sdk.init(
dsn=settings.SENTRY_DSN,
traces_sample_rate=0.1,
Expand Down
12 changes: 7 additions & 5 deletions src/backend/app/projects/project_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,19 +588,21 @@ async def edit_project_boundary(
}


@router.post("/validate_form")
@router.post("/validate-form")
async def validate_form(form: UploadFile):
"""Tests the validity of the xls form uploaded.

Parameters:
- form: The xls form to validate
"""
file_name = os.path.splitext(form.filename)
file_ext = file_name[1]
file = Path(form.filename)
file_ext = file.suffix

allowed_extensions = [".xls", ".xlsx"]
allowed_extensions = [".xls", ".xlsx", "xml"]
if file_ext not in allowed_extensions:
raise HTTPException(status_code=400, detail="Provide a valid .xls file")
raise HTTPException(
status_code=400, detail="Provide a valid .xls,.xlsx,.xml file"
)

contents = await form.read()
return await central_crud.test_form_validity(contents, file_ext[1:])
Expand Down
6 changes: 3 additions & 3 deletions src/frontend/src/components/createnewproject/SelectForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const SelectForm = ({ flag, geojsonFile, customFormFile, setCustomFormFile }) =>
};
useEffect(() => {
if (customFormFile && !customFileValidity) {
dispatch(ValidateCustomForm(`${import.meta.env.VITE_API_URL}/projects/validate_form`, customFormFile));
dispatch(ValidateCustomForm(`${import.meta.env.VITE_API_URL}/projects/validate-form`, customFormFile));
}
}, [customFormFile]);
return (
Expand Down Expand Up @@ -153,8 +153,8 @@ const SelectForm = ({ flag, geojsonFile, customFormFile, setCustomFormFile }) =>
onResetFile={resetFile}
customFile={customFormFile}
btnText="Select a Form"
accept=".xls,.xlsx"
fileDescription="*The supported file formats are .xlsx, .xls"
accept=".xls,.xlsx,.xml"
fileDescription="*The supported file formats are .xlsx, .xls, .xml"
errorMsg={errors.customFormUpload}
/>
) : null}
Expand Down
Loading