Fix subscriber counts in podcast toplist/search results
[mygpo.git] / mygpo / web / templatetags / charts.py
blob2a0240c210f9350dc0af13c0effe452a2bd31ef6
1 from django import template
2 from django.utils.safestring import mark_safe
3 from django.utils.html import format_html
4 from django.contrib.staticfiles.storage import staticfiles_storage
6 from mygpo.utils import format_time
7 from mygpo.publisher.utils import colour_repr
10 register = template.Library()
12 @register.simple_tag
13 def vertical_bar(value, max_value, display=None):
14 if not max_value:
15 return ''
17 if display == 'ratio':
18 value_str = '%d/%d' % (value, max_value)
19 else:
20 value_str = str(value)
22 # handle value == None
23 value = value or 0
25 try:
26 ratio = min(float(value) / float(max_value), 1) * 100
27 except ValueError:
28 return ''
30 if ratio > 40:
31 left = format_html('<span>{}</span>', value_str)
32 right = ''
33 else:
34 left = format_html('&nbsp;')
35 right = format_html('<span>{}</span>', value_str)
37 return format_html('<div class="barbg"><div class="bar" '
38 'style="width: {:.2d}%">{}</div>{}</div>',
39 ratio, left, right)
40 return s
42 @register.filter
43 def timeline(data):
44 s = '<script type="text/javascript" src="//www.google.com/jsapi"></script>\n'
45 s += '<script type="text/javascript">\n'
46 s += 'google.load("visualization", "1", {"packages":["annotatedtimeline"]});\n'
47 s += 'google.setOnLoadCallback(drawChart);\n'
48 s += 'function drawChart() {\n'
49 s += 'var data = new google.visualization.DataTable();\n'
50 s += 'data.addColumn("date", "Date");\n'
51 s += 'data.addColumn("number", "Listeners");\n'
52 s += 'data.addColumn("string", "title1");\n'
53 s += 'data.addColumn("string", "text1");\n'
54 s += 'data.addRows([\n'
56 for r in data:
57 if r.episode:
58 episode = '"%s"' % r.episode.display_title
59 episode_ = '"released"'
60 else:
61 episode = 'undefined'
62 episode_ = 'undefined'
64 s += '[new Date(%d, %d, %d), %d, %s, %s],\n' % (r.date.year, r.date.month-1, r.date.day, r.playcount, episode, episode_)
66 s += ']);\n'
67 s += 'var chart = new google.visualization.AnnotatedTimeLine(document.getElementById("chart_div"));\n'
68 s += 'chart.draw(data, {displayAnnotations: true});\n'
69 s += '}\n'
70 s += '</script>\n'
72 return mark_safe(s)
75 @register.filter
76 def pie_chart(parts):
77 parts = [
78 'cht=p',
79 'chs=250x100',
80 'chl=%s' % '|'.join(parts.keys()),
81 'chd=t:%s' % ','.join([ repr(x) for x in parts.values() ])
84 s = '<img src="http://chart.apis.google.com/chart?%s"' % '&'.join(parts)
86 return mark_safe(s)
89 @register.simple_tag
90 def subscriber_change(change):
92 if change > 1:
93 change -= 1
94 return '+{0:.1%}'.format(change)
96 # we don't care about negative changes
97 return ''