summaryrefslogtreecommitdiffstats
path: root/core/views/caves.py
blob: 856c2cdb77bb7f0f546bfbafcad6a94975a6f8ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
import os
import re
import subprocess
import tempfile
import urllib
import zipfile
from pathlib import Path

import django
from bs4 import BeautifulSoup
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.http import FileResponse, HttpResponse, HttpResponseNotFound, HttpResponseRedirect
from django.shortcuts import redirect, render
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils.safestring import mark_safe

import troggle.settings as settings
from troggle.core.forms import CaveForm, EntranceForm, EntranceLetterForm  # CaveAndEntranceFormSet,
from troggle.core.models.caves import Cave, CaveAndEntrance, Entrance, GetCaveLookup, get_cave_leniently
from troggle.core.models.logbooks import QM
from troggle.core.models.wallets import Wallet
from troggle.core.utils import (
    get_cookie_max_age,
    WriteAndCommitError,
    current_expo,
    get_editor, 
    git_string,
    write_and_commit,
    is_identified_user,
)
from troggle.core.views import expo
from troggle.parsers.caves import read_cave, read_entrance
from troggle.settings import CAVEDESCRIPTIONS, ENTRANCEDESCRIPTIONS

from .auth import login_required_if_public

"""Manages the complex procedures to assemble a cave description out of the compnoents
Manages the use of cavern to parse survex files to produce 3d and pos files
"""

todo = """
- in getCaves() search GCavelookup first, which should raise a MultpleObjectsReturned 
  exception if no duplicates
  
- Learn to use Django .select_related() and .prefetch_related() to speed things up
  especially on the big report pages 
  https://zerotobyte.com/how-to-use-django-select-related-and-prefetch-related/
  
- Remove all the URL rewriting which is there because we have not yet edited all the caves to use
  our new (2023) standard addressing of /16xx/NNN/NNN.html where *all* caves are assumed to have their
  own directory 16xx/NNN/ even if they have no images to put in it.
"""

# def cavepagefwd(request, karea=None, subpath=None):
    # """archaic, just send to the caves list page
    # """
    # return redirect("/caves")
    

def get_cave_from_slug(caveslug):
    """Needs refactoring
    """
    caves = []
    
    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) 
    
    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)=}")
    
    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)=}")
    
    if len(caves) > 1:
        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..")
         return None
    cave = caves[0]
    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")
            
        return cave_zero
    except:
        return None
        
def caveslugfwd(request, slug):
    """This is arse-backwards. It would be better style to have the slug-identified request be the master, and have 
    other paths redirect to it, rather than what we have here.
    Pending a change where we remove cave.url as a field and have an explicit fixed convention instead.
    """
    if not slug:
            message = f"Failed to find cave from identifier given: {slug}."
            return render(request, "errors/generic.html", {"message": message})

    Gcavelookup = GetCaveLookup()
    if slug in Gcavelookup:
        cave = Gcavelookup[slug]

    return redirect(f"/{cave.url}")
    

def getCaves(cave_id):
    """Only gets called if a call to getCave() raises a MultipleObjects exception

    TO DO: search GCavelookup first, which should raise a MultpleObjectsReturned exception if there
    are duplicates"""
    try:
        caves = Cave.objects.filter(kataster_number=cave_id)
        caveset = set(caves)

        Gcavelookup = GetCaveLookup()  # dictionary makes strings to Cave objects
        if cave_id in Gcavelookup:
            caveset.add(Gcavelookup[cave_id])
        return list(caveset)
    except:
        return []


