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\HttpKernel\Exception\HttpException
;
9 use Symfony\Component\HttpFoundation\Request
;
10 use Symfony\Component\HttpFoundation\JsonResponse
;
11 use Symfony\Component\Routing\Generator\UrlGeneratorInterface
;
12 use Wallabag\CoreBundle\Entity\Entry
;
13 use Wallabag\CoreBundle\Entity\Tag
;
14 use Wallabag\CoreBundle\Event\EntrySavedEvent
;
15 use Wallabag\CoreBundle\Event\EntryDeletedEvent
;
17 class EntryRestController
extends WallabagRestController
20 * Check if an entry exist by url.
24 * {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
25 * {"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"}
29 * @return JsonResponse
31 public function getEntriesExistsAction(Request
$request)
33 $this->validateAuthentication();
35 $urls = $request->query
->get('urls', []);
37 // handle multiple urls first
40 foreach ($urls as $url) {
41 $res = $this->getDoctrine()
42 ->getRepository('WallabagCoreBundle:Entry')
43 ->findByUrlAndUserId($url, $this->getUser()->getId());
45 $results[$url] = $res instanceof Entry
? $res->getId() : false;
48 return $this->sendResponse($results);
51 // let's see if it is a simple url?
52 $url = $request->query
->get('url', '');
55 throw $this->createAccessDeniedException('URL is empty?, logged user id: '.$this->getUser()->getId());
58 $res = $this->getDoctrine()
59 ->getRepository('WallabagCoreBundle:Entry')
60 ->findByUrlAndUserId($url, $this->getUser()->getId());
62 $exists = $res instanceof Entry
? $res->getId() : false;
64 return $this->sendResponse(['exists' => $exists]);
68 * Retrieve all entries. It could be filtered by many options.
72 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
73 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
74 * {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
75 * {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
76 * {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
77 * {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
78 * {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
79 * {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
83 * @return JsonResponse
85 public function getEntriesAction(Request
$request)
87 $this->validateAuthentication();
89 $isArchived = (null === $request->query
->get('archive')) ? null : (bool) $request->query
->get('archive');
90 $isStarred = (null === $request->query
->get('starred')) ? null : (bool) $request->query
->get('starred');
91 $sort = $request->query
->get('sort', 'created');
92 $order = $request->query
->get('order', 'desc');
93 $page = (int) $request->query
->get('page', 1);
94 $perPage = (int) $request->query
->get('perPage', 30);
95 $tags = $request->query
->get('tags', '');
96 $since = $request->query
->get('since', 0);
98 /** @var \Pagerfanta\Pagerfanta $pager */
99 $pager = $this->getDoctrine()
100 ->getRepository('WallabagCoreBundle:Entry')
101 ->findEntries($this->getUser()->getId(), $isArchived, $isStarred, $sort, $order, $since, $tags);
103 $pager->setMaxPerPage($perPage);
104 $pager->setCurrentPage($page);
106 $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
107 $paginatedCollection = $pagerfantaFactory->createRepresentation(
112 'archive' => $isArchived,
113 'starred' => $isStarred,
117 'perPage' => $perPage,
121 UrlGeneratorInterface
::ABSOLUTE_URL
125 return $this->sendResponse($paginatedCollection);
129 * Retrieve a single entry.
133 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
137 * @return JsonResponse
139 public function getEntryAction(Entry
$entry)
141 $this->validateAuthentication();
142 $this->validateUserAccess($entry->getUser()->getId());
144 return $this->sendResponse($entry);
148 * Retrieve a single entry as a predefined format.
152 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
158 public function getEntryExportAction(Entry
$entry, Request
$request)
160 $this->validateAuthentication();
161 $this->validateUserAccess($entry->getUser()->getId());
163 return $this->get('wallabag_core.helper.entries_export')
165 ->updateTitle('entry')
166 ->exportAs($request->attributes
->get('_format'));
170 * Handles an entries list and delete URL.
174 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
178 * @return JsonResponse
180 public function deleteEntriesListAction(Request
$request)
182 $this->validateAuthentication();
184 $urls = json_decode($request->query
->get('urls', []));
187 return $this->sendResponse([]);
192 // handle multiple urls
193 foreach ($urls as $key => $url) {
194 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
196 $this->getUser()->getId()
199 $results[$key]['url'] = $url;
201 if (false !== $entry) {
202 $em = $this->getDoctrine()->getManager();
206 // entry deleted, dispatch event about it!
207 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
210 $results[$key]['entry'] = $entry instanceof Entry
? true : false;
213 return $this->sendResponse($results);
217 * Handles an entries list and create URL.
221 * {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
225 * @return JsonResponse
227 * @throws HttpException When limit is reached
229 public function postEntriesListAction(Request
$request)
231 $this->validateAuthentication();
233 $urls = json_decode($request->query
->get('urls', []));
235 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
237 if (count($urls) > $limit) {
238 throw new HttpException(400, 'API limit reached');
243 return $this->sendResponse($results);
246 // handle multiple urls
247 foreach ($urls as $key => $url) {
248 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
250 $this->getUser()->getId()
253 $results[$key]['url'] = $url;
255 if (false === $entry) {
256 $entry = new Entry($this->getUser());
258 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
261 $em = $this->getDoctrine()->getManager();
262 $em->persist($entry);
265 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
267 // entry saved, dispatch event about it!
268 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
271 return $this->sendResponse($results);
277 * 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**.
278 * Otherwise, content will be fetched as normal from the url and values will be overwritten.
282 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
283 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
284 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
285 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
286 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
287 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
288 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
289 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
290 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
291 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
295 * @return JsonResponse
297 public function postEntriesAction(Request
$request)
299 $this->validateAuthentication();
301 $url = $request->request
->get('url');
302 $title = $request->request
->get('title');
303 $tags = $request->request
->get('tags', []);
304 $isArchived = $request->request
->get('archive');
305 $isStarred = $request->request
->get('starred');
306 $content = $request->request
->get('content');
307 $language = $request->request
->get('language');
308 $picture = $request->request
->get('preview_picture');
309 $publishedAt = $request->request
->get('published_at');
310 $authors = $request->request
->get('authors', '');
312 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId());
314 if (false === $entry) {
315 $entry = new Entry($this->getUser());
319 $this->get('wallabag_core.content_proxy')->updateEntry(
326 'language' => $language,
327 'date' => $publishedAt,
328 // faking the preview picture
330 'og_image' => $picture,
332 'authors' => explode(',', $authors),
335 } catch (\Exception
$e) {
336 $this->get('logger')->error('Error while saving an entry', [
340 $entry->setUrl($url);
344 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
347 if (!is_null($isStarred)) {
348 $entry->setStarred((bool) $isStarred);
351 if (!is_null($isArchived)) {
352 $entry->setArchived((bool) $isArchived);
355 $em = $this->getDoctrine()->getManager();
356 $em->persist($entry);
359 // entry saved, dispatch event about it!
360 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
362 return $this->sendResponse($entry);
366 * Change several properties of an entry.
370 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
373 * {"name"="title", "dataType"="string", "required"=false},
374 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
375 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
376 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
377 * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
378 * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
379 * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
380 * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
381 * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
385 * @return JsonResponse
387 public function patchEntriesAction(Entry
$entry, Request
$request)
389 $this->validateAuthentication();
390 $this->validateUserAccess($entry->getUser()->getId());
392 $title = $request->request
->get('title');
393 $tags = $request->request
->get('tags', '');
394 $isArchived = $request->request
->get('archive');
395 $isStarred = $request->request
->get('starred');
396 $content = $request->request
->get('content');
397 $language = $request->request
->get('language');
398 $picture = $request->request
->get('preview_picture');
399 $publishedAt = $request->request
->get('published_at');
400 $authors = $request->request
->get('authors', '');
403 $this->get('wallabag_core.content_proxy')->updateEntry(
407 'title' => !empty($title) ? $title : $entry->getTitle(),
408 'html' => !empty($content) ? $content : $entry->getContent(),
409 'url' => $entry->getUrl(),
410 'language' => $language,
411 'date' => $publishedAt,
412 // faking the preview picture
414 'og_image' => $picture,
416 'authors' => is_string($authors) ? explode(',', $authors) : [],
418 // we don't want the content to be update by fetching the url
421 } catch (\Exception
$e) {
422 $this->get('logger')->error('Error while saving an entry', [
428 if (!is_null($isArchived)) {
429 $entry->setArchived((bool) $isArchived);
432 if (!is_null($isStarred)) {
433 $entry->setStarred((bool) $isStarred);
437 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
440 $em = $this->getDoctrine()->getManager();
443 return $this->sendResponse($entry);
448 * 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).
452 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
456 * @return JsonResponse
458 public function patchEntriesReloadAction(Entry
$entry)
460 $this->validateAuthentication();
461 $this->validateUserAccess($entry->getUser()->getId());
464 $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
465 } catch (\Exception
$e) {
466 $this->get('logger')->error('Error while saving an entry', [
471 return new JsonResponse([], 304);
474 // if refreshing entry failed, don't save it
475 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
476 return new JsonResponse([], 304);
479 $em = $this->getDoctrine()->getManager();
480 $em->persist($entry);
483 // entry saved, dispatch event about it!
484 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
486 return $this->sendResponse($entry);
490 * Delete **permanently** an entry.
494 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
498 * @return JsonResponse
500 public function deleteEntriesAction(Entry
$entry)
502 $this->validateAuthentication();
503 $this->validateUserAccess($entry->getUser()->getId());
505 $em = $this->getDoctrine()->getManager();
509 // entry deleted, dispatch event about it!
510 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
512 return $this->sendResponse($entry);
516 * Retrieve all tags for an entry.
520 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
524 * @return JsonResponse
526 public function getEntriesTagsAction(Entry
$entry)
528 $this->validateAuthentication();
529 $this->validateUserAccess($entry->getUser()->getId());
531 return $this->sendResponse($entry->getTags());
535 * Add one or more tags to an entry.
539 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
542 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
546 * @return JsonResponse
548 public function postEntriesTagsAction(Request
$request, Entry
$entry)
550 $this->validateAuthentication();
551 $this->validateUserAccess($entry->getUser()->getId());
553 $tags = $request->request
->get('tags', '');
555 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
558 $em = $this->getDoctrine()->getManager();
559 $em->persist($entry);
562 return $this->sendResponse($entry);
566 * Permanently remove one tag for an entry.
570 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
571 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
575 * @return JsonResponse
577 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
579 $this->validateAuthentication();
580 $this->validateUserAccess($entry->getUser()->getId());
582 $entry->removeTag($tag);
583 $em = $this->getDoctrine()->getManager();
584 $em->persist($entry);
587 return $this->sendResponse($entry);
591 * Handles an entries list delete tags from them.
595 * {"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."}
599 * @return JsonResponse
601 public function deleteEntriesTagsListAction(Request
$request)
603 $this->validateAuthentication();
605 $list = json_decode($request->query
->get('list', []));
608 return $this->sendResponse([]);
611 // handle multiple urls
614 foreach ($list as $key => $element) {
615 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
617 $this->getUser()->getId()
620 $results[$key]['url'] = $element->url
;
621 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
623 $tags = $element->tags
;
625 if (false !== $entry && !(empty($tags))) {
626 $tags = explode(',', $tags);
627 foreach ($tags as $label) {
628 $label = trim($label);
630 $tag = $this->getDoctrine()
631 ->getRepository('WallabagCoreBundle:Tag')
632 ->findOneByLabel($label);
634 if (false !== $tag) {
635 $entry->removeTag($tag);
639 $em = $this->getDoctrine()->getManager();
640 $em->persist($entry);
645 return $this->sendResponse($results);
649 * Handles an entries list and add tags to them.
653 * {"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."}
657 * @return JsonResponse
659 public function postEntriesTagsListAction(Request
$request)
661 $this->validateAuthentication();
663 $list = json_decode($request->query
->get('list', []));
666 return $this->sendResponse([]);
671 // handle multiple urls
672 foreach ($list as $key => $element) {
673 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
675 $this->getUser()->getId()
678 $results[$key]['url'] = $element->url
;
679 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
681 $tags = $element->tags
;
683 if (false !== $entry && !(empty($tags))) {
684 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
686 $em = $this->getDoctrine()->getManager();
687 $em->persist($entry);
692 return $this->sendResponse($results);
696 * Shortcut to send data serialized in json.
700 * @return JsonResponse
702 private function sendResponse($data)
704 $json = $this->get('serializer')->serialize($data, 'json');
706 return (new JsonResponse())->setJson($json);