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 ->updateAuthor('entry')
184 ->exportAs($request->attributes
->get('_format'));
188 * Handles an entries list and delete URL.
192 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
196 * @return JsonResponse
198 public function deleteEntriesListAction(Request
$request)
200 $this->validateAuthentication();
202 $urls = json_decode($request->query
->get('urls', []));
205 return $this->sendResponse([]);
210 // handle multiple urls
211 foreach ($urls as $key => $url) {
212 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
214 $this->getUser()->getId()
217 $results[$key]['url'] = $url;
219 if (false !== $entry) {
220 $em = $this->getDoctrine()->getManager();
224 // entry deleted, dispatch event about it!
225 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
228 $results[$key]['entry'] = $entry instanceof Entry
? true : false;
231 return $this->sendResponse($results);
235 * Handles an entries list and create URL.
239 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
243 * @throws HttpException When limit is reached
245 * @return JsonResponse
247 public function postEntriesListAction(Request
$request)
249 $this->validateAuthentication();
251 $urls = json_decode($request->query
->get('urls', []));
253 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
255 if (count($urls) > $limit) {
256 throw new HttpException(400, 'API limit reached');
261 return $this->sendResponse($results);
264 // handle multiple urls
265 foreach ($urls as $key => $url) {
266 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
268 $this->getUser()->getId()
271 $results[$key]['url'] = $url;
273 if (false === $entry) {
274 $entry = new Entry($this->getUser());
276 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
279 $em = $this->getDoctrine()->getManager();
280 $em->persist($entry);
283 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
285 // entry saved, dispatch event about it!
286 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
289 return $this->sendResponse($results);
295 * 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**.
296 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
300 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
301 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
302 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
303 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
304 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
305 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
306 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
307 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
308 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
309 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
310 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
314 * @return JsonResponse
316 public function postEntriesAction(Request
$request)
318 $this->validateAuthentication();
320 $url = $request->request
->get('url');
322 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
324 $this->getUser()->getId()
327 if (false === $entry) {
328 $entry = new Entry($this->getUser());
329 $entry->setUrl($url);
332 $data = $this->retrieveValueFromRequest($request);
335 $this->get('wallabag_core.content_proxy')->updateEntry(
339 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
340 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
341 'url' => $entry->getUrl(),
342 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
343 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
344 // faking the open graph preview picture
346 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
348 'authors' => is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
351 } catch (\Exception
$e) {
352 $this->get('logger')->error('Error while saving an entry', [
358 if (null !== $data['isArchived']) {
359 $entry->setArchived((bool) $data['isArchived']);
362 if (null !== $data['isStarred']) {
363 $entry->setStarred((bool) $data['isStarred']);
366 if (!empty($data['tags'])) {
367 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
370 if (null !== $data['isPublic']) {
371 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
372 $entry->generateUid();
373 } elseif (false === (bool) $data['isPublic']) {
378 $em = $this->getDoctrine()->getManager();
379 $em->persist($entry);
382 // entry saved, dispatch event about it!
383 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
385 return $this->sendResponse($entry);
389 * Change several properties of an entry.
393 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
396 * {"name"="title", "dataType"="string", "required"=false},
397 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
398 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
399 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
400 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
401 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
402 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
403 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
404 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
405 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
409 * @return JsonResponse
411 public function patchEntriesAction(Entry
$entry, Request
$request)
413 $this->validateAuthentication();
414 $this->validateUserAccess($entry->getUser()->getId());
416 $contentProxy = $this->get('wallabag_core.content_proxy');
418 $data = $this->retrieveValueFromRequest($request);
420 // this is a special case where user want to manually update the entry content
421 // the ContentProxy will only cleanup the html
422 // and also we force to not re-fetch the content in case of error
423 if (!empty($data['content'])) {
425 $contentProxy->updateEntry(
429 'html' => $data['content'],
433 } catch (\Exception
$e) {
434 $this->get('logger')->error('Error while saving an entry', [
441 if (!empty($data['title'])) {
442 $entry->setTitle($data['title']);
445 if (!empty($data['language'])) {
446 $contentProxy->updateLanguage($entry, $data['language']);
449 if (!empty($data['authors']) && is_string($data['authors'])) {
450 $entry->setPublishedBy(explode(',', $data['authors']));
453 if (!empty($data['picture'])) {
454 $contentProxy->updatePreviewPicture($entry, $data['picture']);
457 if (!empty($data['publishedAt'])) {
458 $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
461 if (null !== $data['isArchived']) {
462 $entry->setArchived((bool) $data['isArchived']);
465 if (null !== $data['isStarred']) {
466 $entry->setStarred((bool) $data['isStarred']);
469 if (!empty($data['tags'])) {
470 $entry->removeAllTags();
471 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
474 if (null !== $data['isPublic']) {
475 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
476 $entry->generateUid();
477 } elseif (false === (bool) $data['isPublic']) {
482 $em = $this->getDoctrine()->getManager();
483 $em->persist($entry);
486 // entry saved, dispatch event about it!
487 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
489 return $this->sendResponse($entry);
494 * 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).
498 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
502 * @return JsonResponse
504 public function patchEntriesReloadAction(Entry
$entry)
506 $this->validateAuthentication();
507 $this->validateUserAccess($entry->getUser()->getId());
510 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
511 } catch (\Exception
$e) {
512 $this->get('logger')->error('Error while saving an entry', [
517 return new JsonResponse([], 304);
520 // if refreshing entry failed, don't save it
521 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
522 return new JsonResponse([], 304);
525 $em = $this->getDoctrine()->getManager();
526 $em->persist($entry);
529 // entry saved, dispatch event about it!
530 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
532 return $this->sendResponse($entry);
536 * Delete **permanently** an entry.
540 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
544 * @return JsonResponse
546 public function deleteEntriesAction(Entry
$entry)
548 $this->validateAuthentication();
549 $this->validateUserAccess($entry->getUser()->getId());
551 $em = $this->getDoctrine()->getManager();
555 // entry deleted, dispatch event about it!
556 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
558 return $this->sendResponse($entry);
562 * Retrieve all tags for an entry.
566 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
570 * @return JsonResponse
572 public function getEntriesTagsAction(Entry
$entry)
574 $this->validateAuthentication();
575 $this->validateUserAccess($entry->getUser()->getId());
577 return $this->sendResponse($entry->getTags());
581 * Add one or more tags to an entry.
585 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
588 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
592 * @return JsonResponse
594 public function postEntriesTagsAction(Request
$request, Entry
$entry)
596 $this->validateAuthentication();
597 $this->validateUserAccess($entry->getUser()->getId());
599 $tags = $request->request
->get('tags', '');
601 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
604 $em = $this->getDoctrine()->getManager();
605 $em->persist($entry);
608 return $this->sendResponse($entry);
612 * Permanently remove one tag for an entry.
616 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
617 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
621 * @return JsonResponse
623 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
625 $this->validateAuthentication();
626 $this->validateUserAccess($entry->getUser()->getId());
628 $entry->removeTag($tag);
629 $em = $this->getDoctrine()->getManager();
630 $em->persist($entry);
633 return $this->sendResponse($entry);
637 * Handles an entries list delete tags from them.
641 * {"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."}
645 * @return JsonResponse
647 public function deleteEntriesTagsListAction(Request
$request)
649 $this->validateAuthentication();
651 $list = json_decode($request->query
->get('list', []));
654 return $this->sendResponse([]);
657 // handle multiple urls
660 foreach ($list as $key => $element) {
661 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
663 $this->getUser()->getId()
666 $results[$key]['url'] = $element->url
;
667 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
669 $tags = $element->tags
;
671 if (false !== $entry && !(empty($tags))) {
672 $tags = explode(',', $tags);
673 foreach ($tags as $label) {
674 $label = trim($label);
676 $tag = $this->getDoctrine()
677 ->getRepository('WallabagCoreBundle:Tag')
678 ->findOneByLabel($label);
680 if (false !== $tag) {
681 $entry->removeTag($tag);
685 $em = $this->getDoctrine()->getManager();
686 $em->persist($entry);
691 return $this->sendResponse($results);
695 * Handles an entries list and add tags to them.
699 * {"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."}
703 * @return JsonResponse
705 public function postEntriesTagsListAction(Request
$request)
707 $this->validateAuthentication();
709 $list = json_decode($request->query
->get('list', []));
712 return $this->sendResponse([]);
717 // handle multiple urls
718 foreach ($list as $key => $element) {
719 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
721 $this->getUser()->getId()
724 $results[$key]['url'] = $element->url
;
725 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
727 $tags = $element->tags
;
729 if (false !== $entry && !(empty($tags))) {
730 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
732 $em = $this->getDoctrine()->getManager();
733 $em->persist($entry);
738 return $this->sendResponse($results);
742 * Shortcut to send data serialized in json.
746 * @return JsonResponse
748 private function sendResponse($data)
750 // https://github.com/schmittjoh/JMSSerializerBundle/issues/293
751 $context = new SerializationContext();
752 $context->setSerializeNull(true);
754 $json = $this->get('serializer')->serialize($data, 'json', $context);
756 return (new JsonResponse())->setJson($json);
760 * Retrieve value from the request.
761 * Used for POST & PATCH on a an entry.
763 * @param Request $request
767 private function retrieveValueFromRequest(Request
$request)
770 'title' => $request->request
->get('title'),
771 'tags' => $request->request
->get('tags', []),
772 'isArchived' => $request->request
->get('archive'),
773 'isStarred' => $request->request
->get('starred'),
774 'isPublic' => $request->request
->get('public'),
775 'content' => $request->request
->get('content'),
776 'language' => $request->request
->get('language'),
777 'picture' => $request->request
->get('preview_picture'),
778 'publishedAt' => $request->request
->get('published_at'),
779 'authors' => $request->request
->get('authors', ''),
784 * Return information about the entry if it exist and depending on the id or not.
786 * @param Entry|null $entry
787 * @param bool $returnId
791 private function returnExistInformation($entry, $returnId)
794 return $entry instanceof Entry
? $entry->getId() : null;
797 return $entry instanceof Entry
;