]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - src/Wallabag/ApiBundle/Controller/EntryRestController.php
Merge pull request #2751 from bdunogier/2.2-guzzle_subscribers_improvement
[github/wallabag/wallabag.git] / src / Wallabag / ApiBundle / Controller / EntryRestController.php
index 24fa7b3bdaadbe0944f883878ba8358574824349..632b16d904d898a59b1421d60c713ee75f3f7c96 100644 (file)
@@ -5,11 +5,14 @@ namespace Wallabag\ApiBundle\Controller;
 use Hateoas\Configuration\Route;
 use Hateoas\Representation\Factory\PagerfantaFactory;
 use Nelmio\ApiDocBundle\Annotation\ApiDoc;
+use Symfony\Component\HttpKernel\Exception\HttpException;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
 use Wallabag\CoreBundle\Entity\Entry;
 use Wallabag\CoreBundle\Entity\Tag;
+use Wallabag\CoreBundle\Event\EntrySavedEvent;
+use Wallabag\CoreBundle\Event\EntryDeletedEvent;
 
 class EntryRestController extends WallabagRestController
 {
@@ -39,12 +42,10 @@ class EntryRestController extends WallabagRestController
                     ->getRepository('WallabagCoreBundle:Entry')
                     ->findByUrlAndUserId($url, $this->getUser()->getId());
 
-                $results[$url] = false === $res ? false : true;
+                $results[$url] = $res instanceof Entry ? $res->getId() : false;
             }
 
-            $json = $this->get('serializer')->serialize($results, 'json');
-
-            return (new JsonResponse())->setJson($json);
+            return $this->sendResponse($results);
         }
 
         // let's see if it is a simple url?
@@ -58,11 +59,9 @@ class EntryRestController extends WallabagRestController
             ->getRepository('WallabagCoreBundle:Entry')
             ->findByUrlAndUserId($url, $this->getUser()->getId());
 
-        $exists = false === $res ? false : true;
-
-        $json = $this->get('serializer')->serialize(['exists' => $exists], 'json');
+        $exists = $res instanceof Entry ? $res->getId() : false;
 
-        return (new JsonResponse())->setJson($json);
+        return $this->sendResponse(['exists' => $exists]);
     }
 
     /**
@@ -96,12 +95,13 @@ class EntryRestController extends WallabagRestController
         $tags = $request->query->get('tags', '');
         $since = $request->query->get('since', 0);
 
+        /** @var \Pagerfanta\Pagerfanta $pager */
         $pager = $this->getDoctrine()
             ->getRepository('WallabagCoreBundle:Entry')
             ->findEntries($this->getUser()->getId(), $isArchived, $isStarred, $sort, $order, $since, $tags);
 
-        $pager->setCurrentPage($page);
         $pager->setMaxPerPage($perPage);
+        $pager->setCurrentPage($page);
 
         $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
         $paginatedCollection = $pagerfantaFactory->createRepresentation(
@@ -122,9 +122,7 @@ class EntryRestController extends WallabagRestController
             )
         );
 
