3 namespace Wallabag\ApiBundle\Controller
;
5 use Hateoas\Configuration\Route
;
6 use Hateoas\Representation\Factory\PagerfantaFactory
;
7 use JMS\Serializer\SerializationContext
;
8 use Nelmio\ApiDocBundle\Annotation\ApiDoc
;
9 use Symfony\Component\HttpFoundation\JsonResponse
;
10 use Symfony\Component\HttpFoundation\Request
;
11 use Symfony\Component\HttpKernel\Exception\HttpException
;
12 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
13 use Wallabag\CoreBundle\Entity\Entry
;
14 use Wallabag\CoreBundle\Entity\Tag
;
15 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
16 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
18 class EntryRestController
extends WallabagRestController
21 * Check if an entry exist by url.
22 * Return ID if entry(ies) exist (and if you give the return_id parameter).
23 * Otherwise it returns false.
25 * @todo Remove that `return_id` in the next major release
29 * {"name"="return_id", "dataType"="string", "required"=false, "format"="1 or 0", "description"="Set 1 if you want to retrieve ID in case entry(ies) exists, 0 by default"},
30 * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
31 * {"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"}
35 * @return JsonResponse
37 public function getEntriesExistsAction(Request
$request)
39 $this->validateAuthentication();
41 $returnId = (null === $request->query
->get('return_id')) ? false : (bool) $request->query
->get('return_id');
42 $urls = $request->query
->get('urls', []);
44 // handle multiple urls first
47 foreach ($urls as $url) {
48 $res = $this->getDoctrine()
49 ->getRepository('WallabagCoreBundle:Entry')
50 ->findByUrlAndUserId($url, $this->getUser()->getId());
52 $results[$url] = $this->returnExistInformation($res, $returnId);
55 return $this->sendResponse($results);
58 // let's see if it is a simple url?
59 $url = $request->query
->get('url', '');
62 throw $this->createAccessDeniedException('URL is empty?, logged user id: ' . $this->getUser()->getId());
65 $res = $this->getDoctrine()
66 ->getRepository('WallabagCoreBundle:Entry')
67 ->findByUrlAndUserId($url, $this->getUser()->getId());
69 $exists = $this->returnExistInformation($res, $returnId);
71 return $this->sendResponse(['exists' => $exists]);
75 * Retrieve all entries. It could be filtered by many options.
79 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
80 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
81 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
82 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
83 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
84 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
85 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
86 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
87 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by entries with a public link"},
91 * @return JsonResponse
93 public function getEntriesAction(Request
$request)
95 $this->validateAuthentication();
97 $isArchived = (null === $request->query
->get('archive')) ? null : (bool) $request->query
->get('archive');
98 $isStarred = (null === $request->query
->get('starred')) ? null : (bool) $request->query
->get('starred');
99 $isPublic = (null === $request->query
->get('public')) ? null : (bool) $request->query
->get('public');
100 $sort = $request->query
->get('sort', 'created');
101 $order = $request->query
->get('order', 'desc');
102 $page = (int) $request->query
->get('page', 1);
103 $perPage = (int) $request->query
->get('perPage', 30);
104 $tags = $request->query
->get('tags', '');
105 $since = $request->query
->get('since', 0);
107 /** @var \Pagerfanta\Pagerfanta $pager */
108 $pager = $this->get('wallabag_core.entry_repository')->findEntries(
109 $this->getUser()->getId(),
119 $pager->setMaxPerPage($perPage);
120 $pager->setCurrentPage($page);
122 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
123 $paginatedCollection = $pagerfantaFactory->createRepresentation(
128 'archive' => $isArchived,
129 'starred' => $isStarred,
130 'public' => $isPublic,
134 'perPage' => $perPage,
138 UrlGeneratorInterface
::ABSOLUTE_URL
142 return $this->sendResponse($paginatedCollection);
146 * Retrieve a single entry.
150 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
154 * @return JsonResponse
156 public function getEntryAction(Entry
$entry)
158 $this->validateAuthentication();
159 $this->validateUserAccess($entry->getUser()->getId());
161 return $this->sendResponse($entry);
165 * Retrieve a single entry as a predefined format.
169 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
175 public function getEntryExportAction(Entry
$entry, Request
$request)
177 $this->validateAuthentication();
178 $this->validateUserAccess($entry->getUser()->getId());
180 return $this->get('wallabag_core.helper.entries_export')
182 ->updateTitle('entry')
183 ->exportAs($request->attributes
->get('_format'));
187 * Handles an entries list and delete URL.
191 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
195 * @return JsonResponse
197 public function deleteEntriesListAction(Request
$request)
199 $this->validateAuthentication();
201 $urls = json_decode($request->query
->get('urls', []));
204 return $this->sendResponse([]);
209 // handle multiple urls
210 foreach ($urls as $key => $url) {
211 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
213 $this->getUser()->getId()
216 $results[$key]['url'] = $url;
218 if (false !== $entry) {
219 $em = $this->getDoctrine()->getManager();
223 // entry deleted, dispatch event about it!
224 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
227 $results[$key]['entry'] = $entry instanceof Entry
? true : false;
230 return $this->sendResponse($results);
234 * Handles an entries list and create URL.
238 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
242 * @throws HttpException When limit is reached
244 * @return JsonResponse
246 public function postEntriesListAction(Request
$request)
248 $this->validateAuthentication();
250 $urls = json_decode($request->query
->get('urls', []));
252 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
254 if (count($urls) > $limit) {
255 throw new HttpException(400, 'API limit reached');
260 return $this->sendResponse($results);
263 // handle multiple urls
264 foreach ($urls as $key => $url) {
265 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
267 $this->getUser()->getId()
270 $results[$key]['url'] = $url;
272 if (false === $entry) {
273 $entry = new Entry($this->getUser());
275 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
278 $em = $this->getDoctrine()->getManager();
279 $em->persist($entry);
282 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
284 // entry saved, dispatch event about it!
285 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
288 return $this->sendResponse($results);
294 * If you want to provide the HTML content (which means wallabag won't fetch it from the url), you must provide `content`, `title` & `url` fields **non-empty**.
295 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
299 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
300 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
301 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
302 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
303 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
304 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
305 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
306 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
307 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
308 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
309 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
313 * @return JsonResponse
315 public function postEntriesAction(Request
$request)
317 $this->validateAuthentication();
319 $url = $request->request
->get('url');
321 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
323 $this->getUser()->getId()
326 if (false === $entry) {
327 $entry = new Entry($this->getUser());
328 $entry->setUrl($url);
331 $data = $this->retrieveValueFromRequest($request);
334 $this->get('wallabag_core.content_proxy')->updateEntry(
338 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
339 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
340 'url' => $entry->getUrl(),
341 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
342 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
343 // faking the open graph preview picture
345 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
347 'authors' => is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
350 } catch (\Exception
$e) {
351 $this->get('logger')->error('Error while saving an entry', [
357 if (!is_null($data['isArchived'])) {
358 $entry->setArchived((bool) $data['isArchived']);
361 if (!is_null($data['isStarred'])) {
362 $entry->setStarred((bool) $data['isStarred']);
365 if (!empty($data['tags'])) {
366 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
369 if (!is_null($data['isPublic'])) {
370 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
371 $entry->generateUid();
372 } elseif (false === (bool) $data['isPublic']) {
377 $em = $this->getDoctrine()->getManager();
378 $em->persist($entry);
381 // entry saved, dispatch event about it!
382 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
384 return $this->sendResponse($entry);
388 * Change several properties of an entry.
392 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
395 * {"name"="title", "dataType"="string", "required"=false},
396 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
397 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
398 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
399 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
400 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
401 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
402 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
403 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
404 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
408 * @return JsonResponse
410 public function patchEntriesAction(Entry
$entry, Request
$request)
412 $this->validateAuthentication();
413 $this->validateUserAccess($entry->getUser()->getId());
415 $contentProxy = $this->get('wallabag_core.content_proxy');
417 $data = $this->retrieveValueFromRequest($request);
419 // this is a special case where user want to manually update the entry content
420 // the ContentProxy will only cleanup the html
421 // and also we force to not re-fetch the content in case of error
422 if (!empty($data['content'])) {
424 $contentProxy->updateEntry(
428 'html' => $data['content'],
432 } catch (\Exception
$e) {
433 $this->get('logger')->error('Error while saving an entry', [
440 if (!empty($data['title'])) {
441 $entry->setTitle($data['title']);
444 if (!empty($data['language'])) {
445 $contentProxy->updateLanguage($entry, $data['language']);
448 if (!empty($data['authors']) && is_string($data['authors'])) {
449 $entry->setPublishedBy(explode(',', $data['authors']));
452 if (!empty($data['picture'])) {
453 $contentProxy->updatePreviewPicture($entry, $data['picture']);
456 if (!empty($data['publishedAt'])) {
457 $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
460 if (!is_null($data['isArchived'])) {
461 $entry->setArchived((bool) $data['isArchived']);
464 if (!is_null($data['isStarred'])) {
465 $entry->setStarred((bool) $data['isStarred']);
468 if (!empty($data['tags'])) {
469 $entry->removeAllTags();
470 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
473 if (!is_null($data['isPublic'])) {
474 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
475 $entry->generateUid();
476 } elseif (false === (bool) $data['isPublic']) {
481 $em = $this->getDoctrine()->getManager();
482 $em->persist($entry);
485 // entry saved, dispatch event about it!
486 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
488 return $this->sendResponse($entry);
493 * 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).
497 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
501 * @return JsonResponse
503 public function patchEntriesReloadAction(Entry
$entry)
505 $this->validateAuthentication();
506 $this->validateUserAccess($entry->getUser()->getId());
509 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
510 } catch (\Exception
$e) {
511 $this->get('logger')->error('Error while saving an entry', [
516 return new JsonResponse([], 304);
519 // if refreshing entry failed, don't save it
520 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
521 return new JsonResponse([], 304);
524 $em = $this->getDoctrine()->getManager();
525 $em->persist($entry);
528 // entry saved, dispatch event about it!
529 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
531 return $this->sendResponse($entry);
535 * Delete **permanently** an entry.
539 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
543 * @return JsonResponse
545 public function deleteEntriesAction(Entry
$entry)
547 $this->validateAuthentication();
548 $this->validateUserAccess($entry->getUser()->getId());
550 $em = $this->getDoctrine()->getManager();
554 // entry deleted, dispatch event about it!
555 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
557 return $this->sendResponse($entry);
561 * Retrieve all tags for an entry.
565 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
569 * @return JsonResponse
571 public function getEntriesTagsAction(Entry
$entry)
573 $this->validateAuthentication();
574 $this->validateUserAccess($entry->getUser()->getId());
576 return $this->sendResponse($entry->getTags());
580 * Add one or more tags to an entry.
584 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
587 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
591 * @return JsonResponse
593 public function postEntriesTagsAction(Request
$request, Entry
$entry)
595 $this->validateAuthentication();
596 $this->validateUserAccess($entry->getUser()->getId());
598 $tags = $request->request
->get('tags', '');
600 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
603 $em = $this->getDoctrine()->getManager();
604 $em->persist($entry);
607 return $this->sendResponse($entry);
611 * Permanently remove one tag for an entry.
615 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
616 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
620 * @return JsonResponse
622 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
624 $this->validateAuthentication();
625 $this->validateUserAccess($entry->getUser()->getId());
627 $entry->removeTag($tag);
628 $em = $this->getDoctrine()->getManager();
629 $em->persist($entry);
632 return $this->sendResponse($entry);
636 * Handles an entries list delete tags from them.
640 * {"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."}
644 * @return JsonResponse
646 public function deleteEntriesTagsListAction(Request
$request)
648 $this->validateAuthentication();
650 $list = json_decode($request->query
->get('list', []));
653 return $this->sendResponse([]);
656 // handle multiple urls
659 foreach ($list as $key => $element) {
660 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
662 $this->getUser()->getId()
665 $results[$key]['url'] = $element->url
;
666 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
668 $tags = $element->tags
;
670 if (false !== $entry && !(empty($tags))) {
671 $tags = explode(',', $tags);
672 foreach ($tags as $label) {
673 $label = trim($label);
675 $tag = $this->getDoctrine()
676 ->getRepository('WallabagCoreBundle:Tag')
677 ->findOneByLabel($label);
679 if (false !== $tag) {
680 $entry->removeTag($tag);
684 $em = $this->getDoctrine()->getManager();
685 $em->persist($entry);
690 return $this->sendResponse($results);
694 * Handles an entries list and add tags to them.
698 * {"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."}
702 * @return JsonResponse
704 public function postEntriesTagsListAction(Request
$request)
706 $this->validateAuthentication();
708 $list = json_decode($request->query
->get('list', []));
711 return $this->sendResponse([]);
716 // handle multiple urls
717 foreach ($list as $key => $element) {
718 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
720 $this->getUser()->getId()
723 $results[$key]['url'] = $element->url
;
724 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
726 $tags = $element->tags
;
728 if (false !== $entry && !(empty($tags))) {
729 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
731 $em = $this->getDoctrine()->getManager();
732 $em->persist($entry);
737 return $this->sendResponse($results);
741 * Shortcut to send data serialized in json.
745 * @return JsonResponse
747 private function sendResponse($data)
749 // https://github.com/schmittjoh/JMSSerializerBundle/issues/293
750 $context = new SerializationContext();
751 $context->setSerializeNull(true);
753 $json = $this->get('serializer')->serialize($data, 'json', $context);
755 return (new JsonResponse())->setJson($json);
759 * Retrieve value from the request.
760 * Used for POST & PATCH on a an entry.
762 * @param Request $request
766 private function retrieveValueFromRequest(Request
$request)
769 'title' => $request->request
->get('title'),
770 'tags' => $request->request
->get('tags', []),
771 'isArchived' => $request->request
->get('archive'),
772 'isStarred' => $request->request
->get('starred'),
773 'isPublic' => $request->request
->get('public'),
774 'content' => $request->request
->get('content'),
775 'language' => $request->request
->get('language'),
776 'picture' => $request->request
->get('preview_picture'),
777 'publishedAt' => $request->request
->get('published_at'),
778 'authors' => $request->request
->get('authors', ''),
783 * Return information about the entry if it exist and depending on the id or not.
785 * @param Entry|null $entry
786 * @param bool $returnId
790 private function returnExistInformation($entry, $returnId)
793 return $entry instanceof Entry
? $entry->getId() : null;
796 return $entry instanceof Entry
;