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