# SPDX-FileCopyrightText: 2024 Thomas Breitner <t.breitner@csl.mpg.de>
#
# SPDX-License-Identifier: EUPL-1.2
from io import BytesIO
from pathlib import Path
from django.template.loader import render_to_string
from django.core.files.images import ImageFile
from wagtail.images import get_image_model
from wagtail.images.rect import Rect
from pdf2image import convert_from_bytes
from wagtail.admin.mail import send_mail
from wagtail.models import Collection
from django_countries import Countries
[docs]
class Languages(Countries):
only = [
"GB",
"FR",
"DE",
]
[docs]
def send_email(
instance=None, page=None, mail_template=None, recipient_list=None, user=None
):
"""
Sends a notification email to a user when her/his ProfilePage is
created.
TODO: refactor to use this function for different kind of emails
"""
from eucrim.core.models import HomePage
this_site = HomePage.objects.first().get_site()
email_context = {
# 'settings': settings,
"root_url": this_site.root_url,
"user": user,
"page": page,
# 'first_name': instance.first_name,
# 'last_name': instance.last_name,
# 'username': instance.username,
# 'email': instance.email,
}
template_subject = "users/notifications/{}_subject.txt".format(mail_template)
template_message = "users/notifications/{}_message.txt".format(mail_template)
email_subject = render_to_string(template_subject, email_context).strip()
email_message = render_to_string(template_message, email_context).strip()
send_mail(
email_subject,
email_message,
recipient_list,
)
[docs]
def get_or_create_collection(name):
root_collection = Collection.get_first_root_node()
try:
collection = Collection.objects.get(name=name)
except Collection.DoesNotExist:
collection = root_collection.add_child(name=name)
except Exception as e:
raise e
return collection
[docs]
def generate_cover_image(file_obj, name=None):
if not name:
name = Path(file_obj.name).name
_cover_bitmap = convert_from_bytes(file_obj.read(), single_file=True)[
0
] # first_page=1, last_page=1
_cover_bitmap_io = BytesIO()
_cover_bitmap.save(_cover_bitmap_io, "JPEG")
cover_imagefile = ImageFile(
_cover_bitmap_io,
name=name,
)
# generate a focal_point - via Rect(left, top, right, bottom)
focal_point = Rect(0, 0, 0, 0)
ImageModel = get_image_model()
cover_image = ImageModel(
title=name,
file=cover_imagefile,
collection=get_or_create_collection("Issue covers"),
)
cover_image.set_focal_point(focal_point)
cover_image.save()
return cover_image
# def get_promote_panels_without_show_in_menus(promote_panels):
# """
# FIXME: seems to remove the field from the Page class for all pages.
# promote_panels = Page.promote_panels
# for p in promote_panels:
# for f in p.children:
# print(f"{f.field_name=}")
# """
# promote_panels[1].children = [field for field in promote_panels[1].children if field.field_name != "show_in_menus"]
# return promote_panels