-
Tor-Einar Skog authoredTor-Einar Skog authored
models.py 9.10 KiB
#
# Copyright (c) 2013-2023 NIBIO.
#
# This file is part of VIPSWeb
# (see https://gitlab.nibio.no/VIPS/VIPSWeb).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
import requests
from django.conf import settings
from django.db import models
from django.utils.translation import gettext as _
from datetime import datetime
class MessageTag:
""" Tags for the Message class.
Fetched from VIPSLogic backend using REST protocol
"""
def __init__(self,
message_tag_id,
default_tag_name,
local_tag_name = None
):
self.message_tag_id = message_tag_id
self.default_tag_name = default_tag_name
self.local_tag_name = local_tag_name
@staticmethod
def get_message_tags(current_language=settings.VIPSLOGIC_LANGUAGE_CODE):
message_tags = []
for item in MessageTag.get_message_tags_as_json():
message_tag = MessageTag.get_instance_from_dict(item, current_language)
message_tags.append(message_tag)
return message_tags
@staticmethod
def get_message_tags_as_json():
request_result = requests.get("%s://%s/rest/messagetag/list" % (settings.VIPSLOGIC_PROTOCOL, settings.VIPSLOGIC_SERVER_NAME))
return request_result.json()
@staticmethod
def get_instance_from_dict(item, current_language=settings.VIPSLOGIC_LANGUAGE_CODE):
local_tag_name = None
for tagLocale in item["messageTagLocaleSet"]:
if tagLocale["messageTagLocalePK"]["locale"] == current_language:
local_tag_name = tagLocale["localName"]
return MessageTag(
item["messageTagId"],
item["defaultTagName"],
local_tag_name
)
class Message:
""" Represents a message from VIPS to the users.
Fetched from VIPSLogic backend using REST protocol
"""
def __init__(self,
message_id,
organization_id,
heading,
lead_paragraph,
body,
date_pub,
date_valid_to,
illustration_file_name,
illustration_caption,
created_by,
crop_category_ids
):
self.message_id = message_id
self.organization_id = organization_id
self.heading = heading
self.lead_paragraph = lead_paragraph
self.body = body
self.date_pub = date_pub
self.date_valid_to = date_valid_to
self.illustration_file_name = illustration_file_name
self.illustration_caption = illustration_caption
self.created_by = created_by
self.crop_category_ids = crop_category_ids
def get_illustration_url(self):
return "%s://%s/static/images/messages/%s/%s" % (settings.VIPSLOGIC_PROTOCOL, settings.VIPSLOGIC_SERVER_NAME,self.organization_id,self.illustration_file_name)
"""
Getting information from persistence layer
Currently this is a REST service
"""
@staticmethod
def get_message(message_id, current_language=settings.VIPSLOGIC_LANGUAGE_CODE):
message_json = Message.get_message_as_json(message_id)
if message_json is not None:
return Message.get_instance_from_dict(message_json, current_language)
return None
@staticmethod
def get_messages_by_tag(tag_id, current_language=settings.VIPSLOGIC_LANGUAGE_CODE):
messages = []
for item in Message.get_messages_by_tag_as_json(tag_id):
message = Message.get_instance_from_dict(item, current_language)
messages.append(message)
return messages
@staticmethod
def get_messages(current_language=settings.VIPSLOGIC_LANGUAGE_CODE, publishedFrom=None, publishedTo=None):
messages = []
for item in Message.get_messages_as_json(publishedFrom, publishedTo):
message = Message.get_instance_from_dict(item, current_language)
messages.append(message)
return messages
@staticmethod
def get_messages_as_json(publishedFrom=None, publishedTo=None):
payload = {"publishedFrom":publishedFrom, "publishedTo":publishedTo}
request_result = requests.get(
"%s://%s/rest/message/list/%s" % (settings.VIPSLOGIC_PROTOCOL, settings.VIPSLOGIC_SERVER_NAME,settings.VIPS_ORGANIZATION_ID),
params=payload
)
return request_result.json()
@staticmethod
def get_messages_by_tag_as_json(tag_id):
request_result = requests.get("%s://%s/rest/message/list/%s/tagfilter?tagId=%s" % (settings.VIPSLOGIC_PROTOCOL, settings.VIPSLOGIC_SERVER_NAME,settings.VIPS_ORGANIZATION_ID,tag_id))
return request_result.json()
@staticmethod
def get_message_as_json(message_id):
request_result = requests.get("%s://%s/rest/message/%s" % (settings.VIPSLOGIC_PROTOCOL, settings.VIPSLOGIC_SERVER_NAME,message_id))
if request_result.status_code == 200:
return request_result.json()
return None
@staticmethod
def get_instance_from_dict(the_dict,current_language=settings.VIPSLOGIC_LANGUAGE_CODE):
message_locale = Message.get_message_locale(the_dict["messageLocaleSet"], current_language)
message_illustration = Message.get_illustration(the_dict["messageIllustrationSet"], current_language)
created_by = ""
if message_locale.get("createdBy","") != "":
created_by = "%s %s" %(
message_locale["createdBy"].get("firstName",""),
message_locale["createdBy"].get("lastName","")
)
#print the_dict["datePub"]
return Message(
the_dict["messageId"],
the_dict["organizationId"],
message_locale.get("heading","MISSING HEADING FOR LOCALE '%s'" % current_language),
message_locale.get("leadParagraph","MISSING LEAD PARAGRAPH FOR LOCALE '%s'" % current_language),
message_locale.get("body","MISSING BODY TEXT FOR LOCALE '%s'" % current_language),
datetime.strptime(the_dict["datePub"],settings.VIPSLOGIC_DATE_FORMAT) ,
datetime.strptime(the_dict["dateValidTo"],settings.VIPSLOGIC_DATE_FORMAT),
message_illustration.get("file_name", None),
message_illustration.get("caption", None),
created_by,
the_dict.get("cropCategoryIds",[])
)
@staticmethod
def get_message_locale(message_locale_set, language):
for message_locale in message_locale_set:
if message_locale["messageLocalePK"]["locale"] == language:
return message_locale
# Fallback: Find message in web site's default language
for message_locale in message_locale_set:
if message_locale["messageLocalePK"]["locale"] == settings.LANGUAGE_CODE:
return message_locale
# If none of this works, try to return the first locale found
# If no locale, return empty set
if len(message_locale_set) > 0:
return message_locale_set[0]
else:
return {}
@staticmethod
def get_illustration(message_illustration_set, language):
message_illustration = {}
if len(message_illustration_set) == 1:
message_illustration["file_name"] = message_illustration_set[0]["messageIllustrationPK"]["fileName"]
for caption in message_illustration_set[0]["messageIllustrationCaptionLocaleSet"]:
if caption["messageIllustrationCaptionLocalePK"]["locale"] == language:
message_illustration["caption"] = caption["caption"]
return message_illustration
class Advertisement(models.Model):
def __unicode__(self):
return self.ad_heading
def __str__(self):
return self.ad_heading
""" Represents an advertisement to be shown on the frontpage """
ad_heading = models.CharField(max_length=200, verbose_name=_("Headline"))
ad_text = models.TextField()
pub_date = models.DateField(verbose_name=_("Date published"))
exp_date = models.DateField(verbose_name=_("Date expired"))
illustration = models.ImageField(upload_to='images/advertisement', blank=True, verbose_name=_("Illustration"))