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