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\HttpFoundation\Response
;
12 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException
;
13 use Symfony\Component\HttpKernel\Exception\HttpException
;
14 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
15 use Wallabag\CoreBundle\Entity\Entry
;
16 use Wallabag\CoreBundle\Entity\Tag
;
17 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
18 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
20 class EntryRestController
extends WallabagRestController
23 * Check if an entry exist by url.
24 * Return ID if entry(ies) exist (and if you give the return_id parameter).
25 * Otherwise it returns false.
27 * @todo Remove that `return_id` in the next major release
31 * {"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"},
32 * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
33 * {"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"}
37 * @return JsonResponse
39 public function getEntriesExistsAction(Request
$request)
41 $this->validateAuthentication();
43 $returnId = (null === $request->query
->get('return_id')) ? false : (bool) $request->query
->get('return_id');
44 $urls = $request->query
->get('urls', []);
46 // handle multiple urls first
49 foreach ($urls as $url) {
50 $res = $this->getDoctrine()
51 ->getRepository('WallabagCoreBundle:Entry')
52 ->findByUrlAndUserId($url, $this->getUser()->getId());
54 $results[$url] = $this->returnExistInformation($res, $returnId);
57 return $this->sendResponse($results);
60 // let's see if it is a simple url?
61 $url = $request->query
->get('url', '');
64 throw $this->createAccessDeniedException('URL is empty?, logged user id: ' . $this->getUser()->getId());
67 $res = $this->getDoctrine()
68 ->getRepository('WallabagCoreBundle:Entry')
69 ->findByUrlAndUserId($url, $this->getUser()->getId());
71 $exists = $this->returnExistInformation($res, $returnId);
73 return $this->sendResponse(['exists' => $exists]);
77 * Retrieve all entries. It could be filtered by many options.
81 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
82 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
83 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
84 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
85 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
86 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
87 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
88 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
89 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by entries with a public link"},
93 * @return JsonResponse
95 public function getEntriesAction(Request
$request)
97 $this->validateAuthentication();
99 $isArchived = (null === $request->query
->get('archive')) ? null : (bool) $request->query
->get('archive');
100 $isStarred = (null === $request->query
->get('starred')) ? null : (bool) $request->query
->get('starred');
101 $isPublic = (null === $request->query
->get('public')) ? null : (bool) $request->query
->get('public');
102 $sort = strtolower($request->query
->get('sort', 'created'));
103 $order = strtolower($request->query
->get('order', 'desc'));
104 $page = (int) $request->query
->get('page', 1);
105 $perPage = (int) $request->query
->get('perPage', 30);
106 $tags = \
is_array($request->query
->get('tags')) ? '' : (string) $request->query
->get('tags', '');
107 $since = $request->query
->get('since', 0);
110 /** @var \Pagerfanta\Pagerfanta $pager */
111 $pager = $this->get('wallabag_core.entry_repository')->findEntries(
112 $this->getUser()->getId(),
121 } catch (\Exception
$e) {
122 throw new BadRequestHttpException($e->getMessage());
125 $pager->setMaxPerPage($perPage);
126 $pager->setCurrentPage($page);
128 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
129 $paginatedCollection = $pagerfantaFactory->createRepresentation(
134 'archive' => $isArchived,
135 'starred' => $isStarred,
136 'public' => $isPublic,
140 'perPage' => $perPage,
144 UrlGeneratorInterface
::ABSOLUTE_URL
148 return $this->sendResponse($paginatedCollection);
152 * Retrieve a single entry.
156 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
160 * @return JsonResponse
162 public function getEntryAction(Entry
$entry)
164 $this->validateAuthentication();
165 $this->validateUserAccess($entry->getUser()->getId());
167 return $this->sendResponse($entry);
171 * Retrieve a single entry as a predefined format.
175 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
181 public function getEntryExportAction(Entry
$entry, Request
$request)
183 $this->validateAuthentication();
184 $this->validateUserAccess($entry->getUser()->getId());
186 return $this->get('wallabag_core.helper.entries_export')
188 ->updateTitle('entry')
189 ->updateAuthor('entry')
190 ->exportAs($request->attributes
->get('_format'));
194 * Handles an entries list and delete URL.
198 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
202 * @return JsonResponse
204 public function deleteEntriesListAction(Request
$request)
206 $this->validateAuthentication();
208 $urls = json_decode($request->query
->get('urls', []));
211 return $this->sendResponse([]);
216 // handle multiple urls
217 foreach ($urls as $key => $url) {
218 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
220 $this->getUser()->getId()
223 $results[$key]['url'] = $url;
225 if (false !== $entry) {
226 $em = $this->getDoctrine()->getManager();
230 // entry deleted, dispatch event about it!
231 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
234 $results[$key]['entry'] = $entry instanceof Entry
? true : false;
237 return $this->sendResponse($results);
241 * Handles an entries list and create URL.
245 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
249 * @throws HttpException When limit is reached
251 * @return JsonResponse
253 public function postEntriesListAction(Request
$request)
255 $this->validateAuthentication();
257 $urls = json_decode($request->query
->get('urls', []));
259 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
261 if (\
count($urls) > $limit) {
262 throw new HttpException(400, 'API limit reached');
267 return $this->sendResponse($results);
270 // handle multiple urls
271 foreach ($urls as $key => $url) {
272 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
274 $this->getUser()->getId()
277 $results[$key]['url'] = $url;
279 if (false === $entry) {
280 $entry = new Entry($this->getUser());
282 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
285 $em = $this->getDoctrine()->getManager();
286 $em->persist($entry);
289 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
291 // entry saved, dispatch event about it!
292 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
295 return $this->sendResponse($results);
301 * 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**.
302 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
306 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
307 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
308 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
309 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
310 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
311 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
312 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
313 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
314 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
315 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
316 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
317 * {"name"="origin_url", "dataType"="string", "required"=false, "format"="http://www.test.com/article.html", "description"="Origin url for the entry (from where you found it)."},
321 * @return JsonResponse
323 public function postEntriesAction(Request
$request)
325 $this->validateAuthentication();
327 $url = $request->request
->get('url');
329 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
331 $this->getUser()->getId()
334 if (false === $entry) {
335 $entry = new Entry($this->getUser());
336 $entry->setUrl($url);
339 $data = $this->retrieveValueFromRequest($request);
342 $this->get('wallabag_core.content_proxy')->updateEntry(
346 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
347 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
348 'url' => $entry->getUrl(),
349 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
350 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
351 // faking the open graph preview picture
353 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
355 'authors' => \
is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
358 } catch (\Exception
$e) {
359 $this->get('logger')->error('Error while saving an entry', [
365 if (null !== $data['isArchived']) {
366 $entry->setArchived((bool) $data['isArchived']);
369 if (null !== $data['isStarred']) {
370 $entry->updateStar((bool) $data['isStarred']);
373 if (!empty($data['tags'])) {
374 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
377 if (!empty($data['origin_url'])) {
378 $entry->setOriginUrl($data['origin_url']);
381 if (null !== $data['isPublic']) {
382 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
383 $entry->generateUid();
384 } elseif (false === (bool) $data['isPublic']) {
389 if (empty($entry->getDomainName())) {
390 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
393 if (empty($entry->getTitle())) {
394 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
397 $em = $this->getDoctrine()->getManager();
398 $em->persist($entry);
401 // entry saved, dispatch event about it!
402 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
404 return $this->sendResponse($entry);
408 * Change several properties of an entry.
412 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
415 * {"name"="title", "dataType"="string", "required"=false},
416 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
417 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
418 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
419 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
420 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
421 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
422 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
423 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
424 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
425 * {"name"="origin_url", "dataType"="string", "required"=false, "format"="http://www.test.com/article.html", "description"="Origin url for the entry (from where you found it)."},
429 * @return JsonResponse
431 public function patchEntriesAction(Entry
$entry, Request
$request)
433 $this->validateAuthentication();
434 $this->validateUserAccess($entry->getUser()->getId());
436 $contentProxy = $this->get('wallabag_core.content_proxy');
438 $data = $this->retrieveValueFromRequest($request);
440 // this is a special case where user want to manually update the entry content
441 // the ContentProxy will only cleanup the html
442 // and also we force to not re-fetch the content in case of error
443 if (!empty($data['content'])) {
445 $contentProxy->updateEntry(
449 'html' => $data['content'],
453 } catch (\Exception
$e) {
454 $this->get('logger')->error('Error while saving an entry', [
461 if (!empty($data['title'])) {
462 $entry->setTitle($data['title']);
465 if (!empty($data['language'])) {
466 $contentProxy->updateLanguage($entry, $data['language']);
469 if (!empty($data['authors']) && \
is_string($data['authors'])) {
470 $entry->setPublishedBy(explode(',', $data['authors']));
473 if (!empty($data['picture'])) {
474 $contentProxy->updatePreviewPicture($entry, $data['picture']);
477 if (!empty($data['publishedAt'])) {
478 $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
481 if (null !== $data['isArchived']) {
482 $entry->setArchived((bool) $data['isArchived']);
485 if (null !== $data['isStarred']) {
486 $entry->updateStar((bool) $data['isStarred']);
489 if (!empty($data['tags'])) {
490 $entry->removeAllTags();
491 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
494 if (null !== $data['isPublic']) {
495 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
496 $entry->generateUid();
497 } elseif (false === (bool) $data['isPublic']) {
502 if (!empty($data['origin_url'])) {
503 $entry->setOriginUrl($data['origin_url']);
506 if (empty($entry->getDomainName())) {
507 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
510 if (empty($entry->getTitle())) {
511 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
514 $em = $this->getDoctrine()->getManager();
515 $em->persist($entry);
518 // entry saved, dispatch event about it!
519 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
521 return $this->sendResponse($entry);
526 * 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).
530 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
534 * @return JsonResponse
536 public function patchEntriesReloadAction(Entry
$entry)
538 $this->validateAuthentication();
539 $this->validateUserAccess($entry->getUser()->getId());
542 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
543 } catch (\Exception
$e) {
544 $this->get('logger')->error('Error while saving an entry', [
549 return new JsonResponse([], 304);
552 // if refreshing entry failed, don't save it
553 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
554 return new JsonResponse([], 304);
557 $em = $this->getDoctrine()->getManager();
558 $em->persist($entry);
561 // entry saved, dispatch event about it!
562 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
564 return $this->sendResponse($entry);
568 * Delete **permanently** an entry.
572 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
576 * @return JsonResponse
578 public function deleteEntriesAction(Entry
$entry)
580 $this->validateAuthentication();
581 $this->validateUserAccess($entry->getUser()->getId());
583 // We copy $entry to keep id in returned object
586 $em = $this->getDoctrine()->getManager();
590 // entry deleted, dispatch event about it!
591 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
593 return $this->sendResponse($e);
597 * Retrieve all tags for an entry.
601 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
605 * @return JsonResponse
607 public function getEntriesTagsAction(Entry
$entry)
609 $this->validateAuthentication();
610 $this->validateUserAccess($entry->getUser()->getId());
612 return $this->sendResponse($entry->getTags());
616 * Add one or more tags to an entry.
620 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
623 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
627 * @return JsonResponse
629 public function postEntriesTagsAction(Request
$request, Entry
$entry)
631 $this->validateAuthentication();
632 $this->validateUserAccess($entry->getUser()->getId());
634 $tags = $request->request
->get('tags', '');
636 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
639 $em = $this->getDoctrine()->getManager();
640 $em->persist($entry);
643 return $this->sendResponse($entry);
647 * Permanently remove one tag for an entry.
651 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
652 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
656 * @return JsonResponse
658 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
660 $this->validateAuthentication();
661 $this->validateUserAccess($entry->getUser()->getId());
663 $entry->removeTag($tag);
664 $em = $this->getDoctrine()->getManager();
665 $em->persist($entry);
668 return $this->sendResponse($entry);
672 * Handles an entries list delete tags from them.
676 * {"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."}
680 * @return JsonResponse
682 public function deleteEntriesTagsListAction(Request
$request)
684 $this->validateAuthentication();
686 $list = json_decode($request->query
->get('list', []));
689 return $this->sendResponse([]);
692 // handle multiple urls
695 foreach ($list as $key => $element) {
696 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
698 $this->getUser()->getId()
701 $results[$key]['url'] = $element->url
;
702 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
704 $tags = $element->tags
;
706 if (false !== $entry && !(empty($tags))) {
707 $tags = explode(',', $tags);
708 foreach ($tags as $label) {
709 $label = trim($label);
711 $tag = $this->getDoctrine()
712 ->getRepository('WallabagCoreBundle:Tag')
713 ->findOneByLabel($label);
715 if (false !== $tag) {
716 $entry->removeTag($tag);
720 $em = $this->getDoctrine()->getManager();
721 $em->persist($entry);
726 return $this->sendResponse($results);
730 * Handles an entries list and add tags to them.
734 * {"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."}
738 * @return JsonResponse
740 public function postEntriesTagsListAction(Request
$request)
742 $this->validateAuthentication();
744 $list = json_decode($request->query
->get('list', []));
747 return $this->sendResponse([]);
752 // handle multiple urls
753 foreach ($list as $key => $element) {
754 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
756 $this->getUser()->getId()
759 $results[$key]['url'] = $element->url
;
760 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
762 $tags = $element->tags
;
764 if (false !== $entry && !(empty($tags))) {
765 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
767 $em = $this->getDoctrine()->getManager();
768 $em->persist($entry);
773 return $this->sendResponse($results);
777 * Shortcut to send data serialized in json.
781 * @return JsonResponse
783 private function sendResponse($data)
785 // https://github.com/schmittjoh/JMSSerializerBundle/issues/293
786 $context = new SerializationContext();
787 $context->setSerializeNull(true);
789 $json = $this->get('jms_serializer')->serialize($data, 'json', $context);
791 return (new JsonResponse())->setJson($json);
795 * Retrieve value from the request.
796 * Used for POST & PATCH on a an entry.
798 * @param Request $request
802 private function retrieveValueFromRequest(Request
$request)
805 'title' => $request->request
->get('title'),
806 'tags' => $request->request
->get('tags', []),
807 'isArchived' => $request->request
->get('archive'),
808 'isStarred' => $request->request
->get('starred'),
809 'isPublic' => $request->request
->get('public'),
810 'content' => $request->request
->get('content'),
811 'language' => $request->request
->get('language'),
812 'picture' => $request->request
->get('preview_picture'),
813 'publishedAt' => $request->request
->get('published_at'),
814 'authors' => $request->request
->get('authors', ''),
815 'origin_url' => $request->request
->get('origin_url', ''),
820 * Return information about the entry if it exist and depending on the id or not.
822 * @param Entry|null $entry
823 * @param bool $returnId
827 private function returnExistInformation($entry, $returnId)
830 return $entry instanceof Entry
? $entry->getId() : null;
833 return $entry instanceof Entry
;