def getCave(cave_id):
    """Returns a cave object when given a cave name or number. 
    It is used by views including cavehref, ent, wallets and qm.

    TO DO: search GCavelookup first, which should raise a MultpleObjectsReturned exception if there
    are duplicates"""
    try:
        cave = Cave.objects.get(kataster_number=cave_id)
        return cave
    except Cave.MultipleObjectsReturned as ex:
        raise MultipleObjectsReturned("Duplicate kataster number") from ex  # propagate this up

    except Cave.DoesNotExist as ex:
        Gcavelookup = GetCaveLookup()  # dictionary makes strings to Cave objects
        if cave_id in Gcavelookup:
            return Gcavelookup[cave_id]
        else:
            raise ObjectDoesNotExist("No cave found with this identifier in any id field") from ex  # propagate this up
    except:
        raise ObjectDoesNotExist("No cave found with this identifier in any id field")


def pad5(x):
    return "0" * (5 - len(x.group(0))) + x.group(0)


def padnumber(x):
    return re.sub(r"\d+", pad5, x) 


def numericalcmp(x, y):
    return cmp(padnumber(x), padnumber(y))

def entKey(e):
    k = caveKey(e.firstcave())
    return k
    
def caveKey(c):
    """This function goes into a lexicographic sort function, and the values are strings,
    but we want to sort numerically on kataster number before sorting on unofficial number.
    """
    if not c.kataster_number:
        return "9999." + c.unofficial_number
    else:
        try:
            if int(c.kataster_number) >= 100:
                return "99." + c.kataster_number
            if int(c.kataster_number) >= 10:
                return "9." + c.kataster_number
            return c.kataster_number
        except:
            return c.kataster_number + "_ERROR"

def getnotablecaves():
    notablecaves = []
    for kataster_number in settings.NOTABLECAVES1623:
        try:
            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)
            
    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)
    return notablecaves


def caveindex(request):
    """Should use Django order-by for lazy sorting, not here. But only after we have a proper slug system in place for Caves
    """
    # allcaves = Cave.objects.all()
    # for c in allcaves:
        # if c.entrances:
            # pass
    
    caves1623 = list(Cave.objects.filter(areacode="1623"))
    caves1624 = list(Cave.objects.filter(areacode="1624"))
    caves1626 = list(Cave.objects.filter(areacode="1626"))
    caves1627 = list(Cave.objects.filter(areacode="1627"))
    caves1623.sort(key=caveKey)
    caves1624.sort(key=caveKey)
    caves1626.sort(key=caveKey)
    caves1627.sort(key=caveKey)
    return render(
        request,
        "caveindex.html",
        {"caves1623": caves1623, 
        "caves1626": caves1626, 
        "caves1627": caves1627, 
        "caves1624": caves1624,
        "notablecaves": getnotablecaves(), 
        "cavepage": True, "year": current_expo()},
    )
    
def entranceindex(request):
    ents = Entrance.objects.all().order_by("slug")

    return render(
        request,
        "entranceindex.html",
        {"entrances": ents},
    )

def entrancetags(request):
    ents = list(Entrance.objects.all())
    ents1623 = []
    for e in ents:
        if e.slug[:4] == "1623":
            if e.firstcave().kataster_number:
                if int(e.firstcave().kataster_number) < 80:
                    if int(e.firstcave().kataster_number) not in [35, 40, 41, 76]:
                        continue
            if e.best_station():
                continue
            if e.findability != "S": # it says we do not have coordinates, but it might be lying. Or coordinates may be only in Spelix.
                ents1623.append(e)
    ents1623.sort(key=entKey)
    
    return render(
        request,
        "entrancetags.html",
        {"entrances": ents1623},
    )


def cave3d(request, cave_id=""):
    """This is used to create a download url in templates/cave.html if anyone wants to download the .3d file
    The caller template tries kataster first, then unofficial_number if that kataster number does not exist
    but only if Cave.survex_file is non-empty
    """
    try:
        cave = getCave(cave_id)
    except ObjectDoesNotExist:
        return HttpResponseNotFound
    except Cave.MultipleObjectsReturned:
        # should really produce a better error message. This is a failure of ambiguous aliases probably.
        caves = Cave.objects.filter(url=kpath)
        return render(request, "svxcaveseveral.html", {"settings": settings, "caves": caves, "year": current_expo()})
    else:
        return file3d(request, cave, cave_id)


