Catch already-existing client in get_device()
[mygpo.git] / mygpo / api / backend.py
blob5100638f9b1e6c3808efb0ada3ae2e0b42e3e20a
2 # This file is part of my.gpodder.org.
4 # my.gpodder.org is free software: you can redistribute it and/or modify it
5 # under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or (at your
7 # option) any later version.
9 # my.gpodder.org is distributed in the hope that it will be useful, but
10 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
12 # License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with my.gpodder.org. If not, see <http://www.gnu.org/licenses/>.
18 import uuid
20 from django.db import transaction, IntegrityError
22 from mygpo.users.settings import STORE_UA
23 from mygpo.users.models import Client
25 import logging
26 logger = logging.getLogger(__name__)
29 def get_device(user, uid, user_agent, undelete=True):
30 """
31 Loads or creates the device indicated by user, uid.
33 If the device has been deleted and undelete=True, it is undeleted.
34 """
36 store_ua = user.profile.settings.get_wksetting(STORE_UA)
38 # list of fields to update -- empty list = no update
39 update_fields = []
41 try:
42 with transaction.atomic():
43 client = Client(id=uuid.uuid1(), user=user, uid=uid)
44 client.clean()
45 client.save()
47 except IntegrityError:
48 client = Client.objects.get(user=user, uid=uid)
50 if client.deleted and undelete:
51 client.deleted = False
52 update_fields.append('deleted')
54 if store_ua and user_agent and client.user_agent != user_agent:
55 client.user_agent = user_agent
56 update_fields.append('user_agent')
58 if update_fields:
59 client.save(update_fields=update_fields)
61 return client