From cf7d7e49904330096fccc7ce51f709b6c5461e22 Mon Sep 17 00:00:00 2001
From: Nick Sweeting <git@sweeting.me>
Date: Sat, 10 Apr 2021 04:16:12 -0400
Subject: [PATCH] add new timezone autosetting and cache header setting
 middlewares

---
 archivebox/core/middleware.py        | 37 ++++++++++++++++++++++++++++
 archivebox/core/settings.py          |  2 ++
 archivebox/templates/admin/base.html |  7 ++++--
 archivebox/templates/core/base.html  | 36 ++++++++++++++++++++++++---
 4 files changed, 76 insertions(+), 6 deletions(-)
 create mode 100644 archivebox/core/middleware.py

diff --git a/archivebox/core/middleware.py b/archivebox/core/middleware.py
new file mode 100644
index 00000000..3b5787c4
--- /dev/null
+++ b/archivebox/core/middleware.py
@@ -0,0 +1,37 @@
+__package__ = 'archivebox.core'
+
+from django.utils import timezone
+
+from ..config import PUBLIC_SNAPSHOTS
+
+
+def detect_timezone(request, activate: bool=True):
+    gmt_offset = (request.COOKIES.get('GMT_OFFSET') or '').strip()
+    tz = None
+    if gmt_offset.replace('-', '').isdigit():
+        tz = timezone.get_fixed_timezone(int(gmt_offset))
+        if activate:
+            timezone.activate(tz)
+    # print('GMT_OFFSET', gmt_offset, tz)
+    return tz
+
+
+def TimezoneMiddleware(get_response):
+    def middleware(request):
+        detect_timezone(request, activate=True)
+        return get_response(request)
+
+    return middleware
+
+
+def CacheControlMiddleware(get_response):
+    def middleware(request):
+        response = get_response(request)
+
+        if '/archive/' in request.path or '/static/' in request.path:
+            policy = 'public' if PUBLIC_SNAPSHOTS else 'private'
+            response['Cache-Control'] = f'{policy}, max-age=60, stale-while-revalidate=300'
+            # print('Set Cache-Control header to', response['Cache-Control'])
+        return response
+
+    return middleware
diff --git a/archivebox/core/settings.py b/archivebox/core/settings.py
index ab574a0a..fade85db 100644
--- a/archivebox/core/settings.py
+++ b/archivebox/core/settings.py
@@ -55,12 +55,14 @@ INSTALLED_APPS = [
 
 
 MIDDLEWARE = [
+    'core.middleware.TimezoneMiddleware',
     'django.middleware.security.SecurityMiddleware',
     'django.contrib.sessions.middleware.SessionMiddleware',
     'django.middleware.common.CommonMiddleware',
     'django.middleware.csrf.CsrfViewMiddleware',
     'django.contrib.auth.middleware.AuthenticationMiddleware',
     'django.contrib.messages.middleware.MessageMiddleware',
+    'core.middleware.CacheControlMiddleware',
 ]
 
 AUTHENTICATION_BACKENDS = [
diff --git a/archivebox/templates/admin/base.html b/archivebox/templates/admin/base.html
index 50af51ee..436318ea 100644
--- a/archivebox/templates/admin/base.html
+++ b/archivebox/templates/admin/base.html
@@ -1,5 +1,8 @@
-{% load i18n static %}<!DOCTYPE html>
-{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}
+{% load i18n static tz %}
+{% get_current_language as LANGUAGE_CODE %}
+{% get_current_language_bidi as LANGUAGE_BIDI %}
+
+<!DOCTYPE html>
 <html lang="{{ LANGUAGE_CODE|default:"en-us" }}" {% if LANGUAGE_BIDI %}dir="rtl"{% endif %}>
 <head>
 <title>{% block title %}{% endblock %} | ArchiveBox</title>
diff --git a/archivebox/templates/core/base.html b/archivebox/templates/core/base.html
index fbecd84b..0f4d9d2b 100644
--- a/archivebox/templates/core/base.html
+++ b/archivebox/templates/core/base.html
@@ -1,5 +1,4 @@
-{% load admin_urls %}
-{% load static %}
+{% load static tz admin_urls %}
 
 <!DOCTYPE html>
 <html lang="en">
@@ -66,6 +65,35 @@
                 </footer>
             {% endblock %}
         </div>
+        <script>
+            // hide images that fail to load
+            document.querySelector('body').addEventListener('error', function (e) {
+                e.target.style.opacity = 0;
+            }, true)
+
+            // setup timezone
+            {% get_current_timezone as TIME_ZONE %}
+            window.TIME_ZONE = '{{TIME_ZONE}}'
+
+            window.setCookie = function(name, value, days) {
+                let expires = ""
+                if (days) {
+                    const date = new Date()
+                    date.setTime(date.getTime() + (days*24*60*60*1000))
+                    expires = "; expires=" + date.toUTCString()
+                }
+                document.cookie = name + "=" + (value || "")  + expires + "; path=/"
+            }
+
+            function setTimeOffset() {
+                if (window.GMT_OFFSET) return
+                window.GMT_OFFSET = -(new Date).getTimezoneOffset()
+                window.setCookie('GMT_OFFSET', window.GMT_OFFSET, 365)
+            }
+
+            jQuery(document).ready(function () {
+                setTimeOffset();
+            });
+        </script>
     </body>
-    
-    </html>
+</html>