]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/ApiBundle/Controller/EntryRestController.php
Fix tests (for real this time)
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / EntryRestController.php
CommitLineData
900c8448
NL
1<?php
2
3namespace Wallabag\ApiBundle\Controller;
4
5use Hateoas\Configuration\Route;
6use Hateoas\Representation\Factory\PagerfantaFactory;
7use Nelmio\ApiDocBundle\Annotation\ApiDoc;
8use Symfony\Component\HttpFoundation\Request;
9use Symfony\Component\HttpFoundation\JsonResponse;
10use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
11use Wallabag\CoreBundle\Entity\Entry;
12use Wallabag\CoreBundle\Entity\Tag;
5a619812
JB
13use Wallabag\CoreBundle\Event\EntrySavedEvent;
14use Wallabag\CoreBundle\Event\EntryDeletedEvent;
900c8448
NL
15
16class EntryRestController extends WallabagRestController
17{
18 /**
19 * Check if an entry exist by url.
20 *
21 * @ApiDoc(
22 * parameters={
23 * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
24 * {"name"="urls", "dataType"="string", "required"=false, "format"="An array of urls (?urls[]=http...&urls[]=http...)", "description"="Urls (as an array) to check if it exists"}
25 * }
26 * )
27 *
28 * @return JsonResponse
29 */
30 public function getEntriesExistsAction(Request $request)
31 {
32 $this->validateAuthentication();
33
34 $urls = $request->query->get('urls', []);
35
36 // handle multiple urls first
37 if (!empty($urls)) {
38 $results = [];
39 foreach ($urls as $url) {
40 $res = $this->getDoctrine()
41 ->getRepository('WallabagCoreBundle:Entry')
42 ->findByUrlAndUserId($url, $this->getUser()->getId());
43
ca9a83ee 44 $results[$url] = $res instanceof Entry ? $res->getId() : false;
900c8448
NL
45 }
46
47 $json = $this->get('serializer')->serialize($results, 'json');
48
49 return (new JsonResponse())->setJson($json);
50 }
51
52 // let's see if it is a simple url?
53 $url = $request->query->get('url', '');
54
55 if (empty($url)) {
56 throw $this->createAccessDeniedException('URL is empty?, logged user id: '.$this->getUser()->getId());
57 }
58
59 $res = $this->getDoctrine()
60 ->getRepository('WallabagCoreBundle:Entry')
61 ->findByUrlAndUserId($url, $this->getUser()->getId());
62
ca9a83ee 63 $exists = $res instanceof Entry ? $res->getId() : false;
900c8448
NL
64
65 $json = $this->get('serializer')->serialize(['exists' => $exists], 'json');
66
67 return (new JsonResponse())->setJson($json);
68 }
69
70 /**
71 * Retrieve all entries. It could be filtered by many options.
72 *
73 * @ApiDoc(
74 * parameters={
75 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
76 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
77 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
78 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
79 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
80 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
81 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
82 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
83 * }
84 * )
85 *
86 * @return JsonResponse
87 */
88 public function getEntriesAction(Request $request)
89 {
90 $this->validateAuthentication();
91
92 $isArchived = (null === $request->query->get('archive')) ? null : (bool) $request->query->get('archive');
93 $isStarred = (null === $request->query->get('starred')) ? null : (bool) $request->query->get('starred');
94 $sort = $request->query->get('sort', 'created');
95 $order = $request->query->get('order', 'desc');
96 $page = (int) $request->query->get('page', 1);
97 $perPage = (int) $request->query->get('perPage', 30);
98 $tags = $request->query->get('tags', '');
99 $since = $request->query->get('since', 0);
100
101 $pager = $this->getDoctrine()
102 ->getRepository('WallabagCoreBundle:Entry')
103 ->findEntries($this->getUser()->getId(), $isArchived, $isStarred, $sort, $order, $since, $tags);
104
105 $pager->setCurrentPage($page);
106 $pager->setMaxPerPage($perPage);
107
108 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
109 $paginatedCollection = $pagerfantaFactory->createRepresentation(
110 $pager,
111 new Route(
112 'api_get_entries',
113 [
114 'archive' => $isArchived,
115 'starred' => $isStarred,
116 'sort' => $sort,
117 'order' => $order,
118 'page' => $page,
119 'perPage' => $perPage,
120 'tags' => $tags,
121 'since' => $since,
122 ],
123 UrlGeneratorInterface::ABSOLUTE_URL
124 )
125 );
126
127 $json = $this->get('serializer')->serialize($paginatedCollection, 'json');
128
129 return (new JsonResponse())->setJson($json);
130 }
131
132 /**
133 * Retrieve a single entry.
134 *
135 * @ApiDoc(
136 * requirements={
137 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
138 * }
139 * )
140 *
141 * @return JsonResponse
142 */
143 public function getEntryAction(Entry $entry)
144 {
145 $this->validateAuthentication();
146 $this->validateUserAccess($entry->getUser()->getId());
147
148 $json = $this->get('serializer')->serialize($entry, 'json');
149
150 return (new JsonResponse())->setJson($json);
151 }
152
864c1dd2
JB
153 /**
154 * Retrieve a single entry as a predefined format.
155 *
156 * @ApiDoc(
157 * requirements={
158 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
159 * }
160 * )
161 *
162 * @return Response
163 */
164 public function getEntryExportAction(Entry $entry, Request $request)
165 {
166 $this->validateAuthentication();
167 $this->validateUserAccess($entry->getUser()->getId());
168
169 return $this->get('wallabag_core.helper.entries_export')
170 ->setEntries($entry)
171 ->updateTitle('entry')
172 ->exportAs($request->attributes->get('_format'));
173 }
174
1eca7831 175 /**
a7abcc7b 176 * Handles an entries list and delete URL.
1eca7831
NL
177 *
178 * @ApiDoc(
179 * parameters={
a7abcc7b 180 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
1eca7831
NL
181 * }
182 * )
183 *
184 * @return JsonResponse
185 */
a7abcc7b 186 public function deleteEntriesListAction(Request $request)
1eca7831
NL
187 {
188 $this->validateAuthentication();
189
a7abcc7b 190 $urls = json_decode($request->query->get('urls', []));
1eca7831
NL
191 $results = [];
192
193 // handle multiple urls
a7abcc7b 194 if (!empty($urls)) {
1eca7831 195 $results = [];
a7abcc7b 196 foreach ($urls as $key => $url) {
1eca7831 197 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
a7abcc7b 198 $url,
1eca7831
NL
199 $this->getUser()->getId()
200 );
201
a7abcc7b
NL
202 $results[$key]['url'] = $url;
203
204 if (false !== $entry) {
205 $em = $this->getDoctrine()->getManager();
206 $em->remove($entry);
207 $em->flush();
208
209 // entry deleted, dispatch event about it!
210 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
211 }
1eca7831 212
a7abcc7b
NL
213 $results[$key]['entry'] = $entry instanceof Entry ? true : false;
214 }
215 }
1eca7831 216
a7abcc7b 217 $json = $this->get('serializer')->serialize($results, 'json');
1eca7831 218
a7abcc7b
NL
219 return (new JsonResponse())->setJson($json);
220 }
1eca7831 221
a7abcc7b
NL
222 /**
223 * Handles an entries list and create URL.
224 *
225 * @ApiDoc(
226 * parameters={
227 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
228 * }
229 * )
230 *
231 * @return JsonResponse
232 */
233 public function postEntriesListAction(Request $request)
234 {
235 $this->validateAuthentication();
1eca7831 236
a7abcc7b
NL
237 $urls = json_decode($request->query->get('urls', []));
238 $results = [];
1eca7831 239
a7abcc7b
NL
240 // handle multiple urls
241 if (!empty($urls)) {
a7abcc7b
NL
242 foreach ($urls as $key => $url) {
243 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
244 $url,
245 $this->getUser()->getId()
246 );
1eca7831 247
a7abcc7b 248 $results[$key]['url'] = $url;
1eca7831 249
a7abcc7b
NL
250 if (false === $entry) {
251 $entry = $this->get('wallabag_core.content_proxy')->updateEntry(
252 new Entry($this->getUser()),
253 $url
254 );
1eca7831 255 }
a7abcc7b
NL
256
257 $em = $this->getDoctrine()->getManager();
258 $em->persist($entry);
259 $em->flush();
260
261 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
262
263 // entry saved, dispatch event about it!
264 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
1eca7831
NL
265 }
266 }
267
268 $json = $this->get('serializer')->serialize($results, 'json');
269
270 return (new JsonResponse())->setJson($json);
271 }
272
900c8448
NL
273 /**
274 * Create an entry.
275 *
276 * @ApiDoc(
277 * parameters={
278 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
279 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
280 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
281 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
282 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
283 * }
284 * )
285 *
286 * @return JsonResponse
287 */
288 public function postEntriesAction(Request $request)
289 {
290 $this->validateAuthentication();
291
292 $url = $request->request->get('url');
293 $title = $request->request->get('title');
294 $isArchived = $request->request->get('archive');
295 $isStarred = $request->request->get('starred');
296
297 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId());
298
299 if (false === $entry) {
300 $entry = $this->get('wallabag_core.content_proxy')->updateEntry(
301 new Entry($this->getUser()),
302 $url
303 );
304 }
305
306 if (!is_null($title)) {
307 $entry->setTitle($title);
308 }
309
310 $tags = $request->request->get('tags', '');
311 if (!empty($tags)) {
312 $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
313 }
314
315 if (!is_null($isStarred)) {
316 $entry->setStarred((bool) $isStarred);
317 }
318
319 if (!is_null($isArchived)) {
320 $entry->setArchived((bool) $isArchived);
321 }
322
323 $em = $this->getDoctrine()->getManager();
324 $em->persist($entry);
900c8448
NL
325 $em->flush();
326
5a619812
JB
327 // entry saved, dispatch event about it!
328 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
329
900c8448
NL
330 $json = $this->get('serializer')->serialize($entry, 'json');
331
332 return (new JsonResponse())->setJson($json);
333 }
334
335 /**
336 * Change several properties of an entry.
337 *
338 * @ApiDoc(
339 * requirements={
340 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
341 * },
342 * parameters={
343 * {"name"="title", "dataType"="string", "required"=false},
344 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
345 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
346 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
347 * }
348 * )
349 *
350 * @return JsonResponse
351 */
352 public function patchEntriesAction(Entry $entry, Request $request)
353 {
354 $this->validateAuthentication();
355 $this->validateUserAccess($entry->getUser()->getId());
356
357 $title = $request->request->get('title');
358 $isArchived = $request->request->get('archive');
359 $isStarred = $request->request->get('starred');
360
361 if (!is_null($title)) {
362 $entry->setTitle($title);
363 }
364
365 if (!is_null($isArchived)) {
366 $entry->setArchived((bool) $isArchived);
367 }
368
369 if (!is_null($isStarred)) {
370 $entry->setStarred((bool) $isStarred);
371 }
372
373 $tags = $request->request->get('tags', '');
374 if (!empty($tags)) {
375 $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
376 }
377
378 $em = $this->getDoctrine()->getManager();
379 $em->flush();
380
381 $json = $this->get('serializer')->serialize($entry, 'json');
382
383 return (new JsonResponse())->setJson($json);
384 }
385
0a6f4568
JB
386 /**
387 * Reload an entry.
5cd0857e 388 * An empty response with HTTP Status 304 will be send if we weren't able to update the content (because it hasn't changed or we got an error).
0a6f4568
JB
389 *
390 * @ApiDoc(
391 * requirements={
392 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
393 * }
394 * )
395 *
396 * @return JsonResponse
397 */
398 public function patchEntriesReloadAction(Entry $entry)
399 {
400 $this->validateAuthentication();
401 $this->validateUserAccess($entry->getUser()->getId());
402
0a6f4568
JB
403 try {
404 $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
405 } catch (\Exception $e) {
406 $this->get('logger')->error('Error while saving an entry', [
407 'exception' => $e,
408 'entry' => $entry,
409 ]);
410
5cd0857e 411 return new JsonResponse([], 304);
0a6f4568
JB
412 }
413
414 // if refreshing entry failed, don't save it
415 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
5cd0857e 416 return new JsonResponse([], 304);
0a6f4568
JB
417 }
418
419 $em = $this->getDoctrine()->getManager();
420 $em->persist($entry);
421 $em->flush();
422
423 // entry saved, dispatch event about it!
424 $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
425
426 $json = $this->get('serializer')->serialize($entry, 'json');
427
428 return (new JsonResponse())->setJson($json);
429 }
430
900c8448
NL
431 /**
432 * Delete **permanently** an entry.
433 *
434 * @ApiDoc(
435 * requirements={
436 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
437 * }
438 * )
439 *
440 * @return JsonResponse
441 */
442 public function deleteEntriesAction(Entry $entry)
443 {
444 $this->validateAuthentication();
445 $this->validateUserAccess($entry->getUser()->getId());
446
447 $em = $this->getDoctrine()->getManager();
448 $em->remove($entry);
449 $em->flush();
450
5a619812
JB
451 // entry deleted, dispatch event about it!
452 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
453
900c8448
NL
454 $json = $this->get('serializer')->serialize($entry, 'json');
455
456 return (new JsonResponse())->setJson($json);
457 }
458
459 /**
460 * Retrieve all tags for an entry.
461 *
462 * @ApiDoc(
463 * requirements={
464 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
465 * }
466 * )
467 *
468 * @return JsonResponse
469 */
470 public function getEntriesTagsAction(Entry $entry)
471 {
472 $this->validateAuthentication();
473 $this->validateUserAccess($entry->getUser()->getId());
474
475 $json = $this->get('serializer')->serialize($entry->getTags(), 'json');
476
477 return (new JsonResponse())->setJson($json);
478 }
479
480 /**
481 * Add one or more tags to an entry.
482 *
483 * @ApiDoc(
484 * requirements={
485 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
486 * },
487 * parameters={
488 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
489 * }
490 * )
491 *
492 * @return JsonResponse
493 */
494 public function postEntriesTagsAction(Request $request, Entry $entry)
495 {
496 $this->validateAuthentication();
497 $this->validateUserAccess($entry->getUser()->getId());
498
499 $tags = $request->request->get('tags', '');
500 if (!empty($tags)) {
501 $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
502 }
503
504 $em = $this->getDoctrine()->getManager();
505 $em->persist($entry);
506 $em->flush();
507
508 $json = $this->get('serializer')->serialize($entry, 'json');
509
510 return (new JsonResponse())->setJson($json);
511 }
512
513 /**
514 * Permanently remove one tag for an entry.
515 *
516 * @ApiDoc(
517 * requirements={
518 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
519 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
520 * }
521 * )
522 *
523 * @return JsonResponse
524 */
525 public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
526 {
527 $this->validateAuthentication();
528 $this->validateUserAccess($entry->getUser()->getId());
529
530 $entry->removeTag($tag);
531 $em = $this->getDoctrine()->getManager();
532 $em->persist($entry);
533 $em->flush();
534
535 $json = $this->get('serializer')->serialize($entry, 'json');
536
537 return (new JsonResponse())->setJson($json);
538 }
d1fc5902
NL
539
540 /**
80299ed2 541 * Handles an entries list delete tags from them.
d1fc5902
NL
542 *
543 * @ApiDoc(
544 * parameters={
80299ed2 545 * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."}
d1fc5902
NL
546 * }
547 * )
548 *
549 * @return JsonResponse
550 */
80299ed2 551 public function deleteEntriesTagsListAction(Request $request)
d1fc5902
NL
552 {
553 $this->validateAuthentication();
554
555 $list = json_decode($request->query->get('list', []));
556 $results = [];
557
558 // handle multiple urls
559 if (!empty($list)) {
d1fc5902
NL
560 foreach ($list as $key => $element) {
561 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
562 $element->url,
563 $this->getUser()->getId()
564 );
565
566 $results[$key]['url'] = $element->url;
d1fc5902
NL
567 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
568
569 $tags = $element->tags;
570
571 if (false !== $entry && !(empty($tags))) {
80299ed2
NL
572 $tags = explode(',', $tags);
573 foreach ($tags as $label) {
574 $label = trim($label);
575
576 $tag = $this->getDoctrine()
577 ->getRepository('WallabagCoreBundle:Tag')
578 ->findOneByLabel($label);
579
580 if (false !== $tag) {
581 $entry->removeTag($tag);
582 }
d1fc5902
NL
583 }
584
585 $em = $this->getDoctrine()->getManager();
586 $em->persist($entry);
587 $em->flush();
588 }
589 }
590 }
591
592 $json = $this->get('serializer')->serialize($results, 'json');
593
594 return (new JsonResponse())->setJson($json);
595 }
80299ed2
NL
596
597 /**
598 * Handles an entries list and add tags to them.
599 *
600 * @ApiDoc(
601 * parameters={
602 * {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."}
603 * }
604 * )
605 *
606 * @return JsonResponse
607 */
608 public function postEntriesTagsListAction(Request $request)
609 {
610 $this->validateAuthentication();
611
612 $list = json_decode($request->query->get('list', []));
613 $results = [];
614
615 // handle multiple urls
616 if (!empty($list)) {
80299ed2
NL
617 foreach ($list as $key => $element) {
618 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
619 $element->url,
620 $this->getUser()->getId()
621 );
622
623 $results[$key]['url'] = $element->url;
624 $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
625
626 $tags = $element->tags;
627
628 if (false !== $entry && !(empty($tags))) {
629 $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
630
631 $em = $this->getDoctrine()->getManager();
632 $em->persist($entry);
633 $em->flush();
634 }
635 }
636 }
637
638 $json = $this->get('serializer')->serialize($results, 'json');
639
640 return (new JsonResponse())->setJson($json);
641 }
900c8448 642}