This commit is contained in:
Holger Sielaff
2024-07-03 21:41:03 +02:00
commit 030d3c8059
45 changed files with 2025 additions and 0 deletions

1
lib/__init__.py Normal file
View File

@@ -0,0 +1 @@
from .middleware.current_user import get_current_user

0
lib/core/__init__.py Normal file
View File

View File

View File

@@ -0,0 +1,26 @@
from threading import local
from django.utils.deprecation import MiddlewareMixin
_user = local()
_request = local()
class CurrentUserMiddleware(MiddlewareMixin):
def process_request(self, request):
_user.value = request.user
_request.value = request
def get_current_user():
try:
return _user.value
except AttributeError:
return None
def get_current_request():
try:
return _request.value
except AttributeError:
return None

58
lib/utils.py Normal file
View File

@@ -0,0 +1,58 @@
import logging
import math
import re
import matplotlib
from django.db import models
from django.utils.safestring import mark_safe
re_hex = re.compile("^([0-9a-f]{3,6})(\W)?", re.IGNORECASE)
def hex2rgb(hexval):
return matplotlib.colors.to_rgb(hexval)
def light_or_dark(rgbColor, colors: tuple = ('#FFFFFF', '#333333')):
if isinstance(rgbColor, str):
rgbColor = hex2rgb(rgbColor)
[r, g, b] = rgbColor
val = 0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b)
hsp = math.sqrt(val)
# logging.error([rgbColor, val, hsp])
# if hsp > 127.5:
if hsp > .5:
# light
return colors[1]
else:
# dark
return colors[0]
def invert_hex(hexval: str):
def _invert(content):
text = content.group(1).lower()
code = {}
l1 = "0123456789abcdef"
l2 = "fedcba9876543210"
for i in range(len(l1)):
code[l1[i]] = l2[i]
inverted = ""
for j in text:
inverted += code[j]
return inverted
prepend_hash = ''
if hexval.startswith('#'):
hexval = hexval[1:]
prepend_hash = '#'
return prepend_hash + re_hex.sub(_invert, hexval)
def color_label(instance: models.Model, value:str=None):
value = value or instance.color
return mark_safe(f'<div style="padding:.5em 1em;display:inline-block;background-color:{instance.color};border-radius:5px;'
# f'color:{invert_hex(instance.color)};'
f'color:{light_or_dark(instance.color)};'
f'">{value}</div>')