]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - src/Wallabag/ImportBundle/Import/PocketImport.php
Merge pull request #2731 from llune/patch-2
[github/wallabag/wallabag.git] / src / Wallabag / ImportBundle / Import / PocketImport.php
index 413c9ccc7ece071e3f01340782afaf5065ed4ded..330934809c5ab164853d98ecf6803035cfc40ab1 100644 (file)
 
 namespace Wallabag\ImportBundle\Import;
 
-use Doctrine\ORM\EntityManager;
 use GuzzleHttp\Client;
-use Symfony\Component\HttpFoundation\Session\Session;
+use GuzzleHttp\Exception\RequestException;
 use Wallabag\CoreBundle\Entity\Entry;
-use Wallabag\CoreBundle\Tools\Utils;
+use Wallabag\CoreBundle\Helper\ContentProxy;
 
-class PocketImport implements ImportInterface
+class PocketImport extends AbstractImport
 {
-    private $user;
-    private $session;
-    private $em;
-    private $consumerKey;
+    private $client;
+    private $accessToken;
 
-    public function __construct($tokenStorage, Session $session, EntityManager $em, $consumerKey)
-    {
-        $this->user = $tokenStorage->getToken()->getUser();
-        $this->session = $session;
-        $this->em = $em;
-        $this->consumerKey = $consumerKey;
-    }
+    const NB_ELEMENTS = 5000;
 
     /**
-     * Create a new Client.
+     * Only used for test purpose.
      *
-     * @return Client
+     * @return string
      */
-    private function createClient()
+    public function getAccessToken()
     {
-        return new Client([
-            'defaults' => [
-                'headers' => [
-                    'content-type' => 'application/json',
-                    'X-Accept' => 'application/json',
-                ],
-            ],
-        ]);
+        return $this->accessToken;
     }
 
     /**
-     * @param $entries
+     * {@inheritdoc}
      */
-    private function parsePocketEntries($entries)
+    public function getName()
     {
-        foreach ($entries as $entry) {
-            $newEntry = new Entry($this->user);
-            $newEntry->setUrl($entry['given_url']);
-            $newEntry->setTitle(isset($entry['resolved_title']) ? $entry['resolved_title'] : (isset($entry['given_title']) ? $entry['given_title'] : 'Untitled'));
-
-            if (isset($entry['excerpt'])) {
-                $newEntry->setContent($entry['excerpt']);
-            }
-
-            if (isset($entry['has_image']) && $entry['has_image'] > 0) {
-                $newEntry->setPreviewPicture($entry['image']['src']);
-            }
-
-            if (isset($entry['word_count'])) {
-                $newEntry->setReadingTime(Utils::convertWordsToMinutes($entry['word_count']));
-            }
+        return 'Pocket';
+    }
 
-            $this->em->persist($newEntry);
-        }
+    /**
+     * {@inheritdoc}
+     */
+    public function getUrl()
+    {
+        return 'import_pocket';
+    }
 
-        $this->em->flush();
+    /**
+     * {@inheritdoc}
+     */
+    public function getDescription()
+    {
+        return 'import.pocket.description';
     }
 
-    public function oAuthRequest($redirectUri, $callbackUri)
+    /**
+     * Return the oauth url to authenticate the client.
+     *
+     * @param string $redirectUri Redirect url in case of error
+     *
+     * @return string|false request_token for callback method
+     */
+    public function getRequestToken($redirectUri)
     {
-        $client = $this->createClient();
-        $request = $client->createRequest('POST', 'https://getpocket.com/v3/oauth/request',
+        $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/request',
             [
                 'body' => json_encode([
-                    'consumer_key' => $this->consumerKey,
+                    'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
                     'redirect_uri' => $redirectUri,
                 ]),
             ]
         );
 
-        $response = $client->send($request);
-        $values = $response->json();
+        try {
+            $response = $this->client->send($request);
+        } catch (RequestException $e) {
+            $this->logger->error(sprintf('PocketImport: Failed to request token: %s', $e->getMessage()), ['exception' => $e]);
 
-        // store code in session for callback method
-        $this->session->set('pocketCode', $values['code']);
+            return false;
+        }
 
-        return 'https://getpocket.com/auth/authorize?request_token='.$values['code'].'&redirect_uri='.$callbackUri;
+        return $response->json()['code'];
     }
 
-    public function oAuthAuthorize()
+    /**
+     * Usually called by the previous callback to authorize the client.
+     * Then it return a token that can be used for next requests.
+     *
+     * @param string $code request_token from getRequestToken
+     *
+     * @return bool
+     */
+    public function authorize($code)
     {
-        $client = $this->createClient();
-
-        $request = $client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize',
+        $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize',
             [
                 'body' => json_encode([
-                    'consumer_key' => $this->consumerKey,
-                    'code' => $this->session->get('pocketCode'),
+                    'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
+                    'code' => $code,
                 ]),
             ]
         );
 
-        $response = $client->send($request);
+        try {
+            $response = $this->client->send($request);
+        } catch (RequestException $e) {
+            $this->logger->error(sprintf('PocketImport: Failed to authorize client: %s', $e->getMessage()), ['exception' => $e]);
 
-        return $response->json()['access_token'];
+            return false;
+        }
+
+        $this->accessToken = $response->json()['access_token'];
+
+        return true;
     }
 
