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', []));
236 $limit = $this->container
->getParameter('wallabag_core.api_limit_mass_actions');
238 if (count($urls) > $limit) {
239 throw new HttpException(400, 'API limit reached');
242 // handle multiple urls
244 foreach ($urls as $key => $url) {
245 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
247 $this->getUser()->getId()
250 $results[$key]['url'] = $url;
252 if (false === $entry) {
253 $entry = $this->get('wallabag_core.content_proxy')->updateEntry(
254 new Entry($this->getUser()),
259 $em = $this->getDoctrine()->getManager();
260 $em->persist($entry);
263 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
265 // entry saved, dispatch event about it!
266 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
270 return $this->sendResponse($results);
278 * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
279 * {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
280 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
281 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
282 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
286 * @return JsonResponse
288 public function postEntriesAction(Request
$request)
290 $this->validateAuthentication();
292 $url = $request->request
->get('url');
293 $title = $request->request
->get('title');
294 $isArchived = $request->request
->get('archive');
295 $isStarred = $request->request
->get('starred');
297 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId());
299 if (false === $entry) {
300 $entry = new Entry($this->getUser());
302 $entry = $this->get('wallabag_core.content_proxy')->updateEntry(
306 } catch (\Exception
$e) {
307 $this->get('logger')->error('Error while saving an entry', [
311 $entry->setUrl($url);
315 if (!is_null($title)) {
316 $entry->setTitle($title);
319 $tags = $request->request
->get('tags', '');
321 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
324 if (!is_null($isStarred)) {
325 $entry->setStarred((bool) $isStarred);
328 if (!is_null($isArchived)) {
329 $entry->setArchived((bool) $isArchived);
332 $em = $this->getDoctrine()->getManager();
333 $em->persist($entry);
336 // entry saved, dispatch event about it!
337 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
339 return $this->sendResponse($entry);
343 * Change several properties of an entry.
347 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
350 * {"name"="title", "dataType"="string", "required"=false},
351 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
352 * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
353 * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
357 * @return JsonResponse
359 public function patchEntriesAction(Entry
$entry, Request
$request)
361 $this->validateAuthentication();
362 $this->validateUserAccess($entry->getUser()->getId());
364 $title = $request->request
->get('title');
365 $isArchived = $request->request
->get('archive');
366 $isStarred = $request->request
->get('starred');
368 if (!is_null($title)) {
369 $entry->setTitle($title);
372 if (!is_null($isArchived)) {
373 $entry->setArchived((bool) $isArchived);
376 if (!is_null($isStarred)) {
377 $entry->setStarred((bool) $isStarred);
380 $tags = $request->request
->get('tags', '');
382 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
385 $em = $this->getDoctrine()->getManager();
388 return $this->sendResponse($entry);
393 * 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).
397 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
401 * @return JsonResponse
403 public function patchEntriesReloadAction(Entry
$entry)
405 $this->validateAuthentication();
406 $this->validateUserAccess($entry->getUser()->getId());
409 $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
410 } catch (\Exception
$e) {
411 $this->get('logger')->error('Error while saving an entry', [
416 return new JsonResponse([], 304);
419 // if refreshing entry failed, don't save it
420 if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
421 return new JsonResponse([], 304);
424 $em = $this->getDoctrine()->getManager();
425 $em->persist($entry);
428 // entry saved, dispatch event about it!
429 $this->get('event_dispatcher')->dispatch(EntrySavedEvent
::NAME
, new EntrySavedEvent($entry));
431 return $this->sendResponse($entry);
435 * Delete **permanently** an entry.
439 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
443 * @return JsonResponse
445 public function deleteEntriesAction(Entry
$entry)
447 $this->validateAuthentication();
448 $this->validateUserAccess($entry->getUser()->getId());
450 $em = $this->getDoctrine()->getManager();
454 // entry deleted, dispatch event about it!
455 $this->get('event_dispatcher')->dispatch(EntryDeletedEvent
::NAME
, new EntryDeletedEvent($entry));
457 return $this->sendResponse($entry);
461 * Retrieve all tags for an entry.
465 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
469 * @return JsonResponse
471 public function getEntriesTagsAction(Entry
$entry)
473 $this->validateAuthentication();
474 $this->validateUserAccess($entry->getUser()->getId());
476 return $this->sendResponse($entry->getTags());
480 * Add one or more tags to an entry.
484 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
487 * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
491 * @return JsonResponse
493 public function postEntriesTagsAction(Request
$request, Entry
$entry)
495 $this->validateAuthentication();
496 $this->validateUserAccess($entry->getUser()->getId());
498 $tags = $request->request
->get('tags', '');
500 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
503 $em = $this->getDoctrine()->getManager();
504 $em->persist($entry);
507 return $this->sendResponse($entry);
511 * Permanently remove one tag for an entry.
515 * {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
516 * {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
520 * @return JsonResponse
522 public function deleteEntriesTagsAction(Entry
$entry, Tag
$tag)
524 $this->validateAuthentication();
525 $this->validateUserAccess($entry->getUser()->getId());
527 $entry->removeTag($tag);
528 $em = $this->getDoctrine()->getManager();
529 $em->persist($entry);
532 return $this->sendResponse($entry);
536 * Handles an entries list delete tags from them.
540 * {"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."}
544 * @return JsonResponse
546 public function deleteEntriesTagsListAction(Request
$request)
548 $this->validateAuthentication();
550 $list = json_decode($request->query
->get('list', []));
553 return $this->sendResponse([]);
556 // handle multiple urls
559 foreach ($list as $key => $element) {
560 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
562 $this->getUser()->getId()
565 $results[$key]['url'] = $element->url
;
566 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
568 $tags = $element->tags
;
570 if (false !== $entry && !(empty($tags))) {
571 $tags = explode(',', $tags);
572 foreach ($tags as $label) {
573 $label = trim($label);
575 $tag = $this->getDoctrine()
576 ->getRepository('WallabagCoreBundle:Tag')
577 ->findOneByLabel($label);
579 if (false !== $tag) {
580 $entry->removeTag($tag);
584 $em = $this->getDoctrine()->getManager();
585 $em->persist($entry);
590 return $this->sendResponse($results);
594 * Handles an entries list and add tags to them.
598 * {"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."}
602 * @return JsonResponse
604 public function postEntriesTagsListAction(Request
$request)
606 $this->validateAuthentication();
608 $list = json_decode($request->query
->get('list', []));
611 return $this->sendResponse([]);
616 // handle multiple urls
617 foreach ($list as $key => $element) {
618 $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
620 $this->getUser()->getId()
623 $results[$key]['url'] = $element->url
;
624 $results[$key]['entry'] = $entry instanceof Entry
? $entry->getId() : false;
626 $tags = $element->tags
;
628 if (false !== $entry && !(empty($tags))) {
629 $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
631 $em = $this->getDoctrine()->getManager();
632 $em->persist($entry);
637 return $this->sendResponse($results);
641 * Shortcut to send data serialized in json.
645 * @return JsonResponse
647 private function sendResponse($data)
649 $json = $this->get('serializer')->serialize($data, 'json');
651 return (new JsonResponse())->setJson($json);