]> git.immae.eu Git - github/wallabag/wallabag.git/blame - src/Wallabag/ImportBundle/Import/PocketImport.php
Add more importer to wallabag:import command
[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;
ff7b031d 11
19d9efab 12class PocketImport extends AbstractImport
ff7b031d 13{
8eedc8cf 14 private $client;
02f64895
JB
15 private $accessToken;
16
17 const NB_ELEMENTS = 5000;
ff7b031d 18
02f64895 19 /**
3849a9f3 20 * Only used for test purpose.
02f64895
JB
21 *
22 * @return string
23 */
24 public function getAccessToken()
25 {
26 return $this->accessToken;
27 }
28
0aa344dc
JB
29 /**
30 * {@inheritdoc}
31 */
d51b38ed
NL
32 public function getName()
33 {
34 return 'Pocket';
35 }
36
7019c7cf
JB
37 /**
38 * {@inheritdoc}
39 */
40 public function getUrl()
41 {
42 return 'import_pocket';
43 }
44
0aa344dc
JB
45 /**
46 * {@inheritdoc}
47 */
d51b38ed
NL
48 public function getDescription()
49 {
0d42217e 50 return 'import.pocket.description';
d51b38ed
NL
51 }
52
ff7b031d 53 /**
252ebd60
JB
54 * Return the oauth url to authenticate the client.
55 *
56 * @param string $redirectUri Redirect url in case of error
57 *
4d0ec0e7 58 * @return string|false request_token for callback method
7ec2897e 59 */
252ebd60 60 public function getRequestToken($redirectUri)
7ec2897e
JB
61 {
62 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/request',
63 [
64 'body' => json_encode([
ebe0787e 65 'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
7ec2897e
JB
66 'redirect_uri' => $redirectUri,
67 ]),
68 ]
69 );
70
252ebd60
JB
71 try {
72 $response = $this->client->send($request);
73 } catch (RequestException $e) {
74 $this->logger->error(sprintf('PocketImport: Failed to request token: %s', $e->getMessage()), ['exception' => $e]);
7ec2897e 75
252ebd60
JB
76 return false;
77 }
7ec2897e 78
252ebd60 79 return $response->json()['code'];
7ec2897e
JB
80 }
81
82 /**
252ebd60
JB
83 * Usually called by the previous callback to authorize the client.
84 * Then it return a token that can be used for next requests.
85 *
86 * @param string $code request_token from getRequestToken
87 *
88 * @return bool
7ec2897e 89 */
252ebd60 90 public function authorize($code)
7ec2897e
JB
91 {
92 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize',
93 [
94 'body' => json_encode([
ebe0787e 95 'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
252ebd60 96 'code' => $code,
7ec2897e
JB
97 ]),
98 ]
99 );
100
252ebd60
JB
101 try {
102 $response = $this->client->send($request);
103 } catch (RequestException $e) {
104 $this->logger->error(sprintf('PocketImport: Failed to authorize client: %s', $e->getMessage()), ['exception' => $e]);
7ec2897e 105
252ebd60
JB
106 return false;
107 }
108
109 $this->accessToken = $response->json()['access_token'];
110
111 return true;
7ec2897e
JB
112 }
113
114 /**
115 * {@inheritdoc}
116 */
02f64895 117 public function import($offset = 0)
7ec2897e 118 {
02f64895
JB
119 static $run = 0;
120
7ec2897e
JB
121 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/get',
122 [
123 'body' => json_encode([
ebe0787e 124 'consumer_key' => $this->user->getConfig()->getPocketConsumerKey(),
252ebd60 125 'access_token' => $this->accessToken,
7ec2897e
JB
126 'detailType' => 'complete',
127 'state' => 'all',
02f64895
JB
128 'sort' => 'newest',
129 'count' => self::NB_ELEMENTS,
130 'offset' => $offset,
7ec2897e
JB
131 ]),
132 ]
133 );
134
252ebd60
JB
135 try {
136 $response = $this->client->send($request);
137 } catch (RequestException $e) {
138 $this->logger->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]);
139
140 return false;
141 }
142
7ec2897e
JB
143 $entries = $response->json();
144
ef75e122
JB
145 if ($this->producer) {
146 $this->parseEntriesForProducer($entries['list']);
02f64895
JB
147 } else {
148 $this->parseEntries($entries['list']);
ef75e122
JB
149 }
150
02f64895
JB
151 // if we retrieve exactly the amount of items requested it means we can get more
152 // re-call import and offset item by the amount previous received:
153 // - first call get 5k offset 0
154 // - second call get 5k offset 5k
155 // - and so on
156 if (count($entries['list']) === self::NB_ELEMENTS) {
157 ++$run;
158
159 return $this->import(self::NB_ELEMENTS * $run);
160 }
7ec2897e 161
252ebd60 162 return true;
7ec2897e
JB
163 }
164
87f23b00 165 /**
252ebd60 166 * Set the Guzzle client.
87f23b00 167 *
252ebd60 168 * @param Client $client
87f23b00 169 */
252ebd60 170 public function setClient(Client $client)
87f23b00 171 {
252ebd60 172 $this->client = $client;
dda57bb9
NL
173 }
174
6d65c0a8
JB
175 /**
176 * {@inheritdoc}
177 *
178 * @see https://getpocket.com/developer/docs/v3/retrieve
179 */
c98db1b6 180 public function parseEntry(array $importedEntry)
ef75e122 181 {
c98db1b6 182 $url = isset($importedEntry['resolved_url']) && $importedEntry['resolved_url'] != '' ? $importedEntry['resolved_url'] : $importedEntry['given_url'];
252ebd60 183
ef75e122
JB
184 $existingEntry = $this->em
185 ->getRepository('WallabagCoreBundle:Entry')
186 ->findByUrlAndUserId($url, $this->user->getId());
87f23b00 187
ef75e122
JB
188 if (false !== $existingEntry) {
189 ++$this->skippedEntries;
ff7b031d 190
ef75e122
JB
191 return;
192 }
ff7b031d 193
ef75e122 194 $entry = new Entry($this->user);
59b97fae 195 $entry->setUrl($url);
ff7b031d 196
59b97fae
JB
197 // update entry with content (in case fetching failed, the given entry will be return)
198 $entry = $this->fetchContent($entry, $url);
56c778b4 199
ef75e122 200 // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted
59b97fae 201 $entry->setArchived($importedEntry['status'] == 1 || $this->markAsRead);
7019c7cf 202
ef75e122 203 // 0 or 1 - 1 If the item is starred
59b97fae 204 $entry->setStarred($importedEntry['favorite'] == 1);
56c778b4 205
ef75e122 206 $title = 'Untitled';
c98db1b6
JB
207 if (isset($importedEntry['resolved_title']) && $importedEntry['resolved_title'] != '') {
208 $title = $importedEntry['resolved_title'];
209 } elseif (isset($importedEntry['given_title']) && $importedEntry['given_title'] != '') {
210 $title = $importedEntry['given_title'];
ff7b031d
NL
211 }
212
ef75e122 213 $entry->setTitle($title);
ef75e122
JB
214
215 // 0, 1, or 2 - 1 if the item has images in it - 2 if the item is an image
c98db1b6
JB
216 if (isset($importedEntry['has_image']) && $importedEntry['has_image'] > 0 && isset($importedEntry['images'][1])) {
217 $entry->setPreviewPicture($importedEntry['images'][1]['src']);
ef75e122
JB
218 }
219
c98db1b6 220 if (isset($importedEntry['tags']) && !empty($importedEntry['tags'])) {
ef75e122
JB
221 $this->contentProxy->assignTagsToEntry(
222 $entry,
40113585
JB
223 array_keys($importedEntry['tags']),
224 $this->em->getUnitOfWork()->getScheduledEntityInsertions()
ef75e122
JB
225 );
226 }
227
7f753117
JB
228 if (!empty($importedEntry['time_added'])) {
229 $entry->setCreatedAt((new \DateTime())->setTimestamp($importedEntry['time_added']));
230 }
231
ef75e122
JB
232 $this->em->persist($entry);
233 ++$this->importedEntries;
56c778b4 234
ef75e122
JB
235 return $entry;
236 }
237
238 /**
3849a9f3 239 * {@inheritdoc}
ef75e122 240 */
3849a9f3 241 protected function setEntryAsRead(array $importedEntry)
ef75e122 242 {
13470c35 243 $importedEntry['status'] = '1';
ef75e122 244
3849a9f3 245 return $importedEntry;
ff7b031d 246 }
ff7b031d 247}