-        $json = $this->get('serializer')->serialize($paginatedCollection, 'json');
-
-        return (new JsonResponse())->setJson($json);
+        return $this->sendResponse($paginatedCollection);
     }
 
     /**
@@ -143,9 +141,133 @@ class EntryRestController extends WallabagRestController
         $this->validateAuthentication();
         $this->validateUserAccess($entry->getUser()->getId());
 
-        $json = $this->get('serializer')->serialize($entry, 'json');
+        return $this->sendResponse($entry);
+    }
 
-        return (new JsonResponse())->setJson($json);
+    /**
+     * Retrieve a single entry as a predefined format.
+     *
+     * @ApiDoc(
+     *      requirements={
+     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
+     *      }
+     * )
+     *
+     * @return Response
+     */
+    public function getEntryExportAction(Entry $entry, Request $request)
+    {
+        $this->validateAuthentication();
+        $this->validateUserAccess($entry->getUser()->getId());
+
+        return $this->get('wallabag_core.helper.entries_export')
+            ->setEntries($entry)
+            ->updateTitle('entry')
+            ->exportAs($request->attributes->get('_format'));
+    }
+
+    /**
+     * Handles an entries list and delete URL.
+     *
+     * @ApiDoc(
+     *       parameters={
+     *          {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
+     *       }
+     * )
+     *
+     * @return JsonResponse
+     */
+    public function deleteEntriesListAction(Request $request)
+    {
+        $this->validateAuthentication();
+
+        $urls = json_decode($request->query->get('urls', []));
+
+        if (empty($urls)) {
+            return $this->sendResponse([]);
+        }
+
+        $results = [];
+
+        // handle multiple urls
+        foreach ($urls as $key => $url) {
+            $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
+                $url,
+                $this->getUser()->getId()
+            );
+
+            $results[$key]['url'] = $url;
+
+            if (false !== $entry) {
+                $em = $this->getDoctrine()->getManager();
+                $em->remove($entry);
+                $em->flush();
+
+                // entry deleted, dispatch event about it!
+                $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
+            }
+
+            $results[$key]['entry'] = $entry instanceof Entry ? true : false;
+        }
+
+        return $this->sendResponse($results);
+    }
+
+    /**
+     * Handles an entries list and create URL.
+     *
+     * @ApiDoc(
+     *       parameters={
+     *          {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
+     *       }
+     * )
+     *
+     * @return JsonResponse
+     *
+     * @throws HttpException When limit is reached
+     */
+    public function postEntriesListAction(Request $request)
+    {
+        $this->validateAuthentication();
+
+        $urls = json_decode($request->query->get('urls', []));
+        $results = [];
+
+        $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions');
+
+        if (count($urls) > $limit) {
+            throw new HttpException(400, 'API limit reached');
+        }
+
+        // handle multiple urls
+        if (!empty($urls)) {
+            foreach ($urls as $key => $url) {
+                $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
+                    $url,
+                    $this->getUser()->getId()
+                );
+
+                $results[$key]['url'] = $url;
+
+                if (false === $entry) {
+                    $entry = $this->get('wallabag_core.content_proxy')->updateEntry(
+                        new Entry($this->getUser()),
+                        $url
+                    );
+                }
+
+                $em = $this->getDoctrine()->getManager();
+                $em->persist($entry);
+                $em->flush();
+
+                $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
+
+                // entry saved, dispatch event about it!
+                $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
+            }
+        }
+
+        return $this->sendResponse($results);
     }
 
     /**
@@ -200,12 +322,12 @@ class EntryRestController extends WallabagRestController
 
         $em = $this->getDoctrine()->getManager();
         $em->persist($entry);
-
         $em->flush();
 
-        $json = $this->get('serializer')->serialize($entry, 'json');
+        // entry saved, dispatch event about it!
+        $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
 
-        return (new JsonResponse())->setJson($json);
+        return $this->sendResponse($entry);
     }
 
     /**
@@ -254,9 +376,50 @@ class EntryRestController extends WallabagRestController
         $em = $this->getDoctrine()->getManager();
         $em->flush();
 
-        $json = $this->get('serializer')->serialize($entry, 'json');
+        return $this->sendResponse($entry);
+    }
 
-        return (new JsonResponse())->setJson($json);
+    /**
+     * Reload an entry.
+     * 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).
+     *
+     * @ApiDoc(
+     *      requirements={
+     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
+     *      }
+     * )
+     *
+     * @return JsonResponse
+     */
+    public function patchEntriesReloadAction(Entry $entry)
+    {
+        $this->validateAuthentication();
+        $this->validateUserAccess($entry->getUser()->getId());
+
+        try {
+            $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
+        } catch (\Exception $e) {
+            $this->get('logger')->error('Error while saving an entry', [
+                'exception' => $e,
+                'entry' => $entry,
+            ]);
+
+            return new JsonResponse([], 304);
+        }
+
+        // if refreshing entry failed, don't save it
+        if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
+            return new JsonResponse([], 304);
+        }
+
+        $em = $this->getDoctrine()->getManager();
+        $em->persist($entry);
+        $em->flush();
+
+        // entry saved, dispatch event about it!
+        $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
+
+        return $this->sendResponse($entry);
     }
 
     /**
@@ -279,9 +442,10 @@ class EntryRestController extends WallabagRestController
         $em->remove($entry);
         $em->flush();
 
-        $json = $this->get('serializer')->serialize($entry, 'json');
+        // entry deleted, dispatch event about it!
+        $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
 
-        return (new JsonResponse())->setJson($json);
+        return $this->sendResponse($entry);
     }
 
     /**
@@ -300,9 +464,7 @@ class EntryRestController extends WallabagRestController
         $this->validateAuthentication();
         $this->validateUserAccess($entry->getUser()->getId());
 
-        $json = $this->get('serializer')->serialize($entry->getTags(), 'json');
-
-        return (new JsonResponse())->setJson($json);
+        return $this->sendResponse($entry->getTags());
     }
 
     /**
@@ -333,9 +495,7 @@ class EntryRestController extends WallabagRestController
         $em->persist($entry);
         $em->flush();
 
-        $json = $this->get('serializer')->serialize($entry, 'json');
-
-        return (new JsonResponse())->setJson($json);
+        return $this->sendResponse($entry);
     }
 
     /**
@@ -360,7 +520,124 @@ class EntryRestController extends WallabagRestController
         $em->persist($entry);
         $em->flush();
 
-        $json = $this->get('serializer')->serialize($entry, 'json');
+        return $this->sendResponse($entry);
+    }
+
+    /**
+     * Handles an entries list delete tags from them.
+     *
+     * @ApiDoc(
+     *       parameters={
+     *          {"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."}
+     *       }
+     * )
+     *
+     * @return JsonResponse
+     */
+    public function deleteEntriesTagsListAction(Request $request)
+    {
+        $this->validateAuthentication();
+
+        $list = json_decode($request->query->get('list', []));
+
+        if (empty($list)) {
+            return $this->sendResponse([]);
+        }
+
+        // handle multiple urls
+        $results = [];
+
+        foreach ($list as $key => $element) {
+            $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
+                $element->url,
+                $this->getUser()->getId()
+            );
+
+            $results[$key]['url'] = $element->url;
+            $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
+
+            $tags = $element->tags;
+
+            if (false !== $entry && !(empty($tags))) {
+                $tags = explode(',', $tags);
+                foreach ($tags as $label) {
+                    $label = trim($label);
+
+                    $tag = $this->getDoctrine()
+                        ->getRepository('WallabagCoreBundle:Tag')
+                        ->findOneByLabel($label);
+
+                    if (false !== $tag) {
+                        $entry->removeTag($tag);
+                    }
+                }
+
+                $em = $this->getDoctrine()->getManager();
+                $em->persist($entry);
+                $em->flush();
+            }
+        }
+
+        return $this->sendResponse($results);
+    }
+
+    /**
+     * Handles an entries list and add tags to them.
+     *
+     * @ApiDoc(
+     *       parameters={
+     *          {"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."}
+     *       }
+     * )
+     *
+     * @return JsonResponse
+     */
+    public function postEntriesTagsListAction(Request $request)
+    {
+        $this->validateAuthentication();
+
+        $list = json_decode($request->query->get('list', []));
+
+        if (empty($list)) {
+            return $this->sendResponse([]);
+        }
+
+        $results = [];
+
+        // handle multiple urls
+        foreach ($list as $key => $element) {
+            $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
+                $element->url,
+                $this->getUser()->getId()
+            );
+
+            $results[$key]['url'] = $element->url;
+            $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
+
+            $tags = $element->tags;
+
+            if (false !== $entry && !(empty($tags))) {
+                $this->get('wallabag_core.content_proxy')->assignTagsToEntry($entry, $tags);
+
+                $em = $this->getDoctrine()->getManager();
+                $em->persist($entry);
+                $em->flush();
+            }
+        }
+
+        return $this->sendResponse($results);
+    }
+
+    /**
+     * Shortcut to send data serialized in json.
+     *
+     * @param mixed $data
+     *
+     * @return JsonResponse
+     */
+    private function sendResponse($data)
+    {
+        $json = $this->get('serializer')->serialize($data, 'json');
 
         return (new JsonResponse())->setJson($json);
     }