Compare commits

...

2 commits

Author SHA1 Message Date
e91b64ca97 software caching thumbnails in javascript 2024-06-22 22:11:38 +02:00
facefc1cc7 add persistent-state-plugin 2024-06-22 20:56:51 +02:00
6 changed files with 147 additions and 52 deletions

View file

@ -7,7 +7,7 @@
<script> <script>
import {mapActions} from "vuex"; import {mapActions, mapGetters, mapMutations} from "vuex";
export default { export default {
name: "AuthenticatedImage", name: "AuthenticatedImage",
@ -16,6 +16,7 @@ export default {
type: String, type: String,
required: true required: true
}, },
cached: Boolean
}, },
data() { data() {
return { return {
@ -23,21 +24,37 @@ export default {
servers: [] servers: []
} }
}, },
computed: {
...mapGetters(['getThumbnail']),
},
methods: { methods: {
...mapActions(['fetchImage']), ...mapActions(['fetchImage']),
loadImage() { ...mapMutations(['setThumbnail']),
this.fetchImage(this.src).then((response) => { async loadImage() {
const mime_type = response.headers.get("content-type"); const response = await this.fetchImage(this.src);
response.arrayBuffer().then((buf) => { const mime_type = response.headers.get("content-type");
const base64 = btoa(new Uint8Array(buf) const buf = await response.arrayBuffer();
.reduce((data, byte) => data + String.fromCharCode(byte), "")); const base64 = btoa(new Uint8Array(buf)
this.image_data = "data:" + mime_type + ";base64," + base64; .reduce((data, byte) => data + String.fromCharCode(byte), ""));
this.image_data = "data:" + mime_type + ";base64," + base64;
if (this.cached)
this.setThumbnail({
url: this.src,
data: this.image_data
}); });
})
} }
}, },
mounted() { mounted() {
this.loadImage(); setTimeout(() => {
if (this.cached) {
const c = this.getThumbnail(this.src);
if (c) {
this.image_data = c;
return;
}
}
this.loadImage();
}, 0);
} }
} }
</script> </script>

View file

@ -25,8 +25,8 @@
<ul> <ul>
<li v-for="attachment in item.attachments" @click="openLightboxModalWith(attachment)"> <li v-for="attachment in item.attachments" @click="openLightboxModalWith(attachment)">
<AuthenticatedImage :src="`/media/2/256/${attachment.hash}/`" :alt="attachment.name" <AuthenticatedImage :src="`/media/2/256/${attachment.hash}/`" :alt="attachment.name"
v-if="attachment.mime_type.startsWith('image/')"/> v-if="attachment.mime_type.startsWith('image/')" cached/>
<AuthenticatedDataLink :href="`/media/2/256/${attachment.hash}/`" :download="attachment.name" <AuthenticatedDataLink :href="`/media/2/${attachment.hash}/`" :download="attachment.name"
v-else/> v-else/>
</li> </li>
</ul> </ul>

View file

@ -0,0 +1,71 @@
import {isProxy, toRaw} from 'vue';
export default (config) => (store) => {
if (!('isLoadedKey' in config)) {
throw new Error("isLoadedKey not defined in config");
}
const initialize = () => {
config.state.forEach(k => {
try {
if (config.debug) console.log("localStorage init", k, localStorage.getItem(config.prefix + k));
const parsed = JSON.parse(localStorage.getItem(config.prefix + k));
if (parsed !== store.state[k] && parsed !== null) {
store.state[k] = parsed;
} else {
if (config.debug) console.log("localStorage not loaded", k, localStorage.getItem(config.prefix + k));
}
} catch (e) {
if (config.debug) console.log("localStorage parse error", k, e);
}
});
store.state[config.isLoadedKey] = true;
}
const reload = initialize;
if (store.state[config.isLoadedKey] !== true)
initialize();
addEventListener('storage', reload);
if ('state' in config) {
config.state.forEach((member) => {
store.watch((state, getters) => state[member], (newValue, oldValue) => {
try {
if (config.debug) console.log('watch', member,
isProxy(newValue) ? toRaw(newValue) : newValue,
isProxy(oldValue) ? toRaw(oldValue) : oldValue);
const key = config.prefix + member;
const encoded = JSON.stringify(isProxy(newValue) ? toRaw(newValue) : newValue);
if (encoded !== localStorage.getItem(key)) {
if (config.debug) console.log("localStorage replace", member, localStorage.getItem(key), encoded);
if (newValue === null)
localStorage.removeItem(key);
else
localStorage.setItem(key, encoded);
} else {
if (config.debug) console.log("localStorage not saved", member, localStorage.getItem(key), encoded);
}
} catch (e) {
if (config.debug) console.log("localsorage save error", member, e);
}
});
});
}
if ('clearingMutation' in config) {
store.subscribe((mutation, state) => {
if (mutation.type === config.clearingMutation) {
removeEventListener('storage', reload)
for (let key in config.state) {
localStorage.removeItem(config.prefix + key);
}
for (let key in config.state) {
store.state[key] = null;
}
addEventListener('storage', reload)
}
});
}
};