def file3d(request, cave, cave_id):
    """Produces a .3d file directly for download.
    survex_file should be in valid path format 'caves-1623/264/264.svx' but it might be mis-entered as simply '2012-ns-10.svx'

    Also the cave.survex_file may well not match the cave description path:
    e.g. it might be to the whole system 'smk-system.svx' instead of just for the specific cave.

    - If the expected .3d file corresponding to cave.survex_file is present, return it.
    - If the cave.survex_file exists, generate the 3d file, cache it and return it
    - Use the cave_id to guess what the 3d file might be and, if in the cache, return it
    
    There is a problem as the filename is shown of all areacode information, so both 1624-161 and 1623-161 
    have a file called 161.svx and return a file called "161.3d" which may 
    get incorrectly cached by other software (i.e your browser)
    """

    def runcavern(survexpath):
        """This has not yet been properly updated with respect to putting the .3d file in the same folder as the .svx filse
        as done in runcavern3d() in parsers/survex.py
        Needs testing.
        """
        if not survexpath.is_file():
            pass
        try:
            completed_process = subprocess.run(
                [settings.CAVERN, "--log", f"--output={settings.SURVEX_DATA}", f"{survexpath}"]
            )
        except OSError as ex:
            # propagate this to caller.
            raise OSError(completed_process.stdout) from ex

        op3d = (Path(settings.SURVEX_DATA) / Path(survexpath).name).with_suffix(".3d")
        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())

    def return3d(threedpath, cave):
        newfilename = cave.slug() + ".3d" # add the "1623-" part of the filename effectively.
        if threedpath.is_file():
            response = HttpResponse(content=open(threedpath, "rb"), content_type="application/3d")
            response["Content-Disposition"] = f"attachment; filename={newfilename}"
            return response
        else:
            message = f'<h1>Path provided  does not correspond to any actual 3d file.</h1><p>path: "{threedpath}"'
            return HttpResponseNotFound(message)

    survexname = Path(cave.survex_file).name  # removes directories ie 1623/161/161.svx -> 161.svx 
    survexpath = Path(settings.SURVEX_DATA, cave.survex_file)
    survexdir  = survexpath.parent
    threedname = Path(survexname).with_suffix(".3d")  # removes .svx, replaces with .3d AND DISCARDS PATH arrgh
    threedpath = survexpath.parent / threedname
 
    # These if statements need refactoring more cleanly
    if cave.survex_file:
        if threedpath.is_file():
            if survexpath.is_file():
                if os.path.getmtime(survexpath) > os.path.getmtime(threedpath):
                    runcavern(survexpath)
            return return3d(threedpath, cave)
        else:
            if survexpath.is_file():
                runcavern(survexpath)
                return return3d(threedpath, cave)

    # Get here if cave.survex_file was set but did not correspond to a valid svx file
    if survexpath.is_file():
        # a file, but invalid format
        message = f'<h1>File is not valid .svx format.</h1><p>Could not generate 3d file from "{survexpath}"'
    else:
        # we could try to guess that 'caves-1623/' is missing,... nah.
        message = f'<h1>Path provided  does not correspond to any actual file.</h1><p>path: "{survexpath}"'

    return HttpResponseNotFound(message)


def rendercave(request, cave, slug, cave_id=""):
    """Gets the data and files ready and then triggers Django to render the template.
    The resulting html contains urls which are dispatched independently, e.g. the 'download' link
    """

    if cave.non_public and settings.PUBLIC_SITE and not request.user.is_authenticated:
        return render(request, "nonpublic.html", {"instance": cave, "cavepage": True, "cave_id": cave_id})
    else:
        # print(f" ! rendercave: slug:'{slug}' survex file:'{cave.survex_file}'")
        try:
            svx3d = Path(cave.survex_file).stem
            svxstem = Path(settings.SURVEX_DATA) / Path(cave.survex_file)
            # print(f" ! rendercave: slug:'{slug}' '' ++ '{svxstem}'")
        except:
            svx3d = ""
            svxstem = ""
            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 
        # see design docum in troggle/templates/cave.html
        # see rendercave() in troggle/core/views/caves.py
        templatefile = "cave.html"
        
        wallets = Wallet.objects.filter(caves=cave)

        if not cave_id:
            cave_id = slug  # cave.unofficial_number
        context = {
            "cave_editable": True,
            "settings": settings,
            "cave": cave,
            "cavepage": True,
            "cave_id": cave_id,
            "svxstem": str(svxstem),
            "svx3d": svx3d,
            "wallets": wallets, 
            "year": current_expo()
        }

        # Do not catch any exceptions here: propagate up to caller
        r = render(
            request, templatefile, context
        )  # crashes here with NoReverseMatch if url not set up for 'edit_cave' in urls.py
        return r
        

    
def cavepage(request, karea=None, subpath=None):
    """Displays a cave description page
    accessed by kataster area number specifically
    OR
    accessed by cave.url specifically set in data, e.g.
    "1623/000/000" <= cave-data/1623-000.html
    "1623/41/115.htm" <= cave-data/1623-115.html
    so we have to query the database to find the URL as we cannot rely on the url actually telling us the cave by inspection.
    
    NOTE that old caves have ".html" (or ".htm") in the URL as they used to be actual files. But since 2006 these URLs 
    refer to virtual pages generated on the fly by troggle, so the".html" is confusing and redundant.
    But this confused Becka so it was re-instated. Thus creating more confusion for future generations...

    There are also A LOT OF URLS to e.g. /1623/161/l/rl89a.htm which are IMAGES and real html files
    in cave descriptions. These need to be handled HERE too (accident of history).
    
    """
    if not subpath or 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 /
    kpath = karea + subpath
    #print(f" ! cavepage:'{kpath}' kataster area:'{karea}' rest of path:'{subpath}'")
    
    # replace this with .count()
    caves = Cave.objects.filter(url=kpath) 
    if len(caves) == 1:
        cave = caves[0]
        return rendercave(request, cave, cave.slug())

    if len(subpath) > 100: # overlong URL
           return redirect(f"/caves")


    # HORRIBLE HACK, to be removed..
    subpath = subpath.strip("//")
    # re do all this using pathlib functions
    parts = subpath.strip("/").split("/")
    if len(parts) > 5:
        # recursive loop. break out of it.
        print(karea,subpath)
        subparts = parts[0].split(".")
        caveid = subparts[0] 
        slug = f"{karea}-{caveid}"
        if cave:= get_cave_from_slug(slug): # walrus operator
            return redirect(f"/{cave.url}")
        else:
            return redirect(f"/caves")
           
    # epath = karea  + subpath # e.g. 1623  /204
    # return expo.expopage(request, epath)
    
    
    # BUGGER the real problem is the the cave description has embedded in it images like
    # src="110/entrance.jpeg and since the cave url is now /1623/110/110.html
    # the images try to load from /1623/110/110/entrance.jpeg and of course fail.
    # THIS IS A HORRIBLE HACK
    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)
        subparts = parts[0].split(".")
        caveid = subparts[0] # e.g. 204.htm => "204"
        k2path = karea +"/"+ caveid + subpath
        return redirect(f"/{k2path}") # potential infinite loop
    elif len(parts) >2:
        # e.g. i/204.jpg, but that's ok as we are already "in" /1623/nn/
        if parts[0] == parts[1]: # double caveid, e.g. /161/161/france.html
            epath = karea 
            for i in parts[1:]:
                epath += "/" + i               
            # print(f"{subpath=}\n  {epath=}")
            return expo.expopage(request, epath)

    # if either the first two parts are not /caveid/caveid/
    # or the number of parts == 2, 
    # This is the bit that MOST images in descriptions get to.
    # simple filename, no folders in path, e.g. href="94_ent_close.jpg"
    # inside a cave or entrance description, this "just works" as the href is just 
    # added to the context of the current page, so there are >> 1 "parts" to the URL.
    print(f"2 {subpath=}")
    epath = karea + "/" + subpath
    return expo.expopage(request, epath)

@login_required_if_public
def edit_cave(request, path="", slug=None):
    """This is the form that edits all the cave data and writes out an XML file in the :expoweb: repo folder
    The format for the file being saved is in templates/dataformat/cave.xml

    It saves the data into into the database and into the html file, which it then commits to git.
    
    We basically ignore the <path> as the <slug> is of the format 1624-114 and contains the area code
    
    Warning. This uses Django deep magic in the CaveForm processing.
    See https://docs.djangoproject.com/en/5.1/topics/forms/modelforms/
    https://django-formset.fly.dev/styling/
    which generates the HTML form fields and also manages the syntax validation.
    
    See class CaveForm(ModelForm) in troggle/core/forms.py
    """
    
    print(f"edit_cave(): {path=} {slug=}")
    message = ""
    if slug is None:
        cave = Cave() # create a New Cave
    else:
        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()"})

    identified_login  = is_identified_user(request.user)
    editor = get_editor(request)   
        
    if request.POST:
        form = CaveForm(request.POST, instance=cave)
        if form.is_valid(): 
            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)
            # print(cave)
            if not cave.filename:
                cave.filename = cave.areacode + "-" + cave.number() + ".html"
            if not cave.url:
                cave.url = cave.areacode + "/" + cave.number() 
            cave.save()
            form.save_m2m() # this does the many-to-many relationship saving between caves and entrances
            if slug is None:
                # it is not visible on the form so it always will be None
                slug = f"{cave.areacode}-{cave.number()}"
                # cs = CaveSlug(cave=cave, slug=slug, primary=True)
                # print(f"edit_cave(): New CaveSlug saved {slug}")
                # cs.save()

            if cave.entrances().count() > 0:
                # Redirect after POST
                edit_response = HttpResponseRedirect("/" + cave.url)
            else:
                edit_response = HttpResponseRedirect(reverse("newentrance", args = [cave.url_parent(), cave.slug()])) 
            edit_response.set_cookie('editor_id', editor, max_age=get_cookie_max_age(request)) # cookie expires after get_cookie_max_age(request) seconds

            try:
                cave_file = cave.file_output()
                write_and_commit([cave_file], f"Online edit of cave {cave}", editor)
                # leave other exceptions unhandled so that they bubble up to user interface
            except PermissionError:
                message = f"CANNOT  save this file.\nPERMISSIONS incorrectly set on server for this file {cave.filename}. Ask a nerd to fix this."
                return render(request, "errors/generic.html", {"message": message})
            except WriteAndCommitError as e:
                message = f"CANNOT git on server for this file {cave.filename}.\n{e}\nEdits may not be committed.\nAsk a nerd to fix this."
                return render(request, "errors/generic.html", {"message": e.message})
            except subprocess.SubprocessError as e:
                message = f"CANNOT update server for this file {cave.filename}.\n{e}\nEdits may not be committed.\nAsk a nerd to fix this."
                return render(request, "errors/generic.html", {"message": message})               
            except:
                raise
            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()=}")
            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}")
                    raise
        
            form = CaveForm(instance=cave, initial={'cave_slug': cave.slug(), "identified_login": identified_login, "who_are_you":editor})
        else:
            form = CaveForm(initial={"identified_login": identified_login, "who_are_you":editor})
            
    # The way formsets are rendered changed between Django 4 and Django 5
    major, _, _, _, _ = django.VERSION
    if major < 5:
        tabletype = "table"
    else:
        tabletype = "div"
    
    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"
    return render(
        request,
        "editcave.html",
        {
            "form": form,
            "cave": cave,
            "message": message, "year": current_expo(), "tabletype": tabletype,
            "path": path + "/", # used for saving images if attached
        },
    )


        