-    public function import($accessToken)
+    /**
+     * {@inheritdoc}
+     */
+    public function import($offset = 0)
     {
-        $client = $this->createClient();
+        static $run = 0;
 
-        $request = $client->createRequest('POST', 'https://getpocket.com/v3/get',
+        $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/get',
             [
                 'body' => json_encode([
-                    'consumer_key' => $this->consumerKey,
-                    'access_token' => $accessToken,
+                    'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
+                    'access_token' => $this->accessToken,
                     'detailType' => 'complete',
+                    'state' => 'all',
+                    'sort' => 'newest',
+                    'count' => self::NB_ELEMENTS,
+                    'offset' => $offset,
                 ]),
             ]
         );
 
-        $response = $client->send($request);
+        try {
+            $response = $this->client->send($request);
+        } catch (RequestException $e) {
+            $this->logger->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]);
+
+            return false;
+        }
+
         $entries = $response->json();
 
-        $this->parsePocketEntries($entries['list']);
+        if ($this->producer) {
+            $this->parseEntriesForProducer($entries['list']);
+        } else {
+            $this->parseEntries($entries['list']);
+        }
 
-        $this->session->getFlashBag()->add(
-            'notice',
-            count($entries['list']).' entries imported'
-        );
+        // if we retrieve exactly the amount of items requested it means we can get more
+        // re-call import and offset item by the amount previous received:
+        //  - first call get 5k offset 0
+        //  - second call get 5k offset 5k
+        //  - and so on
+        if (count($entries['list']) === self::NB_ELEMENTS) {
+            ++$run;
+
+            return $this->import(self::NB_ELEMENTS * $run);
+        }
+
+        return true;
+    }
+
+    /**
+     * Set the Guzzle client.
+     *
+     * @param Client $client
+     */
+    public function setClient(Client $client)
+    {
+        $this->client = $client;
+    }
+
+    /**
+     * {@inheritdoc}
+     *
+     * @see https://getpocket.com/developer/docs/v3/retrieve
+     */
+    public function parseEntry(array $importedEntry)
+    {
+        $url = isset($importedEntry['resolved_url']) && $importedEntry['resolved_url'] != '' ? $importedEntry['resolved_url'] : $importedEntry['given_url'];
+
+        $existingEntry = $this->em
+            ->getRepository('WallabagCoreBundle:Entry')
+            ->findByUrlAndUserId($url, $this->user->getId());
+
+        if (false !== $existingEntry) {
+            ++$this->skippedEntries;
+
+            return;
+        }
+
+        $entry = new Entry($this->user);
+        $entry->setUrl($url);
+
+        // update entry with content (in case fetching failed, the given entry will be return)
+        $entry = $this->fetchContent($entry, $url);
+
+        // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted
+        $entry->setArchived($importedEntry['status'] == 1 || $this->markAsRead);
+
+        // 0 or 1 - 1 If the item is starred
+        $entry->setStarred($importedEntry['favorite'] == 1);
+
+        $title = 'Untitled';
+        if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] != '') {
+            $title = $importedEntry['resolved_title'];
+        } elseif (isset($importedEntry['given_title']) && $importedEntry['given_title'] != '') {
+            $title = $importedEntry['given_title'];
+        }
+
+        $entry->setTitle($title);
+
+        // 0, 1, or 2 - 1 if the item has images in it - 2 if the item is an image
+        if (isset($importedEntry['has_image']) && $importedEntry['has_image'] > 0 && isset($importedEntry['images'][1])) {
+            $entry->setPreviewPicture($importedEntry['images'][1]['src']);
+        }
+
+        if (isset($importedEntry['tags']) && !empty($importedEntry['tags'])) {
+            $this->contentProxy->assignTagsToEntry(
+                $entry,
+                array_keys($importedEntry['tags']),
+                $this->em->getUnitOfWork()->getScheduledEntityInsertions()
+            );
+        }
+
+        if (!empty($importedEntry['time_added'])) {
+            $entry->setCreatedAt((new \DateTime())->setTimestamp($importedEntry['time_added']));
+        }
+
+        $this->em->persist($entry);
+        ++$this->importedEntries;
+
+        return $entry;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    protected function setEntryAsRead(array $importedEntry)
+    {
+        $importedEntry['status'] = '1';
+
+        return $importedEntry;
     }
 }