View file

@ -5,6 +5,8 @@ import * as base64 from 'base-64';
import * as utf8 from 'utf8'; import * as utf8 from 'utf8';
import {ticketStateColorLookup, ticketStateIconLookup, http} from "@/utils"; import {ticketStateColorLookup, ticketStateIconLookup, http} from "@/utils";
import persistentStatePlugin from "@/persistent-state-plugin";
const store = createStore({ const store = createStore({
state: { state: {
keyIncrement: 0, keyIncrement: 0,
@ -17,10 +19,8 @@ const store = createStore({
users: [], users: [],
groups: [], groups: [],
state_options: [], state_options: [],
lastEvent: localStorage.getItem('lf_lastEvent') || '37C3', lastEvent: '37C3',
lastUsed: JSON.parse(localStorage.getItem('lf_lastUsed') || '{}'),
remember: false, remember: false,
user: { user: {
username: null, username: null,
password: null, password: null,
@ -29,7 +29,8 @@ const store = createStore({
expiry: null, expiry: null,
}, },
local_loaded: false, thumbnailCache: {},
persistent_loaded: false,
showAddBoxModal: false, showAddBoxModal: false,
}, },
getters: { getters: {
@ -38,8 +39,10 @@ const store = createStore({
getActiveView: state => router.currentRoute.value.name || 'items', getActiveView: state => router.currentRoute.value.name || 'items',
getFilters: state => router.currentRoute.value.query, getFilters: state => router.currentRoute.value.query,
getBoxes: state => state.loadedBoxes, getBoxes: state => state.loadedBoxes,
checkPermission: state => (event, perm) => state.user.permissions.includes(`${event}:${perm}`) || state.user.permissions.includes(`*:${perm}`), checkPermission: state => (event, perm) => state.user.permissions &&
hasPermissions: state => state.user.permissions.length > 0, (state.user.permissions.includes(`${event}:${perm}`) || state.user.permissions.includes(`*:${perm}`)),
hasPermissions: state => state.user.permissions && state.user.permissions.length > 0,
activeUser: state => state.user.username || 'anonymous',
stateInfo: state => (slug) => { stateInfo: state => (slug) => {
const obj = state.state_options.filter((s) => s.value === slug)[0]; const obj = state.state_options.filter((s) => s.value === slug)[0];
if (obj) { if (obj) {
@ -67,27 +70,18 @@ const store = createStore({
return 'tasks'; return 'tasks';
}, },
isLoggedIn(state) { isLoggedIn(state) {
if (!state.local_loaded) {
state.remember = localStorage.getItem('remember') === 'true';
state.user.username = localStorage.getItem('user');
//state.password = localStorage.getItem('password');
state.user.permissions = JSON.parse(localStorage.getItem('permissions') || '[]');
state.user.token = localStorage.getItem('token');
state.user.expiry = localStorage.getItem('token_expiry');
state.local_loaded = true;
}
return state.user && state.user.username !== null && state.user.token !== null; return state.user && state.user.username !== null && state.user.token !== null;
}, },
getThumbnail: (state) => (url) => {
if (!url) return null;
if (!(url in state.thumbnailCache))
return null;
return state.thumbnailCache[url];
},
}, },
mutations: { mutations: {
updateLastUsed(state, diff) {
state.lastUsed = {...state.lastUsed, ...diff};
localStorage.setItem('lf_lastUsed', JSON.stringify(state.lastUsed));
},
updateLastEvent(state, slug) { updateLastEvent(state, slug) {
state.lastEvent = slug; state.lastEvent = slug;
localStorage.setItem('lf_lastEvent', slug);
}, },
replaceEvents(state, events) { replaceEvents(state, events) {
state.events = events; state.events = events;
@ -147,29 +141,21 @@ const store = createStore({
}, },
setRemember(state, remember) { setRemember(state, remember) {
state.remember = remember; state.remember = remember;
localStorage.setItem('remember', remember);
}, },
setUser(state, user) { setUser(state, user) {
state.user.username = user; state.user.username = user;
if (user)
localStorage.setItem('user', user);
}, },
setPassword(state, password) { setPassword(state, password) {
state.user.password = password; state.user.password = password;
}, },
setPermissions(state, permissions) { setPermissions(state, permissions) {
state.user.permissions = permissions; state.user.permissions = permissions;
if (permissions)
localStorage.setItem('permissions', JSON.stringify(permissions));
}, },
setToken(state, {token, expiry}) { setToken(state, {token, expiry}) {
const user = {...state.user}; const user = {...state.user};
user.token = token; user.token = token;
user.expiry = expiry; user.expiry = expiry;
state.user = user; state.user = user;
if (token)
localStorage.setItem('token', token);
localStorage.setItem('token_expiry', expiry);
}, },
setUserInfo(state, user) { setUserInfo(state, user) {
state.user = user; state.user = user;
@ -183,9 +169,12 @@ const store = createStore({
user.permissions = null; user.permissions = null;
state.user = user; state.user = user;
}, },
setThumbnail(state, {url, data}) {
state.thumbnailCache[url] = data;
},
}, },
actions: { actions: {
async login({commit, dispatch, state}, {username, password, remember}) { async login({commit}, {username, password, remember}) {
commit('setRemember', remember); commit('setRemember', remember);
try { try {
const data = await fetch('/api/2/login/', { const data = await fetch('/api/2/login/', {
@ -195,10 +184,8 @@ const store = createStore({
credentials: 'omit' credentials: 'omit'
}).then(r => r.json()) }).then(r => r.json())
if (data && data.token) { if (data && data.token) {
commit('setToken', data); const {data: {permissions}} = await http.get('/2/self/', data.token);
commit('setUser', username); commit('setUserInfo', {...data, permissions, username, password});
commit('setPassword', password);
dispatch('afterLogin');
return true; return true;
} else { } else {
return false; return false;
@ -372,10 +359,21 @@ const store = createStore({
commit('updateTicket', data); commit('updateTicket', data);
} }
}, },
plugins: [
persistentStatePlugin({ // TODO change remember to some kind of enable field
prefix: "lf_",
debug: false,
isLoadedKey: "persistent_loaded",
state: [
"remember",
"user",
"events",
]
}),
],
}); });
store.watch((state) => state.user, (user) => { store.watch((state) => state.user, (user) => {
console.log('user changed', user);
if (store.getters.isLoggedIn) { if (store.getters.isLoggedIn) {
if (router.currentRoute.value.name === 'login' && router.currentRoute.value.query.redirect) if (router.currentRoute.value.name === 'login' && router.currentRoute.value.query.redirect)
router.push(router.currentRoute.value.query.redirect); router.push(router.currentRoute.value.query.redirect);

View file

@ -4,9 +4,16 @@
<div class="col-xl-8 offset-xl-2"> <div class="col-xl-8 offset-xl-2">
<div class="card bg-dark text-light mb-2" id="filters"> <div class="card bg-dark text-light mb-2" id="filters">
<div class="card-header"> <div class="card-header">
<h3 class="text-center">User: {{user}}</h3> <h3 class="text-center">User: {{ activeUser }}</h3>
</div> </div>
<div class="card-body"> <div class="card-body" v-if="hasPermissions">
<p>Your Account is activated. Got to
<router-link :to="{name: 'items', params: {event: getEventSlug}}">Items</router-link>
or
<router-link :to="{name: 'tickets', params: {event: getEventSlug}}">Tickets</router-link>
</p>
</div>
<div class="card-body" v-else>
<p>Your Account is not yet activated. Please contact an admin.</p> <p>Your Account is not yet activated. Please contact an admin.</p>
</div> </div>
</div> </div>
@ -16,11 +23,13 @@
</template> </template>
<script> <script>
import {mapState} from "vuex"; import {mapGetters, mapState} from "vuex";
export default { export default {
name: 'Empty', name: 'Empty',
computed: mapState(['user']), computed: {
...mapGetters(['hasPermissions', 'getEventSlug', 'activeUser']),
},
}; };
</script> </script>

View file

@ -45,7 +45,7 @@
v-slot="{ item }" v-slot="{ item }"
@itemActivated="openLightboxModalWith($event)" @itemActivated="openLightboxModalWith($event)"
> >
<AuthenticatedImage v-if="item.file" <AuthenticatedImage v-if="item.file" cached
:src="`/media/2/256/${item.file}/`" :src="`/media/2/256/${item.file}/`"
class="card-img-top img-fluid" class="card-img-top img-fluid"
/> />