From 269020391240f15d5d5997f88b51f401abf37cb1 Mon Sep 17 00:00:00 2001
From: Philip Sargent <philip.sargent@klebos.com>
Date: Wed, 31 Mar 2021 23:19:48 +0100
Subject: [PATCH] new method for /site-media/, /static/, /photos/

---
 core/views/expo.py       | 32 ++++++++++++++++++++------------
 localsettings.py         | 10 +++++-----
 templates/nodirlist.html |  7 +++++++
 urls.py                  | 18 ++++--------------
 4 files changed, 36 insertions(+), 31 deletions(-)
 create mode 100644 templates/nodirlist.html

diff --git a/core/views/expo.py b/core/views/expo.py
index 4ca6f22..b62a3db 100644
--- a/core/views/expo.py
+++ b/core/views/expo.py
@@ -90,7 +90,23 @@ def expowebpage(request, expowebpath, path):
         has_menu = True
     return render(request, 'flatpage.html', {'editable': editable, 'path': path, 'title': title, 
                 'body': body, 'homepage': (path == "index.htm"), 'has_menu': has_menu})
-    
+ 
+def mediapage(request, subpath=None, doc_root=None):
+    '''This is for special prefixe paths /photos/ /site_media/, /static/ etc.
+    as defined in urls.py . If given a directory, gives a failure page. 
+    '''
+    # print(" - XXXXX_ROOT: {}  ...{}".format(doc_root, subpath))
+    if doc_root is not None:
+        filetobeopened = Path(doc_root, subpath)
+        if filetobeopened.is_dir():
+            return render(request, 'nodirlist.html', {'path': subpath})
+        try:
+            return HttpResponse(content=open(filetobeopened, "rb"), content_type=getmimetype(subpath))
+        except IOError:
+            return render(request, 'pagenotfound.html', {'path': subpath})
+    else:
+        return render(request, 'pagenotfound.html', {'path': subpath})
+  
 
 def expopage(request, path):
     '''Either renders an HTML page from expoweb with all the menus,
@@ -128,17 +144,9 @@ def expopage(request, path):
         # the final / may have been appended by middleware if there was no page without it
         # do not redirect to a file path without the slash as we may get in a loop. Let the user fix it:
         return render(request, 'dirnotfound.html', {'path': path, 'subpath': path[0:-1]})
-   
-    if path.startswith('site_media'): # BUT we may have missing files, directories or .html here too?!
-        # print(" - MEDIA_ROOT: {}  ...{}".format(settings.MEDIA_ROOT, path))
-        npath = path.replace("site_media", settings.MEDIA_ROOT)
-        filetobeopened = os.path.normpath(npath)
-    elif path.startswith("static"):
-        # print(" - STATIC_ROOT: {}  ...{}".format(settings.MEDIA_ROOT, path))
-        npath = path.replace("static", settings.MEDIA_ROOT)
-        filetobeopened = os.path.normpath(npath)
-    else:
-        filetobeopened = os.path.normpath(expowebpath / path)
+    
+    # So it must be a file in  /expoweb/ but not .htm or .html probably an image
+    filetobeopened = os.path.normpath(expowebpath / path)
     
     try:
         return HttpResponse(content=open(filetobeopened, "rb"), content_type=getmimetype(path))
diff --git a/localsettings.py b/localsettings.py
index 2e79d50..b0853e7 100644
--- a/localsettings.py
+++ b/localsettings.py
@@ -41,6 +41,11 @@ TROGGLE_PATH = Path(__file__).parent
 TEMPLATE_PATH     = os.fspath(TROGGLE_PATH / 'templates')
 MEDIA_ROOT        = os.fspath(TROGGLE_PATH / 'media')
 
+FILES = Path('/mnt/f/expofiles/')
+EXPOFILES = Path('/mnt/f/expofiles/')
+SURVEY_SCANS = EXPOFILES / 'surveyscans'
+PHOTOS_ROOT = EXPOFILES / 'photos'
+
 # URL that handles the media served from MEDIA_ROOT. Make sure to use a
 # trailing slash if there is a path component (optional in other cases).
 MEDIA_URL = '/site-media/'
@@ -129,21 +134,16 @@ EMAIL_PORT=587
 EMAIL_USE_TLS = True
 DEFAULT_FROM_EMAIL = 'django-test@klebos.net'
 
-
-
 SURVEX_DATA = REPOS_ROOT_PATH / "loser"
 TUNNEL_DATA = REPOS_ROOT_PATH / "drawings"
 THREEDCACHEDIR  =  REPOS_ROOT_PATH / 'expowebcache' / '3d'
 
 EXPOWEB = REPOS_ROOT_PATH / "expoweb" 
 SURVEYS = REPOS_ROOT_PATH
-SURVEY_SCANS = '/mnt/f/expofiles/surveyscans/'
-FILES = '/mnt/f/expofiles/'
 CAVEDESCRIPTIONS        = EXPOWEB / "cave_data"
 ENTRANCEDESCRIPTIONS    = EXPOWEB / "entrance_data"
 EXPOWEB_URL = ''
 SURVEYS_URL = '/survey_scans/'
-EXPOFILES ='/mnt/f/expofiles/'
 
 # Sanitise these to be strings as all other code is expecting strings
 # and we have not made the change to pathlib Path type in the other localsettings-* variants yet.
diff --git a/templates/nodirlist.html b/templates/nodirlist.html
new file mode 100644
index 0000000..9b2d295
--- /dev/null
+++ b/templates/nodirlist.html
@@ -0,0 +1,7 @@
+{% extends "expobase.html" %}
+{% block title %}Page not found {{ path }}{% endblock %}
+{% block body %}
+<h1>Directory not displayed: {{ path }}</h1>
+ <p>Only individual files may be displayed from this directory. No directory listing available.
+{% include "menu.html" %}
+{% endblock %}
diff --git a/urls.py b/urls.py
index 46e06b1..2ba8120 100644
--- a/urls.py
+++ b/urls.py
@@ -10,7 +10,7 @@ from troggle.core.views import surveys, logbooks, other, caves, statistics, surv
 from troggle.core.views.other import troggle404, frontpage
 from troggle.core.views.caves import ent, prospecting_image
 from troggle.core.views.statistics import pathsreport, stats
-from troggle.core.views.expo import expofiles_redirect, expofilessingle, expopage, editexpopage
+from troggle.core.views.expo import expofiles_redirect, expofilessingle, expopage, editexpopage, mediapage
 from troggle.core.views.survex import survexcaveslist, survexcavesingle, svx
 """This sets the actualurlpatterns[] and urlpatterns[] lists which django uses 
 to resolve urls - in both directions as these are declarative. 
@@ -40,7 +40,6 @@ else:
     expofilesurls = [
         url(r'^(?P<filepath>.*)$', expofilessingle, name="single"), # local copy of EXPOFILES
     ]
-   
  
 trogglepatterns = [
     url(r'^expofiles/', include(expofilesurls)), 
@@ -134,19 +133,10 @@ trogglepatterns = [
     url(r'^prospecting/(?P<name>[^.]+).png$', prospecting_image, name="prospecting_image"),
     
   
-#   url(r'^javascript/(?P<filepath>.*)$', surveys.expofilessingle,  name="single"), # JSLIB_URL - Apache: Alias /javascript /usr/share/javascript
+    url(r'^photos/(?P<subpath>.*)$',      mediapage, {'doc_root': settings.PHOTOS_ROOT}, name="mediapage"), # photo galleries 
+    url(r'^site_media/(?P<subpath>.*)$',  mediapage, {'doc_root': settings.MEDIA_ROOT},  name="mediapage"), # MEDIA_ROOT: CSS and JS 
+    url(r'^static/(?P<subpath>.*)$',      mediapage, {'doc_root': settings.STATIC_ROOT}, name="mediapage"), # STATIC: CSS and JS 
 
-#   static views not working, removed as a plugin. Use apache instead to serve these:
-#   url(r'^photos/(?P<path>.*)$', staticviews.serve,
-#            {'document_root': settings.PHOTOS_ROOT, 'show_indexes':True}),
-#   url(r'^gallery/(?P<path>.*)$', staticviews.serve,
-#            {'document_root': settings.PHOTOS_ROOT, 'show_indexes':True}),
- 
-#   url(r'^site_media/(?P<filepath>.*)$', surveys.expofilessingle,  name="single"), # MEDIA_ROOT: CSS and JS 
-    url(r'^(site_media/.*)$',   expopage, name="expopage"), # MEDIA_ROOT: CSS and JS 
-
-#   url(r'^static/(?P<filepath>.*)$',     surveys.expofilessingle,  name="single"), # MEDIA_ROOT: CSS and JS
-    url(r'^(static/.*)$',       expopage, name="expopage"), # STATIC: CSS and JS 
 
     url(r'^(.*)_edit$',         editexpopage, name="editexpopage"),
     url(r'^(.*)$',              expopage,     name="expopage"), # CATCHALL assumed relative to EXPOWEB