1
0
mirror of https://github.com/chylex/Nextcloud-News.git synced 2025-04-26 05:15:46 +02:00

Core: Fix compatibility with nextcloud codestyle ()

This commit is contained in:
Sean Molenaar 2018-03-27 15:35:06 +02:00 committed by Bernhard Posselt
parent f3c9d13551
commit 5b94705cf3
112 changed files with 3800 additions and 2325 deletions
appinfo
lib
tests

View File

@ -7,8 +7,8 @@
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Alessandro Cosentino 2012
* @copyright Bernhard Posselt 2012, 2014
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\AppInfo;

View File

@ -7,8 +7,8 @@
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Alessandro Cosentino 2012
* @copyright Bernhard Posselt 2012, 2014
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
return ['routes' => [

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\AppInfo;
@ -40,9 +40,11 @@ use OCA\News\Explore\RecommendedSites;
use OCA\News\Utility\ProxyConfigParser;
class Application extends App {
class Application extends App
{
public function __construct(array $urlParams=[]) {
public function __construct(array $urlParams=[])
{
parent::__construct('news', $urlParams);
// files
@ -60,192 +62,245 @@ class Application extends App {
/**
* App config parser
*/
/** @noinspection PhpParamsInspection */
$this->registerService(AppConfig::class, function($c) {
$config = new AppConfig(
$c->query(INavigationManager::class),
$c->query(IURLGenerator::class),
$c->query(IJobList::class)
);
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
AppConfig::class, function ($c) {
$config = new AppConfig(
$c->query(INavigationManager::class),
$c->query(IURLGenerator::class),
$c->query(IJobList::class)
);
$config->loadConfig($c->query('info'));
$config->loadConfig($c->query('info'));
return $config;
});
return $config;
}
);
/**
* Core
*/
/** @noinspection PhpParamsInspection */
$this->registerService('LoggerParameters', function($c) {
return ['app' => $c->query('AppName')];
});
/** @noinspection PhpParamsInspection */
$this->registerService('databaseType', function($c) {
return $c->query(IConfig::class)->getSystemValue('dbtype');
});
/** @noinspection PhpParamsInspection */
$this->registerService('ConfigView', function($c) {
$fs = $c->query(IRootFolder::class);
$path = 'news/config';
if ($fs->nodeExists($path)) {
return $fs->get($path);
} else {
return $fs->newFolder($path);
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
'LoggerParameters', function ($c) {
return ['app' => $c->query('AppName')];
}
});
);
/** @noinspection PhpParamsInspection */
$this->registerService(Config::class, function($c) {
$config = new Config(
$c->query('ConfigView'),
$c->query(ILogger::class),
$c->query('LoggerParameters')
);
$config->read($c->query('configFile'), true);
return $config;
});
/** @noinspection PhpParamsInspection */
$this->registerService(HTMLPurifier::class, function($c) {
$directory = $c->query(IConfig::class)
->getSystemValue('datadirectory') . '/news/cache/purifier';
if(!is_dir($directory)) {
mkdir($directory, 0770, true);
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
'databaseType', function ($c) {
return $c->query(IConfig::class)->getSystemValue('dbtype');
}
);
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.ForbiddenAttributes', 'class');
$config->set('Cache.SerializerPath', $directory);
$config->set('HTML.SafeIframe', true);
$config->set('URI.SafeIframeRegexp',
'%^https://(?:www\.)?(' .
'youtube(?:-nocookie)?.com/embed/|' .
'player.vimeo.com/video/|' .
'vk.com/video_ext.php)%'); //allow YouTube and Vimeo
$def = $config->getHTMLDefinition(true);
$def->addAttribute('iframe', 'allowfullscreen', 'Bool');
return new HTMLPurifier($config);
});
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
'ConfigView', function ($c) {
$fs = $c->query(IRootFolder::class);
$path = 'news/config';
if ($fs->nodeExists($path)) {
return $fs->get($path);
} else {
return $fs->newFolder($path);
}
}
);
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
Config::class, function ($c) {
$config = new Config(
$c->query('ConfigView'),
$c->query(ILogger::class),
$c->query('LoggerParameters')
);
$config->read($c->query('configFile'), true);
return $config;
}
);
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
HTMLPurifier::class, function ($c) {
$directory = $c->query(IConfig::class)
->getSystemValue('datadirectory') . '/news/cache/purifier';
if(!is_dir($directory)) {
mkdir($directory, 0770, true);
}
$config = HTMLPurifier_Config::createDefault();
$config->set('HTML.ForbiddenAttributes', 'class');
$config->set('Cache.SerializerPath', $directory);
$config->set('HTML.SafeIframe', true);
$config->set(
'URI.SafeIframeRegexp',
'%^https://(?:www\.)?(' .
'youtube(?:-nocookie)?.com/embed/|' .
'player.vimeo.com/video/|' .
'vk.com/video_ext.php)%'
); //allow YouTube and Vimeo
$def = $config->getHTMLDefinition(true);
$def->addAttribute('iframe', 'allowfullscreen', 'Bool');
return new HTMLPurifier($config);
}
);
/**
* Fetchers
*/
/** @noinspection PhpParamsInspection */
$this->registerService(PicoFeedConfig::class, function($c) {
// FIXME: move this into a separate class for testing?
$config = $c->query(Config::class);
$proxy = $c->query(ProxyConfigParser::class);
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
PicoFeedConfig::class, function ($c) {
// FIXME: move this into a separate class for testing?
$config = $c->query(Config::class);
$proxy = $c->query(ProxyConfigParser::class);
// use chrome's user agent string since mod_security rules
// assume that only browsers can send user agent strings. This
// can lead to blocked feed updates like joomla.org
// For more information see
// https://www.atomicorp.com/wiki/index.php/WAF_309925
$userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' .
// use chrome's user agent string since mod_security rules
// assume that only browsers can send user agent strings. This
// can lead to blocked feed updates like joomla.org
// For more information see
// https://www.atomicorp.com/wiki/index.php/WAF_309925
$userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' .
'(KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36';
$pico = new PicoFeedConfig();
$pico->setClientUserAgent($userAgent)
->setClientTimeout($config->getFeedFetcherTimeout())
->setMaxRedirections($config->getMaxRedirects())
->setMaxBodySize($config->getMaxSize())
->setParserHashAlgo('md5');
$pico = new PicoFeedConfig();
$pico->setClientUserAgent($userAgent)
->setClientTimeout($config->getFeedFetcherTimeout())
->setMaxRedirections($config->getMaxRedirects())
->setMaxBodySize($config->getMaxSize())
->setParserHashAlgo('md5');
// proxy settings
$proxySettings = $proxy->parse();
$host = $proxySettings['host'];
$port = $proxySettings['port'];
$user = $proxySettings['user'];
$password = $proxySettings['password'];
// proxy settings
$proxySettings = $proxy->parse();
$host = $proxySettings['host'];
$port = $proxySettings['port'];
$user = $proxySettings['user'];
$password = $proxySettings['password'];
if ($host) {
$pico->setProxyHostname($host);
if ($host) {
$pico->setProxyHostname($host);
if ($port) {
$pico->setProxyPort($port);
if ($port) {
$pico->setProxyPort($port);
}
}
if ($user) {
$pico->setProxyUsername($user)
->setProxyPassword($password);
}
return $pico;
}
);
if ($user) {
$pico->setProxyUsername($user)
->setProxyPassword($password);
$this->registerService(
PicoFeedReader::class, function ($c) {
return new PicoFeedReader($c->query(PicoFeedConfig::class));
}
);
return $pico;
});
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
Fetcher::class, function ($c) {
$fetcher = new Fetcher();
$this->registerService(PicoFeedReader::class, function ($c) {
return new PicoFeedReader($c->query(PicoFeedConfig::class));
});
// register fetchers in order, the most generic fetcher should be
// the last one
$fetcher->registerFetcher($c->query(YoutubeFetcher::class));
$fetcher->registerFetcher($c->query(FeedFetcher::class));
/** @noinspection PhpParamsInspection */
$this->registerService(Fetcher::class, function($c) {
$fetcher = new Fetcher();
// register fetchers in order, the most generic fetcher should be
// the last one
$fetcher->registerFetcher($c->query(YoutubeFetcher::class));
$fetcher->registerFetcher($c->query(FeedFetcher::class));
return $fetcher;
});
return $fetcher;
}
);
}
/**
* Registers the content of a file under a key
*
* @param string $key
* @param string $file path relative to this file, __DIR__ will be prepended
*/
private function registerFileContents($key, $file) {
/** @noinspection PhpParamsInspection */
$this->registerService($key, function () use ($file) {
return file_get_contents(__DIR__ . '/' . $file);
});
private function registerFileContents($key, $file)
{
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
$key, function () use ($file) {
return file_get_contents(__DIR__ . '/' . $file);
}
);
}
/**
* Shortcut for registering a service
* @param string $key
*
* @param string $key
* @param closure $factory
* @param boolean $shared
*/
private function registerService($key, $factory, $shared=true) {
private function registerService($key, $factory, $shared=true)
{
$this->getContainer()->registerService($key, $factory, $shared);
}
/**
* Shortcut for registering a parameter
*
* @param string $key
* @param mixed $value
* @param mixed $value
*/
private function registerParameter($key, $value) {
private function registerParameter($key, $value)
{
$this->getContainer()->registerParameter($key, $value);
}
/**
* Register a class containing the app construction logic instead of the
* inlining everything in this class to enhance testability
* @param string $key fully qualified class name
*
* @param string $key fully qualified class name
* @param string $factory fully qualified factory class name
*/
private function registerFactory($key, $factory) {
/** @noinspection PhpParamsInspection */
$this->registerService($key, function ($c) use ($factory) {
return $c->query($factory)->build();
});
private function registerFactory($key, $factory)
{
/**
* @noinspection PhpParamsInspection
*/
$this->registerService(
$key, function ($c) use ($factory) {
return $c->query($factory)->build();
}
);
}
/**
* Register the additional config parameters found in the info.xml
*/
public function registerConfig() {
public function registerConfig()
{
$this->getContainer()->query(AppConfig::class)->registerAll();
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2016
*/
@ -19,21 +19,27 @@ use Symfony\Component\Console\Output\OutputInterface;
use \OCA\News\Utility\Updater;
class AfterUpdate extends Command {
class AfterUpdate extends Command
{
private $updater;
public function __construct(Updater $updater) {
public function __construct(Updater $updater)
{
parent::__construct();
$this->updater = $updater;
}
protected function configure() {
protected function configure()
{
$this->setName('news:updater:after-update')
->setDescription('This is used to clean up the database. It ' .
'removes old read articles which are not starred');
->setDescription(
'This is used to clean up the database. It ' .
'removes old read articles which are not starred'
);
}
protected function execute(InputInterface $input, OutputInterface $output) {
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->updater->afterUpdate();
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2016
*/
@ -20,23 +20,29 @@ use Symfony\Component\Console\Output\OutputInterface;
use OCA\News\Service\FeedService;
class AllFeeds extends Command {
class AllFeeds extends Command
{
private $feedService;
public function __construct(FeedService $feedService) {
public function __construct(FeedService $feedService)
{
parent::__construct();
$this->feedService = $feedService;
}
protected function configure() {
protected function configure()
{
$json = '{"feeds": [{"id": 39, "userId": "john"}, // etc ]}';
$this->setName('news:updater:all-feeds')
->setDescription('Prints a JSON string which contains all feed ' .
'ids and user ids, e.g.: ' . $json);
->setDescription(
'Prints a JSON string which contains all feed ' .
'ids and user ids, e.g.: ' . $json
);
}
protected function execute(InputInterface $input, OutputInterface $output) {
protected function execute(InputInterface $input, OutputInterface $output)
{
$feeds = $this->feedService->findAllFromAllUsers();
$result = ['feeds' => []];

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2016
*/
@ -19,22 +19,28 @@ use Symfony\Component\Console\Output\OutputInterface;
use \OCA\News\Utility\Updater;
class BeforeUpdate extends Command {
class BeforeUpdate extends Command
{
private $updater;
public function __construct(Updater $updater) {
public function __construct(Updater $updater)
{
parent::__construct();
$this->updater = $updater;
}
protected function configure() {
protected function configure()
{
$this->setName('news:updater:before-update')
->setDescription('This is used to clean up the database. It ' .
->setDescription(
'This is used to clean up the database. It ' .
'deletes folders and feeds that are marked for ' .
'deletion');
'deletion'
);
}
protected function execute(InputInterface $input, OutputInterface $output) {
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->updater->beforeUpdate();
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2016
*/
@ -21,15 +21,18 @@ use Symfony\Component\Console\Output\OutputInterface;
use OCA\News\Service\FeedService;
class UpdateFeed extends Command {
class UpdateFeed extends Command
{
private $feedService;
public function __construct(FeedService $feedService) {
public function __construct(FeedService $feedService)
{
parent::__construct();
$this->feedService = $feedService;
}
protected function configure() {
protected function configure()
{
$this->setName('news:updater:update-feed')
->addArgument(
'feed-id',
@ -44,15 +47,18 @@ class UpdateFeed extends Command {
->setDescription('Console API for updating a single user\'s feed');
}
protected function execute(InputInterface $input, OutputInterface $output) {
protected function execute(InputInterface $input, OutputInterface $output)
{
$feedId = $input->getArgument('feed-id');
$userId = $input->getArgument('user-id');
try {
$this->feedService->update($feedId, $userId);
} catch (Exception $e) {
$output->writeln('<error>Could not update feed with id ' . $feedId .
$output->writeln(
'<error>Could not update feed with id ' . $feedId .
' and user ' . $userId . ': ' . $e->getMessage() .
'</error> ');
'</error> '
);
}
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Config;
@ -17,7 +17,8 @@ use OCP\ILogger;
use OCP\Files\Folder;
class Config {
class Config
{
private $fileSystem;
private $autoPurgeMinimumInterval; // seconds, used to define how
@ -34,8 +35,9 @@ class Config {
private $exploreUrl;
public function __construct(Folder $fileSystem,
ILogger $logger,
$LoggerParameters) {
ILogger $logger,
$LoggerParameters
) {
$this->fileSystem = $fileSystem;
$this->autoPurgeMinimumInterval = 60;
$this->autoPurgeCount = 200;
@ -48,7 +50,8 @@ class Config {
$this->loggerParams = $LoggerParameters;
}
public function getAutoPurgeMinimumInterval() {
public function getAutoPurgeMinimumInterval()
{
if ($this->autoPurgeMinimumInterval > 60) {
return $this->autoPurgeMinimumInterval;
} else {
@ -56,71 +59,85 @@ class Config {
}
}
public function getAutoPurgeCount() {
public function getAutoPurgeCount()
{
return $this->autoPurgeCount;
}
public function getMaxRedirects() {
public function getMaxRedirects()
{
return $this->maxRedirects;
}
public function getFeedFetcherTimeout() {
public function getFeedFetcherTimeout()
{
return $this->feedFetcherTimeout;
}
public function getUseCronUpdates() {
public function getUseCronUpdates()
{
return $this->useCronUpdates;
}
public function getMaxSize() {
public function getMaxSize()
{
return $this->maxSize;
}
public function getExploreUrl() {
public function getExploreUrl()
{
return $this->exploreUrl;
}
public function setAutoPurgeMinimumInterval($value) {
public function setAutoPurgeMinimumInterval($value)
{
$this->autoPurgeMinimumInterval = $value;
}
public function setAutoPurgeCount($value) {
public function setAutoPurgeCount($value)
{
$this->autoPurgeCount = $value;
}
public function setMaxRedirects($value) {
public function setMaxRedirects($value)
{
$this->maxRedirects = $value;
}
public function setFeedFetcherTimeout($value) {
public function setFeedFetcherTimeout($value)
{
$this->feedFetcherTimeout = $value;
}
public function setUseCronUpdates($value) {
public function setUseCronUpdates($value)
{
$this->useCronUpdates = $value;
}
public function setMaxSize($value) {
public function setMaxSize($value)
{
$this->maxSize = $value;
}
public function setExploreUrl($value) {
public function setExploreUrl($value)
{
$this->exploreUrl = $value;
}
public function read($configPath, $createIfNotExists=false) {
public function read($configPath, $createIfNotExists=false)
{
if($createIfNotExists && !$this->fileSystem->nodeExists($configPath)) {
$this->fileSystem->newFile($configPath);
$this->write($configPath);
@ -145,7 +162,7 @@ class Config {
} else {
$this->logger->warning(
'Configuration value "' . $key .
'" does not exist. Ignored value.' ,
'" does not exist. Ignored value.',
$this->loggerParams
);
}
@ -156,7 +173,8 @@ class Config {
}
public function write($configPath) {
public function write($configPath)
{
$ini =
'autoPurgeMinimumInterval = ' .
$this->autoPurgeMinimumInterval . "\n" .

View File

@ -5,22 +5,25 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Config;
class DependencyException extends \Exception {
class DependencyException extends \Exception
{
/**
* Constructor
*
* @param string $msg the error message
*/
public function __construct($msg){
public function __construct($msg)
{
parent::__construct($msg);
}

View File

@ -7,8 +7,9 @@
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Alessandro Cosentino 2012
* @copyright Bernhard Posselt 2012, 2014
*
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -20,68 +21,94 @@ use OCP\AppFramework\Controller;
use OCA\News\Config\Config;
use OCA\News\Service\ItemService;
class AdminController extends Controller {
/**
* Class AdminController
*
* @package OCA\News\Controller
*/
class AdminController extends Controller
{
private $_config;
private $_configPath;
private $_itemService;
private $config;
private $configPath;
private $itemService;
public function __construct($AppName, IRequest $request, Config $config,
ItemService $itemService, $configFile){
parent::__construct($AppName, $request);
$this->config = $config;
$this->configPath = $configFile;
$this->itemService = $itemService;
/**
* AdminController constructor.
*
* @param string $appName The name of the app
* @param IRequest $request The request
* @param Config $config Config for nextcloud
* @param ItemService $itemService Service for items
* @param string $configFile Path to the config
*/
public function __construct($appName, IRequest $request, Config $config,
ItemService $itemService, $configFile
) {
parent::__construct($appName, $request);
$this->_config = $config;
$this->_configPath = $configFile;
$this->_itemService = $itemService;
}
// There are no checks for the index method since the output is rendered
// in admin/admin.php
public function index() {
/**
* Controller main entry.
*
* There are no checks for the index method since the output is
* rendered in admin/admin.php
*
* @return TemplateResponse
*/
public function index()
{
$data = [
'autoPurgeMinimumInterval' =>
$this->config->getAutoPurgeMinimumInterval(),
'autoPurgeCount' => $this->config->getAutoPurgeCount(),
'maxRedirects' => $this->config->getMaxRedirects(),
'feedFetcherTimeout' => $this->config->getFeedFetcherTimeout(),
'useCronUpdates' => $this->config->getUseCronUpdates(),
'maxSize' => $this->config->getMaxSize(),
'exploreUrl' => $this->config->getExploreUrl(),
$this->_config->getAutoPurgeMinimumInterval(),
'autoPurgeCount' => $this->_config->getAutoPurgeCount(),
'maxRedirects' => $this->_config->getMaxRedirects(),
'feedFetcherTimeout' => $this->_config->getFeedFetcherTimeout(),
'useCronUpdates' => $this->_config->getUseCronUpdates(),
'maxSize' => $this->_config->getMaxSize(),
'exploreUrl' => $this->_config->getExploreUrl(),
];
return new TemplateResponse($this->appName, 'admin', $data, 'blank');
}
/**
* @param int $autoPurgeMinimumInterval
* @param int $autoPurgeCount
* @param int $maxRedirects
* @param int $feedFetcherTimeout
* @param int $maxSize
* @param bool $useCronUpdates
* @param string $exploreUrl
* Update the app config.
*
* @param int $autoPurgeMinimumInterval New minimum interval for auto-purge
* @param int $autoPurgeCount New value of auto-purge count
* @param int $maxRedirects New value for max amount of redirects
* @param int $feedFetcherTimeout New timeout value for feed fetcher
* @param int $maxSize New max feed size
* @param bool $useCronUpdates Whether or not to use cron updates
* @param string $exploreUrl URL to use for the explore feed
*
* @return array with the updated values
*/
public function update($autoPurgeMinimumInterval, $autoPurgeCount,
$maxRedirects, $feedFetcherTimeout, $maxSize,
$useCronUpdates, $exploreUrl) {
$this->config->setAutoPurgeMinimumInterval($autoPurgeMinimumInterval);
$this->config->setAutoPurgeCount($autoPurgeCount);
$this->config->setMaxRedirects($maxRedirects);
$this->config->setMaxSize($maxSize);
$this->config->setFeedFetcherTimeout($feedFetcherTimeout);
$this->config->setUseCronUpdates($useCronUpdates);
$this->config->setExploreUrl($exploreUrl);
$this->config->write($this->configPath);
$maxRedirects, $feedFetcherTimeout, $maxSize,
$useCronUpdates, $exploreUrl
) {
$this->_config->setAutoPurgeMinimumInterval($autoPurgeMinimumInterval);
$this->_config->setAutoPurgeCount($autoPurgeCount);
$this->_config->setMaxRedirects($maxRedirects);
$this->_config->setMaxSize($maxSize);
$this->_config->setFeedFetcherTimeout($feedFetcherTimeout);
$this->_config->setUseCronUpdates($useCronUpdates);
$this->_config->setExploreUrl($exploreUrl);
$this->_config->write($this->_configPath);
return [
'autoPurgeMinimumInterval' =>
$this->config->getAutoPurgeMinimumInterval(),
'autoPurgeCount' => $this->config->getAutoPurgeCount(),
'maxRedirects' => $this->config->getMaxRedirects(),
'maxSize' => $this->config->getMaxSize(),
'feedFetcherTimeout' => $this->config->getFeedFetcherTimeout(),
'useCronUpdates' => $this->config->getUseCronUpdates(),
'exploreUrl' => $this->config->getExploreUrl(),
$this->_config->getAutoPurgeMinimumInterval(),
'autoPurgeCount' => $this->_config->getAutoPurgeCount(),
'maxRedirects' => $this->_config->getMaxRedirects(),
'maxSize' => $this->_config->getMaxSize(),
'feedFetcherTimeout' => $this->_config->getFeedFetcherTimeout(),
'useCronUpdates' => $this->_config->getUseCronUpdates(),
'exploreUrl' => $this->_config->getExploreUrl(),
];
}

View File

@ -7,8 +7,8 @@
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Alessandro Cosentino 2012
* @copyright Bernhard Posselt 2012, 2014
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -16,19 +16,35 @@ namespace OCA\News\Controller;
use OCP\IRequest;
use OCP\AppFramework\ApiController as BaseApiController;
class ApiController extends BaseApiController {
public function __construct($appName,
IRequest $request){
/**
* Class ApiController
*
* @package OCA\News\Controller
*/
class ApiController extends BaseApiController
{
/**
* ApiController constructor.
*
* @param string $appName The name of the app
* @param IRequest $request The request
*/
public function __construct($appName, IRequest $request)
{
parent::__construct($appName, $request);
}
/**
* Indication of the API levels
*
* @PublicPage
* @NoCSRFRequired
* @CORS
*
* @return array
*/
public function index() {
public function index()
{
return [
'apiLevels' => ['v1-2']
];

View File

@ -5,8 +5,8 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2014
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -14,11 +14,13 @@ namespace OCA\News\Controller;
use \OCA\News\Db\IAPI;
class EntityApiSerializer {
class EntityApiSerializer
{
private $level;
public function __construct($level) {
public function __construct($level)
{
$this->level = $level;
}
@ -26,14 +28,15 @@ class EntityApiSerializer {
/**
* Call toAPI() method on all entities. Works on
*
* @param mixed $data :
* * Entity
* * Entity[]
* * array('level' => Entity[])
* * Response
* @param mixed $data :
* * Entity
* * Entity[]
* * array('level' => Entity[])
* * Response
* @return array|mixed
*/
public function serialize($data) {
public function serialize($data)
{
if($data instanceof IAPI) {
return [$this->level => [$data->toAPI()]];
@ -49,14 +52,15 @@ class EntityApiSerializer {
}
private function convert($entities) {
private function convert($entities)
{
$converted = [];
foreach($entities as $entity) {
if($entity instanceof IAPI) {
$converted[] = $entity->toAPI();
// break if it contains anything else than entities
// break if it contains anything else than entities
} else {
return $entities;
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -24,7 +24,8 @@ use \OCA\News\Service\FeedService;
use \OCA\News\Service\ItemService;
use \OCA\News\Utility\OPMLExporter;
class ExportController extends Controller {
class ExportController extends Controller
{
private $opmlExporter;
private $folderService;
@ -32,14 +33,15 @@ class ExportController extends Controller {
private $itemService;
private $userId;
public function __construct($AppName,
IRequest $request,
FolderService $folderService,
FeedService $feedService,
ItemService $itemService,
OPMLExporter $opmlExporter,
$UserId){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
FolderService $folderService,
FeedService $feedService,
ItemService $itemService,
OPMLExporter $opmlExporter,
$UserId
) {
parent::__construct($appName, $request);
$this->feedService = $feedService;
$this->folderService = $folderService;
$this->opmlExporter = $opmlExporter;
@ -52,7 +54,8 @@ class ExportController extends Controller {
* @NoAdminRequired
* @NoCSRFRequired
*/
public function opml(){
public function opml()
{
$feeds = $this->feedService->findAll($this->userId);
$folders = $this->folderService->findAll($this->userId);
$opml = $this->opmlExporter->build($folders, $feeds)->saveXML();
@ -66,7 +69,8 @@ class ExportController extends Controller {
* @NoAdminRequired
* @NoCSRFRequired
*/
public function articles(){
public function articles()
{
$feeds = $this->feedService->findAll($this->userId);
$items = $this->itemService->getUnreadOrStarred($this->userId);
@ -82,8 +86,10 @@ class ExportController extends Controller {
}
$response = new JSONResponse($articles);
$response->addHeader('Content-Disposition',
'attachment; filename="articles.json"');
$response->addHeader(
'Content-Disposition',
'attachment; filename="articles.json"'
);
return $response;
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -23,7 +23,8 @@ use \OCA\News\Service\ServiceNotFoundException;
use \OCA\News\Service\ServiceConflictException;
class FeedApiController extends ApiController {
class FeedApiController extends ApiController
{
use JSONHttpError;
@ -34,14 +35,15 @@ class FeedApiController extends ApiController {
private $loggerParams;
private $serializer;
public function __construct($AppName,
IRequest $request,
FeedService $feedService,
ItemService $itemService,
ILogger $logger,
$UserId,
$LoggerParameters){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
FeedService $feedService,
ItemService $itemService,
ILogger $logger,
$UserId,
$LoggerParameters
) {
parent::__construct($appName, $request);
$this->feedService = $feedService;
$this->itemService = $itemService;
$this->userId = $UserId;
@ -56,7 +58,8 @@ class FeedApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*/
public function index() {
public function index()
{
$result = [
'starredCount' => $this->itemService->starredCount($this->userId),
@ -68,8 +71,9 @@ class FeedApiController extends ApiController {
$result['newestItemId'] =
$this->itemService->getNewestItemId($this->userId);
// in case there are no items, ignore
} catch(ServiceNotFoundException $ex) {}
// in case there are no items, ignore
} catch(ServiceNotFoundException $ex) {
}
return $this->serializer->serialize($result);
}
@ -81,10 +85,11 @@ class FeedApiController extends ApiController {
* @CORS
*
* @param string $url
* @param int $folderId
* @param int $folderId
* @return array|mixed|\OCP\AppFramework\Http\JSONResponse
*/
public function create($url, $folderId=0) {
public function create($url, $folderId=0)
{
try {
$this->feedService->purgeDeleted($this->userId, false);
@ -95,8 +100,9 @@ class FeedApiController extends ApiController {
$result['newestItemId'] =
$this->itemService->getNewestItemId($this->userId);
// in case there are no items, ignore
} catch(ServiceNotFoundException $ex) {}
// in case there are no items, ignore
} catch(ServiceNotFoundException $ex) {
}
return $this->serializer->serialize($result);
@ -116,7 +122,8 @@ class FeedApiController extends ApiController {
* @param int $feedId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function delete($feedId) {
public function delete($feedId)
{
try {
$this->feedService->delete($feedId, $this->userId);
} catch(ServiceNotFoundException $ex) {
@ -135,7 +142,8 @@ class FeedApiController extends ApiController {
* @param int $feedId
* @param int $newestItemId
*/
public function read($feedId, $newestItemId) {
public function read($feedId, $newestItemId)
{
$this->itemService->readFeed($feedId, $newestItemId, $this->userId);
}
@ -149,7 +157,8 @@ class FeedApiController extends ApiController {
* @param int $folderId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function move($feedId, $folderId) {
public function move($feedId, $folderId)
{
try {
$this->feedService->patch(
$feedId, $this->userId, ['folderId' => $folderId]
@ -167,11 +176,12 @@ class FeedApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*
* @param int $feedId
* @param int $feedId
* @param string $feedTitle
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function rename($feedId, $feedTitle) {
public function rename($feedId, $feedTitle)
{
try {
$this->feedService->patch(
$feedId, $this->userId, ['title' => $feedTitle]
@ -188,7 +198,8 @@ class FeedApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*/
public function fromAllUsers() {
public function fromAllUsers()
{
$feeds = $this->feedService->findAllFromAllUsers();
$result = ['feeds' => []];
@ -207,15 +218,18 @@ class FeedApiController extends ApiController {
* @NoCSRFRequired
*
* @param string $userId
* @param int $feedId
* @param int $feedId
*/
public function update($userId, $feedId) {
public function update($userId, $feedId)
{
try {
$this->feedService->update($feedId, $userId);
// ignore update failure
// ignore update failure
} catch(\Exception $ex) {
$this->logger->debug('Could not update feed ' . $ex->getMessage(),
$this->loggerParams);
$this->logger->debug(
'Could not update feed ' . $ex->getMessage(),
$this->loggerParams
);
}
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -26,7 +26,8 @@ use OCA\News\Service\ServiceConflictException;
use OCA\News\Db\FeedType;
class FeedController extends Controller {
class FeedController extends Controller
{
use JSONHttpError;
@ -36,14 +37,15 @@ class FeedController extends Controller {
private $userId;
private $settings;
public function __construct($AppName,
IRequest $request,
FolderService $folderService,
FeedService $feedService,
ItemService $itemService,
IConfig $settings,
$UserId){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
FolderService $folderService,
FeedService $feedService,
ItemService $itemService,
IConfig $settings,
$UserId
) {
parent::__construct($appName, $request);
$this->feedService = $feedService;
$this->folderService = $folderService;
$this->itemService = $itemService;
@ -55,7 +57,8 @@ class FeedController extends Controller {
/**
* @NoAdminRequired
*/
public function index(){
public function index()
{
// this method is also used to update the interface
// because of this we also pass the starred count and the newest
@ -69,9 +72,10 @@ class FeedController extends Controller {
$params['newestItemId'] =
$this->itemService->getNewestItemId($this->userId);
// An exception occurs if there is a newest item. If there is none,
// simply ignore it and do not add the newestItemId
} catch (ServiceNotFoundException $ex) {}
// An exception occurs if there is a newest item. If there is none,
// simply ignore it and do not add the newestItemId
} catch (ServiceNotFoundException $ex) {
}
return $params;
}
@ -80,27 +84,32 @@ class FeedController extends Controller {
/**
* @NoAdminRequired
*/
public function active(){
$feedId = (int) $this->settings->getUserValue($this->userId,
$this->appName,'lastViewedFeedId');
$feedType = $this->settings->getUserValue($this->userId, $this->appName,
'lastViewedFeedType');
public function active()
{
$feedId = (int) $this->settings->getUserValue(
$this->userId,
$this->appName, 'lastViewedFeedId'
);
$feedType = $this->settings->getUserValue(
$this->userId, $this->appName,
'lastViewedFeedType'
);
// cast from null to int is 0
if($feedType !== null){
if($feedType !== null) {
$feedType = (int) $feedType;
}
// check if feed or folder exists
try {
if($feedType === FeedType::FOLDER){
if($feedType === FeedType::FOLDER) {
$this->folderService->find($feedId, $this->userId);
} elseif ($feedType === FeedType::FEED){
} elseif ($feedType === FeedType::FEED) {
$this->feedService->find($feedId, $this->userId);
// if its the first launch, those values will be null
} elseif($feedType === null){
// if its the first launch, those values will be null
} elseif($feedType === null) {
throw new ServiceNotFoundException('');
}
@ -122,31 +131,35 @@ class FeedController extends Controller {
* @NoAdminRequired
*
* @param string $url
* @param int $parentFolderId
* @param int $parentFolderId
* @param string $title
* @param string $user
* @param string $password
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function create($url, $parentFolderId, $title=null,
$user=null, $password=null){
$user=null, $password=null
) {
try {
// we need to purge deleted feeds if a feed is created to
// prevent already exists exceptions
$this->feedService->purgeDeleted($this->userId, false);
$feed = $this->feedService->create($url, $parentFolderId,
$this->userId, $title,
$user, $password);
$feed = $this->feedService->create(
$url, $parentFolderId,
$this->userId, $title,
$user, $password
);
$params = ['feeds' => [$feed]];
try {
$params['newestItemId'] =
$this->itemService->getNewestItemId($this->userId);
// An exception occurs if there is a newest item. If there is none,
// simply ignore it and do not add the newestItemId
} catch (ServiceNotFoundException $ex) {}
// An exception occurs if there is a newest item. If there is none,
// simply ignore it and do not add the newestItemId
} catch (ServiceNotFoundException $ex) {
}
return $params;
@ -165,7 +178,8 @@ class FeedController extends Controller {
* @param int $feedId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function delete($feedId){
public function delete($feedId)
{
try {
$this->feedService->markDeleted($feedId, $this->userId);
} catch(ServiceNotFoundException $ex) {
@ -182,7 +196,8 @@ class FeedController extends Controller {
* @param int $feedId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function update($feedId){
public function update($feedId)
{
try {
$feed = $this->feedService->update($feedId, $this->userId);
@ -210,7 +225,8 @@ class FeedController extends Controller {
* @param array $json
* @return array
*/
public function import($json) {
public function import($json)
{
$feed = $this->feedService->importArticles($json, $this->userId);
$params = [
@ -232,7 +248,8 @@ class FeedController extends Controller {
* @param int $highestItemId
* @return array
*/
public function read($feedId, $highestItemId){
public function read($feedId, $highestItemId)
{
$this->itemService->readFeed($feedId, $highestItemId, $this->userId);
return [
@ -252,7 +269,8 @@ class FeedController extends Controller {
* @param int $feedId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function restore($feedId){
public function restore($feedId)
{
try {
$this->feedService->unmarkDeleted($feedId, $this->userId);
} catch(ServiceNotFoundException $ex) {
@ -265,17 +283,18 @@ class FeedController extends Controller {
/**
* @NoAdminRequired
*
* @param int $feedId
* @param bool $pinned
* @param bool $fullTextEnabled
* @param int $updateMode
* @param int $ordering
* @param int $folderId
* @param int $feedId
* @param bool $pinned
* @param bool $fullTextEnabled
* @param int $updateMode
* @param int $ordering
* @param int $folderId
* @param string $title
*/
public function patch($feedId, $pinned=null, $fullTextEnabled=null,
$updateMode=null, $ordering=null, $title=null,
$folderId=null) {
$updateMode=null, $ordering=null, $title=null,
$folderId=null
) {
$attributes = [
'pinned' => $pinned,
'fullTextEnabled' => $fullTextEnabled,
@ -285,9 +304,11 @@ class FeedController extends Controller {
'folderId' => $folderId
];
$diff = array_filter($attributes, function ($value) {
return $value !== null;
});
$diff = array_filter(
$attributes, function ($value) {
return $value !== null;
}
);
try {
$this->feedService->patch($feedId, $this->userId, $diff);

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -23,7 +23,8 @@ use \OCA\News\Service\ServiceConflictException;
use \OCA\News\Service\ServiceValidationException;
class FolderApiController extends ApiController {
class FolderApiController extends ApiController
{
use JSONHttpError;
@ -32,12 +33,13 @@ class FolderApiController extends ApiController {
private $userId;
private $serializer;
public function __construct($AppName,
IRequest $request,
FolderService $folderService,
ItemService $itemService,
$UserId){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
FolderService $folderService,
ItemService $itemService,
$UserId
) {
parent::__construct($appName, $request);
$this->folderService = $folderService;
$this->itemService = $itemService;
$this->userId = $UserId;
@ -50,7 +52,8 @@ class FolderApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*/
public function index() {
public function index()
{
return $this->serializer->serialize(
$this->folderService->findAll($this->userId)
);
@ -65,7 +68,8 @@ class FolderApiController extends ApiController {
* @param string $name
* @return array|mixed|\OCP\AppFramework\Http\JSONResponse
*/
public function create($name) {
public function create($name)
{
try {
$this->folderService->purgeDeleted($this->userId, false);
return $this->serializer->serialize(
@ -87,7 +91,8 @@ class FolderApiController extends ApiController {
* @param int $folderId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function delete($folderId) {
public function delete($folderId)
{
try {
$this->folderService->delete($folderId, $this->userId);
} catch(ServiceNotFoundException $ex) {
@ -102,11 +107,12 @@ class FolderApiController extends ApiController {
* @NoAdminRequired
* @NoCSRFRequired
* @CORS
* @param int $folderId
* @param int $folderId
* @param string $name
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function update($folderId, $name) {
public function update($folderId, $name)
{
try {
$this->folderService->rename($folderId, $name, $this->userId);
@ -130,7 +136,8 @@ class FolderApiController extends ApiController {
* @param int $folderId
* @param int $newestItemId
*/
public function read($folderId, $newestItemId) {
public function read($folderId, $newestItemId)
{
$this->itemService->readFolder($folderId, $newestItemId, $this->userId);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -25,7 +25,8 @@ use \OCA\News\Service\ServiceConflictException;
use \OCA\News\Service\ServiceValidationException;
class FolderController extends Controller {
class FolderController extends Controller
{
use JSONHttpError;
@ -34,13 +35,14 @@ class FolderController extends Controller {
private $itemService;
private $userId;
public function __construct($AppName,
IRequest $request,
FolderService $folderService,
FeedService $feedService,
ItemService $itemService,
$UserId) {
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
FolderService $folderService,
FeedService $feedService,
ItemService $itemService,
$UserId
) {
parent::__construct($appName, $request);
$this->folderService = $folderService;
$this->feedService = $feedService;
$this->itemService = $itemService;
@ -51,7 +53,8 @@ class FolderController extends Controller {
/**
* @NoAdminRequired
*/
public function index() {
public function index()
{
$folders = $this->folderService->findAll($this->userId);
return ['folders' => $folders];
}
@ -60,11 +63,12 @@ class FolderController extends Controller {
/**
* @NoAdminRequired
*
* @param int $folderId
* @param int $folderId
* @param bool $open
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function open($folderId, $open) {
public function open($folderId, $open)
{
try {
$this->folderService->open($folderId, $open, $this->userId);
} catch(ServiceNotFoundException $ex) {
@ -81,7 +85,8 @@ class FolderController extends Controller {
* @param string $folderName
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function create($folderName) {
public function create($folderName)
{
try {
// we need to purge deleted folders if a folder is created to
// prevent already exists exceptions
@ -105,7 +110,8 @@ class FolderController extends Controller {
* @param int $folderId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function delete($folderId) {
public function delete($folderId)
{
try {
$this->folderService->markDeleted($folderId, $this->userId);
} catch (ServiceNotFoundException $ex){
@ -120,13 +126,16 @@ class FolderController extends Controller {
* @NoAdminRequired
*
* @param string $folderName
* @param int $folderId
* @param int $folderId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function rename($folderName, $folderId) {
public function rename($folderName, $folderId)
{
try {
$folder = $this->folderService->rename($folderId, $folderName,
$this->userId);
$folder = $this->folderService->rename(
$folderId, $folderName,
$this->userId
);
return ['folders' => [$folder]];
@ -147,7 +156,8 @@ class FolderController extends Controller {
* @param int $highestItemId
* @return array
*/
public function read($folderId, $highestItemId) {
public function read($folderId, $highestItemId)
{
$this->itemService->readFolder(
$folderId, $highestItemId, $this->userId
);
@ -162,7 +172,8 @@ class FolderController extends Controller {
* @param int $folderId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function restore($folderId) {
public function restore($folderId)
{
try {
$this->folderService->unmarkDeleted($folderId, $this->userId);
} catch (ServiceNotFoundException $ex){

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -19,7 +19,8 @@ use \OCP\AppFramework\Http;
use \OCA\News\Service\ItemService;
use \OCA\News\Service\ServiceNotFoundException;
class ItemApiController extends ApiController {
class ItemApiController extends ApiController
{
use JSONHttpError;
@ -27,11 +28,12 @@ class ItemApiController extends ApiController {
private $userId;
private $serializer;
public function __construct($AppName,
IRequest $request,
ItemService $itemService,
$UserId){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
ItemService $itemService,
$UserId
) {
parent::__construct($appName, $request);
$this->itemService = $itemService;
$this->userId = $UserId;
$this->serializer = new EntityApiSerializer('items');
@ -43,16 +45,17 @@ class ItemApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*
* @param int $type
* @param int $id
* @param int $type
* @param int $id
* @param bool $getRead
* @param int $batchSize
* @param int $offset
* @param int $batchSize
* @param int $offset
* @param bool $oldestFirst
* @return array|mixed
*/
public function index($type=3, $id=0, $getRead=true, $batchSize=-1,
$offset=0, $oldestFirst=false) {
$offset=0, $oldestFirst=false
) {
return $this->serializer->serialize(
$this->itemService->findAll(
$id, $type, $batchSize, $offset, $getRead, $oldestFirst,
@ -72,7 +75,8 @@ class ItemApiController extends ApiController {
* @param int $lastModified
* @return array|mixed
*/
public function updated($type=3, $id=0, $lastModified=0) {
public function updated($type=3, $id=0, $lastModified=0)
{
// needs to be turned into a millisecond timestamp to work properly
if (strlen((string) $lastModified) <= 10) {
$paddedLastModified = $lastModified . '000000';
@ -80,13 +84,16 @@ class ItemApiController extends ApiController {
$paddedLastModified = $lastModified;
}
return $this->serializer->serialize(
$this->itemService->findAllNew($id, $type, $paddedLastModified,
true, $this->userId)
$this->itemService->findAllNew(
$id, $type, $paddedLastModified,
true, $this->userId
)
);
}
private function setRead($isRead, $itemId) {
private function setRead($isRead, $itemId)
{
try {
$this->itemService->read($itemId, $isRead, $this->userId);
} catch(ServiceNotFoundException $ex){
@ -105,7 +112,8 @@ class ItemApiController extends ApiController {
* @param int $itemId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function read($itemId) {
public function read($itemId)
{
return $this->setRead(true, $itemId);
}
@ -118,12 +126,14 @@ class ItemApiController extends ApiController {
* @param int $itemId
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function unread($itemId) {
public function unread($itemId)
{
return $this->setRead(false, $itemId);
}
private function setStarred($isStarred, $feedId, $guidHash) {
private function setStarred($isStarred, $feedId, $guidHash)
{
try {
$this->itemService->star(
$feedId, $guidHash, $isStarred, $this->userId
@ -141,11 +151,12 @@ class ItemApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*
* @param int $feedId
* @param int $feedId
* @param string $guidHash
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function star($feedId, $guidHash) {
public function star($feedId, $guidHash)
{
return $this->setStarred(true, $feedId, $guidHash);
}
@ -155,11 +166,12 @@ class ItemApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*
* @param int $feedId
* @param int $feedId
* @param string $guidHash
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function unstar($feedId, $guidHash) {
public function unstar($feedId, $guidHash)
{
return $this->setStarred(false, $feedId, $guidHash);
}
@ -171,12 +183,14 @@ class ItemApiController extends ApiController {
*
* @param int $newestItemId
*/
public function readAll($newestItemId) {
public function readAll($newestItemId)
{
$this->itemService->readAll($newestItemId, $this->userId);
}
private function setMultipleRead($isRead, $items) {
private function setMultipleRead($isRead, $items)
{
foreach($items as $id) {
try {
$this->itemService->read($id, $isRead, $this->userId);
@ -194,7 +208,8 @@ class ItemApiController extends ApiController {
*
* @param int[] item ids
*/
public function readMultiple($items) {
public function readMultiple($items)
{
$this->setMultipleRead(true, $items);
}
@ -206,16 +221,20 @@ class ItemApiController extends ApiController {
*
* @param int[] item ids
*/
public function unreadMultiple($items) {
public function unreadMultiple($items)
{
$this->setMultipleRead(false, $items);
}
private function setMultipleStarred($isStarred, $items) {
private function setMultipleStarred($isStarred, $items)
{
foreach($items as $item) {
try {
$this->itemService->star($item['feedId'], $item['guidHash'],
$isStarred, $this->userId);
$this->itemService->star(
$item['feedId'], $item['guidHash'],
$isStarred, $this->userId
);
} catch(ServiceNotFoundException $ex) {
continue;
}
@ -230,7 +249,8 @@ class ItemApiController extends ApiController {
*
* @param int[] item ids
*/
public function starMultiple($items) {
public function starMultiple($items)
{
$this->setMultipleStarred(true, $items);
}
@ -242,7 +262,8 @@ class ItemApiController extends ApiController {
*
* @param int[] item ids
*/
public function unstarMultiple($items) {
public function unstarMultiple($items)
{
$this->setMultipleStarred(false, $items);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -24,7 +24,8 @@ use \OCA\News\Service\ItemService;
use \OCA\News\Service\FeedService;
class ItemController extends Controller {
class ItemController extends Controller
{
use JSONHttpError;
@ -33,13 +34,14 @@ class ItemController extends Controller {
private $userId;
private $settings;
public function __construct($AppName,
IRequest $request,
FeedService $feedService,
ItemService $itemService,
IConfig $settings,
$UserId){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
FeedService $feedService,
ItemService $itemService,
IConfig $settings,
$UserId
) {
parent::__construct($appName, $request);
$this->itemService = $itemService;
$this->feedService = $feedService;
$this->userId = $UserId;
@ -50,23 +52,24 @@ class ItemController extends Controller {
/**
* @NoAdminRequired
*
* @param int $type
* @param int $id
* @param int $limit
* @param int $offset
* @param bool $showAll
* @param bool $oldestFirst
* @param int $type
* @param int $id
* @param int $limit
* @param int $offset
* @param bool $showAll
* @param bool $oldestFirst
* @param string $search
* @return array
*/
public function index($type=3, $id=0, $limit=50, $offset=0, $showAll=null,
$oldestFirst=null, $search='') {
$oldestFirst=null, $search=''
) {
// in case this is called directly and not from the website use the
// internal state
if ($showAll === null) {
$showAll = $this->settings->getUserValue(
$this->userId, $this->appName,'showAll'
$this->userId, $this->appName, 'showAll'
) === '1';
}
@ -76,10 +79,14 @@ class ItemController extends Controller {
) === '1';
}
$this->settings->setUserValue($this->userId, $this->appName,
'lastViewedFeedId', $id);
$this->settings->setUserValue($this->userId, $this->appName,
'lastViewedFeedType', $type);
$this->settings->setUserValue(
$this->userId, $this->appName,
'lastViewedFeedId', $id
);
$this->settings->setUserValue(
$this->userId, $this->appName,
'lastViewedFeedType', $type
);
$params = [];
@ -110,9 +117,10 @@ class ItemController extends Controller {
$this->userId, $search
);
// this gets thrown if there are no items
// in that case just return an empty array
} catch(ServiceException $ex) {}
// this gets thrown if there are no items
// in that case just return an empty array
} catch(ServiceException $ex) {
}
return $params;
}
@ -126,9 +134,12 @@ class ItemController extends Controller {
* @param int $lastModified
* @return array
*/
public function newItems($type, $id, $lastModified=0) {
$showAll = $this->settings->getUserValue($this->userId, $this->appName,
'showAll') === '1';
public function newItems($type, $id, $lastModified=0)
{
$showAll = $this->settings->getUserValue(
$this->userId, $this->appName,
'showAll'
) === '1';
$params = [];
@ -138,12 +149,15 @@ class ItemController extends Controller {
$params['feeds'] = $this->feedService->findAll($this->userId);
$params['starred'] =
$this->itemService->starredCount($this->userId);
$params['items'] = $this->itemService->findAllNew($id, $type,
$lastModified, $showAll, $this->userId);
$params['items'] = $this->itemService->findAllNew(
$id, $type,
$lastModified, $showAll, $this->userId
);
// this gets thrown if there are no items
// in that case just return an empty array
} catch(ServiceException $ex) {}
// this gets thrown if there are no items
// in that case just return an empty array
} catch(ServiceException $ex) {
}
return $params;
}
@ -152,15 +166,18 @@ class ItemController extends Controller {
/**
* @NoAdminRequired
*
* @param int $feedId
* @param int $feedId
* @param string $guidHash
* @param bool $isStarred
* @param bool $isStarred
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function star($feedId, $guidHash, $isStarred){
public function star($feedId, $guidHash, $isStarred)
{
try {
$this->itemService->star($feedId, $guidHash, $isStarred,
$this->userId);
$this->itemService->star(
$feedId, $guidHash, $isStarred,
$this->userId
);
} catch(ServiceException $ex) {
return $this->error($ex, Http::STATUS_NOT_FOUND);
}
@ -172,11 +189,12 @@ class ItemController extends Controller {
/**
* @NoAdminRequired
*
* @param int $itemId
* @param int $itemId
* @param bool $isRead
* @return array|\OCP\AppFramework\Http\JSONResponse
*/
public function read($itemId, $isRead=true){
public function read($itemId, $isRead=true)
{
try {
$this->itemService->read($itemId, $isRead, $this->userId);
} catch(ServiceException $ex) {
@ -193,7 +211,8 @@ class ItemController extends Controller {
* @param int $highestItemId
* @return array
*/
public function readAll($highestItemId){
public function readAll($highestItemId)
{
$this->itemService->readAll($highestItemId, $this->userId);
return ['feeds' => $this->feedService->findAll($this->userId)];
}
@ -204,7 +223,8 @@ class ItemController extends Controller {
*
* @param int[] item ids
*/
public function readMultiple($itemIds) {
public function readMultiple($itemIds)
{
foreach($itemIds as $id) {
try {
$this->itemService->read($id, true, $this->userId);

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2014
*/
@ -14,16 +14,18 @@ namespace OCA\News\Controller;
use \OCP\AppFramework\Http\JSONResponse;
trait JSONHttpError {
trait JSONHttpError
{
/**
* @param \Exception $exception the message that is returned taken from the
* exception
* @param int $code the http error code
* exception
* @param int $code the http error code
* @return \OCP\AppFramework\Http\JSONResponse
*/
public function error(\Exception $exception, $code) {
public function error(\Exception $exception, $code)
{
return new JSONResponse(['message' => $exception->getMessage()], $code);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -29,7 +29,8 @@ use OCA\News\Explore\RecommendedSites;
use OCA\News\Explore\RecommendedSiteNotFoundException;
use OCA\News\Db\FeedType;
class PageController extends Controller {
class PageController extends Controller
{
private $settings;
private $l10n;
@ -41,16 +42,17 @@ class PageController extends Controller {
use JSONHttpError;
public function __construct($AppName,
IRequest $request,
IConfig $settings,
IURLGenerator $urlGenerator,
Config $config,
IL10N $l10n,
RecommendedSites $recommendedSites,
StatusService $statusService,
$UserId){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
IConfig $settings,
IURLGenerator $urlGenerator,
Config $config,
IL10N $l10n,
RecommendedSites $recommendedSites,
StatusService $statusService,
$UserId
) {
parent::__construct($appName, $request);
$this->settings = $settings;
$this->urlGenerator = $urlGenerator;
$this->l10n = $l10n;
@ -65,12 +67,15 @@ class PageController extends Controller {
* @NoAdminRequired
* @NoCSRFRequired
*/
public function index() {
public function index()
{
$status = $this->statusService->getStatus();
$response = new TemplateResponse($this->appName, 'index', [
$response = new TemplateResponse(
$this->appName, 'index', [
'warnings' => $status['warnings'],
'url_generator' => $this->urlGenerator
]);
]
);
$csp = new ContentSecurityPolicy();
$csp->addAllowedImageDomain('*')
@ -91,7 +96,8 @@ class PageController extends Controller {
/**
* @NoAdminRequired
*/
public function settings() {
public function settings()
{
$settings = [
'showAll',
'compact',
@ -132,7 +138,8 @@ class PageController extends Controller {
* @param bool $oldestFirst
*/
public function updateSettings($showAll, $compact, $preventReadOnScroll,
$oldestFirst, $compactExpand) {
$oldestFirst, $compactExpand
) {
$settings = ['showAll',
'compact',
'preventReadOnScroll',
@ -146,8 +153,10 @@ class PageController extends Controller {
} else {
$value = '0';
}
$this->settings->setUserValue($this->userId, $this->appName,
$setting, $value);
$this->settings->setUserValue(
$this->userId, $this->appName,
$setting, $value
);
}
}
@ -156,11 +165,16 @@ class PageController extends Controller {
*
* @param string $lang
*/
public function explore($lang) {
$this->settings->setUserValue($this->userId, $this->appName,
'lastViewedFeedId', 0);
$this->settings->setUserValue($this->userId, $this->appName,
'lastViewedFeedType', FeedType::EXPLORE);
public function explore($lang)
{
$this->settings->setUserValue(
$this->userId, $this->appName,
'lastViewedFeedId', 0
);
$this->settings->setUserValue(
$this->userId, $this->appName,
'lastViewedFeedType', FeedType::EXPLORE
);
try {
return $this->recommendedSites->forLanguage($lang);

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -19,16 +19,18 @@ use \OCP\IURLGenerator;
use \OCP\Files\IRootFolder;
use \OCP\AppFramework\Http;
class UserApiController extends ApiController {
class UserApiController extends ApiController
{
private $userSession;
private $rootFolder;
public function __construct($AppName,
IRequest $request,
IUserSession $userSession,
IRootFolder $rootFolder){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
IUserSession $userSession,
IRootFolder $rootFolder
) {
parent::__construct($appName, $request);
$this->userSession = $userSession;
$this->rootFolder = $rootFolder;
}
@ -38,7 +40,8 @@ class UserApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*/
public function index() {
public function index()
{
$user = $this->userSession->getUser();
// find the avatar

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Controller;
@ -21,18 +21,20 @@ use \OCA\News\Utility\Updater;
use \OCA\News\Service\StatusService;
class UtilityApiController extends ApiController {
class UtilityApiController extends ApiController
{
private $updater;
private $settings;
private $statusService;
public function __construct($AppName,
IRequest $request,
Updater $updater,
IConfig $settings,
StatusService $statusService){
parent::__construct($AppName, $request);
public function __construct($appName,
IRequest $request,
Updater $updater,
IConfig $settings,
StatusService $statusService
) {
parent::__construct($appName, $request);
$this->updater = $updater;
$this->settings = $settings;
$this->statusService = $statusService;
@ -44,9 +46,12 @@ class UtilityApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*/
public function version() {
$version = $this->settings->getAppValue($this->appName,
'installed_version');
public function version()
{
$version = $this->settings->getAppValue(
$this->appName,
'installed_version'
);
return ['version' => $version];
}
@ -55,7 +60,8 @@ class UtilityApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*/
public function beforeUpdate() {
public function beforeUpdate()
{
$this->updater->beforeUpdate();
}
@ -64,7 +70,8 @@ class UtilityApiController extends ApiController {
* @NoCSRFRequired
* @CORS
*/
public function afterUpdate() {
public function afterUpdate()
{
$this->updater->afterUpdate();
}
@ -74,7 +81,8 @@ class UtilityApiController extends ApiController {
* @NoCSRFRequired
* @NoAdminRequired
*/
public function status() {
public function status()
{
return $this->statusService->getStatus();
}

View File

@ -6,7 +6,7 @@
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Cron;
@ -17,7 +17,8 @@ use OCA\News\Config\Config;
use OCA\News\Service\StatusService;
use OCA\News\Utility\Updater as UpdaterService;
class Updater extends Job {
class Updater extends Job
{
/**
* @var Config
@ -33,15 +34,18 @@ class Updater extends Job {
private $updaterService;
public function __construct(Config $config, StatusService $status,
UpdaterService $updaterService) {
UpdaterService $updaterService
) {
$this->config = $config;
$this->status = $status;
$this->updaterService = $updaterService;
}
protected function run($argument) {
if ($this->config->getUseCronUpdates() &&
$this->status->isProperlyConfigured()) {
protected function run($argument)
{
if ($this->config->getUseCronUpdates()
&& $this->status->isProperlyConfigured()
) {
$this->updaterService->beforeUpdate();
$this->updaterService->update();
$this->updaterService->afterUpdate();

View File

@ -5,18 +5,20 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
trait EntityJSONSerializer {
trait EntityJSONSerializer
{
public function serializeFields($properties) {
public function serializeFields($properties)
{
$result = [];
foreach($properties as $property) {
$result[$property] = $this->$property;

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -63,7 +63,8 @@ use \OCP\AppFramework\Db\Entity;
* @method string getBasicAuthPassword()
* @method void setBasicAuthPassword(string $value)
*/
class Feed extends Entity implements IAPI, \JsonSerializable {
class Feed extends Entity implements IAPI, \JsonSerializable
{
use EntityJSONSerializer;
@ -92,7 +93,8 @@ class Feed extends Entity implements IAPI, \JsonSerializable {
protected $basicAuthUser;
protected $basicAuthPassword;
public function __construct(){
public function __construct()
{
$this->addType('parentId', 'integer');
$this->addType('added', 'integer');
$this->addType('folderId', 'integer');
@ -111,8 +113,10 @@ class Feed extends Entity implements IAPI, \JsonSerializable {
/**
* Turns entitie attributes into an array
*/
public function jsonSerialize() {
$serialized = $this->serializeFields([
public function jsonSerialize()
{
$serialized = $this->serializeFields(
[
'id',
'userId',
'urlHash',
@ -135,7 +139,8 @@ class Feed extends Entity implements IAPI, \JsonSerializable {
'lastUpdateError',
'basicAuthUser',
'basicAuthPassword'
]);
]
);
$url = parse_url($this->link, PHP_URL_HOST);
@ -150,8 +155,10 @@ class Feed extends Entity implements IAPI, \JsonSerializable {
}
public function toAPI() {
return $this->serializeFields([
public function toAPI()
{
return $this->serializeFields(
[
'id',
'url',
'title',
@ -164,11 +171,13 @@ class Feed extends Entity implements IAPI, \JsonSerializable {
'pinned',
'updateErrorCount',
'lastUpdateError'
]);
]
);
}
public function setUrl($url) {
public function setUrl($url)
{
$url = trim($url);
if(strpos($url, 'http') === 0) {
parent::setUrl($url);
@ -177,7 +186,8 @@ class Feed extends Entity implements IAPI, \JsonSerializable {
}
public function setLink($url) {
public function setLink($url)
{
$url = trim($url);
if(strpos($url, 'http') === 0) {
parent::setLink($url);

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -18,15 +18,18 @@ use OCP\IDBConnection;
use OCP\AppFramework\Db\Entity;
class FeedMapper extends NewsMapper {
class FeedMapper extends NewsMapper
{
public function __construct(IDBConnection $db, Time $time) {
public function __construct(IDBConnection $db, Time $time)
{
parent::__construct($db, 'news_feeds', Feed::class, $time);
}
public function find($id, $userId){
public function find($id, $userId)
{
$sql = 'SELECT `feeds`.*, COUNT(`items`.`id`) AS `unread_count` ' .
'FROM `*PREFIX*news_feeds` `feeds` ' .
'LEFT JOIN `*PREFIX*news_items` `items` ' .
@ -45,7 +48,8 @@ class FeedMapper extends NewsMapper {
}
public function findAllFromUser($userId){
public function findAllFromUser($userId)
{
$sql = 'SELECT `feeds`.*, COUNT(`items`.`id`) AS `unread_count` ' .
'FROM `*PREFIX*news_feeds` `feeds` ' .
'LEFT OUTER JOIN `*PREFIX*news_folders` `folders` '.
@ -69,7 +73,8 @@ class FeedMapper extends NewsMapper {
}
public function findAll(){
public function findAll()
{
$sql = 'SELECT `feeds`.*, COUNT(`items`.`id`) AS `unread_count` ' .
'FROM `*PREFIX*news_feeds` `feeds` ' .
'LEFT OUTER JOIN `*PREFIX*news_folders` `folders` '.
@ -91,7 +96,8 @@ class FeedMapper extends NewsMapper {
}
public function findByUrlHash($hash, $userId){
public function findByUrlHash($hash, $userId)
{
$sql = 'SELECT `feeds`.*, COUNT(`items`.`id`) AS `unread_count` ' .
'FROM `*PREFIX*news_feeds` `feeds` ' .
'LEFT JOIN `*PREFIX*news_items` `items` ' .
@ -110,7 +116,8 @@ class FeedMapper extends NewsMapper {
}
public function delete(Entity $entity){
public function delete(Entity $entity)
{
parent::delete($entity);
// someone please slap me for doing this manually :P
@ -122,12 +129,13 @@ class FeedMapper extends NewsMapper {
/**
* @param int $deleteOlderThan if given gets all entries with a delete date
* older than that timestamp
* @param string $userId if given returns only entries from the given user
* @param int $deleteOlderThan if given gets all entries with a delete date
* older than that timestamp
* @param string $userId if given returns only entries from the given user
* @return array with the database rows
*/
public function getToDelete($deleteOlderThan=null, $userId=null) {
public function getToDelete($deleteOlderThan=null, $userId=null)
{
$sql = 'SELECT * FROM `*PREFIX*news_feeds` ' .
'WHERE `deleted_at` > 0 ';
$params = [];
@ -151,9 +159,11 @@ class FeedMapper extends NewsMapper {
/**
* Deletes all feeds of a user, delete items first since the user_id
* is not defined in there
*
* @param string $userId the name of the user
*/
public function deleteUser($userId) {
public function deleteUser($userId)
{
$sql = 'DELETE FROM `*PREFIX*news_feeds` WHERE `user_id` = ?';
$this->execute($sql, [$userId]);
}

View File

@ -5,16 +5,17 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
class FeedType {
class FeedType
{
const FEED = 0;
const FOLDER = 1;
const STARRED = 2;

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -30,9 +30,9 @@ use \OCP\AppFramework\Db\Entity;
* @method void setDeletedAt(integer $value)
* @method string getLastModified()
* @method void setLastModified(string $value)
*/
class Folder extends Entity implements IAPI, \JsonSerializable {
class Folder extends Entity implements IAPI, \JsonSerializable
{
use EntityJSONSerializer;
@ -43,7 +43,8 @@ class Folder extends Entity implements IAPI, \JsonSerializable {
protected $deletedAt;
protected $lastModified;
public function __construct(){
public function __construct()
{
$this->addType('parentId', 'integer');
$this->addType('opened', 'boolean');
$this->addType('deletedAt', 'integer');
@ -52,21 +53,27 @@ class Folder extends Entity implements IAPI, \JsonSerializable {
/**
* Turns entitie attributes into an array
*/
public function jsonSerialize() {
return $this->serializeFields([
public function jsonSerialize()
{
return $this->serializeFields(
[
'id',
'parentId',
'name',
'userId',
'opened',
'deletedAt',
]);
]
);
}
public function toAPI() {
return $this->serializeFields([
public function toAPI()
{
return $this->serializeFields(
[
'id',
'name'
]);
]
);
}
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -17,13 +17,16 @@ use OCA\News\Utility\Time;
use OCP\IDBConnection;
use OCP\AppFramework\Db\Entity;
class FolderMapper extends NewsMapper {
class FolderMapper extends NewsMapper
{
public function __construct(IDBConnection $db, Time $time) {
public function __construct(IDBConnection $db, Time $time)
{
parent::__construct($db, 'news_folders', Folder::class, $time);
}
public function find($id, $userId){
public function find($id, $userId)
{
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
'WHERE `id` = ? ' .
'AND `user_id` = ?';
@ -32,7 +35,8 @@ class FolderMapper extends NewsMapper {
}
public function findAllFromUser($userId){
public function findAllFromUser($userId)
{
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
'WHERE `user_id` = ? ' .
'AND `deleted_at` = 0';
@ -42,7 +46,8 @@ class FolderMapper extends NewsMapper {
}
public function findByName($folderName, $userId){
public function findByName($folderName, $userId)
{
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
'WHERE `name` = ? ' .
'AND `user_id` = ?';
@ -52,7 +57,8 @@ class FolderMapper extends NewsMapper {
}
public function delete(Entity $entity){
public function delete(Entity $entity)
{
parent::delete($entity);
// someone please slap me for doing this manually :P
@ -71,12 +77,13 @@ class FolderMapper extends NewsMapper {
/**
* @param int $deleteOlderThan if given gets all entries with a delete date
* older than that timestamp
* @param string $userId if given returns only entries from the given user
* @param int $deleteOlderThan if given gets all entries with a delete date
* older than that timestamp
* @param string $userId if given returns only entries from the given user
* @return array with the database rows
*/
public function getToDelete($deleteOlderThan=null, $userId=null) {
public function getToDelete($deleteOlderThan=null, $userId=null)
{
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
'WHERE `deleted_at` > 0 ';
$params = [];
@ -99,9 +106,11 @@ class FolderMapper extends NewsMapper {
/**
* Deletes all folders of a user
*
* @param string $userId the name of the user
*/
public function deleteUser($userId) {
public function deleteUser($userId)
{
$sql = 'DELETE FROM `*PREFIX*news_folders` WHERE `user_id` = ?';
$this->execute($sql, [$userId]);
}

View File

@ -5,14 +5,15 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
interface IAPI {
interface IAPI
{
public function toAPI();
}

View File

@ -7,8 +7,8 @@
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Alessandro Cosentino 2012
* @copyright Bernhard Posselt 2012, 2014
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -46,7 +46,8 @@ use \OCP\AppFramework\Db\Entity;
* @method void setUnread(bool $value)
* @method void setStarred(bool $value)
*/
class Item extends Entity implements IAPI, \JsonSerializable {
class Item extends Entity implements IAPI, \JsonSerializable
{
use EntityJSONSerializer;
@ -70,7 +71,8 @@ class Item extends Entity implements IAPI, \JsonSerializable {
protected $unread = false;
protected $starred = false;
public function __construct() {
public function __construct()
{
$this->addType('pubDate', 'integer');
$this->addType('updatedDate', 'integer');
$this->addType('feedId', 'integer');
@ -79,18 +81,21 @@ class Item extends Entity implements IAPI, \JsonSerializable {
$this->addType('starred', 'boolean');
}
public function isUnread() {
public function isUnread()
{
return $this->unread;
}
public function isStarred() {
public function isStarred()
{
return $this->starred;
}
/**
* Turns entity attributes into an array
*/
public function jsonSerialize() {
public function jsonSerialize()
{
return [
'id' => $this->getId(),
'guid' => $this->getGuid(),
@ -113,7 +118,8 @@ class Item extends Entity implements IAPI, \JsonSerializable {
];
}
public function toAPI() {
public function toAPI()
{
return [
'id' => $this->getId(),
'guid' => $this->getGuid(),
@ -136,7 +142,8 @@ class Item extends Entity implements IAPI, \JsonSerializable {
];
}
public function toExport($feeds) {
public function toExport($feeds)
{
return [
'guid' => $this->getGuid(),
'url' => $this->getUrl(),
@ -154,11 +161,13 @@ class Item extends Entity implements IAPI, \JsonSerializable {
];
}
public function getIntro() {
public function getIntro()
{
return strip_tags($this->getBody());
}
public static function fromImport($import) {
public static function fromImport($import)
{
$item = new static();
$item->setGuid($import['guid']);
$item->setGuidHash($import['guid']);
@ -177,15 +186,18 @@ class Item extends Entity implements IAPI, \JsonSerializable {
return $item;
}
public function setAuthor($name) {
public function setAuthor($name)
{
parent::setAuthor(strip_tags($name));
}
public function setTitle($title) {
public function setTitle($title)
{
parent::setTitle(strip_tags($title));
}
public function generateSearchIndex() {
public function generateSearchIndex()
{
$this->setSearchIndex(
mb_strtolower(
html_entity_decode(strip_tags($this->getBody())) .
@ -199,36 +211,47 @@ class Item extends Entity implements IAPI, \JsonSerializable {
$this->setContentHash($this->computeContentHash());
}
private function computeContentHash() {
return md5($this->getTitle() . $this->getUrl() . $this->getBody() .
private function computeContentHash()
{
return md5(
$this->getTitle() . $this->getUrl() . $this->getBody() .
$this->getEnclosureLink() . $this->getEnclosureMime() .
$this->getAuthor());
$this->getAuthor()
);
}
private function computeFingerprint() {
return md5($this->getTitle() . $this->getUrl() . $this->getBody() .
$this->getEnclosureLink());
private function computeFingerprint()
{
return md5(
$this->getTitle() . $this->getUrl() . $this->getBody() .
$this->getEnclosureLink()
);
}
public function setUrl($url) {
public function setUrl($url)
{
$url = trim($url);
if (strpos($url, 'http') === 0 || strpos($url, 'magnet') === 0) {
parent::setUrl($url);
}
}
public function setBody($body) {
public function setBody($body)
{
// FIXME: this should not happen if the target="_blank" is already
// on the link
parent::setBody(str_replace(
'<a', '<a target="_blank" rel="noreferrer"', $body
));
parent::setBody(
str_replace(
'<a', '<a target="_blank" rel="noreferrer"', $body
)
);
}
/**
* @return int
*/
public function cropApiLastModified() {
public function cropApiLastModified()
{
$lastModified = $this->getLastModified();
if (strlen((string)$lastModified) > 10) {
return (int)substr($lastModified, 0, -6);

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -19,14 +19,17 @@ use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\IDBConnection;
class ItemMapper extends NewsMapper {
class ItemMapper extends NewsMapper
{
public function __construct(IDBConnection $db, Time $time) {
public function __construct(IDBConnection $db, Time $time)
{
parent::__construct($db, 'news_items', Item::class, $time);
}
private function makeSelectQuery($prependTo = '', $oldestFirst = false,
$distinctFingerprint = false) {
$distinctFingerprint = false
) {
if ($oldestFirst) {
$ordering = 'ASC';
} else {
@ -48,11 +51,13 @@ class ItemMapper extends NewsMapper {
/**
* check if type is feed or all items should be shown
* @param bool $showAll
* @param int|null $type
*
* @param bool $showAll
* @param int|null $type
* @return string
*/
private function buildStatusQueryPart($showAll, $type = null) {
private function buildStatusQueryPart($showAll, $type = null)
{
$sql = '';
if (isset($type) && $type === FeedType::STARRED) {
@ -66,34 +71,40 @@ class ItemMapper extends NewsMapper {
return $sql;
}
private function buildSearchQueryPart(array $search = []) {
private function buildSearchQueryPart(array $search = [])
{
return str_repeat('AND `items`.`search_index` LIKE ? ', count($search));
}
/**
* wrap and escape search parameters in a like statement
*
* @param string[] $search an array of strings that should be searched
* @param string[] $search an array of strings that should be searched
* @return array with like parameters
*/
private function buildLikeParameters($search = []) {
return array_map(function ($param) {
$param = addcslashes($param, '\\_%');
return '%' . mb_strtolower($param, 'UTF-8') . '%';
}, $search);
private function buildLikeParameters($search = [])
{
return array_map(
function ($param) {
$param = addcslashes($param, '\\_%');
return '%' . mb_strtolower($param, 'UTF-8') . '%';
}, $search
);
}
/**
* @param int $id
* @param int $id
* @param string $userId
* @return \OCA\News\Db\Item
*/
public function find($id, $userId) {
public function find($id, $userId)
{
$sql = $this->makeSelectQuery('AND `items`.`id` = ? ');
return $this->findEntity($sql, [$userId, $id]);
}
public function starredCount($userId) {
public function starredCount($userId)
{
$sql = 'SELECT COUNT(*) AS size FROM `*PREFIX*news_items` `items` ' .
'JOIN `*PREFIX*news_feeds` `feeds` ' .
'ON `feeds`.`id` = `items`.`feed_id` ' .
@ -113,7 +124,8 @@ class ItemMapper extends NewsMapper {
}
public function readAll($highestItemId, $time, $userId) {
public function readAll($highestItemId, $time, $userId)
{
$sql = 'UPDATE `*PREFIX*news_items` ' .
'SET unread = ? ' .
', `last_modified` = ? ' .
@ -127,7 +139,8 @@ class ItemMapper extends NewsMapper {
}
public function readFolder($folderId, $highestItemId, $time, $userId) {
public function readFolder($folderId, $highestItemId, $time, $userId)
{
$sql = 'UPDATE `*PREFIX*news_items` ' .
'SET unread = ? ' .
', `last_modified` = ? ' .
@ -143,7 +156,8 @@ class ItemMapper extends NewsMapper {
}
public function readFeed($feedId, $highestItemId, $time, $userId) {
public function readFeed($feedId, $highestItemId, $time, $userId)
{
$sql = 'UPDATE `*PREFIX*news_items` ' .
'SET unread = ? ' .
', `last_modified` = ? ' .
@ -160,7 +174,8 @@ class ItemMapper extends NewsMapper {
}
private function getOperator($oldestFirst) {
private function getOperator($oldestFirst)
{
if ($oldestFirst) {
return '>';
} else {
@ -169,7 +184,8 @@ class ItemMapper extends NewsMapper {
}
public function findAllNew($updatedSince, $type, $showAll, $userId) {
public function findAllNew($updatedSince, $type, $showAll, $userId)
{
$sql = $this->buildStatusQueryPart($showAll, $type);
$sql .= 'AND `items`.`last_modified` >= ? ';
@ -179,7 +195,8 @@ class ItemMapper extends NewsMapper {
}
public function findAllNewFolder($id, $updatedSince, $showAll, $userId) {
public function findAllNewFolder($id, $updatedSince, $showAll, $userId)
{
$sql = $this->buildStatusQueryPart($showAll);
$sql .= 'AND `feeds`.`folder_id` = ? ' .
@ -190,7 +207,8 @@ class ItemMapper extends NewsMapper {
}
public function findAllNewFeed($id, $updatedSince, $showAll, $userId) {
public function findAllNewFeed($id, $updatedSince, $showAll, $userId)
{
$sql = $this->buildStatusQueryPart($showAll);
$sql .= 'AND `items`.`feed_id` = ? ' .
@ -201,7 +219,8 @@ class ItemMapper extends NewsMapper {
}
private function findEntitiesIgnoringNegativeLimit($sql, $params, $limit) {
private function findEntitiesIgnoringNegativeLimit($sql, $params, $limit)
{
// ignore limit if negative to offer a way to return all feeds
if ($limit >= 0) {
return $this->findEntities($sql, $params, $limit);
@ -212,7 +231,8 @@ class ItemMapper extends NewsMapper {
public function findAllFeed($id, $limit, $offset, $showAll, $oldestFirst,
$userId, $search = []) {
$userId, $search = []
) {
$params = [$userId];
$params = array_merge($params, $this->buildLikeParameters($search));
$params[] = $id;
@ -232,7 +252,8 @@ class ItemMapper extends NewsMapper {
public function findAllFolder($id, $limit, $offset, $showAll, $oldestFirst,
$userId, $search = []) {
$userId, $search = []
) {
$params = [$userId];
$params = array_merge($params, $this->buildLikeParameters($search));
$params[] = $id;
@ -252,7 +273,8 @@ class ItemMapper extends NewsMapper {
public function findAll($limit, $offset, $type, $showAll, $oldestFirst, $userId,
$search = []) {
$search = []
) {
$params = [$userId];
$params = array_merge($params, $this->buildLikeParameters($search));
$sql = $this->buildStatusQueryPart($showAll, $type);
@ -270,7 +292,8 @@ class ItemMapper extends NewsMapper {
}
public function findAllUnreadOrStarred($userId) {
public function findAllUnreadOrStarred($userId)
{
$params = [$userId, true, true];
$sql = 'AND (`items`.`unread` = ? OR `items`.`starred` = ?) ';
$sql = $this->makeSelectQuery($sql);
@ -278,10 +301,12 @@ class ItemMapper extends NewsMapper {
}
public function findByGuidHash($guidHash, $feedId, $userId) {
public function findByGuidHash($guidHash, $feedId, $userId)
{
$sql = $this->makeSelectQuery(
'AND `items`.`guid_hash` = ? ' .
'AND `feeds`.`id` = ? ');
'AND `feeds`.`id` = ? '
);
return $this->findEntity($sql, [$userId, $guidHash, $feedId]);
}
@ -290,9 +315,11 @@ class ItemMapper extends NewsMapper {
/**
* Delete all items for feeds that have over $threshold unread and not
* starred items
*
* @param int $threshold the number of items that should be deleted
*/
public function deleteReadOlderThanThreshold($threshold) {
public function deleteReadOlderThanThreshold($threshold)
{
$params = [false, false, $threshold];
$sql = 'SELECT (COUNT(*) - `feeds`.`articles_per_update`) AS `size`, ' .
@ -332,7 +359,8 @@ class ItemMapper extends NewsMapper {
}
public function getNewestItemId($userId) {
public function getNewestItemId($userId)
{
$sql = 'SELECT MAX(`items`.`id`) AS `max_id` ' .
'FROM `*PREFIX*news_items` `items` ' .
'JOIN `*PREFIX*news_feeds` `feeds` ' .
@ -348,9 +376,11 @@ class ItemMapper extends NewsMapper {
/**
* Deletes all items of a user
*
* @param string $userId the name of the user
*/
public function deleteUser($userId) {
public function deleteUser($userId)
{
$sql = 'DELETE FROM `*PREFIX*news_items` ' .
'WHERE `feed_id` IN (' .
'SELECT `feeds`.`id` FROM `*PREFIX*news_feeds` `feeds` ' .
@ -364,7 +394,8 @@ class ItemMapper extends NewsMapper {
/**
* Returns a list of ids and userid of all items
*/
public function findAllIds($limit = null, $offset = null) {
public function findAllIds($limit = null, $offset = null)
{
$sql = 'SELECT `id` FROM `*PREFIX*news_items`';
return $this->execute($sql, [], $limit, $offset)->fetchAll();
}
@ -372,7 +403,8 @@ class ItemMapper extends NewsMapper {
/**
* Update search indices of all items
*/
public function updateSearchIndices() {
public function updateSearchIndices()
{
// update indices in steps to prevent memory issues on larger systems
$step = 1000; // update 1000 items at a time
$itemCount = 1;
@ -387,7 +419,8 @@ class ItemMapper extends NewsMapper {
}
}
private function updateSearchIndex(array $items = []) {
private function updateSearchIndex(array $items = [])
{
foreach ($items as $row) {
$sql = 'SELECT * FROM `*PREFIX*news_items` WHERE `id` = ?';
$params = [$row['id']];
@ -397,7 +430,8 @@ class ItemMapper extends NewsMapper {
}
}
public function readItem($itemId, $isRead, $lastModified, $userId) {
public function readItem($itemId, $isRead, $lastModified, $userId)
{
$item = $this->find($itemId, $userId);
// reading an item should set all of the same items as read, whereas

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -20,28 +20,31 @@ use OCA\News\Db\Mysql\ItemMapper as MysqlItemMapper;
use OCA\News\DependencyInjection\IFactory;
class MapperFactory implements IFactory {
class MapperFactory implements IFactory
{
private $dbType;
private $db;
private $dbType;
private $db;
/**
* @var Time
*/
private $time;
public function __construct(IDBConnection $db, $databaseType, Time $time) {
$this->dbType = $databaseType;
$this->db = $db;
public function __construct(IDBConnection $db, $databaseType, Time $time)
{
$this->dbType = $databaseType;
$this->db = $db;
$this->time = $time;
}
public function build() {
switch($this->dbType) {
case 'mysql':
return new MysqlItemMapper($this->db, $this->time);
default:
return new ItemMapper($this->db, $this->time);
}
}
public function build()
{
switch($this->dbType) {
case 'mysql':
return new MysqlItemMapper($this->db, $this->time);
default:
return new ItemMapper($this->db, $this->time);
}
}
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db\Mysql;
@ -16,9 +16,11 @@ namespace OCA\News\Db\Mysql;
use OCA\News\Utility\Time;
use OCP\IDBConnection;
class ItemMapper extends \OCA\News\Db\ItemMapper {
class ItemMapper extends \OCA\News\Db\ItemMapper
{
public function __construct(IDBConnection $db, Time $time){
public function __construct(IDBConnection $db, Time $time)
{
parent::__construct($db, $time);
}
@ -26,9 +28,11 @@ class ItemMapper extends \OCA\News\Db\ItemMapper {
/**
* Delete all items for feeds that have over $threshold unread and not
* starred items
*
* @param int $threshold the number of items that should be deleted
*/
public function deleteReadOlderThanThreshold($threshold){
public function deleteReadOlderThanThreshold($threshold)
{
$sql = 'SELECT (COUNT(*) - `feeds`.`articles_per_update`) AS `size`, ' .
'`feeds`.`id` AS `feed_id`, `feeds`.`articles_per_update` ' .
'FROM `*PREFIX*news_items` `items` ' .
@ -62,7 +66,8 @@ class ItemMapper extends \OCA\News\Db\ItemMapper {
}
public function readItem($itemId, $isRead, $lastModified, $userId) {
public function readItem($itemId, $isRead, $lastModified, $userId)
{
$item = $this->find($itemId, $userId);
if ($isRead) {

View File

@ -7,8 +7,8 @@
*
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Alessandro Cosentino 2012
* @copyright Bernhard Posselt 2012, 2014
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Db;
@ -18,7 +18,8 @@ use OCP\IDBConnection;
use OCP\AppFramework\Db\Mapper;
use OCP\AppFramework\Db\Entity;
abstract class NewsMapper extends Mapper {
abstract class NewsMapper extends Mapper
{
/**
* @var Time
@ -26,23 +27,26 @@ abstract class NewsMapper extends Mapper {
private $time;
public function __construct(IDBConnection $db, $table, $entity,
Time $time) {
Time $time
) {
parent::__construct($db, $table, $entity);
$this->time = $time;
}
public function update(Entity $entity) {
public function update(Entity $entity)
{
$entity->setLastModified($this->time->getMicroTime());
return parent::update($entity);
}
public function insert(Entity $entity) {
public function insert(Entity $entity)
{
$entity->setLastModified($this->time->getMicroTime());
return parent::insert($entity);
}
/**
* @param int $id the id of the feed
* @param int $id the id of the feed
* @param string $userId the id of the user
*
* @return \OCP\AppFramework\Db\Entity
@ -57,27 +61,30 @@ abstract class NewsMapper extends Mapper {
* Important: This method does not filter marked as deleted rows!
*
* @param array $search an assoc array from property to filter value
* @param int $limit
* @param int $limit
*
* @paran int $offset
* @paran int $offset
* @return array
*/
public function where(array $search = [], $limit = null, $offset = null) {
public function where(array $search = [], $limit = null, $offset = null)
{
$entity = new $this->entityClass;
// turn keys into sql query filter, e.g. feedId -> feed_id = :feedId
$filter = array_map(function ($property) use ($entity) {
// check if the property actually exists on the entity to prevent
// accidental Sql injection
if (!property_exists($entity, $property)) {
$msg = 'Property ' . $property . ' does not exist on '
$filter = array_map(
function ($property) use ($entity) {
// check if the property actually exists on the entity to prevent
// accidental Sql injection
if (!property_exists($entity, $property)) {
$msg = 'Property ' . $property . ' does not exist on '
. $this->entityClass;
throw new \BadFunctionCallException($msg);
}
throw new \BadFunctionCallException($msg);
}
$column = $entity->propertyToColumn($property);
return $column . ' = :' . $property;
}, array_keys($search));
$column = $entity->propertyToColumn($property);
return $column . ' = :' . $property;
}, array_keys($search)
);
$andStatement = implode(' AND ', $filter);

View File

@ -5,18 +5,20 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\DependencyInjection;
interface IFactory {
interface IFactory
{
/**
* Method that constructs the object
*
* @return mixed the constructed object
*/
public function build();

View File

@ -5,16 +5,17 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Explore;
use Exception;
class RecommendedSiteNotFoundException extends Exception {
class RecommendedSiteNotFoundException extends Exception
{
}

View File

@ -5,28 +5,31 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Explore;
class RecommendedSites {
class RecommendedSites
{
private $directory;
/**
* @param string $exploreDir the absolute path to where the recommendation
* config files lie without a trailing slash
* config files lie without a trailing slash
*/
public function __construct($exploreDir) {
public function __construct($exploreDir)
{
$this->directory = $exploreDir;
}
public function forLanguage($languageCode) {
public function forLanguage($languageCode)
{
$file = $this->directory . '/feeds.' . $languageCode . '.json';
if (file_exists($file)) {

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Fetcher;
@ -38,7 +38,8 @@ use OCA\News\Utility\PicoFeedFaviconFactory;
use OCA\News\Utility\PicoFeedReaderFactory;
use OCA\News\Utility\Time;
class FeedFetcher implements IFeedFetcher {
class FeedFetcher implements IFeedFetcher
{
private $faviconFactory;
private $reader;
@ -47,10 +48,11 @@ class FeedFetcher implements IFeedFetcher {
private $clientService;
public function __construct(Reader $reader,
PicoFeedFaviconFactory $faviconFactory,
IL10N $l10n,
Time $time,
IClientService $clientService) {
PicoFeedFaviconFactory $faviconFactory,
IL10N $l10n,
Time $time,
IClientService $clientService
) {
$this->faviconFactory = $faviconFactory;
$this->reader = $reader;
$this->time = $time;
@ -62,39 +64,47 @@ class FeedFetcher implements IFeedFetcher {
/**
* This fetcher handles all the remaining urls therefore always returns true
*/
public function canHandle($url) {
public function canHandle($url)
{
return true;
}
/**
* Fetch a feed from remote
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified matches the http header from the feed
* no results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the http header from the feed
* no results are fetched
* @param bool fullTextEnabled if true tells the fetcher to enhance the
*
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified
* matches the http header from the feed no
* results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the
* http header from the feed no
* results are fetched
* @param bool fullTextEnabled if true tells the fetcher to enhance the
* articles by fetching custom enhanced content
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an empty string
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an
* empty string
* @throws FetcherException if it fails
* @return array an array containing the new feed and its items, first
* element being the Feed and second element being an array of Items
*/
public function fetch($url, $getFavicon = true, $lastModified = null,
$etag = null, $fullTextEnabled = false,
$basicAuthUser = null, $basicAuthPassword = null) {
$etag = null, $fullTextEnabled = false,
$basicAuthUser = null, $basicAuthPassword = null
) {
try {
if ($basicAuthUser !== null && trim($basicAuthUser) !== '') {
$resource = $this->reader->discover($url, $lastModified, $etag,
$resource = $this->reader->discover(
$url, $lastModified, $etag,
$basicAuthUser,
$basicAuthPassword);
$basicAuthPassword
);
} else {
$resource = $this->reader->discover($url, $lastModified, $etag);
}
@ -136,16 +146,19 @@ class FeedFetcher implements IFeedFetcher {
}
private function handleError(Exception $ex, $url) {
private function handleError(Exception $ex, $url)
{
$msg = $ex->getMessage();
if ($ex instanceof MalFormedXmlException) {
$msg = $this->l10n->t('Feed contains invalid XML');
} else if ($ex instanceof SubscriptionNotFoundException) {
$msg = $this->l10n->t('Feed not found: Either the website ' .
$msg = $this->l10n->t(
'Feed not found: Either the website ' .
'does not provide a feed or blocks access. To rule out ' .
'blocking, try to download the feed on your server\'s ' .
'command line using curl: curl ' . $url);
'command line using curl: curl ' . $url
);
} else if ($ex instanceof UnsupportedFeedFormatException) {
$msg = $this->l10n->t('Detected feed format is not supported');
} else if ($ex instanceof InvalidCertificateException) {
@ -159,8 +172,10 @@ class FeedFetcher implements IFeedFetcher {
} else if ($ex instanceof TimeoutException) {
$msg = $this->l10n->t('Request timed out');
} else if ($ex instanceof UnauthorizedException) {
$msg = $this->l10n->t('Required credentials for feed were ' .
'either missing or incorrect');
$msg = $this->l10n->t(
'Required credentials for feed were ' .
'either missing or incorrect'
);
} else if ($ex instanceof ForbiddenException) {
$msg = $this->l10n->t('Forbidden to access feed');
}
@ -168,57 +183,59 @@ class FeedFetcher implements IFeedFetcher {
throw new FetcherException($msg);
}
private function buildCurlSslErrorMessage($errorCode) {
private function buildCurlSslErrorMessage($errorCode)
{
switch ($errorCode) {
case 35: // CURLE_SSL_CONNECT_ERROR
return $this->l10n->t(
'Certificate error: A problem occurred ' .
case 35: // CURLE_SSL_CONNECT_ERROR
return $this->l10n->t(
'Certificate error: A problem occurred ' .
'somewhere in the SSL/TLS handshake. Could be ' .
'certificates (file formats, paths, permissions), ' .
'passwords, and others.'
);
case 51: // CURLE_PEER_FAILED_VERIFICATION
return $this->l10n->t(
'Certificate error: The remote server\'s SSL ' .
);
case 51: // CURLE_PEER_FAILED_VERIFICATION
return $this->l10n->t(
'Certificate error: The remote server\'s SSL ' .
'certificate or SSH md5 fingerprint was deemed not OK.'
);
case 58: // CURLE_SSL_CERTPROBLEM
return $this->l10n->t(
'Certificate error: Problem with the local client ' .
);
case 58: // CURLE_SSL_CERTPROBLEM
return $this->l10n->t(
'Certificate error: Problem with the local client ' .
'certificate.'
);
case 59: // CURLE_SSL_CIPHER
return $this->l10n->t(
'Certificate error: Couldn\'t use specified cipher.'
);
case 60: // CURLE_SSL_CACERT
return $this->l10n->t(
'Certificate error: Peer certificate cannot be ' .
);
case 59: // CURLE_SSL_CIPHER
return $this->l10n->t(
'Certificate error: Couldn\'t use specified cipher.'
);
case 60: // CURLE_SSL_CACERT
return $this->l10n->t(
'Certificate error: Peer certificate cannot be ' .
'authenticated with known CA certificates.'
);
case 64: // CURLE_USE_SSL_FAILED
return $this->l10n->t(
'Certificate error: Requested FTP SSL level failed.'
);
case 66: // CURLE_SSL_ENGINE_INITFAILED
return $this->l10n->t(
'Certificate error: Initiating the SSL engine failed.'
);
case 77: // CURLE_SSL_CACERT_BADFILE
return $this->l10n->t(
'Certificate error: Problem with reading the SSL CA ' .
);
case 64: // CURLE_USE_SSL_FAILED
return $this->l10n->t(
'Certificate error: Requested FTP SSL level failed.'
);
case 66: // CURLE_SSL_ENGINE_INITFAILED
return $this->l10n->t(
'Certificate error: Initiating the SSL engine failed.'
);
case 77: // CURLE_SSL_CACERT_BADFILE
return $this->l10n->t(
'Certificate error: Problem with reading the SSL CA ' .
'cert (path? access rights?)'
);
case 83: // CURLE_SSL_ISSUER_ERROR
return $this->l10n->t(
'Certificate error: Issuer check failed'
);
default:
return $this->l10n->t('Unknown SSL certificate error!');
);
case 83: // CURLE_SSL_ISSUER_ERROR
return $this->l10n->t(
'Certificate error: Issuer check failed'
);
default:
return $this->l10n->t('Unknown SSL certificate error!');
}
}
private function decodeTwice($string) {
private function decodeTwice($string)
{
return html_entity_decode(
html_entity_decode(
$string, ENT_QUOTES | ENT_HTML5, 'UTF-8'
@ -228,7 +245,8 @@ class FeedFetcher implements IFeedFetcher {
}
protected function determineRtl($parsedItem, $parsedFeed) {
protected function determineRtl($parsedItem, $parsedFeed)
{
$itemLang = $parsedItem->getLanguage();
$feedLang = $parsedFeed->getLanguage();
@ -240,7 +258,8 @@ class FeedFetcher implements IFeedFetcher {
}
protected function buildItem($parsedItem, $parsedFeed) {
protected function buildItem($parsedItem, $parsedFeed)
{
$item = new Item();
$item->setUnread(true);
$item->setUrl($parsedItem->getUrl());
@ -256,15 +275,17 @@ class FeedFetcher implements IFeedFetcher {
// purification is done in the service layer
$body = $parsedItem->getContent();
$body = mb_convert_encoding($body, 'HTML-ENTITIES',
mb_detect_encoding($body));
$body = mb_convert_encoding(
$body, 'HTML-ENTITIES',
mb_detect_encoding($body)
);
$item->setBody($body);
$enclosureUrl = $parsedItem->getEnclosureUrl();
if ($enclosureUrl) {
$enclosureType = $parsedItem->getEnclosureType();
if (stripos($enclosureType, 'audio/') !== false ||
stripos($enclosureType, 'video/') !== false
if (stripos($enclosureType, 'audio/') !== false
|| stripos($enclosureType, 'video/') !== false
) {
$item->setEnclosureMime($enclosureType);
$item->setEnclosureLink($enclosureUrl);
@ -278,7 +299,8 @@ class FeedFetcher implements IFeedFetcher {
protected function buildFeed($parsedFeed, $url, $getFavicon, $modified,
$etag, $location) {
$etag, $location
) {
$feed = new Feed();
$link = $parsedFeed->getSiteUrl();

View File

@ -5,60 +5,71 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Fetcher;
class Fetcher {
class Fetcher
{
private $fetchers;
public function __construct(){
public function __construct()
{
$this->fetchers = [];
}
/**
* Add an additional fetcher
*
* @param IFeedFetcher $fetcher the fetcher
*/
public function registerFetcher(IFeedFetcher $fetcher){
public function registerFetcher(IFeedFetcher $fetcher)
{
$this->fetchers[] = $fetcher;
}
/**
* Fetch a feed from remote
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified matches the http header from the feed
* no results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the http header from the feed
* no results are fetched
* @param bool fullTextEnabled if true tells the fetcher to enhance the
*
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified
* matches the http header from the feed no
* results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the
* http header from the feed no
* results are fetched
* @param bool fullTextEnabled if true tells the fetcher to enhance the
* articles by fetching custom enhanced content
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an empty string
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an
* empty string
* @throws FetcherException if simple pie fails
* @return array an array containing the new feed and its items, first
* element being the Feed and second element being an array of Items
*/
public function fetch($url, $getFavicon=true, $lastModified=null,
$etag=null, $fullTextEnabled=false,
$basicAuthUser=null, $basicAuthPassword=null) {
$etag=null, $fullTextEnabled=false,
$basicAuthUser=null, $basicAuthPassword=null
) {
foreach($this->fetchers as $fetcher){
if($fetcher->canHandle($url)){
return $fetcher->fetch($url, $getFavicon, $lastModified, $etag,
$fullTextEnabled, $basicAuthUser,
$basicAuthPassword);
if($fetcher->canHandle($url)) {
return $fetcher->fetch(
$url, $getFavicon, $lastModified, $etag,
$fullTextEnabled, $basicAuthUser,
$basicAuthPassword
);
}
}

View File

@ -5,21 +5,24 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Fetcher;
class FetcherException extends \Exception {
class FetcherException extends \Exception
{
/**
* Constructor
*
* @param string $msg the error message
*/
public function __construct($msg){
public function __construct($msg)
{
parent::__construct($msg);
}

View File

@ -5,38 +5,43 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Fetcher;
interface IFeedFetcher {
interface IFeedFetcher
{
/**
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified matches the http header from the feed
* no results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the http header from the feed
* no results are fetched
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified
* matches the http header from the feed no
* results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the
* http header from the feed no
* results are fetched
* @param bool fullTextEnabled if true tells the fetcher to enhance the
* articles by fetching custom enhanced content
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an empty string
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an
* empty string
* @throws FetcherException if the fetcher encounters a problem
* @return array an array containing the new feed and its items, first
* element being the Feed and second element being an array of Items
*/
function fetch($url, $getFavicon=true, $lastModified=null, $etag=null,
$fullTextEnabled=false, $basicAuthUser=null,
$basicAuthPassword=null);
$fullTextEnabled=false, $basicAuthUser=null,
$basicAuthPassword=null
);
/**
* @param string $url the url that should be fetched

View File

@ -5,23 +5,26 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
namespace OCA\News\Fetcher;
class YoutubeFetcher implements IFeedFetcher {
class YoutubeFetcher implements IFeedFetcher
{
private $feedFetcher;
public function __construct(FeedFetcher $feedFetcher){
public function __construct(FeedFetcher $feedFetcher)
{
$this->feedFetcher = $feedFetcher;
}
private function buildUrl($url) {
private function buildUrl($url)
{
$baseRegex = '%(?:https?://|//)?(?:www.)?youtube.com';
$playRegex = $baseRegex . '.*?list=([^&]*)%';
@ -37,34 +40,40 @@ class YoutubeFetcher implements IFeedFetcher {
/**
* This fetcher handles all the remaining urls therefore always returns true
*/
public function canHandle($url){
public function canHandle($url)
{
return $this->buildUrl($url) !== $url;
}
/**
* Fetch a feed from remote
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified matches the http header from the feed
* no results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the http header from the feed
* no results are fetched
* @param bool fullTextEnabled if true tells the fetcher to enhance the
*
* @param string $url remote url of the feed
* @param boolean $getFavicon if the favicon should also be fetched,
* defaults to true
* @param string $lastModified a last modified value from an http header
* defaults to false. If lastModified
* matches the http header from the feed no
* results are fetched
* @param string $etag an etag from an http header.
* If lastModified matches the
* http header from the feed no
* results are fetched
* @param bool fullTextEnabled if true tells the fetcher to enhance the
* articles by fetching custom enhanced content
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an empty string
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an
* empty string
* @throws FetcherException if it fails
* @return array an array containing the new feed and its items, first
* element being the Feed and second element being an array of Items
*/
public function fetch($url, $getFavicon=true, $lastModified=null,
$etag=null, $fullTextEnabled=false,
$basicAuthUser=null, $basicAuthPassword=null) {
$etag=null, $fullTextEnabled=false,
$basicAuthUser=null, $basicAuthPassword=null
) {
$transformedUrl = $this->buildUrl($url);
$result = $this->feedFetcher->fetch(

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Hooks;
@ -18,9 +18,11 @@ use OCA\News\Service\ItemService;
use OCA\News\Service\FeedService;
use OCA\News\Service\FolderService;
class User {
class User
{
public static function deleteUser($params) {
public static function deleteUser($params)
{
$userId = $params['uid'];
$app = new Application();

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Http;
@ -19,19 +19,22 @@ use \OCP\AppFramework\Http\DownloadResponse;
/**
* Prompts the user to download the a text file
*/
class TextDownloadResponse extends DownloadResponse {
class TextDownloadResponse extends DownloadResponse
{
private $content;
/**
* Creates a response that prompts the user to download a file which
* contains the passed string
* @param string $content the content that should be written into the file
* @param string $filename the name that the downloaded file should have
*
* @param string $content the content that should be written into the file
* @param string $filename the name that the downloaded file should have
* @param string $contentType the mimetype that the downloaded file should
* have
* have
*/
public function __construct($content, $filename, $contentType){
public function __construct($content, $filename, $contentType)
{
parent::__construct($filename, $contentType);
$this->content = $content;
}
@ -39,9 +42,11 @@ class TextDownloadResponse extends DownloadResponse {
/**
* Simply sets the headers and returns the file contents
*
* @return string the file contents
*/
public function render(){
public function render()
{
return $this->content;
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Http;
@ -18,17 +18,20 @@ use \OCP\AppFramework\Http\Response;
/**
* Just outputs text to the browser
*/
class TextResponse extends Response {
class TextResponse extends Response
{
private $content;
/**
* Creates a response that just outputs text
* @param string $content the content that should be written into the file
*
* @param string $content the content that should be written into the file
* @param string $contentType the mimetype. text/ is added automatically so
* only plain or html can be added to get text/plain or text/html
* only plain or html can be added to get text/plain or text/html
*/
public function __construct($content, $contentType='plain'){
public function __construct($content, $contentType='plain')
{
$this->content = $content;
$this->addHeader('Content-type', 'text/' . $contentType);
}
@ -36,9 +39,11 @@ class TextResponse extends Response {
/**
* Simply sets the headers and returns the file contents
*
* @return string the file contents
*/
public function render(){
public function render()
{
return $this->content;
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Daniel Opitz <dev@copynpaste.de>
* @author Daniel Opitz <dev@copynpaste.de>
* @copyright Daniel Opitz 2017
*/
@ -17,28 +17,36 @@ use OCP\IDBConnection;
use OCP\Migration\IRepairStep;
use OCP\Migration\IOutput;
class MigrateStatusFlags implements IRepairStep {
class MigrateStatusFlags implements IRepairStep
{
/** @var IDBConnection */
/**
* @var IDBConnection
*/
private $db;
/** @var IConfig */
/**
* @var IConfig
*/
private $config;
/**
* @param IDBConnection $db
* @param IConfig $config
* @param IConfig $config
*/
public function __construct(IDBConnection $db, IConfig $config) {
public function __construct(IDBConnection $db, IConfig $config)
{
$this->db = $db;
$this->config = $config;
}
public function getName() {
public function getName()
{
return 'Migrate binary status into separate boolean fields';
}
public function run(IOutput $output) {
public function run(IOutput $output)
{
$version = $this->config->getAppValue('news', 'installed_version', '0.0.0');
if (version_compare($version, '11.0.6', '>=')) {
return;

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Plugin\Client;
@ -20,24 +20,29 @@ namespace OCA\News\Plugin\Client;
* but atm there is no really good way since there is no uninstall hook which
* would remove the plugin from the apps so fk it :)
*/
class Plugin {
class Plugin
{
private static $scripts = [];
private static $styles = [];
public static function registerStyle($appName, $styleName) {
public static function registerStyle($appName, $styleName)
{
self::$styles[$appName] = $styleName;
}
public static function registerScript($appName, $scriptName) {
public static function registerScript($appName, $scriptName)
{
self::$scripts[$appName] = $scriptName;
}
public static function getStyles() {
public static function getStyles()
{
return self::$styles;
}
public static function getScripts() {
public static function getScripts()
{
return self::$scripts;
}

View File

@ -17,7 +17,8 @@ use PicoFeed\Parser\Item;
use PicoFeed\Processor\ItemProcessorInterface;
use PicoFeed\Scraper\RuleParser;
class LWNProcessor implements ItemProcessorInterface {
class LWNProcessor implements ItemProcessorInterface
{
private $user;
private $password;
@ -30,14 +31,16 @@ class LWNProcessor implements ItemProcessorInterface {
* @param $user
* @param $password
*/
public function __construct($user, $password, IClientService $clientService) {
public function __construct($user, $password, IClientService $clientService)
{
$this->user = $user;
$this->password = $password;
$this->clientService = $clientService;
$this->cookieJar = new CookieJar();
}
private function login() {
private function login()
{
if ($this->cookieJar->count() > 0) {
return true;
}
@ -46,36 +49,44 @@ class LWNProcessor implements ItemProcessorInterface {
}
$client = $this->clientService->newClient();
$response = $client->post('https://lwn.net/login', [
$response = $client->post(
'https://lwn.net/login', [
'cookies' => $this->cookieJar,
'body' => [
'Username' => $this->user,
'Password' => $this->password,
'target' => '/'
]
]);
]
);
return ($response->getStatusCode() === 200 && $this->cookieJar->count() > 0);
}
private function getBody($url) {
private function getBody($url)
{
$client = $this->clientService->newClient();
$response = $client->get($url, [
$response = $client->get(
$url, [
'cookies' => $this->cookieJar
]);
$parser = new RuleParser($response->getBody(), [
]
);
$parser = new RuleParser(
$response->getBody(), [
'body' => array(
'//div[@class="ArticleText"]',
),
'strip' => array(
'//div[@class="FeatureByline"]'
)
]);
]
);
$articleBody = $parser->execute();
// make all links absolute
return str_replace('href="/', 'href="https://lwn.net/', $articleBody);
}
private function canHandle($url) {
private function canHandle($url)
{
$regex = '%(?:https?://|//)?(?:www.)?lwn.net%';
return (bool)preg_match($regex, $url);
@ -89,7 +100,8 @@ class LWNProcessor implements ItemProcessorInterface {
* @param Item $item
* @return bool
*/
public function execute(Feed $feed, Item $item) {
public function execute(Feed $feed, Item $item)
{
if ($this->canHandle($item->getUrl())) {
$loggedIn = $this->login();

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
@ -29,7 +29,8 @@ use OCA\News\Config\Config;
use OCA\News\Utility\Time;
class FeedService extends Service {
class FeedService extends Service
{
private $feedFetcher;
private $itemMapper;
@ -42,14 +43,15 @@ class FeedService extends Service {
private $loggerParams;
public function __construct(FeedMapper $feedMapper,
Fetcher $feedFetcher,
ItemMapper $itemMapper,
ILogger $logger,
IL10N $l10n,
Time $timeFactory,
Config $config,
HTMLPurifier $purifier,
$LoggerParameters){
Fetcher $feedFetcher,
ItemMapper $itemMapper,
ILogger $logger,
IL10N $l10n,
Time $timeFactory,
Config $config,
HTMLPurifier $purifier,
$LoggerParameters
) {
parent::__construct($feedMapper);
$this->feedFetcher = $feedFetcher;
$this->itemMapper = $itemMapper;
@ -65,53 +67,63 @@ class FeedService extends Service {
/**
* Finds all feeds of a user
* @param string $userId the name of the user
*
* @param string $userId the name of the user
* @return Feed[]
*/
public function findAll($userId){
public function findAll($userId)
{
return $this->feedMapper->findAllFromUser($userId);
}
/**
* Finds all feeds from all users
*
* @return array of feeds
*/
public function findAllFromAllUsers() {
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
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an empty string
*
* @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
* @param string $basicAuthUser if given, basic auth is set for this feed
* @param string $basicAuthPassword if given, basic auth is set for this
* feed. Ignored if user is null or an empty string
* @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,
$basicAuthUser=null, $basicAuthPassword=null){
$basicAuthUser=null, $basicAuthPassword=null
) {
// first try if the feed exists already
try {
list($feed, $items) = $this->feedFetcher->fetch($feedUrl, true,
null, null, false, $basicAuthUser,
$basicAuthPassword);
list($feed, $items) = $this->feedFetcher->fetch(
$feedUrl, true,
null, null, false, $basicAuthUser,
$basicAuthPassword
);
// 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'));
$this->l10n->t('Can not add feed: Exists already')
);
// If no matching feed was found everything was ok
} catch(DoesNotExistException $ex){}
// If no matching feed was found everything was ok
} catch(DoesNotExistException $ex){
}
// insert feed
$itemCount = count($items);
@ -138,7 +150,8 @@ class FeedService extends Service {
// and ignore it if it does
try {
$this->itemMapper->findByGuidHash(
$item->getGuidHash(), $item->getFeedId(), $userId);
$item->getGuidHash(), $item->getFeedId(), $userId
);
continue;
} catch(DoesNotExistException $ex){
$unreadCount += 1;
@ -161,7 +174,8 @@ class FeedService extends Service {
/**
* Runs all the feed updates
*/
public function updateAll(){
public function updateAll()
{
// TODO: this method is not covered by any tests
$feeds = $this->feedMapper->findAll();
foreach($feeds as $feed){
@ -180,13 +194,15 @@ class FeedService extends Service {
/**
* Updates a single feed
* @param int $feedId the id of the feed that should be updated
* @param string $userId the id of the user
* @param bool $forceUpdate update even if the article exists already
*
* @param int $feedId the id of the feed that should be updated
* @param string $userId the id of the user
* @param bool $forceUpdate update even if the article exists already
* @throws ServiceNotFoundException if the feed does not exist
* @return Feed the updated feed entity
*/
public function update($feedId, $userId, $forceUpdate=false){
public function update($feedId, $userId, $forceUpdate=false)
{
$existingFeed = $this->find($feedId, $userId);
if($existingFeed->getPreventUpdate() === true) {
@ -229,7 +245,8 @@ class FeedService extends Service {
}
$existingFeed->setHttpLastModified(
$fetchedFeed->getHttpLastModified());
$fetchedFeed->getHttpLastModified()
);
$existingFeed->setHttpEtag($fetchedFeed->getHttpEtag());
$existingFeed->setLocation($fetchedFeed->getLocation());
@ -245,8 +262,9 @@ class FeedService extends Service {
);
// in case of update
if ($forceUpdate ||
$item->getUpdatedDate() > $dbItem->getUpdatedDate()) {
if ($forceUpdate
|| $item->getUpdatedDate() > $dbItem->getUpdatedDate()
) {
$dbItem->setTitle($item->getTitle());
$dbItem->setUrl($item->getUrl());
@ -295,11 +313,13 @@ class FeedService extends Service {
/**
* Import articles
* @param array $json the array with json
* @param string $userId the username
*
* @param array $json the array with json
* @param string $userId the username
* @return Feed if one had to be created for nonexistent feeds
*/
public function importArticles($json, $userId) {
public function importArticles($json, $userId)
{
$url = 'http://nextcloud/nofeed';
$urlHash = md5($url);
@ -343,7 +363,8 @@ class FeedService extends Service {
try {
// if item exists, copy the status
$existingItem = $this->itemMapper->findByGuidHash(
$item->getGuidHash(), $feed->getId(), $userId);
$item->getGuidHash(), $feed->getId(), $userId
);
$existingItem->setStatus($item->getStatus());
$this->itemMapper->update($existingItem);
} catch(DoesNotExistException $ex){
@ -363,11 +384,13 @@ class FeedService extends Service {
/**
* Use this to mark a feed as deleted. That way it can be un-deleted
* @param int $feedId the id of the feed that should be deleted
* @param string $userId the name of the user for security reasons
*
* @param int $feedId the id of the feed that should be deleted
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException when feed does not exist
*/
public function markDeleted($feedId, $userId) {
public function markDeleted($feedId, $userId)
{
$feed = $this->find($feedId, $userId);
$feed->setDeletedAt($this->timeFactory->getTime());
$this->feedMapper->update($feed);
@ -376,11 +399,13 @@ class FeedService extends Service {
/**
* Use this to undo a feed deletion
* @param int $feedId the id of the feed that should be restored
* @param string $userId the name of the user for security reasons
*
* @param int $feedId the id of the feed that should be restored
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException when feed does not exist
*/
public function unmarkDeleted($feedId, $userId) {
public function unmarkDeleted($feedId, $userId)
{
$feed = $this->find($feedId, $userId);
$feed->setDeletedAt(0);
$this->feedMapper->update($feed);
@ -389,12 +414,14 @@ class FeedService extends Service {
/**
* Deletes all deleted feeds
* @param string $userId if given it purges only feeds of that user
*
* @param string $userId if given it purges only feeds of that user
* @param boolean $useInterval defaults to true, if true it only purges
* entries in a given interval to give the user a chance to undo the
* deletion
* entries in a given interval to give the user a chance to undo the
* deletion
*/
public function purgeDeleted($userId=null, $useInterval=true) {
public function purgeDeleted($userId=null, $useInterval=true)
{
$deleteOlderThan = null;
if ($useInterval) {
@ -413,9 +440,11 @@ class FeedService extends Service {
/**
* Deletes all feeds of a user, delete items first since the user_id
* is not defined in there
*
* @param string $userId the name of the user
*/
public function deleteUser($userId) {
public function deleteUser($userId)
{
$this->feedMapper->deleteUser($userId);
}
@ -432,7 +461,8 @@ class FeedService extends Service {
* ]
* @throws ServiceNotFoundException if feed does not exist
*/
public function patch($feedId, $userId, $diff=[]) {
public function patch($feedId, $userId, $diff=[])
{
$feed = $this->find($feedId, $userId);
foreach ($diff as $attribute => $value) {

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
@ -20,7 +20,8 @@ use OCA\News\Config\Config;
use OCA\News\Utility\Time;
class FolderService extends Service {
class FolderService extends Service
{
private $l10n;
private $timeFactory;
@ -28,9 +29,10 @@ class FolderService extends Service {
private $folderMapper;
public function __construct(FolderMapper $folderMapper,
IL10N $l10n,
Time $timeFactory,
Config $config){
IL10N $l10n,
Time $timeFactory,
Config $config
) {
parent::__construct($folderMapper);
$this->l10n = $l10n;
$this->timeFactory = $timeFactory;
@ -41,21 +43,25 @@ class FolderService extends Service {
/**
* Returns all folders of a user
* @param string $userId the name of the user
*
* @param string $userId the name of the user
* @return array of folders
*/
public function findAll($userId) {
public function findAll($userId)
{
return $this->folderMapper->findAllFromUser($userId);
}
private function validateFolder($folderName, $userId){
private function validateFolder($folderName, $userId)
{
$existingFolders =
$this->folderMapper->findByName($folderName, $userId);
if(count($existingFolders) > 0){
if(count($existingFolders) > 0) {
throw new ServiceConflictException(
$this->l10n->t('Can not add folder: Exists already'));
$this->l10n->t('Can not add folder: Exists already')
);
}
if(mb_strlen($folderName) === 0) {
@ -68,15 +74,17 @@ class FolderService extends Service {
/**
* Creates a new folder
* @param string $folderName the name of the folder
* @param string $userId the name of the user for whom it should be created
* @param int $parentId the parent folder id, deprecated we don't nest
* folders
*
* @param string $folderName the name of the folder
* @param string $userId the name of the user for whom it should be created
* @param int $parentId the parent folder id, deprecated we don't nest
* folders
* @throws ServiceConflictException if name exists already
* @throws ServiceValidationException if the folder has invalid parameters
* @return Folder the newly created folder
*/
public function create($folderName, $userId, $parentId=0) {
public function create($folderName, $userId, $parentId=0)
{
$this->validateFolder($folderName, $userId);
$folder = new Folder();
@ -91,7 +99,8 @@ class FolderService extends Service {
/**
* @throws ServiceException if the folder does not exist
*/
public function open($folderId, $opened, $userId){
public function open($folderId, $opened, $userId)
{
$folder = $this->find($folderId, $userId);
$folder->setOpened($opened);
$this->folderMapper->update($folder);
@ -100,15 +109,17 @@ class FolderService extends Service {
/**
* Renames a folder
* @param int $folderId the id of the folder that should be deleted
* @param string $folderName the new name of the folder
* @param string $userId the name of the user for security reasons
*
* @param int $folderId the id of the folder that should be deleted
* @param string $folderName the new name of the folder
* @param string $userId the name of the user for security reasons
* @throws ServiceConflictException if name exists already
* @throws ServiceValidationException if the folder has invalid parameters
* @throws ServiceNotFoundException if the folder does not exist
* @return Folder the updated folder
*/
public function rename($folderId, $folderName, $userId){
public function rename($folderId, $folderName, $userId)
{
$this->validateFolder($folderName, $userId);
$folder = $this->find($folderId, $userId);
@ -119,11 +130,13 @@ class FolderService extends Service {
/**
* Use this to mark a folder as deleted. That way it can be un-deleted
* @param int $folderId the id of the folder that should be deleted
* @param string $userId the name of the user for security reasons
*
* @param int $folderId the id of the folder that should be deleted
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException when folder does not exist
*/
public function markDeleted($folderId, $userId) {
public function markDeleted($folderId, $userId)
{
$folder = $this->find($folderId, $userId);
$folder->setDeletedAt($this->timeFactory->getTime());
$this->folderMapper->update($folder);
@ -132,11 +145,13 @@ class FolderService extends Service {
/**
* Use this to restore a folder
* @param int $folderId the id of the folder that should be restored
* @param string $userId the name of the user for security reasons
*
* @param int $folderId the id of the folder that should be restored
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException when folder does not exist
*/
public function unmarkDeleted($folderId, $userId) {
public function unmarkDeleted($folderId, $userId)
{
$folder = $this->find($folderId, $userId);
$folder->setDeletedAt(0);
$this->folderMapper->update($folder);
@ -145,12 +160,14 @@ class FolderService extends Service {
/**
* Deletes all deleted folders
* @param string $userId if given it purges only folders of that user
*
* @param string $userId if given it purges only folders of that user
* @param boolean $useInterval defaults to true, if true it only purges
* entries in a given interval to give the user a chance to undo the
* deletion
* entries in a given interval to give the user a chance to undo the
* deletion
*/
public function purgeDeleted($userId=null, $useInterval=true) {
public function purgeDeleted($userId=null, $useInterval=true)
{
$deleteOlderThan = null;
if ($useInterval) {
@ -168,9 +185,11 @@ class FolderService extends Service {
/**
* Deletes all folders of a user
*
* @param string $userId the name of the user
*/
public function deleteUser($userId) {
public function deleteUser($userId)
{
$this->folderMapper->deleteUser($userId);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
@ -23,7 +23,8 @@ use OCA\News\Config\Config;
use OCA\News\Utility\Time;
class ItemService extends Service {
class ItemService extends Service
{
private $config;
private $timeFactory;
@ -31,9 +32,10 @@ class ItemService extends Service {
private $systemConfig;
public function __construct(ItemMapper $itemMapper,
Time $timeFactory,
Config $config,
IConfig $systemConfig){
Time $timeFactory,
Config $config,
IConfig $systemConfig
) {
parent::__construct($itemMapper);
$this->config = $config;
$this->timeFactory = $timeFactory;
@ -44,78 +46,88 @@ class ItemService extends Service {
/**
* Returns all new items
* @param int $id the id of the feed, 0 for starred or all items
* @param int $type the type of the feed
* @param int $updatedSince a timestamp with the last modification date
* returns only items with a >= modified timestamp
* @param boolean $showAll if unread items should also be returned
* @param string $userId the name of the user
*
* @param int $id the id of the feed, 0 for starred or all items
* @param int $type the type of the feed
* @param int $updatedSince a timestamp with the last modification date
* returns only items with a >= modified
* timestamp
* @param boolean $showAll if unread items should also be returned
* @param string $userId the name of the user
* @return array of items
*/
public function findAllNew($id, $type, $updatedSince, $showAll, $userId){
public function findAllNew($id, $type, $updatedSince, $showAll, $userId)
{
switch($type){
case FeedType::FEED:
return $this->itemMapper->findAllNewFeed(
$id, $updatedSince, $showAll, $userId
);
case FeedType::FOLDER:
return $this->itemMapper->findAllNewFolder(
$id, $updatedSince, $showAll, $userId
);
default:
return $this->itemMapper->findAllNew(
$updatedSince, $type, $showAll, $userId
);
case FeedType::FEED:
return $this->itemMapper->findAllNewFeed(
$id, $updatedSince, $showAll, $userId
);
case FeedType::FOLDER:
return $this->itemMapper->findAllNewFolder(
$id, $updatedSince, $showAll, $userId
);
default:
return $this->itemMapper->findAllNew(
$updatedSince, $type, $showAll, $userId
);
}
}
/**
* Returns all items
* @param int $id the id of the feed, 0 for starred or all items
* @param int $type the type of the feed
* @param int $limit how many items should be returned
* @param int $offset the offset
* @param boolean $showAll if unread items should also be returned
* @param boolean $oldestFirst if it should be ordered by oldest first
* @param string $userId the name of the user
* @param string[] $search an array of keywords that the result should
* contain in either the author, title, link or body
*
* @param int $id the id of the feed, 0 for starred or all items
* @param int $type the type of the feed
* @param int $limit how many items should be returned
* @param int $offset the offset
* @param boolean $showAll if unread items should also be returned
* @param boolean $oldestFirst if it should be ordered by oldest first
* @param string $userId the name of the user
* @param string[] $search an array of keywords that the result should
* contain in either the author, title, link
* or body
* @return array of items
*/
public function findAll($id, $type, $limit, $offset, $showAll, $oldestFirst,
$userId, $search=[]){
$userId, $search=[]
) {
switch($type){
case FeedType::FEED:
return $this->itemMapper->findAllFeed(
$id, $limit, $offset, $showAll, $oldestFirst, $userId,
$search
);
case FeedType::FOLDER:
return $this->itemMapper->findAllFolder(
$id, $limit, $offset, $showAll, $oldestFirst, $userId,
$search
);
default:
return $this->itemMapper->findAll(
$limit, $offset, $type, $showAll, $oldestFirst, $userId, $search
);
case FeedType::FEED:
return $this->itemMapper->findAllFeed(
$id, $limit, $offset, $showAll, $oldestFirst, $userId,
$search
);
case FeedType::FOLDER:
return $this->itemMapper->findAllFolder(
$id, $limit, $offset, $showAll, $oldestFirst, $userId,
$search
);
default:
return $this->itemMapper->findAll(
$limit, $offset, $type, $showAll, $oldestFirst, $userId, $search
);
}
}
/**
* Star or unstar an item
* @param int $feedId the id of the item's feed that should be starred
* @param string $guidHash the guidHash of the item that should be starred
* @param boolean $isStarred if true the item will be marked as starred,
* if false unstar
* @param string $userId the name of the user for security reasons
*
* @param int $feedId the id of the item's feed that should be starred
* @param string $guidHash the guidHash of the item that should be starred
* @param boolean $isStarred if true the item will be marked as starred,
* if false unstar
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException if the item does not exist
*/
public function star($feedId, $guidHash, $isStarred, $userId){
public function star($feedId, $guidHash, $isStarred, $userId)
{
try {
/** @var Item $item */
/**
* @var Item $item
*/
$item = $this->itemMapper->findByGuidHash(
$guidHash, $feedId, $userId
);
@ -131,13 +143,15 @@ class ItemService extends Service {
/**
* Read or unread an item
* @param int $itemId the id of the item that should be read
* @param boolean $isRead if true the item will be marked as read,
* if false unread
* @param string $userId the name of the user for security reasons
*
* @param int $itemId the id of the item that should be read
* @param boolean $isRead if true the item will be marked as read,
* if false unread
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException if the item does not exist
*/
public function read($itemId, $isRead, $userId){
public function read($itemId, $isRead, $userId)
{
try {
$lastModified = $this->timeFactory->getMicroTime();
$this->itemMapper->readItem($itemId, $isRead, $lastModified, $userId);
@ -149,11 +163,14 @@ class ItemService extends Service {
/**
* Set all items read
* @param int $highestItemId all items below that are marked read. This is
* used to prevent marking items as read that the users hasn't seen yet
* @param string $userId the name of the user
*
* @param int $highestItemId all items below that are marked read. This is
* used to prevent marking items as read that
* the users hasn't seen yet
* @param string $userId the name of the user
*/
public function readAll($highestItemId, $userId){
public function readAll($highestItemId, $userId)
{
$time = $this->timeFactory->getMicroTime();
$this->itemMapper->readAll($highestItemId, $time, $userId);
}
@ -161,12 +178,15 @@ class ItemService extends Service {
/**
* Set a folder read
* @param int $folderId the id of the folder that should be marked read
* @param int $highestItemId all items below that are marked read. This is
* used to prevent marking items as read that the users hasn't seen yet
* @param string $userId the name of the user
*
* @param int $folderId the id of the folder that should be marked read
* @param int $highestItemId all items below that are marked read. This is
* used to prevent marking items as read that
* the users hasn't seen yet
* @param string $userId the name of the user
*/
public function readFolder($folderId, $highestItemId, $userId){
public function readFolder($folderId, $highestItemId, $userId)
{
$time = $this->timeFactory->getMicroTime();
$this->itemMapper->readFolder(
$folderId, $highestItemId, $time, $userId
@ -176,12 +196,15 @@ class ItemService extends Service {
/**
* Set a feed read
* @param int $feedId the id of the feed that should be marked read
* @param int $highestItemId all items below that are marked read. This is
* used to prevent marking items as read that the users hasn't seen yet
* @param string $userId the name of the user
*
* @param int $feedId the id of the feed that should be marked read
* @param int $highestItemId all items below that are marked read. This is
* used to prevent marking items as read that
* the users hasn't seen yet
* @param string $userId the name of the user
*/
public function readFeed($feedId, $highestItemId, $userId){
public function readFeed($feedId, $highestItemId, $userId)
{
$time = $this->timeFactory->getMicroTime();
$this->itemMapper->readFeed($feedId, $highestItemId, $time, $userId);
}
@ -193,7 +216,8 @@ class ItemService extends Service {
* up the database so that old entries don't spam your db. As criteria for
* old, the id is taken
*/
public function autoPurgeOld(){
public function autoPurgeOld()
{
$count = $this->config->getAutoPurgeCount();
if ($count >= 0) {
$this->itemMapper->deleteReadOlderThanThreshold($count);
@ -203,11 +227,13 @@ class ItemService extends Service {
/**
* Returns the newest item id, use this for marking feeds read
* @param string $userId the name of the user
*
* @param string $userId the name of the user
* @throws ServiceNotFoundException if there is no newest item
* @return int
*/
public function getNewestItemId($userId) {
public function getNewestItemId($userId)
{
try {
return $this->itemMapper->getNewestItemId($userId);
} catch(DoesNotExistException $ex) {
@ -218,10 +244,12 @@ class ItemService extends Service {
/**
* Returns the starred count
* @param string $userId the name of the user
*
* @param string $userId the name of the user
* @return int the count
*/
public function starredCount($userId){
public function starredCount($userId)
{
return $this->itemMapper->starredCount($userId);
}
@ -230,16 +258,19 @@ class ItemService extends Service {
* @param string $userId from which user the items should be taken
* @return array of items which are starred or unread
*/
public function getUnreadOrStarred($userId) {
public function getUnreadOrStarred($userId)
{
return $this->itemMapper->findAllUnreadOrStarred($userId);
}
/**
* Deletes all items of a user
*
* @param string $userId the name of the user
*/
public function deleteUser($userId) {
public function deleteUser($userId)
{
$this->itemMapper->deleteUser($userId);
}
@ -247,7 +278,8 @@ class ItemService extends Service {
/**
* Regenerates the search index for all items
*/
public function generateSearchIndices() {
public function generateSearchIndices()
{
$this->itemMapper->updateSearchIndices();
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
@ -19,23 +19,27 @@ use \OCP\AppFramework\Db\MultipleObjectsReturnedException;
use \OCA\News\Db\NewsMapper;
abstract class Service {
abstract class Service
{
protected $mapper;
public function __construct(NewsMapper $mapper){
public function __construct(NewsMapper $mapper)
{
$this->mapper = $mapper;
}
/**
* Delete an entity
* @param int $id the id of the entity
* @param string $userId the name of the user for security reasons
*
* @param int $id the id of the entity
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException if the entity does not exist, or there
* are more than one of it
*/
public function delete($id, $userId){
public function delete($id, $userId)
{
$entity = $this->find($id, $userId);
$this->mapper->delete($entity);
}
@ -43,13 +47,15 @@ abstract class Service {
/**
* Finds an entity by id
* @param int $id the id of the entity
* @param string $userId the name of the user for security reasons
*
* @param int $id the id of the entity
* @param string $userId the name of the user for security reasons
* @throws ServiceNotFoundException if the entity does not exist, or there
* are more than one of it
* @return \OCP\AppFramework\Db\Entity the entity
*/
public function find($id, $userId){
public function find($id, $userId)
{
try {
return $this->mapper->find($id, $userId);
} catch(DoesNotExistException $ex){

View File

@ -5,22 +5,25 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
class ServiceConflictException extends ServiceException {
class ServiceConflictException extends ServiceException
{
/**
* Constructor
*
* @param string $msg the error message
*/
public function __construct($msg){
public function __construct($msg)
{
parent::__construct($msg);
}

View File

@ -5,22 +5,25 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
class ServiceException extends \Exception {
class ServiceException extends \Exception
{
/**
* Constructor
*
* @param string $msg the error message
*/
public function __construct($msg){
public function __construct($msg)
{
parent::__construct($msg);
}

View File

@ -5,22 +5,25 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
class ServiceNotFoundException extends ServiceException {
class ServiceNotFoundException extends ServiceException
{
/**
* Constructor
*
* @param string $msg the error message
*/
public function __construct($msg){
public function __construct($msg)
{
parent::__construct($msg);
}

View File

@ -5,22 +5,25 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
class ServiceValidationException extends ServiceException {
class ServiceValidationException extends ServiceException
{
/**
* Constructor
*
* @param string $msg the error message
*/
public function __construct($msg){
public function __construct($msg)
{
parent::__construct($msg);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Service;
@ -21,7 +21,8 @@ use OCP\IDBConnection;
use OCA\News\Config\Config;
class StatusService {
class StatusService
{
private $settings;
private $config;
@ -32,14 +33,16 @@ class StatusService {
private $connection;
public function __construct(IConfig $settings, IDBConnection $connection,
Config $config, $AppName) {
Config $config, $AppName
) {
$this->settings = $settings;
$this->config = $config;
$this->appName = $AppName;
$this->connection = $connection;
}
public function isProperlyConfigured() {
public function isProperlyConfigured()
{
$cronMode = $this->settings->getAppValue(
'core', 'backgroundjobs_mode'
);
@ -50,7 +53,8 @@ class StatusService {
}
public function getStatus() {
public function getStatus()
{
$version = $this->settings->getAppValue(
$this->appName, 'installed_version'
);

View File

@ -7,14 +7,17 @@ use OCP\Settings\ISettings;
use OCA\News\Config\Config;
class Admin implements ISettings {
class Admin implements ISettings
{
private $config;
public function __construct(Config $config) {
public function __construct(Config $config)
{
$this->config = $config;
}
public function getForm() {
public function getForm()
{
$data = [
'autoPurgeMinimumInterval' =>
$this->config->getAutoPurgeMinimumInterval(),
@ -28,11 +31,13 @@ class Admin implements ISettings {
return new TemplateResponse('news', 'admin', $data, '');
}
public function getSection() {
public function getSection()
{
return 'news';
}
public function getPriority() {
public function getPriority()
{
return 40;
}
}

View File

@ -6,28 +6,34 @@ use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\Settings\IIconSection;
class Section implements IIconSection {
class Section implements IIconSection
{
private $l;
private $url;
public function __construct(IURLGenerator $url, IL10N $l) {
public function __construct(IURLGenerator $url, IL10N $l)
{
$this->url = $url;
$this->l = $l;
}
public function getID() {
public function getID()
{
return 'news';
}
public function getName() {
public function getName()
{
return $this->l->t('News');
}
public function getPriority() {
public function getPriority()
{
return 10;
}
public function getIcon() {
public function getIcon()
{
return $this->url->imagePath('news', 'app-dark.svg');
}
}

View File

@ -5,27 +5,29 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Utility;
/**
* Exports the OPML
*/
class OPMLExporter {
* Exports the OPML
*/
class OPMLExporter
{
/**
* Generates the OPML for the active user
*
* @param \OCA\News\Db\Folder[] $folders
* @param \OCA\News\Db\Feed[] $feeds
* @param \OCA\News\Db\Folder[] $folders
* @param \OCA\News\Db\Feed[] $feeds
* @return \DomDocument the document
*/
public function build($folders, $feeds){
public function build($folders, $feeds)
{
$document = new \DomDocument('1.0', 'UTF-8');
$document->formatOutput = true;
@ -76,7 +78,8 @@ class OPMLExporter {
}
protected function createFeedOutline($feed, $document) {
protected function createFeedOutline($feed, $document)
{
$feedOutline = $document->createElement('outline');
$feedOutline->setAttribute('title', $feed->getTitle());
$feedOutline->setAttribute('text', $feed->getTitle());

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
@ -17,20 +17,24 @@ namespace OCA\News\Utility;
use \PicoFeed\Config\Config;
use \PicoFeed\Client\Client;
class PicoFeedClientFactory {
class PicoFeedClientFactory
{
private $config;
public function __construct(Config $config) {
public function __construct(Config $config)
{
$this->config = $config;
}
/**
* Returns a new instance of an PicoFeed Http client
*
* @return \PicoFeed\Client instance
*/
public function build() {
public function build()
{
$client = Client::getInstance();
$client->setConfig($this->config);
return $client;

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
@ -17,20 +17,24 @@ namespace OCA\News\Utility;
use \PicoFeed\Config\Config;
use \PicoFeed\Reader\Favicon;
class PicoFeedFaviconFactory {
class PicoFeedFaviconFactory
{
private $config;
public function __construct(Config $config) {
public function __construct(Config $config)
{
$this->config = $config;
}
/**
* Returns a new instance of an PicoFeed Http client
*
* @return \PicoFeed\Favicon instance
*/
public function build() {
public function build()
{
return new Favicon($this->config);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
@ -17,20 +17,24 @@ namespace OCA\News\Utility;
use \OCP\IConfig;
class ProxyConfigParser {
class ProxyConfigParser
{
private $config;
public function __construct(IConfig $config) {
public function __construct(IConfig $config)
{
$this->config = $config;
}
/**
* Parses the config and splits up the port + url
*
* @return array
*/
public function parse() {
public function parse()
{
$proxy = $this->config->getSystemValue('proxy');
$userpasswd = $this->config->getSystemValue('proxyuserpwd');

View File

@ -6,20 +6,23 @@
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2016
* @copyright 2016 Bernhard Posselt
*/
namespace OCA\News\Utility;
class Time {
public function getTime() {
class Time
{
public function getTime()
{
return time();
}
/**
* @return int the current unix time in miliseconds
*/
public function getMicroTime() {
public function getMicroTime()
{
list($millisecs, $secs) = explode(" ", microtime());
return $secs . substr($millisecs, 2, 6);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
@ -19,7 +19,8 @@ use \OCA\News\Service\FeedService;
use \OCA\News\Service\ItemService;
class Updater {
class Updater
{
private $folderService;
@ -27,26 +28,30 @@ class Updater {
private $itemService;
public function __construct(FolderService $folderService,
FeedService $feedService,
ItemService $itemService) {
FeedService $feedService,
ItemService $itemService
) {
$this->folderService = $folderService;
$this->feedService = $feedService;
$this->itemService = $itemService;
}
public function beforeUpdate() {
public function beforeUpdate()
{
$this->folderService->purgeDeleted();
$this->feedService->purgeDeleted();
}
public function update() {
public function update()
{
$this->feedService->updateAll();
}
public function afterUpdate() {
public function afterUpdate()
{
$this->itemService->autoPurgeOld();
}

View File

@ -5,8 +5,8 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Daniel Opitz <dev@copynpaste.de>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Daniel Opitz <dev@copynpaste.de>
* @copyright Bernhard Posselt 2015
* @copyright Daniel Opitz 2017
*/
@ -17,9 +17,11 @@ use OCA\News\Db\Feed;
use OCA\News\Tests\Integration\IntegrationTest;
use OCA\News\Tests\Integration\Fixtures\FeedFixture;
class FeedMapperTest extends IntegrationTest {
class FeedMapperTest extends IntegrationTest
{
public function testFind () {
public function testFind()
{
$feed = new FeedFixture();
$feed = $this->feedMapper->insert($feed);
@ -32,12 +34,14 @@ class FeedMapperTest extends IntegrationTest {
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindNotExisting () {
public function testFindNotExisting()
{
$this->feedMapper->find(0, $this->user);
}
public function testFindAll () {
public function testFindAll()
{
$feeds = [
[
'userId' => $this->user,
@ -59,7 +63,8 @@ class FeedMapperTest extends IntegrationTest {
$this->tearDownUser('john');
}
public function testFindAllEmpty () {
public function testFindAllEmpty()
{
$feeds = $this->feedMapper->findAll();
$this->assertInternalType('array', $feeds);
@ -67,7 +72,8 @@ class FeedMapperTest extends IntegrationTest {
}
public function testFindAllFromUser () {
public function testFindAllFromUser()
{
$feeds = [
[
'userId' => $this->user,
@ -90,7 +96,8 @@ class FeedMapperTest extends IntegrationTest {
}
public function testFindAllFromUserNotExisting () {
public function testFindAllFromUserNotExisting()
{
$fetched = $this->feedMapper->findAllFromUser('notexistinguser');
$this->assertInternalType('array', $fetched);
@ -98,11 +105,14 @@ class FeedMapperTest extends IntegrationTest {
}
public function testFindByUrlHash () {
$feed = new FeedFixture([
public function testFindByUrlHash()
{
$feed = new FeedFixture(
[
'urlHash' => 'someTestHash',
'title' => 'Some Test Title'
]);
]
);
$feed = $this->feedMapper->insert($feed);
$fetched = $this->feedMapper->findByUrlHash($feed->getUrlHash(), $this->user);
@ -114,13 +124,22 @@ class FeedMapperTest extends IntegrationTest {
/**
* @expectedException OCP\AppFramework\Db\MultipleObjectsReturnedException
*/
public function testFindByUrlHashMoreThanOneResult () {
$feed1 = $this->feedMapper->insert(new FeedFixture([
'urlHash' => 'someTestHash'
]));
$feed2 = $this->feedMapper->insert(new FeedFixture([
'urlHash' => 'someTestHash'
]));
public function testFindByUrlHashMoreThanOneResult()
{
$feed1 = $this->feedMapper->insert(
new FeedFixture(
[
'urlHash' => 'someTestHash'
]
)
);
$feed2 = $this->feedMapper->insert(
new FeedFixture(
[
'urlHash' => 'someTestHash'
]
)
);
$this->feedMapper->findByUrlHash($feed1->getUrlHash(), $this->user);
}
@ -129,12 +148,14 @@ class FeedMapperTest extends IntegrationTest {
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindByUrlHashNotExisting () {
public function testFindByUrlHashNotExisting()
{
$this->feedMapper->findByUrlHash('some random hash', $this->user);
}
public function testDelete () {
public function testDelete()
{
$this->loadFixtures('default');
$feeds = $this->feedMapper->findAllFromUser($this->user);
@ -157,13 +178,16 @@ class FeedMapperTest extends IntegrationTest {
$this->assertCount(0, $items);
}
public function testGetToDelete () {
$this->loadFeedFixtures([
public function testGetToDelete()
{
$this->loadFeedFixtures(
[
['deletedAt' => 1],
['deletedAt' => 0],
['deletedAt' => 1, 'userId' => 'john'],
['deletedAt' => 1000]
]);
]
);
$fetched = $this->feedMapper->getToDelete();
@ -174,13 +198,16 @@ class FeedMapperTest extends IntegrationTest {
$this->tearDownUser('john');
}
public function testGetToDeleteOlderThan () {
$this->loadFeedFixtures([
public function testGetToDeleteOlderThan()
{
$this->loadFeedFixtures(
[
['deletedAt' => 1],
['deletedAt' => 0],
['deletedAt' => 1, 'userId' => 'john'],
['deletedAt' => 1000]
]);
]
);
$fetched = $this->feedMapper->getToDelete(1000);
@ -191,13 +218,16 @@ class FeedMapperTest extends IntegrationTest {
$this->tearDownUser('john');
}
public function testGetToDeleteUser () {
$this->loadFeedFixtures([
public function testGetToDeleteUser()
{
$this->loadFeedFixtures(
[
['deletedAt' => 1],
['deletedAt' => 0],
['deletedAt' => 1, 'userId' => 'john'],
['deletedAt' => 1000]
]);
]
);
$fetched = $this->feedMapper->getToDelete(2000, $this->user);
@ -208,14 +238,16 @@ class FeedMapperTest extends IntegrationTest {
$this->tearDownUser('john');
}
public function testGetToDeleteEmpty () {
public function testGetToDeleteEmpty()
{
$fetched = $this->feedMapper->getToDelete();
$this->assertInternalType('array', $fetched);
$this->assertCount(0, $fetched);
}
public function testDeleteUser () {
public function testDeleteUser()
{
$this->loadFixtures('default');
$this->assertCount(4, $this->feedMapper->findAllFromUser($this->user));
@ -231,7 +263,8 @@ class FeedMapperTest extends IntegrationTest {
$this->assertCount(0, $items);
}
public function testDeleteUserNotExisting () {
public function testDeleteUserNotExisting()
{
$this->feedMapper->deleteUser('notexistinguser');
}
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
@ -13,10 +13,12 @@ namespace OCA\News\Tests\Integration\Db;
use OCA\News\Tests\Integration\IntegrationTest;
class FolderMapperTest extends IntegrationTest {
class FolderMapperTest extends IntegrationTest
{
public function testFind () {
public function testFind()
{
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
@ -15,9 +15,11 @@ use OCA\News\Tests\Integration\IntegrationTest;
use OCA\News\Tests\Integration\Fixtures\FeedFixture;
use OCA\News\Tests\Integration\Fixtures\ItemFixture;
class ItemMapperTest extends IntegrationTest {
class ItemMapperTest extends IntegrationTest
{
public function testFind() {
public function testFind()
{
$feed = new FeedFixture();
$feed = $this->feedMapper->insert($feed);
@ -32,17 +34,20 @@ class ItemMapperTest extends IntegrationTest {
/**
* Same as whereId with easier title search
* @param $title
*
* @param $title
* @return mixed
*/
private function whereTitleId($title) {
private function whereTitleId($title)
{
return $this->findItemByTitle($title)->getId();
}
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindNotFoundWhenDeletedFeed() {
public function testFindNotFoundWhenDeletedFeed()
{
$this->loadFixtures('default');
$id = $this->whereTitleId('not found feed');
@ -53,7 +58,8 @@ class ItemMapperTest extends IntegrationTest {
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testFindNotFoundWhenDeletedFolder() {
public function testFindNotFoundWhenDeletedFolder()
{
$this->loadFixtures('default');
@ -62,7 +68,8 @@ class ItemMapperTest extends IntegrationTest {
}
private function deleteReadOlderThanThreshold() {
private function deleteReadOlderThanThreshold()
{
$this->loadFixtures('default');
$this->itemMapper->deleteReadOlderThanThreshold(1);
@ -77,7 +84,8 @@ class ItemMapperTest extends IntegrationTest {
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testDeleteOlderThanThresholdOne() {
public function testDeleteOlderThanThresholdOne()
{
$this->loadFixtures('default');
$id = $this->whereTitleId('del1');
@ -89,7 +97,8 @@ class ItemMapperTest extends IntegrationTest {
/**
* @expectedException OCP\AppFramework\Db\DoesNotExistException
*/
public function testDeleteOlderThanThresholdTwo() {
public function testDeleteOlderThanThresholdTwo()
{
$this->loadFixtures('default');
$id = $this->whereTitleId('del2');
@ -99,7 +108,8 @@ class ItemMapperTest extends IntegrationTest {
}
public function testStarredCount () {
public function testStarredCount()
{
$this->loadFixtures('default');
$count = $this->itemMapper->starredCount($this->user);
@ -107,7 +117,8 @@ class ItemMapperTest extends IntegrationTest {
}
public function testReadAll () {
public function testReadAll()
{
$this->loadFixtures('default');
$this->itemMapper->readAll(PHP_INT_MAX, 10, $this->user);
@ -135,7 +146,8 @@ class ItemMapperTest extends IntegrationTest {
}
public function testReadFolder () {
public function testReadFolder()
{
$this->loadFixtures('default');
$folderId = $this->findFolderByName('first folder')->getId();
@ -166,7 +178,8 @@ class ItemMapperTest extends IntegrationTest {
}
public function testReadFeed () {
public function testReadFeed()
{
$this->loadFixtures('default');
$feedId = $this->findFeedByTitle('third feed')->getId();
@ -196,7 +209,8 @@ class ItemMapperTest extends IntegrationTest {
}
public function testDeleteUser () {
public function testDeleteUser()
{
$this->loadFixtures('default');
$this->itemMapper->deleteUser($this->user);
@ -205,7 +219,8 @@ class ItemMapperTest extends IntegrationTest {
$this->assertEquals(0, $id);
}
public function testGetNewestItemId () {
public function testGetNewestItemId()
{
$this->loadFixtures('default');
$id = $this->itemMapper->getNewestItemId($this->user);
@ -214,7 +229,8 @@ class ItemMapperTest extends IntegrationTest {
$this->assertEquals($itemId, $id);
}
public function testFindAllUnreadOrStarred () {
public function testFindAllUnreadOrStarred()
{
$this->loadFixtures('default');
$items = $this->itemMapper->findAllUnreadOrStarred($this->user);
@ -222,7 +238,8 @@ class ItemMapperTest extends IntegrationTest {
}
public function testReadItem() {
public function testReadItem()
{
$this->loadFixtures('readitem');
// assert that all items are unread
$feed = $this->feedMapper->where(['userId' => 'john'])[0];
@ -260,7 +277,8 @@ class ItemMapperTest extends IntegrationTest {
}
}
public function testUnreadItem() {
public function testUnreadItem()
{
$this->loadFixtures('readitem');
// unread an item
$feed = $this->feedMapper->where(['userId' => 'test'])[0];
@ -286,7 +304,8 @@ class ItemMapperTest extends IntegrationTest {
}
}
protected function tearDown() {
protected function tearDown()
{
parent::tearDown();
$this->clearUserNewsDatabase('john');
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
@ -15,13 +15,16 @@ namespace OCA\News\Tests\Integration\Fixtures;
use OCA\News\Db\Feed;
class FeedFixture extends Feed {
class FeedFixture extends Feed
{
use Fixture;
public function __construct(array $defaults=[]) {
public function __construct(array $defaults=[])
{
parent::__construct();
$defaults = array_merge([
$defaults = array_merge(
[
'userId' => 'test',
'urlHash' => 'urlHash',
'url' => 'http://the.url.com',
@ -42,7 +45,8 @@ class FeedFixture extends Feed {
'updateMode' => 0,
'updateErrorCount' => 0,
'lastUpdateError' => '',
], $defaults);
], $defaults
);
unset($defaults['items']);
$this->fillDefaults($defaults);
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
@ -13,9 +13,11 @@
namespace OCA\News\Tests\Integration\Fixtures;
trait Fixture {
trait Fixture
{
protected function fillDefaults(array $defaults=[]) {
protected function fillDefaults(array $defaults=[])
{
foreach ($defaults as $key => $value) {
$method = 'set' . ucfirst($key);
$this->$method($value);

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
@ -15,19 +15,23 @@ namespace OCA\News\Tests\Integration\Fixtures;
use OCA\News\Db\Folder;
class FolderFixture extends Folder {
class FolderFixture extends Folder
{
use Fixture;
public function __construct(array $defaults=[]) {
public function __construct(array $defaults=[])
{
parent::__construct();
$defaults = array_merge([
$defaults = array_merge(
[
'parentId' => 0,
'name' => 'folder',
'userId' => 'test',
'opened' => true,
'deletedAt' => 0,
'lastModified' => 9
], $defaults);
], $defaults
);
unset($defaults['feeds']);
$this->fillDefaults($defaults);
}

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
@ -15,12 +15,15 @@ namespace OCA\News\Tests\Integration\Fixtures;
use OCA\News\Db\Item;
class ItemFixture extends Item {
class ItemFixture extends Item
{
use Fixture;
public function __construct(array $defaults=[]) {
public function __construct(array $defaults=[])
{
parent::__construct();
$defaults = array_merge([
$defaults = array_merge(
[
'url' => 'http://google.de',
'title' => 'title',
'author' => 'my author',
@ -33,7 +36,8 @@ class ItemFixture extends Item {
'starred' => false,
'lastModified' => 113,
'rtl' => false,
], $defaults);
], $defaults
);
if (!array_key_exists('guid', $defaults)) {
$defaults['guid'] = $defaults['title'];

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2015
*/
@ -32,24 +32,34 @@ use OCA\News\Db\ItemMapper;
use OCA\News\Db\FolderMapper;
abstract class IntegrationTest extends \Test\TestCase {
abstract class IntegrationTest extends \Test\TestCase
{
protected $user = 'test';
protected $userPassword = 'test';
/** @var ItemMapper */
/**
* @var ItemMapper
*/
protected $itemMapper;
/** @var FeedMapper */
/**
* @var FeedMapper
*/
protected $feedMapper;
/** @var FolderMapper */
/**
* @var FolderMapper
*/
protected $folderMapper;
/** @var IAppContainer */
/**
* @var IAppContainer
*/
protected $container;
protected function setUp() {
protected function setUp()
{
parent::setUp();
$app = new Application();
$this->container = $app->getContainer();
@ -62,7 +72,8 @@ abstract class IntegrationTest extends \Test\TestCase {
$this->folderMapper = $this->container->query(FolderMapper::class);
}
protected function findItemByTitle($title) {
protected function findItemByTitle($title)
{
// db logic in app code, negligible since its a test
$items = $this->itemMapper->where(['title' => $title]);
$feeds = $this->feedMapper->where(['userId' => $this->user]);
@ -72,10 +83,12 @@ abstract class IntegrationTest extends \Test\TestCase {
$feedIds[$feed->getId()] = true;
}
$result = array_filter($items,
$result = array_filter(
$items,
function (Item $item) use ($feedIds) {
return array_key_exists($item->getFeedId(), $feedIds);
});
return array_key_exists($item->getFeedId(), $feedIds);
}
);
// ok so this is funny: array_filter preserves indices, meaning that
// you can't use 0 as key for the first element return from it :D
@ -84,24 +97,31 @@ abstract class IntegrationTest extends \Test\TestCase {
return $result;
}
protected function findFolderByName($name) {
return $this->folderMapper->where([
protected function findFolderByName($name)
{
return $this->folderMapper->where(
[
'userId' => $this->user,
'name' => $name
])[0];
]
)[0];
}
protected function findFeedByTitle($title) {
return $this->feedMapper->where([
protected function findFeedByTitle($title)
{
return $this->feedMapper->where(
[
'userId' => $this->user,
'title' => $title
])[0];
]
)[0];
}
/**
* @param string $name loads fixtures from a given file
*/
protected function loadFixtures($name) {
protected function loadFixtures($name)
{
$fixtures = include __DIR__ . '/Fixtures/data/' . $name . '.php';
if (array_key_exists('folders', $fixtures)) {
$this->loadFolderFixtures($fixtures['folders']);
@ -111,7 +131,8 @@ abstract class IntegrationTest extends \Test\TestCase {
}
}
protected function loadFolderFixtures(array $folderFixtures=[]) {
protected function loadFolderFixtures(array $folderFixtures=[])
{
foreach ($folderFixtures as $folderFixture) {
$folder = new FolderFixture($folderFixture);
$folderId = $this->loadFixture($folder);
@ -119,19 +140,21 @@ abstract class IntegrationTest extends \Test\TestCase {
}
}
protected function loadFeedFixtures(array $feedFixtures=[], $folderId=0) {
protected function loadFeedFixtures(array $feedFixtures=[], $folderId=0)
{
foreach ($feedFixtures as $feedFixture) {
$feed = new FeedFixture($feedFixture);
$feed->setFolderId($folderId);
$feedId = $this->loadFixture($feed);
if (!empty($feedFixture['items'])) {
$this->loadItemFixtures($feedFixture['items'], $feedId);
}
$this->loadItemFixtures($feedFixture['items'], $feedId);
}
}
}
protected function loadItemFixtures(array $itemFixtures=[], $feedId) {
protected function loadItemFixtures(array $itemFixtures=[], $feedId)
{
foreach ($itemFixtures as $itemFixture) {
$item = new ItemFixture($itemFixture);
$item->setFeedId($feedId);
@ -141,10 +164,12 @@ abstract class IntegrationTest extends \Test\TestCase {
/**
* Saves a fixture in a database and returns the saved result
* @param Entity $fixture
*
* @param Entity $fixture
* @return int the id
*/
protected function loadFixture(Entity $fixture) {
protected function loadFixture(Entity $fixture)
{
if ($fixture instanceof FeedFixture) {
return $this->feedMapper->insert($fixture)->getId();
} elseif ($fixture instanceof ItemFixture) {
@ -158,10 +183,12 @@ abstract class IntegrationTest extends \Test\TestCase {
/**
* Creates and logs in a new ownCloud user
*
* @param $user
* @param $password
*/
protected function setupUser($user, $password) {
protected function setupUser($user, $password)
{
$userManager = $this->container->query(IUserManager::class);
$userManager->createUser($user, $password);
@ -170,9 +197,11 @@ abstract class IntegrationTest extends \Test\TestCase {
/**
* Removes a user and his News app database entries from the database
*
* @param $user
*/
protected function tearDownUser($user) {
protected function tearDownUser($user)
{
$userManager = $this->container->query(IUserManager::class);
if ($userManager->userExists($user)) {
@ -184,9 +213,11 @@ abstract class IntegrationTest extends \Test\TestCase {
/**
* Deletes all news entries of a given user
*
* @param string $user
*/
protected function clearUserNewsDatabase($user) {
protected function clearUserNewsDatabase($user)
{
$sql = [
'DELETE FROM `*PREFIX*news_items` WHERE `feed_id` IN
(SELECT `id` FROM `*PREFIX*news_feeds` WHERE `user_id` = ?)',
@ -200,7 +231,8 @@ abstract class IntegrationTest extends \Test\TestCase {
}
}
protected function tearDown() {
protected function tearDown()
{
parent::tearDown();
$this->tearDownUser($this->user);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Config;
@ -17,16 +17,19 @@ use OCA\News\Config\Config;
use PHPUnit_Framework_TestCase;
class ConfigTest extends PHPUnit_Framework_TestCase {
class ConfigTest extends PHPUnit_Framework_TestCase
{
private $fileSystem;
private $config;
private $configPath;
private $loggerParams;
public function setUp() {
public function setUp()
{
$this->logger = $this->getMockBuilder(
'OCP\ILogger')
'OCP\ILogger'
)
->disableOriginalConstructor()
->getMock();
$this->fileSystem = $this->getMockBuilder('OCP\Files\Folder')->getMock();
@ -38,7 +41,8 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
}
public function testDefaults() {
public function testDefaults()
{
$this->assertEquals(60, $this->config->getAutoPurgeMinimumInterval());
$this->assertEquals(200, $this->config->getAutoPurgeCount());
$this->assertEquals(10, $this->config->getMaxRedirects());
@ -49,7 +53,8 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
}
public function testRead () {
public function testRead()
{
$file = $this->getMockBuilder('OCP\Files\File')->getMock();
$this->fileSystem->expects($this->once())
->method('get')
@ -57,9 +62,11 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
->will($this->returnValue($file));
$file->expects($this->once())
->method('getContent')
->will($this->returnValue(
'autoPurgeCount = 3' . "\n" . 'useCronUpdates = true'
));
->will(
$this->returnValue(
'autoPurgeCount = 3' . "\n" . 'useCronUpdates = true'
)
);
$this->config->read($this->configPath);
@ -69,7 +76,8 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
}
public function testReadIgnoresVeryLowPurgeInterval () {
public function testReadIgnoresVeryLowPurgeInterval()
{
$file = $this->getMockBuilder('OCP\Files\File')->getMock();
$this->fileSystem->expects($this->once())
->method('get')
@ -86,7 +94,8 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
public function testReadBool () {
public function testReadBool()
{
$file = $this->getMockBuilder('OCP\Files\File')->getMock();
$this->fileSystem->expects($this->once())
->method('get')
@ -94,8 +103,10 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
->will($this->returnValue($file));
$file->expects($this->once())
->method('getContent')
->will($this->returnValue(
'autoPurgeCount = 3' . "\n" . 'useCronUpdates = false')
->will(
$this->returnValue(
'autoPurgeCount = 3' . "\n" . 'useCronUpdates = false'
)
);
$this->config->read($this->configPath);
@ -105,7 +116,8 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
}
public function testReadLogsInvalidValue() {
public function testReadLogsInvalidValue()
{
$file = $this->getMockBuilder('OCP\Files\File')->getMock();
$this->fileSystem->expects($this->once())
->method('get')
@ -116,15 +128,20 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
->will($this->returnValue('autoPurgeCounts = 3'));
$this->logger->expects($this->once())
->method('warning')
->with($this->equalTo('Configuration value "autoPurgeCounts" ' .
'does not exist. Ignored value.'),
$this->equalTo($this->loggerParams));
->with(
$this->equalTo(
'Configuration value "autoPurgeCounts" ' .
'does not exist. Ignored value.'
),
$this->equalTo($this->loggerParams)
);
$this->config->read($this->configPath);
}
public function testReadLogsInvalidINI() {
public function testReadLogsInvalidINI()
{
$file = $this->getMockBuilder('OCP\Files\File')->getMock();
$this->fileSystem->expects($this->once())
->method('get')
@ -135,14 +152,17 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
->will($this->returnValue(''));
$this->logger->expects($this->once())
->method('warning')
->with($this->equalTo('Configuration invalid. Ignoring values.'),
$this->equalTo($this->loggerParams));
->with(
$this->equalTo('Configuration invalid. Ignoring values.'),
$this->equalTo($this->loggerParams)
);
$this->config->read($this->configPath);
}
public function testWrite () {
public function testWrite()
{
$json = 'autoPurgeMinimumInterval = 60' . "\n" .
'autoPurgeCount = 3' . "\n" .
'maxRedirects = 10' . "\n" .
@ -168,7 +188,8 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
public function testReadingNonExistentConfigWillWriteDefaults() {
public function testReadingNonExistentConfigWillWriteDefaults()
{
$this->fileSystem->expects($this->once())
->method('nodeExists')
->with($this->equalTo($this->configPath))
@ -200,7 +221,8 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
}
public function testNoLowMinimumAutoPurgeInterval() {
public function testNoLowMinimumAutoPurgeInterval()
{
$this->config->setAutoPurgeMinimumInterval(59);
$interval = $this->config->getAutoPurgeMinimumInterval();
@ -208,21 +230,24 @@ class ConfigTest extends PHPUnit_Framework_TestCase {
}
public function testMinimumAutoPurgeInterval() {
public function testMinimumAutoPurgeInterval()
{
$this->config->setAutoPurgeMinimumInterval(61);
$interval = $this->config->getAutoPurgeMinimumInterval();
$this->assertSame(61, $interval);
}
public function testMaxRedirects() {
public function testMaxRedirects()
{
$this->config->setMaxRedirects(21);
$redirects = $this->config->getMaxRedirects();
$this->assertSame(21, $redirects);
}
public function testFeedFetcherTimeout() {
public function testFeedFetcherTimeout()
{
$this->config->setFeedFetcherTimeout(2);
$timout = $this->config->getFeedFetcherTimeout();

View File

@ -5,18 +5,18 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
use OCA\News\Controller\AdminController;
class AdminControllerTest extends \PHPUnit_Framework_TestCase {
class AdminControllerTest extends \PHPUnit_Framework_TestCase
{
private $appName;
private $request;
@ -28,28 +28,35 @@ class AdminControllerTest extends \PHPUnit_Framework_TestCase {
/**
* Gets run before each test
*/
public function setUp(){
public function setUp()
{
$this->appName = 'news';
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->config = $this->getMockBuilder(
'\OCA\News\Config\Config')
'\OCA\News\Config\Config'
)
->disableOriginalConstructor()
->getMock();
$this->itemService = $this->getMockBuilder(
'\OCA\News\Service\ItemService')
'\OCA\News\Service\ItemService'
)
->disableOriginalConstructor()
->getMock();
$this->configPath = 'my.ini';
$this->controller = new AdminController($this->appName, $this->request,
$this->config, $this->itemService, $this->configPath);
$this->controller = new AdminController(
$this->appName, $this->request,
$this->config, $this->itemService, $this->configPath
);
}
public function testIndex() {
public function testIndex()
{
$expected = [
'autoPurgeMinimumInterval' => 1,
'autoPurgeCount' => 2,
@ -92,7 +99,8 @@ class AdminControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdate() {
public function testUpdate()
{
$expected = [
'autoPurgeMinimumInterval' => 1,
'autoPurgeCount' => 2,

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -19,15 +19,18 @@ use \OCP\AppFramework\Db\Entity;
use \OCA\News\Db\Item;
class TestEntity extends Entity {
class TestEntity extends Entity
{
}
class EntityApiSerializerTest extends \PHPUnit_Framework_TestCase {
class EntityApiSerializerTest extends \PHPUnit_Framework_TestCase
{
public function testSerializeSingle() {
public function testSerializeSingle()
{
$item = new Item();
$item->setUnread(true);
@ -38,7 +41,8 @@ class EntityApiSerializerTest extends \PHPUnit_Framework_TestCase {
}
public function testSerializeMultiple() {
public function testSerializeMultiple()
{
$item = new Item();
$item->setUnread(true);
@ -54,7 +58,8 @@ class EntityApiSerializerTest extends \PHPUnit_Framework_TestCase {
}
public function testResponseNoChange() {
public function testResponseNoChange()
{
$response = new Response();
$serializer = new EntityApiSerializer('items');
@ -64,7 +69,8 @@ class EntityApiSerializerTest extends \PHPUnit_Framework_TestCase {
}
public function testCompleteArraysTransformed() {
public function testCompleteArraysTransformed()
{
$item = new Item();
$item->setUnread(true);
@ -86,7 +92,8 @@ class EntityApiSerializerTest extends \PHPUnit_Framework_TestCase {
}
public function testNoEntityNoChange() {
public function testNoEntityNoChange()
{
$serializer = new EntityApiSerializer('items');
$in = [
@ -102,7 +109,8 @@ class EntityApiSerializerTest extends \PHPUnit_Framework_TestCase {
}
public function testEntitiesNoChange() {
public function testEntitiesNoChange()
{
$serializer = new EntityApiSerializer('items');
$in = [

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -22,7 +22,8 @@ use \OCA\News\Db\Item;
use \OCA\News\Db\Feed;
class ExportControllerTest extends \PHPUnit_Framework_TestCase {
class ExportControllerTest extends \PHPUnit_Framework_TestCase
{
private $appName;
private $request;
@ -36,32 +37,39 @@ class ExportControllerTest extends \PHPUnit_Framework_TestCase {
/**
* Gets run before each test
*/
public function setUp(){
public function setUp()
{
$this->appName = 'news';
$this->user = 'john';
$this->itemService = $this->getMockBuilder(
'\OCA\News\Service\ItemService')
'\OCA\News\Service\ItemService'
)
->disableOriginalConstructor()
->getMock();
$this->feedService = $this->getMockBuilder(
'\OCA\News\Service\FeedService')
'\OCA\News\Service\FeedService'
)
->disableOriginalConstructor()
->getMock();
$this->folderService = $this->getMockBuilder(
'\OCA\News\Service\FolderService')
'\OCA\News\Service\FolderService'
)
->disableOriginalConstructor()
->getMock();
$this->request = $this->getMockBuilder('\OCP\IRequest')
->disableOriginalConstructor()
->getMock();
$this->opmlExporter = new OPMLExporter();
$this->controller = new ExportController($this->appName, $this->request,
$this->controller = new ExportController(
$this->appName, $this->request,
$this->folderService, $this->feedService,
$this->itemService, $this->opmlExporter, $this->user);
$this->itemService, $this->opmlExporter, $this->user
);
}
public function testOpmlExportNoFeeds(){
public function testOpmlExportNoFeeds()
{
$opml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" .
"<opml version=\"2.0\">\n" .
@ -86,7 +94,8 @@ class ExportControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testGetAllArticles(){
public function testGetAllArticles()
{
$item1 = new Item();
$item1->setFeedId(3);
$item2 = new Item();
@ -119,14 +128,16 @@ class ExportControllerTest extends \PHPUnit_Framework_TestCase {
$headers ['Content-Disposition']
);
$this->assertEquals('[{"guid":null,"url":null,"title":null,' .
$this->assertEquals(
'[{"guid":null,"url":null,"title":null,' .
'"author":null,"pubDate":null,"updatedDate":null,"body":null,"enclosureMime":null,' .
'"enclosureLink":null,"unread":false,"starred":false,' .
'"feedLink":"http:\/\/goo","rtl":null},{"guid":null,"url":null,' .
'"title":null,"author":null,"pubDate":null,"updatedDate":null,"body":null,' .
'"enclosureMime":null,"enclosureLink":null,"unread":false,' .
'"starred":false,"feedLink":"http:\/\/gee","rtl":null}]',
$return->render());
$return->render()
);
}
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -23,7 +23,8 @@ use \OCA\News\Db\Feed;
use \OCA\News\Db\Item;
class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
class FeedApiControllerTest extends \PHPUnit_Framework_TestCase
{
private $feedService;
private $itemService;
@ -35,24 +36,29 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
private $logger;
private $loggerParams;
protected function setUp() {
protected function setUp()
{
$this->user = 'tom';
$this->loggerParams = ['hi'];
$this->logger = $this->getMockBuilder(
'\OCP\ILogger')
'\OCP\ILogger'
)
->disableOriginalConstructor()
->getMock();
$this->appName = 'news';
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->feedService = $this->getMockBuilder(
'\OCA\News\Service\FeedService')
'\OCA\News\Service\FeedService'
)
->disableOriginalConstructor()
->getMock();
$this->itemService = $this->getMockBuilder(
'\OCA\News\Service\ItemService')
'\OCA\News\Service\ItemService'
)
->disableOriginalConstructor()
->getMock();
$this->feedAPI = new FeedApiController(
@ -68,7 +74,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testIndex() {
public function testIndex()
{
$feeds = [new Feed()];
$starredCount = 3;
$newestItemId = 2;
@ -88,15 +95,18 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->feedAPI->index();
$this->assertEquals([
$this->assertEquals(
[
'feeds' => [$feeds[0]->toAPI()],
'starredCount' => $starredCount,
'newestItemId' => $newestItemId
], $response);
], $response
);
}
public function testIndexNoNewestItemId() {
public function testIndexNoNewestItemId()
{
$feeds = [new Feed()];
$starredCount = 3;
@ -115,29 +125,36 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->feedAPI->index();
$this->assertEquals([
$this->assertEquals(
[
'feeds' => [$feeds[0]->toAPI()],
'starredCount' => $starredCount,
], $response);
], $response
);
}
public function testDelete() {
public function testDelete()
{
$this->feedService->expects($this->once())
->method('delete')
->with(
$this->equalTo(2),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->feedAPI->delete(2);
}
public function testDeleteDoesNotExist() {
public function testDeleteDoesNotExist()
{
$this->feedService->expects($this->once())
->method('delete')
->will($this->throwException(
new ServiceNotFoundException($this->msg))
->will(
$this->throwException(
new ServiceNotFoundException($this->msg)
)
);
$response = $this->feedAPI->delete(2);
@ -148,7 +165,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testCreate() {
public function testCreate()
{
$feeds = [new Feed()];
$this->feedService->expects($this->once())
@ -159,7 +177,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
->with(
$this->equalTo('url'),
$this->equalTo(3),
$this->equalTo($this->user))
$this->equalTo($this->user)
)
->will($this->returnValue($feeds[0]));
$this->itemService->expects($this->once())
->method('getNewestItemId')
@ -167,14 +186,17 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->feedAPI->create('url', 3);
$this->assertEquals([
$this->assertEquals(
[
'feeds' => [$feeds[0]->toAPI()],
'newestItemId' => 3
], $response);
], $response
);
}
public function testCreateNoItems() {
public function testCreateNoItems()
{
$feeds = [new Feed()];
$this->feedService->expects($this->once())
@ -185,7 +207,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
->with(
$this->equalTo('ho'),
$this->equalTo(3),
$this->equalTo($this->user))
$this->equalTo($this->user)
)
->will($this->returnValue($feeds[0]));
$this->itemService->expects($this->once())
->method('getNewestItemId')
@ -193,14 +216,17 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->feedAPI->create('ho', 3);
$this->assertEquals([
$this->assertEquals(
[
'feeds' => [$feeds[0]->toAPI()]
], $response);
], $response
);
}
public function testCreateExists() {
public function testCreateExists()
{
$this->feedService->expects($this->once())
->method('purgeDeleted')
->with($this->equalTo($this->user), $this->equalTo(false));
@ -218,7 +244,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testCreateError() {
public function testCreateError()
{
$this->feedService->expects($this->once())
->method('create')
->will(
@ -233,31 +260,36 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testRead() {
public function testRead()
{
$this->itemService->expects($this->once())
->method('readFeed')
->with(
$this->equalTo(3),
$this->equalTo(30),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->feedAPI->read(3, 30);
}
public function testMove() {
public function testMove()
{
$this->feedService->expects($this->once())
->method('patch')
->with(
$this->equalTo(3),
$this->equalTo($this->user),
$this->equalTo(['folderId' => 30]));
$this->equalTo(['folderId' => 30])
);
$this->feedAPI->move(3, 30);
}
public function testMoveDoesNotExist() {
public function testMoveDoesNotExist()
{
$this->feedService->expects($this->once())
->method('patch')
->will(
@ -272,7 +304,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testRename() {
public function testRename()
{
$feedId = 3;
$feedTitle = 'test';
@ -281,13 +314,15 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
->with(
$this->equalTo($feedId),
$this->equalTo($this->user),
$this->equalTo(['title' => $feedTitle]));
$this->equalTo(['title' => $feedTitle])
);
$this->feedAPI->rename($feedId, $feedTitle);
}
public function testRenameError() {
public function testRenameError()
{
$feedId = 3;
$feedTitle = 'test';
@ -296,7 +331,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
->with(
$this->equalTo($feedId),
$this->equalTo($this->user),
$this->equalTo(['title' => $feedTitle]))
$this->equalTo(['title' => $feedTitle])
)
->will($this->throwException(new ServiceNotFoundException('hi')));
$result = $this->feedAPI->rename($feedId, $feedTitle);
@ -308,7 +344,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testfromAllUsers(){
public function testfromAllUsers()
{
$feed = new Feed();
$feed->setUrl(3);
$feed->setId(1);
@ -322,7 +359,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdate() {
public function testUpdate()
{
$feedId = 3;
$userId = 'hi';
@ -334,7 +372,8 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdateError() {
public function testUpdateError()
{
$feedId = 3;
$userId = 'hi';
$this->feedService->expects($this->once())
@ -342,8 +381,10 @@ class FeedApiControllerTest extends \PHPUnit_Framework_TestCase {
->will($this->throwException(new \Exception($this->msg)));
$this->logger->expects($this->once())
->method('debug')
->with($this->equalTo('Could not update feed ' . $this->msg),
$this->equalTo($this->loggerParams));
->with(
$this->equalTo('Could not update feed ' . $this->msg),
$this->equalTo($this->loggerParams)
);
$this->feedAPI->update($userId, $feedId);

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -22,7 +22,8 @@ use OCA\News\Service\ServiceNotFoundException;
use OCA\News\Service\ServiceConflictException;
class FeedControllerTest extends \PHPUnit_Framework_TestCase {
class FeedControllerTest extends \PHPUnit_Framework_TestCase
{
private $appName;
private $feedService;
@ -38,11 +39,13 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
/**
* Gets run before each test
*/
public function setUp(){
public function setUp()
{
$this->appName = 'news';
$this->user = 'jack';
$this->settings = $this->getMockBuilder(
'\OCP\IConfig')
'\OCP\IConfig'
)
->disableOriginalConstructor()
->getMock();
$this->itemService = $this
@ -58,15 +61,18 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
->disableOriginalConstructor()
->getMock();
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->controller = new FeedController($this->appName, $this->request,
$this->folderService,
$this->feedService,
$this->itemService,
$this->settings,
$this->user);
$this->controller = new FeedController(
$this->appName, $this->request,
$this->folderService,
$this->feedService,
$this->itemService,
$this->settings,
$this->user
);
$this->exampleResult = [
'activeFeed' => [
'id' => 0,
@ -76,7 +82,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testIndex(){
public function testIndex()
{
$result = [
'feeds' => [
['a feed'],
@ -102,7 +109,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testIndexHighestItemIdExists(){
public function testIndexHighestItemIdExists()
{
$result = [
'feeds' => [
['a feed'],
@ -130,23 +138,29 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
private function activeInitMocks($id, $type){
private function activeInitMocks($id, $type)
{
$this->settings->expects($this->at(0))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedId'))
$this->equalTo('lastViewedFeedId')
)
->will($this->returnValue($id));
$this->settings->expects($this->at(1))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedType'))
$this->equalTo('lastViewedFeedType')
)
->will($this->returnValue($type));
}
public function testActive(){
public function testActive()
{
$id = 3;
$type = FeedType::STARRED;
$result = [
@ -164,7 +178,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testActiveFeedDoesNotExist(){
public function testActiveFeedDoesNotExist()
{
$id = 3;
$type = FeedType::FEED;
$ex = new ServiceNotFoundException('hiu');
@ -183,7 +198,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testActiveFolderDoesNotExist(){
public function testActiveFolderDoesNotExist()
{
$id = 3;
$type = FeedType::FOLDER;
$ex = new ServiceNotFoundException('hiu');
@ -202,7 +218,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testActiveActiveIsNull(){
public function testActiveActiveIsNull()
{
$id = 3;
$type = null;
$result = $this->exampleResult;
@ -216,7 +233,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testCreate(){
public function testCreate()
{
$result = [
'feeds' => [new Feed()],
'newestItemId' => 3
@ -230,10 +248,12 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
->with($this->equalTo($this->user), $this->equalTo(false));
$this->feedService->expects($this->once())
->method('create')
->with($this->equalTo('hi'),
->with(
$this->equalTo('hi'),
$this->equalTo(4),
$this->equalTo($this->user),
$this->equalTo('yo'))
$this->equalTo('yo')
)
->will($this->returnValue($result['feeds'][0]));
$response = $this->controller->create('hi', 4, 'yo');
@ -242,7 +262,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testCreateNoItems(){
public function testCreateNoItems()
{
$result = ['feeds' => [new Feed()]];
$this->feedService->expects($this->once())
@ -255,10 +276,12 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
$this->feedService->expects($this->once())
->method('create')
->with($this->equalTo('hi'),
->with(
$this->equalTo('hi'),
$this->equalTo(4),
$this->equalTo($this->user),
$this->equalTo('yo'))
$this->equalTo('yo')
)
->will($this->returnValue($result['feeds'][0]));
$response = $this->controller->create('hi', 4, 'yo');
@ -267,7 +290,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testCreateReturnsErrorForInvalidCreate(){
public function testCreateReturnsErrorForInvalidCreate()
{
$msg = 'except';
$ex = new ServiceNotFoundException($msg);
$this->feedService->expects($this->once())
@ -287,7 +311,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testCreateReturnsErrorForDuplicateCreate(){
public function testCreateReturnsErrorForDuplicateCreate()
{
$msg = 'except';
$ex = new ServiceConflictException($msg);
$this->feedService->expects($this->once())
@ -305,7 +330,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testDelete(){
public function testDelete()
{
$this->feedService->expects($this->once())
->method('markDeleted')
->with($this->equalTo(4));
@ -314,7 +340,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testDeleteDoesNotExist(){
public function testDeleteDoesNotExist()
{
$msg = 'hehe';
$this->feedService->expects($this->once())
@ -329,7 +356,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdate(){
public function testUpdate()
{
$feed = new Feed();
$feed->setId(3);
$feed->setUnreadCount(44);
@ -353,7 +381,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdateReturnsJSONError(){
public function testUpdateReturnsJSONError()
{
$this->feedService->expects($this->once())
->method('update')
->with($this->equalTo(4), $this->equalTo($this->user))
@ -367,7 +396,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testImport() {
public function testImport()
{
$feed = new Feed();
$expected = [
@ -377,8 +407,10 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
$this->feedService->expects($this->once())
->method('importArticles')
->with($this->equalTo(['json']),
$this->equalTo($this->user))
->with(
$this->equalTo(['json']),
$this->equalTo($this->user)
)
->will($this->returnValue($feed));
$this->itemService->expects($this->once())
@ -392,11 +424,14 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testImportCreatesNoAdditionalFeed() {
public function testImportCreatesNoAdditionalFeed()
{
$this->feedService->expects($this->once())
->method('importArticles')
->with($this->equalTo(['json']),
$this->equalTo($this->user))
->with(
$this->equalTo(['json']),
$this->equalTo($this->user)
)
->will($this->returnValue(null));
$this->itemService->expects($this->once())
@ -410,7 +445,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testReadFeed(){
public function testReadFeed()
{
$expected = [
'feeds' => [
[
@ -429,7 +465,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testRestore() {
public function testRestore()
{
$this->feedService->expects($this->once())
->method('unmarkDeleted')
->with($this->equalTo(4));
@ -438,7 +475,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testRestoreDoesNotExist(){
public function testRestoreDoesNotExist()
{
$msg = 'hehe';
$this->feedService->expects($this->once())
@ -452,7 +490,8 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals($response->getStatus(), Http::STATUS_NOT_FOUND);
}
public function testPatch() {
public function testPatch()
{
$expected = [
'pinned' => true,
'fullTextEnabled' => true,
@ -460,15 +499,18 @@ class FeedControllerTest extends \PHPUnit_Framework_TestCase {
];
$this->feedService->expects($this->once())
->method('patch')
->with($this->equalTo(4),
$this->equalTo($this->user),
$this->equalTo($expected))
->with(
$this->equalTo(4),
$this->equalTo($this->user),
$this->equalTo($expected)
)
->will($this->returnValue(1));
$this->controller->patch(4, true, true, 1);
}
public function testPatchDoesNotExist(){
public function testPatchDoesNotExist()
{
$msg = 'hehe';
$this->feedService->expects($this->once())

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -26,7 +26,8 @@ use \OCA\News\Db\Feed;
use \OCA\News\Db\Item;
class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
class FolderApiControllerTest extends \PHPUnit_Framework_TestCase
{
private $folderService;
private $itemService;
@ -36,19 +37,23 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
private $request;
private $msg;
protected function setUp() {
protected function setUp()
{
$this->appName = 'news';
$this->user = 'tom';
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->folderService = $this->getMockBuilder(
'\OCA\News\Service\FolderService')
'\OCA\News\Service\FolderService'
)
->disableOriginalConstructor()
->getMock();
$this->itemService = $this->getMockBuilder(
'\OCA\News\Service\ItemService')
'\OCA\News\Service\ItemService'
)
->disableOriginalConstructor()
->getMock();
$this->folderAPI = new FolderApiController(
@ -62,7 +67,8 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testIndex() {
public function testIndex()
{
$folders = [new Folder()];
$this->folderService->expects($this->once())
@ -72,13 +78,16 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->folderAPI->index();
$this->assertEquals([
$this->assertEquals(
[
'folders' => [$folders[0]->toAPI()]
], $response);
], $response
);
}
public function testCreate() {
public function testCreate()
{
$folderName = 'test';
$folder = new Folder();
$folder->setName($folderName);
@ -93,13 +102,16 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->folderAPI->create($folderName);
$this->assertEquals([
$this->assertEquals(
[
'folders' => [$folder->toAPI()]
], $response);
], $response
);
}
public function testCreateAlreadyExists() {
public function testCreateAlreadyExists()
{
$msg = 'exists';
$this->folderService->expects($this->once())
@ -117,7 +129,8 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testCreateInvalidFolderName() {
public function testCreateInvalidFolderName()
{
$msg = 'exists';
$this->folderService->expects($this->once())
@ -137,7 +150,8 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testDelete() {
public function testDelete()
{
$folderId = 23;
$this->folderService->expects($this->once())
->method('delete')
@ -147,7 +161,8 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testDeleteDoesNotExist() {
public function testDeleteDoesNotExist()
{
$folderId = 23;
$this->folderService->expects($this->once())
@ -166,20 +181,24 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdate() {
public function testUpdate()
{
$folderId = 23;
$folderName = 'test';
$this->folderService->expects($this->once())
->method('rename')
->with($this->equalTo($folderId),
->with(
$this->equalTo($folderId),
$this->equalTo($folderName),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->folderAPI->update($folderId, $folderName);
}
public function testUpdateDoesNotExist() {
public function testUpdateDoesNotExist()
{
$folderId = 23;
$folderName = 'test';
@ -199,7 +218,8 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdateExists() {
public function testUpdateExists()
{
$folderId = 23;
$folderName = 'test';
@ -219,7 +239,8 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUpdateInvalidFolderName() {
public function testUpdateInvalidFolderName()
{
$folderId = 23;
$folderName = '';
@ -241,13 +262,15 @@ class FolderApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testRead() {
public function testRead()
{
$this->itemService->expects($this->once())
->method('readFolder')
->with(
$this->equalTo(3),
$this->equalTo(30),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->folderAPI->read(3, 30);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -23,7 +23,8 @@ use \OCA\News\Service\ServiceConflictException;
use \OCA\News\Service\ServiceValidationException;
class FolderControllerTest extends \PHPUnit_Framework_TestCase {
class FolderControllerTest extends \PHPUnit_Framework_TestCase
{
private $appName;
private $folderService;
@ -41,21 +42,28 @@ class FolderControllerTest extends \PHPUnit_Framework_TestCase {
{
$this->appName = 'news';
$this->user = 'jack';
$this->folderService = $this->getMockBuilder('\OCA\News\Service\FolderService')
$this->folderService = $this->getMockBuilder(
'\OCA\News\Service\FolderService'
)
->disableOriginalConstructor()
->getMock();
$this->feedService = $this->getMockBuilder('\OCA\News\Service\FeedService')
$this->feedService = $this->getMockBuilder(
'\OCA\News\Service\FeedService'
)
->disableOriginalConstructor()
->getMock();
$this->itemService = $this->getMockBuilder('\OCA\News\Service\ItemService')
$this->itemService = $this->getMockBuilder(
'\OCA\News\Service\ItemService'
)
->disableOriginalConstructor()
->getMock();
$this->request = $this->getMockBuilder('\OCP\IRequest')
$this->request = $this->getMockBuilder(
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->controller = new FolderController(
$this->appName,
$this->request,
$this->appName, $this->request,
$this->folderService,
$this->feedService,
$this->itemService,
@ -82,14 +90,14 @@ class FolderControllerTest extends \PHPUnit_Framework_TestCase {
->method('open')
->with(
$this->equalTo(3),
$this->equalTo(true),
$this->equalTo($this->user)
$this->equalTo(true), $this->equalTo($this->user)
);
$this->controller->open(3, true);
}
public function testOpenDoesNotExist()
{
$this->folderService->expects($this->once())
@ -108,14 +116,14 @@ class FolderControllerTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals($response->getStatus(), Http::STATUS_NOT_FOUND);
}
public function testCollapse()
{
$this->folderService->expects($this->once())
->method('open')
->with(
$this->equalTo(5),
$this->equalTo(false),
$this->equalTo($this->user)
$this->equalTo(false), $this->equalTo($this->user)
);
$this->controller->open(5, false);
@ -221,9 +229,11 @@ class FolderControllerTest extends \PHPUnit_Framework_TestCase {
$this->folderService->expects($this->once())
->method('rename')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo('tech'),
$this->equalTo($this->user))
$this->equalTo($this->user)
)
->will($this->returnValue($result['folders'][0]));
$response = $this->controller->rename('tech', 4);
@ -243,8 +253,10 @@ class FolderControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->controller->rename('tech', 4);
$params = json_decode($response->render(), true);
$this->assertEquals($response->getStatus(),
Http::STATUS_UNPROCESSABLE_ENTITY);
$this->assertEquals(
$response->getStatus(),
Http::STATUS_UNPROCESSABLE_ENTITY
);
$this->assertEquals($msg, $params['message']);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -20,7 +20,8 @@ use \OCA\News\Service\ServiceNotFoundException;
use \OCA\News\Db\Item;
class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
class ItemApiControllerTest extends \PHPUnit_Framework_TestCase
{
private $itemService;
private $itemAPI;
@ -29,15 +30,18 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
private $request;
private $msg;
protected function setUp() {
protected function setUp()
{
$this->user = 'tom';
$this->appName = 'news';
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->itemService = $this->getMockBuilder(
'\OCA\News\Service\ItemService')
'\OCA\News\Service\ItemService'
)
->disableOriginalConstructor()
->getMock();
$this->itemAPI = new ItemApiController(
@ -50,7 +54,8 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testIndex() {
public function testIndex()
{
$items = [new Item()];
$this->itemService->expects($this->once())
@ -68,13 +73,16 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->itemAPI->index(1, 2, true, 30, 20, true);
$this->assertEquals([
$this->assertEquals(
[
'items' => [$items[0]->toApi()]
], $response);
], $response
);
}
public function testIndexDefaultBatchSize() {
public function testIndexDefaultBatchSize()
{
$items = [new Item()];
$this->itemService->expects($this->once())
@ -92,13 +100,16 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->itemAPI->index(1, 2, false);
$this->assertEquals([
$this->assertEquals(
[
'items' => [$items[0]->toApi()]
], $response);
], $response
);
}
public function testUpdated() {
public function testUpdated()
{
$items = [new Item()];
$this->itemService->expects($this->once())
@ -114,13 +125,16 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
$response = $this->itemAPI->updated(1, 2, 30);
$this->assertEquals([
$this->assertEquals(
[
'items' => [$items[0]->toApi()]
], $response);
], $response
);
}
public function testRead() {
public function testRead()
{
$this->itemService->expects($this->once())
->method('read')
->with(
@ -133,11 +147,14 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testReadDoesNotExist() {
public function testReadDoesNotExist()
{
$this->itemService->expects($this->once())
->method('read')
->will($this->throwException(
new ServiceNotFoundException($this->msg))
->will(
$this->throwException(
new ServiceNotFoundException($this->msg)
)
);
$response = $this->itemAPI->read(2);
@ -148,7 +165,8 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUnread() {
public function testUnread()
{
$this->itemService->expects($this->once())
->method('read')
->with(
@ -161,11 +179,14 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUnreadDoesNotExist() {
public function testUnreadDoesNotExist()
{
$this->itemService->expects($this->once())
->method('read')
->will($this->throwException(
new ServiceNotFoundException($this->msg))
->will(
$this->throwException(
new ServiceNotFoundException($this->msg)
)
);
$response = $this->itemAPI->unread(2);
@ -176,7 +197,8 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testStar() {
public function testStar()
{
$this->itemService->expects($this->once())
->method('star')
->with(
@ -190,11 +212,14 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testStarDoesNotExist() {
public function testStarDoesNotExist()
{
$this->itemService->expects($this->once())
->method('star')
->will($this->throwException(
new ServiceNotFoundException($this->msg))
->will(
$this->throwException(
new ServiceNotFoundException($this->msg)
)
);
$response = $this->itemAPI->star(2, 'test');
@ -205,7 +230,8 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUnstar() {
public function testUnstar()
{
$this->itemService->expects($this->once())
->method('star')
->with(
@ -219,11 +245,14 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testUnstarDoesNotExist() {
public function testUnstarDoesNotExist()
{
$this->itemService->expects($this->once())
->method('star')
->will($this->throwException(
new ServiceNotFoundException($this->msg))
->will(
$this->throwException(
new ServiceNotFoundException($this->msg)
)
);
$response = $this->itemAPI->unstar(2, 'test');
@ -234,62 +263,78 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testReadAll() {
public function testReadAll()
{
$this->itemService->expects($this->once())
->method('readAll')
->with(
$this->equalTo(30),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemAPI->readAll(30);
}
public function testReadMultiple() {
public function testReadMultiple()
{
$this->itemService->expects($this->at(0))
->method('read')
->with($this->equalTo(2),
->with(
$this->equalTo(2),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemService->expects($this->at(1))
->method('read')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemAPI->readMultiple([2, 4]);
}
public function testReadMultipleDoesntCareAboutException() {
public function testReadMultipleDoesntCareAboutException()
{
$this->itemService->expects($this->at(0))
->method('read')
->will($this->throwException(new ServiceNotFoundException('')));
$this->itemService->expects($this->at(1))
->method('read')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemAPI->readMultiple([2, 4]);
}
public function testUnreadMultiple() {
public function testUnreadMultiple()
{
$this->itemService->expects($this->at(0))
->method('read')
->with($this->equalTo(2),
->with(
$this->equalTo(2),
$this->equalTo(false),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemService->expects($this->at(1))
->method('read')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo(false),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemAPI->unreadMultiple([2, 4]);
}
public function testStarMultiple() {
public function testStarMultiple()
{
$ids = [
[
'feedId' => 2,
@ -303,21 +348,26 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
$this->itemService->expects($this->at(0))
->method('star')
->with($this->equalTo(2),
->with(
$this->equalTo(2),
$this->equalTo('a'),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemService->expects($this->at(1))
->method('star')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo('b'),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemAPI->starMultiple($ids);
}
public function testStarMultipleDoesntCareAboutException() {
public function testStarMultipleDoesntCareAboutException()
{
$ids = [
[
'feedId' => 2,
@ -334,15 +384,18 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
->will($this->throwException(new ServiceNotFoundException('')));
$this->itemService->expects($this->at(1))
->method('star')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo('b'),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemAPI->starMultiple($ids);
}
public function testUnstarMultiple() {
public function testUnstarMultiple()
{
$ids = [
[
'feedId' => 2,
@ -356,16 +409,20 @@ class ItemApiControllerTest extends \PHPUnit_Framework_TestCase {
$this->itemService->expects($this->at(0))
->method('star')
->with($this->equalTo(2),
->with(
$this->equalTo(2),
$this->equalTo('a'),
$this->equalTo(false),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemService->expects($this->at(1))
->method('star')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo('b'),
$this->equalTo(false),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemAPI->unstarMultiple($ids);
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -22,7 +22,8 @@ use \OCA\News\Db\FeedType;
use \OCA\News\Service\ServiceNotFoundException;
class ItemControllerTest extends \PHPUnit_Framework_TestCase {
class ItemControllerTest extends \PHPUnit_Framework_TestCase
{
private $appName;
private $settings;
@ -36,11 +37,13 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
/**
* Gets run before each test
*/
public function setUp(){
public function setUp()
{
$this->appName = 'news';
$this->user = 'jackob';
$this->settings = $this->getMockBuilder(
'\OCP\IConfig')
'\OCP\IConfig'
)
->disableOriginalConstructor()
->getMock();
$this->itemService =
@ -52,17 +55,21 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
->disableOriginalConstructor()
->getMock();
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->controller = new ItemController($this->appName, $this->request,
$this->feedService, $this->itemService, $this->settings,
$this->user);
$this->controller = new ItemController(
$this->appName, $this->request,
$this->feedService, $this->itemService, $this->settings,
$this->user
);
$this->newestItemId = 12312;
}
public function testRead(){
public function testRead()
{
$this->itemService->expects($this->once())
->method('read')
->with(4, true, $this->user);
@ -71,7 +78,8 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testReadDoesNotExist(){
public function testReadDoesNotExist()
{
$msg = 'hi';
$this->itemService->expects($this->once())
@ -86,51 +94,64 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testReadMultiple() {
public function testReadMultiple()
{
$this->itemService->expects($this->at(0))
->method('read')
->with($this->equalTo(2),
->with(
$this->equalTo(2),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->itemService->expects($this->at(1))
->method('read')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->controller->readMultiple([2, 4]);
}
public function testReadMultipleDontStopOnException() {
public function testReadMultipleDontStopOnException()
{
$this->itemService->expects($this->at(0))
->method('read')
->with($this->equalTo(2),
->with(
$this->equalTo(2),
$this->equalTo(true),
$this->equalTo($this->user))
$this->equalTo($this->user)
)
->will($this->throwException(new ServiceNotFoundException('yo')));
$this->itemService->expects($this->at(1))
->method('read')
->with($this->equalTo(4),
->with(
$this->equalTo(4),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->controller->readMultiple([2, 4]);
}
public function testStar(){
public function testStar()
{
$this->itemService->expects($this->once())
->method('star')
->with(
$this->equalTo(4),
$this->equalTo('test'),
$this->equalTo(true),
$this->equalTo($this->user));
$this->equalTo($this->user)
);
$this->controller->star(4, 'test', true);
}
public function testStarDoesNotExist(){
public function testStarDoesNotExist()
{
$msg = 'ho';
$this->itemService->expects($this->once())
@ -145,15 +166,18 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testReadAll(){
public function testReadAll()
{
$feed = new Feed();
$expected = ['feeds' => [$feed]];
$this->itemService->expects($this->once())
->method('readAll')
->with($this->equalTo(5),
$this->equalTo($this->user));
->with(
$this->equalTo(5),
$this->equalTo($this->user)
);
$this->feedService->expects($this->once())
->method('findAll')
->with($this->equalTo($this->user))
@ -164,35 +188,45 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
private function itemsApiExpects($id, $type, $oldestFirst='1'){
private function itemsApiExpects($id, $type, $oldestFirst='1')
{
$this->settings->expects($this->at(0))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll'))
$this->equalTo('showAll')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(1))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('oldestFirst'))
$this->equalTo('oldestFirst')
)
->will($this->returnValue($oldestFirst));
$this->settings->expects($this->at(2))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedId'),
$this->equalTo($id));
$this->equalTo($id)
);
$this->settings->expects($this->at(3))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedType'),
$this->equalTo($type));
$this->equalTo($type)
);
}
public function testIndex(){
public function testIndex()
{
$feeds = [new Feed()];
$result = [
'items' => [new Item()],
@ -228,7 +262,8 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
$this->equalTo(true),
$this->equalTo(false),
$this->equalTo($this->user),
$this->equalTo([]))
$this->equalTo([])
)
->will($this->returnValue($result['items']));
$response = $this->controller->index(FeedType::FEED, 2, 3);
@ -236,7 +271,8 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testIndexSearch(){
public function testIndexSearch()
{
$feeds = [new Feed()];
$result = [
'items' => [new Item()],
@ -272,29 +308,35 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
$this->equalTo(true),
$this->equalTo(false),
$this->equalTo($this->user),
$this->equalTo(['test', 'search']))
$this->equalTo(['test', 'search'])
)
->will($this->returnValue($result['items']));
$response = $this->controller->index(FeedType::FEED, 2, 3,
0, null, null, 'test%20%20search%20');
$response = $this->controller->index(
FeedType::FEED, 2, 3,
0, null, null, 'test%20%20search%20'
);
$this->assertEquals($result, $response);
}
public function testItemsOffsetNotZero(){
public function testItemsOffsetNotZero()
{
$result = ['items' => [new Item()]];
$this->itemsApiExpects(2, FeedType::FEED);
$this->itemService->expects($this->once())
->method('findAll')
->with($this->equalTo(2),
->with(
$this->equalTo(2),
$this->equalTo(FeedType::FEED),
$this->equalTo(3),
$this->equalTo(10),
$this->equalTo(true),
$this->equalTo(true),
$this->equalTo($this->user))
$this->equalTo($this->user)
)
->will($this->returnValue($result['items']));
$this->feedService->expects($this->never())
@ -305,7 +347,8 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testGetItemsNoNewestItemsId(){
public function testGetItemsNoNewestItemsId()
{
$this->itemsApiExpects(2, FeedType::FEED);
$this->itemService->expects($this->once())
@ -318,7 +361,8 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testNewItems(){
public function testNewItems()
{
$feeds = [new Feed()];
$result = [
'items' => [new Item()],
@ -329,9 +373,11 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
$this->settings->expects($this->once())
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll'))
$this->equalTo('showAll')
)
->will($this->returnValue('1'));
$this->feedService->expects($this->once())
@ -356,7 +402,8 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
$this->equalTo(FeedType::FEED),
$this->equalTo(3),
$this->equalTo(true),
$this->equalTo($this->user))
$this->equalTo($this->user)
)
->will($this->returnValue($result['items']));
$response = $this->controller->newItems(FeedType::FEED, 2, 3);
@ -364,12 +411,15 @@ class ItemControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testGetNewItemsNoNewestItemsId(){
public function testGetNewItemsNoNewestItemsId()
{
$this->settings->expects($this->once())
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll'))
$this->equalTo('showAll')
)
->will($this->returnValue('1'));
$this->itemService->expects($this->once())

View File

@ -5,24 +5,27 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
use OCA\News\Controller\JSONHttpError;
class Test {
class Test
{
use JSONHttpError;
}
class JSONHttpErrorTest extends \PHPUnit_Framework_TestCase {
class JSONHttpErrorTest extends \PHPUnit_Framework_TestCase
{
public function testError() {
public function testError()
{
$ex = new \Exception('hi');
$test = new Test();
$result = $test->error($ex, 3);

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
@ -17,7 +17,8 @@ use OCA\News\Controller\PageController;
use \OCA\News\Db\FeedType;
class PageControllerTest extends \PHPUnit_Framework_TestCase {
class PageControllerTest extends \PHPUnit_Framework_TestCase
{
private $settings;
private $appName;
@ -35,7 +36,8 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
/**
* Gets run before each test
*/
public function setUp(){
public function setUp()
{
$this->appName = 'news';
$this->user = 'becka';
$this->configData = [
@ -49,52 +51,67 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
'homepage' => 'https://github.com/owncloud/test'
];
$this->l10n = $this->request = $this->getMockBuilder(
'\OCP\IL10n')
'\OCP\IL10n'
)
->disableOriginalConstructor()
->getMock();
$this->settings = $this->getMockBuilder(
'\OCP\IConfig')
'\OCP\IConfig'
)
->disableOriginalConstructor()
->getMock();
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->urlGenerator = $this->getMockBuilder(
'\OCP\IURLGenerator')
'\OCP\IURLGenerator'
)
->disableOriginalConstructor()
->getMock();
$this->appConfig = $this->getMockBuilder(
'\OCA\News\Config\Config')
'\OCA\News\Config\Config'
)
->disableOriginalConstructor()
->getMock();
$this->config = $this->getMockBuilder(
'\OCA\News\Config\Config')
'\OCA\News\Config\Config'
)
->disableOriginalConstructor()
->getMock();
$this->recommended = $this->getMockBuilder(
'\OCA\News\Explore\RecommendedSites')
'\OCA\News\Explore\RecommendedSites'
)
->disableOriginalConstructor()
->getMock();
$this->status = $this->getMockBuilder(
'\OCA\News\Service\StatusService')
'\OCA\News\Service\StatusService'
)
->disableOriginalConstructor()
->getMock();
$this->controller = new PageController($this->appName, $this->request,
$this->controller = new PageController(
$this->appName, $this->request,
$this->settings, $this->urlGenerator, $this->config,
$this->l10n, $this->recommended, $this->status,
$this->user);
$this->user
);
}
public function testIndex(){
public function testIndex()
{
$this->status->expects($this->once())
->method('getStatus')
->will($this->returnValue([
'warnings' => [
->will(
$this->returnValue(
[
'warnings' => [
'improperlyConfiguredCron' => false
]
]));
]
]
)
);
$response = $this->controller->index();
$this->assertEquals('index', $response->getTemplateName());
@ -102,14 +119,19 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testIndexNoCorrectCronAjax(){
public function testIndexNoCorrectCronAjax()
{
$this->status->expects($this->once())
->method('getStatus')
->will($this->returnValue([
'warnings' => [
->will(
$this->returnValue(
[
'warnings' => [
'improperlyConfiguredCron' => true
]
]));
]
]
)
);
$response = $this->controller->index();
@ -117,7 +139,8 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testSettings() {
public function testSettings()
{
$result = [
'settings' => [
'showAll' => true,
@ -135,41 +158,53 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
->will($this->returnValue('de'));
$this->settings->expects($this->at(0))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll'))
$this->equalTo('showAll')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(1))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compact'))
$this->equalTo('compact')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(2))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('preventReadOnScroll'))
$this->equalTo('preventReadOnScroll')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(3))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('oldestFirst'))
$this->equalTo('oldestFirst')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(4))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compactExpand'))
$this->equalTo('compactExpand')
)
->will($this->returnValue('1'));
$this->config->expects($this->once())
->method('getExploreUrl')
->will($this->returnValue(' '));
$this->urlGenerator->expects($this->once())
->method('linkToRoute')
->with($this->equalTo('news.page.explore'),
$this->equalTo(['lang' => 'en']))
->with(
$this->equalTo('news.page.explore'),
$this->equalTo(['lang' => 'en'])
)
->will($this->returnValue('test'));
@ -178,7 +213,8 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testSettingsExploreUrlSet() {
public function testSettingsExploreUrlSet()
{
$result = [
'settings' => [
'showAll' => true,
@ -196,33 +232,43 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
->will($this->returnValue('de'));
$this->settings->expects($this->at(0))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll'))
$this->equalTo('showAll')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(1))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compact'))
$this->equalTo('compact')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(2))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('preventReadOnScroll'))
$this->equalTo('preventReadOnScroll')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(3))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('oldestFirst'))
$this->equalTo('oldestFirst')
)
->will($this->returnValue('1'));
$this->settings->expects($this->at(4))
->method('getUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compactExpand'))
$this->equalTo('compactExpand')
)
->will($this->returnValue('1'));
$this->config->expects($this->once())
->method('getExploreUrl')
@ -235,57 +281,73 @@ class PageControllerTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals($result, $response);
}
public function testUpdateSettings() {
public function testUpdateSettings()
{
$this->settings->expects($this->at(0))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('showAll'),
$this->equalTo('1'));
$this->equalTo('1')
);
$this->settings->expects($this->at(1))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compact'),
$this->equalTo('1'));
$this->equalTo('1')
);
$this->settings->expects($this->at(2))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('preventReadOnScroll'),
$this->equalTo('0'));
$this->equalTo('0')
);
$this->settings->expects($this->at(3))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('oldestFirst'),
$this->equalTo('1'));
$this->equalTo('1')
);
$this->settings->expects($this->at(4))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('compactExpand'),
$this->equalTo('1'));
$this->equalTo('1')
);
$this->controller->updateSettings(true, true, false, true, true);
}
public function testExplore(){
public function testExplore()
{
$in = 'test';
$this->settings->expects($this->at(0))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedId'),
$this->equalTo(0));
$this->equalTo(0)
);
$this->settings->expects($this->at(1))
->method('setUserValue')
->with($this->equalTo($this->user),
->with(
$this->equalTo($this->user),
$this->equalTo($this->appName),
$this->equalTo('lastViewedFeedType'),
$this->equalTo(FeedType::EXPLORE));
$this->equalTo(FeedType::EXPLORE)
);
$this->recommended->expects($this->once())
->method('forLanguage')

View File

@ -5,17 +5,18 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
use OCA\News\Controller\UserApiController;
class UserApiControllerTest extends \PHPUnit_Framework_TestCase {
class UserApiControllerTest extends \PHPUnit_Framework_TestCase
{
private $request;
private $appName;
@ -25,26 +26,32 @@ class UserApiControllerTest extends \PHPUnit_Framework_TestCase {
private $user;
private $file;
protected function setUp() {
protected function setUp()
{
$this->appName = 'news';
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->rootFolder = $this->getMockBuilder(
'\OCP\Files\IRootFolder')
'\OCP\Files\IRootFolder'
)
->disableOriginalConstructor()
->getMock();
$this->file = $this->getMockBuilder(
'\OCP\Files\File')
'\OCP\Files\File'
)
->disableOriginalConstructor()
->getMock();
$this->userSession = $this->getMockBuilder(
'\OCP\IUserSession')
'\OCP\IUserSession'
)
->disableOriginalConstructor()
->getMock();
$this->user = $this->getMockBuilder(
'\OCP\IUser')
'\OCP\IUser'
)
->disableOriginalConstructor()
->getMock();
$this->controller = new UserApiController(
@ -55,7 +62,8 @@ class UserApiControllerTest extends \PHPUnit_Framework_TestCase {
}
private function expectUser($uid, $displayName, $lastLogin) {
private function expectUser($uid, $displayName, $lastLogin)
{
$this->userSession->expects($this->any())
->method('getUser')
->will($this->returnValue($this->user));
@ -70,16 +78,21 @@ class UserApiControllerTest extends \PHPUnit_Framework_TestCase {
->will($this->returnValue($displayName));
}
private function expectImg($isJpg, $isPng, $user, $exists, $data) {
private function expectImg($isJpg, $isPng, $user, $exists, $data)
{
$jpg = '/' . $user . '/' . 'avatar.jpg';
$png = '/' . $user . '/' . 'avatar.png';
$this->rootFolder->expects($this->any())
->method('nodeExists')
->will($this->returnValueMap([
[$jpg, $isJpg],
[$png, $isPng]
]));
->will(
$this->returnValueMap(
[
[$jpg, $isJpg],
[$png, $isPng]
]
)
);
$this->rootFolder->expects($this->any())
->method('get')
->will($this->returnValue($this->file));
@ -88,7 +101,8 @@ class UserApiControllerTest extends \PHPUnit_Framework_TestCase {
->will($this->returnValue($data));
}
public function testGetJpeg() {
public function testGetJpeg()
{
$this->expectUser('john', 'John', 123);
$this->expectImg(true, false, 'john', true, 'hi');
@ -106,7 +120,8 @@ class UserApiControllerTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals($expected, $result);
}
public function testGetPng() {
public function testGetPng()
{
$this->expectUser('john', 'John', 123);
$this->expectImg(false, true, 'john', false, 'hi');
@ -124,7 +139,8 @@ class UserApiControllerTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals($expected, $result);
}
public function testNoAvatar() {
public function testNoAvatar()
{
$this->expectUser('john', 'John', 123);
$this->expectImg(false, false, 'john', false, 'hi');

View File

@ -5,17 +5,18 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Controller;
use OCA\News\Controller\UtilityApiController;
class UtilityApiControllerTest extends \PHPUnit_Framework_TestCase {
class UtilityApiControllerTest extends \PHPUnit_Framework_TestCase
{
private $settings;
private $request;
@ -24,22 +25,27 @@ class UtilityApiControllerTest extends \PHPUnit_Framework_TestCase {
private $appName;
private $status;
protected function setUp() {
protected function setUp()
{
$this->appName = 'news';
$this->settings = $this->getMockBuilder(
'\OCP\IConfig')
'\OCP\IConfig'
)
->disableOriginalConstructor()
->getMock();
$this->request = $this->getMockBuilder(
'\OCP\IRequest')
'\OCP\IRequest'
)
->disableOriginalConstructor()
->getMock();
$this->updater = $this->getMockBuilder(
'\OCA\News\Utility\Updater')
'\OCA\News\Utility\Updater'
)
->disableOriginalConstructor()
->getMock();
$this->status = $this->getMockBuilder(
'\OCA\News\Service\StatusService')
'\OCA\News\Service\StatusService'
)
->disableOriginalConstructor()
->getMock();
$this->newsAPI = new UtilityApiController(
@ -49,11 +55,14 @@ class UtilityApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testGetVersion(){
public function testGetVersion()
{
$this->settings->expects($this->once())
->method('getAppValue')
->with($this->equalTo($this->appName),
$this->equalTo('installed_version'))
->with(
$this->equalTo($this->appName),
$this->equalTo('installed_version')
)
->will($this->returnValue('1.0'));
$response = $this->newsAPI->version();
@ -63,21 +72,24 @@ class UtilityApiControllerTest extends \PHPUnit_Framework_TestCase {
}
public function testBeforeUpdate(){
public function testBeforeUpdate()
{
$this->updater->expects($this->once())
->method('beforeUpdate');
$this->newsAPI->beforeUpdate();
}
public function testAfterUpdate(){
public function testAfterUpdate()
{
$this->updater->expects($this->once())
->method('afterUpdate');
$this->newsAPI->afterUpdate();
}
public function testStatus(){
public function testStatus()
{
$in = 'hi';
$this->status->expects($this->once())
->method('getStatus')

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Db;
@ -16,10 +16,12 @@ namespace OCA\News\Tests\Unit\Db;
use OCA\News\Db\Feed;
class FeedTest extends \PHPUnit_Framework_TestCase {
class FeedTest extends \PHPUnit_Framework_TestCase
{
private function createFeed() {
private function createFeed()
{
$feed = new Feed();
$feed->setId(3);
$feed->setHttpLastModified(44);
@ -43,10 +45,12 @@ class FeedTest extends \PHPUnit_Framework_TestCase {
return $feed;
}
public function testToAPI() {
public function testToAPI()
{
$feed = $this->createFeed();
$this->assertEquals([
$this->assertEquals(
[
'id' => 3,
'url' => 'http://google.com/some/weird/path',
'title' => 'title',
@ -59,14 +63,17 @@ class FeedTest extends \PHPUnit_Framework_TestCase {
'link' => 'https://www.google.com/some/weird/path',
'updateErrorCount' => 2,
'lastUpdateError' => 'hi'
], $feed->toAPI());
], $feed->toAPI()
);
}
public function testSerialize() {
public function testSerialize()
{
$feed = $this->createFeed();
$this->assertEquals([
$this->assertEquals(
[
'id' => 3,
'url' => 'http://google.com/some/weird/path',
'title' => 'title',
@ -90,25 +97,29 @@ class FeedTest extends \PHPUnit_Framework_TestCase {
'lastUpdateError' => 'hi',
'basicAuthUser' => 'user',
'basicAuthPassword' => 'password'
], $feed->jsonSerialize());
], $feed->jsonSerialize()
);
}
public function testSetXSSUrl() {
public function testSetXSSUrl()
{
$feed = new Feed();
$feed->setUrl('javascript:alert()');
$this->assertEquals('', $feed->getUrl());
}
public function testSetUrlUpdatesHash() {
public function testSetUrlUpdatesHash()
{
$feed = new Feed();
$feed->setUrl('http://test');
$this->assertEquals(md5('http://test'), $feed->getUrlHash());
}
public function testSetXSSLink() {
public function testSetXSSLink()
{
$feed = new Feed();
$feed->setLink('javascript:alert()');
$this->assertEquals('', $feed->getLink());

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Db;
@ -43,7 +43,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testFind(){
public function testFind()
{
$userId = 'john';
$id = 3;
$rows = [['id' => $this->folders[0]->getId()]];
@ -59,7 +60,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testFindNotFound(){
public function testFindNotFound()
{
$userId = 'john';
$id = 3;
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
@ -75,7 +77,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testFindMoreThanOneResultFound(){
public function testFindMoreThanOneResultFound()
{
$userId = 'john';
$id = 3;
$rows = $this->twoRows;
@ -93,7 +96,8 @@ class FolderMapperTest extends MapperTestUtility
public function testFindAllFromUser(){
public function testFindAllFromUser()
{
$userId = 'john';
$rows = $this->twoRows;
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
@ -107,7 +111,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testFindByName(){
public function testFindByName()
{
$folderName = 'heheh';
$userId = 'john';
$rows = $this->twoRows;
@ -122,7 +127,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testDelete(){
public function testDelete()
{
$folder = new Folder();
$folder->setId(3);
@ -143,7 +149,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testGetPurgeDeleted(){
public function testGetPurgeDeleted()
{
$rows = $this->twoRows;
$deleteOlderThan = 110;
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
@ -157,7 +164,8 @@ class FolderMapperTest extends MapperTestUtility
public function testGetPurgeDeletedUser(){
public function testGetPurgeDeletedUser()
{
$rows = $this->twoRows;
$deleteOlderThan = 110;
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
@ -173,7 +181,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testGetAllPurgeDeletedUser(){
public function testGetAllPurgeDeletedUser()
{
$rows = $this->twoRows;
$sql = 'SELECT * FROM `*PREFIX*news_folders` ' .
@ -186,7 +195,8 @@ class FolderMapperTest extends MapperTestUtility
}
public function testDeleteFromUser(){
public function testDeleteFromUser()
{
$userId = 'john';
$sql = 'DELETE FROM `*PREFIX*news_folders` WHERE `user_id` = ?';

View File

@ -5,32 +5,37 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Db;
use OCA\News\Db\Folder;
class FolderTest extends \PHPUnit_Framework_TestCase {
class FolderTest extends \PHPUnit_Framework_TestCase
{
public function testToAPI() {
public function testToAPI()
{
$folder = new Folder();
$folder->setId(3);
$folder->setName('name');
$this->assertEquals([
$this->assertEquals(
[
'id' => 3,
'name' => 'name'
], $folder->toAPI());
], $folder->toAPI()
);
}
public function testSerialize() {
public function testSerialize()
{
$folder = new Folder();
$folder->setId(3);
$folder->setName('john');
@ -39,13 +44,15 @@ class FolderTest extends \PHPUnit_Framework_TestCase {
$folder->setOpened(true);
$folder->setDeletedAt(9);
$this->assertEquals([
$this->assertEquals(
[
'id' => 3,
'parentId' => 4,
'name' => 'john',
'userId' => 'abc',
'opened' => true,
'deletedAt' => 9,
], $folder->jsonSerialize());
], $folder->jsonSerialize()
);
}
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Db;
@ -16,46 +16,55 @@ namespace OCA\News\Tests\Unit\Db;
use OCA\News\Db\Feed;
use OCA\News\Db\Item;
class ItemTest extends \PHPUnit_Framework_TestCase {
class ItemTest extends \PHPUnit_Framework_TestCase
{
/** @var Item */
/**
* @var Item
*/
private $item;
protected function setUp(){
protected function setUp()
{
$this->item = new Item();
$this->item->setStatus(0);
}
public function testSetRead(){
public function testSetRead()
{
$this->item->setUnread(false);
$this->assertFalse($this->item->isUnread());
}
public function testSetUnread(){
public function testSetUnread()
{
$this->item->setUnread(true);
$this->assertTrue($this->item->isUnread());
}
public function testSetStarred(){
public function testSetStarred()
{
$this->item->setStarred(true);
$this->assertTrue($this->item->isStarred());
}
public function testSetUnstarred(){
public function testSetUnstarred()
{
$this->item->setStarred(false);
$this->assertFalse($this->item->isStarred());
}
public function testToAPI() {
public function testToAPI()
{
$item = new Item();
$item->setId(3);
$item->setGuid('guid');
@ -77,7 +86,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
$item->setFingerprint('fingerprint');
$item->setContentHash('contentHash');
$this->assertEquals([
$this->assertEquals(
[
'id' => 3,
'guid' => 'guid',
'guidHash' => 'hash',
@ -96,11 +106,13 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
'rtl' => true,
'fingerprint' => 'fingerprint',
'contentHash' => 'contentHash'
], $item->toAPI());
], $item->toAPI()
);
}
public function testJSONSerialize() {
public function testJSONSerialize()
{
$item = new Item();
$item->setId(3);
$item->setGuid('guid');
@ -121,7 +133,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
$item->setStarred(true);
$item->setLastModified(321);
$this->assertEquals([
$this->assertEquals(
[
'id' => 3,
'guid' => 'guid',
'guidHash' => 'hash',
@ -140,10 +153,12 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
'rtl' => true,
'intro' => 'this is a test',
'fingerprint' => 'fingerprint'
], $item->jsonSerialize());
], $item->jsonSerialize()
);
}
public function testToExport() {
public function testToExport()
{
$item = new Item();
$item->setId(3);
$item->setGuid('guid');
@ -167,7 +182,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
$feed->setLink('http://test');
$feeds = ["feed1" => $feed];
$this->assertEquals([
$this->assertEquals(
[
'guid' => 'guid',
'url' => 'https://google',
'title' => 'title',
@ -181,11 +197,13 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
'starred' => true,
'feedLink' => 'http://test',
'rtl' => true
], $item->toExport($feeds));
], $item->toExport($feeds)
);
}
private function createImportItem($isRead) {
private function createImportItem($isRead)
{
$item = new Item();
$item->setGuid('guid');
$item->setGuidHash('guid');
@ -210,7 +228,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
}
public function testSearchIndex() {
public function testSearchIndex()
{
$item = new Item();
$item->setBody('<a>somEth&auml;ng</a>');
$item->setUrl('http://link');
@ -222,7 +241,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
}
public function testFromImport() {
public function testFromImport()
{
$item = $this->createImportItem(false);
$import = [
@ -246,7 +266,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
}
public function testFromImportRead() {
public function testFromImportRead()
{
$item = $this->createImportItem(true);
$import = [
@ -271,7 +292,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
public function testSetAuthor(){
public function testSetAuthor()
{
$item = new Item();
$item->setAuthor('<a>my link</li>');
$this->assertEquals('my link', $item->getAuthor());
@ -279,7 +301,8 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
}
public function testSetTitle(){
public function testSetTitle()
{
$item = new Item();
$item->setTitle('<a>my link</li>');
$this->assertEquals('my link', $item->getTitle());
@ -287,28 +310,34 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
}
public function testSetXSSUrl() {
public function testSetXSSUrl()
{
$item = new Item();
$item->setUrl('javascript:alert()');
$this->assertEquals('', $item->getUrl());
}
public function testSetMagnetUrl() {
public function testSetMagnetUrl()
{
$item = new Item();
$item->setUrl('magnet://link.com');
$this->assertEquals('magnet://link.com', $item->getUrl());
}
public function testMakeLinksInBodyOpenNewTab() {
public function testMakeLinksInBodyOpenNewTab()
{
$item = new Item();
$item->setBody("<a href=\"test\">ha</a>");
$this->assertEquals("<a target=\"_blank\" rel=\"noreferrer\" href=\"test\">ha</a>",
$item->getBody());
$this->assertEquals(
"<a target=\"_blank\" rel=\"noreferrer\" href=\"test\">ha</a>",
$item->getBody()
);
}
public function testComputeFingerPrint() {
public function testComputeFingerPrint()
{
$title = 'a';
$body = 'b';
$url = 'http://google.com';
@ -321,8 +350,10 @@ class ItemTest extends \PHPUnit_Framework_TestCase {
$item->setEnclosureLink($link);
$item->generateSearchIndex();
$this->assertEquals(md5($title . $url . $body . $link),
$item->getFingerprint());
$this->assertEquals(
md5($title . $url . $body . $link),
$item->getFingerprint()
);
}
}

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Db;
@ -23,30 +23,35 @@ use OCP\IDBConnection;
use OCA\News\Db\Mysql\ItemMapper as MysqlMapper;
class MapperFactoryTest extends PHPUnit_Framework_TestCase {
class MapperFactoryTest extends PHPUnit_Framework_TestCase
{
private $db;
private $settings;
private $db;
private $settings;
public function setUp() {
$this->db = $this->getMockBuilder(IDBConnection::class)
->disableOriginalConstructor()
->getMock();
}
public function setUp()
{
$this->db = $this->getMockBuilder(IDBConnection::class)
->disableOriginalConstructor()
->getMock();
}
public function testGetItemMapperSqlite() {
$factory = new MapperFactory($this->db, 'sqlite', new Time());
$this->assertTrue($factory->build() instanceof ItemMapper);
}
public function testGetItemMapperSqlite()
{
$factory = new MapperFactory($this->db, 'sqlite', new Time());
$this->assertTrue($factory->build() instanceof ItemMapper);
}
public function testGetItemMapperPostgres() {
$factory = new MapperFactory($this->db, 'pgsql', new Time());
$this->assertTrue($factory->build() instanceof ItemMapper);
}
public function testGetItemMapperPostgres()
{
$factory = new MapperFactory($this->db, 'pgsql', new Time());
$this->assertTrue($factory->build() instanceof ItemMapper);
}
public function testGetItemMapperMysql() {
$factory = new MapperFactory($this->db, 'mysql', new Time());
$this->assertTrue($factory->build() instanceof MysqlMapper);
}
public function testGetItemMapperMysql()
{
$factory = new MapperFactory($this->db, 'mysql', new Time());
$this->assertTrue($factory->build() instanceof MysqlMapper);
}
}

View File

@ -3,7 +3,7 @@
/**
* ownCloud - App Framework
*
* @author Bernhard Posselt
* @author Bernhard Posselt
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com
*
* This library is free software; you can redistribute it and/or
@ -18,7 +18,6 @@
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
@ -27,7 +26,8 @@ namespace OCA\News\Tests\Unit\Db;
/**
* Simple utility class for testing mappers
*/
abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase
{
protected $db;
private $query;
private $queryAt;
@ -40,11 +40,13 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
* Run this function before the actual test to either set or initialize the
* db. After this the db can be accessed by using $this->db
*/
protected function setUp(){
protected function setUp()
{
parent::setUp();
$this->db = $this->getMockBuilder(
'\OCP\IDBConnection')
'\OCP\IDBConnection'
)
->disableOriginalConstructor()
->getMock();
@ -57,40 +59,47 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
/**
* Checks if an array is associative
* @param array $array
*
* @param array $array
* @return bool true if associative
*/
private function isAssocArray(array $array) {
private function isAssocArray(array $array)
{
return array_values($array) !== $array;
}
/**
* Returns the correct PDO constant based on the value type
* @param $value
*
* @param $value
* @return PDO constant
*/
private function getPDOType($value) {
private function getPDOType($value)
{
switch (gettype($value)) {
case 'integer':
return \PDO::PARAM_INT;
case 'boolean':
return \PDO::PARAM_BOOL;
default:
return \PDO::PARAM_STR;
case 'integer':
return \PDO::PARAM_INT;
case 'boolean':
return \PDO::PARAM_BOOL;
default:
return \PDO::PARAM_STR;
}
}
/**
* Create mocks and set expected results for database queries
* @param string $sql the sql query that you expect to receive
* @param array $arguments the expected arguments for the prepare query
* method
* @param array $returnRows the rows that should be returned for the result
* of the database query. If not provided, it wont be assumed that fetch
* will be called on the result
*
* @param string $sql the sql query that you expect to receive
* @param array $arguments the expected arguments for the prepare query
* method
* @param array $returnRows the rows that should be returned for the result
* of the database query. If not provided, it wont
* be assumed that fetch will be called on the
* result
*/
protected function setMapperResult($sql, $arguments=array(), $returnRows=array(),
$limit=null, $offset=null, $expectClose=false){
$limit=null, $offset=null, $expectClose=false
) {
if($limit === null && $offset === null) {
$this->db->expects($this->at($this->prepareAt))
->method('prepare')
@ -104,16 +113,20 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
} elseif($limit === null && $offset !== null) {
$this->db->expects($this->at($this->prepareAt))
->method('prepare')
->with($this->equalTo($sql),
->with(
$this->equalTo($sql),
$this->equalTo(null),
$this->equalTo($offset))
$this->equalTo($offset)
)
->will(($this->returnValue($this->query)));
} else {
$this->db->expects($this->at($this->prepareAt))
->method('prepare')
->with($this->equalTo($sql),
->with(
$this->equalTo($sql),
$this->equalTo($limit),
$this->equalTo($offset))
$this->equalTo($offset)
)
->will(($this->returnValue($this->query)));
}
@ -124,29 +137,33 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
$this->query->expects($this->any())
->method('fetch')
->will($this->returnCallback(
function() use ($iterators, $fetchAt){
$iterator = $iterators[$fetchAt];
$result = $iterator->next();
->will(
$this->returnCallback(
function () use ($iterators, $fetchAt) {
$iterator = $iterators[$fetchAt];
$result = $iterator->next();
if($result === false) {
$fetchAt++;
if($result === false) {
$fetchAt++;
}
$this->queryAt++;
return $result;
}
$this->queryAt++;
return $result;
}
));
)
);
if ($this->isAssocArray($arguments)) {
foreach($arguments as $key => $argument) {
$pdoConstant = $this->getPDOType($argument);
$this->query->expects($this->at($this->queryAt))
->method('bindValue')
->with($this->equalTo($key),
->with(
$this->equalTo($key),
$this->equalTo($argument),
$this->equalTo($pdoConstant));
$this->equalTo($pdoConstant)
);
$this->queryAt++;
}
} else {
@ -155,9 +172,11 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
$pdoConstant = $this->getPDOType($argument);
$this->query->expects($this->at($this->queryAt))
->method('bindValue')
->with($this->equalTo($index),
->with(
$this->equalTo($index),
$this->equalTo($argument),
$this->equalTo($pdoConstant));
$this->equalTo($pdoConstant)
);
$index++;
$this->queryAt++;
}
@ -165,9 +184,13 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
$this->query->expects($this->at($this->queryAt))
->method('execute')
->will($this->returnCallback(function($sql, $p=null, $o=null, $s=null) {
->will(
$this->returnCallback(
function ($sql, $p=null, $o=null, $s=null) {
}));
}
)
);
$this->queryAt++;
@ -188,17 +211,20 @@ abstract class MapperTestUtility extends \PHPUnit_Framework_TestCase {
}
class ArgumentIterator {
class ArgumentIterator
{
private $arguments;
public function __construct($arguments){
public function __construct($arguments)
{
$this->arguments = $arguments;
}
public function next(){
public function next()
{
$result = array_shift($this->arguments);
if($result === null){
if($result === null) {
return false;
} else {
return $result;

View File

@ -5,10 +5,10 @@
* 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
* @author Alessandro Cosentino <cosenal@gmail.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright 2012 Alessandro Cosentino
* @copyright 2012-2014 Bernhard Posselt
*/
namespace OCA\News\Tests\Unit\Fetcher;
@ -20,7 +20,8 @@ use OCP\Http\Client\IClientService;
use PicoFeed\Processor\ItemPostProcessor;
class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
class FeedFetcherTest extends \PHPUnit_Framework_TestCase
{
private $fetcher;
private $parser;
@ -58,43 +59,53 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
private $location;
private $feedLanguage;
protected function setUp(){
protected function setUp()
{
$this->l10n = $this->getMockBuilder(
'\OCP\IL10N')
'\OCP\IL10N'
)
->disableOriginalConstructor()
->getMock();
$this->reader = $this->getMockBuilder(
'\PicoFeed\Reader\Reader')
'\PicoFeed\Reader\Reader'
)
->disableOriginalConstructor()
->getMock();
$this->parser = $this->getMockBuilder(
'\PicoFeed\Parser\Parser')
'\PicoFeed\Parser\Parser'
)
->disableOriginalConstructor()
->getMock();
$this->client = $this->getMockBuilder(
'\PicoFeed\Client\Client')
'\PicoFeed\Client\Client'
)
->disableOriginalConstructor()
->getMock();
$this->parsedFeed = $this->getMockBuilder(
'\PicoFeed\Parser\Feed')
'\PicoFeed\Parser\Feed'
)
->disableOriginalConstructor()
->getMock();
$this->item = $this->getMockBuilder(
'\PicoFeed\Parser\Item')
'\PicoFeed\Parser\Item'
)
->disableOriginalConstructor()
->getMock();
$this->faviconFetcher = $this->getMockBuilder(
'\PicoFeed\Reader\Favicon')
'\PicoFeed\Reader\Favicon'
)
->disableOriginalConstructor()
->getMock();
$this->faviconFactory = $this->getMockBuilder(
'\OCA\News\Utility\PicoFeedFaviconFactory')
'\OCA\News\Utility\PicoFeedFaviconFactory'
)
->disableOriginalConstructor()
->getMock();
$this->time = 2323;
$timeFactory = $this->getMockBuilder(
'\OCA\News\Utility\Time')
'\OCA\News\Utility\Time'
)
->disableOriginalConstructor()
->getMock();
$timeFactory->expects($this->any())
@ -108,11 +119,12 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
$clientService = $this->getMockBuilder(IClientService::class)
->getMock();
$this->fetcher = new FeedFetcher(
$this->reader,
$this->faviconFactory,
$this->l10n,
$timeFactory,
$clientService);
$this->reader,
$this->faviconFactory,
$this->l10n,
$timeFactory,
$clientService
);
$this->url = 'http://tests';
$this->permalink = 'http://permalink';
@ -140,13 +152,15 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
}
public function testCanHandle(){
public function testCanHandle()
{
$url = 'google.de';
$this->assertTrue($this->fetcher->canHandle($url));
}
private function setUpReader($url='', $modified=true, $noParser=false) {
private function setUpReader($url='', $modified=true, $noParser=false)
{
$this->reader->expects($this->once())
->method('discover')
->with($this->equalTo($url))
@ -178,9 +192,11 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
if ($noParser) {
$this->reader->expects($this->once())
->method('getParser')
->will($this->throwException(
new \PicoFeed\Reader\SubscriptionNotFoundException()
));
->will(
$this->throwException(
new \PicoFeed\Reader\SubscriptionNotFoundException()
)
);
} else {
$this->reader->expects($this->once())
->method('getParser')
@ -200,20 +216,23 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
}
private function expectFeed($method, $return, $count = 1) {
private function expectFeed($method, $return, $count = 1)
{
$this->parsedFeed->expects($this->exactly($count))
->method($method)
->will($this->returnValue($return));
}
private function expectItem($method, $return, $count = 1) {
private function expectItem($method, $return, $count = 1)
{
$this->item->expects($this->exactly($count))
->method($method)
->will($this->returnValue($return));
}
private function createItem($enclosureType=null) {
private function createItem($enclosureType=null)
{
$this->expectItem('getUrl', $this->permalink);
$this->expectItem('getTitle', $this->title);
$this->expectItem('getId', $this->guid);
@ -223,11 +242,11 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
date_default_timezone_set('America/Los_Angeles');
$pubdate = \Datetime::createFromFormat('U',$this->pub);
$pubdate = \Datetime::createFromFormat('U', $this->pub);
$this->expectItem('getPublishedDate', $pubdate);
$item->setPubDate($this->pub);
$update = \Datetime::createFromFormat('U',$this->updated);
$update = \Datetime::createFromFormat('U', $this->updated);
$this->expectItem('getUpdatedDate', $update);
$item->setUpdatedDate($this->updated);
@ -256,7 +275,8 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
}
private function createFeed($hasFavicon=false) {
private function createFeed($hasFavicon=false)
{
$this->expectFeed('getTitle', $this->feedTitle);
$this->expectFeed('getSiteUrl', $this->feedLink);
@ -283,12 +303,14 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
return $feed;
}
public function testNoFetchIfNotModified(){
public function testNoFetchIfNotModified()
{
$this->setUpReader($this->url, false);;
$result = $this->fetcher->fetch($this->url, false);
}
public function testFetch(){
public function testFetch()
{
$this->setUpReader($this->url);
$item = $this->createItem();
$feed = $this->createFeed();
@ -299,7 +321,8 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
}
public function testAudioEnclosure(){
public function testAudioEnclosure()
{
$this->setUpReader($this->url);
$item = $this->createItem('audio/ogg');
$feed = $this->createFeed();
@ -310,7 +333,8 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
}
public function testVideoEnclosure(){
public function testVideoEnclosure()
{
$this->setUpReader($this->url);
$item = $this->createItem('video/ogg');
$feed = $this->createFeed();
@ -322,7 +346,8 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
public function testFavicon() {
public function testFavicon()
{
$this->setUpReader($this->url);
$feed = $this->createFeed(true);
@ -333,7 +358,8 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals([$feed, [$item]], $result);
}
public function testFullText() {
public function testFullText()
{
$this->setUpReader($this->url);
$feed = $this->createFeed();
@ -345,13 +371,14 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
}
public function testNoFavicon() {
public function testNoFavicon()
{
$this->setUpReader($this->url);
$feed = $this->createFeed(false);
$this->faviconFetcher->expects($this->never())
->method('find');
->method('find');
$item = $this->createItem();
$this->expectFeed('getItems', [$this->item]);
@ -361,20 +388,24 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
}
public function testRtl() {
public function testRtl()
{
$this->setUpReader($this->url);
$this->expectFeed('getLanguage', 'he-IL');
$this->expectItem('getLanguage', '');
$feed = $this->createFeed();
$item = $this->createItem(null);
$this->expectFeed('getItems', [$this->item]);
list($feed, $items) = $this->fetcher->fetch($this->url, false, null,
null, true);
list($feed, $items) = $this->fetcher->fetch(
$this->url, false, null,
null, true
);
$this->assertTrue($items[0]->getRtl());
}
public function testRtlItemPrecedence() {
public function testRtlItemPrecedence()
{
$this->setUpReader($this->url);
$this->expectFeed('getLanguage', 'de-DE');
$this->expectItem('getLanguage', 'he-IL');
@ -382,12 +413,15 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
$feed = $this->createFeed();
$item = $this->createItem(null);
$this->expectFeed('getItems', [$this->item]);
list($feed, $items) = $this->fetcher->fetch($this->url, false, null,
null, true);
list($feed, $items) = $this->fetcher->fetch(
$this->url, false, null,
null, true
);
$this->assertTrue($items[0]->getRtl());
}
public function testNegativeRtlItemPrecedence() {
public function testNegativeRtlItemPrecedence()
{
$this->setUpReader($this->url);
$this->expectFeed('getLanguage', 'he-IL');
$this->expectItem('getLanguage', 'de-DE');
@ -395,8 +429,10 @@ class FeedFetcherTest extends \PHPUnit_Framework_TestCase {
$feed = $this->createFeed();
$item = $this->createItem(null);
$this->expectFeed('getItems', [$this->item]);
list($feed, $items) = $this->fetcher->fetch($this->url, false, null,
null, true);
list($feed, $items) = $this->fetcher->fetch(
$this->url, false, null,
null, true
);
$this->assertFalse($items[0]->getRtl());
}

View File

@ -1,43 +1,45 @@
<?php
/**
* Nextcloud - News
*
* @author Alessandro Cosentino
* @author Bernhard Posselt
* @copyright 2012 Alessandro Cosentino cosenal@gmail.com
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
* Nextcloud - News
*
* @author Alessandro Cosentino
* @author Bernhard Posselt
* @copyright 2012 Alessandro Cosentino cosenal@gmail.com
* @copyright 2012 Bernhard Posselt dev@bernhard-posselt.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
namespace OCA\News\Tests\Unit\Fetcher;
use OCA\News\Fetcher\Fetcher;
class FetcherTest extends \PHPUnit_Framework_TestCase {
class FetcherTest extends \PHPUnit_Framework_TestCase
{
private $fetcher;
protected function setUp(){
protected function setUp()
{
$this->fetcher = new Fetcher();
}
public function testFetch(){
public function testFetch()
{
$url = 'hi';
$mockFetcher = $this->getMockBuilder('\OCA\News\Fetcher\IFeedFetcher')
->disableOriginalConstructor()
@ -48,18 +50,21 @@ class FetcherTest extends \PHPUnit_Framework_TestCase {
->will($this->returnValue(true));
$mockFetcher->expects($this->once())
->method('fetch')
->with($this->equalTo($url),
$this->equalTo(true),
$this->equalTo(1),
$this->equalTo(2),
$this->equalTo(3));
->with(
$this->equalTo($url),
$this->equalTo(true),
$this->equalTo(1),
$this->equalTo(2),
$this->equalTo(3)
);
$this->fetcher->registerFetcher($mockFetcher);
$this->fetcher->fetch($url, true, 1, 2, 3);
}
public function testNoFetchers(){
public function testNoFetchers()
{
$url = 'hi';
$mockFetcher = $this->getMockBuilder('\OCA\News\Fetcher\IFeedFetcher')
->disableOriginalConstructor()
@ -83,7 +88,8 @@ class FetcherTest extends \PHPUnit_Framework_TestCase {
$this->assertEquals([null, []], $result);
}
public function testMultipleFetchers(){
public function testMultipleFetchers()
{
$url = 'hi';
$mockFetcher = $this->getMockBuilder('\OCA\News\Fetcher\IFeedFetcher')
->disableOriginalConstructor()
@ -107,7 +113,8 @@ class FetcherTest extends \PHPUnit_Framework_TestCase {
}
public function testMultipleFetchersOnlyOneShouldHandle(){
public function testMultipleFetchersOnlyOneShouldHandle()
{
$url = 'hi';
$return = 'zeas';
$mockFetcher = $this->getMockBuilder('\OCA\News\Fetcher\IFeedFetcher')

View File

@ -5,7 +5,7 @@
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @copyright Bernhard Posselt 2012, 2014
*/
@ -15,33 +15,39 @@ use \OCA\News\Db\Feed;
use OCA\News\Fetcher\YoutubeFetcher;
class YoutubeFetcherTest extends \PHPUnit_Framework_TestCase {
class YoutubeFetcherTest extends \PHPUnit_Framework_TestCase
{
private $fetcher;
private $feedFetcher;
public function setUp() {
public function setUp()
{
$this->feedFetcher = $this->getMockBuilder(
'\OCA\News\Fetcher\FeedFetcher')
'\OCA\News\Fetcher\FeedFetcher'
)
->disableOriginalConstructor()
->getMock();
$this->fetcher = new YoutubeFetcher($this->feedFetcher);
}
public function testCanHandleFails() {
public function testCanHandleFails()
{
$url = 'http://youtube.com';
$this->assertFalse($this->fetcher->canHandle($url));
}
public function testCanHandle() {
public function testCanHandle()
{
$url = 'http://youtube.com/test/?test=a&list=b&b=c';
$this->assertTrue($this->fetcher->canHandle($url));
}
public function testPlaylistUrl() {
public function testPlaylistUrl()
{
$url = 'http://youtube.com/something/weird?a=b&list=sobo3&c=1';
$transformedUrl = 'http://gdata.youtube.com/feeds/api/playlists/sobo3';
$favicon = true;

Some files were not shown because too many files have changed in this diff Show More