]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/ImportBundle/Import/PocketImport.php
Retrieve all items from Pocket
[github/wallabag/wallabag.git] / src / Wallabag / ImportBundle / Import / PocketImport.php
CommitLineData
ff7b031d
NL
1<?php
2
3namespace Wallabag\ImportBundle\Import;
4
252ebd60 5use Psr\Log\NullLogger;
ff7b031d
NL
6use Doctrine\ORM\EntityManager;
7use GuzzleHttp\Client;
252ebd60 8use GuzzleHttp\Exception\RequestException;
ff7b031d 9use Wallabag\CoreBundle\Entity\Entry;
252ebd60 10use Wallabag\CoreBundle\Helper\ContentProxy;
63e40f2d 11use Craue\ConfigBundle\Util\Config;
ff7b031d 12
19d9efab 13class PocketImport extends AbstractImport
ff7b031d 14{
8eedc8cf 15 private $client;
ff7b031d 16 private $consumerKey;
303768df
NL
17 private $skippedEntries = 0;
18 private $importedEntries = 0;
02f64895
JB
19 private $accessToken;
20
21 const NB_ELEMENTS = 5000;
ff7b031d 22
ef75e122 23 public function __construct(EntityManager $em, ContentProxy $contentProxy, Config $craueConfig)
ff7b031d 24 {
ff7b031d 25 $this->em = $em;
252ebd60 26 $this->contentProxy = $contentProxy;
63e40f2d 27 $this->consumerKey = $craueConfig->get('pocket_consumer_key');
252ebd60 28 $this->logger = new NullLogger();
ef75e122
JB
29 }
30
02f64895
JB
31 /**
32 * Only used for test purpose
33 *
34 * @return string
35 */
36 public function getAccessToken()
37 {
38 return $this->accessToken;
39 }
40
0aa344dc
JB
41 /**
42 * {@inheritdoc}
43 */
d51b38ed
NL
44 public function getName()
45 {
46 return 'Pocket';
47 }
48
7019c7cf
JB
49 /**
50 * {@inheritdoc}
51 */
52 public function getUrl()
53 {
54 return 'import_pocket';
55 }
56
0aa344dc
JB
57 /**
58 * {@inheritdoc}
59 */
d51b38ed
NL
60 public function getDescription()
61 {
0d42217e 62 return 'import.pocket.description';
d51b38ed
NL
63 }
64
ff7b031d 65 /**
252ebd60
JB
66 * Return the oauth url to authenticate the client.
67 *
68 * @param string $redirectUri Redirect url in case of error
69 *
4d0ec0e7 70 * @return string|false request_token for callback method
7ec2897e 71 */
252ebd60 72 public function getRequestToken($redirectUri)
7ec2897e
JB
73 {
74 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/request',
75 [
76 'body' => json_encode([
77 'consumer_key' => $this->consumerKey,
78 'redirect_uri' => $redirectUri,
79 ]),
80 ]
81 );
82
252ebd60
JB
83 try {
84 $response = $this->client->send($request);
85 } catch (RequestException $e) {
86 $this->logger->error(sprintf('PocketImport: Failed to request token: %s', $e->getMessage()), ['exception' => $e]);
7ec2897e 87
252ebd60
JB
88 return false;
89 }
7ec2897e 90
252ebd60 91 return $response->json()['code'];
7ec2897e
JB
92 }
93
94 /**
252ebd60
JB
95 * Usually called by the previous callback to authorize the client.
96 * Then it return a token that can be used for next requests.
97 *
98 * @param string $code request_token from getRequestToken
99 *
100 * @return bool
7ec2897e 101 */
252ebd60 102 public function authorize($code)
7ec2897e
JB
103 {
104 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize',
105 [
106 'body' => json_encode([
107 'consumer_key' => $this->consumerKey,
252ebd60 108 'code' => $code,
7ec2897e
JB
109 ]),
110 ]
111 );
112
252ebd60
JB
113 try {
114 $response = $this->client->send($request);
115 } catch (RequestException $e) {
116 $this->logger->error(sprintf('PocketImport: Failed to authorize client: %s', $e->getMessage()), ['exception' => $e]);
7ec2897e 117
252ebd60
JB
118 return false;
119 }
120
121 $this->accessToken = $response->json()['access_token'];
122
123 return true;
7ec2897e
JB
124 }
125
126 /**
127 * {@inheritdoc}
128 */
02f64895 129 public function import($offset = 0)
7ec2897e 130 {
02f64895
JB
131 static $run = 0;
132
7ec2897e
JB
133 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/get',
134 [
135 'body' => json_encode([
136 'consumer_key' => $this->consumerKey,
252ebd60 137 'access_token' => $this->accessToken,
7ec2897e
JB
138 'detailType' => 'complete',
139 'state' => 'all',
02f64895
JB
140 'sort' => 'newest',
141 'count' => self::NB_ELEMENTS,
142 'offset' => $offset,
7ec2897e
JB
143 ]),
144 ]
145 );
146
252ebd60
JB
147 try {
148 $response = $this->client->send($request);
149 } catch (RequestException $e) {
150 $this->logger->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]);
151
152 return false;
153 }
154
7ec2897e
JB
155 $entries = $response->json();
156
ef75e122
JB
157 if ($this->producer) {
158 $this->parseEntriesForProducer($entries['list']);
02f64895
JB
159 } else {
160 $this->parseEntries($entries['list']);
ef75e122
JB
161 }
162
02f64895
JB
163 // if we retrieve exactly the amount of items requested it means we can get more
164 // re-call import and offset item by the amount previous received:
165 // - first call get 5k offset 0
166 // - second call get 5k offset 5k
167 // - and so on
168 if (count($entries['list']) === self::NB_ELEMENTS) {
169 ++$run;
170
171 return $this->import(self::NB_ELEMENTS * $run);
172 }
7ec2897e 173
252ebd60 174 return true;
7ec2897e
JB
175 }
176
177 /**
252ebd60 178 * {@inheritdoc}
ff7b031d 179 */
252ebd60 180 public function getSummary()
ff7b031d 181 {
252ebd60
JB
182 return [
183 'skipped' => $this->skippedEntries,
184 'imported' => $this->importedEntries,
185 ];
ff7b031d
NL
186 }
187
87f23b00 188 /**
252ebd60 189 * Set the Guzzle client.
87f23b00 190 *
252ebd60 191 * @param Client $client
87f23b00 192 */
252ebd60 193 public function setClient(Client $client)
87f23b00 194 {
252ebd60 195 $this->client = $client;
dda57bb9
NL
196 }
197
c98db1b6 198 public function parseEntry(array $importedEntry)
ef75e122 199 {
c98db1b6 200 $url = isset($importedEntry['resolved_url']) && $importedEntry['resolved_url'] != '' ? $importedEntry['resolved_url'] : $importedEntry['given_url'];
252ebd60 201
ef75e122
JB
202 $existingEntry = $this->em
203 ->getRepository('WallabagCoreBundle:Entry')
204 ->findByUrlAndUserId($url, $this->user->getId());
87f23b00 205
ef75e122
JB
206 if (false !== $existingEntry) {
207 ++$this->skippedEntries;
ff7b031d 208
ef75e122
JB
209 return;
210 }
ff7b031d 211
ef75e122
JB
212 $entry = new Entry($this->user);
213 $entry = $this->fetchContent($entry, $url);
ff7b031d 214
ef75e122
JB
215 // jump to next entry in case of problem while getting content
216 if (false === $entry) {
217 ++$this->skippedEntries;
ff7b031d 218
ef75e122
JB
219 return;
220 }
56c778b4 221
ef75e122 222 // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted
c98db1b6 223 if ($importedEntry['status'] == 1 || $this->markAsRead) {
ef75e122
JB
224 $entry->setArchived(true);
225 }
7019c7cf 226
ef75e122 227 // 0 or 1 - 1 If the item is starred
c98db1b6 228 if ($importedEntry['favorite'] == 1) {
ef75e122
JB
229 $entry->setStarred(true);
230 }
56c778b4 231
ef75e122 232 $title = 'Untitled';
c98db1b6
JB
233 if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] != '') {
234 $title = $importedEntry['resolved_title'];
235 } elseif (isset($importedEntry['given_title']) && $importedEntry['given_title'] != '') {
236 $title = $importedEntry['given_title'];
ff7b031d
NL
237 }
238
ef75e122
JB
239 $entry->setTitle($title);
240 $entry->setUrl($url);
241
242 // 0, 1, or 2 - 1 if the item has images in it - 2 if the item is an image
c98db1b6
JB
243 if (isset($importedEntry['has_image']) && $importedEntry['has_image'] > 0 && isset($importedEntry['images'][1])) {
244 $entry->setPreviewPicture($importedEntry['images'][1]['src']);
ef75e122
JB
245 }
246
c98db1b6 247 if (isset($importedEntry['tags']) && !empty($importedEntry['tags'])) {
ef75e122
JB
248 $this->contentProxy->assignTagsToEntry(
249 $entry,
c98db1b6 250 array_keys($importedEntry['tags'])
ef75e122
JB
251 );
252 }
253
254 $this->em->persist($entry);
255 ++$this->importedEntries;
56c778b4 256
ef75e122
JB
257 return $entry;
258 }
259
260 /**
261 * Faster parse entries for Producer.
262 * We don't care to make check at this time. They'll be done by the consumer.
263 *
264 * @param array $entries
265 */
266 public function parseEntriesForProducer($entries)
267 {
c98db1b6 268 foreach ($entries as $importedEntry) {
ef75e122 269 // set userId for the producer (it won't know which user is connected)
c98db1b6 270 $importedEntry['userId'] = $this->user->getId();
ef75e122
JB
271
272 if ($this->markAsRead) {
c98db1b6 273 $importedEntry['status'] = 1;
56c778b4 274 }
ef75e122
JB
275
276 ++$this->importedEntries;
277
c98db1b6 278 $this->producer->publish(json_encode($importedEntry));
56c778b4 279 }
ff7b031d 280 }
ff7b031d 281}