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