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\HttpException
;
13 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
14 use Wallabag\CoreBundle\Entity\Entry
;
15 use Wallabag\CoreBundle\Entity\Tag
;
16 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
17 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
19 class EntryRestController
extends WallabagRestController
22 * Check if an entry exist by url.
23 * Return ID if entry(ies) exist (and if you give the return_id parameter).
24 * Otherwise it returns false.
26 * @todo Remove that `return_id` in the next major release
30 * {"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"},
31 * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
32 * {"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"}
36 * @return JsonResponse
38 public function getEntriesExistsAction(Request
$request)
40 $this->validateAuthentication();
42 $returnId = (null === $request->query
->get('return_id')) ? false : (bool) $request->query
->get('return_id');
43 $urls = $request->query
->get('urls', []);
45 // handle multiple urls first
48 foreach ($urls as $url) {
49 $res = $this->getDoctrine()
50 ->getRepository('WallabagCoreBundle:Entry')
51 ->findByUrlAndUserId($url, $this->getUser()->getId());
53 $results[$url] = $this->returnExistInformation($res, $returnId);
56 return $this->sendResponse($results);
59 // let's see if it is a simple url?
60 $url = $request->query
->get('url', '');
63 throw $this->createAccessDeniedException('URL is empty?, logged user id: ' . $this->getUser()->getId());
66 $res = $this->getDoctrine()
67 ->getRepository('WallabagCoreBundle:Entry')
68 ->findByUrlAndUserId($url, $this->getUser()->getId());
70 $exists = $this->returnExistInformation($res, $returnId);
72 return $this->sendResponse(['exists' => $exists]);
76 * Retrieve all entries. It could be filtered by many options.
80 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
81 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
82 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
83 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
84 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
85 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
86 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
87 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
88 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by entries with a public link"},
92 * @return JsonResponse
94 public function getEntriesAction(Request
$request)
96 $this->validateAuthentication();
98 $isArchived = (null === $request->query
->get('archive')) ? null : (bool) $request->query
->get('archive');
99 $isStarred = (null === $request->query
->get('starred')) ? null : (bool) $request->query
->get('starred');
100 $isPublic = (null === $request->query
->get('public')) ? null : (bool) $request->query
->get('public');
101 $sort = $request->query
->get('sort', 'created');
102 $order = $request->query
->get('order', 'desc');
103 $page = (int) $request->query
->get('page', 1);
104 $perPage = (int) $request->query
->get('perPage', 30);
105 $tags = $request->query
->get('tags', '');
106 $since = $request->query
->get('since', 0);
108 /** @var \Pagerfanta\Pagerfanta $pager */
109 $pager = $this->get('wallabag_core.entry_repository')->findEntries(
110 $this->getUser()->getId(),
120 $pager->setMaxPerPage($perPage);
121 $pager->setCurrentPage($page);
123 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
124 $paginatedCollection = $pagerfantaFactory->createRepresentation(
129 'archive' => $isArchived,
130 'starred' => $isStarred,
131 'public' => $isPublic,
135 'perPage' => $perPage,
139 UrlGeneratorInterface
::ABSOLUTE_URL
143 return $this->sendResponse($paginatedCollection);
147 * Retrieve a single entry.
151 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
155 * @return JsonResponse
157 public function getEntryAction(Entry
$entry)
159 $this->validateAuthentication();
160 $this->validateUserAccess($entry->getUser()->getId());
162 return $this->sendResponse($entry);
166 * Retrieve a single entry as a predefined format.
170 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
176 public function getEntryExportAction(Entry
$entry, Request
$request)
178 $this->validateAuthentication();
179 $this->validateUserAccess($entry->getUser()->getId());
181 return $this->get('wallabag_core.helper.entries_export')
183 ->updateTitle('entry')
184 ->updateAuthor('entry')
185 ->exportAs($request->attributes
->get('_format'));
189 * Handles an entries list and delete URL.
193 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
197 * @return JsonResponse
199 public function deleteEntriesListAction(Request
$request)
201 $this->validateAuthentication();
203 $urls = json_decode($request->query
->get('urls', []));
206 return $this->sendResponse([]);
211 // handle multiple urls
212 foreach ($urls as $key => $url) {
213 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
215 $this->getUser()->getId()
218 $results[$key]['url'] = $url;
220 if (false !== $entry) {
221 $em = $this->getDoctrine()->getManager();
225 // entry deleted, dispatch event about it!
226 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
229 $results[$key]['entry'] = $entry instanceof Entry
? true : false;
232 return $this->sendResponse($results);
236 * Handles an entries list and create URL.
240 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
244 * @throws HttpException When limit is reached
246 * @return JsonResponse
248 public function postEntriesListAction(Request
$request)
250 $this->validateAuthentication();
252 $urls = json_decode($request->query
->get('urls', []));
254 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
256 if (count($urls) > $limit) {
257 throw new HttpException(400, 'API limit reached');
262 return $this->sendResponse($results);
265 // handle multiple urls
266 foreach ($urls as $key => $url) {
267 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
269 $this->getUser()->getId()
272 $results[$key]['url'] = $url;
274 if (false === $entry) {
275 $entry = new Entry($this->getUser());
277 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
280 $em = $this->getDoctrine()->getManager();
281 $em->persist($entry);
284 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
286 // entry saved, dispatch event about it!
287 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
290 return $this->sendResponse($results);
296 * 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**.
297 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
301 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
302 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
303 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
304 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
305 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
306 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
307 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
308 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
309 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
310 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
311 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
315 * @return JsonResponse
317 public function postEntriesAction(Request
$request)
319 $this->validateAuthentication();
321 $url = $request->request
->get('url');
323 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
325 $this->getUser()->getId()
328 if (false === $entry) {
329 $entry = new Entry($this->getUser());
330 $entry->setUrl($url);
333 $data = $this->retrieveValueFromRequest($request);
336 $this->get('wallabag_core.content_proxy')->updateEntry(
340 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
341 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
342 'url' => $entry->getUrl(),
343 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
344 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
345 // faking the open graph preview picture
347 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
349 'authors' => is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
352 } catch (\Exception
$e) {
353 $this->get('logger')->error('Error while saving an entry', [
359 if (null !== $data['isArchived']) {
360 $entry->setArchived((bool) $data['isArchived']);
363 if (null !== $data['isStarred']) {
364 $entry->setStarred((bool) $data['isStarred']);
367 if (!empty($data['tags'])) {
368 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
371 if (null !== $data['isPublic']) {
372 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
373 $entry->generateUid();
374 } elseif (false === (bool) $data['isPublic']) {
379 $em = $this->getDoctrine()->getManager();
380 $em->persist($entry);
383 // entry saved, dispatch event about it!
384 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
386 return $this->sendResponse($entry);
390 * Change several properties of an entry.
394 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
397 * {"name"="title", "dataType"="string", "required"=false},
398 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
399 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
400 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
401 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
402 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
403 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
404 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
405 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
406 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
410 * @return JsonResponse
412 public function patchEntriesAction(Entry
$entry, Request
$request)
414 $this->validateAuthentication();
415 $this->validateUserAccess($entry->getUser()->getId());
417 $contentProxy = $this->get('wallabag_core.content_proxy');
419 $data = $this->retrieveValueFromRequest($request);
421 // this is a special case where user want to manually update the entry content
422 // the ContentProxy will only cleanup the html
423 // and also we force to not re-fetch the content in case of error
424 if (!empty($data['content'])) {
426 $contentProxy->updateEntry(
430 'html' => $data['content'],
434 } catch (\Exception
$e) {
435 $this->get('logger')->error('Error while saving an entry', [
442 if (!empty($data['title'])) {
443 $entry->setTitle($data['title']);
446 if (!empty($data['language'])) {
447 $contentProxy->updateLanguage($entry, $data['language']);
450 if (!empty($data['authors']) && is_string($data['authors'])) {
451 $entry->setPublishedBy(explode(',', $data['authors']));
454 if (!empty($data['picture'])) {
455 $contentProxy->updatePreviewPicture($entry, $data['picture']);
458 if (!empty($data['publishedAt'])) {
459 $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
462 if (null !== $data['isArchived']) {
463 $entry->setArchived((bool) $data['isArchived']);
466 if (null !== $data['isStarred']) {
467 $entry->setStarred((bool) $data['isStarred']);
470 if (!empty($data['tags'])) {
471 $entry->removeAllTags();
472 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
475 if (null !== $data['isPublic']) {
476 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
477 $entry->generateUid();
478 } elseif (false === (bool) $data['isPublic']) {
483 $em = $this->getDoctrine()->getManager();
484 $em->persist($entry);
487 // entry saved, dispatch event about it!
488 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
490 return $this->sendResponse($entry);
495 * 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).
499 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
503 * @return JsonResponse
505 public function patchEntriesReloadAction(Entry
$entry)
507 $this->validateAuthentication();
508 $this->validateUserAccess($entry->getUser()->getId());
511 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
512 } catch (\Exception
$e) {
513 $this->get('logger')->error('Error while saving an entry', [
518 return new JsonResponse([], 304);
521 // if refreshing entry failed, don't save it
522 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
523 return new JsonResponse([], 304);
526 $em = $this->getDoctrine()->getManager();
527 $em->persist($entry);
530 // entry saved, dispatch event about it!
531 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
533 return $this->sendResponse($entry);
537 * Delete **permanently** an entry.
541 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
545 * @return JsonResponse
547 public function deleteEntriesAction(Entry
$entry)
549 $this->validateAuthentication();
550 $this->validateUserAccess($entry->getUser()->getId());
552 $em = $this->getDoctrine()->getManager();
556 // entry deleted, dispatch event about it!
557 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
559 return $this->sendResponse($entry);
563 * Retrieve all tags for an entry.
567 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
571 * @return JsonResponse
573 public function getEntriesTagsAction(Entry
$entry)
575 $this->validateAuthentication();
576 $this->validateUserAccess($entry->getUser()->getId());
578 return $this->sendResponse($entry->getTags());
582 * Add one or more tags to an entry.
586 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
589 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
593 * @return JsonResponse
595 public function postEntriesTagsAction(Request
$request, Entry
$entry)
597 $this->validateAuthentication();
598 $this->validateUserAccess($entry->getUser()->getId());
600 $tags = $request->request
->get('tags', '');
602 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
605 $em = $this->getDoctrine()->getManager();
606 $em->persist($entry);
609 return $this->sendResponse($entry);
613 * Permanently remove one tag for an entry.
617 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
618 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
622 * @return JsonResponse
624 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
626 $this->validateAuthentication();
627 $this->validateUserAccess($entry->getUser()->getId());
629 $entry->removeTag($tag);
630 $em = $this->getDoctrine()->getManager();
631 $em->persist($entry);
634 return $this->sendResponse($entry);
638 * Handles an entries list delete tags from them.
642 * {"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."}
646 * @return JsonResponse
648 public function deleteEntriesTagsListAction(Request
$request)
650 $this->validateAuthentication();
652 $list = json_decode($request->query
->get('list', []));
655 return $this->sendResponse([]);
658 // handle multiple urls
661 foreach ($list as $key => $element) {
662 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
664 $this->getUser()->getId()
667 $results[$key]['url'] = $element->url
;
668 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
670 $tags = $element->tags
;
672 if (false !== $entry && !(empty($tags))) {
673 $tags = explode(',', $tags);
674 foreach ($tags as $label) {
675 $label = trim($label);
677 $tag = $this->getDoctrine()
678 ->getRepository('WallabagCoreBundle:Tag')
679 ->findOneByLabel($label);
681 if (false !== $tag) {
682 $entry->removeTag($tag);
686 $em = $this->getDoctrine()->getManager();
687 $em->persist($entry);
692 return $this->sendResponse($results);
696 * Handles an entries list and add tags to them.
700 * {"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."}
704 * @return JsonResponse
706 public function postEntriesTagsListAction(Request
$request)
708 $this->validateAuthentication();
710 $list = json_decode($request->query
->get('list', []));
713 return $this->sendResponse([]);
718 // handle multiple urls
719 foreach ($list as $key => $element) {
720 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
722 $this->getUser()->getId()
725 $results[$key]['url'] = $element->url
;
726 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
728 $tags = $element->tags
;
730 if (false !== $entry && !(empty($tags))) {
731 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
733 $em = $this->getDoctrine()->getManager();
734 $em->persist($entry);
739 return $this->sendResponse($results);
743 * Shortcut to send data serialized in json.
747 * @return JsonResponse
749 private function sendResponse($data)
751 // https://github.com/schmittjoh/JMSSerializerBundle/issues/293
752 $context = new SerializationContext();
753 $context->setSerializeNull(true);
755 $json = $this->get('serializer')->serialize($data, 'json', $context);
757 return (new JsonResponse())->setJson($json);
761 * Retrieve value from the request.
762 * Used for POST & PATCH on a an entry.
764 * @param Request $request
768 private function retrieveValueFromRequest(Request
$request)
771 'title' => $request->request
->get('title'),
772 'tags' => $request->request
->get('tags', []),
773 'isArchived' => $request->request
->get('archive'),
774 'isStarred' => $request->request
->get('starred'),
775 'isPublic' => $request->request
->get('public'),
776 'content' => $request->request
->get('content'),
777 'language' => $request->request
->get('language'),
778 'picture' => $request->request
->get('preview_picture'),
779 'publishedAt' => $request->request
->get('published_at'),
780 'authors' => $request->request
->get('authors', ''),
785 * Return information about the entry if it exist and depending on the id or not.
787 * @param Entry|null $entry
788 * @param bool $returnId
792 private function returnExistInformation($entry, $returnId)
795 return $entry instanceof Entry
? $entry->getId() : null;
798 return $entry instanceof Entry
;