@login_required_if_public
def edit_entrance(request, path="", caveslug=None, entslug=None):
    """This is the form that edits the entrance data for a single entrance and writes out
    an XML file in the :expoweb: repo folder
    
    The format for the file being saved is in templates/dataformat/entrance.xml
    
    Warning. This uses Django deep magic for multiple forms and the CaveAndEntrance class.

    It does save the data into into the database directly, not by parsing the file.
    
    'path' comes from the urls.py regex but is usually empty (!)
    So we make the proper path for storing the images ourselves.
    
    GET RID of all this entranceletter stuff. Far too overcomplexified.
    We don't need it. Just the entrance slug is fine, then check uniqueness.
    
    A whole new form is created just to edit the entranceletter. 
    To Do: put the entranceletter field on the Entrance, and delete the whole
    CaveandEntrance class and form thing. 
    Don't use the existance of a CaveandEntrance object to see if the letter is valid, 
    just count the entrances instead.
    We can do this simplification as troggle now assumes only 1 cave per entrance.
    """
    def check_new_slugname_ok(slug, letter):
        """In Nov.2023 it is possible to create a 2nd entrance and not set an entrance letter, 
        which leads to a constraint uniqueness crash. FIX THIS.
        The letter may be set to an existing letter, OR it may be unset, but there may
        be an existing unlettered single entrance. Both of these will crash unless fixed.
        """
        slugname = f"{slug}{letter}"
        nents = Entrance.objects.filter(slug=slugname).count()
        print(f"check_new_slugname_ok() {slugname=} {letter=} => {nents}")
        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!
            e.save()
            gcl = GetCaveLookup()
            c = gcl[slug]
            nce = CaveAndEntrance.objects.filter(cave=c, entrance=e).count()
            if nce == 0 :
                return slugname, letter
        
        # That entrance already exists, or the CE does, OK.. do recursive call, starting at "b"
        if letter =="":
            return check_new_slugname_ok(slug, "b") 
        else:
            nextletter = chr(ord(letter)+1)
            return check_new_slugname_ok(slug, nextletter) 

    if not (cave:= get_cave_from_slug(caveslug)): # walrus operator
        return render(request, "errors/badslug.html", {"badslug": f"for cave {caveslug} - from edit_entrance()"})

    if entslug:
        try:
            entrance = Entrance.objects.get(slug=entslug)
        except:
            return render(request, "errors/badslug.html", {"badslug": f"for entrance {entslug}  - from edit_entrance()"})
    else:
        # a new entrance on a cave
        entrance = None

    if entslug:
        print(f"Edit Entrance {caveslug=} {entslug=} {path=} number of ents:{cave.entrances().count()}")
        caveAndEntrance = CaveAndEntrance.objects.get(entrance=entrance, cave=cave)
        entlettereditable = False  
    else:
        caveAndEntrance = CaveAndEntrance(cave=cave, entrance=Entrance()) # creates a new Entrance object as well as a new CE object
        entlettereditable = True
        
    ce = caveAndEntrance
    if ce.entranceletter == "" and cave.entrances().count() > 0 :
        # this should not be blank on a multiple-entrance cave
        # 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=}")
    # if the entletter is not editable, then the entletterform does not appear and so is always invalid.
    
    print(f"{caveslug=}")
    print(f"{cave=}")
    imgpath = Path(path) / cave.areacode / cave.number()
    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=}")
        entform = EntranceForm(request.POST, instance=entrance)
        
        if not entlettereditable:
            entranceletter = ce.entranceletter
        else:
            entletterform = EntranceLetterForm(request.POST, instance=ce)
            if entletterform.is_valid():
                ce = entletterform.save(commit=False)
                entranceletter = entletterform.cleaned_data["entranceletter"]
                message = f"- POST valid {caveslug=} {entslug=} {path=} entletterform valid \n   {entletterform=}."
                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)
                # if entletterform.errors:
                    # for field in entletterform:
                        # for error in field.errors:
                            # print(f"ERR {field=} {error=}")
                # return render(request, "errors/generic.html", {"message": message})
                entranceletter=""
                
        if not entform.is_valid():
            message = f"- POST INVALID {caveslug=} {entslug=} {path=} entform valid:{entform.is_valid()} entletterform valid:{entletterform.is_valid()}"        
            entrance = entform.save(commit=False)
            print(message)
            return render(request, "errors/generic.html", {"message": message})
        else: 
            
            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:
                # we are creating a new entrance
                entrance = entform.save(commit=False)
                # entrance = ce.entrance # the one we created earlier?

                try:
                    if entranceletter:
                        slugname, letter = check_new_slugname_ok(cave.slug(), entranceletter)
                    else:
                        slugname, letter = check_new_slugname_ok(cave.slug(), "")
                    ce.entranceletter = letter
                  
                except Exception as e:
                    print(f"- EXCEPTION entranceletter {caveslug=} {entslug=} {entranceletter=} {path=}\n{e}")
                    raise
                entrance.slug = slugname
                entrance.cached_primary_slug = slugname
                entrance.filename = slugname + ".html"
            else:
                # an existing entrance ?
                entrance.slug = entslug
                entrance.cached_primary_slug = entslug
                entrance.filename = entslug + ".html"
            try:
                entrance.save() 
                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}'")
                raise
            ce.entrance = entrance
            # try not to invoke this: 
            #   UNIQUE constraint failed: core_caveandentrance.cave_id, core_caveandentrance.entranceletter
            ce.save()
            
            entrance_file = entrance.file_output()
            cave_file = cave.file_output()

            
            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)
                edit_response.set_cookie('editor_id', editor, max_age=get_cookie_max_age(request)) # cookie expires after get_cookie_max_age(request) seconds
                return edit_response
            except Exception as e:
                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)
                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}'")
        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}'")
            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}'")

            entform = EntranceForm(instance=entrance, initial={"identified_login": identified_login, "who_are_you":editor})
            if entslug is None:
                entletterform = EntranceLetterForm()
                # print(f" Getting entletter from EntranceLetterForm")
            else:
                entletter = ce.entranceletter
                if entletter == "":
                    entletterform = EntranceLetterForm()
                    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()
 
    if identified_login:
        # disable editing the git id string as we get it from the logged-on user data
        entform.fields["who_are_you"].widget.attrs["readonly"]="readonly"
    return render(
        request,
        "editentrance.html",
        {   "year": current_expo(),
            "entform": entform,
            "cave": cave,
            "ent": entrance,
            "entletter": entletter,
            "entletterform": entletterform, # is unset if not being used
            "entlettereditable": entlettereditable,
            "path": str(imgpath) + "/", # used for saving images if attached
        },
    )


