mirror of
https://expo.survex.com/repositories/troggle/.git
synced 2026-03-25 10:58:50 +00:00
stop print msgs many
This commit is contained in:
@@ -60,7 +60,7 @@ def get_cave_from_slug(caveslug):
|
||||
"""
|
||||
caves = []
|
||||
|
||||
print(f"get_cave_from_slug(): {caveslug} ...")
|
||||
# print(f"get_cave_from_slug(): {caveslug} ...")
|
||||
areacode = caveslug[:4] # e.g. 1623
|
||||
id = caveslug[5:] # e.g. 161 or 2023-MM-02
|
||||
thisarea = Cave.objects.filter(areacode=areacode)
|
||||
@@ -68,31 +68,31 @@ def get_cave_from_slug(caveslug):
|
||||
caves_k = thisarea.filter(kataster_number=id)
|
||||
if len(caves_k) == 1:
|
||||
caves.append(caves_k[0])
|
||||
print(f"get_cave_from_slug(): {caves_k=} {len(caves_k)=}")
|
||||
# print(f"get_cave_from_slug(): {caves_k=} {len(caves_k)=}")
|
||||
|
||||
caves_id = thisarea.filter(unofficial_number=id)
|
||||
if len(caves_id) == 1:
|
||||
caves.append(caves_id[0])
|
||||
print(f"get_cave_from_slug(): {caves_id=} {len(caves_id)=}")
|
||||
# print(f"get_cave_from_slug(): {caves_id=} {len(caves_id)=}")
|
||||
|
||||
if len(caves) > 1:
|
||||
print(f"get_cave_from_slug(): {caveslug} More than 1 \n{caves}")
|
||||
# print(f"get_cave_from_slug(): {caveslug} More than 1 \n{caves}")
|
||||
return None
|
||||
if len(caves) <1:
|
||||
print(f"get_cave_from_slug(): {caveslug} Nowt found..")
|
||||
# print(f"get_cave_from_slug(): {caveslug} Nowt found..")
|
||||
return None
|
||||
cave = caves[0]
|
||||
print(f"get_cave_from_slug(): {caveslug} FOUND {cave}")
|
||||
# print(f"get_cave_from_slug(): {caveslug} FOUND {cave}")
|
||||
return cave
|
||||
|
||||
|
||||
try:
|
||||
cave_zero = Cave.objects.get(caveslug__slug=caveslug)
|
||||
print(f"Getting cave from '{caveslug}'")
|
||||
if cave_zero != cave:
|
||||
print(f"get_cave_from_slug(): {caveslug} BAD DISCREPANCY {cave_zero=} {cave=}")
|
||||
else:
|
||||
print(f"get_cave_from_slug(): {caveslug} SUCCESS")
|
||||
# print(f"Getting cave from '{caveslug}'")
|
||||
# if cave_zero != cave:
|
||||
# print(f"get_cave_from_slug(): {caveslug} BAD DISCREPANCY {cave_zero=} {cave=}")
|
||||
# else:
|
||||
# print(f"get_cave_from_slug(): {caveslug} SUCCESS")
|
||||
|
||||
return cave_zero
|
||||
except:
|
||||
@@ -191,15 +191,17 @@ def getnotablecaves():
|
||||
cave = Cave.objects.get(kataster_number=kataster_number, areacode="1623")
|
||||
notablecaves.append(cave)
|
||||
except:
|
||||
print(" ! Notable Caves: FAILED to get only one cave per kataster_number OR invalid number for: 1623-"+kataster_number)
|
||||
pass
|
||||
# print(" ! Notable Caves: FAILED to get only one cave per kataster_number OR invalid number for: 1623-"+kataster_number)
|
||||
|
||||
for kataster_number in settings.NOTABLECAVES1626:
|
||||
try:
|
||||
cave = Cave.objects.get(kataster_number=kataster_number, areacode="1626")
|
||||
notablecaves.append(cave)
|
||||
except:
|
||||
print(" ! Notable Caves: FAILED to get only one cave per kataster_number OR invalid number for: 1626-"+kataster_number)
|
||||
print(notablecaves)
|
||||
pass
|
||||
# print(" ! Notable Caves: FAILED to get only one cave per kataster_number OR invalid number for: 1626-"+kataster_number)
|
||||
# print(notablecaves)
|
||||
return notablecaves
|
||||
|
||||
def caves_undropped_gpx(request):
|
||||
@@ -414,9 +416,10 @@ def file3d(request, cave, cave_id):
|
||||
op3dlog = Path(op3d.with_suffix(".log"))
|
||||
|
||||
if not op3d.is_file():
|
||||
print(f" - - Regeneration FAILED\n - - from '{survexpath}'\n - - to '{op3d}'")
|
||||
print(" - - Regeneration stdout: ", completed_process.stdout)
|
||||
print(" - - Regeneration cavern log output: ", op3dlog.read_text())
|
||||
pass
|
||||
# print(f" - - Regeneration FAILED\n - - from '{survexpath}'\n - - to '{op3d}'")
|
||||
# print(" - - Regeneration stdout: ", completed_process.stdout)
|
||||
# print(" - - Regeneration cavern log output: ", op3dlog.read_text())
|
||||
|
||||
def return3d(threedpath, cave):
|
||||
newfilename = cave.slug() + ".3d" # add the "1623-" part of the filename effectively.
|
||||
@@ -473,7 +476,7 @@ def rendercave(request, cave, slug, cave_id=""):
|
||||
except:
|
||||
svx3d = ""
|
||||
svxstem = ""
|
||||
print(f" ! rendercave: slug:'{slug}' FAIL TO MANAGE survex file:'{cave.survex_file}'")
|
||||
# print(f" ! rendercave: slug:'{slug}' FAIL TO MANAGE survex file:'{cave.survex_file}'")
|
||||
# NOTE the template itself loads the 3d file using javascript before it loads anything else.
|
||||
# Django cannot see what this javascript is doing, so we need to ensure that the 3d file exists first.
|
||||
# So only do this render if a valid .3d file exists. TO BE DONE
|
||||
@@ -523,7 +526,7 @@ def cavepage(request, karea=None, subpath=None):
|
||||
|
||||
"""
|
||||
if not subpath or subpath=='/':
|
||||
print(f"{karea=} {subpath=} ")
|
||||
# print(f"{karea=} {subpath=} ")
|
||||
return render(request, "pagenotfound.html", {"path": f"{karea}/{subpath}"}, status=404)
|
||||
# lack of validation for karea, 162x
|
||||
# subpath has an initial /
|
||||
@@ -546,7 +549,7 @@ def cavepage(request, karea=None, subpath=None):
|
||||
parts = subpath.strip("/").split("/")
|
||||
if len(parts) > 5:
|
||||
# recursive loop. break out of it.
|
||||
print(karea,subpath)
|
||||
# print(karea,subpath)
|
||||
subparts = parts[0].split(".")
|
||||
caveid = subparts[0]
|
||||
slug = f"{karea}-{caveid}"
|
||||
@@ -566,7 +569,7 @@ def cavepage(request, karea=None, subpath=None):
|
||||
if len(parts) == 1:
|
||||
# either need to insert caveid OR leave as relative link as we are already "in" /1623/nn/
|
||||
# if we are doing a cave description file
|
||||
print("SIMPLE", subpath, parts)
|
||||
# print("SIMPLE", subpath, parts)
|
||||
subparts = parts[0].split(".")
|
||||
caveid = subparts[0] # e.g. 204.htm => "204"
|
||||
k2path = karea +"/"+ caveid + subpath
|
||||
@@ -609,12 +612,12 @@ def edit_cave(request, path="", slug=None):
|
||||
See class CaveForm(ModelForm) in troggle/core/forms.py
|
||||
"""
|
||||
|
||||
print(f"edit_cave(): {path=} {slug=}")
|
||||
# print(f"edit_cave(): {path=} {slug=}")
|
||||
message = ""
|
||||
if slug is None:
|
||||
cave = Cave() # create a New Cave
|
||||
else:
|
||||
print(f"{slug=}")
|
||||
# print(f"{slug=}")
|
||||
if not (cave:= get_cave_from_slug(slug)): # walrus operator
|
||||
return render(request, "errors/badslug.html", {"badslug": f"for cave {slug} - from edit_cave()"})
|
||||
|
||||
@@ -624,7 +627,7 @@ def edit_cave(request, path="", slug=None):
|
||||
if request.POST:
|
||||
form = CaveForm(request.POST, instance=cave)
|
||||
if form.is_valid():
|
||||
print(f'edit_cave(): POST is valid. Editing {cave}')
|
||||
# print(f'edit_cave(): POST is valid. Editing {cave}')
|
||||
editor = form.cleaned_data["who_are_you"]
|
||||
editor = git_string(editor)
|
||||
cave = form.save(commit=False)
|
||||
@@ -664,20 +667,20 @@ def edit_cave(request, path="", slug=None):
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
except:
|
||||
raise
|
||||
print(f"Returning response now, which should set cookie on client browser")
|
||||
# print(f"Returning response now, which should set cookie on client browser")
|
||||
return edit_response
|
||||
|
||||
# if a GET; and also falls-through from the POST handling to refresh the page
|
||||
else:
|
||||
if slug is not None:
|
||||
# re-read cave data from file.
|
||||
print(f"edit_cave(): {cave=} {cave.filename=}")
|
||||
print(f"edit_cave(): {cave.slug()=}")
|
||||
# print(f"edit_cave(): {cave=} {cave.filename=}")
|
||||
# print(f"edit_cave(): {cave.slug()=}")
|
||||
if cave.filename:
|
||||
try:
|
||||
read_cave(cave.filename, cave=cave)
|
||||
except Exception as e:
|
||||
print(f"edit_cave(): EXCEPTION attempting to read_cave({cave.filename})\n{e}")
|
||||
# print(f"edit_cave(): EXCEPTION attempting to read_cave({cave.filename})\n{e}")
|
||||
raise
|
||||
|
||||
form = CaveForm(instance=cave, initial={'cave_slug': cave.slug(), "identified_login": identified_login, "who_are_you":editor})
|
||||
@@ -746,7 +749,7 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
nents = Entrance.objects.filter(slug=slugname).count()
|
||||
if not (c:= get_cave_from_slug(slug)): # walrus operator
|
||||
return False
|
||||
print(f"check_new_slugname_ok() {slugname=} {letter=} => {nents}=(number of entrances) ")
|
||||
# print(f"check_new_slugname_ok() {slugname=} {letter=} => {nents}=(number of entrances) ")
|
||||
if nents == 0:
|
||||
# looks good, but we need to check the CaveaAndEntrance object too
|
||||
e = entrance #Entrance.objects.get(slug=slugname) # does not exist yet!
|
||||
@@ -780,7 +783,7 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
entrance = None
|
||||
|
||||
if entslug:
|
||||
print(f"Edit Entrance {caveslug=} {entslug=} {path=} number of ents:{cave.entrances().count()}")
|
||||
# print(f"Edit Entrance {caveslug=} {entslug=} {path=} number of ents:{cave.entrances().count()}")
|
||||
caveAndEntrance = CaveAndEntrance.objects.get(entrance=entrance, cave=cave)
|
||||
entlettereditable = False
|
||||
else:
|
||||
@@ -793,19 +796,19 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
# but it doesn't trigger the entrance letter form unless entletter has a value
|
||||
entlettereditable = True # but the user has to remember to actually set it...
|
||||
|
||||
print(f"{entlettereditable=}")
|
||||
# print(f"{entlettereditable=}")
|
||||
# if the entletter is not editable, then the entletterform does not appear and so is always invalid.
|
||||
|
||||
print(f"{caveslug=}")
|
||||
print(f"{cave=}")
|
||||
# print(f"{caveslug=}")
|
||||
# print(f"{cave=}")
|
||||
imgpath = Path(path) / cave.areacode / cave.number()
|
||||
print(f"Edit Entrance {imgpath=}")
|
||||
# print(f"Edit Entrance {imgpath=}")
|
||||
|
||||
identified_login = is_identified_user(request.user)
|
||||
editor = get_editor(request)
|
||||
|
||||
if request.POST:
|
||||
print(f"POST Online edit of entrance: '{entrance}' where {cave=}")
|
||||
# print(f"POST Online edit of entrance: '{entrance}' where {cave=}")
|
||||
entform = EntranceForm(request.POST, instance=entrance)
|
||||
|
||||
if not entlettereditable:
|
||||
@@ -816,12 +819,12 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
ce = entletterform.save(commit=False)
|
||||
entranceletter = entletterform.cleaned_data["entranceletter"]
|
||||
message = f"- POST valid {caveslug=} {entslug=} {path=} entletterform valid \n {entletterform=}."
|
||||
print(message)
|
||||
# print(message)
|
||||
else:
|
||||
# maybe this doesn't matter? It just means entranceletter unset ?
|
||||
# probably because 'Cave and entrance with this Cave and Entranceletter already exists.'
|
||||
message = f"- POST INVALID {caveslug=} {entslug=} {path=} entletterform invalid \n{entletterform.errors=}\n{entletterform=}."
|
||||
print(message)
|
||||
# print(message)
|
||||
# if entletterform.errors:
|
||||
# for field in entletterform:
|
||||
# for error in field.errors:
|
||||
@@ -832,11 +835,11 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
if not entform.is_valid():
|
||||
message = f"- POST INVALID {caveslug=} {entslug=} {path=} entform valid:{entform.is_valid()} "
|
||||
# entrance = entform.save(commit=False)
|
||||
print(message)
|
||||
# print(message)
|
||||
# return render(request, "errors/generic.html", {"message": message})
|
||||
else:
|
||||
|
||||
print(f"'edit_entrance(): POST is valid {caveslug=} Editing {entslug=} {entranceletter=} {path=}")
|
||||
# print(f"'edit_entrance(): POST is valid {caveslug=} Editing {entslug=} {entranceletter=} {path=}")
|
||||
editor = entform.cleaned_data["who_are_you"]
|
||||
editor = git_string(editor)
|
||||
if entslug is None:
|
||||
@@ -852,7 +855,7 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
ce.entranceletter = letter
|
||||
|
||||
except Exception as e:
|
||||
print(f"- EXCEPTION entranceletter {caveslug=} {entslug=} {entranceletter=} {path=}\n{e}")
|
||||
# print(f"- EXCEPTION entranceletter {caveslug=} {entslug=} {entranceletter=} {path=}\n{e}")
|
||||
raise
|
||||
entrance.slug = slugname
|
||||
entrance.cached_primary_slug = slugname
|
||||
@@ -864,15 +867,15 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
entrance.filename = entslug + ".html"
|
||||
try:
|
||||
entrance.save()
|
||||
print(f"- post {entrance.slug=} {entrance.tag_station=} {entrance.other_station=}")
|
||||
# print(f"- post {entrance.slug=} {entrance.tag_station=} {entrance.other_station=}")
|
||||
except Exception as e:
|
||||
# fails with uniqueness constraint failure. Which is on CaveAndEntrance, not just on entrance,
|
||||
# which is confusing to a user who is just editing an Entrance.
|
||||
# Can happen when user specifies an existing letter! (or none, when they should set one)
|
||||
print(f"SAVE EXCEPTION FAIL {entrance=}")
|
||||
print(f"CAVE {cave}\n{e}")
|
||||
for ce in cave.entrances():
|
||||
print(f"CAVE:{ce.cave} - ENT:{ce.entrance} - LETTER:'{ce.entranceletter}'")
|
||||
# print(f"SAVE EXCEPTION FAIL {entrance=}")
|
||||
# print(f"CAVE {cave}\n{e}")
|
||||
# for ce in cave.entrances():
|
||||
# print(f"CAVE:{ce.cave} - ENT:{ce.entrance} - LETTER:'{ce.entranceletter}'")
|
||||
raise
|
||||
ce.entrance = entrance
|
||||
# try not to invoke this:
|
||||
@@ -883,7 +886,7 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
cave_file = cave.file_output()
|
||||
|
||||
|
||||
print(f"- POST WRITE letter: '{ce}' {entrance=}")
|
||||
# print(f"- POST WRITE letter: '{ce}' {entrance=}")
|
||||
try:
|
||||
write_and_commit([entrance_file, cave_file], f"Online edit of entrance {entrance.slug}", editor)
|
||||
edit_response = HttpResponseRedirect("/" + cave.url)
|
||||
@@ -893,23 +896,23 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
efilepath, econtent, eencoding = entrance_file
|
||||
cfilepath, ccontent, cencoding = cave_file
|
||||
message = f"- FAIL write_and_commit \n entr:'{efilepath}'\n cave:'{cfilepath}'\n\n{e}"
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
# Unlike other similar forms, we do NOT drop into this GET code after processing the POST
|
||||
else: # GET the page, not POST, or if either of the forms were invalid when POSTed
|
||||
entletterform = None
|
||||
entletter = ""
|
||||
print(f"ENTRANCE in db: entranceletter = '{ce.entranceletter}'")
|
||||
# print(f"ENTRANCE in db: entranceletter = '{ce.entranceletter}'")
|
||||
if entrance:
|
||||
# re-read entrance data from file.
|
||||
filename = str(entrance.slug +".html")
|
||||
try:
|
||||
ent = read_entrance(filename, ent=entrance)
|
||||
print(f"ENTRANCE from file: entranceletter = '{ce.entranceletter}'")
|
||||
# print(f"ENTRANCE from file: entranceletter = '{ce.entranceletter}'")
|
||||
except:
|
||||
# ent only in db not on file. Interesting, let's run with it using whatever we have in the db
|
||||
print(f"ENTRANCE NOT read from file: entranceletter = '{ce.entranceletter}'")
|
||||
# print(f"ENTRANCE NOT read from file: entranceletter = '{ce.entranceletter}'")
|
||||
|
||||
entform = EntranceForm(instance=entrance, initial={"identified_login": identified_login, "who_are_you":editor})
|
||||
if entslug is None:
|
||||
@@ -919,8 +922,8 @@ def edit_entrance(request, path="", caveslug=None, entslug=None):
|
||||
entletter = ce.entranceletter
|
||||
if entletter == "":
|
||||
entletterform = EntranceLetterForm()
|
||||
print(f" Blank value: getting entletter from EntranceLetterForm")
|
||||
print(f"{entletter=} ")
|
||||
# print(f" Blank value: getting entletter from EntranceLetterForm")
|
||||
# print(f"{entletter=} ")
|
||||
else:
|
||||
entform = EntranceForm(initial={"identified_login": identified_login, "who_are_you":editor})
|
||||
entletterform = EntranceLetterForm()
|
||||
@@ -967,7 +970,7 @@ def cave_debug(request):
|
||||
|
||||
def caveslist(request):
|
||||
caves = Cave.objects.all()
|
||||
print("CAVESLIST")
|
||||
# print("CAVESLIST")
|
||||
return render(
|
||||
request,
|
||||
"caveslist.html",
|
||||
@@ -1047,8 +1050,8 @@ def qm(request, cave_id, qm_id, year, grade=None, blockname=None):
|
||||
manyqms = c.get_open_QMs() | c.get_ticked_QMs() # set union operation
|
||||
qmqs = manyqms.filter(expoyear=year, blockname=blockname, number=qm_id, grade=grade)
|
||||
if len(qmqs) > 1:
|
||||
for q in qmqs:
|
||||
print(qmqs)
|
||||
# for q in qmqs:
|
||||
# print(qmqs)
|
||||
message = f"Multiple QMs with the same cave, year, number, grade AND first-several+terminal chars of the survexblock name. (Could be caused by incomplete databasereset). Fix this in the survex file(s). {cave_id=} {year=} {qm_id=} {blockname=}"
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
else:
|
||||
@@ -1112,7 +1115,7 @@ def expo_kmz(request):
|
||||
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'])
|
||||
# print(e.cavelist()[0].url.rpartition("/")[0] + "/", ao, a['href'])
|
||||
except:
|
||||
pass
|
||||
html = mark_safe(soup.prettify("utf-8").decode("utf-8"))
|
||||
|
||||
@@ -65,7 +65,7 @@ def image_selector(request, path):
|
||||
templates/html_editor_scripts_css.html: $('#image_popup_content').load("{% url 'image_selector' path %}" + path, function() {
|
||||
"""
|
||||
directory = get_dir(path)
|
||||
print(f" - image selector {directory=} {path=}")
|
||||
# print(f" - image selector {directory=} {path=}")
|
||||
thumbnailspath = Path(settings.EXPOWEB) / directory / "t"
|
||||
thumbnails = []
|
||||
if thumbnailspath.is_dir():
|
||||
@@ -141,7 +141,7 @@ def extract_gps(dict):
|
||||
def is_present(gpsifd):
|
||||
item = getattr(piexif.GPSIFD, gpsifd)
|
||||
if item in dict:
|
||||
print(f" {gpsifd} = id '{item}'")
|
||||
# print(f" {gpsifd} = id '{item}'")
|
||||
return dict[item]
|
||||
return None
|
||||
|
||||
@@ -183,7 +183,8 @@ def extract_gps(dict):
|
||||
direction = ""
|
||||
|
||||
if version := is_present("GPSVersionID"):
|
||||
print(f"GPS exif {version=}")
|
||||
pass
|
||||
# print(f"GPS exif {version=}")
|
||||
|
||||
if alt := extract("GPSAltitude"):
|
||||
altitude = f"{alt:.0f}m above sea-level"
|
||||
@@ -205,7 +206,7 @@ def extract_gps(dict):
|
||||
else:
|
||||
timestamp_utc = f"{ds}"
|
||||
|
||||
print(f"attempting latitude")
|
||||
# print(f"attempting latitude")
|
||||
if ref := is_present("GPSLatitudeRef"):
|
||||
latref = ref.decode()
|
||||
else:
|
||||
@@ -214,13 +215,14 @@ def extract_gps(dict):
|
||||
if item := is_present("GPSLatitude"):
|
||||
d, m, s = rationalise(item)
|
||||
latitude = f"{d:02.0f}:{m:02.0f}:{s:02.0f} {latref}"
|
||||
print(f"{latitude=}")
|
||||
# print(f"{latitude=}")
|
||||
latitude = dms2dd(d, m, s, latref)
|
||||
print(f"{latitude=}")
|
||||
# print(f"{latitude=}")
|
||||
else:
|
||||
print("failed to find latitude")
|
||||
pass
|
||||
# print("failed to find latitude")
|
||||
|
||||
print(f"attempting logitude")
|
||||
# print(f"attempting logitude")
|
||||
if ref := is_present("GPSLongitudeRef"):
|
||||
lonref = ref.decode()
|
||||
else:
|
||||
@@ -229,23 +231,24 @@ def extract_gps(dict):
|
||||
if item := is_present("GPSLongitude"):
|
||||
d, m, s = rationalise(item)
|
||||
longitude = f"{d:02.0f}:{m:02.0f}:{s:02.0f} {lonref}"
|
||||
print(f"{longitude=}")
|
||||
# print(f"{longitude=}")
|
||||
longitude = dms2dd(d, m, s, lonref)
|
||||
print(f"{longitude=}")
|
||||
# print(f"{longitude=}")
|
||||
else:
|
||||
print("failed to find longitude")
|
||||
pass
|
||||
# print("failed to find longitude")
|
||||
|
||||
if latitude and longitude:
|
||||
# 3 digits for longitude (0-359) or +/-(0-180), 2 for latitude +/-(0-90)
|
||||
# we might want to rectify longitude to be always +(0-359) not +/- 180 ?
|
||||
location = f'<a href="https://www.openstreetmap.org/?mlat={latitude}&mlon={longitude}">{latitude:09.6f} {latref}, {longitude:010.6f} {lonref}</a>'
|
||||
print(location)
|
||||
# print(location)
|
||||
else:
|
||||
location = ""
|
||||
|
||||
print(direction)
|
||||
print(altitude)
|
||||
print(timestamp_utc)
|
||||
# print(direction)
|
||||
# print(altitude)
|
||||
# print(timestamp_utc)
|
||||
# location = dms2dd() # to do...
|
||||
rotate_this = f"?to_be_rotated" # this should rotate the i/ and t/ images and then re-render the same page.
|
||||
rotate_button = f"<br /><a href='{rotate_this}'><b>↺</b> </a>rotate this image"
|
||||
@@ -262,13 +265,13 @@ def fix_dump_bugs(exif_dict):
|
||||
if 41729 in exif_dict['Exif'] and isinstance(exif_dict['Exif'][41729], int):
|
||||
# SceneType = 1 for a directly photogrpahed image
|
||||
cc = exif_dict['Exif'][41729]
|
||||
print(f"PIEXIF BUG workaround: 41729 {cc} is {type(cc)}")
|
||||
# print(f"PIEXIF BUG workaround: 41729 {cc} is {type(cc)}")
|
||||
exif_dict['Exif'][41729] = str(exif_dict['Exif'][41729]).encode('utf-8')
|
||||
|
||||
if 37121 in exif_dict['Exif']:
|
||||
cc = exif_dict['Exif'][37121]
|
||||
if isinstance(cc, tuple):
|
||||
print(f"PIEXIF BUG workaround: 37121 {cc} is {type(cc)}")
|
||||
# print(f"PIEXIF BUG workaround: 37121 {cc} is {type(cc)}")
|
||||
exif_dict['Exif'][37121] = ",".join([str(v) for v in cc]).encode("ASCII")
|
||||
# if 37380 in exif_dict['Exif']:
|
||||
# # exposure bias
|
||||
@@ -284,7 +287,7 @@ def fix_dump_bugs(exif_dict):
|
||||
rational = f"({cc * 1000:.0f}, 1000)"
|
||||
else:
|
||||
rational = f"(1000, {cc * 1000:.0f})"
|
||||
print(f"PIEXIF BUG workaround: 50728 {cc} is {type(cc)} - using {rational}")
|
||||
# print(f"PIEXIF BUG workaround: 50728 {cc} is {type(cc)} - using {rational}")
|
||||
exif_dict['Exif'][50728] = rational
|
||||
|
||||
return exif_dict
|
||||
@@ -314,7 +317,7 @@ def new_image_form(request, path):
|
||||
if identified_login:
|
||||
# disable editing the git id string as we get it from the logged-on user data
|
||||
form.fields["who_are_you"].widget.attrs["readonly"]="readonly"
|
||||
print(form.fields["who_are_you"].widget.attrs)
|
||||
# print(form.fields["who_are_you"].widget.attrs)
|
||||
|
||||
if form.is_valid():
|
||||
# print(f"new_image_form(): form is valid ")
|
||||
@@ -325,7 +328,7 @@ def new_image_form(request, path):
|
||||
title = form.cleaned_data["header"]
|
||||
referer = request.headers["Referer"] # original
|
||||
host = request.headers["Host"]
|
||||
print(f"{host=}")
|
||||
# print(f"{host=}")
|
||||
f = request.FILES["file_"]
|
||||
if not title:
|
||||
title = f.name
|
||||
@@ -338,7 +341,7 @@ def new_image_form(request, path):
|
||||
exif_dict = piexif.load(i.info["exif"])
|
||||
if "GPS" in exif_dict:
|
||||
gps_data = exif_dict['GPS']
|
||||
print(f"new_image_form() EXIF loaded from {f.name}\n {gps_data=}")
|
||||
# print(f"new_image_form() EXIF loaded from {f.name}\n {gps_data=}")
|
||||
gps_annotations = extract_gps(gps_data)
|
||||
descrip += gps_annotations
|
||||
i = reorient_image(i, exif_dict)
|
||||
@@ -363,7 +366,8 @@ def new_image_form(request, path):
|
||||
try:
|
||||
i = i.resize((int(width / scale), int(height / scale)), Image.LANCZOS)
|
||||
except Exception as e:
|
||||
print(f"new_image_form(): rescaling exception: {e} ")
|
||||
pass
|
||||
# print(f"new_image_form(): rescaling exception: {e} ")
|
||||
|
||||
# print(f"new_image_form(): rescaled ")
|
||||
tscale = max(width / THUMBNAIL_WIDTH, height / THUMBNAIL_HEIGHT)
|
||||
@@ -378,7 +382,7 @@ def new_image_form(request, path):
|
||||
try:
|
||||
exif_bytes = piexif.dump(fix_dump_bugs(exif_dict))
|
||||
except Exception as e:
|
||||
print(f"EXCEPTION {e}\n {exif_dict=}\n {gps_data=}")
|
||||
# print(f"EXCEPTION {e}\n {exif_dict=}\n {gps_data=}")
|
||||
raise
|
||||
i.save(ib, format='JPEG', quality = IMAGE_QUALITY, exif=exif_bytes)
|
||||
|
||||
@@ -420,10 +424,10 @@ def new_image_form(request, path):
|
||||
editor # this works, a new who_are_you typed on the Image form is used as the git comment
|
||||
)
|
||||
except WriteAndCommitError as e:
|
||||
print(f"new_image_form(): WriteAndCommitError: {e}")
|
||||
# print(f"new_image_form(): WriteAndCommitError: {e}")
|
||||
return JsonResponse({"error": e})
|
||||
except Exception as e:
|
||||
print(f"new_image_form(): EXCEPTION: {e}")
|
||||
# print(f"new_image_form(): EXCEPTION: {e}")
|
||||
return JsonResponse({"error": e})
|
||||
|
||||
linked_image_template = loader.get_template("linked_image_template.html")
|
||||
@@ -443,7 +447,7 @@ def new_image_form(request, path):
|
||||
if identified_login:
|
||||
# disable editing the git id string as we get it from the logged-on user data
|
||||
form.fields["who_are_you"].widget.attrs["readonly"]="readonly"
|
||||
print(form.fields["who_are_you"].widget.attrs)
|
||||
# print(form.fields["who_are_you"].widget.attrs)
|
||||
|
||||
# print(f"new_image_form(): POST and not POST ")
|
||||
template = loader.get_template("new_image_form.html")
|
||||
@@ -482,24 +486,25 @@ def save_original_in_expofiles(f, year, photographer, host, handbook_directory,
|
||||
write_url_file(filepath, host, handbook_directory, page)
|
||||
elif isinstance(f, TemporaryUploadedFile):
|
||||
if filepath.is_file:
|
||||
print(f"+++++ Out of cheese error\n Destination EXISTS {filepath}")
|
||||
# print(f"+++++ Out of cheese error\n Destination EXISTS {filepath}")
|
||||
tail = random_slug(str(filepath), 2)
|
||||
newname = f"{filepath.stem}_{tail}{filepath.suffix}"
|
||||
filepath = filepath.parent / newname
|
||||
print(f"+++++ The turtle moves\n Attempting to use {filepath}")
|
||||
# print(f"+++++ The turtle moves\n Attempting to use {filepath}")
|
||||
if Path(f.temporary_file_path()).is_file:
|
||||
# print(f"+++++ Found {f.temporary_file_path()}")
|
||||
try:
|
||||
dest = shutil.move(f.temporary_file_path(), filepath)
|
||||
write_url_file(filepath, host, handbook_directory, page)
|
||||
except Exception as e:
|
||||
print("+++++ ",e)
|
||||
# print("+++++ ",e)
|
||||
raise
|
||||
else:
|
||||
pass
|
||||
print(f"+++++ Out of cheese error\n Can't find {f.temporary_file_path()}")
|
||||
else:
|
||||
msg = f"Unknown uploaded file type: {f}, should be a temporary file or in-memory."
|
||||
print(msg)
|
||||
# print(msg)
|
||||
raise TypeError(msg)
|
||||
return
|
||||
|
||||
@@ -515,7 +520,7 @@ def write_url_file(targetpath, host, handbook_rel_path, page):
|
||||
# FIND AND FIX the correct host for this !
|
||||
content = f"[InternetShortcut]\nURL={page}\n\n[TroggleImage]\nURL=http://{host}/{handbook_rel_path}"
|
||||
content = content.replace("localhost:8000", "expo.survex.com")
|
||||
print(content)
|
||||
# print(content)
|
||||
filepath = targetpath.with_suffix(".url")
|
||||
write_files([(filepath, content, "utf8")])
|
||||
|
||||
|
||||
@@ -79,11 +79,11 @@ def mapfile(request, path):
|
||||
"""Serves unadorned file: everything in the /map/... folder tree"""
|
||||
fn = Path(settings.EXPOWEB, "map", path)
|
||||
if fn.is_file():
|
||||
print(f"MAP cuttout. \n{path=}\n{fn=} mime:{getmimetype(fn)}")
|
||||
# print(f"MAP cuttout. \n{path=}\n{fn=} mime:{getmimetype(fn)}")
|
||||
return HttpResponse(content=open(fn, "r"), content_type=getmimetype(fn))
|
||||
else:
|
||||
message = f"### File not found ### {fn}"
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
|
||||
@@ -148,7 +148,7 @@ def pubspage(request):
|
||||
This is a placeholder, we need to do something like what is done in indexpage() below...
|
||||
"""
|
||||
expowebpath = Path(settings.EXPOWEB)
|
||||
print("--redirecting from pubspage()")
|
||||
# print("--redirecting from pubspage()")
|
||||
return expowebpage(request, expowebpath, "pubs.htm")
|
||||
|
||||
def indexpage(request):
|
||||
@@ -157,7 +157,7 @@ def indexpage(request):
|
||||
This edits the most recent year on the fly..
|
||||
This now works.
|
||||
"""
|
||||
print("--redirecting from indexpage()")
|
||||
# print("--redirecting from indexpage()")
|
||||
subpath = Path(settings.EXPOWEB) / "index00.htm"
|
||||
with open(subpath, "r") as o:
|
||||
html = o.read()
|
||||
@@ -172,7 +172,7 @@ def expowebpage(request, expowebpath, path):
|
||||
|
||||
if not Path(expowebpath / path).is_file():
|
||||
# Should not get here if the path has suffix "_edit"
|
||||
print(f" - 404 error in expowebpage() {Path(expowebpath / path)}")
|
||||
# print(f" - 404 error in expowebpage() {Path(expowebpath / path)}")
|
||||
return render(request, "pagenotfound.html", {"path": path}, status=404)
|
||||
|
||||
# print(f' - {sys_getfilesystemencoding()=}')
|
||||
@@ -427,7 +427,7 @@ def editexpopage(request, path):
|
||||
except Cave.DoesNotExist:
|
||||
pass
|
||||
|
||||
print(f" - {sys_getfilesystemencoding()=}")
|
||||
# print(f" - {sys_getfilesystemencoding()=}")
|
||||
if sys_getfilesystemencoding() != "utf-8":
|
||||
return HttpResponse(
|
||||
default_head
|
||||
@@ -437,7 +437,7 @@ def editexpopage(request, path):
|
||||
# detect if this is a text file for editing
|
||||
filepath = Path(settings.EXPOWEB) / path
|
||||
if filepath.suffix in [".txt", ".sty", ".tex"] or filepath.name == "Makefile" or filepath.name == "cave-number-index":
|
||||
print("Editing TEXT file", filepath)
|
||||
# print("Editing TEXT file", filepath)
|
||||
return edittxtpage(request, path, filepath)
|
||||
|
||||
try:
|
||||
@@ -461,7 +461,7 @@ def editexpopage(request, path):
|
||||
+ "<h3>HTML Parsing failure:<br>Page could not be parsed into header and body:<br>failure detected in expowebpage in views.expo.py</h3> Please edit this <var>:expoweb:</var> page to be in the expected full HTML format .</body>"
|
||||
)
|
||||
except IOError:
|
||||
print("### File not found ### ", filepath)
|
||||
# print("### File not found ### ", filepath)
|
||||
filefound = False
|
||||
|
||||
identified_login = is_identified_user(request.user)
|
||||
@@ -499,13 +499,13 @@ def editexpopage(request, path):
|
||||
if not filefound or result != html: # Check if content changed at all
|
||||
edit_response = HttpResponseRedirect(reverse("expopage", args=[path])) # Redirect after POST
|
||||
edit_response.set_cookie('editor_id', editor, max_age=get_cookie_max_age(request)) # cookie expires after get_cookie_max_age(request) seconds
|
||||
print(f"Cookie set: {editor} for {get_cookie_max_age(request)/(3600)} hour(s)")
|
||||
# print(f"Cookie set: {editor} for {get_cookie_max_age(request)/(3600)} hour(s)")
|
||||
try:
|
||||
change_message = pageform.cleaned_data["change_message"]
|
||||
write_and_commit([(filepath, result, "utf-8")], f"{change_message} - online edit of {path}", editor)
|
||||
except WriteAndCommitError as e:
|
||||
return render(request, "errors/generic.html", {"message": e.message})
|
||||
print(f"Returning response now, which should set cookie on client browser")
|
||||
# print(f"Returning response now, which should set cookie on client browser")
|
||||
return edit_response
|
||||
else:
|
||||
if filefound:
|
||||
@@ -536,7 +536,7 @@ def edittxtpage(request, path, filepath):
|
||||
Yes this is a security hazard as arbitrary text can be uploaded and it is not enclosed in any HTML furniture.
|
||||
"""
|
||||
def simple_get(viewtext):
|
||||
print(f"simple_get {editor=}")
|
||||
# print(f"simple_get {editor=}")
|
||||
form = ExpotextfileForm(initial={"identified_login": identified_login, "who_are_you":editor})
|
||||
if identified_login:
|
||||
# disable editing the git id string as we get it from the logged-on user data
|
||||
@@ -558,7 +558,7 @@ def edittxtpage(request, path, filepath):
|
||||
|
||||
if not filepath.is_file():
|
||||
message = f"File not found '{filepath}\n\nfailure detected in expowebpage() in views.expo.py"
|
||||
print(f"Not a file: {filepath}")
|
||||
# print(f"Not a file: {filepath}")
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
try:
|
||||
@@ -566,7 +566,7 @@ def edittxtpage(request, path, filepath):
|
||||
originaltext = f.read()
|
||||
except IOError:
|
||||
message = f'Cannot open {filepath} for text file reading even though it is a file.'
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
identified_login = is_identified_user(request.user)
|
||||
@@ -578,7 +578,7 @@ def edittxtpage(request, path, filepath):
|
||||
form = ExpotextfileForm(request.POST)
|
||||
if not form.is_valid():
|
||||
message = f'Invalid form response for text file editing "{request.POST}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
else:
|
||||
editor = form.cleaned_data["who_are_you"]
|
||||
@@ -588,32 +588,32 @@ def edittxtpage(request, path, filepath):
|
||||
# print(":: ",i, " => ", request.POST[i])
|
||||
newtext = request.POST["text"]
|
||||
|
||||
print("POST")
|
||||
# print("POST")
|
||||
if "Cancel" in request.POST:
|
||||
print("cancel")
|
||||
# print("cancel")
|
||||
return simple_get(originaltext)
|
||||
if "Save" in request.POST:
|
||||
print("submitted for saving..")
|
||||
# print("submitted for saving..")
|
||||
|
||||
# should insert sanitization in here
|
||||
# but user cannot rename the file, and cannot create new files
|
||||
# and this is only used for .txt files
|
||||
if newtext != originaltext: # Check if content has changed at all
|
||||
print("text changed.. saving and committing")
|
||||
# print("text changed.. saving and committing")
|
||||
try:
|
||||
write_and_commit([(filepath, newtext, "utf-8")], f"Online edit of {path}", editor)
|
||||
except WriteAndCommitError as e:
|
||||
return render(request, "errors/generic.html", {"message": e.message})
|
||||
|
||||
print("re-reading from file..")
|
||||
# print("re-reading from file..")
|
||||
try:
|
||||
with open(filepath) as f:
|
||||
rereadtext = f.read()
|
||||
except:
|
||||
print("### File reading failure, but it exists.. ### ", filepath)
|
||||
# print("### File reading failure, but it exists.. ### ", filepath)
|
||||
return render(request, "errors/generic.html", {"message": e.message})
|
||||
savepath = "/" + path
|
||||
print(f"redirect {savepath}")
|
||||
# print(f"redirect {savepath}")
|
||||
response = redirect(savepath) # Redirect after POST
|
||||
response.set_cookie('editor_id', editor, max_age=get_cookie_max_age(request)) # cookie expires after get_cookie_max_age(request) seconds
|
||||
return response
|
||||
@@ -625,7 +625,7 @@ def edittxtpage(request, path, filepath):
|
||||
else:
|
||||
# mistake not POST or GET
|
||||
message="Something went wrong"
|
||||
print(message)
|
||||
# print(message)
|
||||
return simple_get(originaltext)
|
||||
|
||||
class ExpoPageForm(forms.Form):
|
||||
|
||||
@@ -86,7 +86,7 @@ def fillblankpeople(w):
|
||||
|
||||
wp = w.people() # just a list of names as strings, direct from JSON.
|
||||
if not isinstance(wp, list): # might be None
|
||||
print(f"{w} NOT A LIST {type(wp)}: {wp}")
|
||||
# print(f"{w} NOT A LIST {type(wp)}: {wp}")
|
||||
populatewallet(w)
|
||||
return
|
||||
|
||||
@@ -116,13 +116,13 @@ def is_cave(wallet, id):
|
||||
# Historic wallets were all 1623 area. So, just for wallets,
|
||||
# assume it is 1623-xxx
|
||||
if f"1623-{id}" in Gcavelookup:
|
||||
print(f" - Should modify wallet {wallet} to use 1623- prefix for cave <{id}>")
|
||||
# print(f" - Should modify wallet {wallet} to use 1623- prefix for cave <{id}>")
|
||||
Gcavelookup[id] = Gcavelookup[f"1623-{id}"] # restoring an ambiguous alias, BAD idea.
|
||||
return True
|
||||
else:
|
||||
print(f" - Wallet {wallet} Failed to find cave object from id <{id}>")
|
||||
# print(f" - Wallet {wallet} Failed to find cave object from id <{id}>")
|
||||
if id.lower() != "unknown" and id != "":
|
||||
print(f" - adding <{id}> to pendingcaves DataIssues")
|
||||
# print(f" - adding <{id}> to pendingcaves DataIssues")
|
||||
add_cave_to_pending_list(id, wallet, f"Wallet {wallet} - Could not find cave id <{id}>")
|
||||
return False
|
||||
|
||||
@@ -181,7 +181,7 @@ def parse_name_list(w):
|
||||
else:
|
||||
wurl = f"/walletedit/{w.walletname.replace('#',':')}"
|
||||
message = f"{w} name '{n.lower()}' NOT found in GetPersonExpeditionNameLookup({w.year()}) n.startswith* = {check} ?!"
|
||||
print(message)
|
||||
# print(message)
|
||||
DataIssue.objects.update_or_create(parser="wallets", message=message, url=wurl)
|
||||
return peeps
|
||||
|
||||
@@ -234,7 +234,7 @@ def walletslistperson(request, slug):
|
||||
else:
|
||||
wurl = f"/walletedit/{w.walletname.replace('#',':')}"
|
||||
message = f"{w} name '{n.lower()}' NOT found in GetPersonExpeditionNameLookup({year}) ?!"
|
||||
print(message)
|
||||
# print(message)
|
||||
DataIssue.objects.update_or_create(parser="wallets", message=message, url=wurl)
|
||||
|
||||
fix_manywallets(manywallets)
|
||||
@@ -247,7 +247,7 @@ def walletslistperson(request, slug):
|
||||
expeditions = Expedition.objects.all()
|
||||
length_ug = 0.0
|
||||
for w in manywallets:
|
||||
print(f"{w}: no .persons in this wallet but people() is {w.people()}")
|
||||
# print(f"{w}: no .persons in this wallet but people() is {w.people()}")
|
||||
for sb in w.survexblock_set.all():
|
||||
length_ug += sb.legslength
|
||||
return render(
|
||||
@@ -262,7 +262,7 @@ def setwalletsdates():
|
||||
"""This sets all the undated wallets, but they should already all be dated on
|
||||
import or on edit"""
|
||||
wallets = Wallet.objects.filter(walletdate=None)
|
||||
print(f"undated wallets: {len(wallets)}")
|
||||
# print(f"undated wallets: {len(wallets)}")
|
||||
for w in wallets:
|
||||
w.walletdate = w.date()
|
||||
w.save()
|
||||
@@ -314,7 +314,7 @@ def walletslistyear(request, year):
|
||||
|
||||
def cavewallets(request, caveid):
|
||||
"""Returns all the wallets for just one cave"""
|
||||
print("-cavewallets")
|
||||
# print("-cavewallets")
|
||||
|
||||
Gcavelookup = GetCaveLookup()
|
||||
if caveid in Gcavelookup:
|
||||
@@ -337,7 +337,7 @@ def cavewallets(request, caveid):
|
||||
length_by_year = dict(sorted(length_by_year.items()))
|
||||
for y in length_by_year:
|
||||
checksum += length_by_year[y]
|
||||
print(f"{y} {length_by_year[y]:.0f}")
|
||||
# print(f"{y} {length_by_year[y]:.0f}")
|
||||
for key in list(length_by_year.keys()):
|
||||
if length_by_year[key] < 0.1:
|
||||
del length_by_year[key]
|
||||
@@ -353,7 +353,7 @@ def cavewallets(request, caveid):
|
||||
def oldwallet(request, path):
|
||||
"""Now called only for non-standard wallet structures for pre-2000 wallets"""
|
||||
# print([ s.walletname for s in Wallet.objects.all() ])
|
||||
print(f"! - oldwallet path:{path}")
|
||||
# print(f"! - oldwallet path:{path}")
|
||||
try:
|
||||
wallet = Wallet.objects.get(walletname=urlunquote(path))
|
||||
return render(request, "wallet_old.html", {"wallet": wallet, "settings": settings, "year": current_expo()})
|
||||
@@ -371,11 +371,11 @@ def scansingle(request, path, file):
|
||||
imagefile = Path(singlescan.ffile, file)
|
||||
if imagefile.is_file():
|
||||
message = f" - scansingle {imagefile} {path}:{file}:{getmimetype(file)}:"
|
||||
print(message)
|
||||
# print(message)
|
||||
return HttpResponse(content=open(imagefile, "rb"), content_type=getmimetype(file)) # any type of image
|
||||
else:
|
||||
message = f"Scan folder file '{imagefile}' not found. {path=} {file=}"
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
except:
|
||||
|
||||
@@ -85,13 +85,13 @@ def signup(request):
|
||||
pageform = ExpoSignupForm(request.POST) # A form bound to the POST data
|
||||
if pageform.is_valid():
|
||||
clean = pageform.cleaned_data
|
||||
print(f" # Signup form OK {clean['name']}")
|
||||
# print(f" # Signup form OK {clean['name']}")
|
||||
register_on_expo(signup_person)
|
||||
save_signups(editor, signup_person.slug, clean)
|
||||
return HttpResponseRedirect("/signupok")
|
||||
|
||||
else:
|
||||
print(f" # Signup form INVALID\n{pageform.errors} ")
|
||||
# print(f" # Signup form INVALID\n{pageform.errors} ")
|
||||
return render(
|
||||
request, "login/signup.html",
|
||||
{"form": pageform, "identified_login": identified_login,
|
||||
@@ -140,7 +140,7 @@ def read_signups():
|
||||
|
||||
signupsfile = signups_dir / SIGNUPS_FILE
|
||||
if not signupsfile.is_file():
|
||||
print(f" ! Nobody has signed up for expedition {current_expo()} yet.")
|
||||
# print(f" ! Nobody has signed up for expedition {current_expo()} yet.")
|
||||
return { "SIGNEDUP": {} } # dict where e.g. {"philip-sargent": encrypted_form_data, more users etc.}
|
||||
|
||||
with open(signupsfile, 'r', encoding='utf-8') as json_f:
|
||||
@@ -154,7 +154,7 @@ def read_signups():
|
||||
except Exception as e:
|
||||
message = f"! Troggle USERs. Failed to load {signupsfile} JSON file. Exception <{e}>"
|
||||
if message:
|
||||
print(message)
|
||||
# print(message)
|
||||
DataIssue.objects.update_or_create(parser="_signups", message=message, url="") ###########################
|
||||
return { "SIGNEDUP": {} }
|
||||
signups_dict = signups_single_dict[SIGNEDUP]
|
||||
@@ -188,18 +188,18 @@ def save_signups(editor, person_slug, clean):
|
||||
# re-encrypt everything
|
||||
signups_crypt[su] = f.encrypt(json.dumps(signups_clear[su]).encode("utf8")).decode()
|
||||
|
||||
print(f" SAVE after adding: {len(signups_crypt)} signups")
|
||||
# print(f" SAVE after adding: {len(signups_crypt)} signups")
|
||||
encryptedfile = settings.EXPOWEB / ENCRYPTED_DIR / current_expo() / SIGNUPS_FILE
|
||||
try:
|
||||
print(f"- Rewriting the entire encrypted set of signups to disc ")
|
||||
# print(f"- Rewriting the entire encrypted set of signups to disc ")
|
||||
write_signups(signups_crypt, encryptedfile, editor)
|
||||
except:
|
||||
message = f'! - Users encrypted data saving failed - \n!! Permissions failure ?! on attempting to save file "{encryptedfile}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
raise
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
print(f"- Exporting bierbook ")
|
||||
# print(f"- Exporting bierbook ")
|
||||
write_bierbook(signups_clear, editor)
|
||||
|
||||
def write_signups(signups, encryptedfile, editor):
|
||||
@@ -208,21 +208,21 @@ def write_signups(signups, encryptedfile, editor):
|
||||
with open(encryptedfile, 'w', encoding='utf-8') as json_f:
|
||||
json.dump(jsondict, json_f, indent=1)
|
||||
except Exception as e:
|
||||
print(f" ! Exception dumping json <{e}>")
|
||||
# print(f" ! Exception dumping json <{e}>")
|
||||
raise
|
||||
|
||||
commit_msg = f"Online signup to next expo"
|
||||
try:
|
||||
add_commit(encryptedfile, commit_msg, editor)
|
||||
except Exception as e:
|
||||
print(f" ! Exception doing git add/commit <{e}>")
|
||||
# print(f" ! Exception doing git add/commit <{e}>")
|
||||
raise
|
||||
return True
|
||||
|
||||
def write_bierbook(signups_clear, editor):
|
||||
bieryeardir = settings.EXPOWEB / BIERBOOK / current_expo()
|
||||
bierfile = bieryeardir / BIERFILE
|
||||
print(bierfile)
|
||||
# print(bierfile)
|
||||
|
||||
names = ""
|
||||
for id in signups_clear:
|
||||
@@ -234,7 +234,7 @@ def write_bierbook(signups_clear, editor):
|
||||
for i in range(0,3):
|
||||
names += "\\ldots\\ldots\\ldots\n"
|
||||
|
||||
print(names)
|
||||
# print(names)
|
||||
if not bieryeardir.is_dir():
|
||||
bieryeardir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
@@ -46,7 +46,8 @@ def legs_by_expo(expos):
|
||||
tourists = PersonExpedition.objects.filter(expedition=expedition, noncaver=True).count()
|
||||
missing_length = ( nblocks > 0 and survexleglength <= 1)
|
||||
if missing_length:
|
||||
print(expedition, nblocks, survexleglength, missing_length)
|
||||
pass
|
||||
# print(expedition, nblocks, survexleglength, missing_length)
|
||||
|
||||
legsbyexpo.append((expedition, {"success":success, "people": expoers, "tourists": tourists,
|
||||
"nsurvexlegs": legsyear, "survexleglength": survexleglength, "nblocks": nblocks, "missing_length": missing_length}))
|
||||
@@ -156,13 +157,14 @@ def therionissues(request):
|
||||
try:
|
||||
with open(logpath, "r") as f:
|
||||
therionlog = f.readlines()
|
||||
print(f"{logpath} has {len(therionlog)} entries")
|
||||
# print(f"{logpath} has {len(therionlog)} entries")
|
||||
except:
|
||||
msg = f"{logpath} EXCEPTION opening or reading therion logfile. Run a full reset."
|
||||
print(msg)
|
||||
# print(msg)
|
||||
return render(request, "therionreport.html", {"therionlog": newlog})
|
||||
else:
|
||||
print(f"{logpath} NOT FOUND: {len(therionlog)} entries")
|
||||
pass
|
||||
# print(f"{logpath} NOT FOUND: {len(therionlog)} entries")
|
||||
|
||||
for line in therionlog:
|
||||
line = line.replace("! Un-parsed image filename:", "")
|
||||
@@ -179,7 +181,8 @@ def surveximport(request):
|
||||
with open(logpath, "r") as f:
|
||||
contents = f.read()
|
||||
else:
|
||||
print(f"{logpath} NOT FOUND {len(contents)}")
|
||||
pass
|
||||
# print(f"{logpath} NOT FOUND {len(contents)}")
|
||||
return render(request, "survexreport.html", {"log": contents, "year": current_expo()})
|
||||
|
||||
|
||||
@@ -192,7 +195,8 @@ def survexdebug(request):
|
||||
with open(logpath, "r") as f:
|
||||
contents = f.read()
|
||||
else:
|
||||
print(f"{logpath} NOT FOUND {len(contents)}")
|
||||
pass
|
||||
# print(f"{logpath} NOT FOUND {len(contents)}")
|
||||
return render(request, "survexdebug.html", {"log": contents, "year": current_expo()})
|
||||
|
||||
|
||||
@@ -307,7 +311,7 @@ def dataissues(request):
|
||||
return render(request, "dataissues.html", {"didict": dilist, "year": current_expo()})
|
||||
except:
|
||||
message = f'! - Server not online - please wait 5 minutes for database rebuild'
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
|
||||
@@ -362,10 +366,11 @@ def old_key(p):
|
||||
# print(p,p.last().expedition)
|
||||
return int(p.last().expedition.year)
|
||||
else:
|
||||
print(p,p.last())
|
||||
pass
|
||||
# print(p,p.last())
|
||||
|
||||
else:
|
||||
print(f"{p} never attended expo")
|
||||
# print(f"{p} never attended expo")
|
||||
return 2050
|
||||
|
||||
|
||||
@@ -381,7 +386,7 @@ def aliases(request, year):
|
||||
|
||||
oldpersons = persons
|
||||
oldpersons.sort(key=old_key)
|
||||
print(len(oldpersons))
|
||||
# print(len(oldpersons))
|
||||
|
||||
aliases = GetPersonExpeditionNameLookup(expo)
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ def expofilerename(request, filepath):
|
||||
"""If file is a JPG but has no filename extension, then it must be renamed
|
||||
before it can be rotated.
|
||||
"""
|
||||
print(f"{path}: '{Path(path).suffix.lower()}'")
|
||||
# print(f"{path}: '{Path(path).suffix.lower()}'")
|
||||
if Path(path).suffix.lower() in [".png", ".jpg", ".jpeg"]:
|
||||
return True
|
||||
else:
|
||||
@@ -136,14 +136,14 @@ def expofilerename(request, filepath):
|
||||
def rotate_image(ctx):
|
||||
wallet = str(Path(ctx["filepath"]).parent).lstrip("surveyscans/")
|
||||
cwd = settings.SCANS_ROOT / wallet
|
||||
print(f"ROTATE \n{cwd=} \n{ctx['filename']=}")
|
||||
# print(f"ROTATE \n{cwd=} \n{ctx['filename']=}")
|
||||
mogrify = settings.MOGRIFY
|
||||
rot = subprocess.run(
|
||||
[mogrify, "-rotate", "90", ctx["filename"]], cwd=cwd, capture_output=True, text=True
|
||||
)
|
||||
msgdata = rot.stderr + "\n" + rot.stdout + "\nreturn code: " + str(rot.returncode)
|
||||
message = f'! - ROTATE - Success: rotated this file {ctx["filename"]}.' + msgdata
|
||||
print(message)
|
||||
# print(message)
|
||||
# DataIssue.objects.create(parser="mogrify", message=message)
|
||||
|
||||
if rot.returncode != 0:
|
||||
@@ -156,7 +156,7 @@ def expofilerename(request, filepath):
|
||||
+ str(rot.returncode)
|
||||
)
|
||||
message = f"! - ROTATE - CANNOT blurk for this file {ctx['filename']}. \n" + msgdata
|
||||
print(message)
|
||||
# print(message)
|
||||
DataIssue.objects.create(parser="mogrify", message=message)
|
||||
|
||||
# return to the GET view
|
||||
@@ -183,13 +183,13 @@ def expofilerename(request, filepath):
|
||||
def _setup(filepath_arg):
|
||||
if not filepath_arg:
|
||||
message = f'\n File to rename not specified "{filepath_arg}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
return {"response": render(request, "errors/generic.html", {"message": message})}
|
||||
|
||||
actualpath = Path(settings.EXPOFILES) / Path(filepath_arg)
|
||||
if not actualpath.is_file():
|
||||
message = f'\n File not found when attempting rename "{filepath_arg}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
return {"response": render(request, "errors/generic.html", {"message": message})}
|
||||
|
||||
filename = Path(filepath_arg).name
|
||||
@@ -202,14 +202,14 @@ def expofilerename(request, filepath):
|
||||
# ensure we are renaming only within wallets (surveyscans)
|
||||
if not actualpath.is_relative_to(Path(settings.SCANS_ROOT)):
|
||||
message = f'\n Can only do rename within wallets (expofiles/surveyscans/) currently, sorry. "{actualpath}" '
|
||||
print(message)
|
||||
# print(message)
|
||||
return {"response": render(request, "errors/generic.html", {"message": message})}
|
||||
|
||||
files = []
|
||||
dirs = []
|
||||
notpics = []
|
||||
dirpath = actualpath.parent
|
||||
print(f'! - FORM rename expofile - start \n{filepath_arg=} \n{dirpath=} \n{walletpath=}')
|
||||
# print(f'! - FORM rename expofile - start \n{filepath_arg=} \n{dirpath=} \n{walletpath=}')
|
||||
|
||||
if dirpath.is_dir():
|
||||
try:
|
||||
@@ -246,7 +246,7 @@ def expofilerename(request, filepath):
|
||||
form = ExpofileRenameForm(request.POST)
|
||||
if not form.is_valid():
|
||||
message = f'Invalid form response for file renaming "{request.POST}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
return {"response": render(request, "errors/generic.html", {"message": message})}
|
||||
|
||||
if "rotate" in request.POST:
|
||||
@@ -255,7 +255,7 @@ def expofilerename(request, filepath):
|
||||
|
||||
if "rename" in request.POST:
|
||||
if "renametoname" not in request.POST:
|
||||
print("renametoname not in request.POST")
|
||||
# print("renametoname not in request.POST")
|
||||
# blank filename passed it, so just treat as another GET
|
||||
return simple_get(ctx)
|
||||
|
||||
@@ -263,7 +263,7 @@ def expofilerename(request, filepath):
|
||||
if (ctx["folder"] / renameto).is_file() or (ctx["folder"] / renameto).is_dir():
|
||||
rename_bad = renameto
|
||||
message = f'\n Cannot rename to an existing file or folder. "{ctx["filename"]}" -> "{(ctx["folder"] / renameto)}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(
|
||||
request,
|
||||
"renameform.html",
|
||||
@@ -283,9 +283,9 @@ def expofilerename(request, filepath):
|
||||
# perform rename
|
||||
ctx["actualpath"].rename((ctx["folder"] / renameto))
|
||||
message = f'\n RENAMED "{ctx["filename"]}" -> "{(ctx["folder"] / renameto)}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
walletid = ctx["actualpath"].relative_to(Path(settings.SCANS_ROOT)).parent.stem.replace("#", ":")
|
||||
print(walletid)
|
||||
# print(walletid)
|
||||
return redirect(f'/survey_scans/{walletid}/')
|
||||
|
||||
# fallback: show GET view
|
||||
@@ -397,7 +397,7 @@ def photoupload(request, folder=None):
|
||||
(ctx["yearpath"] / newphotographer).mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
message = f'\n !! Permissions failure ?! 0 attempting to mkdir "{(ctx["yearpath"] / newphotographer)}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
# refresh directory listing so the response shows the newly created folder
|
||||
try:
|
||||
@@ -414,7 +414,7 @@ def photoupload(request, folder=None):
|
||||
multiple = request.FILES.getlist("uploadfiles")
|
||||
if not multiple:
|
||||
# user supplied no files — attach a form error and return to show it
|
||||
print(f"photoupload(): no files to upload {multiple}")
|
||||
# print(f"photoupload(): no files to upload {multiple}")
|
||||
form.add_error("uploadfiles", "No files uploaded.") # does not seem to be visible on form?
|
||||
ctx["form"] = form
|
||||
return ctx
|
||||
@@ -433,7 +433,7 @@ def photoupload(request, folder=None):
|
||||
else:
|
||||
saved_filename = fs.save(f.name, content=f)
|
||||
except Exception:
|
||||
print(f'\n !! Permissions failure ?! attempting to save "{f.name}" in "{ctx["dirpath"]}" {renameto=}')
|
||||
# print(f'\n !! Permissions failure ?! attempting to save "{f.name}" in "{ctx["dirpath"]}" {renameto=}')
|
||||
if "saved_filename" in locals():
|
||||
if (ctx["dirpath"] / saved_filename).is_file():
|
||||
ctx["actual_saved"].append(saved_filename)
|
||||
@@ -485,7 +485,7 @@ def gpxupload(request, folder=None):
|
||||
# dangerous, we should check the actual file binary signature
|
||||
return Path(name).suffix.lower() in [".xml", ".gpx"]
|
||||
|
||||
print(f"gpxupload() {folder=}")
|
||||
# print(f"gpxupload() {folder=}")
|
||||
|
||||
def _setup(folder_arg):
|
||||
year = current_expo()
|
||||
|
||||
@@ -46,7 +46,7 @@ class ExpoPasswordResetForm(PasswordResetForm):
|
||||
def clean_email(self):
|
||||
email = self.cleaned_data.get('email')
|
||||
# Add custom validation logic etc.
|
||||
print(f" * ExpoPasswordResetForm PASSWORD reset email posted '{email=}'")
|
||||
# print(f" * ExpoPasswordResetForm PASSWORD reset email posted '{email=}'")
|
||||
# method_list = [attribute for attribute in dir(PasswordResetForm) if callable(getattr(PasswordResetForm, attribute)) and attribute.startswith('__') is False]
|
||||
# print(method_list)
|
||||
return email
|
||||
@@ -89,7 +89,7 @@ def newregister(request, username=None):
|
||||
email = form.cleaned_data["email"]
|
||||
|
||||
nameslug = troggle_slugify(fullname)
|
||||
print(f"NEW user slug {nameslug}")
|
||||
# print(f"NEW user slug {nameslug}")
|
||||
|
||||
if User.objects.filter(username=nameslug).count() != 0:
|
||||
# Disallow a name which already exists, use the other form.
|
||||
@@ -126,14 +126,14 @@ def re_register_email(request):
|
||||
if request.method == "POST":
|
||||
form = register_email_form(request.POST) # only username and password
|
||||
if form.is_valid():
|
||||
print("POST VALID")
|
||||
# print("POST VALID")
|
||||
email = form.cleaned_data["email"]
|
||||
u.email = email
|
||||
u.save()
|
||||
save_users(request, u, email)
|
||||
return render(request, "login/register_email.html", {"form": form, "confirmed": True})
|
||||
else:
|
||||
print("POST INVALID")
|
||||
# print("POST INVALID")
|
||||
return render(request, "login/register_email.html", {"form": form})
|
||||
else: # GET
|
||||
form = register_email_form(initial=initial_values)
|
||||
@@ -143,8 +143,8 @@ def reshow_disabled(request, url_username, initial_values, warning, admin_notice
|
||||
"""Shows the form, but completely disabled, with messages showing what the user did
|
||||
wrong or inappropriately. Could all be replaced by form validation methods ?
|
||||
"""
|
||||
print(warning)
|
||||
print(admin_notice)
|
||||
# print(warning)
|
||||
# print(admin_notice)
|
||||
form = register_form(initial=initial_values)
|
||||
form.fields["username"].widget.attrs["readonly"]="readonly"
|
||||
form.fields["email"].widget.attrs["readonly"]="readonly"
|
||||
@@ -165,7 +165,7 @@ def register(request, url_username=None):
|
||||
warning = ""
|
||||
admin_notice = ""
|
||||
initial_values={"visible-passwords": "True"}
|
||||
print(f"{url_username=} {request.user.username=}")
|
||||
# print(f"{url_username=} {request.user.username=}")
|
||||
|
||||
# Since this form is for old expoers, we can expect that they know how to login as 'expo'. So require this at least.
|
||||
if request.user.is_anonymous:
|
||||
@@ -202,7 +202,7 @@ def register(request, url_username=None):
|
||||
if request.method == "POST":
|
||||
form = register_form(request.POST)
|
||||
if form.is_valid():
|
||||
print("POST VALID") # so now username and email fields are readonly
|
||||
# print("POST VALID") # so now username and email fields are readonly
|
||||
un = form.cleaned_data["username"]
|
||||
pw= form.cleaned_data["password1"]
|
||||
email = form.cleaned_data["email"]
|
||||
@@ -232,7 +232,7 @@ def save_users(request, updated_user, email="troggle@exposerver.expo"):
|
||||
f = get_encryptor()
|
||||
ru = []
|
||||
|
||||
print(f"\n + Saving users, encrypted emails, and password hashes")
|
||||
# print(f"\n + Saving users, encrypted emails, and password hashes")
|
||||
for u in User.objects.all():
|
||||
if u.username in ["expo", "expoadmin"]:
|
||||
continue
|
||||
@@ -240,7 +240,7 @@ def save_users(request, updated_user, email="troggle@exposerver.expo"):
|
||||
ru.append({"username":u.username, "email": e_email, "pwhash": u.password, "encrypted": True})
|
||||
# print(u.username, e_email)
|
||||
original = f.decrypt(e_email).decode()
|
||||
print(f" - {u.username} - {original}")
|
||||
# print(f" - {u.username} - {original}")
|
||||
|
||||
if updated_user.is_anonymous:
|
||||
git_string = f"troggle <troggle@exposerver.expo>"
|
||||
@@ -248,11 +248,11 @@ def save_users(request, updated_user, email="troggle@exposerver.expo"):
|
||||
git_string = f"{updated_user.username} <{email}>"
|
||||
encryptedfile = settings.EXPOWEB / ENCRYPTED_DIR / USERS_FILE
|
||||
try:
|
||||
print(f"- Rewriting the entire encrypted set of registered users to disc ")
|
||||
# print(f"- Rewriting the entire encrypted set of registered users to disc ")
|
||||
write_users(ru, encryptedfile, git_string)
|
||||
except:
|
||||
message = f'! - Users encrypted data saving failed - \n!! Permissions failure ?! on attempting to save file "{encryptedfile}"'
|
||||
print(message)
|
||||
# print(message)
|
||||
raise
|
||||
return render(request, "errors/generic.html", {"message": message})
|
||||
|
||||
@@ -262,14 +262,14 @@ def write_users(registered_users, encryptedfile, git_string):
|
||||
with open(encryptedfile, 'w', encoding='utf-8') as json_f:
|
||||
json.dump(jsondict, json_f, indent=1)
|
||||
except Exception as e:
|
||||
print(f" ! Exception dumping json <{e}>")
|
||||
# print(f" ! Exception dumping json <{e}>")
|
||||
raise
|
||||
|
||||
commit_msg = f"Online (re-)registration of a troggle User"
|
||||
try:
|
||||
add_commit(encryptedfile, commit_msg, git_string)
|
||||
except Exception as e:
|
||||
print(f" ! Exception doing git add/commit <{e}>")
|
||||
# print(f" ! Exception doing git add/commit <{e}>")
|
||||
raise
|
||||
return True
|
||||
|
||||
@@ -329,9 +329,9 @@ class register_email_form(forms.Form): # not a model-form, just a form-form
|
||||
|
||||
email = cleaned_data.get("email")
|
||||
users = User.objects.filter(email=email)
|
||||
print(f"{len(users)=}")
|
||||
# print(f"{len(users)=}")
|
||||
if len(users) > 1: # allow 0 (change) or 1 (confirm)
|
||||
print("ValidationError")
|
||||
# print("ValidationError")
|
||||
raise ValidationError(
|
||||
"Duplicate email address. Another registered user is already using this email address. Email addresses must be unique as that is how we reset forgotten passwords."
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user