]> git.immae.eu Git - github/wallabag/wallabag.git/blobdiff - src/Wallabag/ImportBundle/Import/PocketImport.php
Merge pull request #4152 from ldidry/add-env-var-dev.sh
[github/wallabag/wallabag.git] / src / Wallabag / ImportBundle / Import / PocketImport.php
index 85bab0db67084aa4a901dd8ffefd825707d6baaa..24fdaa2b83f6efd7f863a366ffd3fd51a3e8ff60 100644 (file)
@@ -2,29 +2,33 @@
 
 namespace Wallabag\ImportBundle\Import;
 
-use Doctrine\ORM\EntityManager;
-use GuzzleHttp\Client;
-use Symfony\Component\HttpFoundation\Session\Session;
-use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
+use Http\Client\Common\HttpMethodsClient;
+use Http\Client\Common\Plugin\ErrorPlugin;
+use Http\Client\Common\PluginClient;
+use Http\Client\Exception\RequestException;
+use Http\Client\HttpClient;
+use Http\Discovery\MessageFactoryDiscovery;
+use Http\Message\MessageFactory;
+use Psr\Http\Message\ResponseInterface;
 use Wallabag\CoreBundle\Entity\Entry;
-use Wallabag\CoreBundle\Entity\Tag;
-use Wallabag\CoreBundle\Tools\Utils;
 