def ent(request, cave_id, ent_letter):
    cave = Cave.objects.filter(kataster_number=cave_id)[0]
    cave_and_ent = CaveAndEntrance.objects.filter(cave=cave).filter(entranceletter=ent_letter)[0]
    return render(
        request,
        "entrance.html",
        {   "year": current_expo(),
            "cave": cave,
            "entrance": cave_and_ent.entrance,
            "letter": cave_and_ent.entranceletter,
        },
    )

def cave_debug(request):
    ents = Entrance.objects.all().order_by('id')
    caves = Cave.objects.all().order_by('id')
    return render(
        request,
        "cave_debug.html",
        {"ents": ents, "caves": caves, "year": current_expo()},
    )
    
def caveslist(request):
    caves = Cave.objects.all()
    print("CAVESLIST")
    return render(
        request,
        "caveslist.html",
        {"caves": caves, "year": current_expo()},
    )
def get_entrances(request, caveslug):
    if not (cave:= get_cave_from_slug(caveslug)): # walrus operator
        return render(request, "errors/badslug.html", {"badslug": f"{caveslug} - from get_entrances()"})
    return render(
        request, "options.html", {"year": current_expo(), "items": [(e.entrance.slug(), e.entrance.slug()) for e in cave.entrances()]}
    )


def caveQMs(request, slug, open=False):
    """Lists all the QMs on a particular cave
    relies on the template to find all the QMs for the cave specified in the slug, e.g. '1623-161'
    Now working in July 2022
    """
    if not (cave:= get_cave_from_slug(slug)): # walrus operator
        return render(request, "errors/badslug.html", {"badslug": f"{slug} - from caveQMs()"})

    if cave.non_public and settings.PUBLIC_SITE and not request.user.is_authenticated:
        return render(request, "nonpublic.html", {"instance": cave})
    elif open:
        return render(request, "cave_open_qms.html", {"cave": cave, "year": current_expo()})
    else:
        return render(request, "cave_qms.html", {"cave": cave, "year": current_expo()})


