3 namespace Wallabag\ImportBundle\Import
;
5 use Http\Client\Common\HttpMethodsClient
;
6 use Http\Client\Common\Plugin\ErrorPlugin
;
7 use Http\Client\Common\PluginClient
;
8 use Http\Client\HttpClient
;
9 use Http\Discovery\MessageFactoryDiscovery
;
10 use Http\Message\MessageFactory
;
11 use Http\Client\Exception\RequestException
;
12 use Wallabag\CoreBundle\Entity\Entry
;
13 use Psr\Http\Message\ResponseInterface
;
15 class PocketImport
extends AbstractImport
17 const NB_ELEMENTS
= 5000;
19 * @var HttpMethodsClient
25 * Only used for test purpose.
29 public function getAccessToken()
31 return $this->accessToken
;
37 public function getName()
45 public function getUrl()
47 return 'import_pocket';
53 public function getDescription()
55 return 'import.pocket.description';
59 * Return the oauth url to authenticate the client.
61 * @param string $redirectUri Redirect url in case of error
63 * @return string|false request_token for callback method
65 public function getRequestToken($redirectUri)
68 $response = $this->client
->post('https://getpocket.com/v3/oauth/request', [], json_encode([
69 'consumer_key' => $this->user
->getConfig()->getPocketConsumerKey(),
70 'redirect_uri' => $redirectUri,
72 } catch (RequestException
$e) {
73 $this->logger
->error(sprintf('PocketImport: Failed to request token: %s', $e->getMessage()), ['exception' => $e]);
78 return $this->jsonDecode($response)['code'];
82 * Usually called by the previous callback to authorize the client.
83 * Then it return a token that can be used for next requests.
85 * @param string $code request_token from getRequestToken
89 public function authorize($code)
93 $response = $this->client
->post('https://getpocket.com/v3/oauth/authorize', [], json_encode([
94 'consumer_key' => $this->user
->getConfig()->getPocketConsumerKey(),
97 } catch (RequestException
$e) {
98 $this->logger
->error(sprintf('PocketImport: Failed to authorize client: %s', $e->getMessage()), ['exception' => $e]);
103 $this->accessToken
= $this->jsonDecode($response)['access_token'];
111 public function import($offset = 0)
116 $response = $this->client
->post('https://getpocket.com/v3/get', [], json_encode([
117 'consumer_key' => $this->user
->getConfig()->getPocketConsumerKey(),
118 'access_token' => $this->accessToken
,
119 'detailType' => 'complete',
122 'count' => self
::NB_ELEMENTS
,
125 } catch (RequestException
$e) {
126 $this->logger
->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]);
131 $entries = $this->jsonDecode($response);
133 if ($this->producer
) {
134 $this->parseEntriesForProducer($entries['list']);
136 $this->parseEntries($entries['list']);
139 // if we retrieve exactly the amount of items requested it means we can get more
140 // re-call import and offset item by the amount previous received:
141 // - first call get 5k offset 0
142 // - second call get 5k offset 5k
144 if (self
::NB_ELEMENTS
=== \
count($entries['list'])) {
147 return $this->import(self
::NB_ELEMENTS
* $run);
154 * Set the Http client.
156 * @param HttpClient $client
157 * @param MessageFactory|null $messageFactory
159 public function setClient(HttpClient
$client, MessageFactory
$messageFactory = null)
161 $this->client
= new HttpMethodsClient(new PluginClient($client, [new ErrorPlugin()]), $messageFactory ?: MessageFactoryDiscovery
::find());
167 public function validateEntry(array $importedEntry)
169 if (empty($importedEntry['resolved_url']) && empty($importedEntry['given_url'])) {
179 * @see https://getpocket.com/developer/docs/v3/retrieve
181 public function parseEntry(array $importedEntry)
183 $url = isset($importedEntry['resolved_url']) && '' !== $importedEntry['resolved_url'] ? $importedEntry['resolved_url'] : $importedEntry['given_url'];
185 $existingEntry = $this->em
186 ->getRepository('WallabagCoreBundle:Entry')
187 ->findByUrlAndUserId($url, $this->user
->getId());
189 if (false !== $existingEntry) {
190 ++
$this->skippedEntries
;
195 $entry = new Entry($this->user
);
196 $entry->setUrl($url);
198 // update entry with content (in case fetching failed, the given entry will be return)
199 $this->fetchContent($entry, $url);
201 // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted
202 $entry->updateArchived(1 === (int) $importedEntry['status'] || $this->markAsRead
);
204 // 0 or 1 - 1 if the item is starred
205 $entry->setStarred(1 === (int) $importedEntry['favorite']);
208 if (isset($importedEntry['resolved_title']) && '' !== $importedEntry['resolved_title']) {
209 $title = $importedEntry['resolved_title'];
210 } elseif (isset($importedEntry['given_title']) && '' !== $importedEntry['given_title']) {
211 $title = $importedEntry['given_title'];
214 $entry->setTitle($title);
216 // 0, 1, or 2 - 1 if the item has images in it - 2 if the item is an image
217 if (isset($importedEntry['has_image']) && $importedEntry['has_image'] > 0 && isset($importedEntry['images'][1])) {
218 $entry->setPreviewPicture($importedEntry['images'][1]['src']);
221 if (isset($importedEntry['tags']) && !empty($importedEntry['tags'])) {
222 $this->tagsAssigner
->assignTagsToEntry(
224 array_keys($importedEntry['tags']),
225 $this->em
->getUnitOfWork()->getScheduledEntityInsertions()
229 if (!empty($importedEntry['time_added'])) {
230 $entry->setCreatedAt((new \
DateTime())->setTimestamp($importedEntry['time_added']));
233 $this->em
->persist($entry);
234 ++
$this->importedEntries
;
242 protected function setEntryAsRead(array $importedEntry)
244 $importedEntry['status'] = '1';
246 return $importedEntry;
249 protected function jsonDecode(ResponseInterface
$response)
251 $data = \
json_decode((string) $response->getBody(), true);
253 if (JSON_ERROR_NONE
!== json_last_error()) {
254 throw new \
InvalidArgumentException('Unable to parse JSON data: ' . json_last_error_msg());