X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=src%2FWallabag%2FImportBundle%2FImport%2FPocketImport.php;h=330934809c5ab164853d98ecf6803035cfc40ab1;hb=da4136557963018287cae61226e9006c3c741747;hp=dd1c34abcba9179486c5e55e811289df00a326a8;hpb=303768dfe9b85f87d043eb225c5c8c3a88d8c051;p=github%2Fwallabag%2Fwallabag.git diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index dd1c34ab..33093480 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -2,226 +2,244 @@ 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\Entity\Tag; -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 $skippedEntries = 0; - private $importedEntries = 0; - - public function __construct($tokenStorage, Session $session, EntityManager $em, $consumerKey) + private $client; + private $accessToken; + + const NB_ELEMENTS = 5000; + + /** + * 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() + /** + * {@inheritdoc} + */ + public function getUrl() { - return 'This importer will import all your Pocket 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']; + $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/request', + [ + 'body' => json_encode([ + 'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(), + 'redirect_uri' => $redirectUri, + ]), + ] + ); + + try { + $response = $this->client->send($request); + } catch (RequestException $e) { + $this->logger->error(sprintf('PocketImport: Failed to request token: %s', $e->getMessage()), ['exception' => $e]); + + return false; } - return 'Untitled'; + return $response->json()['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']; - } + $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize', + [ + 'body' => json_encode([ + 'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(), + 'code' => $code, + ]), + ] + ); - return $pocketEntry['given_url']; - } + try { + $response = $this->client->send($request); + } catch (RequestException $e) { + $this->logger->error(sprintf('PocketImport: Failed to authorize client: %s', $e->getMessage()), ['exception' => $e]); - private function assignTagsToEntry(Entry $entry, $tags) - { - 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(); + return false; } + + $this->accessToken = $response->json()['access_token']; + + return true; } /** - * @param $entries + * {@inheritdoc} */ - private function parsePocketEntries($entries) + public function import($offset = 0) { - foreach ($entries as $pocketEntry) { - $entry = new Entry($this->user); - $url = $this->guessURL($pocketEntry); - - $existingEntry = $this->em - ->getRepository('WallabagCoreBundle:Entry') - ->findOneByUrlAndUserId($url, $this->user->getId()); - - if (count($existingEntry) > 0) { - ++$this->skippedEntries; - continue; - } + static $run = 0; - $entry->setUrl($url); - $entry->setDomainName(parse_url($url, PHP_URL_HOST)); - - if ($pocketEntry['status'] == 1) { - $entry->setArchived(true); - } - if ($pocketEntry['favorite'] == 1) { - $entry->setStarred(true); - } + $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/get', + [ + 'body' => json_encode([ + 'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(), + 'access_token' => $this->accessToken, + 'detailType' => 'complete', + 'state' => 'all', + 'sort' => 'newest', + 'count' => self::NB_ELEMENTS, + 'offset' => $offset, + ]), + ] + ); - $entry->setTitle($this->guessTitle($pocketEntry)); + try { + $response = $this->client->send($request); + } catch (RequestException $e) { + $this->logger->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]); - if (isset($pocketEntry['excerpt'])) { - $entry->setContent($pocketEntry['excerpt']); - } + return false; + } - if (isset($pocketEntry['has_image']) && $pocketEntry['has_image'] > 0) { - $entry->setPreviewPicture($pocketEntry['image']['src']); - } + $entries = $response->json(); - if (isset($pocketEntry['word_count'])) { - $entry->setReadingTime(Utils::convertWordsToMinutes($pocketEntry['word_count'])); - } + if ($this->producer) { + $this->parseEntriesForProducer($entries['list']); + } else { + $this->parseEntries($entries['list']); + } - if (!empty($pocketEntry['tags'])) { - $this->assignTagsToEntry($entry, $pocketEntry['tags']); - } + // 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; - $this->em->persist($entry); - ++$this->importedEntries; + return $this->import(self::NB_ELEMENTS * $run); } - $this->em->flush(); + return true; } - public function oAuthRequest($redirectUri, $callbackUri) + /** + * Set the Guzzle client. + * + * @param Client $client + */ + public function setClient(Client $client) { - $client = $this->createClient(); - $request = $client->createRequest('POST', 'https://getpocket.com/v3/oauth/request', - [ - 'body' => json_encode([ - 'consumer_key' => $this->consumerKey, - 'redirect_uri' => $redirectUri, - ]), - ] - ); + $this->client = $client; + } - $response = $client->send($request); - $values = $response->json(); + /** + * {@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']; - // store code in session for callback method - $this->session->set('pocketCode', $values['code']); + $existingEntry = $this->em + ->getRepository('WallabagCoreBundle:Entry') + ->findByUrlAndUserId($url, $this->user->getId()); - return 'https://getpocket.com/auth/authorize?request_token='.$values['code'].'&redirect_uri='.$callbackUri; - } + if (false !== $existingEntry) { + ++$this->skippedEntries; - public function oAuthAuthorize() - { - $client = $this->createClient(); + return; + } - $request = $client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize', - [ - 'body' => json_encode([ - 'consumer_key' => $this->consumerKey, - 'code' => $this->session->get('pocketCode'), - ]), - ] - ); + $entry = new Entry($this->user); + $entry->setUrl($url); - $response = $client->send($request); + // update entry with content (in case fetching failed, the given entry will be return) + $entry = $this->fetchContent($entry, $url); - return $response->json()['access_token']; - } + // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted + $entry->setArchived($importedEntry['status'] == 1 || $this->markAsRead); - public function import($accessToken) - { - $client = $this->createClient(); + // 0 or 1 - 1 If the item is starred + $entry->setStarred($importedEntry['favorite'] == 1); - $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', - ]), - ] - ); + $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']; + } - $response = $client->send($request); - $entries = $response->json(); + $entry->setTitle($title); - $this->parsePocketEntries($entries['list']); + // 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']); + } - $this->session->getFlashBag()->add( - 'notice', - $this->importedEntries.' entries imported, '.$this->skippedEntries.' already saved.' - ); + 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; } }