2020-07-07 20:49:31 +08:00
|
|
|
# The core application of the Mia project.
|
|
|
|
# by imacat <imacat@mail.imacat.idv.tw>, 2020/7/1
|
|
|
|
|
|
|
|
# Copyright (c) 2020 imacat.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
2020-07-24 06:42:33 +08:00
|
|
|
"""The utilities of the Mia core application.
|
2020-07-07 20:49:31 +08:00
|
|
|
|
|
|
|
"""
|
2020-07-20 21:55:34 +08:00
|
|
|
import random
|
2020-07-01 23:35:23 +08:00
|
|
|
import urllib.parse
|
2020-08-29 21:54:12 +08:00
|
|
|
from typing import Dict, List, Any, Type, Tuple
|
2020-07-01 23:35:23 +08:00
|
|
|
|
2020-07-14 22:01:32 +08:00
|
|
|
from django.conf import settings
|
2020-08-28 20:26:02 +08:00
|
|
|
from django.db.models import Model
|
2020-08-13 08:05:35 +08:00
|
|
|
from django.http import HttpRequest
|
2020-08-29 21:54:12 +08:00
|
|
|
from django.urls import reverse
|
2020-07-14 22:01:32 +08:00
|
|
|
from django.utils.translation import pgettext, get_language
|
|
|
|
|
|
|
|
|
2020-08-13 08:05:35 +08:00
|
|
|
def new_pk(cls: Type[Model]) -> int:
|
2020-07-23 23:04:18 +08:00
|
|
|
"""Finds a random ID that does not conflict with the existing data records.
|
2020-07-20 21:55:34 +08:00
|
|
|
|
|
|
|
Args:
|
2020-08-13 08:05:35 +08:00
|
|
|
cls: The Django model class.
|
2020-07-20 21:55:34 +08:00
|
|
|
|
|
|
|
Returns:
|
2020-08-13 08:05:35 +08:00
|
|
|
The new random ID.
|
2020-07-20 21:55:34 +08:00
|
|
|
"""
|
|
|
|
while True:
|
2020-08-02 01:04:47 +08:00
|
|
|
pk = random.randint(100000000, 999999999)
|
2020-07-20 21:55:34 +08:00
|
|
|
try:
|
2020-08-02 01:04:47 +08:00
|
|
|
cls.objects.get(pk=pk)
|
2020-07-20 21:55:34 +08:00
|
|
|
except cls.DoesNotExist:
|
2020-08-02 01:04:47 +08:00
|
|
|
return pk
|
2020-07-20 21:55:34 +08:00
|
|
|
|
|
|
|
|
2020-08-13 08:05:35 +08:00
|
|
|
def strip_post(post: Dict[str, str]) -> None:
|
2020-08-09 14:23:43 +08:00
|
|
|
"""Strips the values of the POSTed data. Empty strings are removed.
|
2020-07-31 00:14:12 +08:00
|
|
|
|
|
|
|
Args:
|
2020-08-09 14:23:43 +08:00
|
|
|
post (dict[str]): The POSTed data.
|
2020-07-31 00:14:12 +08:00
|
|
|
"""
|
2020-08-09 14:23:43 +08:00
|
|
|
for key in list(post.keys()):
|
|
|
|
post[key] = post[key].strip()
|
|
|
|
if post[key] == "":
|
|
|
|
del post[key]
|
2020-07-31 00:14:12 +08:00
|
|
|
|
|
|
|
|
2020-07-14 22:01:32 +08:00
|
|
|
class Language:
|
|
|
|
"""A language.
|
|
|
|
|
|
|
|
Args:
|
2020-08-13 08:05:35 +08:00
|
|
|
language: The Django language code.
|
2020-07-14 22:01:32 +08:00
|
|
|
|
|
|
|
Attributes:
|
2020-07-16 23:18:16 +08:00
|
|
|
id (str): The language ID
|
2020-07-14 22:01:32 +08:00
|
|
|
db (str): The database column suffix of this language.
|
|
|
|
locale (str); The locale name of this language.
|
|
|
|
is_default (bool): Whether this is the default language.
|
|
|
|
"""
|
2020-08-13 08:05:35 +08:00
|
|
|
def __init__(self, language: str):
|
2020-07-16 23:18:16 +08:00
|
|
|
self.id = language
|
2020-07-16 23:13:15 +08:00
|
|
|
self.db = "_" + language.lower().replace("-", "_")
|
2020-07-14 22:01:32 +08:00
|
|
|
if language == "zh-hant":
|
|
|
|
self.locale = "zh-TW"
|
|
|
|
elif language == "zh-hans":
|
|
|
|
self.locale = "zh-CN"
|
|
|
|
else:
|
|
|
|
self.locale = language
|
|
|
|
self.is_default = (language == settings.LANGUAGE_CODE)
|
|
|
|
|
|
|
|
@staticmethod
|
2020-07-14 22:12:17 +08:00
|
|
|
def default():
|
2020-07-14 22:01:32 +08:00
|
|
|
return Language(settings.LANGUAGE_CODE)
|
|
|
|
|
2020-07-14 22:14:39 +08:00
|
|
|
@staticmethod
|
|
|
|
def current():
|
|
|
|
return Language(get_language())
|
|
|
|
|
2020-07-14 22:01:32 +08:00
|
|
|
|
2020-07-01 23:35:23 +08:00
|
|
|
class UrlBuilder:
|
|
|
|
"""The URL builder.
|
|
|
|
|
|
|
|
Attributes:
|
2020-08-13 08:05:35 +08:00
|
|
|
path (str): the base path
|
2020-07-01 23:35:23 +08:00
|
|
|
params (list[Param]): The query parameters
|
|
|
|
"""
|
2020-08-13 08:05:35 +08:00
|
|
|
def __init__(self, start_url: str):
|
2020-07-01 23:35:23 +08:00
|
|
|
"""Constructs a new URL builder.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
start_url (str): The URL to start with
|
|
|
|
"""
|
|
|
|
pos = start_url.find("?")
|
|
|
|
if pos == -1:
|
2020-08-13 08:05:35 +08:00
|
|
|
self.path = start_url
|
2020-08-02 01:04:47 +08:00
|
|
|
self.params = []
|
2020-07-01 23:35:23 +08:00
|
|
|
return
|
2020-08-13 08:05:35 +08:00
|
|
|
self.path = start_url[:pos]
|
2020-07-01 23:35:23 +08:00
|
|
|
self.params = []
|
2020-07-11 17:23:38 +08:00
|
|
|
for piece in start_url[pos + 1:].split("&"):
|
2020-07-01 23:35:23 +08:00
|
|
|
pos = piece.find("=")
|
|
|
|
name = urllib.parse.unquote(piece[:pos])
|
2020-07-11 17:23:38 +08:00
|
|
|
value = urllib.parse.unquote(piece[pos + 1:])
|
2020-07-01 23:35:23 +08:00
|
|
|
self.params.append(self.Param(name, value))
|
|
|
|
|
2020-07-31 21:16:03 +08:00
|
|
|
def add(self, name, value):
|
2020-07-01 23:35:23 +08:00
|
|
|
"""Adds a query parameter.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
name (str): The parameter name
|
|
|
|
value (str): The parameter value
|
|
|
|
|
|
|
|
Returns:
|
2020-07-02 00:50:27 +08:00
|
|
|
UrlBuilder: The URL builder itself, with the parameter
|
|
|
|
modified.
|
2020-07-01 23:35:23 +08:00
|
|
|
"""
|
2020-07-24 07:25:30 +08:00
|
|
|
if value is not None:
|
|
|
|
self.params.append(self.Param(name, value))
|
2020-07-01 23:35:23 +08:00
|
|
|
return self
|
|
|
|
|
2020-07-31 21:16:03 +08:00
|
|
|
def remove(self, name):
|
2020-07-01 23:35:23 +08:00
|
|
|
"""Removes a query parameter.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
name (str): The parameter name
|
|
|
|
|
|
|
|
Returns:
|
2020-07-02 00:50:27 +08:00
|
|
|
UrlBuilder: The URL builder itself, with the parameter
|
|
|
|
modified.
|
2020-07-01 23:35:23 +08:00
|
|
|
"""
|
|
|
|
self.params = [x for x in self.params if x.name != name]
|
|
|
|
return self
|
|
|
|
|
2020-08-03 23:12:04 +08:00
|
|
|
def query(self, **kwargs):
|
|
|
|
"""A keyword-styled query parameter setter. The existing values are
|
|
|
|
always replaced. Multiple-values are added when the value is a list or
|
|
|
|
tuple. The existing values are dropped when the value is None.
|
2020-07-01 23:35:23 +08:00
|
|
|
"""
|
2020-08-03 23:12:04 +08:00
|
|
|
for key in kwargs:
|
|
|
|
self.remove(key)
|
|
|
|
if isinstance(kwargs[key], list) or isinstance(kwargs[key], tuple):
|
|
|
|
for value in kwargs[key]:
|
|
|
|
self.add(key, value)
|
|
|
|
elif kwargs[key] is None:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
self.add(key, kwargs[key])
|
|
|
|
return self
|
2020-07-01 23:35:23 +08:00
|
|
|
|
2020-07-07 22:18:40 +08:00
|
|
|
def clone(self):
|
|
|
|
"""Returns a copy of this URL builder.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
UrlBuilder: A copy of this URL builder.
|
|
|
|
"""
|
2020-08-13 08:05:35 +08:00
|
|
|
another = UrlBuilder(self.path)
|
2020-07-07 22:18:40 +08:00
|
|
|
another.params = [
|
|
|
|
self.Param(x.name, x.value) for x in self.params]
|
|
|
|
return another
|
|
|
|
|
2020-08-13 08:05:35 +08:00
|
|
|
def __str__(self) -> str:
|
2020-07-07 21:06:11 +08:00
|
|
|
if len(self.params) == 0:
|
2020-08-13 08:05:35 +08:00
|
|
|
return self.path
|
|
|
|
return self.path + "?" + "&".join([
|
2020-07-07 21:06:11 +08:00
|
|
|
str(x) for x in self.params])
|
2020-07-01 23:35:23 +08:00
|
|
|
|
|
|
|
class Param:
|
|
|
|
"""A query parameter.
|
|
|
|
|
|
|
|
Attributes:
|
2020-08-13 08:05:35 +08:00
|
|
|
name: The parameter name
|
|
|
|
value: The parameter value
|
2020-07-01 23:35:23 +08:00
|
|
|
"""
|
2020-08-13 08:05:35 +08:00
|
|
|
def __init__(self, name: str, value: str):
|
2020-07-01 23:35:23 +08:00
|
|
|
"""Constructs a new query parameter
|
|
|
|
|
|
|
|
Args:
|
|
|
|
name (str): The parameter name
|
|
|
|
value (str): The parameter value
|
|
|
|
"""
|
|
|
|
self.name = name
|
|
|
|
self.value = value
|
|
|
|
|
2020-08-13 08:05:35 +08:00
|
|
|
def __str__(self) -> str:
|
2020-07-01 23:35:23 +08:00
|
|
|
"""Returns the string representation of this query
|
|
|
|
parameter.
|
|
|
|
|
|
|
|
Returns:
|
2020-07-02 00:50:27 +08:00
|
|
|
str: The string representation of this query
|
|
|
|
parameter
|
2020-07-01 23:35:23 +08:00
|
|
|
"""
|
|
|
|
return "%s=%s" % (
|
|
|
|
urllib.parse.quote(self.name),
|
|
|
|
urllib.parse.quote(self.value))
|
2020-07-07 20:54:35 +08:00
|
|
|
|
2020-07-09 01:03:03 +08:00
|
|
|
|
2020-07-07 20:54:35 +08:00
|
|
|
class Pagination:
|
|
|
|
"""The pagination.
|
|
|
|
|
|
|
|
Args:
|
2020-08-13 08:05:35 +08:00
|
|
|
request: The request.
|
|
|
|
items: All the items.
|
|
|
|
is_reversed: Whether we should display the last page first.
|
2020-07-07 20:54:35 +08:00
|
|
|
|
|
|
|
Raises:
|
2020-07-11 17:23:38 +08:00
|
|
|
PaginationException: With invalid pagination parameters
|
2020-07-07 20:54:35 +08:00
|
|
|
|
|
|
|
Attributes:
|
2020-08-05 10:17:46 +08:00
|
|
|
current_url (UrlBuilder): The current request URL.
|
2020-08-02 01:04:47 +08:00
|
|
|
is_reversed (bool): Whether we should display the last page first.
|
2020-07-07 22:18:40 +08:00
|
|
|
page_size (int): The page size.
|
|
|
|
total_pages (int): The total number of pages available.
|
|
|
|
is_paged (bool): Whether there are more than one page.
|
|
|
|
page_no (int): The current page number.
|
2020-07-19 21:08:10 +08:00
|
|
|
items (list[Model]): The items in the current page.
|
2020-07-07 20:54:35 +08:00
|
|
|
"""
|
2020-07-11 17:23:38 +08:00
|
|
|
DEFAULT_PAGE_SIZE = 10
|
|
|
|
|
2020-08-13 08:05:35 +08:00
|
|
|
def __init__(self, request: HttpRequest, items: List[Any],
|
|
|
|
is_reversed: bool = False):
|
2020-08-05 10:17:46 +08:00
|
|
|
self.current_url = UrlBuilder(request.get_full_path())
|
2020-07-07 22:18:40 +08:00
|
|
|
self.is_reversed = is_reversed
|
2020-08-02 01:04:47 +08:00
|
|
|
self.page_size = self.DEFAULT_PAGE_SIZE
|
|
|
|
self.total_pages = None
|
|
|
|
self.is_paged = None
|
|
|
|
self.page_no = 1
|
|
|
|
self.items = []
|
2020-07-11 17:23:38 +08:00
|
|
|
|
|
|
|
# The page size
|
|
|
|
try:
|
|
|
|
self.page_size = int(request.GET["page-size"])
|
|
|
|
if self.page_size == self.DEFAULT_PAGE_SIZE:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page-size"))
|
2020-07-11 17:23:38 +08:00
|
|
|
if self.page_size < 1:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page-size"))
|
2020-07-11 17:23:38 +08:00
|
|
|
except KeyError:
|
|
|
|
self.page_size = self.DEFAULT_PAGE_SIZE
|
|
|
|
except ValueError:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page-size"))
|
2020-07-07 22:18:40 +08:00
|
|
|
self.total_pages = int(
|
2020-07-19 21:08:10 +08:00
|
|
|
(len(items) - 1) / self.page_size) + 1
|
2020-07-11 17:23:38 +08:00
|
|
|
default_page_no = 1 if not is_reversed else self.total_pages
|
2020-07-07 22:18:40 +08:00
|
|
|
self.is_paged = self.total_pages > 1
|
2020-07-11 17:23:38 +08:00
|
|
|
|
|
|
|
# The page number
|
|
|
|
try:
|
|
|
|
self.page_no = int(request.GET["page"])
|
|
|
|
if not self.is_paged:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page"))
|
2020-07-11 17:23:38 +08:00
|
|
|
if self.page_no == default_page_no:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page"))
|
2020-07-11 17:23:38 +08:00
|
|
|
if self.page_no < 1:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page"))
|
2020-07-11 17:23:38 +08:00
|
|
|
if self.page_no > self.total_pages:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page"))
|
2020-07-11 17:23:38 +08:00
|
|
|
except KeyError:
|
|
|
|
self.page_no = default_page_no
|
|
|
|
except ValueError:
|
2020-08-05 10:17:46 +08:00
|
|
|
raise PaginationException(self.current_url.remove("page"))
|
2020-07-11 17:23:38 +08:00
|
|
|
|
2020-07-07 22:18:40 +08:00
|
|
|
if not self.is_paged:
|
|
|
|
self.page_no = 1
|
2020-07-19 21:08:10 +08:00
|
|
|
self.items = items
|
2020-07-07 22:18:40 +08:00
|
|
|
return
|
2020-07-07 21:04:07 +08:00
|
|
|
start_no = self.page_size * (self.page_no - 1)
|
2020-07-19 21:08:10 +08:00
|
|
|
self.items = items[start_no:start_no + self.page_size]
|
2020-07-07 22:18:40 +08:00
|
|
|
|
2020-07-07 22:49:37 +08:00
|
|
|
def links(self):
|
2020-08-02 01:04:47 +08:00
|
|
|
"""Returns the navigation links of the pagination bar.
|
|
|
|
|
|
|
|
Returns:
|
2020-08-13 08:05:35 +08:00
|
|
|
List[Link]: The navigation links of the pagination bar.
|
2020-08-02 01:04:47 +08:00
|
|
|
"""
|
2020-08-05 10:17:46 +08:00
|
|
|
base_url = self.current_url.clone().remove("page").remove("s")
|
2020-08-02 01:04:47 +08:00
|
|
|
links = []
|
|
|
|
# The previous page
|
|
|
|
link = self.Link()
|
|
|
|
link.title = pgettext("Pagination|", "Previous")
|
|
|
|
if self.page_no > 1:
|
|
|
|
if self.page_no - 1 == 1:
|
|
|
|
if not self.is_reversed:
|
|
|
|
link.url = str(base_url)
|
2020-07-07 22:18:40 +08:00
|
|
|
else:
|
2020-07-31 21:16:03 +08:00
|
|
|
link.url = str(base_url.clone().add(
|
2020-08-02 01:04:47 +08:00
|
|
|
"page", "1"))
|
2020-07-07 22:18:40 +08:00
|
|
|
else:
|
2020-07-31 21:16:03 +08:00
|
|
|
link.url = str(base_url.clone().add(
|
2020-08-02 01:04:47 +08:00
|
|
|
"page", str(self.page_no - 1)))
|
|
|
|
link.is_small_screen = True
|
|
|
|
links.append(link)
|
|
|
|
# The first page
|
|
|
|
link = self.Link()
|
|
|
|
link.title = "1"
|
|
|
|
if not self.is_reversed:
|
|
|
|
link.url = str(base_url)
|
|
|
|
else:
|
|
|
|
link.url = str(base_url.clone().add(
|
|
|
|
"page", "1"))
|
|
|
|
if self.page_no == 1:
|
|
|
|
link.is_active = True
|
|
|
|
links.append(link)
|
|
|
|
# The previous ellipsis
|
|
|
|
if self.page_no > 4:
|
2020-07-07 22:18:40 +08:00
|
|
|
link = self.Link()
|
2020-08-02 01:04:47 +08:00
|
|
|
if self.page_no > 5:
|
|
|
|
link.title = pgettext("Pagination|", "...")
|
2020-07-07 22:18:40 +08:00
|
|
|
else:
|
2020-08-02 01:04:47 +08:00
|
|
|
link.title = "2"
|
2020-07-31 21:16:03 +08:00
|
|
|
link.url = str(base_url.clone().add(
|
2020-08-02 01:04:47 +08:00
|
|
|
"page", "2"))
|
|
|
|
links.append(link)
|
|
|
|
# The nearby pages
|
|
|
|
for no in range(self.page_no - 2, self.page_no + 3):
|
|
|
|
if no <= 1 or no >= self.total_pages:
|
|
|
|
continue
|
|
|
|
link = self.Link()
|
|
|
|
link.title = str(no)
|
|
|
|
link.url = str(base_url.clone().add(
|
|
|
|
"page", str(no)))
|
|
|
|
if no == self.page_no:
|
2020-07-07 22:18:40 +08:00
|
|
|
link.is_active = True
|
2020-08-02 01:04:47 +08:00
|
|
|
links.append(link)
|
|
|
|
# The next ellipsis
|
|
|
|
if self.page_no + 3 < self.total_pages:
|
2020-07-07 22:18:40 +08:00
|
|
|
link = self.Link()
|
2020-08-02 01:04:47 +08:00
|
|
|
if self.page_no + 4 < self.total_pages:
|
|
|
|
link.title = pgettext("Pagination|", "...")
|
|
|
|
else:
|
|
|
|
link.title = str(self.total_pages - 1)
|
|
|
|
link.url = str(base_url.clone().add(
|
|
|
|
"page", str(self.total_pages - 1)))
|
|
|
|
links.append(link)
|
|
|
|
# The last page
|
|
|
|
link = self.Link()
|
|
|
|
link.title = str(self.total_pages)
|
|
|
|
if self.is_reversed:
|
|
|
|
link.url = str(base_url)
|
|
|
|
else:
|
|
|
|
link.url = str(base_url.clone().add(
|
|
|
|
"page", str(self.total_pages)))
|
|
|
|
if self.page_no == self.total_pages:
|
|
|
|
link.is_active = True
|
|
|
|
links.append(link)
|
|
|
|
# The next page
|
|
|
|
link = self.Link()
|
|
|
|
link.title = pgettext("Pagination|", "Next")
|
|
|
|
if self.page_no < self.total_pages:
|
|
|
|
if self.page_no + 1 == self.total_pages:
|
|
|
|
if self.is_reversed:
|
|
|
|
link.url = str(base_url)
|
2020-07-07 22:18:40 +08:00
|
|
|
else:
|
2020-07-31 21:16:03 +08:00
|
|
|
link.url = str(base_url.clone().add(
|
2020-08-02 01:04:47 +08:00
|
|
|
"page", str(self.total_pages)))
|
|
|
|
else:
|
|
|
|
link.url = str(base_url.clone().add(
|
|
|
|
"page", str(self.page_no + 1)))
|
|
|
|
link.is_small_screen = True
|
|
|
|
links.append(link)
|
|
|
|
return links
|
2020-07-07 22:18:40 +08:00
|
|
|
|
|
|
|
class Link:
|
|
|
|
"""A navigation link in the pagination bar.
|
|
|
|
|
|
|
|
Attributes:
|
|
|
|
url (str): The link URL, or for a non-link slot.
|
|
|
|
title (str): The title of the link.
|
|
|
|
is_active (bool): Whether this link is currently active.
|
|
|
|
is_small_screen (bool): Whether this link is for small
|
|
|
|
screens
|
|
|
|
"""
|
2020-08-02 01:04:47 +08:00
|
|
|
def __int__(self):
|
|
|
|
self.url = None
|
|
|
|
self.title = None
|
|
|
|
self.is_active = False
|
|
|
|
self.is_small_screen = False
|
2020-07-07 20:54:35 +08:00
|
|
|
|
2020-07-08 23:40:36 +08:00
|
|
|
def page_size_options(self):
|
2020-08-02 01:04:47 +08:00
|
|
|
"""Returns the page size options.
|
|
|
|
|
|
|
|
Returns:
|
2020-08-13 08:05:35 +08:00
|
|
|
List[PageSizeOption]: The page size options.
|
2020-08-02 01:04:47 +08:00
|
|
|
"""
|
2020-08-05 10:17:46 +08:00
|
|
|
base_url = self.current_url.remove("page").remove("page-size")
|
2020-07-11 17:23:38 +08:00
|
|
|
return [self.PageSizeOption(x, self._page_size_url(base_url, x))
|
2020-07-09 01:03:03 +08:00
|
|
|
for x in [10, 100, 200]]
|
2020-07-08 23:40:36 +08:00
|
|
|
|
2020-07-11 17:23:38 +08:00
|
|
|
@staticmethod
|
2020-08-13 08:05:35 +08:00
|
|
|
def _page_size_url(base_url: UrlBuilder, size: int) -> str:
|
2020-07-11 17:23:38 +08:00
|
|
|
"""Returns the URL for a new page size.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
base_url (UrlBuilder): The base URL builder.
|
|
|
|
size (int): The new page size.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
str: The URL for the new page size.
|
|
|
|
"""
|
|
|
|
if size == Pagination.DEFAULT_PAGE_SIZE:
|
|
|
|
return str(base_url)
|
2020-07-31 21:16:03 +08:00
|
|
|
return str(base_url.clone().add("page-size", str(size)))
|
2020-07-11 17:23:38 +08:00
|
|
|
|
2020-07-08 23:40:36 +08:00
|
|
|
class PageSizeOption:
|
|
|
|
"""A page size option.
|
|
|
|
|
|
|
|
Args:
|
2020-08-13 08:05:35 +08:00
|
|
|
size: The page size.
|
|
|
|
url: The URL of this page size.
|
2020-07-08 23:40:36 +08:00
|
|
|
|
|
|
|
Attributes:
|
|
|
|
size (int): The page size.
|
|
|
|
url (str): The URL for this page size.
|
|
|
|
"""
|
2020-08-13 08:05:35 +08:00
|
|
|
def __init__(self, size: int, url: str):
|
2020-07-08 23:40:36 +08:00
|
|
|
self.size = size
|
|
|
|
self.url = url
|
|
|
|
|
2020-07-07 20:54:35 +08:00
|
|
|
|
2020-07-11 17:23:38 +08:00
|
|
|
class PaginationException(Exception):
|
|
|
|
"""The exception thrown with invalid pagination parameters.
|
2020-07-09 01:03:03 +08:00
|
|
|
|
|
|
|
Args:
|
2020-08-13 08:05:35 +08:00
|
|
|
url_builder: The canonical URL to redirect to.
|
2020-07-09 01:03:03 +08:00
|
|
|
|
2020-07-11 17:23:38 +08:00
|
|
|
Attributes:
|
|
|
|
url (str): The canonical URL to redirect to.
|
2020-07-09 01:03:03 +08:00
|
|
|
"""
|
2020-08-13 08:05:35 +08:00
|
|
|
def __init__(self, url_builder: UrlBuilder):
|
2020-08-05 10:17:46 +08:00
|
|
|
self.url = str(url_builder)
|
2020-08-29 21:54:12 +08:00
|
|
|
|
|
|
|
|
|
|
|
CDN_LIBRARIES = {
|
|
|
|
"jquery": {"css": [], "js": ["https://code.jquery.com/jquery-3.5.1.min.js"]},
|
|
|
|
"bootstrap4": {
|
|
|
|
"css": ["https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"],
|
|
|
|
"js": ["https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js",
|
|
|
|
"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"]},
|
|
|
|
"font-awesome-5": {
|
|
|
|
"css": ["https://use.fontawesome.com/releases/v5.14.0/css/all.css"],
|
|
|
|
"js": []},
|
|
|
|
"bootstrap4-datatables": {
|
|
|
|
"css": ["https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css",
|
|
|
|
"https://cdn.datatables.net/1.10.21/css/dataTables.bootstrap4.min.css"],
|
|
|
|
"js": ["https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js",
|
|
|
|
"https://cdn.datatables.net/1.10.21/js/dataTables.bootstrap4.min.js"]},
|
|
|
|
"jquery-ui": {"css": ["https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"],
|
|
|
|
"js": ["https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"]},
|
|
|
|
"bootstrap4-tempusdominus": {
|
|
|
|
"css": ["https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css"],
|
|
|
|
"js": ["https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment-with-locales.min.js",
|
|
|
|
"https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.js"]},
|
|
|
|
"decimal-js": {"css": [],
|
|
|
|
"js": ["https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.2.0/decimal.min.js"]},
|
|
|
|
"period-chooser": {"css": ["mia_core/css/period-chooser.css"],
|
|
|
|
"js": ["mia_core/js/period-chooser.js"]}
|
|
|
|
}
|
|
|
|
DEFAULT_LIBS = []
|
|
|
|
|
|
|
|
|
|
|
|
class CssAndJavaScriptLibraries:
|
|
|
|
"""The CSS and JavaScript library resolver."""
|
|
|
|
AVAILABLE_LIBS: List[str] = ["jquery", "bootstrap4", "font-awesome-5",
|
|
|
|
"bootstrap4-datatables", "jquery-ui",
|
|
|
|
"bootstrap4-tempusdominus", "decimal-js",
|
|
|
|
"i18n", "period-chooser"]
|
|
|
|
|
|
|
|
def __init__(self, *args):
|
|
|
|
self._use: Dict[str, bool] = {x: False for x in self.AVAILABLE_LIBS}
|
|
|
|
self._add_default_libs()
|
|
|
|
# The specified libraries
|
|
|
|
if len(args) > 0:
|
|
|
|
libs = args[0]
|
|
|
|
invalid = [x for x in libs if x not in self.AVAILABLE_LIBS]
|
|
|
|
if len(invalid) > 0:
|
|
|
|
raise NameError("library %s invalid" % ", ".join(invalid))
|
|
|
|
for lib in libs:
|
|
|
|
self._use[lib] = True
|
|
|
|
self._css = []
|
|
|
|
try:
|
|
|
|
self._css = self._css + settings.DEFAULT_CSS
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
self._js = []
|
|
|
|
try:
|
|
|
|
self._css = self._css + settings.DEFAULT_JS
|
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def _add_default_libs(self):
|
|
|
|
"""Adds the default libraries."""
|
|
|
|
invalid = [x for x in DEFAULT_LIBS if x not in self.AVAILABLE_LIBS]
|
|
|
|
if len(invalid) > 0:
|
|
|
|
raise NameError("library %s invalid" % ", ".join(invalid))
|
|
|
|
for lib in DEFAULT_LIBS:
|
|
|
|
self._use[lib] = True
|
|
|
|
|
|
|
|
def use(self, *args) -> None:
|
|
|
|
"""Use the specific libraries.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
args: The libraries.
|
|
|
|
"""
|
|
|
|
if len(args) == 0:
|
|
|
|
return
|
|
|
|
libs = args[0]
|
|
|
|
invalid = [x for x in libs if x not in self.AVAILABLE_LIBS]
|
|
|
|
if len(invalid) > 0:
|
|
|
|
raise NameError("library %s invalid" % ", ".join(invalid))
|
|
|
|
for lib in libs:
|
|
|
|
self._use[lib] = True
|
|
|
|
|
|
|
|
def add_css(self, css) -> None:
|
|
|
|
"""Adds a custom CSS file."""
|
|
|
|
self._css.append(css)
|
|
|
|
|
|
|
|
def add_js(self, js) -> None:
|
|
|
|
"""Adds a custom JavaScript file."""
|
|
|
|
self._js.append(js)
|
|
|
|
|
|
|
|
def css(self) -> List[str]:
|
|
|
|
"""Returns the stylesheet files to use."""
|
|
|
|
use: Dict[str, bool] = self._solve_use_depencies()
|
|
|
|
css = []
|
|
|
|
for lib in [x for x in self.AVAILABLE_LIBS if use[x]]:
|
|
|
|
if lib == "i18n":
|
|
|
|
continue
|
|
|
|
try:
|
|
|
|
css = css + settings.STATIC_LIBS[lib]["css"]
|
|
|
|
except AttributeError:
|
|
|
|
css = css + CDN_LIBRARIES[lib]["css"]
|
|
|
|
except TypeError:
|
|
|
|
css = css + CDN_LIBRARIES[lib]["css"]
|
|
|
|
except KeyError:
|
|
|
|
css = css + CDN_LIBRARIES[lib]["css"]
|
|
|
|
return css + self._css
|
|
|
|
|
|
|
|
def js(self) -> List[str]:
|
|
|
|
"""Returns the JavaScript files to use."""
|
|
|
|
use: Dict[str, bool] = self._solve_use_depencies()
|
|
|
|
js = []
|
|
|
|
for lib in [x for x in self.AVAILABLE_LIBS if use[x]]:
|
|
|
|
if lib == "i18n":
|
|
|
|
js.append(reverse("javascript-catalog"))
|
|
|
|
continue
|
|
|
|
try:
|
|
|
|
js = js + settings.STATIC_LIBS[lib]["js"]
|
|
|
|
except AttributeError:
|
|
|
|
js = js + CDN_LIBRARIES[lib]["js"]
|
|
|
|
except TypeError:
|
|
|
|
js = js + CDN_LIBRARIES[lib]["js"]
|
|
|
|
except KeyError:
|
|
|
|
js = js + CDN_LIBRARIES[lib]["js"]
|
|
|
|
return js + self._js
|
|
|
|
|
|
|
|
def _solve_use_depencies(self) -> Dict[str, bool]:
|
|
|
|
"""Solves and returns the library dependencies."""
|
|
|
|
use: Dict[str, bool] = {x: self._use[x] for x in self._use}
|
|
|
|
if use["period-chooser"]:
|
|
|
|
use["bootstrap4-tempusdominus"] = True
|
|
|
|
if use["bootstrap4-tempusdominus"]:
|
|
|
|
use["bootstrap4"] = True
|
|
|
|
if use["bootstrap4-datatables"]:
|
|
|
|
use["bootstrap4"] = True
|
|
|
|
if use["jquery-ui"]:
|
|
|
|
use["jquery"] = True
|
|
|
|
if use["bootstrap4"]:
|
|
|
|
use["jquery"] = True
|
|
|
|
return use
|
|
|
|
|
|
|
|
|
|
|
|
def add_default_libs(*args) -> None:
|
|
|
|
"""Adds the specified libraries to the default CSS and JavaScript
|
|
|
|
libraries.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
args: The libraries to be added to the default libraries
|
|
|
|
"""
|
|
|
|
libs = args
|
|
|
|
invalid = [x for x in libs
|
|
|
|
if x not in CssAndJavaScriptLibraries.AVAILABLE_LIBS]
|
|
|
|
if len(invalid) > 0:
|
|
|
|
raise NameError("library %s invalid" % ", ".join(invalid))
|
|
|
|
for lib in libs:
|
|
|
|
if lib not in DEFAULT_LIBS:
|
|
|
|
DEFAULT_LIBS.append(lib)
|