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 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' or 'archived', 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 = strtolower($request->query
->get('sort', 'created'));
101 $order = strtolower($request->query
->get('order', 'desc'));
102 $page = (int) $request->query
->get('page', 1);
103 $perPage = (int) $request->query
->get('perPage', 30);
104 $tags = \
is_array($request->query
->get('tags')) ? '' : (string) $request->query
->get('tags', '');
105 $since = $request->query
->get('since', 0);
108 /** @var \Pagerfanta\Pagerfanta $pager */
109 $pager = $this->get('wallabag_core.entry_repository')->findEntries(
110 $this->getUser()->getId(),
119 } catch (\Exception
$e) {
120 throw new BadRequestHttpException($e->getMessage());
123 $pager->setMaxPerPage($perPage);
124 $pager->setCurrentPage($page);
126 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
127 $paginatedCollection = $pagerfantaFactory->createRepresentation(
132 'archive' => $isArchived,
133 'starred' => $isStarred,
134 'public' => $isPublic,
138 'perPage' => $perPage,
146 return $this->sendResponse($paginatedCollection);
150 * Retrieve a single entry.
154 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
158 * @return JsonResponse
160 public function getEntryAction(Entry
$entry)
162 $this->validateAuthentication();
163 $this->validateUserAccess($entry->getUser()->getId());
165 return $this->sendResponse($entry);
169 * Retrieve a single entry as a predefined format.
173 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
179 public function getEntryExportAction(Entry
$entry, Request
$request)
181 $this->validateAuthentication();
182 $this->validateUserAccess($entry->getUser()->getId());
184 return $this->get('wallabag_core.helper.entries_export')
186 ->updateTitle('entry')
187 ->updateAuthor('entry')
188 ->exportAs($request->attributes
->get('_format'));
192 * Handles an entries list and delete URL.
196 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
200 * @return JsonResponse
202 public function deleteEntriesListAction(Request
$request)
204 $this->validateAuthentication();
206 $urls = json_decode($request->query
->get('urls', []));
209 return $this->sendResponse([]);
214 // handle multiple urls
215 foreach ($urls as $key => $url) {
216 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
218 $this->getUser()->getId()
221 $results[$key]['url'] = $url;
223 if (false !== $entry) {
224 $em = $this->getDoctrine()->getManager();
228 // entry deleted, dispatch event about it!
229 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
232 $results[$key]['entry'] = $entry instanceof Entry
? true : false;
235 return $this->sendResponse($results);
239 * Handles an entries list and create URL.
243 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
247 * @throws HttpException When limit is reached
249 * @return JsonResponse
251 public function postEntriesListAction(Request
$request)
253 $this->validateAuthentication();
255 $urls = json_decode($request->query
->get('urls', []));
257 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
259 if (\
count($urls) > $limit) {
260 throw new HttpException(400, 'API limit reached');
265 return $this->sendResponse($results);
268 // handle multiple urls
269 foreach ($urls as $key => $url) {
270 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
272 $this->getUser()->getId()
275 $results[$key]['url'] = $url;
277 if (false === $entry) {
278 $entry = new Entry($this->getUser());
280 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
283 $em = $this->getDoctrine()->getManager();
284 $em->persist($entry);
287 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
289 // entry saved, dispatch event about it!
290 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
293 return $this->sendResponse($results);
299 * 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**.
300 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
304 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
305 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
306 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
307 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
308 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
309 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
310 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
311 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
312 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
313 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
314 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
315 * {"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)."},
319 * @return JsonResponse
321 public function postEntriesAction(Request
$request)
323 $this->validateAuthentication();
325 $url = $request->request
->get('url');
327 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
329 $this->getUser()->getId()
332 if (false === $entry) {
333 $entry = new Entry($this->getUser());
334 $entry->setUrl($url);
337 $data = $this->retrieveValueFromRequest($request);
340 $this->get('wallabag_core.content_proxy')->updateEntry(
344 'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
345 'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
346 'url' => $entry->getUrl(),
347 'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
348 'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
349 // faking the open graph preview picture
351 'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
353 'authors' => \
is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
356 } catch (\Exception
$e) {
357 $this->get('logger')->error('Error while saving an entry', [
363 if (null !== $data['isArchived']) {
364 $entry->updateArchived((bool) $data['isArchived']);
367 if (null !== $data['isStarred']) {
368 $entry->updateStar((bool) $data['isStarred']);
371 if (!empty($data['tags'])) {
372 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
375 if (!empty($data['origin_url'])) {
376 $entry->setOriginUrl($data['origin_url']);
379 if (null !== $data['isPublic']) {
380 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
381 $entry->generateUid();
382 } elseif (false === (bool) $data['isPublic']) {
387 if (empty($entry->getDomainName())) {
388 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
391 if (empty($entry->getTitle())) {
392 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
395 $em = $this->getDoctrine()->getManager();
396 $em->persist($entry);
399 // entry saved, dispatch event about it!
400 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
402 return $this->sendResponse($entry);
406 * Change several properties of an entry.
410 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
413 * {"name"="title", "dataType"="string", "required"=false},
414 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
415 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
416 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
417 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
418 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
419 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
420 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
421 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
422 * {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
423 * {"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)."},
427 * @return JsonResponse
429 public function patchEntriesAction(Entry
$entry, Request
$request)
431 $this->validateAuthentication();
432 $this->validateUserAccess($entry->getUser()->getId());
434 $contentProxy = $this->get('wallabag_core.content_proxy');
436 $data = $this->retrieveValueFromRequest($request);
438 // this is a special case where user want to manually update the entry content
439 // the ContentProxy will only cleanup the html
440 // and also we force to not re-fetch the content in case of error
441 if (!empty($data['content'])) {
443 $contentProxy->updateEntry(
447 'html' => $data['content'],
451 } catch (\Exception
$e) {
452 $this->get('logger')->error('Error while saving an entry', [
459 if (!empty($data['title'])) {
460 $entry->setTitle($data['title']);
463 if (!empty($data['language'])) {
464 $contentProxy->updateLanguage($entry, $data['language']);
467 if (!empty($data['authors']) && \
is_string($data['authors'])) {
468 $entry->setPublishedBy(explode(',', $data['authors']));
471 if (!empty($data['picture'])) {
472 $contentProxy->updatePreviewPicture($entry, $data['picture']);
475 if (!empty($data['publishedAt'])) {
476 $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
479 if (null !== $data['isArchived']) {
480 $entry->updateArchived((bool) $data['isArchived']);
483 if (null !== $data['isStarred']) {
484 $entry->updateStar((bool) $data['isStarred']);
487 if (!empty($data['tags'])) {
488 $entry->removeAllTags();
489 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
492 if (null !== $data['isPublic']) {
493 if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
494 $entry->generateUid();
495 } elseif (false === (bool) $data['isPublic']) {
500 if (!empty($data['origin_url'])) {
501 $entry->setOriginUrl($data['origin_url']);
504 if (empty($entry->getDomainName())) {
505 $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
508 if (empty($entry->getTitle())) {
509 $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
512 $em = $this->getDoctrine()->getManager();
513 $em->persist($entry);
516 // entry saved, dispatch event about it!
517 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
519 return $this->sendResponse($entry);
524 * 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).
528 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
532 * @return JsonResponse
534 public function patchEntriesReloadAction(Entry
$entry)
536 $this->validateAuthentication();
537 $this->validateUserAccess($entry->getUser()->getId());
540 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
541 } catch (\Exception
$e) {
542 $this->get('logger')->error('Error while saving an entry', [
547 return new JsonResponse([], 304);
550 // if refreshing entry failed, don't save it
551 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
552 return new JsonResponse([], 304);
555 $em = $this->getDoctrine()->getManager();
556 $em->persist($entry);
559 // entry saved, dispatch event about it!
560 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
562 return $this->sendResponse($entry);
566 * Delete **permanently** an entry.
570 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
574 * @return JsonResponse
576 public function deleteEntriesAction(Entry
$entry)
578 $this->validateAuthentication();
579 $this->validateUserAccess($entry->getUser()->getId());
581 // We copy $entry to keep id in returned object
584 $em = $this->getDoctrine()->getManager();
588 // entry deleted, dispatch event about it!
589 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
591 return $this->sendResponse($e);
595 * Retrieve all tags for an entry.
599 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
603 * @return JsonResponse
605 public function getEntriesTagsAction(Entry
$entry)
607 $this->validateAuthentication();
608 $this->validateUserAccess($entry->getUser()->getId());
610 return $this->sendResponse($entry->getTags());
614 * Add one or more tags to an entry.
618 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
621 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
625 * @return JsonResponse
627 public function postEntriesTagsAction(Request
$request, Entry
$entry)
629 $this->validateAuthentication();
630 $this->validateUserAccess($entry->getUser()->getId());
632 $tags = $request->request
->get('tags', '');
634 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
637 $em = $this->getDoctrine()->getManager();
638 $em->persist($entry);
641 return $this->sendResponse($entry);
645 * Permanently remove one tag for an entry.
649 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
650 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
654 * @return JsonResponse
656 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
658 $this->validateAuthentication();
659 $this->validateUserAccess($entry->getUser()->getId());
661 $entry->removeTag($tag);
662 $em = $this->getDoctrine()->getManager();
663 $em->persist($entry);
666 return $this->sendResponse($entry);
670 * Handles an entries list delete tags from them.
674 * {"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."}
678 * @return JsonResponse
680 public function deleteEntriesTagsListAction(Request
$request)
682 $this->validateAuthentication();
684 $list = json_decode($request->query
->get('list', []));
687 return $this->sendResponse([]);
690 // handle multiple urls
693 foreach ($list as $key => $element) {
694 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
696 $this->getUser()->getId()
699 $results[$key]['url'] = $element->url
;
700 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
702 $tags = $element->tags
;
704 if (false !== $entry && !(empty($tags))) {
705 $tags = explode(',', $tags);
706 foreach ($tags as $label) {
707 $label = trim($label);
709 $tag = $this->getDoctrine()
710 ->getRepository('WallabagCoreBundle:Tag')
711 ->findOneByLabel($label);
713 if (false !== $tag) {
714 $entry->removeTag($tag);
718 $em = $this->getDoctrine()->getManager();
719 $em->persist($entry);
724 return $this->sendResponse($results);
728 * Handles an entries list and add tags to them.
732 * {"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."}
736 * @return JsonResponse
738 public function postEntriesTagsListAction(Request
$request)
740 $this->validateAuthentication();
742 $list = json_decode($request->query
->get('list', []));
745 return $this->sendResponse([]);
750 // handle multiple urls
751 foreach ($list as $key => $element) {
752 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
754 $this->getUser()->getId()
757 $results[$key]['url'] = $element->url
;
758 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
760 $tags = $element->tags
;
762 if (false !== $entry && !(empty($tags))) {
763 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
765 $em = $this->getDoctrine()->getManager();
766 $em->persist($entry);
771 return $this->sendResponse($results);
775 * Retrieve value from the request.
776 * Used for POST & PATCH on a an entry.
778 * @param Request $request
782 private function retrieveValueFromRequest(Request
$request)
785 'title' => $request->request
->get('title'),
786 'tags' => $request->request
->get('tags', []),
787 'isArchived' => $request->request
->get('archive'),
788 'isStarred' => $request->request
->get('starred'),
789 'isPublic' => $request->request
->get('public'),
790 'content' => $request->request
->get('content'),
791 'language' => $request->request
->get('language'),
792 'picture' => $request->request
->get('preview_picture'),
793 'publishedAt' => $request->request
->get('published_at'),
794 'authors' => $request->request
->get('authors', ''),
795 'origin_url' => $request->request
->get('origin_url', ''),
800 * Return information about the entry if it exist and depending on the id or not.
802 * @param Entry|null $entry
803 * @param bool $returnId
807 private function returnExistInformation($entry, $returnId)
810 return $entry instanceof Entry
? $entry->getId() : null;
813 return $entry instanceof Entry
;