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