]> git.immae.eu Git - github/wallabag/wallabag.git/blob - src/Wallabag/ImportBundle/Import/PocketImport.php
Merge pull request #1642 from wallabag/v2-escape-preview
[github/wallabag/wallabag.git] / src / Wallabag / ImportBundle / Import / PocketImport.php
1 <?php
2
3 namespace Wallabag\ImportBundle\Import;
4
5 use Psr\Log\LoggerInterface;
6 use Psr\Log\NullLogger;
7 use Doctrine\ORM\EntityManager;
8 use GuzzleHttp\Client;
9 use GuzzleHttp\Exception\RequestException;
10 use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
11 use Wallabag\CoreBundle\Entity\Entry;
12 use Wallabag\CoreBundle\Entity\Tag;
13 use Wallabag\CoreBundle\Helper\ContentProxy;
14 use Craue\ConfigBundle\Util\Config;
15
16 class PocketImport implements ImportInterface
17 {
18 private $user;
19 private $em;
20 private $contentProxy;
21 private $logger;
22 private $client;
23 private $consumerKey;
24 private $skippedEntries = 0;
25 private $importedEntries = 0;
26 protected $accessToken;
27
28 public function __construct(TokenStorageInterface $tokenStorage, EntityManager $em, ContentProxy $contentProxy, Config $craueConfig)
29 {
30 $this->user = $tokenStorage->getToken()->getUser();
31 $this->em = $em;
32 $this->contentProxy = $contentProxy;
33 $this->consumerKey = $craueConfig->get('pocket_consumer_key');
34 $this->logger = new NullLogger();
35 }
36
37 public function setLogger(LoggerInterface $logger)
38 {
39 $this->logger = $logger;
40 }
41
42 /**
43 * {@inheritdoc}
44 */
45 public function getName()
46 {
47 return 'Pocket';
48 }
49
50 /**
51 * {@inheritdoc}
52 */
53 public function getUrl()
54 {
55 return 'import_pocket';
56 }
57
58 /**
59 * {@inheritdoc}
60 */
61 public function getDescription()
62 {
63 return 'This importer will import all your Pocket data. Pocket doesn\'t allow us to retrieve content from their service, so the readable content of each article will be re-fetched by wallabag.';
64 }
65
66 /**
67 * Return the oauth url to authenticate the client.
68 *
69 * @param string $redirectUri Redirect url in case of error
70 *
71 * @return string request_token for callback method
72 */
73 public function getRequestToken($redirectUri)
74 {
75 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/request',
76 [
77 'body' => json_encode([
78 'consumer_key' => $this->consumerKey,
79 'redirect_uri' => $redirectUri,
80 ]),
81 ]
82 );
83
84 try {
85 $response = $this->client->send($request);
86 } catch (RequestException $e) {
87 $this->logger->error(sprintf('PocketImport: Failed to request token: %s', $e->getMessage()), ['exception' => $e]);
88
89 return false;
90 }
91
92 return $response->json()['code'];
93 }
94
95 /**
96 * Usually called by the previous callback to authorize the client.
97 * Then it return a token that can be used for next requests.
98 *
99 * @param string $code request_token from getRequestToken
100 *
101 * @return bool
102 */
103 public function authorize($code)
104 {
105 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/oauth/authorize',
106 [
107 'body' => json_encode([
108 'consumer_key' => $this->consumerKey,
109 'code' => $code,
110 ]),
111 ]
112 );
113
114 try {
115 $response = $this->client->send($request);
116 } catch (RequestException $e) {
117 $this->logger->error(sprintf('PocketImport: Failed to authorize client: %s', $e->getMessage()), ['exception' => $e]);
118
119 return false;
120 }
121
122 $this->accessToken = $response->json()['access_token'];
123
124 return true;
125 }
126
127 /**
128 * {@inheritdoc}
129 */
130 public function import()
131 {
132 $request = $this->client->createRequest('POST', 'https://getpocket.com/v3/get',
133 [
134 'body' => json_encode([
135 'consumer_key' => $this->consumerKey,
136 'access_token' => $this->accessToken,
137 'detailType' => 'complete',
138 'state' => 'all',
139 'sort' => 'oldest',
140 ]),
141 ]
142 );
143
144 try {
145 $response = $this->client->send($request);
146 } catch (RequestException $e) {
147 $this->logger->error(sprintf('PocketImport: Failed to import: %s', $e->getMessage()), ['exception' => $e]);
148
149 return false;
150 }
151
152 $entries = $response->json();
153
154 $this->parseEntries($entries['list']);
155
156 return true;
157 }
158
159 /**
160 * {@inheritdoc}
161 */
162 public function getSummary()
163 {
164 return [
165 'skipped' => $this->skippedEntries,
166 'imported' => $this->importedEntries,
167 ];
168 }
169
170 /**
171 * Set the Guzzle client.
172 *
173 * @param Client $client
174 */
175 public function setClient(Client $client)
176 {
177 $this->client = $client;
178 }
179
180 private function assignTagsToEntry(Entry $entry, $tags)
181 {
182 foreach ($tags as $tag) {
183 $label = trim($tag['tag']);
184 $tagEntity = $this->em
185 ->getRepository('WallabagCoreBundle:Tag')
186 ->findOneByLabel($label);
187
188 if (is_object($tagEntity)) {
189 $entry->addTag($tagEntity);
190 } else {
191 $newTag = new Tag();
192 $newTag->setLabel($label);
193
194 $entry->addTag($newTag);
195 }
196 $this->em->flush();
197 }
198 }
199
200 /**
201 * @see https://getpocket.com/developer/docs/v3/retrieve
202 *
203 * @param $entries
204 */
205 private function parseEntries($entries)
206 {
207 $i = 1;
208
209 foreach ($entries as $pocketEntry) {
210 $url = isset($pocketEntry['resolved_url']) && $pocketEntry['resolved_url'] != '' ? $pocketEntry['resolved_url'] : $pocketEntry['given_url'];
211
212 $existingEntry = $this->em
213 ->getRepository('WallabagCoreBundle:Entry')
214 ->findByUrlAndUserId($url, $this->user->getId());
215
216 if (false !== $existingEntry) {
217 ++$this->skippedEntries;
218 continue;
219 }
220
221 $entry = new Entry($this->user);
222 $entry = $this->contentProxy->updateEntry($entry, $url);
223
224 // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted
225 if ($pocketEntry['status'] == 1) {
226 $entry->setArchived(true);
227 }
228
229 // 0 or 1 - 1 If the item is favorited
230 if ($pocketEntry['favorite'] == 1) {
231 $entry->setStarred(true);
232 }
233
234 $title = 'Untitled';
235 if (isset($pocketEntry['resolved_title']) && $pocketEntry['resolved_title'] != '') {
236 $title = $pocketEntry['resolved_title'];
237 } elseif (isset($pocketEntry['given_title']) && $pocketEntry['given_title'] != '') {
238 $title = $pocketEntry['given_title'];
239 }
240
241 $entry->setTitle($title);
242
243 // 0, 1, or 2 - 1 if the item has images in it - 2 if the item is an image
244 if (isset($pocketEntry['has_image']) && $pocketEntry['has_image'] > 0 && isset($pocketEntry['images'][1])) {
245 $entry->setPreviewPicture($pocketEntry['images'][1]['src']);
246 }
247
248 if (isset($pocketEntry['tags']) && !empty($pocketEntry['tags'])) {
249 $this->assignTagsToEntry($entry, $pocketEntry['tags']);
250 }
251
252 $this->em->persist($entry);
253 ++$this->importedEntries;
254
255 // flush every 20 entries
256 if (($i % 20) === 0) {
257 $this->em->flush();
258 }
259 ++$i;
260 }
261
262 $this->em->flush();
263 }
264 }