def qm(request, cave_id, qm_id, year, grade=None, blockname=None):
    """Reports on one specific QM
    Fixed and working July 2022, for both CSV imported QMs
    
    Needs refactoring though! Uses extremely baroque way of getting the QMs instead of querying for QM objects
    directly, presumably as a result of a baroque history.

    Many caves have several QMS with the same number, grade, year (2018) and first 8 chars of the survexblock. 
    This crashes things, so the terminal char of the survexblock name was added to disambiguate
    """
    
    if not qm_id:
        message = f"No qm_id specified {cave_id=} {year=}  {blockname=}"
        return render(request, "errors/generic.html", {"message": message})
        
    year = int(year)

    if blockname == "" or not blockname:
        # CSV import QMs, use old technique
        try:
            c = getCave(cave_id)
            manyqms =  c.get_open_QMs() | c.get_ticked_QMs() # set union operation
            qm = manyqms.get(number=qm_id, expoyear=year, grade=grade)
            return render(request, "qm.html", {"qm": qm})
        except QM.DoesNotExist:
            # raise
            return render(
                request,
                "errors/badslug.html",
                {
                    "badslug": f"QM.DoesNotExist blockname is empty string: {cave_id=} {year=} {qm_id=} {grade=} {blockname=}"
                },
            )
        except QM.MultipleObjectsReturned:
            # raise
            qms = manyqms.filter(number=qm_id, expoyear=year)
            return render(
                request,
                "errors/badslug.html",
                {
                    "badslug": f"QM.MultipleObjectsReturned  {cave_id=} {year=} {qm_id=} {grade=} {blockname=} {qms=}"
                },
            )

    else:
        try:
            qmslug = f"{cave_id}-{year}-{blockname=}{qm_id}{grade}"
            print(f"{qmslug=}")
            c = getCave(cave_id)
            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)
                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:
                qm = qmqs.get(expoyear=year, blockname=blockname, number=qm_id, grade=grade)
                if qm:
                    print(
                        qm,
                        f"{qmslug=}:{cave_id=} {year=} {qm_id=} {blockname=} {qm.expoyear=} {qm.completion_description=}",
                    )
                    return render(request, "qm.html", {"qm": qm, "year": current_expo()})
                else:
                    # raise
                    return render(
                        request,
                        "errors/badslug.html",
                        {"badslug": f"Failed get {cave_id=} {year=} {qm_id=} {grade=} {blockname=}"},
                    )
        except MultipleObjectsReturned:
            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})
        except QM.DoesNotExist:
            # raise
            return render(
                request,
                "errors/badslug.html",
                {
                    "badslug": f"QM.DoesNotExist blockname is not empty string {cave_id=} {year=} {qm_id=} {grade=} {blockname=}"
                },
            )
            
def expo_kml(request):
            return render(
                request,
                "expo.kml",
                {
                    "entrances": Entrance.objects.all()
                },
                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")