From 252ebd60719d32ec954d0519c9edf2b52b03310c Mon Sep 17 00:00:00 2001 From: Jeremy Benoist Date: Wed, 30 Dec 2015 12:23:51 +0100 Subject: Rewrote Pocket Import For the moment, we won't do a queue system, just a plain synchronous import. We also use ContentProxy to grab content for each article from Pocket. Error from Pocket are now logged using the logger. The ImportInterface need to be simple and not related to oAuth (not all import will use that method). --- .../ImportBundle/Import/ImportInterface.php | 29 ++-- src/Wallabag/ImportBundle/Import/PocketImport.php | 154 ++++++++++++--------- 2 files changed, 97 insertions(+), 86 deletions(-) (limited to 'src/Wallabag/ImportBundle/Import') diff --git a/src/Wallabag/ImportBundle/Import/ImportInterface.php b/src/Wallabag/ImportBundle/Import/ImportInterface.php index 0f9b3256..8cf238aa 100644 --- a/src/Wallabag/ImportBundle/Import/ImportInterface.php +++ b/src/Wallabag/ImportBundle/Import/ImportInterface.php @@ -2,7 +2,9 @@ namespace Wallabag\ImportBundle\Import; -interface ImportInterface +use Psr\Log\LoggerAwareInterface; + +interface ImportInterface extends LoggerAwareInterface { /** * Name of the import. @@ -19,27 +21,18 @@ interface ImportInterface public function getDescription(); /** - * Return the oauth url to authenticate the client. - * - * @param string $redirectUri Redirect url in case of error - * @param string $callbackUri Url when the authentication is complete - * - * @return string - */ - public function oAuthRequest($redirectUri, $callbackUri); - - /** - * Usually called by the previous callback to authorize the client. - * Then it return a token that can be used for next requests. + * Import content using the user token. * - * @return string + * @return bool */ - public function oAuthAuthorize(); + public function import(); /** - * Import content using the user token. + * Return an array with summary info about the import, with keys: + * - skipped + * - imported. * - * @param string $accessToken User access token + * @return array */ - public function import($accessToken); + public function getSummary(); } diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index e5c86f07..1710d9d3 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -2,29 +2,39 @@ namespace Wallabag\ImportBundle\Import; +use Psr\Log\LoggerInterface; +use Psr\Log\NullLogger; use Doctrine\ORM\EntityManager; use GuzzleHttp\Client; -use Symfony\Component\HttpFoundation\Session\Session; +use GuzzleHttp\Exception\RequestException; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; -use Wallabag\CoreBundle\Tools\Utils; +use Wallabag\CoreBundle\Helper\ContentProxy; class PocketImport implements ImportInterface { private $user; - private $session; private $em; + private $contentProxy; + private $logger; private $consumerKey; private $skippedEntries = 0; private $importedEntries = 0; + protected $accessToken; - public function __construct(TokenStorageInterface $tokenStorage, Session $session, EntityManager $em, $consumerKey) + public function __construct(TokenStorageInterface $tokenStorage, EntityManager $em, ContentProxy $contentProxy, $consumerKey) { $this->user = $tokenStorage->getToken()->getUser(); - $this->session = $session; $this->em = $em; + $this->contentProxy = $contentProxy; $this->consumerKey = $consumerKey; + $this->logger = new NullLogger(); + } + + public function setLogger(LoggerInterface $logger) + { + $this->logger = $logger; } /** @@ -44,9 +54,13 @@ class PocketImport implements ImportInterface } /** - * {@inheritdoc} + * Return the oauth url to authenticate the client. + * + * @param string $redirectUri Redirect url in case of error + * + * @return string request_token for callback method */ - public function oAuthRequest($redirectUri, $callbackUri) + public function getRequestToken($redirectUri) { $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/request', [ @@ -57,44 +71,59 @@ class PocketImport implements ImportInterface ] ); - $response = $this->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']; } /** - * {@inheritdoc} + * 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 oAuthAuthorize() + public function authorize($code) { $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize', [ 'body' => json_encode([ 'consumer_key' => $this->consumerKey, - 'code' => $this->session->get('pocketCode'), + 'code' => $code, ]), ] ); - $response = $this->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; } /** * {@inheritdoc} */ - public function import($accessToken) + public function import() { $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/get', [ 'body' => json_encode([ 'consumer_key' => $this->consumerKey, - 'access_token' => $accessToken, + 'access_token' => $this->accessToken, 'detailType' => 'complete', 'state' => 'all', 'sort' => 'oldest', @@ -102,61 +131,45 @@ class PocketImport implements ImportInterface ] ); - $response = $this->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']); - $this->session->getFlashBag()->add( - 'notice', - $this->importedEntries.' entries imported, '.$this->skippedEntries.' already saved.' - ); + return true; } /** - * Set the Guzzle client. - * - * @param Client $client + * {@inheritdoc} */ - public function setClient(Client $client) + public function getSummary() { - $this->client = $client; + return [ + 'skipped' => $this->skippedEntries, + 'imported' => $this->importedEntries, + ]; } /** - * Returns the good title for current entry. - * - * @param $pocketEntry + * Set the Guzzle client. * - * @return string + * @param Client $client */ - private function guessTitle($pocketEntry) + public function setClient(Client $client) { - if (isset($pocketEntry['resolved_title']) && $pocketEntry['resolved_title'] != '') { - return $pocketEntry['resolved_title']; - } elseif (isset($pocketEntry['given_title']) && $pocketEntry['given_title'] != '') { - return $pocketEntry['given_title']; - } - - return 'Untitled'; + $this->client = $client; } /** - * Returns the good URL for current entry. - * - * @param $pocketEntry - * - * @return string + * @todo move that in a more global place */ - private function guessURL($pocketEntry) - { - if (isset($pocketEntry['resolved_url']) && $pocketEntry['resolved_url'] != '') { - return $pocketEntry['resolved_url']; - } - - return $pocketEntry['given_url']; - } - private function assignTagsToEntry(Entry $entry, $tags) { foreach ($tags as $tag) { @@ -177,13 +190,16 @@ class PocketImport implements ImportInterface } /** + * @see https://getpocket.com/developer/docs/v3/retrieve + * * @param $entries */ private function parsePocketEntries($entries) { foreach ($entries as $pocketEntry) { $entry = new Entry($this->user); - $url = $this->guessURL($pocketEntry); + + $url = isset($pocketEntry['resolved_url']) && $pocketEntry['resolved_url'] != '' ? $pocketEntry['resolved_url'] : $pocketEntry['given_url']; $existingEntry = $this->em ->getRepository('WallabagCoreBundle:Entry') @@ -194,31 +210,33 @@ class PocketImport implements ImportInterface continue; } - $entry->setUrl($url); - $entry->setDomainName(parse_url($url, PHP_URL_HOST)); + $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) { $entry->setArchived(true); } + + // 0 or 1 - 1 If the item is favorited if ($pocketEntry['favorite'] == 1) { $entry->setStarred(true); } - $entry->setTitle($this->guessTitle($pocketEntry)); - - if (isset($pocketEntry['excerpt'])) { - $entry->setContent($pocketEntry['excerpt']); + $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']; } - if (isset($pocketEntry['has_image']) && $pocketEntry['has_image'] > 0) { - $entry->setPreviewPicture($pocketEntry['image']['src']); - } + $entry->setTitle($title); - if (isset($pocketEntry['word_count'])) { - $entry->setReadingTime(Utils::convertWordsToMinutes($pocketEntry['word_count'])); + // 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 (!empty($pocketEntry['tags'])) { + if (isset($pocketEntry['tags']) && !empty($pocketEntry['tags'])) { $this->assignTagsToEntry($entry, $pocketEntry['tags']); } -- cgit v1.2.3