##// END OF EJS Templates
Use dict instead of context instance in post view API
neko259 -
r1075:d66b9778 default
parent child Browse files
Show More
@@ -1,240 +1,240 b''
1 1 from datetime import datetime
2 2 import json
3 3 import logging
4 4 from django.db import transaction
5 5 from django.http import HttpResponse
6 6 from django.shortcuts import get_object_or_404, render
7 7 from django.template import RequestContext
8 8 from django.utils import timezone
9 9 from django.core import serializers
10 10
11 11 from boards.forms import PostForm, PlainErrorList
12 12 from boards.models import Post, Thread, Tag
13 13 from boards.utils import datetime_to_epoch
14 14 from boards.views.thread import ThreadView
15 15 from boards.models.user import Notification
16 16
17 17 __author__ = 'neko259'
18 18
19 19 PARAMETER_TRUNCATED = 'truncated'
20 20 PARAMETER_TAG = 'tag'
21 21 PARAMETER_OFFSET = 'offset'
22 22 PARAMETER_DIFF_TYPE = 'type'
23 PARAMETER_POST = 'post'
23 24
24 25 DIFF_TYPE_HTML = 'html'
25 26 DIFF_TYPE_JSON = 'json'
26 27
27 28 STATUS_OK = 'ok'
28 29 STATUS_ERROR = 'error'
29 30
30 31 logger = logging.getLogger(__name__)
31 32
32 33
33 34 @transaction.atomic
34 35 def api_get_threaddiff(request, thread_id, last_update_time):
35 36 """
36 37 Gets posts that were changed or added since time
37 38 """
38 39
39 40 thread = get_object_or_404(Post, id=thread_id).get_thread()
40 41
41 42 # Add 1 to ensure we don't load the same post over and over
42 43 last_update_timestamp = float(last_update_time) + 1
43 44
44 45 filter_time = datetime.fromtimestamp(last_update_timestamp / 1000000,
45 46 timezone.get_current_timezone())
46 47
47 48 json_data = {
48 49 'added': [],
49 50 'updated': [],
50 51 'last_update': None,
51 52 }
52 53 added_posts = Post.objects.filter(threads__in=[thread],
53 54 pub_time__gt=filter_time) \
54 55 .order_by('pub_time')
55 56 updated_posts = Post.objects.filter(threads__in=[thread],
56 57 pub_time__lte=filter_time,
57 58 last_edit_time__gt=filter_time)
58 59
59 60 diff_type = request.GET.get(PARAMETER_DIFF_TYPE, DIFF_TYPE_HTML)
60 61
61 62 for post in added_posts:
62 63 json_data['added'].append(get_post_data(post.id, diff_type, request))
63 64 for post in updated_posts:
64 65 json_data['updated'].append(get_post_data(post.id, diff_type, request))
65 66 json_data['last_update'] = datetime_to_epoch(thread.last_edit_time)
66 67
67 68 return HttpResponse(content=json.dumps(json_data))
68 69
69 70
70 71 def api_add_post(request, opening_post_id):
71 72 """
72 73 Adds a post and return the JSON response for it
73 74 """
74 75
75 76 opening_post = get_object_or_404(Post, id=opening_post_id)
76 77
77 78 logger.info('Adding post via api...')
78 79
79 80 status = STATUS_OK
80 81 errors = []
81 82
82 83 if request.method == 'POST':
83 84 form = PostForm(request.POST, request.FILES, error_class=PlainErrorList)
84 85 form.session = request.session
85 86
86 87 if form.need_to_ban:
87 88 # Ban user because he is suspected to be a bot
88 89 # _ban_current_user(request)
89 90 status = STATUS_ERROR
90 91 if form.is_valid():
91 92 post = ThreadView().new_post(request, form, opening_post,
92 93 html_response=False)
93 94 if not post:
94 95 status = STATUS_ERROR
95 96 else:
96 97 logger.info('Added post #%d via api.' % post.id)
97 98 else:
98 99 status = STATUS_ERROR
99 100 errors = form.as_json_errors()
100 101
101 102 response = {
102 103 'status': status,
103 104 'errors': errors,
104 105 }
105 106
106 107 return HttpResponse(content=json.dumps(response))
107 108
108 109
109 110 def get_post(request, post_id):
110 111 """
111 112 Gets the html of a post. Used for popups. Post can be truncated if used
112 113 in threads list with 'truncated' get parameter.
113 114 """
114 115
115 116 post = get_object_or_404(Post, id=post_id)
116 117
117 context = RequestContext(request)
118 context['post'] = post
118 params = dict()
119 params[PARAMETER_POST] = post
119 120 if PARAMETER_TRUNCATED in request.GET:
120 context[PARAMETER_TRUNCATED] = True
121 params[PARAMETER_TRUNCATED] = True
121 122
122 # TODO Use dict here
123 return render(request, 'boards/api_post.html', context_instance=context)
123 return render(request, 'boards/api_post.html', params)
124 124
125 125
126 126 def api_get_threads(request, count):
127 127 """
128 128 Gets the JSON thread opening posts list.
129 129 Parameters that can be used for filtering:
130 130 tag, offset (from which thread to get results)
131 131 """
132 132
133 133 if PARAMETER_TAG in request.GET:
134 134 tag_name = request.GET[PARAMETER_TAG]
135 135 if tag_name is not None:
136 136 tag = get_object_or_404(Tag, name=tag_name)
137 137 threads = tag.get_threads().filter(archived=False)
138 138 else:
139 139 threads = Thread.objects.filter(archived=False)
140 140
141 141 if PARAMETER_OFFSET in request.GET:
142 142 offset = request.GET[PARAMETER_OFFSET]
143 143 offset = int(offset) if offset is not None else 0
144 144 else:
145 145 offset = 0
146 146
147 147 threads = threads.order_by('-bump_time')
148 148 threads = threads[offset:offset + int(count)]
149 149
150 150 opening_posts = []
151 151 for thread in threads:
152 152 opening_post = thread.get_opening_post()
153 153
154 154 # TODO Add tags, replies and images count
155 155 post_data = get_post_data(opening_post.id, include_last_update=True)
156 156 post_data['bumpable'] = thread.can_bump()
157 157 post_data['archived'] = thread.archived
158 158
159 159 opening_posts.append(post_data)
160 160
161 161 return HttpResponse(content=json.dumps(opening_posts))
162 162
163 163
164 164 # TODO Test this
165 165 def api_get_tags(request):
166 166 """
167 167 Gets all tags or user tags.
168 168 """
169 169
170 170 # TODO Get favorite tags for the given user ID
171 171
172 172 tags = Tag.objects.get_not_empty_tags()
173 173 tag_names = []
174 174 for tag in tags:
175 175 tag_names.append(tag.name)
176 176
177 177 return HttpResponse(content=json.dumps(tag_names))
178 178
179 179
180 180 # TODO The result can be cached by the thread last update time
181 181 # TODO Test this
182 182 def api_get_thread_posts(request, opening_post_id):
183 183 """
184 184 Gets the JSON array of thread posts
185 185 """
186 186
187 187 opening_post = get_object_or_404(Post, id=opening_post_id)
188 188 thread = opening_post.get_thread()
189 189 posts = thread.get_replies()
190 190
191 191 json_data = {
192 192 'posts': [],
193 193 'last_update': None,
194 194 }
195 195 json_post_list = []
196 196
197 197 for post in posts:
198 198 json_post_list.append(get_post_data(post.id))
199 199 json_data['last_update'] = datetime_to_epoch(thread.last_edit_time)
200 200 json_data['posts'] = json_post_list
201 201
202 202 return HttpResponse(content=json.dumps(json_data))
203 203
204 204
205 205 def api_get_notifications(request, username):
206 206 last_notification_id_str = request.GET.get('last', None)
207 207 last_id = int(last_notification_id_str) if last_notification_id_str is not None else None
208 208
209 209 posts = Notification.objects.get_notification_posts(username=username,
210 210 last=last_id)
211 211
212 212 json_post_list = []
213 213 for post in posts:
214 214 json_post_list.append(get_post_data(post.id))
215 215 return HttpResponse(content=json.dumps(json_post_list))
216 216
217 217
218 218
219 219 def api_get_post(request, post_id):
220 220 """
221 221 Gets the JSON of a post. This can be
222 222 used as and API for external clients.
223 223 """
224 224
225 225 post = get_object_or_404(Post, id=post_id)
226 226
227 227 json = serializers.serialize("json", [post], fields=(
228 228 "pub_time", "_text_rendered", "title", "text", "image",
229 229 "image_width", "image_height", "replies", "tags"
230 230 ))
231 231
232 232 return HttpResponse(content=json)
233 233
234 234
235 235 # TODO Remove this method and use post method directly
236 236 def get_post_data(post_id, format_type=DIFF_TYPE_JSON, request=None,
237 237 include_last_update=False):
238 238 post = get_object_or_404(Post, id=post_id)
239 239 return post.get_post_data(format_type=format_type, request=request,
240 240 include_last_update=include_last_update)
General Comments 0
You need to be logged in to leave comments. Login now