-class PocketImport implements ImportInterface
+class PocketImport extends AbstractImport
 {
-    private $user;
-    private $session;
-    private $em;
-    private $consumerKey;
-    private $skippedEntries = 0;
-    private $importedEntries = 0;
-
-    public function __construct(TokenStorageInterface $tokenStorage, Session $session, EntityManager $em, $consumerKey)
+    const NB_ELEMENTS = 5000;
+    /**
+     * @var HttpMethodsClient
+     */
+    private $client;
+    private $accessToken;
+
+    /**
+     * Only used for test purpose.
+     *
+     * @return string
+     */
+    public function getAccessToken()
     {
-        $this->user = $tokenStorage->getToken()->getUser();
-        $this->session = $session;
-        $this->em = $em;
-        $this->consumerKey = $consumerKey;
+        return $this->accessToken;
     }
 
     /**
@@ -38,197 +42,214 @@ class PocketImport implements ImportInterface
     /**
      * {@inheritdoc}
      */
-    public function getDescription()
+    public function getUrl()
     {
-        return 'This importer will import all your <a href="https://getpocket.com">Pocket</a> data.';
+        return 'import_pocket';
     }
 
     /**
-     * Create a new Client.
-     *
-     * @return Client
+     * {@inheritdoc}
      */
-    private function createClient()
+    public function getDescription()
     {
-        return new Client([
-            'defaults' => [
-                'headers' => [
-                    'content-type' => 'application/json',
-                    'X-Accept' => 'application/json',
-                ],
-            ],
-        ]);
+        return 'import.pocket.description';
     }
 
     /**
-     * Returns the good title for current entry.
+     * Return the oauth url to authenticate the client.
      *
-     * @param $pocketEntry
+     * @param string $redirectUri Redirect url in case of error
      *
-     * @return string
+     * @return string|false request_token for callback method
      */
-    private function guessTitle($pocketEntry)
+    public function getRequestToken($redirectUri)
     {
-        if (isset($pocketEntry['resolved_title']) && $pocketEntry['resolved_title'] != '') {
-            return $pocketEntry['resolved_title'];
-        } elseif (isset($pocketEntry['given_title']) && $pocketEntry['given_title'] != '') {
-            return $pocketEntry['given_title'];
+        try {
+            $response = $this->client->post('https://getpocket.com/v3/oauth/request', [], json_encode([
+                'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
+                'redirect_uri' => $redirectUri,
+            ]));
+        } catch (RequestException $e) {
+            $this->logger->error(sprintf('PocketImport: Failed to request token: %s', $e->getMessage()), ['exception' => $e]);
+
+            return false;
         }
 
-        return 'Untitled';
+        return $this->jsonDecode($response)['code'];
     }
 
     /**
-     * Returns the good URL for current entry.
+     * Usually called by the previous callback to authorize the client.
+     * Then it return a token that can be used for next requests.
      *
-     * @param $pocketEntry
+     * @param string $code request_token from getRequestToken
      *
-     * @return string
+     * @return bool
      */
-    private function guessURL($pocketEntry)
+    public function authorize($code)
     {
-        if (isset($pocketEntry['resolved_url']) && $pocketEntry['resolved_url'] != '') {
-            return $pocketEntry['resolved_url'];
+        try {
+            $response = $this->client->post('https://getpocket.com/v3/oauth/authorize', [], json_encode([
+                'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
+                'code' => $code,
+            ]));
+        } catch (RequestException $e) {
+            $this->logger->error(sprintf('PocketImport: Failed to authorize client: %s', $e->getMessage()), ['exception' => $e]);
+
+            return false;
         }
 
-        return $pocketEntry['given_url'];
+        $this->accessToken = $this->jsonDecode($response)['access_token'];
+
+        return true;
     }
 
-    private function assignTagsToEntry(Entry $entry, $tags)
+    /**
+     * {@inheritdoc}
+     */
+    public function import($offset = 0)
     {
-        foreach ($tags as $tag) {
-            $label = trim($tag['tag']);
-            $tagEntity = $this->em
-                ->getRepository('WallabagCoreBundle:Tag')
-                ->findOneByLabelAndUserId($label, $this->user->getId());
-
-            if (is_object($tagEntity)) {
-                $entry->addTag($tagEntity);
-            } else {
-                $newTag = new Tag($this->user);
-                $newTag->setLabel($label);
-                $entry->addTag($newTag);
-            }
-            $this->em->flush();
+        static $run = 0;
+
+        try {
+            $response = $this->client->post('https://getpocket.com/v3/get', [], json_encode([
+                'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
+                'access_token' => $this->accessToken,
+                'detailType' => 'complete',
+                'state' => 'all',
+                'sort' => 'newest',
+                'count' => self::NB_ELEMENTS,
+                'offset' => $offset,
+            ]));
+        } catch (RequestException $e) {
+            $this->logger->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]);
+
+            return false;
+        }
+
+        $entries = $this->jsonDecode($response);
+
+        if ($this->producer) {
+            $this->parseEntriesForProducer($entries['list']);
+        } else {
+            $this->parseEntries($entries['list']);
+        }
+
+        // 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 (self::NB_ELEMENTS === \count($entries['list'])) {
+            ++$run;
+
+            return $this->import(self::NB_ELEMENTS * $run);
         }
+
+        return true;
     }
 
     /**
-     * @param $entries
+     * Set the Http client.
      */
-    private function parsePocketEntries($entries)
+    public function setClient(HttpClient $client, MessageFactory $messageFactory = null)
     {
-        foreach ($entries as $pocketEntry) {
-            $entry = new Entry($this->user);
-            $url = $this->guessURL($pocketEntry);
+        $this->client = new HttpMethodsClient(new PluginClient($client, [new ErrorPlugin()]), $messageFactory ?: MessageFactoryDiscovery::find());
+    }
 
-            $existingEntry = $this->em
-                ->getRepository('WallabagCoreBundle:Entry')
-                ->existByUrlAndUserId($url, $this->user->getId());
+    /**
+     * {@inheritdoc}
+     */
+    public function validateEntry(array $importedEntry)
+    {
+        if (empty($importedEntry['resolved_url']) && empty($importedEntry['given_url'])) {
+            return false;
+        }
+
+        return true;
+    }
 
-            if (false !== $existingEntry) {
-                ++$this->skippedEntries;
-                continue;
-            }
+    /**
+     * {@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'];
 
-            $entry->setUrl($url);
-            $entry->setDomainName(parse_url($url, PHP_URL_HOST));
+        $existingEntry = $this->em
+            ->getRepository('WallabagCoreBundle:Entry')
+            ->findByUrlAndUserId($url, $this->user->getId());
 
-            if ($pocketEntry['status'] == 1) {
-                $entry->setArchived(true);
-            }
-            if ($pocketEntry['favorite'] == 1) {
-                $entry->setStarred(true);
-            }
+        if (false !== $existingEntry) {
+            ++$this->skippedEntries;
 
-            $entry->setTitle($this->guessTitle($pocketEntry));
+            return;
+        }
 
-            if (isset($pocketEntry['excerpt'])) {
-                $entry->setContent($pocketEntry['excerpt']);
-            }
+        $entry = new Entry($this->user);
+        $entry->setUrl($url);
 
-            if (isset($pocketEntry['has_image']) && $pocketEntry['has_image'] > 0) {
-                $entry->setPreviewPicture($pocketEntry['image']['src']);
-            }
+        // update entry with content (in case fetching failed, the given entry will be return)
+        $this->fetchContent($entry, $url);
 
-            if (isset($pocketEntry['word_count'])) {
-                $entry->setReadingTime(Utils::convertWordsToMinutes($pocketEntry['word_count']));
-            }
+        // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted
+        $entry->updateArchived(1 === (int) $importedEntry['status'] || $this->markAsRead);
 
-            if (!empty($pocketEntry['tags'])) {
-                $this->assignTagsToEntry($entry, $pocketEntry['tags']);
-            }
+        // 0 or 1 - 1 if the item is starred
+        $entry->setStarred(1 === (int) $importedEntry['favorite']);
 
-            $this->em->persist($entry);
-            ++$this->importedEntries;
+        $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'];
         }
 
-        $this->em->flush();
-    }
+        $entry->setTitle($title);
 
-    public function oAuthRequest($redirectUri, $callbackUri)
-    {
-        $client = $this->createClient();
-        $request = $client->createRequest('POST', 'https://getpocket.com/v3/oauth/request',
-            [
-                'body' => json_encode([
-                    'consumer_key' => $this->consumerKey,
-                    'redirect_uri' => $redirectUri,
-                ]),
-            ]
-        );
-
-        $response = $client->send($request);
-        $values = $response->json();
-
-        // store code in session for callback method
-        $this->session->set('pocketCode', $values['code']);
-
-        return 'https://getpocket.com/auth/authorize?request_token='.$values['code'].'&redirect_uri='.$callbackUri;
-    }
+        // 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']);
+        }
 
-    public function oAuthAuthorize()
-    {
-        $client = $this->createClient();
+        if (isset($importedEntry['tags']) && !empty($importedEntry['tags'])) {
+            $this->tagsAssigner->assignTagsToEntry(
+                $entry,
+                array_keys($importedEntry['tags']),
+                $this->em->getUnitOfWork()->getScheduledEntityInsertions()
+            );
+        }
 
-        $request = $client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize',
-            [
-                'body' => json_encode([
-                    'consumer_key' => $this->consumerKey,
-                    'code' => $this->session->get('pocketCode'),
-                ]),
-            ]
-        );
+        if (!empty($importedEntry['time_added'])) {
+            $entry->setCreatedAt((new \DateTime())->setTimestamp($importedEntry['time_added']));
+        }
 
-        $response = $client->send($request);
+        $this->em->persist($entry);
+        ++$this->importedEntries;
 
-        return $response->json()['access_token'];
+        return $entry;
     }
 
-    public function import($accessToken)
+    /**
+     * {@inheritdoc}
+     */
+    protected function setEntryAsRead(array $importedEntry)
     {
-        $client = $this->createClient();
-
-        $request = $client->createRequest('POST', 'https://getpocket.com/v3/get',
-            [
-                'body' => json_encode([
-                    'consumer_key' => $this->consumerKey,
-                    'access_token' => $accessToken,
-                    'detailType' => 'complete',
-                    'state' => 'all',
-                    'sort' => 'oldest',
-                ]),
-            ]
-        );
-
-        $response = $client->send($request);
-        $entries = $response->json();
-
-        $this->parsePocketEntries($entries['list']);
-
-        $this->session->getFlashBag()->add(
-            'notice',
-            $this->importedEntries.' entries imported, '.$this->skippedEntries.' already saved.'
-        );
+        $importedEntry['status'] = '1';
+
+        return $importedEntry;
+    }
+
+    protected function jsonDecode(ResponseInterface $response)
+    {
+        $data = json_decode((string) $response->getBody(), true);
+
+        if (JSON_ERROR_NONE !== json_last_error()) {
+            throw new \InvalidArgumentException('Unable to parse JSON data: ' . json_last_error_msg());
+        }
+
+        return $data;
     }
 }