summaryrefslogtreecommitdiffstats
path: root/activities/templatetags/activity_tags.py
blob: fb822f6e1a7326dfcebea628fee826c1d3bd0a97 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import datetime

from django import template
from django.utils import timezone

from activities.models import Hashtag

register = template.Library()


@register.filter
def timedeltashort(value: datetime.datetime):
    """
    A more compact version of timesince
    """
    if not value:
        return ""
    # TODO: Handle things in the future properly
    delta = timezone.now() - value
    seconds = int(delta.total_seconds())
    days = delta.days
    if seconds < 60:
        text = f"{seconds:0n}s"
    elif seconds < 60 * 60:
        minutes = seconds // 60
        text = f"{minutes:0n}m"
    elif seconds < 60 * 60 * 24:
        hours = seconds // (60 * 60)
        text = f"{hours:0n}h"
    elif days < 365:
        text = f"{days:0n}d"
    else:
        years = max(days // 365.25, 1)
        text = f"{years:0n}y"
    return text


@register.filter
def linkify_hashtags(value: str):
    """
    Convert hashtags in content in to /tags/<hashtag>/ links.
    """
    if not value:
        return ""

    return Hashtag.linkify_hashtags(value)