74 lines
2.0 KiB
Python
74 lines
2.0 KiB
Python
from datetime import timedelta
|
|
|
|
from django.conf import settings
|
|
from django.db.models import Sum
|
|
from django.utils import timezone
|
|
|
|
from .models import Chapter, Entry, TrafficDaily
|
|
|
|
|
|
def traffic_report(request):
|
|
days = request.GET.get('days', '30')
|
|
days = int(days) if days in ('7', '30', '90') else 30
|
|
|
|
kind = request.GET.get('kind', 'all')
|
|
if kind not in ('all', 'chapter', 'blog'):
|
|
kind = 'all'
|
|
|
|
qs = TrafficDaily.objects.filter(
|
|
day__gte=timezone.localdate() - timedelta(days=days - 1)
|
|
)
|
|
|
|
if kind != 'all':
|
|
qs = qs.filter(kind=kind)
|
|
|
|
def grouped(*fields):
|
|
return qs.values(*fields).annotate(
|
|
views=Sum('views')
|
|
).order_by('-views', *fields)
|
|
|
|
counts = {row['kind']: row['views'] for row in grouped('kind')}
|
|
|
|
countries = list(grouped('country'))
|
|
regions = list(grouped('country', 'region')[:100])
|
|
cities = list(grouped('country', 'region', 'city')[:100])
|
|
|
|
sources = grouped('source')[:30]
|
|
series = list(grouped('day').order_by('day'))
|
|
|
|
top = list(
|
|
qs.exclude(target_id=0)
|
|
.values('kind', 'target_id')
|
|
.annotate(views=Sum('views'))
|
|
.order_by('-views', 'target_id')[:25]
|
|
)
|
|
|
|
chapters = Chapter.objects.in_bulk(
|
|
row['target_id'] for row in top if row['kind'] == 'chapter'
|
|
)
|
|
posts = Entry.objects.in_bulk(
|
|
row['target_id'] for row in top if row['kind'] == 'blog'
|
|
)
|
|
|
|
for row in top:
|
|
obj = (
|
|
chapters if row['kind'] == 'chapter' else posts
|
|
).get(row['target_id'])
|
|
row['title'] = str(obj) if obj else 'Removed content'
|
|
|
|
return {
|
|
'days': days,
|
|
'kind': kind,
|
|
'total': sum(counts.values()),
|
|
'chapters': counts.get('chapter', 0),
|
|
'blogs': counts.get('blog', 0),
|
|
'countries': countries,
|
|
'regions': regions,
|
|
'cities': cities,
|
|
'sources': sources,
|
|
'top': top,
|
|
'series': series,
|
|
'analytics_enabled': settings.SLX_ANALYTICS,
|
|
'geo_configured': bool(settings.SLX_GEOIP_DB),
|
|
}
|