Coverage for src/ptf/templatetags/helpers.py: 52%
213 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-05 09:56 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-05 09:56 +0000
1import os
2from urllib.parse import unquote
4from langcodes import Language
6from django import template
7from django.contrib.staticfiles.finders import find
8from django.http import QueryDict
9from django.template.defaultfilters import stringfilter
10from django.urls import reverse
11from django.utils.translation import gettext as _
13from ptf import models
14from ptf.display import resolver
15from ptf.model_helpers import get_resource as get_resource_helper
16from ptf.solr.search_helpers import CleanSearchURL
18register = template.Library()
21@register.filter
22@stringfilter
23def get_resource(value):
24 """Usage, {% if pid|get_resource %}"""
25 resource = get_resource_helper(value)
26 return resource
29@register.simple_tag
30def get_resource_url(pid):
31 resource = models.Resource.objects.get(pid=pid)
32 resource = resource.cast()
33 return resource.get_url_absolute()
36@register.filter
37@stringfilter
38def cleanURL_encode(value, arg):
39 """Usage : {{ 'q=test&qt=all'|cleanURL_encode:request.path }}"""
40 query = QueryDict(value)
41 return CleanSearchURL.encode(query, arg)
44def decode_query_string(request):
45 raw_query_string = request.META.get("QUERY_STRING", "")
46 if raw_query_string:
47 decoded_query_string = unquote(raw_query_string)
48 else:
49 decoded_query_string = ""
50 return decoded_query_string
53@register.simple_tag
54def pretty_search(url, encoding, *args):
55 """
56 Usage {% pretty_search 'path' 'q' criteria1 criteria2 ... %}
57 @param path: the url name
58 @param encoding: one or many encodings reference to CleanSearchURL
59 @param args: one or many criteria for search
60 @return: url with querystring like search?q=test+a
61 """
62 path = reverse(url)
63 query_parts = []
64 for index in range(len(encoding)):
65 if args[index]: 65 ↛ 64line 65 didn't jump to line 64 because the condition on line 65 was always true
66 query_parts.append(f"{args[index]}")
67 query_string = " ".join(query_parts)
68 return f"{path}?{query_string}-{encoding}"
71@register.filter
72@stringfilter
73def cleanURL_params_paginate(value, page):
74 """
75 création du lien pour la pagination
76 exemple Usage : {{ '?q=test+all+qa'|cleanURL_encode:"3" }}
77 @return: ?q=test+all+3+qat
78 """
79 print("Value ", value, " page ", str(page))
80 _, query = CleanSearchURL.decode(value)
81 print("Query ", query)
82 queryDict = query.copy()
83 if "page" in queryDict:
84 del queryDict["page"] # supprime la page demandée
85 queryDict.appendlist("page", str(page))
87 result = CleanSearchURL.encode(queryDict, "")
88 return result
91@register.filter
92@stringfilter
93def build_Url_paginate(value, page):
94 print("Value", value, "Page", page)
95 newQuery = ""
96 if len(value) > 1:
97 newQuery = value + "&"
98 else:
99 newQuery = value + "?"
100 newQuery = newQuery + "page" + "=" + str(page)
101 return newQuery
104@register.filter
105@stringfilter
106def replace_basename_binary_file(value):
107 """Usage, {% binary_file.pdf| static_basename_binary_file %}"""
108 # if hasattr(settings, 'SITE_URL_PREFIX'):
109 # if len(value) > 0 and value[0] != '/':
110 # value = '/' + settings.SITE_URL_PREFIX + '/' + value
111 # else:
112 # value = '/' + settings.SITE_URL_PREFIX + value
113 return value
116@register.filter
117@stringfilter
118def basename(value):
119 return os.path.basename(value)
122@register.filter
123def sort_by(queryset, order):
124 return queryset.order_by(order)
127@register.filter
128def sort_by_date(queryset, container):
129 if container.my_collection.pid == "PCJ": 129 ↛ 130line 129 didn't jump to line 130 because the condition on line 129 was never true
130 return queryset.order_by("-date_published")
131 return queryset
134# @register.filter
135# def get_abstract_tag(queryset, tag):
136# return queryset.filter(tag=tag)
139@register.simple_tag
140def get_flag_icon(language):
141 flag = "flag-icon-"
143 if language == "en":
144 flag += "gb"
145 # elif language == "es":
146 # flag += "mx"
147 else:
148 flag += language
150 return flag
153@register.filter
154def get_flag_unicode(lang):
155 territory = Language.get(lang).maximize().territory
156 if lang == "en":
157 territory = "GB"
158 elif lang == "pt":
159 territory = "PT"
160 points = [ord(x) + 127397 for x in territory]
161 return chr(points[0]) + chr(points[1])
164@register.filter
165@stringfilter
166def short_doi(value):
167 if len(value) > 9: 167 ↛ 170line 167 didn't jump to line 170 because the condition on line 167 was always true
168 value = value[8:]
170 return value
173@register.filter
174@stringfilter
175def get_doi_url(value):
176 if value and value.find("10.") == 0:
177 value = resolver.get_doi_url(value)
178 else:
179 value = ""
181 return value
184@register.filter
185@stringfilter
186def get_type_value(value):
187 value = resolver.ARTICLE_TYPES.get(value, "Article de recherche")
188 return value
191@register.filter
192def exclude_do_not_publish_filter(queryset, export_to_website):
193 """
194 if we export to website (production), we don't export article for which do_not_publish=True
195 """
196 qs = queryset
197 if export_to_website: 197 ↛ 198line 197 didn't jump to line 198 because the condition on line 197 was never true
198 qs = queryset.exclude(do_not_publish=True)
199 return qs
202@register.filter
203def are_all_equal_contrib(contributions):
204 return models.are_all_equal_contrib(contributions)
207@register.filter
208def filter_by_role(contributions, role):
209 if contributions is None: 209 ↛ 210line 209 didn't jump to line 210 because the condition on line 209 was never true
210 return []
211 return [contribution for contribution in contributions if contribution.role.find(role) == 0]
214@register.filter
215def get_addresses(contributions):
216 addresses = []
217 for contribution in contributions:
218 for contrib_address in contribution.contribaddress_set.all():
219 if contrib_address.address not in addresses:
220 addresses.append(contrib_address.address)
221 return addresses
224@register.filter
225def contributions_with_index(contributions, addresses):
226 results = []
227 for contribution in contributions:
228 indexes = []
229 for contrib_address in contribution.contribaddress_set.all():
230 address = contrib_address.address
231 index = addresses.index(address) + 1
232 if index not in [item["index"] for item in indexes]:
233 indexes.append({"index": index, "address": address})
234 # indexes.sort(key=lambda d: d['index'])
235 results.append((contribution, indexes))
236 return results
239@register.filter
240def address_index_value(index, with_letter):
241 value = index
242 if with_letter:
243 value = chr(ord("a") + index - 1)
244 return value
247@register.filter
248def affiliation_id(with_letter):
249 return "affilition_a" if with_letter else "affiliation"
252@register.filter
253def contributions_with_letter_index(contributions, addresses):
254 results = []
255 for contribution in contributions:
256 indexes = []
257 for contrib_address in contribution.contribaddress_set.all():
258 address = contrib_address.address
259 index = addresses.index(address) + 1
260 letter = chr(ord("a") + index)
261 if index not in [item["index"] for item in indexes]:
262 indexes.append({"index": letter, "address": address})
263 # indexes.sort(key=lambda d: d['index'])
264 results.append((contribution, indexes))
265 return results
268@register.filter
269def is_author_of_original_article(contribution, original_contributions):
270 if original_contributions is None or len(original_contributions) == 0:
271 return False
273 is_original_author = False
274 i = 0
275 while not is_original_author and i < len(original_contributions):
276 if contribution.is_equal(original_contributions[i]):
277 is_original_author = True
278 i += 1
280 return is_original_author
283@register.filter
284def to_str(value):
285 return str(value)
288@register.filter
289def get_dict_item(my_dict: dict, key: str):
290 """
291 Wrapper around dict.get() that can be used directly in templates.
292 Its purpose is to the ability to pass a variable instead of a plain string.
293 Usage `my_dict|get_dict_item:key`
294 """
295 return my_dict.get(key)
298@register.filter
299def get_article_heading(article):
300 heading = article.get_subj_text()
301 collection = article.get_top_collection()
302 if collection.pid in ["CRMATH", "CRMECA", "CRPHYS", "CRGEOS", "CRCHIM", "CRBIOL"]: 302 ↛ 311line 302 didn't jump to line 311 because the condition on line 302 was always true
303 if int(article.my_container.year) > 2023: 303 ↛ 304line 303 didn't jump to line 304 because the condition on line 303 was never true
304 atype = resolver.ARTICLE_TYPES.get(article.atype, None)
305 if atype is not None:
306 if heading:
307 heading = _(atype) + " - " + heading
308 else:
309 heading = _(atype)
311 return heading
314@register.filter
315def get_image_path(journal: models.Collection, logo: bool = False):
316 """
317 Usage: `journal|get_image_path`
318 @param journal: La revue dont l'on veut récupérer l'image
319 @param logo: Booléen indiquant si l'on veut récupérer le logo ou non
320 @return un string contenant le chemin vers l'image, par exemple : "pid/img/PID.jpg" ou "pid/img/pid.png" dans le cas d'un logo
321 """
322 if journal is None or type(journal) is not models.Collection:
323 return ""
325 pid = journal.pid
326 # Si le pid final est en minuscule, on récupère le logo
327 link = pid.lower() + "/img/" + (pid if not logo else pid.lower())
328 for extension in [".jpg", ".png"]:
329 # Si find renvoie None, c'est que l'image n'a pas été trouvé pour cette extension
330 abs_path = find(link + extension)
331 if abs_path is not None: 331 ↛ 332line 331 didn't jump to line 332 because the condition on line 331 was never true
332 break
333 else:
334 # Dans le cas où on a rien trouvé
335 return ""
337 return link + extension