This repository has been archived by the owner on Jan 5, 2019. It is now read-only.
/
sync.py
198 lines (162 loc) · 7.53 KB
/
sync.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# coding: utf-8
'''
Storage for Weave.
Created on 15.03.2010
@license: GNU GPL v3 or above, see LICENSE for more details.
@copyleft: 2010-2011 by the django-sync-server team, see AUTHORS for more details.
'''
from datetime import datetime
try:
import json # New in Python v2.6
except ImportError:
from django.utils import simplejson as json
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import ValidationError
from django.http import Http404
from django.shortcuts import get_object_or_404
# django-sync-server own stuff
from weave.models import Collection, Wbo
from weave.utils import limit_wbo_queryset, weave_timestamp
from weave.decorators import weave_assert_username, weave_assert_version, \
logged_in_or_basicauth, weave_render_response, debug_sync_request
from weave import Logging
logger = Logging.get_logger()
@debug_sync_request
@logged_in_or_basicauth
@weave_assert_version(("1.0", "1.1"))
@weave_assert_username
@csrf_exempt
@weave_render_response
def info(request, version, username, timestamp):
"""
return all collection keys with the timestamp
https://wiki.mozilla.org/Labs/Weave/Sync/1.0/API#GET
"""
collections = {}
for collection in Collection.on_site.filter(user=request.user):
collections[collection.name] = weave_timestamp(collection.modified)
return collections
@debug_sync_request
@logged_in_or_basicauth
@weave_assert_version(("1.0", "1.1"))
@weave_assert_username
@csrf_exempt
@weave_render_response
def storage(request, version, username, timestamp, col_name=None, wboid=None):
"""
Handle storing Collections and WBOs.
"""
if 'X-If-Unmodified-Since' in request.META:
since = datetime.fromtimestamp(float(request.META['X-If-Unmodified-Since']))
else:
since = None
if request.method == 'GET':
# Returns a list of the WBO contained in a collection.
collection = get_object_or_404(Collection.on_site, user=request.user, name=col_name)
if wboid is not None: # return one WBO
wbo = get_object_or_404(Wbo, user=request.user, collection=collection, wboid=wboid)
return wbo.get_response_dict()
wbo_queryset = Wbo.objects.filter(user=request.user, collection=collection)
wbo_queryset = limit_wbo_queryset(request, wbo_queryset)
# If defined, returns the full WBO, rather than just the id.
if not 'full' in request.GET: # return only the WBO ids
return [wbo.wboid for wbo in wbo_queryset]
return [wbo.get_response_dict() for wbo in wbo_queryset]
elif request.method == 'PUT':
# https://wiki.mozilla.org/Labs/Weave/Sync/1.0/API#PUT
# Adds the WBO defined in the request body to the collection.
payload = request.raw_post_data
logger.debug("Payload for PUT: %s" % payload)
if not payload:
raise NotImplementedError
val = json.loads(payload)
if val.get('id', None) != wboid:
raise ValidationError
# TODO: I don't think that it's good to just pass 0 in case the header is not defined
collection, created = Collection.on_site.create_or_update(
request.user,
col_name,
timestamp,
since,
)
if created:
logger.debug("Created new collection %s" % collection)
else:
logger.debug("Found existing collection %s" % collection)
wbo, created = Wbo.objects.create_or_update(val, collection, request.user, timestamp)
if created:
logger.debug("New wbo created: %r" % wbo)
else:
logger.debug("Existing wbo updated: %r" % wbo)
return weave_timestamp(timestamp)
elif request.method == 'POST':
status = {'success': [], 'failed': []}
payload = request.raw_post_data
logger.debug("Payload in POST: %s" % payload)
if not payload:
raise NotImplementedError
# TODO: I don't think that it's good to just pass 0 in case the header is not defined
collection, created = Collection.on_site.create_or_update(
request.user,
col_name,
timestamp,
since,
)
if created:
logger.debug("Create new collection %s" % collection)
else:
logger.debug("Found existing collection %s" % collection)
data = json.loads(payload)
if not isinstance(data, list):
raise NotImplementedError
for item in data:
try:
wbo, created = Wbo.objects.create_or_update(item, collection, request.user, timestamp)
except ValidationError, err:
logger.debug("Can't create Wbo from %r: %s" % (item, err))
status['failed'].append(item["id"])
else:
status['success'].append(wbo.wboid)
if created:
logger.debug("New wbo created: %s" % wbo)
else:
logger.debug("Existing wbo updated: %s" % wbo)
return status
elif request.method == 'DELETE':
# FIXME: This is am mess, it needs better structure
if col_name is None and wboid is None:
Collection.on_site.filter(user=request.user).delete()
return weave_timestamp(timestamp)
if col_name is not None and wboid is not None:
try:
wbo = Wbo.objects.get(user=request.user, collection__name=col_name, wboid=wboid)
except Wbo.DoesNotExist, err:
msg = (
"Deletion of wboid %s from collection %r for user %s requested,"
" but there is no such wbo: %s"
) % (wboid, col_name, request.user, err)
logger.info(msg)
if settings.DEBUG:
raise Http404(msg)
else:
raise Http404()
else:
logger.info("Delete Wbo %s in collection %s for user %s" % (wbo.wboid, col_name, request.user))
wbo.delete()
else:
ids = request.GET.get('ids', None)
if ids is not None:
for wbo in Wbo.objects.filter(user=request.user, wboid__in=ids.split(',')):
logger.info("Delete Wbo %s in collection %s for user %s" % (wbo.wboid, col_name, request.user))
wbo.delete()
else:
collection = Collection.on_site.filter(user=request.user, name=col_name).delete()
if collection is not None:
logger.info("Delete collection %s for user %s" % (collection.name, request.user))
Wbo.objects.filter(user=request.user, collection=collection).delete()
else:
logger.info("Deletion of collection %s requested but there is no such collection!" % (col_name))
return weave_timestamp(timestamp)
else:
raise NotImplementedError("request.method %r not implemented!" % request.method)