summaryrefslogtreecommitdiffstats
path: root/service/feedservice.php
blob: cb8d4f7cc83918f98ee04d98c14d65edf8ecf552 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
<?php
/**
 * ownCloud - News
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Alessandro Cosentino <cosenal@gmail.com>
 * @author Bernhard Posselt <dev@bernhard-posselt.com>
 * @copyright Alessandro Cosentino 2012
 * @copyright Bernhard Posselt 2012, 2014
 */

namespace OCA\News\Service;

use \OCP\ILogger;
use \OCP\IL10N;
use \OCP\AppFramework\Db\DoesNotExistException;

use \OCA\News\Db\Feed;
use \OCA\News\Db\Item;
use \OCA\News\Db\FeedMapper;
use \OCA\News\Db\ItemMapper;
use \OCA\News\Fetcher\Fetcher;
use \OCA\News\Fetcher\FetcherException;
use \OCA\News\ArticleEnhancer\Enhancer;
use \OCA\News\Utility\Config;


class FeedService extends Service {

	private $feedFetcher;
	private $itemMapper;
	private $feedMapper;
	private $logger;
	private $l10n;
	private $timeFactory;
	private $autoPurgeMinimumInterval;
	private $enhancer;
	private $purifier;
	private $loggerParams;

	public function __construct(FeedMapper $feedMapper,
	                            Fetcher $feedFetcher,
		                        ItemMapper $itemMapper,
		                        ILogger $logger,
		                        IL10N $l10n,
		                        $timeFactory,
		                        Config $config,
		                        Enhancer $enhancer,
		                        $purifier,
		                        $loggerParams){
		parent::__construct($feedMapper);
		$this->feedFetcher = $feedFetcher;
		$this->itemMapper = $itemMapper;
		$this->logger = $logger;
		$this->l10n = $l10n;
		$this->timeFactory = $timeFactory;
		$this->autoPurgeMinimumInterval = $config->getAutoPurgeMinimumInterval();
		$this->enhancer = $enhancer;
		$this->purifier = $purifier;
		$this->feedMapper = $feedMapper;
		$this->loggerParams = $loggerParams;
	}

	/**
	 * Finds all feeds of a user
	 * @param string $userId the name of the user
	 * @return Feed[]
	 */
	public function findAll($userId){
		return $this->feedMapper->findAllFromUser($userId);
	}


	/**
	 * Finds all feeds from all users
	 * @return array of feeds
	 */
	public function findAllFromAllUsers() {
		return $this->feedMapper->findAll();
	}


	/**
	 * Creates a new feed
	 * @param string $feedUrl the url to the feed
	 * @param int $folderId the folder where it should be put into, 0 for root folder
	 * @param string $userId for which user the feed should be created
	 * @param string $title if given, this is used for the opml feed title
	 * @throws ServiceConflictException if the feed exists already
	 * @throws ServiceNotFoundException if the url points to an invalid feed
	 * @return Feed the newly created feed
	 */
	public function create($feedUrl, $folderId, $userId, $title=null){
		// first try if the feed exists already
		try {
			list($feed, $items) = $this->feedFetcher->fetch($feedUrl);

			// try again if feed exists depending on the reported link
			try {
				$this->feedMapper->findByUrlHash($feed->getUrlHash(), $userId);
				throw new ServiceConflictException(
					$this->l10n->t('Can not add feed: Exists already'));

			// If no matching feed was found everything was ok
			} catch(DoesNotExistException $ex){}

			// insert feed
			$feed->setFolderId($folderId);
			$feed->setUserId($userId);
			$feed->setArticlesPerUpdate(count($items));

			if ($title) {
				$feed->setTitle($title);
			}

			$feed = $this->feedMapper->insert($feed);

			// insert items in reverse order because the first one is usually the
			// newest item
			$unreadCount = 0;
			for($i=count($items)-1; $i>=0; $i--){
				$item = $items[$i];
				$item->setFeedId($feed->getId());

				// check if item exists (guidhash is the same)
				// and ignore it if it does
				try {
					$this->itemMapper->findByGuidHash(
						$item->getGuidHash(), $item->getFeedId(), $userId);
					continue;
				} catch(DoesNotExistException $ex){
					$unreadCount += 1;
					$item = $this->enhancer->enhance($item, $feed->getLink());
					$item->setBody($this->purifier->purify($item->getBody()));
					$this->itemMapper->insert($item);
				}
			}

			// set unread count
			$feed->setUnreadCount($unreadCount);

			return $feed;
		} catch(FetcherException $ex){
			$this->logger->debug($ex->getMessage(), $this->loggerParams);
			throw new ServiceNotFoundException(
				$this->l10n->t(
					'Can not add feed: URL does not exist, SSL Certificate can not be validated ' .
					'or feed has invalid xml'));
		}
	}


