aboutsummaryrefslogtreecommitdiff
path: root/glifestream/stream/templatetags/gls_filters.py
blob: 4be8f7bb151beeab6c7c4c4bd86f1f234891f44f (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
#  gLifestream Copyright (C) 2009, 2011, 2015 Wojciech Polak
#
#  This program is free software; you can redistribute it and/or modify it
#  under the terms of the GNU 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 General Public License for more details.
#
#  You should have received a copy of the GNU General Public License along
#  with this program.  If not, see <http://www.gnu.org/licenses/>.

from django import template
register = template.Library()

import re
import math
import time
import datetime
import calendar
from django.conf import settings
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.template.defaultfilters import date as ddate
from django.template.defaultfilters import urlencode, stringfilter
from glifestream.utils.slugify import slugify
from glifestream.stream import media
from glifestream.apis import *

try:
    import json
except ImportError:
    import simplejson as json


@register.filter
def gls_date(date):
    ts = calendar.timegm(date.utctimetuple())
    if (time.time() - ts) > (7 * 86400):
        return ddate(datetime.datetime.fromtimestamp(ts), 'D, d-m-Y')
    else:
        return get_relative_time(date)


@register.filter
def gls_udate(date):
    return int(time.mktime(date.timetuple()))


@register.filter
def gls_hdate(date):
    ts = time.mktime(date.timetuple())
    return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%dT%H:%M:%SZ')


@register.filter
def gls_media(s):
    return media.set_upload_url(media.set_thumbs_url(s))


@register.filter
def gls_link(e, entry):
    if not entry.service.public:
        if entry.author_name:
            return '?class=%s&author=%s' % (entry.service.cls,
                                            urlencode(entry.author_name))
    else:
        return '?class=%s' % entry.service.cls
    return entry.service.link


@register.filter
def gls_title(e, entry):
    title = entry.title
    try:
        mod = eval(entry.service.api)
        if hasattr(mod, 'filter_title'):
            title = mod.filter_title(entry)
    except:
        pass
    if entry.friends_only:
        title = ''
    if title == '':
        title = str(entry.date_published)[0:16]
    return mark_safe(title)


@register.filter
def gls_content(e, entry):
    if entry.friends_only:
        return mark_safe('<div class="friends-only-entry"><p>' +
                         _('The content of this entry is available only to my friends. If you are listed as my friend on Facebook, you may click Facebook Connect button to read it.') + '</p><p><fb:login-button v="2" size="medium" onlogin="fb_login_friend()"></fb:login-button></p></div>')
    try:
        mod = eval(entry.service.api)
        if hasattr(mod, 'filter_content'):
            s = mod.filter_content(entry)
            if entry.geolat and entry.geolng:
                s += '<div class="geo"><a href="#" class="show-map"><span class="latitude">%.10f</span> <span class="longitude">%.10f</span>%s</a></div>' % (
                    entry.geolat, entry.geolng, _('show map'))
            return mark_safe(gls_media(s))
    except:
        pass
    return mark_safe(gls_media(force_text(entry.content)))


@register.filter
def gls_mediarss(e, entry):
    if entry.friends_only:
        return ''
    return mark_safe(media.mrss_gen_xml(entry))


@register.filter
def gls_reply_url(e, entry):
    if entry.service.api == 'twitter':
        u = entry.link.split('/')
        return 'https://twitter.com/?status=@%s%%20&in_reply_to_status_id=%s&in_reply_to=%s' % (u[3], u[5], u[3])
    elif entry.service.api == 'identica':
        return 'http://identi.ca/notice/new?replyto=%s' % entry.author_name
    return '#'


@register.filter
def gls_slugify(value):
    s = slugify(value)
    if len(s) and s[-1] == '-':
        s = s[0:-1]
    a = s.split('-')
    if len(a) > 1 and a[-1].startswith('http'):
        a.pop()
        s = '-'.join(a)
    return s


@register.filter
def get_relative_time(t):
    t = time.mktime(t.utctimetuple())
    diff_seconds = (t - time.mktime(time.gmtime())) + 20
    diff_minutes = math.fabs(int(math.floor(diff_seconds / 60)))

    if diff_minutes > (60 * 24):
        rel = int(math.floor(diff_minutes / (60 * 24)))
        if rel == 1:
            rel = _('Yesterday')
        else:
            rel = _('%d days ago') % rel
    elif diff_minutes > 60:
        rel = int(math.floor(diff_minutes / 60))
        rel = ungettext ('%(count)d hour ago', '%(count)d hours ago', rel) % \
            {'count': rel, }
    else:
        rel = int(diff_minutes)
        rel = ungettext ('%(count)d minute ago', '%(count)d minutes ago', rel) % \
            {'count': rel, }
    return rel


@register.filter
def encode_json(content):
    enc = json.JSONEncoder()
    return mark_safe(enc.encode(content))


unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)')


def fix_ampersands(value):
    return unencoded_ampersands_re.sub('&amp;', force_text(value))


@register.filter('gls_fix_ampersands', is_safe=True)
@stringfilter
def fix_ampersands_filter(value):
    """Replaces ampersands with ``&amp;`` entities."""
    return fix_ampersands(value)

Return to:

Send suggestions and report system problems to the System administrator.