X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=src%2FWallabag%2FImportBundle%2FImport%2FPocketImport.php;h=85bab0db67084aa4a901dd8ffefd825707d6baaa;hb=f808b01692a835673f328d7221ba8c212caa9b61;hp=81af8e5758a9fb0e73abe976f668c62d759288be;hpb=d51b38ed309c9aead938e8c8963c05c6d82b4ec2;p=github%2Fwallabag%2Fwallabag.git diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index 81af8e57..7d38826b 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -2,143 +2,242 @@ 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; -class PocketImport implements ImportInterface +class PocketImport extends AbstractImport { - private $user; - private $session; - private $em; - private $consumerKey; + const NB_ELEMENTS = 5000; + private $client; + private $accessToken; - public function __construct($tokenStorage, Session $session, EntityManager $em, $consumerKey) + /** + * 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; } + /** + * {@inheritdoc} + */ public function getName() { return 'Pocket'; } - public function getDescription() - { - return 'This importer will import all your Pocket data.'; - } - /** - * Create a new Client. - * - * @return Client + * {@inheritdoc} */ - private function createClient() + public function getUrl() { - return new Client([ - 'defaults' => [ - 'headers' => [ - 'content-type' => 'application/json', - 'X-Accept' => 'application/json', - ], - ], - ]); + return 'import_pocket'; } /** - * @param $entries + * {@inheritdoc} */ - private function parsePocketEntries($entries) + public function getDescription() { - 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'])); - } - - $this->em->persist($newEntry); - } - - $this->em->flush(); + 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 false; + } + + $this->accessToken = $response->json()['access_token']; - return $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) + $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->tagsAssigner->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; } }