	/**
	 * Runs all the feed updates
	 */
	public function updateAll(){
		// TODO: this method is not covered by any tests
		$feeds = $this->feedMapper->findAll();
		foreach($feeds as $feed){
			try {
				$this->update($feed->getId(), $feed->getUserId());
			} catch(\Exception $ex){
				$this->logger->debug('Could not update feed ' . $ex->getMessage(),
					$this->loggerParams);
			}
		}
	}


	/**
	 * Updates a single feed
	 * @param int $feedId the id of the feed that should be updated
	 * @param string $userId the id of the user
	 * @throws ServiceNotFoundException if the feed does not exist
	 * @return Feed the updated feed entity
	 */
	public function update($feedId, $userId){
		try {
			$existingFeed = $this->feedMapper->find($feedId, $userId);

			if($existingFeed->getPreventUpdate() === true) {
				return $existingFeed;
			}

			try {
				list(, $items) = $this->feedFetcher->fetch(
					$existingFeed->getUrl(), false);

				// update number of articles on every feed update
				if($existingFeed->getArticlesPerUpdate() !== count($items)) {
					$existingFeed->setArticlesPerUpdate(count($items));
					$this->feedMapper->update($existingFeed);
				}

				// insert items in reverse order because the first one is usually
				// the newest item
				for($i=count($items)-1; $i>=0; $i--){
					$item = $items[$i];
					$item->setFeedId($existingFeed->getId());

					try {
						$this->itemMapper->findByGuidHash($item->getGuidHash(), $feedId, $userId);
					} catch(DoesNotExistException $ex){
						$item = $this->enhancer->enhance($item,
							$existingFeed->getLink());
						$item->setBody($this->purifier->purify($item->getBody()));
						$this->itemMapper->insert($item);
					}
				}

			} catch(FetcherException $ex){
				// failed updating is not really a problem, so only log it

				$this->logger->debug('Can not update feed with url ' . $existingFeed->getUrl() .
					': Not found or bad source', $this->loggerParams);
				$this->logger->debug($ex->getMessage(), $this->loggerParams);
			}

			return $this->feedMapper->find($feedId, $userId);

		} catch (DoesNotExistException $ex){
			throw new ServiceNotFoundException('Feed does not exist');
		}

	}


	/**
	 * Moves a feed into a different folder
	 * @param int $feedId the id of the feed that should be moved
	 * @param int $folderId the id of the folder where the feed should be moved to
	 * @param string $userId the name of the user whose feed should be moved
	 * @throws ServiceNotFoundException if the feed does not exist
	 */
	public function move($feedId, $folderId, $userId){
		$feed = $this->find($feedId, $userId);
		$feed->setFolderId($folderId);
		$this->feedMapper->update($feed);
	}


	/**
	 * Rename a feed
	 * @param int $feedId the id of the feed that should be moved
	 * @param string $feedTitle the new title of the feed
	 * @param string $userId the name of the user whose feed should be renamed
	 * @throws ServiceNotFoundException if the feed does not exist
	 */
	public function rename($feedId, $feedTitle, $userId) {
		$feed = $this->find($feedId, $userId);
		$feed->setTitle($feedTitle</