1# Copyright 2013-2016 The Distro Tracker Developers 

2# See the COPYRIGHT file at the top-level directory of this distribution and 

3# at https://deb.li/DTAuthors 

4# 

5# This file is part of Distro Tracker. It is subject to the license terms 

6# in the LICENSE file found in the top-level directory of this 

7# distribution and at https://deb.li/DTLicense. No part of Distro Tracker, 

8# including this file, may be copied, modified, propagated, or distributed 

9# except according to the terms contained in the LICENSE file. 

10""" 

11Implements the command which removes all subscriptions for a given email. 

12""" 

13from django.core.management.base import BaseCommand, CommandError 

14 

15from distro_tracker.core.models import EmailSettings, UserEmail 

16from distro_tracker.core.utils import get_or_none 

17 

18 

19class Command(BaseCommand): 

20 """ 

21 A Django management command which removes all subscriptions for the given 

22 emails. 

23 """ 

24 help = "Removes all package subscriptions for the given emails." # noqa 

25 

26 def add_arguments(self, parser): 

27 parser.add_argument('emails', nargs='+') 

28 

29 def handle(self, *args, **kwargs): 

30 if len(kwargs['emails']) == 0: 30 ↛ 31line 30 didn't jump to line 31, because the condition on line 30 was never true

31 raise CommandError('At least one email must be given.') 

32 verbosity = int(kwargs.get('verbosity', 1)) 

33 for email in kwargs['emails']: 

34 out = self._remove_subscriptions(email) 

35 if verbosity >= 1: 35 ↛ 33line 35 didn't jump to line 33, because the condition on line 35 was never false

36 self.stdout.write(out) 

37 

38 def _remove_subscriptions(self, email): 

39 """ 

40 Removes subscriptions for the given email. 

41 

42 :param email: Email for which to remove all subscriptions. 

43 :type email: string 

44 

45 :returns: A message explaining the result of the operation. 

46 :rtype: string 

47 """ 

48 user = get_or_none(UserEmail, email__iexact=email) 

49 if not user: 

50 return ('Email {email} is not subscribed to any packages. ' 

51 'Bad email?'.format(email=email)) 

52 email_settings, _ = EmailSettings.objects.get_or_create(user_email=user) 

53 if email_settings.packagename_set.count() == 0: 

54 return 'Email {email} is not subscribed to any packages.'.format( 

55 email=email) 

56 out = [ 

57 'Unsubscribing {email} from {package}'.format( 

58 email=email, package=package) 

59 for package in email_settings.packagename_set.all() 

60 ] 

61 email_settings.unsubscribe_all() 

62 return '\n'.join(out)