3 namespace Wallabag\ApiBundle\Controller
;
5 use Hateoas\Configuration\Route
;
6 use Hateoas\Representation\Factory\PagerfantaFactory
;
7 use Nelmio\ApiDocBundle\Annotation\ApiDoc
;
8 use Symfony\Component\HttpFoundation\JsonResponse
;
9 use Symfony\Component\HttpFoundation\Request
;
10 use Symfony\Component\HttpFoundation\Response
;
11 use Symfony\Component\HttpKernel\Exception\BadRequestHttpException
;
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' or 'archived', 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 = strtolower($request->query
->get('sort', 'created'));
102 $order = strtolower($request->query
->get('order', 'desc'));
103 $page = (int) $request->query
->get('page', 1);
104 $perPage = (int) $request->query
->get('perPage', 30);
105 $tags = \
is_array($request->query
->get('tags')) ? '' : (string) $request->query
->get('tags', '');
106 $since = $request->query
->get('since', 0);
109 /** @var \Pagerfanta\Pagerfanta $pager */
110 $pager = $this->get('wallabag_core.entry_repository')->findEntries(
111 $this->getUser()->getId(),
120 } catch (\Exception
$e) {
121 throw new BadRequestHttpException($e->getMessage());
124 $pager->setMaxPerPage($perPage);
125 $pager->setCurrentPage($page);
127 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
128 $paginatedCollection = $pagerfantaFactory->createRepresentation(
133 'archive' => $isArchived,
134 'starred' => $isStarred,
135 'public' => $isPublic,
139 'perPage' => $perPage,
143 UrlGeneratorInterface
::ABSOLUTE_URL
147 return $this->sendResponse($paginatedCollection);
151 * Retrieve a single entry.
155 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
159 * @return JsonResponse
161 public function getEntryAction(Entry
$entry)
163 $this->validateAuthentication();
164 $this->validateUserAccess($entry->getUser()->getId());
166 return $this->sendResponse($entry);
170 * Retrieve a single entry as a predefined format.
174 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
180 public function getEntryExportAction(Entry
$entry, Request
$request)
182 $this->validateAuthentication();
183 $this->validateUserAccess($entry->getUser()->getId());
185 return $this->get('wallabag_core.helper.entries_export')
187 ->updateTitle('entry')
188 ->updateAuthor('entry')
189 ->exportAs($request->attributes
->get('_format'));
193 * Handles an entries list and delete URL.
197 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
201 * @return JsonResponse
203 public function deleteEntriesListAction(Request
$request)
205 $this->validateAuthentication();
207 $urls = json_decode($request->query
->get('urls', []));
210 return $this->sendResponse([]);
215 // handle multiple urls
216 foreach ($urls as $key => $url) {
217 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
219 $this->getUser()->getId()
222 $results[$key]['url'] = $url;
224 if (false !== $entry) {
225 $em = $this->getDoctrine()->getManager();
229 // entry deleted, dispatch event about it!
230 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
233 $results[$key]['entry'] = $entry instanceof Entry
? true : false;
236 return $this->sendResponse($results);
240 * Handles an entries list and create URL.
244 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
248 * @throws HttpException When limit is reached
250 * @return JsonResponse
252 public function postEntriesListAction(Request
$request)
254 $this->validateAuthentication();
256 $urls = json_decode($request->query
->get('urls', []));
258 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
260 if (\
count($urls) > $limit) {
261 throw new HttpException(400, 'API limit reached');
266 return $this->sendResponse($results);
269 // handle multiple urls
270 foreach ($urls as $key => $url) {
271 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
273 $this->getUser()->getId()
276 $results[$key]['url'] = $url;
278 if (false === $entry) {
279 $entry = new Entry($this->getUser());
281 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
284 $em = $this->getDoctrine()->getManager();
285 $em->persist($entry);
288 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
290 // entry saved, dispatch event about it!
291 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
294 return $this->sendResponse($results);
300 * 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**.
301 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
305 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
306 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
307 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
308 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
309 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
310 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
311 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
312 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
313 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
314 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
315 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
316 * {"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)."},
320 * @return JsonResponse
322 public function postEntriesAction(Request
$request)
324 $this->validateAuthentication();
326 $url = $request->request
->get('url');
328 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
330 $this->getUser()->getId()
333 if (false === $entry) {
334 $entry = new Entry($this->getUser());
335 $entry->setUrl($url);
338 $data = $this->retrieveValueFromRequest($request);
341 $this->get('wallabag_core.content_proxy')->updateEntry(
345 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
346 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
347 'url' => $entry->getUrl(),
348 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
349 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
350 // faking the open graph preview picture
352 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
354 'authors' => \
is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
357 } catch (\Exception
$e) {
358 $this->get('logger')->error('Error while saving an entry', [
364 if (null !== $data['isArchived']) {
365 $entry->updateArchived((bool) $data['isArchived']);
368 if (null !== $data['isStarred']) {
369 $entry->updateStar((bool) $data['isStarred']);
372 if (!empty($data['tags'])) {
373 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
376 if (!empty($data['origin_url'])) {
377 $entry->setOriginUrl($data['origin_url']);
380 if (null !== $data['isPublic']) {
381 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
382 $entry->generateUid();
383 } elseif (false === (bool) $data['isPublic']) {
388 if (empty($entry->getDomainName())) {
389 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
392 if (empty($entry->getTitle())) {
393 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
396 $em = $this->getDoctrine()->getManager();
397 $em->persist($entry);
400 // entry saved, dispatch event about it!
401 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
403 return $this->sendResponse($entry);
407 * Change several properties of an entry.
411 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
414 * {"name"="title", "dataType"="string", "required"=false},
415 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
416 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
417 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
418 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
419 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
420 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
421 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
422 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
423 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
424 * {"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)."},
428 * @return JsonResponse
430 public function patchEntriesAction(Entry
$entry, Request
$request)
432 $this->validateAuthentication();
433 $this->validateUserAccess($entry->getUser()->getId());
435 $contentProxy = $this->get('wallabag_core.content_proxy');
437 $data = $this->retrieveValueFromRequest($request);
439 // this is a special case where user want to manually update the entry content
440 // the ContentProxy will only cleanup the html
441 // and also we force to not re-fetch the content in case of error
442 if (!empty($data['content'])) {
444 $contentProxy->updateEntry(
448 'html' => $data['content'],
452 } catch (\Exception
$e) {
453 $this->get('logger')->error('Error while saving an entry', [
460 if (!empty($data['title'])) {
461 $entry->setTitle($data['title']);
464 if (!empty($data['language'])) {
465 $contentProxy->updateLanguage($entry, $data['language']);
468 if (!empty($data['authors']) && \
is_string($data['authors'])) {
469 $entry->setPublishedBy(explode(',', $data['authors']));
472 if (!empty($data['picture'])) {
473 $contentProxy->updatePreviewPicture($entry, $data['picture']);
476 if (!empty($data['publishedAt'])) {
477 $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
480 if (null !== $data['isArchived']) {
481 $entry->updateArchived((bool) $data['isArchived']);
484 if (null !== $data['isStarred']) {
485 $entry->updateStar((bool) $data['isStarred']);
488 if (!empty($data['tags'])) {
489 $entry->removeAllTags();
490 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
493 if (null !== $data['isPublic']) {
494 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
495 $entry->generateUid();
496 } elseif (false === (bool) $data['isPublic']) {
501 if (!empty($data['origin_url'])) {
502 $entry->setOriginUrl($data['origin_url']);
505 if (empty($entry->getDomainName())) {
506 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
509 if (empty($entry->getTitle())) {
510 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
513 $em = $this->getDoctrine()->getManager();
514 $em->persist($entry);
517 // entry saved, dispatch event about it!
518 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
520 return $this->sendResponse($entry);
525 * 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).
529 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
533 * @return JsonResponse
535 public function patchEntriesReloadAction(Entry
$entry)
537 $this->validateAuthentication();
538 $this->validateUserAccess($entry->getUser()->getId());
541 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
542 } catch (\Exception
$e) {
543 $this->get('logger')->error('Error while saving an entry', [
548 return new JsonResponse([], 304);
551 // if refreshing entry failed, don't save it
552 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
553 return new JsonResponse([], 304);
556 $em = $this->getDoctrine()->getManager();
557 $em->persist($entry);
560 // entry saved, dispatch event about it!
561 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
563 return $this->sendResponse($entry);
567 * Delete **permanently** an entry.
571 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
575 * @return JsonResponse
577 public function deleteEntriesAction(Entry
$entry)
579 $this->validateAuthentication();
580 $this->validateUserAccess($entry->getUser()->getId());
582 // We copy $entry to keep id in returned object
585 $em = $this->getDoctrine()->getManager();
589 // entry deleted, dispatch event about it!
590 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
592 return $this->sendResponse($e);
596 * Retrieve all tags for an entry.
600 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
604 * @return JsonResponse
606 public function getEntriesTagsAction(Entry
$entry)
608 $this->validateAuthentication();
609 $this->validateUserAccess($entry->getUser()->getId());
611 return $this->sendResponse($entry->getTags());
615 * Add one or more tags to an entry.
619 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
622 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
626 * @return JsonResponse
628 public function postEntriesTagsAction(Request
$request, Entry
$entry)
630 $this->validateAuthentication();
631 $this->validateUserAccess($entry->getUser()->getId());
633 $tags = $request->request
->get('tags', '');
635 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
638 $em = $this->getDoctrine()->getManager();
639 $em->persist($entry);
642 return $this->sendResponse($entry);
646 * Permanently remove one tag for an entry.
650 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
651 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
655 * @return JsonResponse
657 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
659 $this->validateAuthentication();
660 $this->validateUserAccess($entry->getUser()->getId());
662 $entry->removeTag($tag);
663 $em = $this->getDoctrine()->getManager();
664 $em->persist($entry);
667 return $this->sendResponse($entry);
671 * Handles an entries list delete tags from them.
675 * {"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."}
679 * @return JsonResponse
681 public function deleteEntriesTagsListAction(Request
$request)
683 $this->validateAuthentication();
685 $list = json_decode($request->query
->get('list', []));
688 return $this->sendResponse([]);
691 // handle multiple urls
694 foreach ($list as $key => $element) {
695 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
697 $this->getUser()->getId()
700 $results[$key]['url'] = $element->url
;
701 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
703 $tags = $element->tags
;
705 if (false !== $entry && !(empty($tags))) {
706 $tags = explode(',', $tags);
707 foreach ($tags as $label) {
708 $label = trim($label);
710 $tag = $this->getDoctrine()
711 ->getRepository('WallabagCoreBundle:Tag')
712 ->findOneByLabel($label);
714 if (false !== $tag) {
715 $entry->removeTag($tag);
719 $em = $this->getDoctrine()->getManager();
720 $em->persist($entry);
725 return $this->sendResponse($results);
729 * Handles an entries list and add tags to them.
733 * {"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."}
737 * @return JsonResponse
739 public function postEntriesTagsListAction(Request
$request)
741 $this->validateAuthentication();
743 $list = json_decode($request->query
->get('list', []));
746 return $this->sendResponse([]);
751 // handle multiple urls
752 foreach ($list as $key => $element) {
753 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
755 $this->getUser()->getId()
758 $results[$key]['url'] = $element->url
;
759 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
761 $tags = $element->tags
;
763 if (false !== $entry && !(empty($tags))) {
764 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
766 $em = $this->getDoctrine()->getManager();
767 $em->persist($entry);
772 return $this->sendResponse($results);
776 * Retrieve value from the request.
777 * Used for POST & PATCH on a an entry.
779 * @param Request $request
783 private function retrieveValueFromRequest(Request
$request)
786 'title' => $request->request
->get('title'),
787 'tags' => $request->request
->get('tags', []),
788 'isArchived' => $request->request
->get('archive'),
789 'isStarred' => $request->request
->get('starred'),
790 'isPublic' => $request->request
->get('public'),
791 'content' => $request->request
->get('content'),
792 'language' => $request->request
->get('language'),
793 'picture' => $request->request
->get('preview_picture'),
794 'publishedAt' => $request->request
->get('published_at'),
795 'authors' => $request->request
->get('authors', ''),
796 'origin_url' => $request->request
->get('origin_url', ''),
801 * Return information about the entry if it exist and depending on the id or not.
803 * @param Entry|null $entry
804 * @param bool $returnId
808 private function returnExistInformation($entry, $returnId)
811 return $entry instanceof Entry
? $entry->getId() : null;
814 return $entry instanceof Entry
;