Start of creating kmz file, with entrance photos and links to expo.survex.com

This commit is contained in:
Martin Green
2023-05-08 01:10:43 +01:00
parent ea7c29a54e
commit f7fca58c57
8 changed files with 160 additions and 74 deletions

View File

@@ -1,10 +1,15 @@
import os
import re
import subprocess
import tempfile
import zipfile
import urllib
from bs4 import BeautifulSoup
from pathlib import Path
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect
from django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect, FileResponse
from django.shortcuts import render
from django.urls import NoReverseMatch, reverse
@@ -17,6 +22,8 @@ from troggle.core.views import expo
from troggle.settings import CAVEDESCRIPTIONS, ENTRANCEDESCRIPTIONS
from troggle.parsers.caves import read_cave, read_entrance
from django.template import loader
from django.utils.safestring import mark_safe
from .auth import login_required_if_public
@@ -628,3 +635,45 @@ def expo_kml(request):
},
content_type = "application/vnd.google-earth.kml+xml"
)
def expo_kmz(request):
notablecaves = set(getnotablecaves())
#Zip file written to a file, to save this function using too much memory
with tempfile.TemporaryDirectory() as tmpdirname:
zippath = os.path.join(tmpdirname, 'expo.kmz')
with zipfile.ZipFile(zippath, 'w', compression=zipfile.ZIP_DEFLATED) as myzip:
entrances = []
for e in Entrance.objects.all():
html = loader.get_template("entrance_html.kml").render({"entrance": e}, request)
soup=BeautifulSoup(html)
for img in soup.find_all("img"):
#src_orig = img['src']
src = urllib.parse.urljoin(e.cavelist()[0].url.rpartition("/")[0] + "/", img['src'])
img['src'] = src
p = os.path.join(settings.EXPOWEB, src)
#print(e.cavelist()[0].url, e.cavelist()[0].url.rpartition("/")[0] + "/", src_orig, p)
if os.path.isfile(p):
myzip.write(p, src)
for a in soup.find_all("a"):
try:
ao = a['href']
aa = urllib.parse.urljoin(e.cavelist()[0].url.rpartition("/")[0] + "/", ao)
a['href'] = urllib.parse.urljoin("https://expo.survex.com/", aa)
print(e.cavelist()[0].url.rpartition("/")[0] + "/", ao, a['href'])
except:
pass
html = mark_safe(soup.prettify("utf-8").decode("utf-8"))
size = {True: "large", False:"small"}[bool(set(e.cavelist()) & notablecaves)]
entrances.append(loader.get_template("entrance.kml").render({"entrance": e, "html": html, "size": size}, request))
s = loader.get_template("expo.kml").render({"entrances": entrances}, request)
myzip.writestr("expo.kml", s)
for f in os.listdir(settings.KMZ_ICONS_PATH):
p = os.path.join(settings.KMZ_ICONS_PATH, f)
if os.path.isfile(p):
myzip.write(p, os.path.join("icons", f))
return FileResponse(open(zippath, 'rb'), content_type="application/vnd.google-earth.kmz .kmz")