fix length calculation of celery queue
[mygpo.git] / mygpo / admin / views.py
blob3d0db37c71e5d4f8f97df931c3b7d80397a19f39
1 import re
2 import socket
3 from itertools import count, chain
4 from collections import Counter
6 import django
7 from django.shortcuts import render
8 from django.contrib import messages
9 from django.core.urlresolvers import reverse
10 from django.core.cache import cache
11 from django.http import HttpResponseRedirect
12 from django.utils.translation import ugettext as _
13 from django.views.generic import TemplateView
14 from django.utils.decorators import method_decorator
15 from django.conf import settings
17 from mygpo.admin.auth import require_staff
18 from mygpo.admin.group import PodcastGrouper
19 from mygpo.maintenance.merge import PodcastMerger, IncorrectMergeException
20 from mygpo.users.models import User
21 from mygpo.admin.clients import UserAgentStats, ClientStats
22 from mygpo.admin.tasks import merge_podcasts, unify_slugs
23 from mygpo.utils import get_git_head
24 from mygpo.api.httpresponse import JsonResponse
25 from mygpo.cel import celery
26 from mygpo.db.couchdb import get_main_database
27 from mygpo.db.couchdb.user import activate_user
28 from mygpo.db.couchdb.episode import episode_count, filetype_stats
29 from mygpo.db.couchdb.podcast import podcast_count, podcast_for_url
32 class InvalidPodcast(Exception):
33 """ raised when we try to merge a podcast that doesn't exist """
35 class AdminView(TemplateView):
37 @method_decorator(require_staff)
38 def dispatch(self, *args, **kwargs):
39 return super(AdminView, self).dispatch(*args, **kwargs)
42 class Overview(AdminView):
43 template_name = 'admin/overview.html'
46 class HostInfo(AdminView):
47 """ shows host information for diagnosis """
49 template_name = 'admin/hostinfo.html'
51 def get(self, request):
52 commit, msg = get_git_head()
53 base_dir = settings.BASE_DIR
54 hostname = socket.gethostname()
55 django_version = django.VERSION
57 main_db = get_main_database()
59 db_tasks = main_db.server.active_tasks()
61 i = celery.control.inspect()
62 scheduled = i.scheduled()
63 if not scheduled:
64 num_celery_tasks = None
65 else:
66 num_celery_tasks = sum(len(node) for node in scheduled.values())
68 return self.render_to_response({
69 'git_commit': commit,
70 'git_msg': msg,
71 'base_dir': base_dir,
72 'hostname': hostname,
73 'django_version': django_version,
74 'main_db': main_db.uri,
75 'db_tasks': db_tasks,
76 'num_celery_tasks': num_celery_tasks,
81 class MergeSelect(AdminView):
82 template_name = 'admin/merge-select.html'
84 def get(self, request):
85 num = int(request.GET.get('podcasts', 2))
86 urls = [''] * num
88 return self.render_to_response({
89 'urls': urls,
93 class MergeBase(AdminView):
95 def _get_podcasts(self, request):
96 podcasts = []
97 for n in count():
98 podcast_url = request.POST.get('feed%d' % n, None)
99 if podcast_url is None:
100 break
102 if not podcast_url:
103 continue
105 podcast = podcast_for_url(podcast_url)
107 if not podcast:
108 raise InvalidPodcast(podcast_url)
110 podcasts.append(podcast_for_url(podcast_url))
112 return podcasts
115 class MergeVerify(MergeBase):
117 template_name = 'admin/merge-grouping.html'
119 def post(self, request):
121 try:
122 podcasts = self._get_podcasts(request)
124 except InvalidPodcast as ip:
125 messages.error(request,
126 _('No podcast with URL {url}').format(url=str(ip)))
128 grouper = PodcastGrouper(podcasts)
130 get_features = lambda (e_id, e): ((e.url, e.title), e_id)
132 num_groups = grouper.group(get_features)
134 return self.render_to_response({
135 'podcasts': podcasts,
136 'groups': num_groups,
140 class MergeProcess(MergeBase):
142 RE_EPISODE = re.compile(r'episode_([0-9a-fA-F]{32})')
144 def post(self, request):
146 try:
147 podcasts = self._get_podcasts(request)
149 except InvalidPodcast as ip:
150 messages.error(request,
151 _('No podcast with URL {url}').format(url=str(ip)))
153 grouper = PodcastGrouper(podcasts)
155 features = {}
156 for key, feature in request.POST.items():
157 m = self.RE_EPISODE.match(key)
158 if m:
159 episode_id = m.group(1)
160 features[episode_id] = feature
162 get_features = lambda (e_id, e): (features[e_id], e_id)
164 num_groups = grouper.group(get_features)
166 if 'renew' in request.POST:
167 return render(request, 'admin/merge-grouping.html', {
168 'podcasts': podcasts,
169 'groups': num_groups,
173 elif 'merge' in request.POST:
175 podcast_ids = [p.get_id() for p in podcasts]
176 num_groups = list(num_groups)
178 res = merge_podcasts.delay(podcast_ids, num_groups)
180 return HttpResponseRedirect(reverse('admin-merge-status',
181 args=[res.task_id]))
184 class MergeStatus(AdminView):
185 """ Displays the status of the merge operation """
187 template_name = 'admin/task-status.html'
189 def get(self, request, task_id):
190 result = merge_podcasts.AsyncResult(task_id)
192 if not result.ready():
193 return self.render_to_response({
194 'ready': False,
197 # clear cache to make merge result visible
198 # TODO: what to do with multiple frontends?
199 cache.clear()
201 try:
202 actions, podcast = result.get()
204 except IncorrectMergeException as ime:
205 messages.error(request, str(ime))
206 return HttpResponseRedirect(reverse('admin-merge'))
208 return self.render_to_response({
209 'ready': True,
210 'actions': actions.items(),
211 'podcast': podcast,
216 class UserAgentStatsView(AdminView):
217 template_name = 'admin/useragents.html'
219 def get(self, request):
221 uas = UserAgentStats()
222 useragents = uas.get_entries()
224 return self.render_to_response({
225 'useragents': useragents.most_common(),
226 'max_users': uas.max_users,
227 'total': uas.total_users,
231 class ClientStatsView(AdminView):
232 template_name = 'admin/clients.html'
234 def get(self, request):
236 cs = ClientStats()
237 clients = cs.get_entries()
239 return self.render_to_response({
240 'clients': clients.most_common(),
241 'max_users': cs.max_users,
242 'total': cs.total_users,
246 class ClientStatsJsonView(AdminView):
247 def get(self, request):
249 cs = ClientStats()
250 clients = cs.get_entries()
252 return JsonResponse(map(self.to_dict, clients.most_common()))
254 def to_dict(self, res):
255 obj, count = res
257 if not isinstance(obj, tuple):
258 return obj, count
260 return obj._asdict(), count
263 class StatsView(AdminView):
264 """ shows general stats as HTML page """
266 template_name = 'admin/stats.html'
268 def _get_stats(self):
269 return {
270 'podcasts': podcast_count(),
271 'episodes': episode_count(),
272 'users': User.count(),
275 def get(self, request):
276 stats = self._get_stats()
277 return self.render_to_response({
278 'stats': stats,
282 class StatsJsonView(StatsView):
283 """ provides general stats as JSON """
285 def get(self, request):
286 stats = self._get_stats()
287 return JsonResponse(stats)
290 class FiletypeStatsView(AdminView):
292 template_name = 'admin/filetypes.html'
294 def get(self, request):
295 stats = filetype_stats()
297 if len(stats):
298 max_num = stats.most_common(1)[0][1]
299 else:
300 max_num = 0
302 return self.render_to_response({
303 'max_num': max_num,
304 'stats': stats.most_common(),
308 class ActivateUserView(AdminView):
309 """ Lets admins manually activate users """
311 template_name = 'admin/activate-user.html'
313 def get(self, request):
314 return self.render_to_response({})
316 def post(self, request):
318 username = request.POST.get('username')
319 email = request.POST.get('email')
321 if not (username or email):
322 messages.error(request,
323 _('Provide either username or email address'))
324 return HttpResponseRedirect(reverse('admin-activate-user'))
326 user = None
328 if username:
329 user = User.get_user(username, is_active=None)
331 if email and not user:
332 user = User.get_user_by_email(email, is_active=None)
334 if not user:
335 messages.error(request, _('No user found'))
336 return HttpResponseRedirect(reverse('admin-activate-user'))
338 activate_user(user)
339 messages.success(request,
340 _('User {username} ({email}) activated'.format(
341 username=user.username, email=user.email)))
342 return HttpResponseRedirect(reverse('admin-activate-user'))
346 class UnifyDuplicateSlugsSelect(AdminView):
347 """ select a podcast for which to unify slugs """
348 template_name = 'admin/unify-slugs-select.html'
351 class UnifyDuplicateSlugs(AdminView):
352 """ start slug-unification task """
354 def post(self, request):
355 podcast_url = request.POST.get('feed')
356 podcast = podcast_for_url(podcast_url)
358 if not podcast:
359 messages.error(request, _('Podcast with URL "%s" does not exist' %
360 (podcast_url,)))
361 return HttpResponseRedirect(reverse('admin-unify-slugs-select'))
363 res = unify_slugs.delay(podcast)
364 return HttpResponseRedirect(reverse('admin-unify-slugs-status',
365 args=[res.task_id]))
368 class UnifySlugsStatus(AdminView):
369 """ Displays the status of the unify-slugs operation """
371 template_name = 'admin/task-status.html'
373 def get(self, request, task_id):
374 result = merge_podcasts.AsyncResult(task_id)
376 if not result.ready():
377 return self.render_to_response({
378 'ready': False,
381 # clear cache to make merge result visible
382 # TODO: what to do with multiple frontends?
383 cache.clear()
385 actions, podcast = result.get()
387 return self.render_to_response({
388 'ready': True,
389 'actions': actions.items(),
390 'podcast': podcast,