. * */ namespace OCA\News\Bl; use \OCA\AppFramework\Db\DoesNotExistException; use \OCA\AppFramework\Core\API; use \OCA\News\Db\Feed; use \OCA\News\Db\FeedMapper; use \OCA\News\Db\ItemMapper; use \OCA\News\Utility\FeedFetcher; use \OCA\News\Utility\FetcherException; class FeedBl extends Bl { private $feedFetcher; private $itemMapper; private $api; public function __construct(FeedMapper $feedMapper, FeedFetcher $feedFetcher, ItemMapper $itemMapper, API $api){ parent::__construct($feedMapper); $this->feedFetcher = $feedFetcher; $this->itemMapper = $itemMapper; $this->api = $api; } public function findAllFromUser($userId){ return $this->mapper->findAllFromUser($userId); } public function create($feedUrl, $folderId, $userId){ // first try if the feed exists already try { $this->mapper->findByUrlHash(md5($feedUrl), $userId); throw new BLException('Can not add feed: Exists already'); } catch(DoesNotExistException $ex){} try { list($feed, $items) = $this->feedFetcher->fetch($feedUrl); // insert feed $feed->setFolderId($folderId); $feed->setUserId($userId); $feed = $this->mapper->insert($feed); // insert items foreach($items as $item){ $item->setFeedId($feed->getId()); $this->itemMapper->insert($item); } // set unread count $feed->setUnreadCount(count($items)); return $feed; } catch(FetcherException $ex){ $this->api->log($ex->getMessage()); throw new BLException('Can not add feed: Not found or bad source'); } } // FIXME: this method is not covered by any tests public function updateAll(){ $feeds = $this->mapper->findAll(); foreach($feeds as $feed){ try { $this->update($feed->getId(), $feed->getUserId()); } catch(BLException $ex){ continue; } } } public function update($feedId, $userId){ $feed = $this->mapper->find($feedId, $userId); try { list($feed, $items) = $this->feedFetcher->fetch($feed->getUrl()); // update items foreach($items as $item){ // if a database exception is being thrown the unique constraint // on the item guid hash is being violated and we need to update // the item try { $item->setFeedId($feed->getId()); $this->itemMapper->insert($item); } catch(\DatabaseException $ex){ $existing = $this->itemMapper->findByGuidHash( $item->getGuidHash(), $feedId, $userId); $item->setId($existing->getId()); $this->itemMapper->update($item); } } } catch(FetcherException $ex){ // failed updating is not really a problem, so only log it $this->api->log('Can not update feed: Not found or bad source'); } } public function move($feedId, $folderId, $userId){ $feed = $this->find($feedId, $userId); $feed->setFolderId($folderId); $this->mapper->update($feed); } // TODO: delete associated items }