[Flattr] fix bug when flattring episode
[mygpo.git] / mygpo / core / tasks.py
blob763e7635444fe872ffb4c674e197a76cfb984c9e
1 from datetime import datetime
3 from django.utils.translation import ugettext as _
4 from django.conf import settings
6 from mygpo.podcasts.models import Podcast, Episode
7 from mygpo.celery import celery
8 from mygpo.history.models import HistoryEntry
9 from mygpo.data.feeddownloader import PodcastUpdater
10 from mygpo.utils import get_timestamp
11 from mygpo.users.models import EpisodeAction
12 from mygpo.flattr import Flattr
13 from mygpo.db.couchdb.episode_state import episode_state_for_user_episode, \
14 add_episode_actions
17 @celery.task(max_retries=5, default_retry_delay=60)
18 def flattr_thing(user, thing_id, domain, is_secure, thing_type):
19 """ Task to flattr a thing """
21 flattr = Flattr(user, domain, is_secure)
23 if thing_type == 'Podcast':
24 thing = Podcast.objects.get(id=thing_id)
25 episode, podcast = None, thing
27 elif thing_type == 'Episode':
28 query = Episode.objects.filter(id=thing_id).select_related('podcast')
29 thing = query.get()
30 episode, podcast = thing, thing.podcast
32 else:
33 raise NotImplemented(_("Can't flattr a '%s'") % thing_type)
36 if not thing.flattr_url:
37 return False, _('No Payment URL available')
39 try:
40 success, msg = flattr.flattr_url(thing.flattr_url)
42 if settings.FLATTR_MYGPO_THING:
43 flattr.flattr_url(settings.FLATTR_MYGPO_THING)
45 except Exception as ex:
46 raise flattr_thing.retry(exc=ex)
48 if success:
49 HistoryEntry.objects.create(
50 timestamp=datetime.utcnow(),
51 podcast=podcast,
52 episode=episode,
53 user=user,
54 client=None,
55 action=HistoryEntry.FLATTR,
59 return success, msg
62 @celery.task(max_retries=5, default_retry_delay=60)
63 def auto_flattr_episode(user, episode_id):
64 """ Task to auto-flattr an episode
66 In addition to the flattring itself, it also records the event """
68 success, msg = flattr_thing(user, episode_id, None, False, 'Episode')
70 if not success:
71 return False
73 episode = Episode.objects.get(id=episode_id)
74 state = episode_state_for_user_episode(user, episode)
76 action = EpisodeAction()
77 action.action = 'flattr'
78 action.upload_timestamp = get_timestamp(datetime.utcnow())
79 add_episode_actions(state, [action])
81 return True