Merge branch 'master' into pg-search
[mygpo.git] / mygpo / api / backend.py
blob91cbc50d2178a61cfff38a97aceaf2c78e96e7bb
1 import uuid
3 from django.db import transaction, IntegrityError
5 from mygpo.users.settings import STORE_UA
6 from mygpo.users.models import Client
8 import logging
9 logger = logging.getLogger(__name__)
12 def get_device(user, uid, user_agent, undelete=True):
13 """
14 Loads or creates the device indicated by user, uid.
16 If the device has been deleted and undelete=True, it is undeleted.
17 """
19 store_ua = user.profile.settings.get_wksetting(STORE_UA)
21 # list of fields to update -- empty list = no update
22 update_fields = []
24 try:
25 with transaction.atomic():
26 client = Client(id=uuid.uuid1(), user=user, uid=uid)
27 client.clean_fields()
28 client.clean()
29 client.save()
31 except IntegrityError:
32 client = Client.objects.get(user=user, uid=uid)
34 if client.deleted and undelete:
35 client.deleted = False
36 update_fields.append('deleted')
38 if store_ua and user_agent and client.user_agent != user_agent:
39 client.user_agent = user_agent
40 update_fields.append('user_agent')
42 if update_fields:
43 client.save(update_fields=update_fields)
45 return client