Skip to content
Snippets Groups Projects
Commit 1cfe4b42 authored by Jonathan Weth's avatar Jonathan Weth :keyboard: Committed by root
Browse files

Merge pull request #309 from Katharineum/feature/pwa-optimization

Feature/pwa optimization
parents 71a2753c aa45b7e3
No related branches found
No related tags found
1 merge request!86Merge school-apps
Showing
with 227 additions and 130 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="ES6" />
<option name="languageLevel" value="JS_1_8_5" />
</component>
<component name="NodePackageJsonFileManager">
<packageJsonPaths />
......
......@@ -9,4 +9,5 @@ django_react_templatetags
kanboard
PyPDF2
martor
django-pwa
django_widget_tweaks
\ No newline at end of file
......@@ -4,5 +4,6 @@ from . import views
urlpatterns = [
path('', views.index, name='dashboard'),
path('test/', views.test_notification, name='test'),
path('offline/', views.offline, name='offline')
]
......@@ -50,4 +50,7 @@ def test_notification(request):
description="Ihr Antrag XY wurde von der Schulleitung genehmigt.", app="AUB",
link=reverse("aub_details", args=[1]))
print(reverse("aub_details", args=[1]))
return redirect(reverse('dashboard'))
\ No newline at end of file
return redirect(reverse('dashboard'))
def offline(request):
return render(request, 'common/offline.html')
\ No newline at end of file
......@@ -20,7 +20,8 @@ ALLOWED_HOSTS = [
'178.63.239.184',
'159.69.181.50',
'localhost',
'127.0.0.1'
'127.0.0.1',
'13049d63.ngrok.io'
]
INTERNAL_IPS = [
......@@ -49,6 +50,7 @@ INSTALLED_APPS = [
'django_react_templatetags',
'martor',
'widget_tweaks',
'pwa',
'templatetags.apps.TemplatetagsConfig',
]
......@@ -172,6 +174,37 @@ MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# DBSETTINGS_USE_CACHE = False
# PWA
PWA_APP_NAME = 'SchoolApps'
PWA_APP_DESCRIPTION = "Eine Sammlung an nützlichen Apps für den Schulalltag am Katharineum zu Lübeck"
PWA_APP_THEME_COLOR = '#da1f3d'
PWA_APP_BACKGROUND_COLOR = '#ffffff'
PWA_APP_DISPLAY = 'standalone'
PWA_APP_SCOPE = '/'
PWA_APP_ORIENTATION = 'any'
PWA_APP_START_URL = '/'
PWA_APP_ICONS = [
{
"src": "/static/icons/android_192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/static/icons/android_512.png",
"sizes": "512x512",
"type": "image/png"
}
]
PWA_APP_SPLASH_SCREEN = [
{
'src': '/static/icons/android_512.png',
'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)'
}
]
PWA_APP_DIR = 'ltr'
PWA_SERVICE_WORKER_PATH = os.path.join(BASE_DIR, 'static/common', 'serviceworker.js')
PWA_APP_LANG = 'de-DE'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
......
......@@ -13,31 +13,18 @@ Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
import os
from django.conf import settings
from django.conf.urls import include
from django.contrib import admin
from django.contrib.staticfiles.views import serve
from django.urls import path
from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.shortcuts import render
from django.views import defaults
from schoolapps.settings import BASE_DIR
def manifest(request):
return serve(request, "manifest.json")
def serviceworker(request):
return serve(request, "common/pwabuilder-sw.js")
from django.urls import path
def custom_page_not_found(request, exception):
print(exception)
return render(request, '404.html', context={"martor": False})
return render(request, 'common/404.html', context={"martor": False})
handler404 = custom_page_not_found
......@@ -85,7 +72,7 @@ urlpatterns = [
#######
path('faq/', include('faq.urls')),
path("pwabuilder-sw.js", serviceworker),
path('', include('pwa.urls')),
path('martor/', include('martor.urls')),
......
File mode changed from 100755 to 100644
{
"dir": "ltr",
"lang": "de",
"name": "SchoolApps",
"scope": "",
"display": "standalone",
"start_url": "https://info.katharineum.de/",
"short_name": "SchoolApps",
"theme_color": "#da1f3d",
"description": "",
"background_color": "#ffffff",
"related_applications": [],
"prefer_related_applications": false,
"icons": [
{
"src": "/static/icons/android_192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/static/icons/android_512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
//This is the "Offline copy of pages" service worker
//Add this below content to your HTML page, or add the js file to your page at the very top to register service worker
if (navigator.serviceWorker.controller) {
console.log('[PWA Builder] active service worker found, no need to register')
} else {
//Register the ServiceWorker
navigator.serviceWorker.register('pwabuilder-sw.js', {
scope: './'
}).then(function (reg) {
console.log('Service worker has been registered for scope:' + reg.scope);
});
}
//This is the "Offline copy of pages" service worker
//Install stage sets up the index page (home page) in the cache and opens a new cache
self.addEventListener('install', function (event) {
var indexPage = new Request('/');
event.waitUntil(
fetch(indexPage).then(function (response) {
return caches.open('pwabuilder-offline').then(function (cache) {
console.log('[PWA Builder] Cached index page during Install' + response.url);
return cache.put(indexPage, response);
});
}));
});
//If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener('fetch', function (event) {
var updateCache = function (request) {
return caches.open('pwabuilder-offline').then(function (cache) {
return fetch(request).then(function (response) {
console.log('[PWA Builder] add page to offline' + response.url)
return cache.put(request, response);
});
});
};
event.waitUntil(updateCache(event.request));
event.respondWith(
fetch(event.request).catch(function (error) {
console.log('[PWA Builder] Network request Failed. Serving content from cache: ' + error);
//Check to see if you have it in the cache
//Return response
//If not in the cache, then return error page
return caches.open('pwabuilder-offline').then(function (cache) {
return cache.match(event.request).then(function (matching) {
var report = !matching || matching.status === 404 ? Promise.reject('no-match') : matching;
return report
});
});
})
);
})
//This is the SchoolApps service worker with Advanced caching
const CACHE = "schoolapps-cache";
const precacheFiles = [
'/',
'/faq/',
];
const offlineFallbackPage = '/offline/';
const networkFirstPaths = [
];
const avoidCachingPaths = [
'/admin/',
'/settings/',
'/support/',
'/faq/ask/',
'/aub/apply_for/',
'/aub/check1/',
'/aub/check2/',
'/aktuell.pdf',
'/timetable/aktuell.pdf',
];
function pathComparer(requestUrl, pathRegEx) {
return requestUrl.match(new RegExp(pathRegEx));
}
function comparePaths(requestUrl, pathsArray) {
if (requestUrl) {
for (let index = 0; index < pathsArray.length; index++) {
const pathRegEx = pathsArray[index];
if (pathComparer(requestUrl, pathRegEx)) {
return true;
}
}
}
return false;
}
self.addEventListener("install", function (event) {
console.log("[SchoolApps PWA] Install Event processing");
console.log("[SchoolApps PWA] Skip waiting on install");
self.skipWaiting();
event.waitUntil(
caches.open(CACHE).then(function (cache) {
console.log("[SchoolApps PWA] Caching pages during install");
return cache.addAll(precacheFiles).then(function () {
return cache.add(offlineFallbackPage);
});
})
);
});
// Allow sw to control of current page
self.addEventListener("activate", function (event) {
console.log("[SchoolApps PWA] Claiming clients for current page");
event.waitUntil(self.clients.claim());
});
// If any fetch fails, it will look for the request in the cache and serve it from there first
self.addEventListener("fetch", function (event) {
if (event.request.method !== "GET") return;
if (comparePaths(event.request.url, networkFirstPaths)) {
networkFirstFetch(event);
} else {
cacheFirstFetch(event);
}
});
function cacheFirstFetch(event) {
event.respondWith(
fromCache(event.request).then(
function (response) {
// The response was found in the cache so we respond with it and update the entry
// This is where we call the server to get the newest version of the
// file to use the next time we show view
event.waitUntil(
fetch(event.request).then(function (response) {
return updateCache(event.request, response);
})
);
return response;
},
function () {
// The response was not found in the cache so we look for it on the server
return fetch(event.request)
.then(function (response) {
// If request was success, add or update it in the cache
event.waitUntil(updateCache(event.request, response.clone()));
return response;
})
.catch(function (error) {
// The following validates that the request was for a navigation to a new document
if (event.request.destination !== "document" || event.request.mode !== "navigate") {
return;
}
console.log("[SchoolApps PWA] Network request failed and no cache." + error);
// Use the precached offline page as fallback
return caches.match(offlineFallbackPage)
});
}
)
);
}
function networkFirstFetch(event) {
event.respondWith(
fetch(event.request)
.then(function (response) {
// If request was success, add or update it in the cache
event.waitUntil(updateCache(event.request, response.clone()));
return response;
})
.catch(function (error) {
console.log("[SchoolApps PWA] Network request Failed. Serving content from cache: " + error);
return fromCache(event.request);
})
);
}
function fromCache(request) {
// Check to see if you have it in the cache
// Return response
// If not in the cache, then return error page
return caches.open(CACHE).then(function (cache) {
return cache.match(request).then(function (matching) {
if (!matching || matching.status === 404) {
return Promise.reject("no-match");
}
return matching;
});
});
}
function updateCache(request, response) {
if (!comparePaths(request.url, avoidCachingPaths)) {
return caches.open(CACHE).then(function (cache) {
return cache.put(request, response);
});
}
return Promise.resolve();
}
File mode changed from 100755 to 100644
!function(){"use strict";try{self["workbox:sw:4.3.1"]&&_()}catch(t){}const t="https://storage.googleapis.com/workbox-cdn/releases/4.3.1",e={backgroundSync:"background-sync",broadcastUpdate:"broadcast-update",cacheableResponse:"cacheable-response",core:"core",expiration:"expiration",googleAnalytics:"offline-ga",navigationPreload:"navigation-preload",precaching:"precaching",rangeRequests:"range-requests",routing:"routing",strategies:"strategies",streams:"streams"};self.workbox=new class{constructor(){return this.v={},this.t={debug:"localhost"===self.location.hostname,modulePathPrefix:null,modulePathCb:null},this.s=this.t.debug?"dev":"prod",this.o=!1,new Proxy(this,{get(t,s){if(t[s])return t[s];const o=e[s];return o&&t.loadModule(`workbox-${o}`),t[s]}})}setConfig(t={}){if(this.o)throw new Error("Config must be set before accessing workbox.* modules");Object.assign(this.t,t),this.s=this.t.debug?"dev":"prod"}loadModule(t){const e=this.i(t);try{importScripts(e),this.o=!0}catch(s){throw console.error(`Unable to import module '${t}' from '${e}'.`),s}}i(e){if(this.t.modulePathCb)return this.t.modulePathCb(e,this.t.debug);let s=[t];const o=`${e}.${this.s}.js`,r=this.t.modulePathPrefix;return r&&""===(s=r.split("/"))[s.length-1]&&s.splice(s.length-1,1),s.push(o),s.join("/")}}}();
//# sourceMappingURL=workbox-sw.js.map
This diff is collapsed.
This diff is collapsed.
{% include "partials/header.html" %}
<main>
<h3>Leider existiert diese Seite nicht. (Fehler 404)</h3>
<p class="flow-text">
Beim Aufrufen dieser Seite ist ein Fehler aufgetreten. Wahrscheinlich existiert die gewünschte Seite unter der
Adresse "<code id="url"></code>" nicht.
Solltest du der Meinung sein, dass diese Seite eigentlich existieren müsste, wende dich bitte an die
<a href="mailto:support@katharineum.de">Computer-AG</a>.
</p>
</main>
<script>
document.getElementById("url").innerHTML = window.location.pathname;
</script>
{% include 'partials/footer.html' %}
{% include 'partials/header.html' %}
<main>
<h3><i class="material-icons left medium" style="font-size: 2.92rem;">signal_wifi_off</i> Es besteht keine
Verbindung zum Internet. </h3>
<p class="flow-text">
Beim Aufrufen dieser Seite ist ein Fehler aufgetreten. Vermutlich hast du keine Verbindung zum Internet.
Prüfe, ob dein WLAN oder deine mobilen Daten engeschaltet sind, und probiere es noch einmal.
Wenn du der Meinung bist, dass du über eine Verbindung verfügst, wende dich bitte an die
<a href="mailto:support@katharineum.de">Computer-AG</a>
.
</p>
</main>
{% include 'partials/footer.html' %}
......@@ -60,7 +60,6 @@
<!-- JavaScript (jquery v. 3.4.1.slim)-->
<!---------------->
<script src="{% static 'common/manup.min.js' %}"></script>
<script src="{% static "common/pwabuilder-sw-register.js" %}"></script>
<script src="{% static 'js/materialize.min.js' %}"></script>
<script src="{% static 'common/helper.js' %}"></script>
</body>
......
{% load static %}
{% load pwa %}
{% load url_name %}
<!DOCTYPE html>
......@@ -66,7 +67,9 @@
<!-- Favicon -->
<link rel="shortcut icon" type="image/x-icon" href="{% static 'common/favicon.ico' %}">
<link rel="manifest" href="{% static "common/manifest.json" %}">
<!-- PWA -->
{% progressive_web_app_meta %}
<!--------->
<!-- CSS -->
......@@ -75,7 +78,7 @@
<link rel="stylesheet" type="text/css" media="screen"
href="{% static 'css/materialize.min.css' %}">
<link rel="stylesheet" type="text/css" href="{% static 'common/style.css' %}">
<script src="{% static 'js/jquery/jquery-3.3.1.slim.min.js' %}"></script>
<script src="{% static 'js/jquery/jquery-3.4.1.slim.min.js' %}"></script>
<!-- location (for "active" in sidenav -->
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment