X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=src%2FWallabag%2FImportBundle%2FImport%2FPocketImport.php;h=24fdaa2b83f6efd7f863a366ffd3fd51a3e8ff60;hb=8d4ed0df0633f43fc2d65fef72c36070113844d1;hp=19b63f176cb8d78c1a00d003617d5ad3cffe699c;hpb=519ba0b5e71cd9b5abd620f682fd2296e6180af3;p=github%2Fwallabag%2Fwallabag.git diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index 19b63f17..24fdaa2b 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -2,41 +2,33 @@ namespace Wallabag\ImportBundle\Import; -use Psr\Log\LoggerInterface; -use Psr\Log\NullLogger; -use Doctrine\ORM\EntityManager; -use GuzzleHttp\Client; -use GuzzleHttp\Exception\RequestException; -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\Helper\ContentProxy; -use Craue\ConfigBundle\Util\Config; -class PocketImport implements ImportInterface +class PocketImport extends AbstractImport { - private $user; - private $em; - private $contentProxy; - private $logger; + const NB_ELEMENTS = 5000; + /** + * @var HttpMethodsClient + */ private $client; - private $consumerKey; - private $skippedEntries = 0; - private $importedEntries = 0; - private $markAsRead; - protected $accessToken; - - public function __construct(TokenStorageInterface $tokenStorage, EntityManager $em, ContentProxy $contentProxy, Config $craueConfig) - { - $this->user = $tokenStorage->getToken()->getUser(); - $this->em = $em; - $this->contentProxy = $contentProxy; - $this->consumerKey = $craueConfig->get('pocket_consumer_key'); - $this->logger = new NullLogger(); - } + private $accessToken; - public function setLogger(LoggerInterface $logger) + /** + * Only used for test purpose. + * + * @return string + */ + public function getAccessToken() { - $this->logger = $logger; + return $this->accessToken; } /** @@ -72,24 +64,18 @@ class PocketImport implements ImportInterface */ public function getRequestToken($redirectUri) { - $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/request', - [ - 'body' => json_encode([ - 'consumer_key' => $this->consumerKey, - 'redirect_uri' => $redirectUri, - ]), - ] - ); - try { - $response = $this->client->send($request); + $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 $response->json()['code']; + return $this->jsonDecode($response)['code']; } /** @@ -102,167 +88,168 @@ class PocketImport implements ImportInterface */ public function authorize($code) { - $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize', - [ - 'body' => json_encode([ - 'consumer_key' => $this->consumerKey, - 'code' => $code, - ]), - ] - ); - try { - $response = $this->client->send($request); + $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; } - $this->accessToken = $response->json()['access_token']; + $this->accessToken = $this->jsonDecode($response)['access_token']; return true; } /** - * Set whether articles must be all marked as read. - * - * @param bool $markAsRead + * {@inheritdoc} */ - public function setMarkAsRead($markAsRead) + public function import($offset = 0) { - $this->markAsRead = $markAsRead; + 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 $this; + 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; } /** - * Get whether articles must be all marked as read. + * Set the Http client. */ - public function getMarkAsRead() + public function setClient(HttpClient $client, MessageFactory $messageFactory = null) { - return $this->markAsRead; + $this->client = new HttpMethodsClient(new PluginClient($client, [new ErrorPlugin()]), $messageFactory ?: MessageFactoryDiscovery::find()); } /** * {@inheritdoc} */ - public function import() + public function validateEntry(array $importedEntry) { - $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/get', - [ - 'body' => json_encode([ - 'consumer_key' => $this->consumerKey, - 'access_token' => $this->accessToken, - 'detailType' => 'complete', - 'state' => 'all', - 'sort' => 'oldest', - ]), - ] - ); - - try { - $response = $this->client->send($request); - } catch (RequestException $e) { - $this->logger->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]); - + if (empty($importedEntry['resolved_url']) && empty($importedEntry['given_url'])) { return false; } - $entries = $response->json(); - - $this->parseEntries($entries['list']); - return true; } /** * {@inheritdoc} + * + * @see https://getpocket.com/developer/docs/v3/retrieve */ - public function getSummary() + public function parseEntry(array $importedEntry) { - return [ - 'skipped' => $this->skippedEntries, - 'imported' => $this->importedEntries, - ]; + $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->updateArchived(1 === (int) $importedEntry['status'] || $this->markAsRead); + + // 0 or 1 - 1 if the item is starred + $entry->setStarred(1 === (int) $importedEntry['favorite']); + + $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; } /** - * Set the Guzzle client. - * - * @param Client $client + * {@inheritdoc} */ - public function setClient(Client $client) + protected function setEntryAsRead(array $importedEntry) { - $this->client = $client; + $importedEntry['status'] = '1'; + + return $importedEntry; } - /** - * @see https://getpocket.com/developer/docs/v3/retrieve - * - * @param $entries - */ - private function parseEntries($entries) + protected function jsonDecode(ResponseInterface $response) { - $i = 1; - - foreach ($entries as $pocketEntry) { - $url = isset($pocketEntry['resolved_url']) && $pocketEntry['resolved_url'] != '' ? $pocketEntry['resolved_url'] : $pocketEntry['given_url']; - - $existingEntry = $this->em - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($url, $this->user->getId()); - - if (false !== $existingEntry) { - ++$this->skippedEntries; - continue; - } - - $entry = new Entry($this->user); - $entry = $this->contentProxy->updateEntry($entry, $url); - - // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted - if ($pocketEntry['status'] == 1 || $this->markAsRead) { - $entry->setArchived(true); - } - - // 0 or 1 - 1 If the item is starred - if ($pocketEntry['favorite'] == 1) { - $entry->setStarred(true); - } - - $title = 'Untitled'; - if (isset($pocketEntry['resolved_title']) && $pocketEntry['resolved_title'] != '') { - $title = $pocketEntry['resolved_title']; - } elseif (isset($pocketEntry['given_title']) && $pocketEntry['given_title'] != '') { - $title = $pocketEntry['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($pocketEntry['has_image']) && $pocketEntry['has_image'] > 0 && isset($pocketEntry['images'][1])) { - $entry->setPreviewPicture($pocketEntry['images'][1]['src']); - } - - if (isset($pocketEntry['tags']) && !empty($pocketEntry['tags'])) { - $this->contentProxy->assignTagsToEntry( - $entry, - array_keys($pocketEntry['tags']) - ); - } - - $this->em->persist($entry); - ++$this->importedEntries; - - // flush every 20 entries - if (($i % 20) === 0) { - $this->em->flush(); - $this->em->clear($entry); - } - ++$i; + $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()); } - $this->em->flush(); + return $data; } }