From: Jérémy Benoist Date: Tue, 6 Jun 2017 09:44:18 +0000 (+0200) Subject: Merge pull request #3165 from wallabag/it-translation-update X-Git-Tag: 2.3.0~31^2~72 X-Git-Url: https://git.immae.eu/?a=commitdiff_plain;h=9fe87bc2e20fa95573287a61ef9798cc15648187;hp=d06a1ebdfb6f70adea935c727799798f2b8ea3f0;p=github%2Fwallabag%2Fwallabag.git Merge pull request #3165 from wallabag/it-translation-update Update Italian translation --- diff --git a/app/AppKernel.php b/app/AppKernel.php index b9293498..c50783a6 100644 --- a/app/AppKernel.php +++ b/app/AppKernel.php @@ -48,6 +48,10 @@ class AppKernel extends Kernel $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); $bundles[] = new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(); + + if ('test' === $this->getEnvironment()) { + $bundles[] = new DAMA\DoctrineTestBundle\DAMADoctrineTestBundle(); + } } return $bundles; diff --git a/app/Resources/static/themes/material/css/article.scss b/app/Resources/static/themes/material/css/article.scss index 8b67f6bd..27ff5221 100644 --- a/app/Resources/static/themes/material/css/article.scss +++ b/app/Resources/static/themes/material/css/article.scss @@ -132,6 +132,7 @@ background-color: $blueAccentColor; padding: 0 15px 0 10px; margin: auto 2px; + border-radius: 6px; a, i { diff --git a/app/Resources/static/themes/material/css/cards.scss b/app/Resources/static/themes/material/css/cards.scss index f5b79193..3edbe673 100644 --- a/app/Resources/static/themes/material/css/cards.scss +++ b/app/Resources/static/themes/material/css/cards.scss @@ -175,15 +175,66 @@ a.original:not(.waves-effect) { } .card-stacked { + display: flex; + flex-flow: row wrap; + &:hover ul.tools-list { - display: block; + display: inline; + text-align: right; + } + + .preview { + max-width: 100px; + height: auto; + margin-right: 10px; + flex: 1; + + img { + max-width: 100%; + max-height: 100%; + } + } + + div.metadata { + .chip { + background-color: $blueAccentColor; + padding: 0 15px 0 10px; + margin: auto 2px; + border-radius: 6px; + + a, + i { + color: #fff; + } + + i.material-icons { + float: right; + font-size: 20px; + line-height: 32px; + padding-left: 8px; + } + } + } + + div.card-content { + flex: 4; } ul.tools-list { + flex: 1; display: none; + flex-basis: 5em; + align-self: flex-end; + float: right; + max-width: 6em; } } +#content .collection .collection-item { + min-height: 65px; + height: auto; +} + .quickstart .card .card-action a, .quickstart .card .card-action a:hover { color: #fff !important; diff --git a/app/Resources/static/themes/material/css/entries.scss b/app/Resources/static/themes/material/css/entries.scss index b6a46a9e..c667be27 100644 --- a/app/Resources/static/themes/material/css/entries.scss +++ b/app/Resources/static/themes/material/css/entries.scss @@ -2,6 +2,15 @@ * Entries * ========================================================================== */ +.collection { + margin: 15px 15px 0; + + .collection-item { + padding: 7px; + height: 65px; + } +} + .results { height: 1em; diff --git a/app/config/config.yml b/app/config/config.yml index 9792616e..04f8547d 100644 --- a/app/config/config.yml +++ b/app/config/config.yml @@ -58,6 +58,7 @@ wallabag_core: cache_lifetime: 10 action_mark_as_read: 1 list_mode: 0 + fetching_error_message_title: 'No title found' fetching_error_message: | wallabag can't retrieve contents for this article. Please troubleshoot this issue. api_limit_mass_actions: 10 diff --git a/app/config/config_test.yml b/app/config/config_test.yml index f5e2c25e..c620c359 100644 --- a/app/config/config_test.yml +++ b/app/config/config_test.yml @@ -29,7 +29,8 @@ doctrine: user: "%test_database_user%" password: "%test_database_password%" charset: "%test_database_charset%" - path: "%test_database_path%" + path: "%env(TEST_DATABASE_PATH)%" + orm: metadata_cache_driver: type: service diff --git a/app/config/parameters.yml.dist b/app/config/parameters.yml.dist index 97f51ed1..afcee039 100644 --- a/app/config/parameters.yml.dist +++ b/app/config/parameters.yml.dist @@ -10,17 +10,18 @@ parameters: # database_user: %env.database_user% # database_password: %env.database_password% - database_driver: pdo_sqlite + database_driver: pdo_mysql database_host: 127.0.0.1 database_port: ~ - database_name: symfony + database_name: wallabag database_user: root database_password: ~ - database_path: "%kernel.root_dir%/../data/db/wallabag.sqlite" + # For SQLite, database_path should be "%kernel.root_dir%/../data/db/wallabag.sqlite" + database_path: null database_table_prefix: wallabag_ database_socket: null - # with MySQL, use "utf8mb4" if you got problem with content with emojis - database_charset: utf8 + # with PostgreSQL and SQLite, you must set "utf8" + database_charset: utf8mb4 mailer_transport: smtp mailer_host: 127.0.0.1 diff --git a/app/config/parameters_test.yml b/app/config/parameters_test.yml index 5f2e25bb..010785e6 100644 --- a/app/config/parameters_test.yml +++ b/app/config/parameters_test.yml @@ -5,5 +5,6 @@ parameters: test_database_name: null test_database_user: null test_database_password: null - test_database_path: '%kernel.root_dir%/../data/db/wallabag_test.sqlite' + test_database_path: "%env(TEST_DATABASE_PATH)%" + env(TEST_DATABASE_PATH): "%kernel.root_dir%/../data/db/wallabag_test.sqlite" test_database_charset: utf8 diff --git a/app/config/tests/parameters_test.mysql.yml b/app/config/tests/parameters_test.mysql.yml index bca2d466..36b227fb 100644 --- a/app/config/tests/parameters_test.mysql.yml +++ b/app/config/tests/parameters_test.mysql.yml @@ -6,4 +6,5 @@ parameters: test_database_user: root test_database_password: ~ test_database_path: ~ + env(TEST_DATABASE_PATH): ~ test_database_charset: utf8mb4 diff --git a/app/config/tests/parameters_test.pgsql.yml b/app/config/tests/parameters_test.pgsql.yml index 3e18d4a0..60f51df6 100644 --- a/app/config/tests/parameters_test.pgsql.yml +++ b/app/config/tests/parameters_test.pgsql.yml @@ -6,4 +6,5 @@ parameters: test_database_user: travis test_database_password: ~ test_database_path: ~ + env(TEST_DATABASE_PATH): ~ test_database_charset: utf8 diff --git a/app/config/tests/parameters_test.sqlite.yml b/app/config/tests/parameters_test.sqlite.yml index b8a5f41a..5c731bf5 100644 --- a/app/config/tests/parameters_test.sqlite.yml +++ b/app/config/tests/parameters_test.sqlite.yml @@ -5,5 +5,8 @@ parameters: test_database_name: ~ test_database_user: ~ test_database_password: ~ - test_database_path: "%kernel.root_dir%/../data/db/wallabag_test.sqlite" + # Using an environnement variable in order to avoid the error "attempt to write a readonly database" + # when the schema is dropped then recreate + test_database_path: "%env(TEST_DATABASE_PATH)%" + env(TEST_DATABASE_PATH): "%kernel.root_dir%/../data/db/wallabag_test.sqlite" test_database_charset: utf8 diff --git a/composer.json b/composer.json index d8c58de2..0a170c16 100644 --- a/composer.json +++ b/composer.json @@ -61,10 +61,9 @@ "wallabag/tcpdf": "^6.2", "simplepie/simplepie": "~1.3.1", "willdurand/hateoas-bundle": "~1.0", - "htmlawed/htmlawed": "~1.1.19", "liip/theme-bundle": "~1.1", "lexik/form-filter-bundle": "~5.0", - "j0k3r/graby": "~1.0", + "j0k3r/graby": "^1.0", "friendsofsymfony/user-bundle": "^2.0", "friendsofsymfony/oauth-server-bundle": "^1.5", "stof/doctrine-extensions-bundle": "^1.2", @@ -90,9 +89,10 @@ "doctrine/doctrine-fixtures-bundle": "~2.2", "doctrine/data-fixtures": "~1.1.1", "sensio/generator-bundle": "^3.0", - "symfony/phpunit-bridge": "^3.0", + "symfony/phpunit-bridge": "^3.3", "friendsofphp/php-cs-fixer": "~1.9", - "m6web/redis-mock": "^2.0" + "m6web/redis-mock": "^2.0", + "dama/doctrine-test-bundle": "^1.0" }, "scripts": { "post-cmd": [ diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 3216b6ff..8f5285e6 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -30,4 +30,8 @@ + + + + diff --git a/src/Wallabag/ApiBundle/Controller/EntryRestController.php b/src/Wallabag/ApiBundle/Controller/EntryRestController.php index 31bb67fd..93c8157e 100644 --- a/src/Wallabag/ApiBundle/Controller/EntryRestController.php +++ b/src/Wallabag/ApiBundle/Controller/EntryRestController.php @@ -231,7 +231,6 @@ class EntryRestController extends WallabagRestController $this->validateAuthentication(); $urls = json_decode($request->query->get('urls', [])); - $results = []; $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions'); @@ -239,32 +238,34 @@ class EntryRestController extends WallabagRestController throw new HttpException(400, 'API limit reached'); } + $results = []; + if (empty($urls)) { + return $this->sendResponse($results); + } + // handle multiple urls - if (!empty($urls)) { - foreach ($urls as $key => $url) { - $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( - $url, - $this->getUser()->getId() - ); - - $results[$key]['url'] = $url; - - if (false === $entry) { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry( - new Entry($this->getUser()), - $url - ); - } + foreach ($urls as $key => $url) { + $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId( + $url, + $this->getUser()->getId() + ); - $em = $this->getDoctrine()->getManager(); - $em->persist($entry); - $em->flush(); + $results[$key]['url'] = $url; - $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + if (false === $entry) { + $entry = new Entry($this->getUser()); - // entry saved, dispatch event about it! - $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url); } + + $em = $this->getDoctrine()->getManager(); + $em->persist($entry); + $em->flush(); + + $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false; + + // entry saved, dispatch event about it! + $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry)); } return $this->sendResponse($results); @@ -273,6 +274,9 @@ class EntryRestController extends WallabagRestController /** * Create an entry. * + * If you want to provide the HTML content (which means wallabag won't fetch it from the url), you must provide `content`, `title` & `url` fields **non-empty**. + * Otherwise, content will be fetched as normal from the url and values will be overwritten. + * * @ApiDoc( * parameters={ * {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."}, @@ -280,6 +284,11 @@ class EntryRestController extends WallabagRestController * {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."}, * {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"}, * {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"}, + * {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"}, + * {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"}, + * {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"}, + * {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"}, + * {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"}, * } * ) * @@ -291,32 +300,46 @@ class EntryRestController extends WallabagRestController $url = $request->request->get('url'); $title = $request->request->get('title'); + $tags = $request->request->get('tags', []); $isArchived = $request->request->get('archive'); $isStarred = $request->request->get('starred'); + $content = $request->request->get('content'); + $language = $request->request->get('language'); + $picture = $request->request->get('preview_picture'); + $publishedAt = $request->request->get('published_at'); + $authors = $request->request->get('authors', ''); $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId($url, $this->getUser()->getId()); if (false === $entry) { $entry = new Entry($this->getUser()); - try { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry( - $entry, - $url - ); - } catch (\Exception $e) { - $this->get('logger')->error('Error while saving an entry', [ - 'exception' => $e, - 'entry' => $entry, - ]); - $entry->setUrl($url); - } } - if (!is_null($title)) { - $entry->setTitle($title); + try { + $this->get('wallabag_core.content_proxy')->updateEntry( + $entry, + $url, + [ + 'title' => $title, + 'html' => $content, + 'url' => $url, + 'language' => $language, + 'date' => $publishedAt, + // faking the preview picture + 'open_graph' => [ + 'og_image' => $picture, + ], + 'authors' => explode(',', $authors), + ] + ); + } catch (\Exception $e) { + $this->get('logger')->error('Error while saving an entry', [ + 'exception' => $e, + 'entry' => $entry, + ]); + $entry->setUrl($url); } - $tags = $request->request->get('tags', ''); if (!empty($tags)) { $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags); } @@ -406,7 +429,7 @@ class EntryRestController extends WallabagRestController $this->validateUserAccess($entry->getUser()->getId()); try { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); } catch (\Exception $e) { $this->get('logger')->error('Error while saving an entry', [ 'exception' => $e, diff --git a/src/Wallabag/ApiBundle/Controller/UserRestController.php b/src/Wallabag/ApiBundle/Controller/UserRestController.php new file mode 100644 index 00000000..a1b78e3f --- /dev/null +++ b/src/Wallabag/ApiBundle/Controller/UserRestController.php @@ -0,0 +1,139 @@ +validateAuthentication(); + + return $this->sendUser($this->getUser()); + } + + /** + * Register an user. + * + * @ApiDoc( + * requirements={ + * {"name"="username", "dataType"="string", "required"=true, "description"="The user's username"}, + * {"name"="password", "dataType"="string", "required"=true, "description"="The user's password"}, + * {"name"="email", "dataType"="string", "required"=true, "description"="The user's email"} + * } + * ) + * + * @todo Make this method (or the whole API) accessible only through https + * + * @return JsonResponse + */ + public function putUserAction(Request $request) + { + if (!$this->container->getParameter('fosuser_registration')) { + $json = $this->get('serializer')->serialize(['error' => "Server doesn't allow registrations"], 'json'); + + return (new JsonResponse())->setJson($json)->setStatusCode(403); + } + + $userManager = $this->get('fos_user.user_manager'); + $user = $userManager->createUser(); + // enable created user by default + $user->setEnabled(true); + + $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user, [ + 'csrf_protection' => false, + ]); + + // simulate form submission + $form->submit([ + 'username' => $request->request->get('username'), + 'plainPassword' => [ + 'first' => $request->request->get('password'), + 'second' => $request->request->get('password'), + ], + 'email' => $request->request->get('email'), + ]); + + if ($form->isSubmitted() && false === $form->isValid()) { + $view = $this->view($form, 400); + $view->setFormat('json'); + + // handle errors in a more beautiful way than the default view + $data = json_decode($this->handleView($view)->getContent(), true)['children']; + $errors = []; + + if (isset($data['username']['errors'])) { + $errors['username'] = $this->translateErrors($data['username']['errors']); + } + + if (isset($data['email']['errors'])) { + $errors['email'] = $this->translateErrors($data['email']['errors']); + } + + if (isset($data['plainPassword']['children']['first']['errors'])) { + $errors['password'] = $this->translateErrors($data['plainPassword']['children']['first']['errors']); + } + + $json = $this->get('serializer')->serialize(['error' => $errors], 'json'); + + return (new JsonResponse())->setJson($json)->setStatusCode(400); + } + + $userManager->updateUser($user); + + // dispatch a created event so the associated config will be created + $event = new UserEvent($user, $request); + $this->get('event_dispatcher')->dispatch(FOSUserEvents::USER_CREATED, $event); + + return $this->sendUser($user); + } + + /** + * Send user response. + * + * @param User $user + * + * @return JsonResponse + */ + private function sendUser(User $user) + { + $json = $this->get('serializer')->serialize( + $user, + 'json', + SerializationContext::create()->setGroups(['user_api']) + ); + + return (new JsonResponse())->setJson($json); + } + + /** + * Translate errors message. + * + * @param array $errors + * + * @return array + */ + private function translateErrors($errors) + { + $translatedErrors = []; + foreach ($errors as $error) { + $translatedErrors[] = $this->get('translator')->trans($error); + } + + return $translatedErrors; + } +} diff --git a/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml b/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml index 57d37f4b..c0283e71 100644 --- a/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml +++ b/src/Wallabag/ApiBundle/Resources/config/routing_rest.yml @@ -17,3 +17,8 @@ misc: type: rest resource: "WallabagApiBundle:WallabagRest" name_prefix: api_ + +user: + type: rest + resource: "WallabagApiBundle:UserRest" + name_prefix: api_ diff --git a/src/Wallabag/CoreBundle/Command/InstallCommand.php b/src/Wallabag/CoreBundle/Command/InstallCommand.php index 0d9364f6..d9608246 100644 --- a/src/Wallabag/CoreBundle/Command/InstallCommand.php +++ b/src/Wallabag/CoreBundle/Command/InstallCommand.php @@ -499,20 +499,18 @@ class InstallCommand extends ContainerAwareCommand $output = new BufferedOutput(); $exitCode = $this->getApplication()->run(new ArrayInput($parameters), $output); + // PDO does not always close the connection after Doctrine commands. + // See https://github.com/symfony/symfony/issues/11750. + $this->getContainer()->get('doctrine')->getManager()->getConnection()->close(); + if (0 !== $exitCode) { $this->getApplication()->setAutoExit(true); - $this->defaultOutput->writeln(''); - $this->defaultOutput->writeln('The command "'.$command.'" generates some errors: '); - $this->defaultOutput->writeln($output->fetch()); - - die(); + throw new \RuntimeException( + 'The command "'.$command."\" generates some errors: \n\n" + .$output->fetch()); } - // PDO does not always close the connection after Doctrine commands. - // See https://github.com/symfony/symfony/issues/11750. - $this->getContainer()->get('doctrine')->getManager()->getConnection()->close(); - return $this; } diff --git a/src/Wallabag/CoreBundle/Controller/ConfigController.php b/src/Wallabag/CoreBundle/Controller/ConfigController.php index 1a80cc1a..0e61c642 100644 --- a/src/Wallabag/CoreBundle/Controller/ConfigController.php +++ b/src/Wallabag/CoreBundle/Controller/ConfigController.php @@ -250,7 +250,7 @@ class ConfigController extends Controller case 'entries': // SQLite doesn't care about cascading remove, so we need to manually remove associated stuff // otherwise they won't be removed ... - if ($this->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) { + if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { $this->getDoctrine()->getRepository('WallabagAnnotationBundle:Annotation')->removeAllByUserId($this->getUser()->getId()); } @@ -262,7 +262,7 @@ class ConfigController extends Controller ->removeAllByUserId($this->getUser()->getId()); break; case 'archived': - if ($this->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) { + if ($this->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { $this->removeAnnotationsForArchivedByUserId($this->getUser()->getId()); } diff --git a/src/Wallabag/CoreBundle/Controller/EntryController.php b/src/Wallabag/CoreBundle/Controller/EntryController.php index 8d2ac6d4..fafa49f1 100644 --- a/src/Wallabag/CoreBundle/Controller/EntryController.php +++ b/src/Wallabag/CoreBundle/Controller/EntryController.php @@ -53,22 +53,17 @@ class EntryController extends Controller /** * Fetch content and update entry. - * In case it fails, entry will return to avod loosing the data. + * In case it fails, $entry->getContent will return an error message. * * @param Entry $entry * @param string $prefixMessage Should be the translation key: entry_saved or entry_reloaded - * - * @return Entry */ private function updateEntry(Entry $entry, $prefixMessage = 'entry_saved') { - // put default title in case of fetching content failed - $entry->setTitle('No title found'); - $message = 'flashes.entry.notice.'.$prefixMessage; try { - $entry = $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); + $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl()); } catch (\Exception $e) { $this->get('logger')->error('Error while saving an entry', [ 'exception' => $e, @@ -79,8 +74,6 @@ class EntryController extends Controller } $this->get('session')->getFlashBag()->add('notice', $message); - - return $entry; } /** @@ -321,8 +314,7 @@ class EntryController extends Controller $pagerAdapter = new DoctrineORMAdapter($qb->getQuery(), true, false); - $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries') - ->prepare($pagerAdapter, $page); + $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); try { $entries->setCurrentPage($page); diff --git a/src/Wallabag/CoreBundle/Controller/TagController.php b/src/Wallabag/CoreBundle/Controller/TagController.php index fb6a720b..9422bae4 100644 --- a/src/Wallabag/CoreBundle/Controller/TagController.php +++ b/src/Wallabag/CoreBundle/Controller/TagController.php @@ -70,7 +70,7 @@ class TagController extends Controller $em->flush(); } - $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer')); + $redirectUrl = $this->get('wallabag_core.helper.redirect')->to($request->headers->get('referer'), '', true); return $this->redirect($redirectUrl); } @@ -125,8 +125,7 @@ class TagController extends Controller $pagerAdapter = new ArrayAdapter($entriesByTag); - $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries') - ->prepare($pagerAdapter, $page); + $entries = $this->get('wallabag_core.helper.prepare_pager_for_entries')->prepare($pagerAdapter); try { $entries->setCurrentPage($page); diff --git a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php index 75b37729..8b5b5744 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/Configuration.php @@ -41,6 +41,8 @@ class Configuration implements ConfigurationInterface ->end() ->scalarNode('fetching_error_message') ->end() + ->scalarNode('fetching_error_message_title') + ->end() ->scalarNode('action_mark_as_read') ->defaultValue(1) ->end() diff --git a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php index c075c19f..a2a703cb 100644 --- a/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php +++ b/src/Wallabag/CoreBundle/DependencyInjection/WallabagCoreExtension.php @@ -26,6 +26,7 @@ class WallabagCoreExtension extends Extension $container->setParameter('wallabag_core.action_mark_as_read', $config['action_mark_as_read']); $container->setParameter('wallabag_core.list_mode', $config['list_mode']); $container->setParameter('wallabag_core.fetching_error_message', $config['fetching_error_message']); + $container->setParameter('wallabag_core.fetching_error_message_title', $config['fetching_error_message_title']); $container->setParameter('wallabag_core.api_limit_mass_actions', $config['api_limit_mass_actions']); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); diff --git a/src/Wallabag/CoreBundle/Entity/Entry.php b/src/Wallabag/CoreBundle/Entity/Entry.php index 08a67c34..9a7dd4e7 100644 --- a/src/Wallabag/CoreBundle/Entity/Entry.php +++ b/src/Wallabag/CoreBundle/Entity/Entry.php @@ -550,7 +550,7 @@ class Entry } /** - * @return ArrayCollection + * @return ArrayCollection */ public function getTags() { @@ -685,7 +685,7 @@ class Entry } /** - * @return int + * @return string */ public function getHttpStatus() { @@ -693,7 +693,7 @@ class Entry } /** - * @param int $httpStatus + * @param string $httpStatus * * @return Entry */ diff --git a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php index 3b4c4cf9..5e6af8cc 100644 --- a/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php +++ b/src/Wallabag/CoreBundle/Event/Subscriber/SQLiteCascadeDeleteSubscriber.php @@ -45,9 +45,8 @@ class SQLiteCascadeDeleteSubscriber implements EventSubscriber public function preRemove(LifecycleEventArgs $args) { $entity = $args->getEntity(); - - if (!$this->doctrine->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver || - !$entity instanceof Entry) { + if (!$this->doctrine->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform + || !$entity instanceof Entry) { return; } diff --git a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php index c712bb26..1c56fa9f 100644 --- a/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php +++ b/src/Wallabag/CoreBundle/GuzzleSiteAuthenticator/GrabySiteConfigBuilder.php @@ -5,7 +5,6 @@ namespace Wallabag\CoreBundle\GuzzleSiteAuthenticator; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfig; use BD\GuzzleSiteAuthenticator\SiteConfig\SiteConfigBuilder; use Graby\SiteConfig\ConfigBuilder; -use OutOfRangeException; use Psr\Log\LoggerInterface; class GrabySiteConfigBuilder implements SiteConfigBuilder @@ -38,13 +37,7 @@ class GrabySiteConfigBuilder implements SiteConfigBuilder } /** - * Builds the SiteConfig for a host. - * - * @param string $host The "www." prefix is ignored - * - * @return SiteConfig - * - * @throws OutOfRangeException If there is no config for $host + * {@inheritdoc} */ public function buildForHost($host) { diff --git a/src/Wallabag/CoreBundle/Helper/ContentProxy.php b/src/Wallabag/CoreBundle/Helper/ContentProxy.php index 4b3e6fbb..bfaa1976 100644 --- a/src/Wallabag/CoreBundle/Helper/ContentProxy.php +++ b/src/Wallabag/CoreBundle/Helper/ContentProxy.php @@ -31,22 +31,20 @@ class ContentProxy } /** - * Fetch content using graby and hydrate given entry with results information. - * In case we couldn't find content, we'll try to use Open Graph data. + * Update entry using either fetched or provided content. * - * We can also force the content, in case of an import from the v1 for example, so the function won't - * fetch the content from the website but rather use information given with the $content parameter. - * - * @param Entry $entry Entry to update - * @param string $url Url to grab content for - * @param array $content An array with AT LEAST keys title, html, url, language & content_type to skip the fetchContent from the url - * - * @return Entry + * @param Entry $entry Entry to update + * @param string $url Url of the content + * @param array $content Array with content provided for import with AT LEAST keys title, html, url to skip the fetchContent from the url + * @param bool $disableContentUpdate Whether to skip trying to fetch content using Graby */ - public function updateEntry(Entry $entry, $url, array $content = []) + public function updateEntry(Entry $entry, $url, array $content = [], $disableContentUpdate = false) { - // do we have to fetch the content or the provided one is ok? - if (empty($content) || false === $this->validateContent($content)) { + if (!empty($content['html'])) { + $content['html'] = $this->graby->cleanupHtml($content['html'], $url); + } + + if ((empty($content) || false === $this->validateContent($content)) && false === $disableContentUpdate) { $fetchedContent = $this->graby->fetchContent($url); // when content is imported, we have information in $content @@ -56,8 +54,24 @@ class ContentProxy } } + // be sure to keep the url in case of error + // so we'll be able to refetch it in the future + $content['url'] = !empty($content['url']) ? $content['url'] : $url; + + $this->stockEntry($entry, $content); + } + + /** + * Stock entry with fetched or imported content. + * Will fall back to OpenGraph data if available. + * + * @param Entry $entry Entry to stock + * @param array $content Array with at least title, url & html + */ + private function stockEntry(Entry $entry, array $content) + { $title = $content['title']; - if (!$title && isset($content['open_graph']['og_title'])) { + if (!$title && !empty($content['open_graph']['og_title'])) { $title = $content['open_graph']['og_title']; } @@ -65,19 +79,30 @@ class ContentProxy if (false === $html) { $html = $this->fetchingErrorMessage; - if (isset($content['open_graph']['og_description'])) { + if (!empty($content['open_graph']['og_description'])) { $html .= '

But we found a short description:

'; $html .= $content['open_graph']['og_description']; } } - $entry->setUrl($content['url'] ?: $url); + $entry->setUrl($content['url']); $entry->setTitle($title); $entry->setContent($html); $entry->setHttpStatus(isset($content['status']) ? $content['status'] : ''); - if (isset($content['date']) && null !== $content['date'] && '' !== $content['date']) { - $entry->setPublishedAt(new \DateTime($content['date'])); + if (!empty($content['date'])) { + $date = $content['date']; + + // is it a timestamp? + if (filter_var($date, FILTER_VALIDATE_INT) !== false) { + $date = '@'.$content['date']; + } + + try { + $entry->setPublishedAt(new \DateTime($date)); + } catch (\Exception $e) { + $this->logger->warning('Error while defining date', ['e' => $e, 'url' => $content['url'], 'date' => $content['date']]); + } } if (!empty($content['authors'])) { @@ -97,12 +122,12 @@ class ContentProxy $entry->setDomainName($domainName); } - if (isset($content['open_graph']['og_image']) && $content['open_graph']['og_image']) { + if (!empty($content['open_graph']['og_image'])) { $entry->setPreviewPicture($content['open_graph']['og_image']); } // if content is an image define as a preview too - if (isset($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { + if (!empty($content['content_type']) && in_array($this->mimeGuesser->guess($content['content_type']), ['jpeg', 'jpg', 'gif', 'png'], true)) { $entry->setPreviewPicture($content['url']); } @@ -110,17 +135,14 @@ class ContentProxy $this->tagger->tag($entry); } catch (\Exception $e) { $this->logger->error('Error while trying to automatically tag an entry.', [ - 'entry_url' => $url, + 'entry_url' => $content['url'], 'error_msg' => $e->getMessage(), ]); } - - return $entry; } /** - * Validate that the given content as enough value to be used - * instead of fetch the content from the url. + * Validate that the given content has at least a title, an html and a url. * * @param array $content * @@ -128,6 +150,6 @@ class ContentProxy */ private function validateContent(array $content) { - return isset($content['title']) && isset($content['html']) && isset($content['url']) && isset($content['language']) && isset($content['content_type']); + return !empty($content['title']) && !empty($content['html']) && !empty($content['url']); } } diff --git a/src/Wallabag/CoreBundle/Helper/DownloadImages.php b/src/Wallabag/CoreBundle/Helper/DownloadImages.php index 0d330d2a..54e23a05 100644 --- a/src/Wallabag/CoreBundle/Helper/DownloadImages.php +++ b/src/Wallabag/CoreBundle/Helper/DownloadImages.php @@ -54,7 +54,7 @@ class DownloadImages $crawler = new Crawler($html); $result = $crawler ->filterXpath('//img') - ->extract(array('src')); + ->extract(['src']); $relativePath = $this->getRelativePath($entryId); @@ -66,6 +66,11 @@ class DownloadImages continue; } + // if image contains "&" and we can't find it in the html it might be because it's encoded as & + if (false !== stripos($image, '&') && false === stripos($html, $image)) { + $image = str_replace('&', '&', $image); + } + $html = str_replace($image, $imagePath, $html); } @@ -114,7 +119,7 @@ class DownloadImages $ext = $this->mimeGuesser->guess($res->getHeader('content-type')); $this->logger->debug('DownloadImages: Checking extension', ['ext' => $ext, 'header' => $res->getHeader('content-type')]); if (!in_array($ext, ['jpeg', 'jpg', 'gif', 'png'], true)) { - $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping '.$imagePath); + $this->logger->error('DownloadImages: Processed image with not allowed extension. Skipping: '.$imagePath); return false; } diff --git a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php index 7d3798b9..df579ebd 100644 --- a/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php +++ b/src/Wallabag/CoreBundle/Helper/PreparePagerForEntries.php @@ -20,16 +20,15 @@ class PreparePagerForEntries /** * @param AdapterInterface $adapter - * @param int $page * * @return null|Pagerfanta */ - public function prepare(AdapterInterface $adapter, $page = 1) + public function prepare(AdapterInterface $adapter) { $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null; if (null === $user || !is_object($user)) { - return null; + return; } $entries = new Pagerfanta($adapter); diff --git a/src/Wallabag/CoreBundle/Helper/Redirect.php b/src/Wallabag/CoreBundle/Helper/Redirect.php index f78b7fe0..abc84d08 100644 --- a/src/Wallabag/CoreBundle/Helper/Redirect.php +++ b/src/Wallabag/CoreBundle/Helper/Redirect.php @@ -21,12 +21,13 @@ class Redirect } /** - * @param string $url URL to redirect - * @param string $fallback Fallback URL if $url is null + * @param string $url URL to redirect + * @param string $fallback Fallback URL if $url is null + * @param bool $ignoreActionMarkAsRead Ignore configured action when mark as read * * @return string */ - public function to($url, $fallback = '') + public function to($url, $fallback = '', $ignoreActionMarkAsRead = false) { $user = $this->tokenStorage->getToken() ? $this->tokenStorage->getToken()->getUser() : null; @@ -34,7 +35,8 @@ class Redirect return $url; } - if (Config::REDIRECT_TO_HOMEPAGE === $user->getConfig()->getActionMarkAsRead()) { + if (!$ignoreActionMarkAsRead && + Config::REDIRECT_TO_HOMEPAGE === $user->getConfig()->getActionMarkAsRead()) { return $this->router->generate('homepage'); } diff --git a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php index add27db2..509d0dec 100644 --- a/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php +++ b/src/Wallabag/CoreBundle/Helper/RuleBasedTagger.php @@ -15,6 +15,7 @@ class RuleBasedTagger private $rulerz; private $tagRepository; private $entryRepository; + private $logger; public function __construct(RulerZ $rulerz, TagRepository $tagRepository, EntryRepository $entryRepository, LoggerInterface $logger) { diff --git a/src/Wallabag/CoreBundle/Resources/config/services.yml b/src/Wallabag/CoreBundle/Resources/config/services.yml index a68b2fdc..a9b0d2d5 100644 --- a/src/Wallabag/CoreBundle/Resources/config/services.yml +++ b/src/Wallabag/CoreBundle/Resources/config/services.yml @@ -41,6 +41,7 @@ services: arguments: - error_message: '%wallabag_core.fetching_error_message%' + error_message_title: '%wallabag_core.fetching_error_message_title%' - "@wallabag_core.guzzle.http_client" - "@wallabag_core.graby.config_builder" calls: diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig index 174b7b54..b64e1436 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/_card_list.html.twig @@ -1,18 +1,28 @@ -
-
-
- - - {{ entry.title| striptags | truncate(120, true, '…') | raw }} - - - + diff --git a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig index b2d91c9c..6f657b18 100644 --- a/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig +++ b/src/Wallabag/CoreBundle/Resources/views/themes/material/Entry/entries.html.twig @@ -24,9 +24,9 @@

-
    +
      {% for entry in entries %} -
    • +
    • {% if listMode == 1 %} {% include "@WallabagCore/themes/material/Entry/_card_list.html.twig" with {'entry': entry} only %} {% elseif entry.previewPicture is null %} diff --git a/src/Wallabag/ImportBundle/Command/ImportCommand.php b/src/Wallabag/ImportBundle/Command/ImportCommand.php index ce72837a..5f1ab0af 100644 --- a/src/Wallabag/ImportBundle/Command/ImportCommand.php +++ b/src/Wallabag/ImportBundle/Command/ImportCommand.php @@ -5,6 +5,7 @@ namespace Wallabag\ImportBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Config\Definition\Exception\Exception; use Symfony\Component\Console\Input\InputArgument; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -17,9 +18,10 @@ class ImportCommand extends ContainerAwareCommand ->setDescription('Import entries from a JSON export') ->addArgument('username', InputArgument::REQUIRED, 'User to populate') ->addArgument('filepath', InputArgument::REQUIRED, 'Path to the JSON file') - ->addOption('importer', null, InputArgument::OPTIONAL, 'The importer to use: v1, v2, instapaper, pinboard, readability, firefox or chrome', 'v1') - ->addOption('markAsRead', null, InputArgument::OPTIONAL, 'Mark all entries as read', false) - ->addOption('useUserId', null, InputArgument::OPTIONAL, 'Use user id instead of username to find account', false) + ->addOption('importer', null, InputOption::VALUE_OPTIONAL, 'The importer to use: v1, v2, instapaper, pinboard, readability, firefox or chrome', 'v1') + ->addOption('markAsRead', null, InputOption::VALUE_OPTIONAL, 'Mark all entries as read', false) + ->addOption('useUserId', null, InputOption::VALUE_NONE, 'Use user id instead of username to find account') + ->addOption('disableContentUpdate', null, InputOption::VALUE_NONE, 'Disable fetching updated content from URL') ; } @@ -69,6 +71,7 @@ class ImportCommand extends ContainerAwareCommand } $import->setMarkAsRead($input->getOption('markAsRead')); + $import->setDisableContentUpdate($input->getOption('disableContentUpdate')); $import->setUser($user); $res = $import diff --git a/src/Wallabag/ImportBundle/Import/AbstractImport.php b/src/Wallabag/ImportBundle/Import/AbstractImport.php index a61388c0..9b624296 100644 --- a/src/Wallabag/ImportBundle/Import/AbstractImport.php +++ b/src/Wallabag/ImportBundle/Import/AbstractImport.php @@ -24,6 +24,7 @@ abstract class AbstractImport implements ImportInterface protected $producer; protected $user; protected $markAsRead; + protected $disableContentUpdate = false; protected $skippedEntries = 0; protected $importedEntries = 0; protected $queuedEntries = 0; @@ -84,6 +85,18 @@ abstract class AbstractImport implements ImportInterface return $this->markAsRead; } + /** + * Set whether articles should be fetched for updated content. + * + * @param bool $disableContentUpdate + */ + public function setDisableContentUpdate($disableContentUpdate) + { + $this->disableContentUpdate = $disableContentUpdate; + + return $this; + } + /** * Fetch content from the ContentProxy (using graby). * If it fails return the given entry to be saved in all case (to avoid user to loose the content). @@ -91,15 +104,16 @@ abstract class AbstractImport implements ImportInterface * @param Entry $entry Entry to update * @param string $url Url to grab content for * @param array $content An array with AT LEAST keys title, html, url, language & content_type to skip the fetchContent from the url - * - * @return Entry */ protected function fetchContent(Entry $entry, $url, array $content = []) { try { - return $this->contentProxy->updateEntry($entry, $url, $content); + $this->contentProxy->updateEntry($entry, $url, $content, $this->disableContentUpdate); } catch (\Exception $e) { - return $entry; + $this->logger->error('Error trying to import an entry.', [ + 'entry_url' => $url, + 'error_msg' => $e->getMessage(), + ]); } } diff --git a/src/Wallabag/ImportBundle/Import/BrowserImport.php b/src/Wallabag/ImportBundle/Import/BrowserImport.php index ef0eeb7e..71e65e59 100644 --- a/src/Wallabag/ImportBundle/Import/BrowserImport.php +++ b/src/Wallabag/ImportBundle/Import/BrowserImport.php @@ -201,7 +201,7 @@ abstract class BrowserImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); if (array_key_exists('tags', $data)) { $this->tagsAssigner->assignTagsToEntry( diff --git a/src/Wallabag/ImportBundle/Import/InstapaperImport.php b/src/Wallabag/ImportBundle/Import/InstapaperImport.php index 70a53f1a..3aa12f6f 100644 --- a/src/Wallabag/ImportBundle/Import/InstapaperImport.php +++ b/src/Wallabag/ImportBundle/Import/InstapaperImport.php @@ -68,6 +68,14 @@ class InstapaperImport extends AbstractImport continue; } + // last element in the csv is the folder where the content belong + // BUT it can also be the status (since status = folder in Instapaper) + // and we don't want archive, unread & starred to become a tag + $tags = null; + if (false === in_array($data[3], ['Archive', 'Unread', 'Starred'])) { + $tags = [$data[3]]; + } + $entries[] = [ 'url' => $data[0], 'title' => $data[1], @@ -75,6 +83,7 @@ class InstapaperImport extends AbstractImport 'is_archived' => $data[3] === 'Archive' || $data[3] === 'Starred', 'is_starred' => $data[3] === 'Starred', 'html' => false, + 'tags' => $tags, ]; } fclose($handle); @@ -116,7 +125,15 @@ class InstapaperImport extends AbstractImport $entry->setTitle($importedEntry['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $importedEntry['url'], $importedEntry); + $this->fetchContent($entry, $importedEntry['url'], $importedEntry); + + if (!empty($importedEntry['tags'])) { + $this->tagsAssigner->assignTagsToEntry( + $entry, + $importedEntry['tags'], + $this->em->getUnitOfWork()->getScheduledEntityInsertions() + ); + } $entry->setArchived($importedEntry['is_archived']); $entry->setStarred($importedEntry['is_starred']); diff --git a/src/Wallabag/ImportBundle/Import/PinboardImport.php b/src/Wallabag/ImportBundle/Import/PinboardImport.php index 489b9257..110b0464 100644 --- a/src/Wallabag/ImportBundle/Import/PinboardImport.php +++ b/src/Wallabag/ImportBundle/Import/PinboardImport.php @@ -109,7 +109,7 @@ class PinboardImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); if (!empty($data['tags'])) { $this->tagsAssigner->assignTagsToEntry( diff --git a/src/Wallabag/ImportBundle/Import/PocketImport.php b/src/Wallabag/ImportBundle/Import/PocketImport.php index 8835161b..c1d5b6da 100644 --- a/src/Wallabag/ImportBundle/Import/PocketImport.php +++ b/src/Wallabag/ImportBundle/Import/PocketImport.php @@ -192,7 +192,7 @@ class PocketImport extends AbstractImport $entry->setUrl($url); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $url); + $this->fetchContent($entry, $url); // 0, 1, 2 - 1 if the item is archived - 2 if the item should be deleted $entry->setArchived($importedEntry['status'] == 1 || $this->markAsRead); diff --git a/src/Wallabag/ImportBundle/Import/ReadabilityImport.php b/src/Wallabag/ImportBundle/Import/ReadabilityImport.php index de320d23..002b27f4 100644 --- a/src/Wallabag/ImportBundle/Import/ReadabilityImport.php +++ b/src/Wallabag/ImportBundle/Import/ReadabilityImport.php @@ -109,7 +109,7 @@ class ReadabilityImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); $entry->setArchived($data['is_archived']); $entry->setStarred($data['is_starred']); diff --git a/src/Wallabag/ImportBundle/Import/WallabagImport.php b/src/Wallabag/ImportBundle/Import/WallabagImport.php index 0e5382cf..c64ccd64 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagImport.php +++ b/src/Wallabag/ImportBundle/Import/WallabagImport.php @@ -108,7 +108,7 @@ abstract class WallabagImport extends AbstractImport $entry->setTitle($data['title']); // update entry with content (in case fetching failed, the given entry will be return) - $entry = $this->fetchContent($entry, $data['url'], $data); + $this->fetchContent($entry, $data['url'], $data); if (array_key_exists('tags', $data)) { $this->tagsAssigner->assignTagsToEntry( diff --git a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php index 59e3ce02..1f0df646 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagV1Import.php +++ b/src/Wallabag/ImportBundle/Import/WallabagV1Import.php @@ -4,6 +4,17 @@ namespace Wallabag\ImportBundle\Import; class WallabagV1Import extends WallabagImport { + protected $fetchingErrorMessage; + protected $fetchingErrorMessageTitle; + + public function __construct($em, $contentProxy, $tagsAssigner, $eventDispatcher, $fetchingErrorMessageTitle, $fetchingErrorMessage) + { + $this->fetchingErrorMessageTitle = $fetchingErrorMessageTitle; + $this->fetchingErrorMessage = $fetchingErrorMessage; + + parent::__construct($em, $contentProxy, $tagsAssigner, $eventDispatcher); + } + /** * {@inheritdoc} */ @@ -43,10 +54,11 @@ class WallabagV1Import extends WallabagImport 'created_at' => '', ]; - // force content to be refreshed in case on bad fetch in the v1 installation + // In case of a bad fetch in v1, replace title and content with v2 error strings + // If fetching fails again, they will get this instead of the v1 strings if (in_array($entry['title'], $this->untitled)) { - $data['title'] = ''; - $data['html'] = ''; + $data['title'] = $this->fetchingErrorMessageTitle; + $data['html'] = $this->fetchingErrorMessage; } if (array_key_exists('tags', $entry) && $entry['tags'] != '') { diff --git a/src/Wallabag/ImportBundle/Import/WallabagV2Import.php b/src/Wallabag/ImportBundle/Import/WallabagV2Import.php index d2a89d79..3e085ecf 100644 --- a/src/Wallabag/ImportBundle/Import/WallabagV2Import.php +++ b/src/Wallabag/ImportBundle/Import/WallabagV2Import.php @@ -36,8 +36,8 @@ class WallabagV2Import extends WallabagImport return [ 'html' => $entry['content'], 'content_type' => $entry['mimetype'], - 'is_archived' => (int) ($entry['is_archived'] || $this->markAsRead), - 'is_starred' => false, + 'is_archived' => (bool) ($entry['is_archived'] || $this->markAsRead), + 'is_starred' => (bool) $entry['is_starred'], ] + $entry; } diff --git a/src/Wallabag/ImportBundle/Resources/config/services.yml b/src/Wallabag/ImportBundle/Resources/config/services.yml index 661dc7e1..b224a6a2 100644 --- a/src/Wallabag/ImportBundle/Resources/config/services.yml +++ b/src/Wallabag/ImportBundle/Resources/config/services.yml @@ -35,6 +35,8 @@ services: - "@wallabag_core.content_proxy" - "@wallabag_core.tags_assigner" - "@event_dispatcher" + - "%wallabag_core.fetching_error_message_title%" + - "%wallabag_core.fetching_error_message%" calls: - [ setLogger, [ "@logger" ]] tags: diff --git a/src/Wallabag/UserBundle/Controller/ManageController.php b/src/Wallabag/UserBundle/Controller/ManageController.php index 1c5c86d4..084f2c67 100644 --- a/src/Wallabag/UserBundle/Controller/ManageController.php +++ b/src/Wallabag/UserBundle/Controller/ManageController.php @@ -33,9 +33,7 @@ class ManageController extends Controller // enable created user by default $user->setEnabled(true); - $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user, [ - 'validation_groups' => ['Profile'], - ]); + $form = $this->createForm('Wallabag\UserBundle\Form\NewUserType', $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { diff --git a/src/Wallabag/UserBundle/Entity/User.php b/src/Wallabag/UserBundle/Entity/User.php index 3a167de7..ed6ce331 100644 --- a/src/Wallabag/UserBundle/Entity/User.php +++ b/src/Wallabag/UserBundle/Entity/User.php @@ -4,11 +4,11 @@ namespace Wallabag\UserBundle\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; +use JMS\Serializer\Annotation\Groups; +use JMS\Serializer\Annotation\XmlRoot; use Scheb\TwoFactorBundle\Model\Email\TwoFactorInterface; use Scheb\TwoFactorBundle\Model\TrustedComputerInterface; use FOS\UserBundle\Model\User as BaseUser; -use JMS\Serializer\Annotation\ExclusionPolicy; -use JMS\Serializer\Annotation\Expose; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Security\Core\User\UserInterface; use Wallabag\ApiBundle\Entity\Client; @@ -18,23 +18,25 @@ use Wallabag\CoreBundle\Entity\Entry; /** * User. * + * @XmlRoot("user") * @ORM\Entity(repositoryClass="Wallabag\UserBundle\Repository\UserRepository") * @ORM\Table(name="`user`") * @ORM\HasLifecycleCallbacks() - * @ExclusionPolicy("all") * * @UniqueEntity("email") * @UniqueEntity("username") */ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterface { + /** @Serializer\XmlAttribute */ /** * @var int * - * @Expose * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") + * + * @Groups({"user_api"}) */ protected $id; @@ -42,20 +44,40 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf * @var string * * @ORM\Column(name="name", type="text", nullable=true) + * + * @Groups({"user_api"}) */ protected $name; /** - * @var date + * @var string + * + * @Groups({"user_api"}) + */ + protected $username; + + /** + * @var string + * + * @Groups({"user_api"}) + */ + protected $email; + + /** + * @var \DateTime * * @ORM\Column(name="created_at", type="datetime") + * + * @Groups({"user_api"}) */ protected $createdAt; /** - * @var date + * @var \DateTime * * @ORM\Column(name="updated_at", type="datetime") + * + * @Groups({"user_api"}) */ protected $updatedAt; @@ -135,7 +157,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf } /** - * @return string + * @return \DateTime */ public function getCreatedAt() { @@ -143,7 +165,7 @@ class User extends BaseUser implements TwoFactorInterface, TrustedComputerInterf } /** - * @return string + * @return \DateTime */ public function getUpdatedAt() { diff --git a/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php b/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php index 0bdd1cae..e4d55c19 100644 --- a/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php +++ b/src/Wallabag/UserBundle/EventListener/CreateConfigListener.php @@ -5,7 +5,6 @@ namespace Wallabag\UserBundle\EventListener; use Doctrine\ORM\EntityManager; use FOS\UserBundle\Event\UserEvent; use FOS\UserBundle\FOSUserEvents; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Wallabag\CoreBundle\Entity\Config; @@ -47,7 +46,7 @@ class CreateConfigListener implements EventSubscriberInterface ]; } - public function createConfig(UserEvent $event, $eventName = null, EventDispatcherInterface $eventDispatcher = null) + public function createConfig(UserEvent $event) { $config = new Config($event->getUser()); $config->setTheme($this->theme); diff --git a/tests/Wallabag/ApiBundle/Controller/DeveloperControllerTest.php b/tests/Wallabag/ApiBundle/Controller/DeveloperControllerTest.php index 6659443b..d37cbbf9 100644 --- a/tests/Wallabag/ApiBundle/Controller/DeveloperControllerTest.php +++ b/tests/Wallabag/ApiBundle/Controller/DeveloperControllerTest.php @@ -3,6 +3,7 @@ namespace Tests\Wallabag\ApiBundle\Controller; use Tests\Wallabag\CoreBundle\WallabagCoreTestCase; +use Wallabag\ApiBundle\Entity\Client; class DeveloperControllerTest extends WallabagCoreTestCase { @@ -33,14 +34,10 @@ class DeveloperControllerTest extends WallabagCoreTestCase $this->assertContains('My app', $alert[0]); } - /** - * @depends testCreateClient - */ public function testCreateToken() { $client = $this->getClient(); - $em = $client->getContainer()->get('doctrine.orm.entity_manager'); - $apiClient = $em->getRepository('WallabagApiBundle:Client')->findOneByName('My app'); + $apiClient = $this->createApiClientForUser('admin'); $client->request('POST', '/oauth/v2/token', [ 'grant_type' => 'password', @@ -83,6 +80,7 @@ class DeveloperControllerTest extends WallabagCoreTestCase public function testRemoveClient() { $client = $this->getClient(); + $adminApiClient = $this->createApiClientForUser('admin'); $em = $client->getContainer()->get('doctrine.orm.entity_manager'); // Try to remove an admin's client with a wrong user @@ -90,12 +88,8 @@ class DeveloperControllerTest extends WallabagCoreTestCase $client->request('GET', '/developer'); $this->assertContains('no_client', $client->getResponse()->getContent()); - // get an ID of a admin's client - $this->logInAs('admin'); - $nbClients = $em->getRepository('WallabagApiBundle:Client')->findByUser($this->getLoggedInUserId()); - $this->logInAs('bob'); - $client->request('GET', '/developer/client/delete/'.$nbClients[0]->getId()); + $client->request('GET', '/developer/client/delete/'.$adminApiClient->getId()); $this->assertEquals(403, $client->getResponse()->getStatusCode()); // Try to remove the admin's client with the good user @@ -111,7 +105,29 @@ class DeveloperControllerTest extends WallabagCoreTestCase $client->click($link); $this->assertEquals(302, $client->getResponse()->getStatusCode()); - $newNbClients = $em->getRepository('WallabagApiBundle:Client')->findByUser($this->getLoggedInUserId()); - $this->assertGreaterThan(count($newNbClients), count($nbClients)); + $this->assertNull( + $em->getRepository('WallabagApiBundle:Client')->find($adminApiClient->getId()), + 'The client should have been removed' + ); + } + + /** + * @param string $username + * + * @return Client + */ + private function createApiClientForUser($username) + { + $client = $this->getClient(); + $em = $client->getContainer()->get('doctrine.orm.entity_manager'); + $userManager = $client->getContainer()->get('fos_user.user_manager'); + $user = $userManager->findUserBy(array('username' => $username)); + $apiClient = new Client($user); + $apiClient->setName('My app'); + $apiClient->setAllowedGrantTypes(['password']); + $em->persist($apiClient); + $em->flush(); + + return $apiClient; } } diff --git a/tests/Wallabag/ApiBundle/Controller/EntryRestControllerTest.php b/tests/Wallabag/ApiBundle/Controller/EntryRestControllerTest.php index bf7d373a..0968cfaf 100644 --- a/tests/Wallabag/ApiBundle/Controller/EntryRestControllerTest.php +++ b/tests/Wallabag/ApiBundle/Controller/EntryRestControllerTest.php @@ -3,8 +3,10 @@ namespace Tests\Wallabag\ApiBundle\Controller; use Tests\Wallabag\ApiBundle\WallabagApiTestCase; +use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\CoreBundle\Helper\ContentProxy; +use Wallabag\UserBundle\Entity\User; class EntryRestControllerTest extends WallabagApiTestCase { @@ -342,6 +344,10 @@ class EntryRestControllerTest extends WallabagApiTestCase 'url' => 'http://www.lemonde.fr/pixels/article/2015/03/28/plongee-dans-l-univers-d-ingress-le-jeu-de-google-aux-frontieres-du-reel_4601155_4408996.html', 'tags' => 'google', 'title' => 'New title for my article', + 'content' => 'my content', + 'language' => 'de_DE', + 'published_at' => '2016-09-08T11:55:58+0200', + 'authors' => 'bob,helen', ]); $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); @@ -355,6 +361,12 @@ class EntryRestControllerTest extends WallabagApiTestCase $this->assertEquals('New title for my article', $content['title']); $this->assertEquals(1, $content['user_id']); $this->assertCount(2, $content['tags']); + $this->assertSame('my content', $content['content']); + $this->assertSame('de_DE', $content['language']); + $this->assertSame('2016-09-08T11:55:58+0200', $content['published_at']); + $this->assertCount(2, $content['published_by']); + $this->assertContains('bob', $content['published_by']); + $this->assertContains('helen', $content['published_by']); } public function testPostSameEntry() @@ -801,22 +813,28 @@ class EntryRestControllerTest extends WallabagApiTestCase public function testDeleteEntriesTagsListAction() { - $entry = $this->client->getContainer()->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId('http://0.0.0.0/entry4', 1); + $em = $this->client->getContainer()->get('doctrine.orm.entity_manager'); + $entry = new Entry($em->getReference(User::class, 1)); + $entry->setUrl('http://0.0.0.0/test-entry'); + $entry->addTag((new Tag())->setLabel('foo-tag')); + $entry->addTag((new Tag())->setLabel('bar-tag')); + $em->persist($entry); + $em->flush(); - $tags = $entry->getTags(); - - $this->assertCount(4, $tags); + $em->clear(); $list = [ [ - 'url' => 'http://0.0.0.0/entry4', - 'tags' => 'new tag 1, new tag 2', + 'url' => 'http://0.0.0.0/test-entry', + 'tags' => 'foo-tag, bar-tag', ], ]; $this->client->request('DELETE', '/api/entries/tags/list?list='.json_encode($list)); + $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); + + $entry = $em->getRepository('WallabagCoreBundle:Entry')->find($entry->getId()); + $this->assertCount(0, $entry->getTags()); } public function testPostEntriesListAction() @@ -841,9 +859,14 @@ class EntryRestControllerTest extends WallabagApiTestCase public function testDeleteEntriesListAction() { + $em = $this->client->getContainer()->get('doctrine.orm.entity_manager'); + $em->persist((new Entry($em->getReference(User::class, 1)))->setUrl('http://0.0.0.0/test-entry1')); + + $em->flush(); + $em->clear(); $list = [ - 'http://www.lemonde.fr/musiques/article/2017/04/23/loin-de-la-politique-le-printemps-de-bourges-retombe-en-enfance_5115862_1654986.html', - 'http://0.0.0.0/entry3', + 'http://0.0.0.0/test-entry1', + 'http://0.0.0.0/test-entry-not-exist', ]; $this->client->request('DELETE', '/api/entries/list?urls='.json_encode($list)); @@ -853,10 +876,10 @@ class EntryRestControllerTest extends WallabagApiTestCase $content = json_decode($this->client->getResponse()->getContent(), true); $this->assertTrue($content[0]['entry']); - $this->assertEquals('http://www.lemonde.fr/musiques/article/2017/04/23/loin-de-la-politique-le-printemps-de-bourges-retombe-en-enfance_5115862_1654986.html', $content[0]['url']); + $this->assertEquals('http://0.0.0.0/test-entry1', $content[0]['url']); $this->assertFalse($content[1]['entry']); - $this->assertEquals('http://0.0.0.0/entry3', $content[1]['url']); + $this->assertEquals('http://0.0.0.0/test-entry-not-exist', $content[1]['url']); } public function testLimitBulkAction() diff --git a/tests/Wallabag/ApiBundle/Controller/TagRestControllerTest.php b/tests/Wallabag/ApiBundle/Controller/TagRestControllerTest.php index 90b132eb..7f69bd67 100644 --- a/tests/Wallabag/ApiBundle/Controller/TagRestControllerTest.php +++ b/tests/Wallabag/ApiBundle/Controller/TagRestControllerTest.php @@ -22,36 +22,35 @@ class TagRestControllerTest extends WallabagApiTestCase return end($content); } - /** - * @depends testGetUserTags - */ - public function testDeleteUserTag($tag) + public function testDeleteUserTag() { - $tagName = $tag['label']; + $tagLabel = 'tagtest'; + $tag = new Tag(); + $tag->setLabel($tagLabel); + + $em = $this->client->getContainer()->get('doctrine.orm.entity_manager'); + $em->persist($tag); + $em->flush(); + $em->clear(); - $this->client->request('DELETE', '/api/tags/'.$tag['id'].'.json'); + $this->client->request('DELETE', '/api/tags/'.$tag->getId().'.json'); $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); $content = json_decode($this->client->getResponse()->getContent(), true); $this->assertArrayHasKey('label', $content); - $this->assertEquals($tag['label'], $content['label']); - $this->assertEquals($tag['slug'], $content['slug']); + $this->assertEquals($tag->getLabel(), $content['label']); + $this->assertEquals($tag->getSlug(), $content['slug']); - $entries = $this->client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findAllByTagId($this->user->getId(), $tag['id']); + $entries = $em->getRepository('WallabagCoreBundle:Entry') + ->findAllByTagId($this->user->getId(), $tag->getId()); $this->assertCount(0, $entries); - $tag = $this->client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Tag') - ->findOneByLabel($tagName); + $tag = $em->getRepository('WallabagCoreBundle:Tag')->findOneByLabel($tagLabel); - $this->assertNull($tag, $tagName.' was removed because it begun an orphan tag'); + $this->assertNull($tag, $tagLabel.' was removed because it begun an orphan tag'); } public function dataForDeletingTagByLabel() diff --git a/tests/Wallabag/ApiBundle/Controller/UserRestControllerTest.php b/tests/Wallabag/ApiBundle/Controller/UserRestControllerTest.php new file mode 100644 index 00000000..3f4969a5 --- /dev/null +++ b/tests/Wallabag/ApiBundle/Controller/UserRestControllerTest.php @@ -0,0 +1,110 @@ +client->request('GET', '/api/user.json'); + $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); + + $content = json_decode($this->client->getResponse()->getContent(), true); + + $this->assertArrayHasKey('id', $content); + $this->assertArrayHasKey('email', $content); + $this->assertArrayHasKey('name', $content); + $this->assertArrayHasKey('username', $content); + $this->assertArrayHasKey('created_at', $content); + $this->assertArrayHasKey('updated_at', $content); + + $this->assertEquals('bigboss@wallabag.org', $content['email']); + $this->assertEquals('Big boss', $content['name']); + $this->assertEquals('admin', $content['username']); + + $this->assertEquals('application/json', $this->client->getResponse()->headers->get('Content-Type')); + } + + public function testCreateNewUser() + { + $this->client->request('PUT', '/api/user.json', [ + 'username' => 'google', + 'password' => 'googlegoogle', + 'email' => 'wallabag@google.com', + ]); + + $this->assertEquals(200, $this->client->getResponse()->getStatusCode()); + + $content = json_decode($this->client->getResponse()->getContent(), true); + + $this->assertArrayHasKey('id', $content); + $this->assertArrayHasKey('email', $content); + $this->assertArrayHasKey('username', $content); + $this->assertArrayHasKey('created_at', $content); + $this->assertArrayHasKey('updated_at', $content); + + $this->assertEquals('wallabag@google.com', $content['email']); + $this->assertEquals('google', $content['username']); + + $this->assertEquals('application/json', $this->client->getResponse()->headers->get('Content-Type')); + + // remove the created user to avoid side effect on other tests + // @todo remove these lines when test will be isolated + $em = $this->client->getContainer()->get('doctrine.orm.entity_manager'); + + $query = $em->createQuery('DELETE FROM Wallabag\CoreBundle\Entity\Config c WHERE c.user = :user_id'); + $query->setParameter('user_id', $content['id']); + $query->execute(); + + $query = $em->createQuery('DELETE FROM Wallabag\UserBundle\Entity\User u WHERE u.id = :id'); + $query->setParameter('id', $content['id']); + $query->execute(); + } + + public function testCreateNewUserWithExistingEmail() + { + $this->client->request('PUT', '/api/user.json', [ + 'username' => 'admin', + 'password' => 'googlegoogle', + 'email' => 'bigboss@wallabag.org', + ]); + + $this->assertEquals(400, $this->client->getResponse()->getStatusCode()); + + $content = json_decode($this->client->getResponse()->getContent(), true); + + $this->assertArrayHasKey('error', $content); + $this->assertArrayHasKey('username', $content['error']); + $this->assertArrayHasKey('email', $content['error']); + + // $this->assertEquals('fos_user.username.already_used', $content['error']['username'][0]); + // $this->assertEquals('fos_user.email.already_used', $content['error']['email'][0]); + // This shouldn't be translated ... + $this->assertEquals('This value is already used.', $content['error']['username'][0]); + $this->assertEquals('This value is already used.', $content['error']['email'][0]); + + $this->assertEquals('application/json', $this->client->getResponse()->headers->get('Content-Type')); + } + + public function testCreateNewUserWithTooShortPassword() + { + $this->client->request('PUT', '/api/user.json', [ + 'username' => 'facebook', + 'password' => 'face', + 'email' => 'facebook@wallabag.org', + ]); + + $this->assertEquals(400, $this->client->getResponse()->getStatusCode()); + + $content = json_decode($this->client->getResponse()->getContent(), true); + + $this->assertArrayHasKey('error', $content); + $this->assertArrayHasKey('password', $content['error']); + + $this->assertEquals('validator.password_too_short', $content['error']['password'][0]); + + $this->assertEquals('application/json', $this->client->getResponse()->headers->get('Content-Type')); + } +} diff --git a/tests/Wallabag/ApiBundle/WallabagApiTestCase.php b/tests/Wallabag/ApiBundle/WallabagApiTestCase.php index cf9b3347..8709da70 100644 --- a/tests/Wallabag/ApiBundle/WallabagApiTestCase.php +++ b/tests/Wallabag/ApiBundle/WallabagApiTestCase.php @@ -8,7 +8,7 @@ use Symfony\Component\BrowserKit\Cookie; abstract class WallabagApiTestCase extends WebTestCase { /** - * @var Client + * @var \Symfony\Bundle\FrameworkBundle\Client */ protected $client = null; @@ -23,7 +23,7 @@ abstract class WallabagApiTestCase extends WebTestCase } /** - * @return Client + * @return \Symfony\Bundle\FrameworkBundle\Client */ protected function createAuthorizedClient() { @@ -37,7 +37,7 @@ abstract class WallabagApiTestCase extends WebTestCase $firewallName = $container->getParameter('fos_user.firewall_name'); $this->user = $userManager->findUserBy(['username' => 'admin']); - $loginManager->loginUser($firewallName, $this->user); + $loginManager->logInUser($firewallName, $this->user); // save the login token into the session and put it in a cookie $container->get('session')->set('_security_'.$firewallName, serialize($container->get('security.token_storage')->getToken())); diff --git a/tests/Wallabag/CoreBundle/Command/ExportCommandTest.php b/tests/Wallabag/CoreBundle/Command/ExportCommandTest.php index b21f3318..2eebf39b 100644 --- a/tests/Wallabag/CoreBundle/Command/ExportCommandTest.php +++ b/tests/Wallabag/CoreBundle/Command/ExportCommandTest.php @@ -10,7 +10,7 @@ use Tests\Wallabag\CoreBundle\WallabagCoreTestCase; class ExportCommandTest extends WallabagCoreTestCase { /** - * @expectedException Symfony\Component\Console\Exception\RuntimeException + * @expectedException \Symfony\Component\Console\Exception\RuntimeException * @expectedExceptionMessage Not enough arguments (missing: "username") */ public function testExportCommandWithoutUsername() @@ -55,7 +55,7 @@ class ExportCommandTest extends WallabagCoreTestCase 'username' => 'admin', ]); - $this->assertContains('Exporting 6 entrie(s) for user « admin »... Done', $tester->getDisplay()); + $this->assertContains('Exporting 5 entrie(s) for user « admin »... Done', $tester->getDisplay()); $this->assertFileExists('admin-export.json'); } diff --git a/tests/Wallabag/CoreBundle/Command/InstallCommandTest.php b/tests/Wallabag/CoreBundle/Command/InstallCommandTest.php index 122a87d4..94fc0b94 100644 --- a/tests/Wallabag/CoreBundle/Command/InstallCommandTest.php +++ b/tests/Wallabag/CoreBundle/Command/InstallCommandTest.php @@ -2,8 +2,11 @@ namespace Tests\Wallabag\CoreBundle\Command; +use DAMA\DoctrineTestBundle\Doctrine\DBAL\StaticDriver; use Doctrine\Bundle\DoctrineBundle\Command\CreateDatabaseDoctrineCommand; use Doctrine\Bundle\DoctrineBundle\Command\DropDatabaseDoctrineCommand; +use Doctrine\DBAL\Platforms\PostgreSqlPlatform; +use Doctrine\DBAL\Platforms\SqlitePlatform; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; @@ -18,7 +21,9 @@ class InstallCommandTest extends WallabagCoreTestCase { parent::setUp(); - if ($this->getClient()->getContainer()->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOPgSql\Driver) { + /** @var \Doctrine\DBAL\Connection $connection */ + $connection = $this->getClient()->getContainer()->get('doctrine')->getConnection(); + if ($connection->getDatabasePlatform() instanceof PostgreSqlPlatform) { /* * LOG: statement: CREATE DATABASE "wallabag" * ERROR: source database "template1" is being accessed by other users @@ -30,34 +35,44 @@ class InstallCommandTest extends WallabagCoreTestCase */ $this->markTestSkipped('PostgreSQL spotted: can\'t find a good way to drop current database, skipping.'); } - } - /** - * Ensure next tests will have a clean database. - */ - public static function tearDownAfterClass() - { - $application = new Application(static::$kernel); - $application->setAutoExit(false); + if ($connection->getDatabasePlatform() instanceof SqlitePlatform) { + // Environnement variable useful only for sqlite to avoid the error "attempt to write a readonly database" + // We can't define always this environnement variable because pdo_mysql seems to use it + // and we have the error: + // SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; + // check the manual that corresponds to your MariaDB server version for the right syntax to use + // near '/tmp/wallabag_testTYj1kp' at line 1 + $databasePath = tempnam(sys_get_temp_dir(), 'wallabag_test'); + putenv("TEST_DATABASE_PATH=$databasePath"); + + // The environnement has been changed, recreate the client in order to update connection + parent::setUp(); + } - $application->run(new ArrayInput([ - 'command' => 'doctrine:schema:drop', - '--no-interaction' => true, - '--force' => true, - '--env' => 'test', - ]), new NullOutput()); + // disable doctrine-test-bundle + StaticDriver::setKeepStaticConnections(false); - $application->run(new ArrayInput([ - 'command' => 'doctrine:schema:create', - '--no-interaction' => true, - '--env' => 'test', - ]), new NullOutput()); + $this->resetDatabase($this->getClient()); + } - $application->run(new ArrayInput([ - 'command' => 'doctrine:fixtures:load', - '--no-interaction' => true, - '--env' => 'test', - ]), new NullOutput()); + public function tearDown() + { + $databasePath = getenv('TEST_DATABASE_PATH'); + // Remove variable environnement + putenv('TEST_DATABASE_PATH'); + if ($databasePath && file_exists($databasePath)) { + unlink($databasePath); + } else { + // Create a new client to avoid the error: + // Transaction commit failed because the transaction has been marked for rollback only. + $client = static::createClient(); + $this->resetDatabase($client); + } + + // enable doctrine-test-bundle + StaticDriver::setKeepStaticConnections(true); + parent::tearDown(); } public function testRunInstallCommand() @@ -67,18 +82,14 @@ class InstallCommandTest extends WallabagCoreTestCase $command = $application->find('wallabag:install'); - // We mock the QuestionHelper - $question = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor() - ->getMock(); - $question->expects($this->any()) - ->method('ask') - ->will($this->returnValue('yes_'.uniqid('', true))); - - // We override the standard helper with our mock - $command->getHelperSet()->set($question, 'question'); - $tester = new CommandTester($command); + $tester->setInputs([ + 'y', // dropping database + 'y', // create super admin + 'username_'.uniqid('', true), // username + 'password_'.uniqid('', true), // password + 'email_'.uniqid('', true).'@wallabag.it', // email + ]); $tester->execute([ 'command' => $command->getName(), ]); @@ -97,18 +108,13 @@ class InstallCommandTest extends WallabagCoreTestCase $command = $application->find('wallabag:install'); - // We mock the QuestionHelper - $question = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor() - ->getMock(); - $question->expects($this->any()) - ->method('ask') - ->will($this->returnValue('yes_'.uniqid('', true))); - - // We override the standard helper with our mock - $command->getHelperSet()->set($question, 'question'); - $tester = new CommandTester($command); + $tester->setInputs([ + 'y', // create super admin + 'username_'.uniqid('', true), // username + 'password_'.uniqid('', true), // password + 'email_'.uniqid('', true).'@wallabag.it', // email + ]); $tester->execute([ 'command' => $command->getName(), '--reset' => true, @@ -129,7 +135,7 @@ class InstallCommandTest extends WallabagCoreTestCase { // skipped SQLite check when database is removed because while testing for the connection, // the driver will create the file (so the database) before testing if database exist - if ($this->getClient()->getContainer()->get('doctrine')->getConnection()->getDriver() instanceof \Doctrine\DBAL\Driver\PDOSqlite\Driver) { + if ($this->getClient()->getContainer()->get('doctrine')->getConnection()->getDatabasePlatform() instanceof \Doctrine\DBAL\Platforms\SqlitePlatform) { $this->markTestSkipped('SQLite spotted: can\'t test with database removed.'); } @@ -150,18 +156,13 @@ class InstallCommandTest extends WallabagCoreTestCase $command = $application->find('wallabag:install'); - // We mock the QuestionHelper - $question = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor() - ->getMock(); - $question->expects($this->any()) - ->method('ask') - ->will($this->returnValue('yes_'.uniqid('', true))); - - // We override the standard helper with our mock - $command->getHelperSet()->set($question, 'question'); - $tester = new CommandTester($command); + $tester->setInputs([ + 'y', // create super admin + 'username_'.uniqid('', true), // username + 'password_'.uniqid('', true), // password + 'email_'.uniqid('', true).'@wallabag.it', // email + ]); $tester->execute([ 'command' => $command->getName(), ]); @@ -183,23 +184,12 @@ class InstallCommandTest extends WallabagCoreTestCase $command = $application->find('wallabag:install'); - // We mock the QuestionHelper - $question = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor() - ->getMock(); - - $question->expects($this->exactly(3)) - ->method('ask') - ->will($this->onConsecutiveCalls( - false, // don't want to reset the entire database - true, // do want to reset the schema - false // don't want to create a new user - )); - - // We override the standard helper with our mock - $command->getHelperSet()->set($question, 'question'); - $tester = new CommandTester($command); + $tester->setInputs([ + 'n', // don't want to reset the entire database + 'y', // do want to reset the schema + 'n', // don't want to create a new user + ]); $tester->execute([ 'command' => $command->getName(), ]); @@ -239,22 +229,11 @@ class InstallCommandTest extends WallabagCoreTestCase $command = $application->find('wallabag:install'); - // We mock the QuestionHelper - $question = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor() - ->getMock(); - - $question->expects($this->exactly(2)) - ->method('ask') - ->will($this->onConsecutiveCalls( - false, // don't want to reset the entire database - false // don't want to create a new user - )); - - // We override the standard helper with our mock - $command->getHelperSet()->set($question, 'question'); - $tester = new CommandTester($command); + $tester->setInputs([ + 'n', // don't want to reset the entire database + 'n', // don't want to create a new user + ]); $tester->execute([ 'command' => $command->getName(), ]); @@ -275,21 +254,11 @@ class InstallCommandTest extends WallabagCoreTestCase $command = $application->find('wallabag:install'); - // We mock the QuestionHelper - $question = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor() - ->getMock(); - $question->expects($this->any()) - ->method('ask') - ->will($this->returnValue('yes_'.uniqid('', true))); - - // We override the standard helper with our mock - $command->getHelperSet()->set($question, 'question'); - $tester = new CommandTester($command); $tester->execute([ 'command' => $command->getName(), - '--no-interaction' => true, + ], [ + 'interactive' => false, ]); $this->assertContains('Checking system requirements.', $tester->getDisplay()); diff --git a/tests/Wallabag/CoreBundle/Command/TagAllCommandTest.php b/tests/Wallabag/CoreBundle/Command/TagAllCommandTest.php index ec31708f..4cde3679 100644 --- a/tests/Wallabag/CoreBundle/Command/TagAllCommandTest.php +++ b/tests/Wallabag/CoreBundle/Command/TagAllCommandTest.php @@ -10,7 +10,7 @@ use Tests\Wallabag\CoreBundle\WallabagCoreTestCase; class TagAllCommandTest extends WallabagCoreTestCase { /** - * @expectedException Symfony\Component\Console\Exception\RuntimeException + * @expectedException \Symfony\Component\Console\Exception\RuntimeException * @expectedExceptionMessage Not enough arguments (missing: "username") */ public function testRunTagAllCommandWithoutUsername() diff --git a/tests/Wallabag/CoreBundle/Controller/ConfigControllerTest.php b/tests/Wallabag/CoreBundle/Controller/ConfigControllerTest.php index 35888f16..5bc815ee 100644 --- a/tests/Wallabag/CoreBundle/Controller/ConfigControllerTest.php +++ b/tests/Wallabag/CoreBundle/Controller/ConfigControllerTest.php @@ -67,8 +67,17 @@ class ConfigControllerTest extends WallabagCoreTestCase public function testChangeReadingSpeed() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://0.0.0.0/test-entry1') + ->setReadingTime(22); + $this->getEntityManager()->persist($entry); + + $this->getEntityManager()->flush(); + $this->getEntityManager()->clear(); + $crawler = $client->request('GET', '/unread/list'); $form = $crawler->filter('button[id=submit-filter]')->form(); $dataFilters = [ @@ -409,6 +418,7 @@ class ConfigControllerTest extends WallabagCoreTestCase public function testTaggingRuleCreation() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/config'); @@ -939,6 +949,7 @@ class ConfigControllerTest extends WallabagCoreTestCase public function testSwitchViewMode() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $client->request('GET', '/unread/list'); diff --git a/tests/Wallabag/CoreBundle/Controller/EntryControllerTest.php b/tests/Wallabag/CoreBundle/Controller/EntryControllerTest.php index 116e5f32..cc7b3672 100644 --- a/tests/Wallabag/CoreBundle/Controller/EntryControllerTest.php +++ b/tests/Wallabag/CoreBundle/Controller/EntryControllerTest.php @@ -71,6 +71,7 @@ class EntryControllerTest extends WallabagCoreTestCase public function testGetNew() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/new'); @@ -84,6 +85,7 @@ class EntryControllerTest extends WallabagCoreTestCase public function testPostNewViaBookmarklet() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/'); @@ -195,6 +197,12 @@ class EntryControllerTest extends WallabagCoreTestCase public function testPostNewOkUrlExist() { $this->logInAs('admin'); + + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $client = $this->getClient(); $crawler = $client->request('GET', '/new'); @@ -288,7 +296,7 @@ class EntryControllerTest extends WallabagCoreTestCase $tags = $entry->getTags(); $this->assertCount(2, $tags); - $this->assertEquals('wallabag', $tags[0]->getLabel()); + $this->assertContains('wallabag', $tags); $em->remove($entry); $em->flush(); @@ -317,7 +325,7 @@ class EntryControllerTest extends WallabagCoreTestCase $tags = $entry->getTags(); $this->assertCount(2, $tags); - $this->assertEquals('wallabag', $tags[1]->getLabel()); + $this->assertContains('wallabag', $tags); $em->remove($entry); $em->flush(); @@ -364,24 +372,23 @@ class EntryControllerTest extends WallabagCoreTestCase $this->assertEquals('/all/list', $client->getResponse()->getTargetUrl()); } - /** - * @depends testPostNewOk - */ public function testView() { $this->logInAs('admin'); $client = $this->getClient(); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://example.com/foo'); + $entry->setTitle('title foo'); + $entry->setContent('foo bar baz'); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); - $crawler = $client->request('GET', '/view/'.$content->getId()); + $crawler = $client->request('GET', '/view/'.$entry->getId()); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertGreaterThan(1, $body = $crawler->filter('body')->extract(['_text'])); - $this->assertContains($content->getTitle(), $body[0]); + $this->assertContains($entry->getTitle(), $body[0]); } /** @@ -394,27 +401,23 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $em = $client->getContainer() - ->get('doctrine.orm.entity_manager'); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setTitle('title foo'); + $entry->setContent(''); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $this->getEntityManager()->clear(); - $content = $em - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); - - // empty content - $content->setContent(''); - $em->persist($content); - $em->flush(); - - $client->request('GET', '/reload/'.$content->getId()); + $client->request('GET', '/reload/'.$entry->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); - $content = $em + $entry = $this->getEntityManager() ->getRepository('WallabagCoreBundle:Entry') - ->find($content->getId()); + ->find($entry->getId()); - $this->assertNotEmpty($content->getContent()); + $this->assertNotEmpty($entry->getContent()); } /** @@ -425,32 +428,21 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $em = $client->getContainer() - ->get('doctrine.orm.entity_manager'); - - $content = $em - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); - - // put a known failed url - $content->setUrl('http://0.0.0.0/failed.html'); - $em->persist($content); - $em->flush(); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://0.0.0.0/failed.html'); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); - $client->request('GET', '/reload/'.$content->getId()); + $client->request('GET', '/reload/'.$entry->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); // force EntityManager to clear previous entity // otherwise, retrieve the same entity will retrieve change from the previous request :0 - $em->clear(); - $newContent = $em + $this->getEntityManager()->clear(); + $newContent = $this->getEntityManager() ->getRepository('WallabagCoreBundle:Entry') - ->find($content->getId()); - - $newContent->setUrl($this->url); - $em->persist($newContent); - $em->flush(); + ->find($entry->getId()); $this->assertNotEquals($client->getContainer()->getParameter('wallabag_core.fetching_error_message'), $newContent->getContent()); } @@ -460,12 +452,12 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); - $crawler = $client->request('GET', '/edit/'.$content->getId()); + $crawler = $client->request('GET', '/edit/'.$entry->getId()); $this->assertEquals(200, $client->getResponse()->getStatusCode()); @@ -478,12 +470,12 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); - $crawler = $client->request('GET', '/edit/'.$content->getId()); + $crawler = $client->request('GET', '/edit/'.$entry->getId()); $this->assertEquals(200, $client->getResponse()->getStatusCode()); @@ -508,19 +500,20 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $this->getEntityManager()->clear(); - $client->request('GET', '/archive/'.$content->getId()); + $client->request('GET', '/archive/'.$entry->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); $res = $client->getContainer() ->get('doctrine.orm.entity_manager') ->getRepository('WallabagCoreBundle:Entry') - ->find($content->getId()); + ->find($entry->getId()); $this->assertEquals($res->isArchived(), true); } @@ -530,19 +523,20 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $this->getEntityManager()->clear(); - $client->request('GET', '/star/'.$content->getId()); + $client->request('GET', '/star/'.$entry->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); $res = $client->getContainer() ->get('doctrine.orm.entity_manager') ->getRepository('WallabagCoreBundle:Entry') - ->findOneById($content->getId()); + ->findOneById($entry->getId()); $this->assertEquals($res->isStarred(), true); } @@ -552,16 +546,16 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); - $client->request('GET', '/delete/'.$content->getId()); + $client->request('GET', '/delete/'.$entry->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); - $client->request('GET', '/delete/'.$content->getId()); + $client->request('GET', '/delete/'.$entry->getId()); $this->assertEquals(404, $client->getResponse()->getStatusCode()); } @@ -627,7 +621,13 @@ class EntryControllerTest extends WallabagCoreTestCase public function testFilterOnReadingTime() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setReadingTime(22); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); $crawler = $client->request('GET', '/unread/list'); @@ -666,9 +666,20 @@ class EntryControllerTest extends WallabagCoreTestCase public function testFilterOnReadingTimeOnlyUpper() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); - $crawler = $client->request('GET', '/unread/list'); + $crawler = $client->request('GET', '/all/list'); + $this->assertCount(5, $crawler->filter('div[class=entry]')); + + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setReadingTime(23); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + + $crawler = $client->request('GET', '/all/list'); + $this->assertCount(6, $crawler->filter('div[class=entry]')); $form = $crawler->filter('button[id=submit-filter]')->form(); @@ -678,12 +689,13 @@ class EntryControllerTest extends WallabagCoreTestCase $crawler = $client->submit($form, $data); - $this->assertCount(3, $crawler->filter('div[class=entry]')); + $this->assertCount(5, $crawler->filter('div[class=entry]')); } public function testFilterOnReadingTimeOnlyLower() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/unread/list'); @@ -696,12 +708,22 @@ class EntryControllerTest extends WallabagCoreTestCase $crawler = $client->submit($form, $data); - $this->assertCount(4, $crawler->filter('div[class=entry]')); + $this->assertCount(0, $crawler->filter('div[class=entry]')); + + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setReadingTime(23); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + + $crawler = $client->submit($form, $data); + $this->assertCount(1, $crawler->filter('div[class=entry]')); } public function testFilterOnUnreadStatus() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/all/list'); @@ -714,12 +736,23 @@ class EntryControllerTest extends WallabagCoreTestCase $crawler = $client->submit($form, $data); + $this->assertCount(4, $crawler->filter('div[class=entry]')); + + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setArchived(false); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + + $crawler = $client->submit($form, $data); + $this->assertCount(5, $crawler->filter('div[class=entry]')); } public function testFilterOnCreationDate() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/unread/list'); @@ -733,7 +766,7 @@ class EntryControllerTest extends WallabagCoreTestCase $crawler = $client->submit($form, $data); - $this->assertCount(6, $crawler->filter('div[class=entry]')); + $this->assertCount(5, $crawler->filter('div[class=entry]')); $data = [ 'entry_filter[createdAt][left_date]' => date('d/m/Y'), @@ -742,7 +775,7 @@ class EntryControllerTest extends WallabagCoreTestCase $crawler = $client->submit($form, $data); - $this->assertCount(6, $crawler->filter('div[class=entry]')); + $this->assertCount(5, $crawler->filter('div[class=entry]')); $data = [ 'entry_filter[createdAt][left_date]' => '01/01/1970', @@ -786,6 +819,7 @@ class EntryControllerTest extends WallabagCoreTestCase public function testFilterOnDomainName() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/unread/list'); @@ -818,6 +852,7 @@ class EntryControllerTest extends WallabagCoreTestCase public function testFilterOnStatus() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/unread/list'); @@ -839,6 +874,7 @@ class EntryControllerTest extends WallabagCoreTestCase public function testPreviewPictureFilter() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); $crawler = $client->request('GET', '/unread/list'); @@ -846,14 +882,21 @@ class EntryControllerTest extends WallabagCoreTestCase $form['entry_filter[previewPicture]']->tick(); $crawler = $client->submit($form); - $this->assertCount(2, $crawler->filter('div[class=entry]')); + $this->assertCount(1, $crawler->filter('div[class=entry]')); } public function testFilterOnLanguage() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setLanguage('fr'); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $crawler = $client->request('GET', '/unread/list'); $form = $crawler->filter('button[id=submit-filter]')->form(); $data = [ @@ -877,10 +920,14 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findOneByUser($this->getLoggedInUserId()); + // sharing is enabled + $client->getContainer()->get('craue_config')->set('share_public', 1); + + $content = new Entry($this->getLoggedInUser()); + $content->setUrl($this->url); + $this->getEntityManager()->persist($content); + $this->getEntityManager()->flush(); + $this->getEntityManager()->clear(); // no uid $client->request('GET', '/share/'.$content->getUid()); @@ -970,6 +1017,20 @@ class EntryControllerTest extends WallabagCoreTestCase $url = 'http://www.20minutes.fr/montpellier/1952003-20161030-video-car-tombe-panne-rugbymen-perpignan-improvisent-melee-route'; $client->getContainer()->get('craue_config')->set('download_images_enabled', 1); + $crawler = $client->request('GET', '/new'); + + $this->assertEquals(200, $client->getResponse()->getStatusCode()); + + $form = $crawler->filter('form[name=entry]')->form(); + + $data = [ + 'entry[url]' => $url, + ]; + + $client->submit($form, $data); + + $this->assertEquals(302, $client->getResponse()->getStatusCode()); + $content = $client->getContainer() ->get('doctrine.orm.entity_manager') ->getRepository('WallabagCoreBundle:Entry') @@ -987,28 +1048,19 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('empty'); $client = $this->getClient(); - $em = $client->getContainer()->get('doctrine.orm.entity_manager'); - $user = $em - ->getRepository('WallabagUserBundle:User') - ->find($this->getLoggedInUserId()); - - if (!$user) { - $this->markTestSkipped('No user found in db.'); - } - // Redirect to homepage - $config = $user->getConfig(); + $config = $this->getLoggedInUser()->getConfig(); $config->setActionMarkAsRead(Config::REDIRECT_TO_HOMEPAGE); - $em->persist($config); - $em->flush(); + $this->getEntityManager()->persist($config); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); - $client->request('GET', '/view/'.$content->getId()); - $client->request('GET', '/archive/'.$content->getId()); + $this->getEntityManager()->flush(); + + $client->request('GET', '/view/'.$entry->getId()); + $client->request('GET', '/archive/'.$entry->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); $this->assertEquals('/', $client->getResponse()->headers->get('location')); @@ -1019,46 +1071,36 @@ class EntryControllerTest extends WallabagCoreTestCase $this->logInAs('empty'); $client = $this->getClient(); - $em = $client->getContainer()->get('doctrine.orm.entity_manager'); - $user = $em - ->getRepository('WallabagUserBundle:User') - ->find($this->getLoggedInUserId()); - - if (!$user) { - $this->markTestSkipped('No user found in db.'); - } - // Redirect to current page - $config = $user->getConfig(); + $config = $this->getLoggedInUser()->getConfig(); $config->setActionMarkAsRead(Config::REDIRECT_TO_CURRENT_PAGE); - $em->persist($config); - $em->flush(); + $this->getEntityManager()->persist($config); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $this->getEntityManager()->persist($entry); - $client->request('GET', '/view/'.$content->getId()); - $client->request('GET', '/archive/'.$content->getId()); + $this->getEntityManager()->flush(); + + $client->request('GET', '/view/'.$entry->getId()); + $client->request('GET', '/archive/'.$entry->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); - $this->assertContains('/view/'.$content->getId(), $client->getResponse()->headers->get('location')); + $this->assertContains('/view/'.$entry->getId(), $client->getResponse()->headers->get('location')); } public function testFilterOnHttpStatus() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); - $crawler = $client->request('GET', '/new'); - $form = $crawler->filter('form[name=entry]')->form(); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://www.lemonde.fr/incorrect-url/'); + $entry->setHttpStatus(404); + $this->getEntityManager()->persist($entry); - $data = [ - 'entry[url]' => 'http://www.lemonde.fr/incorrect-url/', - ]; - - $client->submit($form, $data); + $this->getEntityManager()->flush(); $crawler = $client->request('GET', '/all/list'); $form = $crawler->filter('button[id=submit-filter]')->form(); @@ -1071,14 +1113,17 @@ class EntryControllerTest extends WallabagCoreTestCase $this->assertCount(1, $crawler->filter('div[class=entry]')); - $crawler = $client->request('GET', '/new'); - $form = $crawler->filter('form[name=entry]')->form(); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setHttpStatus(200); + $this->getEntityManager()->persist($entry); - $data = [ - 'entry[url]' => 'http://www.nextinpact.com/news/101235-wallabag-alternative-libre-a-pocket-creuse-petit-a-petit-son-nid.htm', - ]; + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://www.nextinpact.com/news/101235-wallabag-alternative-libre-a-pocket-creuse-petit-a-petit-son-nid.htm'); + $entry->setHttpStatus(200); + $this->getEntityManager()->persist($entry); - $client->submit($form, $data); + $this->getEntityManager()->flush(); $crawler = $client->request('GET', '/all/list'); $form = $crawler->filter('button[id=submit-filter]')->form(); @@ -1106,8 +1151,15 @@ class EntryControllerTest extends WallabagCoreTestCase public function testSearch() { $this->logInAs('admin'); + $this->useTheme('baggy'); $client = $this->getClient(); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl($this->url); + $entry->setTitle('test'); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + // Search on unread list $crawler = $client->request('GET', '/unread/list'); @@ -1118,35 +1170,37 @@ class EntryControllerTest extends WallabagCoreTestCase $crawler = $client->submit($form, $data); - $this->assertCount(5, $crawler->filter('div[class=entry]')); + $this->assertCount(4, $crawler->filter('div[class=entry]')); // Search on starred list $crawler = $client->request('GET', '/starred/list'); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://localhost/foo/bar'); + $entry->setTitle('testeur'); + $entry->setStarred(true); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $form = $crawler->filter('form[name=search]')->form(); $data = [ - 'search_entry[term]' => 'title', + 'search_entry[term]' => 'testeur', ]; $crawler = $client->submit($form, $data); $this->assertCount(1, $crawler->filter('div[class=entry]')); - // Added new article to test on archive list - $crawler = $client->request('GET', '/new'); - $form = $crawler->filter('form[name=entry]')->form(); - $data = [ - 'entry[url]' => $this->url, - ]; - $client->submit($form, $data); - $content = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId($this->url, $this->getLoggedInUserId()); - $client->request('GET', '/archive/'.$content->getId()); - $crawler = $client->request('GET', '/archive/list'); + // Added new article to test on archive list + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://0.0.0.0/foo/baz/qux'); + $entry->setTitle('Le manège'); + $entry->setArchived(true); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $form = $crawler->filter('form[name=search]')->form(); $data = [ 'search_entry[term]' => 'manège', @@ -1155,7 +1209,7 @@ class EntryControllerTest extends WallabagCoreTestCase $crawler = $client->submit($form, $data); $this->assertCount(1, $crawler->filter('div[class=entry]')); - $client->request('GET', '/delete/'.$content->getId()); + $client->request('GET', '/delete/'.$entry->getId()); // test on list of all articles $crawler = $client->request('GET', '/all/list'); @@ -1170,6 +1224,13 @@ class EntryControllerTest extends WallabagCoreTestCase $this->assertCount(0, $crawler->filter('div[class=entry]')); // test url search on list of all articles + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://domain/qux'); + $entry->setTitle('Le manège'); + $entry->setArchived(true); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $crawler = $client->request('GET', '/all/list'); $form = $crawler->filter('form[name=search]')->form(); diff --git a/tests/Wallabag/CoreBundle/Controller/ExportControllerTest.php b/tests/Wallabag/CoreBundle/Controller/ExportControllerTest.php index 63f2c829..b38961d3 100644 --- a/tests/Wallabag/CoreBundle/Controller/ExportControllerTest.php +++ b/tests/Wallabag/CoreBundle/Controller/ExportControllerTest.php @@ -239,7 +239,7 @@ class ExportControllerTest extends WallabagCoreTestCase $this->assertEquals($contentInDB->getLanguage(), $content[0]['language']); $this->assertEquals($contentInDB->getReadingtime(), $content[0]['reading_time']); $this->assertEquals($contentInDB->getDomainname(), $content[0]['domain_name']); - $this->assertEquals(['foo bar', 'baz', 'foot'], $content[0]['tags']); + $this->assertEquals(['foo bar', 'baz'], $content[0]['tags']); } public function testXmlExport() diff --git a/tests/Wallabag/CoreBundle/Controller/TagControllerTest.php b/tests/Wallabag/CoreBundle/Controller/TagControllerTest.php index c3b22dcd..af1ad7af 100644 --- a/tests/Wallabag/CoreBundle/Controller/TagControllerTest.php +++ b/tests/Wallabag/CoreBundle/Controller/TagControllerTest.php @@ -3,6 +3,7 @@ namespace Tests\Wallabag\CoreBundle\Controller; use Tests\Wallabag\CoreBundle\WallabagCoreTestCase; +use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; class TagControllerTest extends WallabagCoreTestCase @@ -24,10 +25,11 @@ class TagControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $entry = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId('http://0.0.0.0/entry1', $this->getLoggedInUserId()); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://0.0.0.0/foo'); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $this->getEntityManager()->clear(); $crawler = $client->request('GET', '/view/'.$entry->getId()); @@ -41,23 +43,15 @@ class TagControllerTest extends WallabagCoreTestCase $this->assertEquals(302, $client->getResponse()->getStatusCode()); // be sure to reload the entry - $entry = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId('http://0.0.0.0/entry1', $this->getLoggedInUserId()); - - $this->assertEquals(4, count($entry->getTags())); + $entry = $this->getEntityManager()->getRepository(Entry::class)->find($entry->getId()); + $this->assertCount(1, $entry->getTags()); // tag already exists and already assigned $client->submit($form, $data); $this->assertEquals(302, $client->getResponse()->getStatusCode()); - $newEntry = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->find($entry->getId()); - - $this->assertEquals(4, count($newEntry->getTags())); + $entry = $this->getEntityManager()->getRepository(Entry::class)->find($entry->getId()); + $this->assertCount(1, $entry->getTags()); // tag already exists but still not assigned to this entry $data = [ @@ -67,12 +61,8 @@ class TagControllerTest extends WallabagCoreTestCase $client->submit($form, $data); $this->assertEquals(302, $client->getResponse()->getStatusCode()); - $newEntry = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->find($entry->getId()); - - $this->assertEquals(4, count($newEntry->getTags())); + $entry = $this->getEntityManager()->getRepository(Entry::class)->find($entry->getId()); + $this->assertCount(2, $entry->getTags()); } public function testAddMultipleTagToEntry() @@ -116,20 +106,25 @@ class TagControllerTest extends WallabagCoreTestCase $this->logInAs('admin'); $client = $this->getClient(); - $entry = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Entry') - ->findByUrlAndUserId('http://0.0.0.0/entry1', $this->getLoggedInUserId()); - - $tag = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Tag') - ->findOneByEntryAndTagLabel($entry, $this->tagName); - + $tag = new Tag(); + $tag->setLabel($this->tagName); + $entry = new Entry($this->getLoggedInUser()); + $entry->setUrl('http://0.0.0.0/foo'); + $entry->addTag($tag); + $this->getEntityManager()->persist($entry); + $this->getEntityManager()->flush(); + $this->getEntityManager()->clear(); + + // We make a first request to set an history and test redirection after tag deletion + $client->request('GET', '/view/'.$entry->getId()); + $entryUri = $client->getRequest()->getUri(); $client->request('GET', '/remove-tag/'.$entry->getId().'/'.$tag->getId()); $this->assertEquals(302, $client->getResponse()->getStatusCode()); + $this->assertEquals($entryUri, $client->getResponse()->getTargetUrl()); + // re-retrieve the entry to be sure to get fresh data from database (mostly for tags) + $entry = $this->getEntityManager()->getRepository(Entry::class)->find($entry->getId()); $this->assertNotContains($this->tagName, $entry->getTags()); $client->request('GET', '/remove-tag/'.$entry->getId().'/'.$tag->getId()); diff --git a/tests/Wallabag/CoreBundle/Helper/ContentProxyTest.php b/tests/Wallabag/CoreBundle/Helper/ContentProxyTest.php index 77dfd5bf..a3570125 100644 --- a/tests/Wallabag/CoreBundle/Helper/ContentProxyTest.php +++ b/tests/Wallabag/CoreBundle/Helper/ContentProxyTest.php @@ -3,12 +3,14 @@ namespace Tests\Wallabag\CoreBundle\Helper; use Psr\Log\NullLogger; +use Monolog\Logger; +use Monolog\Handler\TestHandler; use Wallabag\CoreBundle\Helper\ContentProxy; use Wallabag\CoreBundle\Entity\Entry; use Wallabag\CoreBundle\Entity\Tag; use Wallabag\UserBundle\Entity\User; -use Wallabag\CoreBundle\Repository\TagRepository; use Wallabag\CoreBundle\Helper\RuleBasedTagger; +use Graby\Graby; class ContentProxyTest extends \PHPUnit_Framework_TestCase { @@ -36,7 +38,8 @@ class ContentProxyTest extends \PHPUnit_Framework_TestCase ]); $proxy = new ContentProxy($graby, $tagger, $this->getLogger(), $this->fetchingErrorMessage); - $entry = $proxy->updateEntry(new Entry(new User()), 'http://user@:80'); + $entry = new Entry(new User()); + $proxy->updateEntry($entry, 'http://user@:80'); $this->assertEquals('http://user@:80', $entry->getUrl()); $this->assertEmpty($entry->getTitle()); @@ -70,7 +73,8 @@ class ContentProxyTest extends \PHPUnit_Framework_TestCase ]); $proxy = new ContentProxy($graby, $tagger, $this->getLogger(), $this->fetchingErrorMessage); - $entry = $proxy->updateEntry(new Entry(new User()), 'http://0.0.0.0'); + $entry = new Entry(new User()); + $proxy->updateEntry($entry, 'http://0.0.0.0'); $this->assertEquals('http://0.0.0.0', $entry->getUrl()); $this->assertEmpty($entry->getTitle()); @@ -109,7 +113,8 @@ class ContentProxyTest extends \PHPUnit_Framework_TestCase ]); $proxy = new ContentProxy($graby, $tagger, $this->getLogger(), $this->fetchingErrorMessage); - $entry = $proxy->updateEntry(new Entry(new User()), 'http://domain.io'); + $entry = new Entry(new User()); + $proxy->updateEntry($entry, 'http://domain.io'); $this->assertEquals('http://domain.io', $entry->getUrl()); $this->assertEquals('my title', $entry->getTitle()); @@ -150,7 +155,8 @@ class ContentProxyTest extends \PHPUnit_Framework_TestCase ]); $proxy = new ContentProxy($graby, $tagger, $this->getLogger(), $this->fetchingErrorMessage); - $entry = $proxy->updateEntry(new Entry(new User()), 'http://0.0.0.0'); + $entry = new Entry(new User()); + $proxy->updateEntry($entry, 'http://0.0.0.0'); $this->assertEquals('http://1.1.1.1', $entry->getUrl()); $this->assertEquals('this is my title', $entry->getTitle()); @@ -191,7 +197,8 @@ class ContentProxyTest extends \PHPUnit_Framework_TestCase ]); $proxy = new ContentProxy($graby, $tagger, $this->getLogger(), $this->fetchingErrorMessage); - $entry = $proxy->updateEntry(new Entry(new User()), 'http://0.0.0.0'); + $entry = new Entry(new User()); + $proxy->updateEntry($entry, 'http://0.0.0.0'); $this->assertEquals('http://1.1.1.1', $entry->getUrl()); $this->assertEquals('this is my title', $entry->getTitle()); @@ -210,16 +217,62 @@ class ContentProxyTest extends \PHPUnit_Framework_TestCase $tagger->expects($this->once()) ->method('tag'); - $graby = $this->getMockBuilder('Graby\Graby')->getMock(); + $proxy = new ContentProxy((new Graby()), $tagger, $this->getLogger(), $this->fetchingErrorMessage); + $entry = new Entry(new User()); + $proxy->updateEntry( + $entry, + 'http://0.0.0.0', + [ + 'html' => str_repeat('this is my content', 325), + 'title' => 'this is my title', + 'url' => 'http://1.1.1.1', + 'content_type' => 'text/html', + 'language' => 'fr', + 'date' => '1395635872', + 'authors' => ['Jeremy', 'Nico', 'Thomas'], + 'all_headers' => [ + 'Cache-Control' => 'no-cache', + ], + ] + ); - $proxy = new ContentProxy($graby, $tagger, $this->getLogger(), $this->fetchingErrorMessage); - $entry = $proxy->updateEntry(new Entry(new User()), 'http://0.0.0.0', [ - 'html' => str_repeat('this is my content', 325), - 'title' => 'this is my title', - 'url' => 'http://1.1.1.1', - 'content_type' => 'text/html', - 'language' => 'fr', - ]); + $this->assertEquals('http://1.1.1.1', $entry->getUrl()); + $this->assertEquals('this is my title', $entry->getTitle()); + $this->assertContains('this is my content', $entry->getContent()); + $this->assertEquals('text/html', $entry->getMimetype()); + $this->assertEquals('fr', $entry->getLanguage()); + $this->assertEquals(4.0, $entry->getReadingTime()); + $this->assertEquals('1.1.1.1', $entry->getDomainName()); + $this->assertEquals('24/03/2014', $entry->getPublishedAt()->format('d/m/Y')); + $this->assertContains('Jeremy', $entry->getPublishedBy()); + $this->assertContains('Nico', $entry->getPublishedBy()); + $this->assertContains('Thomas', $entry->getPublishedBy()); + $this->assertContains('no-cache', $entry->getHeaders()); + } + + public function testWithForcedContentAndDatetime() + { + $tagger = $this->getTaggerMock(); + $tagger->expects($this->once()) + ->method('tag'); + + $logHandler = new TestHandler(); + $logger = new Logger('test', [$logHandler]); + + $proxy = new ContentProxy((new Graby()), $tagger, $logger, $this->fetchingErrorMessage); + $entry = new Entry(new User()); + $proxy->updateEntry( + $entry, + 'http://1.1.1.1', + [ + 'html' => str_repeat('this is my content', 325), + 'title' => 'this is my title', + 'url' => 'http://1.1.1.1', + 'content_type' => 'text/html', + 'language' => 'fr', + 'date' => '2016-09-08T11:55:58+0200', + ] + ); $this->assertEquals('http://1.1.1.1', $entry->getUrl()); $this->assertEquals('this is my title', $entry->getTitle()); @@ -228,32 +281,126 @@ class ContentProxyTest extends \PHPUnit_Framework_TestCase $this->assertEquals('fr', $entry->getLanguage()); $this->assertEquals(4.0, $entry->getReadingTime()); $this->assertEquals('1.1.1.1', $entry->getDomainName()); + $this->assertEquals('08/09/2016', $entry->getPublishedAt()->format('d/m/Y')); } - public function testTaggerThrowException() + public function testWithForcedContentAndBadDate() { - $graby = $this->getMockBuilder('Graby\Graby') - ->disableOriginalConstructor() - ->getMock(); + $tagger = $this->getTaggerMock(); + $tagger->expects($this->once()) + ->method('tag'); + $logger = new Logger('foo'); + $handler = new TestHandler(); + $logger->pushHandler($handler); + + $proxy = new ContentProxy((new Graby()), $tagger, $logger, $this->fetchingErrorMessage); + $entry = new Entry(new User()); + $proxy->updateEntry( + $entry, + 'http://1.1.1.1', + [ + 'html' => str_repeat('this is my content', 325), + 'title' => 'this is my title', + 'url' => 'http://1.1.1.1', + 'content_type' => 'text/html', + 'language' => 'fr', + 'date' => '01 02 2012', + ] + ); + + $this->assertEquals('http://1.1.1.1', $entry->getUrl()); + $this->assertEquals('this is my title', $entry->getTitle()); + $this->assertContains('this is my content', $entry->getContent()); + $this->assertEquals('text/html', $entry->getMimetype()); + $this->assertEquals('fr', $entry->getLanguage()); + $this->assertEquals(4.0, $entry->getReadingTime()); + $this->assertEquals('1.1.1.1', $entry->getDomainName()); + $this->assertNull($entry->getPublishedAt()); + + $records = $handler->getRecords(); + + $this->assertCount(1, $records); + $this->assertContains('Error while defining date', $records[0]['message']); + } + + public function testTaggerThrowException() + { $tagger = $this->getTaggerMock(); $tagger->expects($this->once()) ->method('tag') ->will($this->throwException(new \Exception())); - $proxy = new ContentProxy($graby, $tagger, $this->getLogger(), $this->fetchingErrorMessage); - - $entry = $proxy->updateEntry(new Entry(new User()), 'http://0.0.0.0', [ - 'html' => str_repeat('this is my content', 325), - 'title' => 'this is my title', - 'url' => 'http://1.1.1.1', - 'content_type' => 'text/html', - 'language' => 'fr', - ]); + $proxy = new ContentProxy((new Graby()), $tagger, $this->getLogger(), $this->fetchingErrorMessage); + $entry = new Entry(new User()); + $proxy->updateEntry( + $entry, + 'http://1.1.1.1', + [ + 'html' => str_repeat('this is my content', 325), + 'title' => 'this is my title', + 'url' => 'http://1.1.1.1', + 'content_type' => 'text/html', + 'language' => 'fr', + ] + ); $this->assertCount(0, $entry->getTags()); } + public function dataForCrazyHtml() + { + return [ + 'script and comment' => [ + 'Script inside:
      ', + 'lol', + ], + 'script' => [ + 'Script inside:', + 'script', + ], + ]; + } + + /** + * @dataProvider dataForCrazyHtml + */ + public function testWithCrazyHtmlContent($html, $escapedString) + { + $tagger = $this->getTaggerMock(); + $tagger->expects($this->once()) + ->method('tag'); + + $proxy = new ContentProxy((new Graby()), $tagger, $this->getLogger(), $this->fetchingErrorMessage); + $entry = new Entry(new User()); + $proxy->updateEntry( + $entry, + 'http://1.1.1.1', + [ + 'html' => $html, + 'title' => 'this is my title', + 'url' => 'http://1.1.1.1', + 'content_type' => 'text/html', + 'language' => 'fr', + 'status' => '200', + 'open_graph' => [ + 'og_title' => 'my OG title', + 'og_description' => 'OG desc', + 'og_image' => 'http://3.3.3.3/cover.jpg', + ], + ] + ); + + $this->assertEquals('http://1.1.1.1', $entry->getUrl()); + $this->assertEquals('this is my title', $entry->getTitle()); + $this->assertNotContains($escapedString, $entry->getContent()); + $this->assertEquals('http://3.3.3.3/cover.jpg', $entry->getPreviewPicture()); + $this->assertEquals('text/html', $entry->getMimetype()); + $this->assertEquals('fr', $entry->getLanguage()); + $this->assertEquals('200', $entry->getHttpStatus()); + $this->assertEquals('1.1.1.1', $entry->getDomainName()); + } + private function getTaggerMock() { return $this->getMockBuilder(RuleBasedTagger::class) diff --git a/tests/Wallabag/CoreBundle/Helper/DownloadImagesTest.php b/tests/Wallabag/CoreBundle/Helper/DownloadImagesTest.php index 85f12d87..9125f8dc 100644 --- a/tests/Wallabag/CoreBundle/Helper/DownloadImagesTest.php +++ b/tests/Wallabag/CoreBundle/Helper/DownloadImagesTest.php @@ -12,7 +12,24 @@ use GuzzleHttp\Stream\Stream; class DownloadImagesTest extends \PHPUnit_Framework_TestCase { - public function testProcessHtml() + public function dataForSuccessImage() + { + return [ + 'imgur' => [ + '
      ', + 'http://imgur.com/gallery/WxtWY', + ], + 'image with &' => [ + '
      ', + 'https://www.tvaddons.ag/realdebrid-kodi-jarvis/', + ], + ]; + } + + /** + * @dataProvider dataForSuccessImage + */ + public function testProcessHtml($html, $url) { $client = new Client(); @@ -27,9 +44,10 @@ class DownloadImagesTest extends \PHPUnit_Framework_TestCase $download = new DownloadImages($client, sys_get_temp_dir().'/wallabag_test', 'http://wallabag.io/', $logger); - $res = $download->processHtml(123, '
      ', 'http://imgur.com/gallery/WxtWY'); + $res = $download->processHtml(123, $html, $url); - $this->assertContains('http://wallabag.io/assets/images/9/b/9b0ead26/c638b4c2.png', $res); + // this the base path of all image (since it's calculated using the entry id: 123) + $this->assertContains('http://wallabag.io/assets/images/9/b/9b0ead26/', $res); } public function testProcessHtmlWithBadImage() diff --git a/tests/Wallabag/CoreBundle/Helper/RedirectTest.php b/tests/Wallabag/CoreBundle/Helper/RedirectTest.php index 0539f20a..f420d06a 100644 --- a/tests/Wallabag/CoreBundle/Helper/RedirectTest.php +++ b/tests/Wallabag/CoreBundle/Helper/RedirectTest.php @@ -89,4 +89,22 @@ class RedirectTest extends \PHPUnit_Framework_TestCase $this->assertEquals($this->routerMock->generate('homepage'), $redirectUrl); } + + public function testUserForRedirectWithIgnoreActionMarkAsRead() + { + $this->token->getUser()->getConfig()->setActionMarkAsRead(Config::REDIRECT_TO_HOMEPAGE); + + $redirectUrl = $this->redirect->to('/unread/list', '', true); + + $this->assertEquals('/unread/list', $redirectUrl); + } + + public function testUserForRedirectNullWithFallbackWithIgnoreActionMarkAsRead() + { + $this->token->getUser()->getConfig()->setActionMarkAsRead(Config::REDIRECT_TO_HOMEPAGE); + + $redirectUrl = $this->redirect->to(null, 'fallback', true); + + $this->assertEquals('fallback', $redirectUrl); + } } diff --git a/tests/Wallabag/CoreBundle/ParamConverter/UsernameRssTokenConverterTest.php b/tests/Wallabag/CoreBundle/ParamConverter/UsernameRssTokenConverterTest.php index 2e6fccfb..ca8e0d50 100644 --- a/tests/Wallabag/CoreBundle/ParamConverter/UsernameRssTokenConverterTest.php +++ b/tests/Wallabag/CoreBundle/ParamConverter/UsernameRssTokenConverterTest.php @@ -136,7 +136,7 @@ class UsernameRssTokenConverterTest extends \PHPUnit_Framework_TestCase } /** - * @expectedException Symfony\Component\HttpKernel\Exception\NotFoundHttpException + * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException * @expectedExceptionMessage User not found */ public function testApplyUserNotFound() diff --git a/tests/Wallabag/CoreBundle/WallabagCoreTestCase.php b/tests/Wallabag/CoreBundle/WallabagCoreTestCase.php index 7bf4b43c..eec6939d 100644 --- a/tests/Wallabag/CoreBundle/WallabagCoreTestCase.php +++ b/tests/Wallabag/CoreBundle/WallabagCoreTestCase.php @@ -2,11 +2,20 @@ namespace Tests\Wallabag\CoreBundle; +use Symfony\Bundle\FrameworkBundle\Client; +use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\BrowserKit\Cookie; +use Symfony\Component\Console\Input\ArrayInput; +use Symfony\Component\Console\Output\NullOutput; +use Wallabag\CoreBundle\Entity\Config; +use Wallabag\UserBundle\Entity\User; abstract class WallabagCoreTestCase extends WebTestCase { + /** + * @var Client|null + */ private $client = null; public function getClient() @@ -21,6 +30,44 @@ abstract class WallabagCoreTestCase extends WebTestCase $this->client = static::createClient(); } + public function resetDatabase(Client $client) + { + $application = new Application($client->getKernel()); + $application->setAutoExit(false); + + $application->run(new ArrayInput([ + 'command' => 'doctrine:schema:drop', + '--no-interaction' => true, + '--force' => true, + '--env' => 'test', + ]), new NullOutput()); + + $application->run(new ArrayInput([ + 'command' => 'doctrine:schema:create', + '--no-interaction' => true, + '--env' => 'test', + ]), new NullOutput()); + + $application->run(new ArrayInput([ + 'command' => 'doctrine:fixtures:load', + '--no-interaction' => true, + '--env' => 'test', + ]), new NullOutput()); + + /* + * Recreate client to avoid error: + * + * [Doctrine\DBAL\ConnectionException] + * Transaction commit failed because the transaction has been marked for rollback only. + */ + $this->client = static::createClient(); + } + + public function getEntityManager() + { + return $this->client->getContainer()->get('doctrine.orm.entity_manager'); + } + /** * Login a user without making a HTTP request. * If we make a HTTP request we lose ability to mock service in the container. @@ -37,7 +84,7 @@ abstract class WallabagCoreTestCase extends WebTestCase $firewallName = $container->getParameter('fos_user.firewall_name'); $user = $userManager->findUserBy(array('username' => $username)); - $loginManager->loginUser($firewallName, $user); + $loginManager->logInUser($firewallName, $user); $session->set('_security_'.$firewallName, serialize($container->get('security.token_storage')->getToken())); $session->save(); @@ -65,22 +112,41 @@ abstract class WallabagCoreTestCase extends WebTestCase } /** - * Return the user id of the logged in user. + * Return the user of the logged in user. * You should be sure that you called `logInAs` before. * - * @return int + * @return User */ - public function getLoggedInUserId() + public function getLoggedInUser() { $token = static::$kernel->getContainer()->get('security.token_storage')->getToken(); if (null !== $token) { - return $token->getUser()->getId(); + return $token->getUser(); } throw new \RuntimeException('No logged in User.'); } + /** + * Return the user id of the logged in user. + * You should be sure that you called `logInAs` before. + * + * @return int + */ + public function getLoggedInUserId() + { + return $this->getLoggedInUser()->getId(); + } + + public function useTheme($theme) + { + $config = $this->getEntityManager()->getRepository(Config::class)->findOneByUser($this->getLoggedInUser()); + $config->setTheme($theme); + $this->getEntityManager()->persist($config); + $this->getEntityManager()->flush(); + } + /** * Check if Redis is installed. * If not, mark test as skip. diff --git a/tests/Wallabag/ImportBundle/Command/ImportCommandTest.php b/tests/Wallabag/ImportBundle/Command/ImportCommandTest.php index 7043c345..f507563c 100644 --- a/tests/Wallabag/ImportBundle/Command/ImportCommandTest.php +++ b/tests/Wallabag/ImportBundle/Command/ImportCommandTest.php @@ -95,6 +95,7 @@ class ImportCommandTest extends WallabagCoreTestCase 'username' => 1, 'filepath' => $application->getKernel()->getContainer()->getParameter('kernel.root_dir').'/../tests/Wallabag/ImportBundle/fixtures/wallabag-v2-read.json', '--useUserId' => true, + '--importer' => 'v2', ]); } } diff --git a/tests/Wallabag/ImportBundle/Command/RedisWorkerCommandTest.php b/tests/Wallabag/ImportBundle/Command/RedisWorkerCommandTest.php index 74952847..e5e251a0 100644 --- a/tests/Wallabag/ImportBundle/Command/RedisWorkerCommandTest.php +++ b/tests/Wallabag/ImportBundle/Command/RedisWorkerCommandTest.php @@ -11,7 +11,7 @@ use M6Web\Component\RedisMock\RedisMockFactory; class RedisWorkerCommandTest extends WallabagCoreTestCase { /** - * @expectedException Symfony\Component\Console\Exception\RuntimeException + * @expectedException \Symfony\Component\Console\Exception\RuntimeException * @expectedExceptionMessage Not enough arguments (missing: "serviceName") */ public function testRunRedisWorkerCommandWithoutArguments() @@ -28,7 +28,7 @@ class RedisWorkerCommandTest extends WallabagCoreTestCase } /** - * @expectedException Symfony\Component\Config\Definition\Exception\Exception + * @expectedException \Symfony\Component\Config\Definition\Exception\Exception * @expectedExceptionMessage No queue or consumer found for service name */ public function testRunRedisWorkerCommandWithBadService() diff --git a/tests/Wallabag/ImportBundle/Controller/InstapaperControllerTest.php b/tests/Wallabag/ImportBundle/Controller/InstapaperControllerTest.php index c2e5fdb7..84742e0a 100644 --- a/tests/Wallabag/ImportBundle/Controller/InstapaperControllerTest.php +++ b/tests/Wallabag/ImportBundle/Controller/InstapaperControllerTest.php @@ -107,6 +107,9 @@ class InstapaperControllerTest extends WallabagCoreTestCase $crawler = $client->followRedirect(); + $this->assertGreaterThan(1, $body = $crawler->filter('body')->extract(['_text'])); + $this->assertContains('flashes.import.notice.summary', $body[0]); + $content = $client->getContainer() ->get('doctrine.orm.entity_manager') ->getRepository('WallabagCoreBundle:Entry') @@ -115,14 +118,25 @@ class InstapaperControllerTest extends WallabagCoreTestCase $this->getLoggedInUserId() ); - $this->assertGreaterThan(1, $body = $crawler->filter('body')->extract(['_text'])); - $this->assertContains('flashes.import.notice.summary', $body[0]); - $this->assertNotEmpty($content->getMimetype(), 'Mimetype for http://www.liberation.fr is ok'); $this->assertNotEmpty($content->getPreviewPicture(), 'Preview picture for http://www.liberation.fr is ok'); $this->assertNotEmpty($content->getLanguage(), 'Language for http://www.liberation.fr is ok'); + $this->assertContains('foot', $content->getTags(), 'It includes the "foot" tag'); $this->assertEquals(1, count($content->getTags())); $this->assertInstanceOf(\DateTime::class, $content->getCreatedAt()); + + $content = $client->getContainer() + ->get('doctrine.orm.entity_manager') + ->getRepository('WallabagCoreBundle:Entry') + ->findByUrlAndUserId( + 'http://www.20minutes.fr/high-tech/2077615-20170531-dis-donc-donald-trump-quoi-exactement-covfefe', + $this->getLoggedInUserId() + ); + + $this->assertContains('foot', $content->getTags()); + $this->assertContains('test_tag', $content->getTags()); + + $this->assertEquals(2, count($content->getTags())); } public function testImportInstapaperWithFileAndMarkAllAsRead() diff --git a/tests/Wallabag/ImportBundle/Controller/PinboardControllerTest.php b/tests/Wallabag/ImportBundle/Controller/PinboardControllerTest.php index 96b32484..e2b6e7b6 100644 --- a/tests/Wallabag/ImportBundle/Controller/PinboardControllerTest.php +++ b/tests/Wallabag/ImportBundle/Controller/PinboardControllerTest.php @@ -121,7 +121,13 @@ class PinboardControllerTest extends WallabagCoreTestCase $this->assertNotEmpty($content->getMimetype(), 'Mimetype for https://ma.ttias.be is ok'); $this->assertNotEmpty($content->getPreviewPicture(), 'Preview picture for https://ma.ttias.be is ok'); $this->assertNotEmpty($content->getLanguage(), 'Language for https://ma.ttias.be is ok'); - $this->assertEquals(3, count($content->getTags())); + + $tags = $content->getTags(); + $this->assertContains('foot', $tags, 'It includes the "foot" tag'); + $this->assertContains('varnish', $tags, 'It includes the "varnish" tag'); + $this->assertContains('PHP', $tags, 'It includes the "PHP" tag'); + $this->assertEquals(3, count($tags)); + $this->assertInstanceOf(\DateTime::class, $content->getCreatedAt()); $this->assertEquals('2016-10-26', $content->getCreatedAt()->format('Y-m-d')); } diff --git a/tests/Wallabag/ImportBundle/Controller/ReadabilityControllerTest.php b/tests/Wallabag/ImportBundle/Controller/ReadabilityControllerTest.php index e6d33fe9..bde0a600 100644 --- a/tests/Wallabag/ImportBundle/Controller/ReadabilityControllerTest.php +++ b/tests/Wallabag/ImportBundle/Controller/ReadabilityControllerTest.php @@ -121,7 +121,11 @@ class ReadabilityControllerTest extends WallabagCoreTestCase $this->assertNotEmpty($content->getMimetype(), 'Mimetype for http://www.zataz.com is ok'); $this->assertNotEmpty($content->getPreviewPicture(), 'Preview picture for http://www.zataz.com is ok'); $this->assertNotEmpty($content->getLanguage(), 'Language for http://www.zataz.com is ok'); - $this->assertEquals(1, count($content->getTags())); + + $tags = $content->getTags(); + $this->assertContains('foot', $tags, 'It includes the "foot" tag'); + $this->assertEquals(1, count($tags)); + $this->assertInstanceOf(\DateTime::class, $content->getCreatedAt()); $this->assertEquals('2016-09-08', $content->getCreatedAt()->format('Y-m-d')); } diff --git a/tests/Wallabag/ImportBundle/Controller/WallabagV1ControllerTest.php b/tests/Wallabag/ImportBundle/Controller/WallabagV1ControllerTest.php index 0c7f97ed..2c492c20 100644 --- a/tests/Wallabag/ImportBundle/Controller/WallabagV1ControllerTest.php +++ b/tests/Wallabag/ImportBundle/Controller/WallabagV1ControllerTest.php @@ -112,24 +112,22 @@ class WallabagV1ControllerTest extends WallabagCoreTestCase ->get('doctrine.orm.entity_manager') ->getRepository('WallabagCoreBundle:Entry') ->findByUrlAndUserId( - 'https://framablog.org/2014/02/05/framabag-service-libre-gratuit-interview-developpeur/', + 'http://www.framablog.org/index.php/post/2014/02/05/Framabag-service-libre-gratuit-interview-developpeur', $this->getLoggedInUserId() ); - $tag = $client->getContainer() - ->get('doctrine.orm.entity_manager') - ->getRepository('WallabagCoreBundle:Tag') - ->findOneByLabel('Framabag'); - - $this->assertTrue($content->getTags()->contains($tag)); - $this->assertGreaterThan(1, $body = $crawler->filter('body')->extract(['_text'])); $this->assertContains('flashes.import.notice.summary', $body[0]); - $this->assertNotEmpty($content->getMimetype(), 'Mimetype for http://www.framablog.org is ok'); - $this->assertNotEmpty($content->getPreviewPicture(), 'Preview picture for http://www.framablog.org is ok'); - $this->assertNotEmpty($content->getLanguage(), 'Language for http://www.framablog.org is ok'); - $this->assertEquals(2, count($content->getTags())); + $this->assertEmpty($content->getMimetype(), 'Mimetype for http://www.framablog.org is empty'); + $this->assertEmpty($content->getPreviewPicture(), 'Preview picture for http://www.framablog.org is empty'); + $this->assertEmpty($content->getLanguage(), 'Language for http://www.framablog.org is empty'); + + $tags = $content->getTags(); + $this->assertContains('foot', $tags, 'It includes the "foot" tag'); + $this->assertContains('Framabag', $tags, 'It includes the "Framabag" tag'); + $this->assertEquals(2, count($tags)); + $this->assertInstanceOf(\DateTime::class, $content->getCreatedAt()); } diff --git a/tests/Wallabag/ImportBundle/Controller/WallabagV2ControllerTest.php b/tests/Wallabag/ImportBundle/Controller/WallabagV2ControllerTest.php index 556ab1bd..24893259 100644 --- a/tests/Wallabag/ImportBundle/Controller/WallabagV2ControllerTest.php +++ b/tests/Wallabag/ImportBundle/Controller/WallabagV2ControllerTest.php @@ -119,10 +119,14 @@ class WallabagV2ControllerTest extends WallabagCoreTestCase $this->getLoggedInUserId() ); - $this->assertNotEmpty($content->getMimetype(), 'Mimetype for http://www.liberation.fr is ok'); - $this->assertNotEmpty($content->getPreviewPicture(), 'Preview picture for http://www.liberation.fr is ok'); - $this->assertNotEmpty($content->getLanguage(), 'Language for http://www.liberation.fr is ok'); - $this->assertEquals(1, count($content->getTags())); + // empty because it wasn't re-imported + $this->assertEmpty($content->getMimetype(), 'Mimetype for http://www.liberation.fr is empty'); + $this->assertEmpty($content->getPreviewPicture(), 'Preview picture for http://www.liberation.fr is empty'); + $this->assertEmpty($content->getLanguage(), 'Language for http://www.liberation.fr is empty'); + + $tags = $content->getTags(); + $this->assertContains('foot', $tags, 'It includes the "foot" tag'); + $this->assertEquals(1, count($tags)); $content = $client->getContainer() ->get('doctrine.orm.entity_manager') @@ -135,9 +139,16 @@ class WallabagV2ControllerTest extends WallabagCoreTestCase $this->assertNotEmpty($content->getMimetype(), 'Mimetype for https://www.mediapart.fr is ok'); $this->assertNotEmpty($content->getPreviewPicture(), 'Preview picture for https://www.mediapart.fr is ok'); $this->assertNotEmpty($content->getLanguage(), 'Language for https://www.mediapart.fr is ok'); - $this->assertEquals(3, count($content->getTags())); + + $tags = $content->getTags(); + $this->assertContains('foot', $tags, 'It includes the "foot" tag'); + $this->assertContains('mediapart', $tags, 'It includes the "mediapart" tag'); + $this->assertContains('blog', $tags, 'It includes the "blog" tag'); + $this->assertEquals(3, count($tags)); + $this->assertInstanceOf(\DateTime::class, $content->getCreatedAt()); $this->assertEquals('2016-09-08', $content->getCreatedAt()->format('Y-m-d')); + $this->assertTrue($content->isStarred(), 'Entry is starred'); } public function testImportWallabagWithEmptyFile() diff --git a/tests/Wallabag/ImportBundle/Import/InstapaperImportTest.php b/tests/Wallabag/ImportBundle/Import/InstapaperImportTest.php index 6777a02e..9158c8a2 100644 --- a/tests/Wallabag/ImportBundle/Import/InstapaperImportTest.php +++ b/tests/Wallabag/ImportBundle/Import/InstapaperImportTest.php @@ -18,6 +18,7 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase protected $logHandler; protected $contentProxy; protected $tagsAssigner; + protected $uow; private function getInstapaperImport($unsetUser = false, $dispatched = 0) { @@ -27,6 +28,20 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase ->disableOriginalConstructor() ->getMock(); + $this->uow = $this->getMockBuilder('Doctrine\ORM\UnitOfWork') + ->disableOriginalConstructor() + ->getMock(); + + $this->em + ->expects($this->any()) + ->method('getUnitOfWork') + ->willReturn($this->uow); + + $this->uow + ->expects($this->any()) + ->method('getScheduledEntityInsertions') + ->willReturn([]); + $this->contentProxy = $this->getMockBuilder('Wallabag\CoreBundle\Helper\ContentProxy') ->disableOriginalConstructor() ->getMock(); @@ -67,14 +82,14 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase public function testImport() { - $instapaperImport = $this->getInstapaperImport(false, 3); + $instapaperImport = $this->getInstapaperImport(false, 4); $instapaperImport->setFilepath(__DIR__.'/../fixtures/instapaper-export.csv'); $entryRepo = $this->getMockBuilder('Wallabag\CoreBundle\Repository\EntryRepository') ->disableOriginalConstructor() ->getMock(); - $entryRepo->expects($this->exactly(3)) + $entryRepo->expects($this->exactly(4)) ->method('findByUrlAndUserId') ->willReturn(false); @@ -88,14 +103,14 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase ->getMock(); $this->contentProxy - ->expects($this->exactly(3)) + ->expects($this->exactly(4)) ->method('updateEntry') ->willReturn($entry); $res = $instapaperImport->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 3, 'queued' => 0], $instapaperImport->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 4, 'queued' => 0], $instapaperImport->getSummary()); } public function testImportAndMarkAllAsRead() @@ -107,9 +122,9 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase ->disableOriginalConstructor() ->getMock(); - $entryRepo->expects($this->exactly(3)) + $entryRepo->expects($this->exactly(4)) ->method('findByUrlAndUserId') - ->will($this->onConsecutiveCalls(false, true, true)); + ->will($this->onConsecutiveCalls(false, true, true, true)); $this->em ->expects($this->any()) @@ -133,7 +148,7 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase $this->assertTrue($res); - $this->assertEquals(['skipped' => 2, 'imported' => 1, 'queued' => 0], $instapaperImport->getSummary()); + $this->assertEquals(['skipped' => 3, 'imported' => 1, 'queued' => 0], $instapaperImport->getSummary()); } public function testImportWithRabbit() @@ -165,7 +180,7 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase ->getMock(); $producer - ->expects($this->exactly(3)) + ->expects($this->exactly(4)) ->method('publish'); $instapaperImport->setProducer($producer); @@ -173,7 +188,7 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase $res = $instapaperImport->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 3], $instapaperImport->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 4], $instapaperImport->getSummary()); } public function testImportWithRedis() @@ -211,7 +226,7 @@ class InstapaperImportTest extends \PHPUnit_Framework_TestCase $res = $instapaperImport->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 3], $instapaperImport->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 4], $instapaperImport->getSummary()); $this->assertNotEmpty($redisMock->lpop('instapaper')); } diff --git a/tests/Wallabag/ImportBundle/Import/ReadabilityImportTest.php b/tests/Wallabag/ImportBundle/Import/ReadabilityImportTest.php index 254f0a25..8f466d38 100644 --- a/tests/Wallabag/ImportBundle/Import/ReadabilityImportTest.php +++ b/tests/Wallabag/ImportBundle/Import/ReadabilityImportTest.php @@ -67,14 +67,14 @@ class ReadabilityImportTest extends \PHPUnit_Framework_TestCase public function testImport() { - $readabilityImport = $this->getReadabilityImport(false, 24); + $readabilityImport = $this->getReadabilityImport(false, 3); $readabilityImport->setFilepath(__DIR__.'/../fixtures/readability.json'); $entryRepo = $this->getMockBuilder('Wallabag\CoreBundle\Repository\EntryRepository') ->disableOriginalConstructor() ->getMock(); - $entryRepo->expects($this->exactly(24)) + $entryRepo->expects($this->exactly(3)) ->method('findByUrlAndUserId') ->willReturn(false); @@ -88,14 +88,14 @@ class ReadabilityImportTest extends \PHPUnit_Framework_TestCase ->getMock(); $this->contentProxy - ->expects($this->exactly(24)) + ->expects($this->exactly(3)) ->method('updateEntry') ->willReturn($entry); $res = $readabilityImport->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 24, 'queued' => 0], $readabilityImport->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 3, 'queued' => 0], $readabilityImport->getSummary()); } public function testImportAndMarkAllAsRead() @@ -165,7 +165,7 @@ class ReadabilityImportTest extends \PHPUnit_Framework_TestCase ->getMock(); $producer - ->expects($this->exactly(24)) + ->expects($this->exactly(3)) ->method('publish'); $readabilityImport->setProducer($producer); @@ -173,7 +173,7 @@ class ReadabilityImportTest extends \PHPUnit_Framework_TestCase $res = $readabilityImport->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 24], $readabilityImport->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 3], $readabilityImport->getSummary()); } public function testImportWithRedis() @@ -211,7 +211,7 @@ class ReadabilityImportTest extends \PHPUnit_Framework_TestCase $res = $readabilityImport->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 24], $readabilityImport->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 3], $readabilityImport->getSummary()); $this->assertNotEmpty($redisMock->lpop('readability')); } diff --git a/tests/Wallabag/ImportBundle/Import/WallabagV1ImportTest.php b/tests/Wallabag/ImportBundle/Import/WallabagV1ImportTest.php index 9f0c5bac..834b7ef5 100644 --- a/tests/Wallabag/ImportBundle/Import/WallabagV1ImportTest.php +++ b/tests/Wallabag/ImportBundle/Import/WallabagV1ImportTest.php @@ -19,6 +19,8 @@ class WallabagV1ImportTest extends \PHPUnit_Framework_TestCase protected $contentProxy; protected $tagsAssigner; protected $uow; + protected $fetchingErrorMessageTitle = 'No title found'; + protected $fetchingErrorMessage = 'wallabag can\'t retrieve contents for this article. Please troubleshoot this issue.'; private function getWallabagV1Import($unsetUser = false, $dispatched = 0) { @@ -58,7 +60,14 @@ class WallabagV1ImportTest extends \PHPUnit_Framework_TestCase ->expects($this->exactly($dispatched)) ->method('dispatch'); - $wallabag = new WallabagV1Import($this->em, $this->contentProxy, $this->tagsAssigner, $dispatcher); + $wallabag = new WallabagV1Import( + $this->em, + $this->contentProxy, + $this->tagsAssigner, + $dispatcher, + $this->fetchingErrorMessageTitle, + $this->fetchingErrorMessage + ); $this->logHandler = new TestHandler(); $logger = new Logger('test', [$this->logHandler]); @@ -82,14 +91,14 @@ class WallabagV1ImportTest extends \PHPUnit_Framework_TestCase public function testImport() { - $wallabagV1Import = $this->getWallabagV1Import(false, 3); + $wallabagV1Import = $this->getWallabagV1Import(false, 1); $wallabagV1Import->setFilepath(__DIR__.'/../fixtures/wallabag-v1.json'); $entryRepo = $this->getMockBuilder('Wallabag\CoreBundle\Repository\EntryRepository') ->disableOriginalConstructor() ->getMock(); - $entryRepo->expects($this->exactly(4)) + $entryRepo->expects($this->exactly(2)) ->method('findByUrlAndUserId') ->will($this->onConsecutiveCalls(false, true, false, false)); @@ -103,14 +112,14 @@ class WallabagV1ImportTest extends \PHPUnit_Framework_TestCase ->getMock(); $this->contentProxy - ->expects($this->exactly(3)) + ->expects($this->exactly(1)) ->method('updateEntry') ->willReturn($entry); $res = $wallabagV1Import->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 1, 'imported' => 3, 'queued' => 0], $wallabagV1Import->getSummary()); + $this->assertEquals(['skipped' => 1, 'imported' => 1, 'queued' => 0], $wallabagV1Import->getSummary()); } public function testImportAndMarkAllAsRead() @@ -180,7 +189,7 @@ class WallabagV1ImportTest extends \PHPUnit_Framework_TestCase ->getMock(); $producer - ->expects($this->exactly(4)) + ->expects($this->exactly(2)) ->method('publish'); $wallabagV1Import->setProducer($producer); @@ -188,7 +197,7 @@ class WallabagV1ImportTest extends \PHPUnit_Framework_TestCase $res = $wallabagV1Import->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 4], $wallabagV1Import->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 2], $wallabagV1Import->getSummary()); } public function testImportWithRedis() @@ -226,7 +235,7 @@ class WallabagV1ImportTest extends \PHPUnit_Framework_TestCase $res = $wallabagV1Import->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 4], $wallabagV1Import->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 2], $wallabagV1Import->getSummary()); $this->assertNotEmpty($redisMock->lpop('wallabag_v1')); } diff --git a/tests/Wallabag/ImportBundle/Import/WallabagV2ImportTest.php b/tests/Wallabag/ImportBundle/Import/WallabagV2ImportTest.php index efcaeb9e..5cc04aa5 100644 --- a/tests/Wallabag/ImportBundle/Import/WallabagV2ImportTest.php +++ b/tests/Wallabag/ImportBundle/Import/WallabagV2ImportTest.php @@ -89,7 +89,7 @@ class WallabagV2ImportTest extends \PHPUnit_Framework_TestCase ->disableOriginalConstructor() ->getMock(); - $entryRepo->expects($this->exactly(24)) + $entryRepo->expects($this->exactly(6)) ->method('findByUrlAndUserId') ->will($this->onConsecutiveCalls(false, true, false)); @@ -106,7 +106,7 @@ class WallabagV2ImportTest extends \PHPUnit_Framework_TestCase $res = $wallabagV2Import->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 22, 'imported' => 2, 'queued' => 0], $wallabagV2Import->getSummary()); + $this->assertEquals(['skipped' => 4, 'imported' => 2, 'queued' => 0], $wallabagV2Import->getSummary()); } public function testImportAndMarkAllAsRead() @@ -172,7 +172,7 @@ class WallabagV2ImportTest extends \PHPUnit_Framework_TestCase ->getMock(); $producer - ->expects($this->exactly(24)) + ->expects($this->exactly(6)) ->method('publish'); $wallabagV2Import->setProducer($producer); @@ -180,7 +180,7 @@ class WallabagV2ImportTest extends \PHPUnit_Framework_TestCase $res = $wallabagV2Import->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 24], $wallabagV2Import->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 6], $wallabagV2Import->getSummary()); } public function testImportWithRedis() @@ -214,7 +214,7 @@ class WallabagV2ImportTest extends \PHPUnit_Framework_TestCase $res = $wallabagV2Import->setMarkAsRead(true)->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 24], $wallabagV2Import->getSummary()); + $this->assertEquals(['skipped' => 0, 'imported' => 0, 'queued' => 6], $wallabagV2Import->getSummary()); $this->assertNotEmpty($redisMock->lpop('wallabag_v2')); } @@ -267,7 +267,7 @@ class WallabagV2ImportTest extends \PHPUnit_Framework_TestCase ->disableOriginalConstructor() ->getMock(); - $entryRepo->expects($this->exactly(24)) + $entryRepo->expects($this->exactly(6)) ->method('findByUrlAndUserId') ->will($this->onConsecutiveCalls(false, true, false)); @@ -284,6 +284,6 @@ class WallabagV2ImportTest extends \PHPUnit_Framework_TestCase $res = $wallabagV2Import->import(); $this->assertTrue($res); - $this->assertEquals(['skipped' => 22, 'imported' => 2, 'queued' => 0], $wallabagV2Import->getSummary()); + $this->assertEquals(['skipped' => 4, 'imported' => 2, 'queued' => 0], $wallabagV2Import->getSummary()); } } diff --git a/tests/Wallabag/ImportBundle/fixtures/instapaper-export.csv b/tests/Wallabag/ImportBundle/fixtures/instapaper-export.csv index 28a4c8e6..1a648f8a 100644 --- a/tests/Wallabag/ImportBundle/fixtures/instapaper-export.csv +++ b/tests/Wallabag/ImportBundle/fixtures/instapaper-export.csv @@ -2,3 +2,4 @@ URL,Title,Selection,Folder http://www.liberation.fr/societe/2012/12/06/baumettes-un-tour-en-cellule_865551,Baumettes : un tour en cellule,,Unread https://redditblog.com/2016/09/20/amp-and-reactredux/,AMP and React+Redux: Why Not?,,Archive https://medium.com/@the_minh/why-foursquare-swarm-is-still-my-favourite-social-network-e38228493e6c,Why Foursquare / Swarm is still my favourite social network,,Starred +http://www.20minutes.fr/high-tech/2077615-20170531-dis-donc-donald-trump-quoi-exactement-covfefe,"Dis donc Donald Trump, c'est quoi exactement «covfefe»?",,test_tag diff --git a/tests/Wallabag/ImportBundle/fixtures/pinboard_export b/tests/Wallabag/ImportBundle/fixtures/pinboard_export index 2dd744d3..b5f653e7 100644 --- a/tests/Wallabag/ImportBundle/fixtures/pinboard_export +++ b/tests/Wallabag/ImportBundle/fixtures/pinboard_export @@ -1,5 +1,3 @@ [{"href":"https:\/\/developers.google.com\/web\/updates\/2016\/07\/infinite-scroller","description":"Complexities of an Infinite Scroller","extended":"TL;DR: Re-use your DOM elements and remove the ones that are far away from the viewport. Use placeholders to account for delayed data","meta":"21ff61c6f648901168f9e6119f53df7d","hash":"e69b65724cca1c585b446d4c47865d76","time":"2016-10-31T15:57:56Z","shared":"yes","toread":"no","tags":"infinite dom performance scroll"}, {"href":"https:\/\/ma.ttias.be\/varnish-explained\/","description":"Varnish (explained) for PHP developers","extended":"A few months ago, I gave a presentation at LaraconEU in Amsterdam titled \"Varnish for PHP developers\". The generic title of that presentation is actually Varnish Explained and this is a write-up of that presentation, the video and the slides.","meta":"d32ad9fac2ed29da4aec12c562e9afb1","hash":"21dd6bdda8ad62666a2c9e79f6e80f98","time":"2016-10-26T06:43:03Z","shared":"yes","toread":"no","tags":"varnish PHP"}, -{"href":"https:\/\/ilia.ws\/files\/nginx_torontophpug.pdf","description":"Nginx Tricks for PHP Developers","extended":"","meta":"9adbb5c4ca6760e335b920800d88c70a","hash":"0189bb08f8bd0122c6544bed4624c546","time":"2016-10-05T07:11:27Z","shared":"yes","toread":"no","tags":"nginx PHP best_practice"}, -{"href":"https:\/\/jolicode.com\/blog\/starting-a-mobile-application-with-react-native","description":"Starting a mobile application with React Native","extended":"While preparing our next React Native training, I learnt a lot on the library and discovered an amazing community with a lot of packages.","meta":"bd140bd3e53e3a0b4cb08cdaf64bcbfc","hash":"015fa10cd97f56186420555e52cfab62","time":"2016-09-23T10:58:20Z","shared":"yes","toread":"no","tags":"react-native"}, -{"href":"http:\/\/open.blogs.nytimes.com\/2016\/08\/29\/testing-varnish-using-varnishtest\/","description":"Testing Varnish Using Varnishtest","extended":"Varnish ships with the ability to test using the testing tool varnishtest. Varnishtest gives you the ability to write VCL tests you can run on the command line or as part of your build process.","meta":"ca2752a07adea4bab52cd19e8fdbf356","hash":"d3e642cc1274d10e4c12ee31f5dde736","time":"2016-08-30T09:33:24Z","shared":"yes","toread":"no","tags":"varnish test vcl"}] +{"href":"https:\/\/ilia.ws\/files\/nginx_torontophpug.pdf","description":"Nginx Tricks for PHP Developers","extended":"","meta":"9adbb5c4ca6760e335b920800d88c70a","hash":"0189bb08f8bd0122c6544bed4624c546","time":"2016-10-05T07:11:27Z","shared":"yes","toread":"no","tags":"nginx PHP best_practice"}] diff --git a/tests/Wallabag/ImportBundle/fixtures/readability.json b/tests/Wallabag/ImportBundle/fixtures/readability.json index 32f6fa53..b9fd570d 100644 --- a/tests/Wallabag/ImportBundle/fixtures/readability.json +++ b/tests/Wallabag/ImportBundle/fixtures/readability.json @@ -10,13 +10,6 @@ "article__title": "We Looked At 167,943 Tweets & Found Out Hashtags Are Worthless", "archive": false }, - { - "article__title": "Réfugiés: l'UE va créer 100 000 places d'accueil dans les Balkans", - "article__url": "http://www.liberation.fr/planete/2015/10/26/refugies-l-ue-va-creer-100-000-places-d-accueil-dans-les-balkans_1408867", - "archive": false, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": false - }, { "article__title": "No title found", "article__url": "http://news.nationalgeographic.com/2016/02/160211-albatrosses-mothers-babies-animals-science/&sf20739758=1", @@ -24,152 +17,12 @@ "date_added": "2016-09-08T11:55:58+0200", "favorite": true }, - { - "archive": 0, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Échecs", - "article__url": "https://fr.wikipedia.org/wiki/Échecs" - }, { "archive": 0, "date_added": "2016-09-08T11:55:58+0200", "favorite": 0, "article__title": "90% des dossiers médicaux des Coréens du sud vendus à des entreprises privées - ZATAZ", "article__url": "http://www.zataz.com/90-des-dossiers-medicaux-des-coreens-du-sud-vendus-a-des-entreprises-privees/" - }, - { - "archive": 0, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Mass Surveillance As Art", - "article__url": "https://www.nationaljournal.com/s/73311/mass-surveillance-art" - }, - { - "archive": 0, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "What David Cameron did to the pig, his party is now doing to the country", - "article__url": "http://www.newstatesman.com/2015/09/what-david-cameron-did-pig-his-party-now-doing-country" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "CLICK HERE to support 2016 CES Winner, Revolutionary Auto-Tracking Robot", - "article__url": "https://www.indiegogo.com/projects/2016-ces-winner-revolutionary-auto-tracking-robot" - }, - { - "archive": 0, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 1, - "article__title": "No title found", - "article__url": "http://carnetdevol.shost.ca/wordpress/aide-memoire-sur-les-commandes-associees-a-systemd/" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Présentation d'Arduino - Tuto Arduino - Le blog d'Eskimon", - "article__url": "http://eskimon.fr/73-arduino-101-presentation" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Lenovo ThinkPad X1 Carbon Ultrabook Review", - "article__url": "http://www.notebookcheck.net/Lenovo-ThinkPad-X1-Carbon-Ultrabook-Review.138033.0.html" - }, - { - "archive": 0, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Visitons le Château de Landsberg !", - "article__url": "http://autour-du-mont-sainte-odile.overblog.com/2016/01/visitons-le-chateau-de-landsberg.html" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Contrer les stéréotypes par les livres : “C'est dès l'enfance qu'ils se construisent”", - "article__url": "https://www.actualitte.com/article/monde-edition/contrer-les-stereotypes-par-les-livres-c-est-des-l-enfance-qu-ils-se-construisent/64058" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "[ROM][6.0.1][Layers][N5] TipsyOS official builds {UBER TCs}", - "article__url": "http://forum.xda-developers.com/google-nexus-5/development/rom-tipsyos-official-builds-uber-tcs-t3325989" - }, - { - "archive": 0, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Top 15 Podcasts All Web Developers Should Follow - Envato Tuts+ Code Article", - "article__url": "http://code.tutsplus.com/articles/top-15-podcasts-all-web-developers-should-follow--net-14461" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "University of Mississippi", - "article__url": "http://olemiss.edu" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "FinnChristiansen.de Jetzt Dank Let’s Encrypt Per HTTPS Erreichbar", - "article__url": "https://www.finnchristiansen.de/2015/12/06/finnchristiansen-de-jetzt-dank-lets-encrypt-per-https-erreichbar/" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Le développeur et l'ingénierie logicielle", - "article__url": "http://wemucs.com/le-developpeur-et-lingenierie-logicielle/" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "The Role of Methylation in Gene Expression", - "article__url": "http://www.nature.com/scitable/topicpage/the-role-of-methylation-in-gene-expression-1070" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "E-Mail-Adresse kostenlos, FreeMail, De-Mail & Nachrichten", - "article__url": "http://web.de" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "OpenSSH Server on Arch Linux | DominicM test", - "article__url": "http://dominicm.com/openssh-server-arch-linux/" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Site Moved | Site Help", - "article__url": "http://g1.com/help/sitemoved.asp" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "#Maroc : le stylo anti-pédophiles EAGLE d’AMESYS est moins bien configuré que les faux-lowers Twitter du roi Mohammed VI", - "article__url": "https://reflets.info/maroc-le-stylo-anti-pedophiles-eagle-damesys-est-moins-bien-configure-que-les-faux-lowers-twitter-du-roi-mohammed-vi/" - }, - { - "archive": 1, - "date_added": "2016-09-08T11:55:58+0200", - "favorite": 0, - "article__title": "Simple Cloud Infrastructure for Developers", - "article__url": "https://www.digitalocean.com/" } ], "recommendations": [] diff --git a/tests/Wallabag/ImportBundle/fixtures/wallabag-v1.json b/tests/Wallabag/ImportBundle/fixtures/wallabag-v1.json index f298469f..28270ec4 100644 --- a/tests/Wallabag/ImportBundle/fixtures/wallabag-v1.json +++ b/tests/Wallabag/ImportBundle/fixtures/wallabag-v1.json @@ -32,38 +32,5 @@ "content": "README.md

      wallabag is a self hostable application allowing you to not miss any content anymore. Click, save, read it when you can. It extracts content so that you can read it when you have time.

      \n

      More informations on our website: wallabag.org

      \n

      License

      \n

      Copyright © 2010-2014 Nicolas Lœuillet nicolas@loeuillet.org This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See the COPYING file for more details.

      \n", "user_id": "1", "tags":"" - }, - { - "0": "3", - "1": "a self hostable application for saving web pages | wallabag", - "2": "https://www.wallabag.org/", - "3": "1", - "4": "0", - "5": "\n
      \n
      \n

      wallabag (formerly poche) is a self hostable application for saving web pages. Unlike other services, wallabag is free (as in freedom) and open source.

      \n
      \n\n
      \n
      \n
      \n

      With this application you will not miss content anymore. Click, save, read it when you want. It saves the content you select so that you can read it when you have time.

      \n
      \n\n
      \n
      \n
      \n

      How it works

      \n

      Thanks to the bookmarklet or third-party applications, you save an article in your wallabag to read it later. Then, when you open your wallabag, you can comfortably read your articles.

      \n

      How to use wallabag

      \n

      There are two ways to use wallabag: you can install it on your web server or you can create an account at Framabag (we install and upgrade wallabag for you).

      \n
      \n\n
      \n", - "6": "1", - "id": "3", - "title": "a self hostable application for saving web pages | wallabag", - "url": "https://www.wallabag.org/", - "is_read": "1", - "is_fav": "0", - "content": "\n
      \n
      \n

      wallabag (formerly poche) is a self hostable application for saving web pages. Unlike other services, wallabag is free (as in freedom) and open source.

      \n
      \n\n
      \n
      \n
      \n

      With this application you will not miss content anymore. Click, save, read it when you want. It saves the content you select so that you can read it when you have time.

      \n
      \n\n
      \n
      \n
      \n

      How it works

      \n

      Thanks to the bookmarklet or third-party applications, you save an article in your wallabag to read it later. Then, when you open your wallabag, you can comfortably read your articles.

      \n

      How to use wallabag

      \n

      There are two ways to use wallabag: you can install it on your web server or you can create an account at Framabag (we install and upgrade wallabag for you).

      \n
      \n\n
      \n", - "user_id": "1" - }, - { - "0": "4", - "1": "Sans titre", - "2": "http:\/\/www.konradlischka.info\/2016\/01\/blog\/wie-ein-deutsches-start-up-mit-wagniskapital-die-marktluecke-fuer-lokalen-digitaljournalismus-schliessen-will\/", - "3": "0", - "4": "0", - "5": "[unable to retrieve full-text content]", - "6": "1", - "id": "4", - "title": "Sans titre", - "url": "http:\/\/www.konradlischka.info\/2016\/01\/blog\/wie-ein-deutsches-start-up-mit-wagniskapital-die-marktluecke-fuer-lokalen-digitaljournalismus-schliessen-will\/", - "is_read": "0", - "is_fav": "0", - "content": "[unable to retrieve full-text content]", - "user_id": "1", - "tags": "" } ] diff --git a/tests/Wallabag/ImportBundle/fixtures/wallabag-v2.json b/tests/Wallabag/ImportBundle/fixtures/wallabag-v2.json index efa8faf2..0e30d95b 100644 --- a/tests/Wallabag/ImportBundle/fixtures/wallabag-v2.json +++ b/tests/Wallabag/ImportBundle/fixtures/wallabag-v2.json @@ -6,7 +6,7 @@ "is_archived": false, "created_at": "2016-09-08T11:55:58+0200", "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": false, + "is_starred": true, "content": "
      Édition CAMédia\n

      Deux nouvelles éditions pour débattre dans le club sur la laïcité et sur la démocratie

      \n

      18 janv. 2016 | Par

      \n

      CAMédia après un échange sur « l'éthique du débat » a lancé deux discussions , l'une sur le thème de la laïcité, l'autre ( encore en cours) sur celui de la démocratie. Nous sommes heureux de pouvoir signaler la création de deux nouvelles éditions participatives sur ces thèmes. Nous vous invitons à les lire et à participer à leurs débats.

      \n
      \n

      De l'importance de rêver, éloge du merveilleux

      \n

      17 janv. 2016 | Par

      \n

      Je parlerai ici des rêves comme moteur de vie, de ces rêves qui vous rattachent et vous font espérer à ce qu’il y a de plus humain dans l’homme, même au milieu de la plus noire des détresses.

      \n
      \n

      Fin(s) d'une toute-puissance

      \n

      18 janv. 2016 | Par

      \n

      En ce début d’année, je recommande la lecture du dernier ouvrage de Guillaume Duval, La France ne sera jamais plus une grande puissance ? Tant mieux !

      \n
      \n

      L’Allier, département de destruction massive du tissu culturel

      \n

      18 janv. 2016 | Par

      \n

      Les temps sont durs pour les petites structures, les associations culturelles qui, de bourgades en villages, travaillent au cœur des régions. Leurs subventions sont souvent revues à la baisse. Le département de l’Allier les a carrément supprimées. Pour favoriser « l’événementiel ».

      \n
      Édition Les invités de Mediapart\n

      La démocratie déjà attaquée par la coopération réglementaire transatlantique

      \n

      18 janv. 2016 | Par

      \n

      Lora Verheecke et David Lundy travaillent pour Corporate Europe Observatory, une ONG basée à Bruxelles qui enquête sur le pouvoir des lobbies des grandes entreprises sur la politique de l’Union européenne. Ils révèlent que depuis 25 ans le projet de « coopération réglementaire » mené par l’Union européenne et les États-Unis a été dominé par les grandes entreprises. ET que le TTIP cherche à entériner ce projet.

      \n
      \n

      2016, une année test pour Jacob Zuma et son gouvernement

      \n

      18 janv. 2016 | Par

      \n

      Les turbulences de l’an passé ont toutes les chances de continuer à troubler le climat politique et social de l’Afrique du Sud en 2016. La situation exige des changements profonds dans la conduite des affaires du pays. Jacob Zuma tout en admettant la nécessité de ces changements, est-il l’homme de la situation ? Son gouvernement répondra-t-il aux attentes des citoyens sud-africains ?

      \n
      \n

      Un mal fou (janvier 2016)

      \n

      14 janv. 2016 | Par

      \n

      J’ai une fringale d’aventure, d’aventures à venir. J’ai la fringale de la fringale des aventures et soudain, rupture. Je n’y arrive plus, tout est bloqué, tout empêché. Faut dire que depuis un an environ, tout est devenu plus compliqué. Ecrire va de moins en moins de soi.

      \n
      \n

      Redoublement : le changement à bas bruit ?

      \n

      17 janv. 2016 | Par

      \n

      S’il est une caractéristique de la forme scolaire française bien établie dans la culture des personnels, des élèves et des parents, c’est bien le redoublement, censé sanctionner des résultats insuffisants pour envisager le passage dans la classe supérieure. Or, en ce domaine, l’évolution est nette.

      \n
      \n

      Samedi-sciences (196): des chasseurs de mammouths en Arctique il y a 45 000 ans

      \n

      16 janv. 2016 | Par Michel de Pracontal

      \n

      Les restes d’un mammouth retrouvés en Arctique sibérien, datés de 45 000 ans, portent les traces de blessures infligées par des chasseurs humains. Les scientifiques pensaient jusqu’ici que notre espèce ne s’était pas aventurée dans cette région glaciale il y a plus de 30 000 ou 35 0000 ans. En réalité, des hommes ont réussi à survivre en Arctique au moins 10 000 ans plus tôt que l’on croyait.

      \n
      \n

      De la démocratie, du citoyen et de l'éthique

      \n

      14 janv. 2016 | Par

      \n

      Trois ouvrages sont parus au Seuil, qui font état de la nécessité d’intégrer le citoyen dans la gouvernance de la nation. Non pas à titre consultatif mais doté d’un pouvoir délibératif pour constituer une contre-force face aux clans politico-financiers qui dominent la vie publique.

      \n
      ", "mimetype": "text/html", "language": "fr", @@ -96,299 +96,5 @@ "domain_name": "www.nationaljournal.com", "preview_picture": "https://www.nationaljournal.com/media/media/2015/09/17/06Julian-Assange.jpg", "tags": [] - }, - { - "is_archived": 0, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 605, - "title": "What David Cameron did to the pig, his party is now doing to the country", - "url": "http://www.newstatesman.com/2015/09/what-david-cameron-did-pig-his-party-now-doing-country", - "content": "

      Whatever you do, don’t think about David Cameron and a dead pig. I know, I know it’s like trying not to think of an elephant, but the fact is that the allegations that the Prime Minister may have put a 'private part of his anatomy\" into a dead pig's mouth as part of an initiation ritual for an elite drinking society at Oxford University are actually a very serious matter, and it’s all about corruption and the nature of elected power, and it would help if we could all just calm down for a second and stop giggling. Don’t think I don’t see you at the back there.

      \n

      You know, I feel for David Cameron today, I really do. Politicians’ private sex lives should never be used against them - unless their particular proclivities implicate them in gross hypocrisy or they have harmed another human being. If the rumours are true, it’s unlikely that the pig in question was hurt by the Prime Minister’s ministrations, given that it was already missing its limbs and torso.

      \n

      Sniggering aside, this is unlikely to hurt David Cameron in the long run. He’s not looking for re-election, and besides, everyone knows posh people get up to weird sex stuff. Weird sex stuff is as British as weak tea and racism. When I was at Oxford, it was an open secret that the posh kids had naughty parties, and, of course, so did the rest of us - the difference was the much lower budget, and the fact that the posh kids didn’t seem to enjoy it as much as we did. It all seemed to be more about getting on than getting off. You didn’t shag or not shag the pig’s face because that was what you were into, you did it because you had your eye on a safe seat in Dorset in 20 years’ time and you needed to make the right friends.

      \n

      There is a reason that David Cameron is allowed to hold office when everyone assumes he spent the 1980s taking drugs and getting up to weird things with his Eton mates, but Jeremy Corbyn is considered unelectable because he didn’t sing the national anthem last week. Cameron is part of a select group of people to whom different rules apply, and he knows it, and his friends know it, and the tabloids know it, and the whole cosy British political machine knows it. This is why Corbyn will spend the next five years being savaged for having a slightly rumpled tie by the same newspapers that reported on the dead pig allegations under the title \"the making of an extraordinary Prime Minister\".

      \n

      The thing that's really horrifying about what has already been dubbed the 'Hameron' scandal is that it demonstrates what entitlement of this kind actually means, and how embarrassing it all is. There are people out there who can spend their early twenties in close proximity to cocaine and popping their peckers in offal and not even consider for a second that there might be anyone better placed to run the country. These are people who know the rules don’t apply to them, who know they can do whatever they want and still end up in charge.

      \n

      I don't honestly care whether or not David Cameron shagged a dead pig. I've been to enough house parties in Bethnal Green that this sort of thing doesn't shock me. Come back to me when there’s video evidence of Cameron dressed in a leather gimp-suit tanned from the flayed skins of the former shadow cabinet, leaping into an entire Shropshire field full of pigs and screaming that his name is Legion. Then we’ll talk. There are a lot of things that David Cameron has definitely done that I do find disgusting, though. Taking away benefits from sick and disabled people, pricing poor kids out of higher education, and forcing millions of families to rely on food banks. That, to me, is shocking and grotesque. I don't give a damn about what he did or didn’t do to that pig, and whether there was mood-lighting involved.

      \n

      But the fact is that a lot of people do, and they're precisely the sort of people whose votes Cameron has relied on to shore up the power he clearly feels is his by right, might and various dodgy initiation rituals involving sex workers, smashing up pubs and knobbing bits of meat. Cameron clearly believes those people are there to be manipulated, and that’s the reason this story actually matters, beyond the immediate risk that a handful of pearl-clutchers in the Home Counties might splutter themselves to death.

      \n

      I was explaining all this to an American friend who asked, not unreasonably, why I'd spent all morning scrolling through Twitter and cackling like a toddler with a nerf gun. I did my best to describe seriously what had happened, and my friend, who does not follow British politics, asked me, 'so this guy, was he elected or appointed?'

      \n

      The answer, of course, is both. David Cameron is not just prime minister because a quarter of the country voted for him. That's not how power works in Britain, or anywhere, and it's moments like this that show it plainly, which is why we're all vaguely embarrassed today. Cameron's route to the office he clearly believes himself born to began much earlier, possibly even on a balmy Oxford night, just Dave, a dead pig and a select group of wide-eyed, gurning future business leaders, all whooping and cheering.

      \n

      It would surely have been a moment more important to Cameron's career than any number of photoshoots with builders in Totnes. Power and money are accessed through the back door, or, as it may be, the pig's mouth, and as with any kink, the eroticism isn't about the act, but about what the act symbolises. It's about humiliation, about control, about power play. What might the young swain have been thinking as he unzipped? What went through his head? If you ask me, I'll bet he was thinking: Soon. Someday soon, I will do this to the whole bloody country.

      \n", - "annotations": [], - "mimetype": "text/html", - "language": "en", - "reading_time": 5, - "domain_name": "www.newstatesman.com", - "preview_picture": "http://www.newstatesman.com/sites/default/files/styles/thumb_730/public/blogs_2015/09/gettyimages-464604046.jpg?itok=EaABrZda", - "tags": [] - }, - { - "is_archived": 1, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 604, - "title": "CLICK HERE to support 2016 CES Winner, Revolutionary Auto-Tracking Robot", - "url": "https://www.indiegogo.com/projects/2016-ces-winner-revolutionary-auto-tracking-robot", - "content": "
      \n
      \n

      Sign Up for Inspiration

      \n

      Private, secure, spam-free

      \n

      Follow us

      \n
      \n
      \n

      About Indiegogo

      \n
      \n

      Language

      \n
      \n
      \n
      \n
      \n
      \n

      Campaigning

      \n
      \n
      \n

      Contributing

      \n
      \n
      \n

      Sign Up for Inspiration

      \n

      Private, secure, spam-free

      \n
      \n
      \n

      About Indiegogo

      \n
      \n
      \n

      Follow us

      \n
      \n
      \n

      Language

      \n
      \n
      \n
      \n
      ", - "annotations": [], - "mimetype": "text/html", - "reading_time": 0, - "domain_name": "www.indiegogo.com", - "preview_picture": "https://c1.iggcdn.com/indiegogo-media-prod-cld/image/upload/c_fill,f_auto,h_630,w_1200/v1447395263/d6ckex9ynild6ica1xdk.jpg", - "tags": [] - }, - { - "is_archived": 0, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 1, - "id": 603, - "title": "No title found", - "url": "http://carnetdevol.shost.ca/wordpress/aide-memoire-sur-les-commandes-associees-a-systemd/", - "content": "wallabag can't retrieve contents for this article. Please report this issue to us.", - "annotations": [], - "mimetype": "text/html", - "reading_time": 0, - "domain_name": "carnetdevol.shost.ca", - "tags": [] - }, - { - "is_archived": 1, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 602, - "title": "Présentation d'Arduino - Tuto Arduino - Le blog d'Eskimon", - "url": "http://eskimon.fr/73-arduino-101-presentation", - "content": "
      \n

      Comment faire de l’électronique en utilisant un langage de programmation ? La réponse, c’est le projet Arduino qui l’apporte. Vous allez le voir, celui-ci a été conçu pour être accessible à tous par sa simplicité. Mais il peut également être d’usage professionnel, tant les possibilités d’applications sont nombreuses.

      \n\n
      \n
      \n
      \n

      Qu’est-ce que c’est ?

      \n
      Une équipe de développeurs composée de Massimo Banzi, David Cuartielles, Tom Igoe, Gianluca Martino, David Mellis et Nicholas Zambetti a imaginé un projet répondant au doux nom de Arduino et mettant en œuvre une petite carte électronique programmable et un logiciel multiplateforme, qui puisse être accessible à tout un chacun dans le but de créer facilement des systèmes électroniques. Étant donné qu’il y a des débutants parmi nous, commençons par voir un peu le vocabulaire commun propre au domaine de l’électronique et de l’informatique.\n

      Une carte électronique

      \n

      Une carte électronique est un support plan, flexible ou rigide, généralement composé d’epoxy ou de fibre de verre. Elle possède des pistes électriques disposées sur une, deux ou plusieurs couches (en surface et/ou en interne) qui permettent la mise en relation électrique des composants électroniques. Chaque piste relie tel composant à tel autre, de façon à créer un système électronique qui fonctionne et qui réalise les opérations demandées.

      \n
      \"\"\"\"
      Exemples de cartes électroniques
      \n

      Évidemment, tous les composants d’une carte électronique ne sont pas forcément reliés entre eux. Le câblage des composants suit un plan spécifique à chaque carte électronique, qui se nomme le schéma électronique.

      \n
      \"\"
      Exemple de schéma électronique – carte Arduino Uno
      \n

      Enfin, avant de passer à la réalisation d’un carte électronique, il est nécessaire de transformer le schéma électronique en un schéma de câblage, appelé typon.

      \n
      \"\"
      Exemple de typon – carte Arduino
      \n

      Une fois que l’on a une carte électronique, on fait quoi avec ?

      \n

      Eh bien une fois que la carte électronique est faite, nous n’avons plus qu’à la tester et l’utiliser ! Dans notre cas, avec Arduino, nous n’aurons pas à fabriquer la carte et encore moins à la concevoir. Elle existe, elle est déjà prête à l’emploi et nous n’avons plus qu’à l’utiliser. Et pour cela, vous allez devoir apprendre comment l’utiliser, ce que je vais vous montrer dans ce tutoriel.

      \n

      Programmable ?

      \n

      J’ai parlé de carte électronique programmable au début de ce chapitre. Mais savez-vous ce que c’est exactement ? Non pas vraiment. Alors voyons ensemble de quoi il s’agit. La carte Arduino est une carte électronique qui ne sait rien faire sans qu’on lui dise quoi faire. Pourquoi ? Eh bien c’est du au fait qu’elle est programmable. Cela signifie qu’elle a besoin d’un programme pour fonctionner.

      \n

      Un programme

      \n

      Un programme est une liste d’instructions qui est exécuté par un système. Par exemple votre navigateur internet, avec lequel vous lisez probablement ce cours, est un programme. On peut analogiquement faire référence à une liste de course :

      \n
      \"\"
      \n

      Chaque élément de cette liste est une instruction qui vous dis : « Va chercher le lait » ou « Va chercher le pain », etc. Dans un programme le fonctionnement est similaire :

      \n
      • Attendre que l’utilisateur rentre un site internet à consulter
      • \n
      • Rechercher sur internet la page demandée
      • \n
      • Afficher le résultat
      • \n

      Tel pourrait être le fonctionnement de votre navigateur internet. Il va attendre que vous lui demandiez quelque chose pour aller le chercher et ensuite vous le montrer. Eh bien, tout aussi simplement que ces deux cas, une carte électronique programmable suit une liste d’instructions pour effectuer les opérations demandées par le programme.

      \n

      Et on les trouves où ces programmes ? Comment on fait pour le mettre dans la carte ? o_O

      \n

      Des programmes, on peut en trouver de partout. Mais restons concentré sur Arduino. Le programme que nous allons mettre dans la carte Arduino, c’est nous qui allons le réaliser. Oui, vous avez bien lu. Nous allons programmer cette carte Arduino. Bien sûr, ce ne sera pas aussi simple qu’une liste de course, mais rassurez-vous cependant car nous allons réussir quand même ! Je vous montrerais comment y parvenir, puisque avant tout c’est un des objectifs de ce tutoriel. Voici un exemple de programme : \"\" Vous le voyez comme moi, il s’agit de plusieurs lignes de texte, chacune étant une instruction. Ce langage ressemble à un véritable baragouin et ne semble vouloir à priori rien dire du tout… Et pourtant, c’est ce que nous saurons faire dans quelques temps ! Car nous apprendrons le langage informatique utilisé pour programmer la carte Arduino. Je ne m’attarde pas sur les détails, nous aurons amplement le temps de revenir sur le sujet plus tard. Pour répondre à la deuxième question, nous allons avoir besoin d’un logiciel…

      \n

      Et un logiciel ?

      \n

      Bon, je ne vais pas vous faire le détail de ce qu’est un logiciel, vous savez sans aucun doute de quoi il s’agit. Ce n’est autre qu’un programme informatique exécuté sur un ordinateur. Oui, pour programmer la carte Arduino, nous allons utiliser un programme ! En fait, il va s’agir d’un compilateur. Alors qu’est-ce que c’est exactement ?

      \n

      Un compilateur

      \n

      En informatique, ce terme désigne un logiciel qui est capable de traduire un langage informatique, ou plutôt un programme utilisant un langage informatique, vers un langage plus approprié afin que la machine qui va le lire puisse le comprendre. C’est un peu comme si le patron anglais d’une firme Chinoise donnait des instructions en anglais à un de ses ouvriers chinois. L’ouvrier ne pourrait comprendre ce qu’il doit faire. Pour cela, il a besoin que l’on traduise ce que lui dit son patron. C’est le rôle du traducteur. Le compilateur va donc traduire les instructions du programme précédent, écrites en langage texte, vers un langage dit « machine ». Ce langage utilise uniquement des 0 et des 1. Nous verrons plus tard pourquoi. Cela pourrait être imagé de la façon suivante :

      \n
      \"\"
      \n

      Donc, pour traduire le langage texte vers le langage machine (avec des 0 et des 1), nous aurons besoin de ce fameux compilateur. Et pas n’importe lequel, il faut celui qui soit capable de traduire le langage texte Arduino vers le langage machine Arduino. Et oui, sinon rien ne va fonctionner. Si vous mettez un traducteur Français vers Allemand entre notre patron anglais et son ouvrier chinois, ça ne fonctionnera pas mieux que s’ils discutaient directement. Vous comprenez ?

      \n

      Et pourquoi on doit utiliser un traducteur, on peut pas simplement apprendre le langage machine directement ?

      \n

      Comment dire… non ! Non parce que le langage machine est quasiment impossible à utiliser tel quel. Par exemple, comme il est composé de 0 et de 1, si je vous montre ça : « 0001011100111010101000111 », vous serez incapable, tout comme moi, de dire ce que cela signifie ! Et même si je vous dis que la suite « 01000001 » correspond à la lettre « A », je vous donne bien du courage pour coder rien qu’une phrase ! 😛 Bref, oubliez cette idée. C’est quand même plus facile d’utiliser des mots anglais (car oui nous allons être obligé de faire un peu d’anglais pour programmer, mais rien de bien compliqué rassure-vous) que des suites de 0 et de 1. Vous ne croyez pas ?

      \n

      Envoyer le programme dans la carte

      \n

      Là, je ne vais pas vous dire grand chose car c’est l’environnement de développement qui va gérer tout ça. Nous n’aurons qu’à apprendre comment utiliser ce dernier et il se débrouillera tout seul pour envoyer le programme dans la carte. Nah ! Nous n’aurons donc qu’à créer le programme sans nous soucier du reste.

      \n
      \n
      \n
      \n

      Pourquoi choisir Arduino ?

      \n
      \n

      Que va-t-on faire avec ?

      \n

      Avec Arduino, nous allons commencer par apprendre à programmer puis à utiliser des composants électroniques. Au final, nous saurons créer des systèmes électroniques plus ou moins complexes. Mais ce n’est pas tout…

      \n

      D’abord, Arduino c’est…

      \n

      … une carte électronique programmable et un logiciel gratuit :

      \n
      \"\"
      \n

      Mais aussi

      \n

      – Un prix dérisoire étant donné l’étendue des applications possibles. On comptera 20 euros pour la carte que l’on va utiliser dans le cours. Le logiciel est fournit gratuitement ! – Une compatibilité sous toutes les plateformes, à savoir : Windows, Linux et Mac OS. – Une communauté ultra développée ! Des milliers de forums d’entre-aide, de présentations de projets, de propositions de programmes et de bibliothèques, … – Un site en anglais arduino.cc et un autre en français arduino.cc où vous trouverez tout de la référence Arduino, le matériel, des exemples d’utilisations, de l’aide pour débuter, des explications sur le logiciel et le matériel, etc. – Une liberté quasi absolue. Elle constitue en elle même deux choses :

      \n
      • Le logiciel : gratuit et open source, développé en Java, dont la simplicité d’utilisation relève du savoir cliquer sur la souris
      • \n
      • Le matériel : cartes électroniques dont les schémas sont en libre circulation sur internet
      • \n

      Cette liberté a une condition : le nom « Arduino » ne doit être employé que pour les cartes « officielles ». En somme, vous ne pouvez pas fabriquer votre propre carte sur le modèle Arduino et lui assigner le nom « Arduino ».

      \n

      Et enfin, les applications possibles

      \n

      Voici une liste non exhaustive des applications possible réalisées grâce à Arduino :

      \n
      • contrôler des appareils domestiques
      • \n
      • donner une « intelligence » à un robot
      • \n
      • réaliser des jeux de lumières
      • \n
      • permettre à un ordinateur de communiquer avec une carte électronique et différents capteurs
      • \n
      • télécommander un appareil mobile (modélisme)
      • \n
      • etc.
      • \n

      Il y a tellement d’autres infinités d’utilisations, vous pouvez simplement chercher sur votre moteur de recherche préféré ou sur Youtube le mot « Arduino » pour découvrir les milliers de projets réalisés avec !

      \n

      Arduino dans ce tutoriel

      \n

      Je vais quand même rappeler les principaux objectifs de ce cours. Nous allons avant tout découvrir Arduino dans son ensemble et apprendre à l’utiliser. Dans un premier temps, il s’agira de vous présenter ce qu’est Arduino, comment cela fonctionne globalement, pour ensuite entrer un peu plus dans le détail. Nous allons alors apprendre à utiliser le langage Arduino pour pouvoir créer des programmes très simple pour débuter. Nous enchainerons ensuite avec les différentes fonctionnalités de la carte et ferons de petits TP qui vous permettront d’assimiler chaque notion abordée. Dès lors que vous serez plutôt à l’aise avec toutes les bases, nous nous rapprocherons de l’utilisation de composants électroniques plus ou moins complexes et finirons par un plus « gros » TP alliant la programmation et l’électronique. De quoi vous mettre de l’eau à la bouche ! 😛

      \n

      Arduino à l’école ?

      \n

      Pédagogiquement, Arduino a aussi pas mal d’atout. En effet, ses créateurs ont d’abord pensé ce projet pour qu’il soit facile d’accès. Il permet ainsi une très bonne approche de nombreux domaines et ainsi d’apprendre plein de choses assez simplement.

      \n

      Des exemples

      \n

      Voici quelques exemples d’utilisation possible :

      \n
      • Simuler le fonctionnement des portes logiques
      • \n
      • Permettre l’utilisation de différents capteurs
      • \n
      • Mettre en œuvre et faciliter la compréhension d’un réseau informatique
      • \n
      • Se servir d’Arduino pour créer des maquettes animées montrant le fonctionnement des collisions entres les plaques de la croute terrestre, par exemple \":mrgreen:\"
      • \n
      • Donner un exemple concret d’utilisation des matrices avec un clavier alphanumérique 16 touches ou plus
      • \n
      • Être la base pour des élèves ayant un TPE à faire pour le BAC
      • \n
      • …
      • \n

      De plus, énormément de ressources et tutoriels (mais souvent en anglais) se trouvent sur internet, ce qui offre un autonomie particulière à l’apprenant.

      \n

      Des outils existant !

      \n

      Enfin, pour terminer de vous convaincre d’utiliser Arduino pour découvrir le monde merveilleux de l’embarqué, il existe différents outils qui puissent être utilisé avec Arduino. Je vais en citer deux qui me semble être les principaux : Ardublock est un outil qui se greffe au logiciel Arduino et qui permet de programmer avec des blocs. Chaque bloc est une instruction. On peut aisément faire des programmes avec cet outil et mêmes des plutôt complexes. Cela permet par exemple de se concentrer sur ce que l’on doit faire avec Arduino et non se concentrer sur Arduino pour ensuite ce que l’on doit comprendre avec. Citons entre autre la simulation de porte logique : plutôt créer des programmes rapidement sans connaitre le langage pour comprendre plus facilement comment fonctionne une porte logique. Et ce n’est qu’un exemple. Car cela permet aussi de permettre à de jeunes enfants de commencer à programmer sans de trop grandes complications.

      \n
      \"\"\"\"\"\"
      Exemple de programmes réalisés avec Ardublock
      \n

      Processing est une autre plateforme en lien avec Arduino. Là il n’y a pas de matériel, uniquement un logiciel. Il permet entre autre de créer des interfaces graphiques avec un langage de programmation très similaire à celui d’Arduino. Par contre, cela demande un niveau un peu plus élevé pour pouvoir l’utiliser, même si cela reste simple dans l’ensemble.

      \n
      \"\"
      Voilà un exemple de ce que j’avais réalisé avec Processing pour faire communiquer mon ordinateur avec ma carte Arduino
      \n

      J’espère avoir été assez convaincant afin que vous franchissiez le pas et ayez du plaisir à apprendre ! \":)\"

      \n
      \n
      \n
      \n

      Les cartes Arduino

      \n
      Le matériel que j’ai choisi d’utiliser tout au long de ce cours n’a pas un prix excessif et, je l’ai dit, tourne aux alentours de 25 € TTC. Il existe plusieurs magasins en lignes et en boutiques qui vendent des cartes Arduino. Je vais vous en donner quelques-uns, mais avant, il va falloir différencier certaines choses.\n

      Les fabricants

      \n

      Le projet Arduino est libre et les schémas des cartes circulent librement sur internet. D’où la mise en garde que je vais faire : il se peut qu’un illustre inconnu fabrique lui même ses cartes Arduino. Cela n’a rien de mal en soi, s’il veut les commercialiser, il peut. Mais s’il est malhonnête, il peut vous vendre un produit défectueux. Bien sûr, tout le monde ne cherchera pas à vous arnaquer. Mais la prudence est de rigueur. Faites donc attention où vous achetez vos cartes.

      \n

      Les types de cartes

      \n
      \"\"
      \n

      Il y a trois types de cartes :

      \n
      • Lesdites « officielles » qui sont fabriquées en Italie par le fabricant officiel : Smart Projects
      • \n
      • Lesdits « compatibles » qui ne sont pas fabriqués par Smart Projects, mais qui sont totalement compatibles avec les Arduino officielles.
      • \n
      • Les « autres » fabriquées par diverse entreprise et commercialisées sous un nom différent (Freeduino, Seeduino, Femtoduino, …).
      • \n

      Les différentes cartes

      \n

      Des cartes Arduino il en existe beaucoup ! Voyons celles qui nous intéressent… La carte Uno et Duemilanove Nous choisirons d’utiliser la carte portant le nom de « Uno » ou « Duemilanove ». Ces deux versions sont presque identiques.

      \n
      \"\"\"\"
      Carte Arduino « Duemilavove » et « Uno » avec laquelle nous allons travailler
      \n

      La carte Mega La carte Arduino Mega est une autre carte qui offre toutes les fonctionnalités de la carte précédente, mais avec des fonctionnalités supplémentaires. On retrouve notamment un nombre d’entrées et de sorties plus important ainsi que plusieurs liaisons séries. Bien sûr, le prix est plus élevé : > 40 € !

      \n
      \"\"
      Carte Arduino « Mega »
      \n

      Les autres cartes Il existe encore beaucoup d’autres cartes, je vous laisse vous débrouiller pour trouver celle qui conviendra à vos projets. Cela dit, je vous conseil dans un premier temps d’utiliser la carte Arduino Uno ou Duemilanove d’une part car elle vous sera largement suffisante pour débuter et d’autre part car c’est avec celle-ci que nous présentons le cours.

      \n

      Où acheter ?

      \n

      Il existe sur le net une multitude de magasins qui proposent des cartes Arduino. Pour consulter la liste de ces magasins, rien de plus simple, il suffit de vous rendre sur le forum dédié :

      \n\n

      J’ai vu des cartes officielles « édition SMD/CMS ». Ca à l’air bien aussi, c’est quoi la différence ? Je peux m’en servir ?

      \n

      Il n’y a pas de différence ! enfin presque… « SMD » signifie Surface Mount Device, en français on appelle ça des « CMS » pour Composants Montés en Surface. Ces composants sont soudés directement sur le cuivre de la carte, il ne la traverse pas comme les autres. Pour les cartes Arduino, on retrouve le composant principal en édition SMD dans ces cartes. La carte est donc la même, aucune différence pour le tuto. Les composants sont les mêmes, seule l’allure « physique » est différente. Par exemple, ci-dessus la « Mega » est en SMD et la Uno est « classique ».

      \n
      \n
      \n
      \n

      Liste d’achat

      \n
      Tout au long du cours, nous allons utiliser du matériel en supplément de la carte. Rassurez-vous le prix est bien moindre. Je vous donne cette liste, cela vous évitera d’acheter en plusieurs fois. Vous allez devoir me croire sur parole sur leur intérêt. Nous découvrirons comment chaque composant fonctionne et comment les utiliser tout au long du tutoriel. \":)\"

      Attention, cette liste ne contient que les composants en quantités minimales strictes. Libre à vous de prendre plus de LED et de résistances par exemple (au cas où vous en perdriez ou détruisiez…). Pour ce qui est des prix, j’ai regardé sur différents sites grands publics (donc pas Farnell par exemple), ils peuvent donc paraître plus élevé que la normale dans la mesure où ces sites amortissent moins sur des ventes à des clients fidèles qui prennent tout en grande quantité…

      \n

      Avant que j’oublie, quatres éléments n’apparaitront pas dans la liste et sont indispensables :

      \n\n\n\n\n
      Une Arduino Uno ou DuemilanoveUn câble USB A mâle/B mâle
      \"\"\"\"
      \n\n\n\n
      Une BreadBoard (plaque d’essai)Un lot de fils pour brancher le tout !
      \"\"\"\"

      Liste Globale

      \n

      Voici donc la liste du matériel nécessaire pour suivre le cours. Libre à vous de tout acheter ou non.

      \n
      Liste incomplète, le tutoriel n’est pas terminé ! Mais elle suffit pour suivre les chapitres en ligne.
      \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
      DésignationQuantitéPhotoDescription
      LED rouge7\"\"Ce composant est une sorte de lampe un peu spécial. Nous nous en servirons principalement pour faire de la signalisation.
      LED verte3
      LED jaune (ou orange)2
      Résistance (entre 220 et 470 Ohm)10\"\"La résistance est un composant de base qui s’oppose au passage du courant. On s’en sert pour limiter des courants maximums mais aussi pour d’autres choses.
      Résistance (entre 2.2 et 4.7 kOhm)2
      Résistance (10 kOhm)2
      Bouton Poussoir2\"\"Un bouton poussoir sert à faire passer le courant lorsqu’on appuie dessus ou au contraire garder le circuit « éteint » lorsqu’il est relâché.
      Transistor (2N2222 ou BC547)2\"\"Le transistor sert à plein de chose. Il peut être utilisé pour faire de l’amplification (de courant ou de tension) mais aussi comme un interrupteur commandé électriquement.
      Afficheur 7 segments (anode commune)2\"\"Un afficheur 7 segments est un ensemble de LEDs (cf. ci-dessus) disposées géométriquement pour afficher des chiffres.
      Décodeur BCD (CD4543BE)1\"\"Le décodeur BCD (Binaire Codé Décimal) permet piloter des afficheurs 7 segments en limitant le nombre de fils de données (4 au lieu de 7).
      Condensateur (10nF/5V ou plus)2\"\"Le condensateur est un composant de base. Il sert à plein de chose. On peut se le représenter comme un petit réservoir à électricité.
      Condensateur (1000µF 15V ou plus1\"\"Celui-ci est un plus gros réservoir que le précédent
      Potentiomètre linéaire (10 kOhm)1\"\"Le potentiomètre est une résistance que l’on peut faire varier manuellement.
      LED RVB1\"\"Une LED RVB (Rouge Vert Bleu) est une LED permettant de mélanger les couleurs de bases pour en créer d’autres.
      Écran LCD alphanumérique1\"\"L’écran LCD alphanumérique permet d’afficher des caractères tels que les chiffres et les lettres. Il va apporter de l’interactivité à vos projets les plus fous !

      Les revendeurs

      \n

      Je vous ai déjà donné le lien, vous pourrez trouver ces composants chez les revendeurs listés dans ce sujet du forum :

      \n\n

      Les kits

      \n

      Enfin, il existe des kits tout prêts chez certains revendeurs. Nous n’en conseillerons aucun pour plusieurs raisons. Tout d’abord, pour ne pas faire trop de publicité et rester conforme avec la charte du site. Ensuite, car il est difficile de trouver un kit « complet ». Ils ont tous des avantages et des inconvénients mais aucun (au moment de la publication de ces lignes) ne propose absolument tous les composants que nous allons utiliser. Nous ne voulons donc pas que vous reveniez vous plaindre sur les forums car nous vous aurions fait dépenser votre argent inutilement !

      \n
      Cela étant dit, merci de ne pas nous spammer de MP pour que l’on donne notre avis sur tel ou tel kit ! Usez des forums pour cela, il y a toujours quelqu’un qui sera là pour vous aider. Et puis nous n’avons pas les moyens de tous les acheter et tester leur qualité !
      \n
      \n
      \n
      \n
      \n
      \n\n\n", - "annotations": [], - "mimetype": "text/html", - "language": "fr-FR", - "reading_time": 17, - "domain_name": "eskimon.fr", - "preview_picture": "http://eskimon.fr/wp-content/uploads/tuto/385800.jpg", - "tags": [] - }, - { - "is_archived": 1, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 543, - "title": "Lenovo ThinkPad X1 Carbon Ultrabook Review", - "url": "http://www.notebookcheck.net/Lenovo-ThinkPad-X1-Carbon-Ultrabook-Review.138033.0.html", - "content": "

      The Lenovo X1 Carbon 3rd Gen is a beautiful machine. Much like the Dell XPS 13 took the initiative to cram a 13-inch screen into an 11-inch form factor, the X1 Carbon sports dimensions that are more comparable to a typical 13-inch machine—and that includes its weight and thinness, both of which are indisputably manageable. It’s also practically designed; the matte black surfaces that comprise the majority of the case are minimalist and attractive, but they’re simultaneously haptically comfortable, with an unmistakably cool metal feel and a comfortable fit for use on both lap and desk. The case also feels fairly solid, though the incidence of flex and relative lack of torsion resistance in some regards gave us pause.

      \n

      Perhaps more exciting, however, is what has improved over the X1 Carbon 2nd Gen. Criticism of the 2nd Gen’s radical (and arguably illogical) keyboard design and polarizing full-depression clickpad scared away many prospective buyers—as such fearlessly progressive and experimental design decisions generally don’t fit well with the business market, where practicality rules supreme. The Gen 3 wholeheartedly acknowledges these complaints and implements a complete reversal of those decisions. As a result, the keyboard—immediately familiar and accessible—is one of the absolute best we have ever used on an Ultrabook. Meanwhile, the three classic top-mounted physical buttons for use with the Trackpoint have returned, and the touchpad itself ditches the controversial full-click design in favor of a far more comfortable (and, in our judgment, reliable) clickpad approach. The end result is that the X1 Carbon Gen 3 features some of the best input devices we’ve tested on an Ultrabook.

      \n

      What about performance? CPU performance differences between the 2nd Gen and 3rd Gen X1 Carbon models were essentially nil in our testing—for all intents and purposes, the machines are identical in this regard. However in GPU testing, we witnessed a notable speed boost—in some cases up to 19% better. As compared with other modern notebooks of its class, apart from some multi-core synthetic performance hiccups, the X1 Carbon 3rd Gen holds its own, both in terms of CPU/GPU and general system performance. The only final niggle here is the Samsung PM851 SSD, whose write speeds are conspicuously capped at around 250 MB/s.

      \n

      While the leap to a Broadwell chipset and slightly larger battery seemed sure to promise improved battery runtimes, we were surprised to find throughout our testing that there wasn’t much of a difference at all. Our classic Wi-Fi Surfing Test produced a result only slightly better than that of the 2nd Gen, and the revised Wi-Fi test we just recently implemented—which is more broad and aggressive and arguably closer to actual real-world usage patterns—recorded under five hours before the machine shut down. That’s hardly an impressive number on one hand given the 50 Wh battery and supposed enhanced efficiency, though it’s still likely to get most users through a typical trip unplugged, especially if more restrictive power savings options are employed. If longer battery life is a priority, we’d suggest taking a look instead at the Dell XPS 13-9343 or the MacBook Air 13.

      \n

      Rounding out the list of considerations is an underwhelming screen, at least in terms of brightness, contrast, and color saturation—though we do most certainly appreciate the anti-glare display filter for both its diffusion of reflections and relative ease of cleaning. The X1 Carbon Gen 3 is also invariably cool and quiet, clearly favoring comfort over top-end performance (as we discovered during our stress testing of the device).

      \n

      Summing up, the X1 Carbon Gen 3 is indisputably superior to its predecessor. Although some of these improvements come in the form of better GPU performance, cooler temperatures, and lower average system noise levels, the vast majority of them center on the thankful retreat from the experimental (and finicky) input devices of the Gen 2 design and back to sanity. This isn’t just a return to form, either; to reiterate, by our judgment, they are some of the best input devices on any Ultrabook we’ve tested to date. But in spite of this self-improvement, how does the X1 Carbon compare with its modern competitors? In truth, though it’s a compelling option, it’s lost some ground since our last encounter. While notebooks such as the MacBook Air 13 and (especially) the Dell XPS 13-9343 have sprinted forward with such massive improvements in portability, battery life, and LCD quality, the X1 Carbon 3rd Gen has only marginally improved, mostly regaining footing it’s lost elsewhere. It’s still a strong contender, and it’s certainly the best Carbon to date, but especially at a pricey $1,574, we fear that its inability to innovate further may relegate it to the shadows of these more aggressive contenders.

      \n", - "annotations": [], - "mimetype": "text/html", - "language": "en", - "reading_time": 3, - "domain_name": "www.notebookcheck.net", - "preview_picture": "http://www.notebookcheck.net/fileadmin/Notebooks/Lenovo/ThinkPad_X1_Carbon_2015/x12015.jpg", - "tags": [] - }, - { - "is_archived": 0, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 541, - "title": "Visitons le Château de Landsberg !", - "url": "http://autour-du-mont-sainte-odile.overblog.com/2016/01/visitons-le-chateau-de-landsberg.html", - "content": "

      Situé au dessus de Heiligenstein et de Barr, à mi-hauteur de la montée vers plateau de la Bloss, le château de Landsberg est un but de promenade apprécié des randonneurs et des amateurs de vieilles pierres. Posé sur un éperon de granite, visible de loin, la forteresse médiévale domine fièrement la plaine d’Alsace.

      \n

      \"Visitons

      \n

      Le château primitif

      \n

      Fin du onzième siècle, Philippe de Souabe et Otton de Brunswick se disputent le trône impérial. Philippe, tenant des Hohenstaufen, veut conforter la puissance des couvents du Mont Sainte Odile. Il s’appuie sur un de ses représentants pour construire une nouvelle forteresse sur le Mont. Conrad de Vinhege érige le château de Landsberg dont sa famille prendra bientôt le nom. Nous sommes en 1197-1198. Le burg est construit sur les terres de l’abbaye de Niedermunster, le Couvent du Bas du Mont Sainte Odile. Un acte est signé de l’Abbesse Edelinde, il est daté du 23 juin 1200, il confirme la cession du terrain au chevalier Conrad.
      Nous avons publié le texte de l’abbesse Edelinde, l’an passé. (cliquez sur le lien)
      Ce premier château n’avait pas l’importance des ruines que nous pouvons admirer aujourd’hui. Il ne comportait qu’un donjon et un corps de logis, complété par une basse-cour. Commençons la visite des ruines par cette partie. Le donjon est construit sur un carré de dix mètres de côté. Puissant, placé en diagonale par rapport au corps de logis, il formait bouclier pour défendre celui-ci du côté de la plaine, au nord-est. En levant la tête, le visiteur découvre l’accès : une porte haute, qui était accessible par un pont volant à partir de l’étage du logis seigneurial. Tout en haut du donjon, on distingue encore les corbeaux qui portaient les hourds. Les hourds, constructions de bois, ancêtres des mâchicoulis, permettaient aux défenseurs de surplomber les assaillants du château.
      \"VisitonsLe logis seigneurial comportait un rez-de-chaussée dédié à l’usage domestique : cuisines, citerne, salle des gardes. Ces pièces basses n’étaient éclairées que par quelques meurtrières. Le premier étage était l’habitation de Conrad et de ses successeurs : la façade nord-est est largement éclairée par quatre baies géminées en plein-cintre. Les fenêtres doubles sont séparées par de fines colonnes et surmontées d’élégants occuli. Au sud-est, deux doubles baies et un magnifique oriel agrémentent la façade. Situé sur le coté de la porte du château, cet élément de décor est le plus frappant du site du Landsberg, un genre d’échauguette semi-cylindrique, portée par un cul de lampe conique. Nous serions là dans la chapelle castrale du Landsberg. Coté extérieur, deux petites sculptures ornent la base de l’oriel : une fleur de lys et un petit personnage accroupi. A l’intérieur, une frise d’arceaux délimite les petites fenêtres du chœur de la chapelle. L’une d’elles a la forme d’une croix. Admirez la finesse des dessins du chapiteau de la colonne toujours en place au droite de l’oriel !
      Le château de Landsberg est situé à la limite géologique des grès, prédominants au nord, et des granites d’Andlau, côté sud. Les bases et les assises de la forteresse sont en granite, roche dure extraite du fossé creusé au nord, par les carriers du moyen âge. Les parties hautes sont en grès rose du Maennelstein, plus facile à travailler.

      \n

      Le château neuf

      \n

      Ce premier château était, somme toute, de dimensions modestes. Quelques dizaines d’ années plus tard, preuve de l’importance des couvents du Mont Sainte Odile et signe de la puissance croissante de la famille de Landsberg, le site fut agrandi de façon conséquente. Nous sommes alors en 1240-1250.
      L’extension se fait au nord-ouest. Les deux tours rondes et l’imposante courtine délimitent l’emprise du Château Neuf. A l’origine, cette nouvelle enceinte était détachée du vieux burg, les deux sites ne furent rattachés que postérieurement. Les tours circulaires mesurent environ sept mètres de diamètre. Leur sommet portaient des créneaux. Un chemin de ronde surmontait la courtine : il était garni de hourds et traversait les deux tours. Archères et bretèches sont toutes orientées au nord, côté montagne, là où le risque d’attaque était le plus grand.
      Deux corps de logis se partageaient le site. Au sud, le bâtiment ne comportait qu’un seul étage, éclairé au sud-ouest par des fenêtres à banquettes, aujourd’hui murées. Le deuxième bâtiment, côté nord, fut construit plus tard. Composé de deux étages, il communiquait directement avec la tour nord.
      L’ensemble a connu plusieurs remaniements au cours des siècles.

      \n

      \"Visitons

      \n

      Les extensions du XVème et du XVIème siècles

      \n

      L’apparition des armes à feu modifie l’art de la guerre. La géométrie des châteaux doit s’adapter aux armes nouvelles : résister aux boulets et accueillir couleuvrines et canons. Tous les châteaux des Vosges n’ont pas connu cette évolution, certains, trop solitaires, trop isolés, ont été abandonnés dés cette époque. Au Landsberg, les seigneurs ont respecté le vieux burg dans sa forme initiale, mais ils l’ont adapté tout d’abord en renforçant ses murs, puis en l’entourant de nouvelles murailles. Au nord, le château neuf se voit délaissé, ses nombreuses ouvertures extérieures sont murées, à part les archères, bien entendu. Ses courtines sont prolongées pour assurer la continuité avec celles du vieux burg. Un puissant bastion est construit au sud-est. Les armes nouvelles sont mises en place : couleuvrines, poivrière portant une canonnière protégée par des vastes vantaux. Ainsi, un vaste glacis s’étend devant la forteresse. C’est en faisant le tour du château dans les fossés que le promeneur se rendra le mieux compte de la force de la place et de son adaptation aux débuts de l’artillerie.
      \"VisitonsQuelques temps, le château est passé des Landsberg au Comte Palatin, avant de revenir à la famille qui resta maître des lieux jusqu’à la Révolution.
      On ne trouve guère de textes relatant l’histoire du château de Landsberg dans les temps troublés que connut l’Alsace. Lors de la Guerre du Bundschuh, les paysans révoltés s’étaient installés dans la prévôté de Truttenhausen, toute proche. Cependant, rien ne dit que les Rustauds aient attaqué le château. Lors de la Guerre de Trente Ans, il semble que les troupes de Mansfeld, puis les Suédois se soient plutôt attaqués aux riches villes de la plaine, comme Obernai, oubliant les forteresses de montagne, déjà devenues inutiles. Cependant, le château est décrit comme ruiné au milieu du XVIIème siècle.
      Depuis longtemps, les Landsberg avaient délaissé le burg de leurs ancêtres pour lui préférer leur résidence de Niedernai, située en plaine. Le château fut confié à des gardes, puis servit de ferme. Aujourd’hui, les ruines du Landsberg sont une propriété privée. Merci à vous de respecter le site.

      \n

      Dans la basse cour du château fleurit au printemps, l’éranthe d’hiver. Sa floraison ne dure que quelques jours. Cette petite fleur jaune est rare sous nos climats. De son nom latin ‘Eranthis hyemalis’, l’éranthe est originaire d’Italie ou de Turquie. La légende nous dit qu’elle aurait été rapportée des croisades par un sire de Landsberg. Elle serait un remède à la mélancolie.

      \n

      Promenade et accès au château de Landsberg\"Visitons

      \n

      Les automobilistes pourront garer leur véhicule sur le petit parking situé à l’ouest d’Heiligenstein. Ils gagneront Truttenhausen sur la petite route à travers prés. Un sentier du Club Vosgien ( disque bleu ) monte vers les ruines.
      Les marcheurs préfèreront effectuer une boucle à partir de Saint-Jacques, par exemple. Saint-Jacques, Kapellenhausfelsen, Ameisenberg, Landsberg ( balisage : triangle bleu ) avec un retour sur Saint-Jacques par le sentier sans dénivelé ( rectangle : bicolore rouge et blanc).
      A moins qu’ils ne préfèrent rechercher les pierres sculptées du Chemin des Chameaux. (cliquez sur le lien ), ou découvrir la Chapelle du Frère Léon dans la vallée de la Kirneck.

      \n

      Illustrations

      \n
      • Photographies du château de Landsberg ( BrR, FrP et PiP)
      • \n
      • Schéma des ruines ( PiP)
      • \n
      • L’Orgueil, Herrade de landsberg, Hortus Deliciarum
      • \n
      • Les Ruines du Landsberg, aquarelle de Osterwald, 1873
      • \n
      \n", - "annotations": [], - "mimetype": "text/html", - "language": "fr", - "reading_time": 7, - "domain_name": "autour-du-mont-sainte-odile.overblog.com", - "preview_picture": "http://img.over-blog-kiwi.com/0/28/39/78/20160128/ob_68f59d_12.jpg", - "tags": [] - }, - { - "is_archived": 1, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 454, - "title": "Contrer les stéréotypes par les livres : “C'est dès l'enfance qu'ils se construisent”", - "url": "https://www.actualitte.com/article/monde-edition/contrer-les-stereotypes-par-les-livres-c-est-des-l-enfance-qu-ils-se-construisent/64058", - "content": "

      Même dans l'espace jeunesse d'un immense salon littéraire, difficile de passer à côté du livre de coloriage féministe — et fier de l'être — de la maison d'édition Goater. Cette structure atypique, adossée à un bar de Rennes, Le Papier-Timbré, propose des titres tout aussi uniques, de ces livres que l'on devine importants avant même de les ouvrir.

      \n\n

      \"Livre

      \n

      Judikael et Jean-Marie Goater (ActuaLitté, CC BY SA 2.0)

      \n\n\n

      Le Papier-Timbré et les éditions Goater avancent main dans la main, dans une même structure, depuis 2009. En plus de la licence IV, permis de publier : « On est très occupé par les soirées étudiantes et festives, mais on développe en plus des projets autour des livres qui, parfois, émergent d'ailleurs avec la clientèle. C'est surtout un motif supplémentaire pour se retrouver et partager des moments de convivialité, partager des goûts, des envies, de la littérature, des essais et de la jeunesse », explique Jean-Marie Goater.

      \n

      \n

      En plus de la production maison, le café-librairie propose celle de maisons soeurs : les éditions de juillet, L'Oeuf, les Éditions Pontcerq, essentiellement des petits éditeurs de Rennes et de la Bretagne. La maison est diffusée et distribuée en Bretagne par Coop Breizh, diffusé par Hobo Diffusion, distribué par Makassar pour la France (comme les éditions surréalistes Prairial). Les tirages vont de 500 exemplaires à 3000 sauf exceptions et coéditions comme Détachez vos ceintures, projet collectif des éditions du Kyste contre l'aéroport de Notre-Dame-des-Landes, ou Galette-saucisse, je t’aime ! de Benjamin Keltz, avec les Éditions du coin de la rue.

      \n

      \n

      Mon premier cahier de coloriage féministe ! sera en librairie d'ici quelques jours, et la maison Goater y croit dur comme fer : « Nous avons commencé par traduire et adapter C'est quoi ton genre ?, un livre écrit par Jacinta Bunnell et publié par l'éditeur anarchiste américain PM Press », explique Jean-Marie Goater. Dans les pages du livre, on croise des monstres qui aiment les petits sacs à main et les chaussures, des princesses qui ne suivent pas vraiment le dress code, ou des enfants en fauteuil roulant, encore rares dans les livres jeunesse.

      \n

      \n

      \"Livre

      \n

      (ActuaLitté, CC BY SA 2.0)

      \n

      \n

      \n

      Après cette publication, la maison a souhaité développer un projet en France, en réunissant 16 dessinatrices dont 4 dessinateurs pour leur proposer d'expliquer le féminisme aux enfants, à travers un dessin. « Le livre aborde la vie à l'école, les habillements, les métiers, le sport, mais aussi les quelques femmes féministes importantes de l'histoire... Ça reste ludique et sans prétention encyclopédique sur le féminisme, mais il est plus simple d'aborder le sujet avec un support comme celui-ci à la maison, à l'école ou au centre de loisirs. » Comme le précédent, l'ouvrage présente d'une nouvelle manière les situations traditionnelles des livres de coloriage ou jeunesse.

      \n

      \n

      Des ressources rares, des besoins importants

      \n

      \n

      Pas la peine d'insister pour que Jean-Marie Goater partage son avis : « La production majoritaire est quand même très caricaturale et stéréotypée, cependant on remarque depuis quelques années des éditeurs intéressants qui essaient de bousculer un peu ces stéréotypes comme La Ville Brûle, ou encore l'édition LGBT qui commence à arriver avec Des ailes sur un tracteur qui a publié un cahier de coloriage avec Sophie Labelle, plutôt sur les questions trans. »

      \n

      \n

      Contrairement à ce que les détracteurs des livres jeunesse atypiques prétendent (coucou, Jean-François Copé), lutter contre les stéréotypes n'a rien d'une guerre de civilisation ou autre affabulation du genre. Il s'agit simplement de montrer que chacun doit être fier de ce qu'il est, respecter ce que l'autre est, et ne pas chercher l'assentiment des uns ou des autres. « Fuck the world », comme dirait 2Pac... « Se poser ces questions est indispensable, il faut qu'il y ait ce débat : les enfants ne sont pas si naïfs que ça, ils ont besoin de se poser ce genre de questions. »

      \n

      \n

      \"Livre

      \n

      (ActuaLitté, CC BY SA 2.0)

      \n

      \n

      \n

      Judikael, venu aider son père, acquiesce : il a répondu à l'appel à dessins et proposé une activité dans le cahier de coloriage féministe. « Ce genre de ressources pour enfant est important, parce que c'est dès l'enfance que se construisent certains préjugés, certains stéréotypes qui restent ensuite. Quand on voit que 90 % des personnes présentes dans les manuels scolaires sont des hommes par exemple, ce genre d'ouvrages permet à certaines personnes de se reconnaître davantage dans certains rôles, qu'on ne leur attribue pas forcément de base. »

      \n

      \n

      Là est la lutte, résumée par Judikael : « On parle souvent de “déconstruire” dans le féminisme, les préjugés ou autre, ces livres peuvent permettre d'éviter de les construire. » En Terminale L, Judikael confirme que les préjugés sont toujours présents, forcément surtout en sport ou vis-à-vis de « la filière homme » (comprendre, la filière scientifique) et de « la filière femme » (comprendre, la filière littéraire). Si l'histoire du féminisme est désormais abordée en classe, certains sujets restent touchy : le journal du lycée s'est vu censurer un article sur la culture du viol, et la ségrégation hommes-femmes, « au prétexte que c'était trop hard, que les lycéens n'allaient pas comprendre »...

      \n

      \n

      « L'édition, c'est un milieu qui est quand même très hypocrite »

      \n

      \n

      À votre avis, comment réagit l'éditeur de Mon premier cahier de coloriage féministe lorsqu'on lui parle des différences entre les salaires des hommes et des femmes dans l'édition, ou dans les aides attribuées par le CNL ? Sans langue de bois : « C'est pas trop surprenant malheureusement, parce que c'est à l'image des autres professions. En tant que bar-maison d'édition, de toute façon, je ne rentre pas dans la case du CNL, je me tourne plutôt vers la région », explique Jean-Marie Goater.

      \n

      \n

      Haut les coeurs : « C'est pas grave, je m'en passe très bien. L'édition, c'est un milieu qui a quand même une grande dimension d'hypocrisie sur pas mal d'aspects, on le voit sur certaines pratiques... Il y a des cons dans ce métier-là comme dans d'autres métiers, mais je pense que ce serait bien de faire le ménage, comme à Angoulême, c'est quand même criant. Dans certains secteurs du livre, la majorité des lecteurs sont des lectrices, très clairement, ce serait quand même la moindre des choses qu'il n'y ait pas des inégalités de ce type qui existent dans le monde de l'édition. »

      \n

      \n

      \"Livre

      \n

      Un album jeunesse bilingue français-langue des signes (ActuaLitté, CC BY SA 2.0)

      \n

      \n

      \n

      Même sans aide du CNL, les éditions Goater produisent de quoi lire : Les Joyeux Punks, un album à compter, mais aussi une collection d'albums bilingues français-langue des signes, des livres en breton, dont une traduction du Persepolis de Marjane Satrapi. Pour les amateurs de polar, Goater noir, une collection de 14 titres qui a notamment fait revivre Le Soviet, la série culte des années 89-90 d'abord publiée chez Fleuve Noir et Série Noire. Pour les amateurs des écrits du Colonel Durruti, un inédit est prévu pour le mois d'octobre prochain.

      \n

      \n

      Perdez-vous sans hésiter dans le catalogue de la maison, qui propose aussi de la littérature blanche \"classique\", des essais sur l'écologie et le convivialisme ou la convivialité, l'écologie sociale, et l'Histoire, surtout XXe.

      \n\n
      ", - "annotations": [], - "mimetype": "text/html", - "language": "en", - "reading_time": 6, - "domain_name": "www.actualitte.com", - "preview_picture": "//cdn.actualitte.com/images/facebook/25284788384-ea234db7b9-z-56eeff88c23a0.jpg", - "tags": [] - }, - { - "is_archived": 1, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 99, - "title": "[ROM][6.0.1][Layers][N5] TipsyOS official builds {UBER TCs}", - "url": "http://forum.xda-developers.com/google-nexus-5/development/rom-tipsyos-official-builds-uber-tcs-t3325989", - "content": "
      \n
      \"\"

      *Welcome to Tipsy OS*

      \n
      \"\"
      \n
      This is something Martin Coulon (@martinusbe) started in his 'free' time when waiting for GZR Validus or Tesla builds and having some drinks.
      He just started with a slim base; on lp and early mm, and now using AOSPB as a base (wich Martin is also a part of)....then added what we thought useful.
      It grew up to be a fully functional Rom
      The main goal is to keep it AOSPB/Slim based and will not add any cm features unless AOSPB/Slim does.
      \n

      TipsyOS is Black and Yellow default themed, we don't like white UI, so it may look a bit weird on light switch,
      but heh! use layers to suit it your needs =)

      \n

      We are a team wich is constantly learning and ...drinking because both gets along so well hahaha \"\"

      \n

      Just report the bugs and request features, we'll see what we can do!.......

      \n

      And don't get it twisted, its not because we're Tipsy that this project is not a serious one, try it and feel speed and stability \"\"

      \n

      My builds are compiled with UBER toolchains 4.9 on both rom and kernel code.
      We can go over with 5.2/3, 6 ...but to be really honest, 4.9 is the most battery friendly in my opinion, and is still super smooth and snappy!

      \n

      Im using a cm device tree base a bit modified...
      This rom includes a custom kernel, cm was my base, and i have decided to go a bit wild and cherry-picked up some stuff from:
      Francisco Franco, Chet Kener, Faux123, Flar2, Hellsgod and some others
      So a huge thanks for them and their AWESOME open sources work!
      I will continue to work on this kernel because its fun \"\"

      \n
      \"\"

      For cool wallpapers, test builds, requests; join us on our community!

      \n
      \nGoogle+ Community\n
      Features:\n
      \n

      Code:

      \n
      \nWe slowly adding only what we need, we don't want a 1236544547 features rom...\n\"The Tavern\":\nPower menu customisations\nToasts/ListView/System animations\nBattery bar\nLCD Density\nGesture Anywhere\nExpanded Desktop\nStatus bar customisations\nAosp Recents and OmniSwitch \nBuilt in:\nDashboard (settings) columns selector\nDashboard lines remover\nSlim Navbar customisation\nVolume steps\nNotification led changer\nHeadsUp switch\nKernel Adiutor app\nLayers manager app\nLayers backup/restore app\nAdaway\nNova launcher\nViper4Android\nES Manager\nSnapCam\nChangelog generator in about phone menu....\nand prolly some other stuff that i can't remember but heh,\n just flash dat sh#t to figure out by yourself =)\n
      \n
      \n


      Installation Instructions

      \n

      1. Make sure you have a working recovery and a nandroid backup

      \n

      2. Download the ROM.

      \n

      3. Reboot to recovery.

      \n

      4.Wipe everything! system/data/cache partitions (except internal storage indeed!)

      \n

      7. Flash the ROM.

      \n

      Optional- Flash 6.x GApps.

      \n

      8. Reboot and feel Tipsy!

      \n

      Download:

      \n

      Tipsy HammerHead downloads folder

      \n

      STAY TIPSY \"\"\"\"
      \"\"

      \n

      TipsyOs, a ROM for Nexus 5 aka Hammerhead

      \n
      \n
      Kernel features:
      Kexec patch for multirom support, intelliplug, hellsactive governor, extra io schedulers, intellithermal v2, etc etc and growing, just check commits on history on the link below\n

      Known bugs:
      quick tiles may be a bit messy while re arranging them....
      u tell me then.

      \n

      don't even think to report a bug with:
      a dirty flashed rom,
      xposed frameworks installed,
      all of your apps installed, if u have a bug, clean flash the build, (flash the gapps if needed) and reproduce your bug without any data restore.
      BRING BACK LOGCAT or u will be simply ignored....

      \n

      Contributors
      martinusbe
      @Alx31
      ROM OS Version: 6.0.1 Marshmallow
      ROM Kernel: Linux 3.4.x
      Based On: AOSPB

      \n

      Version Information
      Status: Stable
      Created 2016_29_02

      \n

      Credits:
      AOSPB/Slim team for an amazing base, Google, CyanogenMod for device trees and some other repos, Dirty Unicorns/CrDroid/AICP and other roms with their open sources i may have forgotten...

      \n

      Rom code: https://github.com/TipsyOs
      Device: Hammerhead commits history
      Kernel code: Kernel commits history
      My github: https://github.com/Alx31

      \n

      \"\"

      \n

      Last edited by Alx31; 29th February 2016 at 10:48 PM.

      ", - "annotations": [], - "mimetype": "text/html", - "language": "en", - "reading_time": 3, - "domain_name": "forum.xda-developers.com", - "preview_picture": "http://cdn3.xda-developers.com/images/xda-facebook-default.jpg", - "tags": [] - }, - { - "is_archived": 0, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 98, - "title": "Top 15 Podcasts All Web Developers Should Follow - Envato Tuts+ Code Article", - "url": "http://code.tutsplus.com/articles/top-15-podcasts-all-web-developers-should-follow--net-14461", - "content": "

      As web developers, we’re always trying to get better at what we do. One of the best ways to do that is to listen to what other developers have to share. And even if you’re not learning, it’s still fun to hear what other devs are talking about. Today, I’ll share 15 podcasts that you should definitely check out.

      \n
      \n
      \n

      It seems that as often as a few times a month, Yahoo! brings in developers on the cutting edge of web technology to keep their employees up to date. For the benefit of the rest of us, these talks are recorded and published. You’ll find well-known devs like Douglas Crockford and NNicolas Zakas, and talks on everything from performance and accessibility to JavaScript and the DOM.

      \n
      \n
      \n

      This may be my favourite show from this list. The Dev Show, hosted weekly by Dan Benjamin and Jason Seifer, will give you a carefully curated set of development-related links (usually with a web dev slant) to enjoy. As an added bonus, you can watch the show live on Tuesdays at 1pm EST.

      \n
      \n
      \n

      The tagline for the Changelog says it all: “Open Source moves fast. Keep up.” This podcast, and the accompanying blog, is all about keeping you updated with the latest in Open Source Technology. It’s hosted by Adam Stacoviak and Wynn Netherland, and seems to be the official Github podcast.

      \n
      \n
      \n

      If you’re familiar with jQuery (and you probably are), you know there’s a podcast to go with it. Each week, hosts Ralph Whitbeck and Rey Bango bring you the latest in jQuery news, as well as great interviews with important people in the jQuery community. You can listen in to the jQuery wisdom of people like Remy Sharp, Yehuda Katz, Cody Lindley, and our own Jeffrey Way, among so many others.

      \n
      \n
      \n

      Sitepoint is a great resource for anyone interesting in technology, design, and even business. Books, courses, forums, blogs, articles, they’ve got it all. Of course, there’s a podcast too: check it out to find out what’s going on in the web industry.

      \n
      \n
      \n

      According to the site, WebPulp is “a podcast about technology that powers the web.” In each podcast, host Josh Owens interviews someone from behind the scenes of a well-known webapp; you’ll find out what hardware and software it takes to run apps like the 37signals apps, or GitHub.

      \n
      \n
      \n

      It’s pretty apparent that both Nettuts+ readers and writers are big fans of WordPress. If you can’t get enough WordPress goodness, you’ll probably want to sign up for the WordPress Podcast, “a weekly podcast with news, interviews and plugin tips.” There’s a bonus here: one of the most recent interviewees was none other than Collis Ta’eed, CEO of Envato.

      \n
      \n
      \n

      If you’re a user of Ellis Lab’s Expression Engine, you’ll enjoy the EE Podcast (Ellis Lab is the company behind CodeIgniter; in fact, EE is build completely on CI). Each week, Ryan Irelan and Lea Alcantara will fill in you on a certain aspect of of EE deveopment.

      \n
      \n
      \n

      If you’re a web developer, you’re probably pretty familiar with Chris Coyier’s website CSS Tricks. Besides his excellent articles, Chris occasionally puts out a screencast every few weeks. With his relaxed style, you’ll learn about a random—but always practical—part of web development in each episode.

      \n
      \n
      \n

      Hosted by Jeffrey Zeldman and Dan Benjamin, the Big Web Show “features special guests and topics like web publishing, art direction, content strategy, typography, web technology, and more. It’s everything web that matters.” You’ll listen to interviews in which famous web personalities like Eric Meyer, Jason Fried, Nicole Sullivan, Ethan Marcotte, and other professionals you should know open their minds and let you learn from the best. You can catch this show live on Thursdays a 1PM EST. Just like the Dev Show and the EE Podcast, the Big Web Show is part of Dan Benjamin’s incredible 5by5 podcast network.

      \n
      \n
      \n

      You may be familiar with Carsonified, the company behind many web dev / design training initiatives (including the Future of Web Design and Future of Web Apps confernces). On Think Vitamin, Carsonified’s “blog about the web”, you can catch Think Vitamin Radio, “a bi-weekly chat about web design, development, and entrepreneurship.”

      \n
      \n
      \n

      User Interface Engineering “is a leading research, training, and consulting firm specializing in web site and product usability.” You can take advantage of some of the free usability training they offer in their podcast, the Userability Podcast.

      \n
      \n
      \n

      This is a great resource for any beginner (and even intermediate) jQuery developers. In each episode, Remy Sharp will explain how to create an popular web effect using jQuery. You’ll learn how to build pop-up bubbles, sliding headers, and simple tabs.

      \n
      \n
      \n

      Of course, Nettuts+ publishes screencasts, too! For your convenience, you can get these in an iTunes feed, or subscribe to them on YouTube.

      \n
      \n
      \n

      HuffDuffer is a site created by Jeremy Keith; it allows you to easily create your own podcasts. From the tag cloud above, you can see that a lot of the content being collected is related to web development. Check it out!

      \n
      \n

      I’m sure most developers listen to the occasional podcast. Have I missed your favourite podcast? Let us all know in the comments!

      \n", - "annotations": [], - "mimetype": "text/html", - "reading_time": 4, - "domain_name": "code.tutsplus.com", - "preview_picture": "https://cdn.tutsplus.com/net/uploads/legacy/793_podcasts/preview.jpg", - "tags": [] - }, - { - "is_archived": 1, - "created_at": "2016-09-08T11:55:58+0200", - "updated_at": "2016-09-08T11:57:16+0200", - "is_starred": 0, - "id": 97, - "title": "University of Mississippi", - "url": "http://olemiss.edu", - "content": "
      \n
      \n
      \n
      \n

      UNIVERSITY OF MISSISSIPPI SCHOOLS AND COLLEGES

      \n

      The Schools of Nursing and Pharmacy operate on both the Oxford and Jackson campuses. The Schools of Dentistry, Health Related Professionals and Medicine, and the Health Sciences Graduate School, are based in Jackson only. (Additional healthcare programs are available through the School of Applied Sciences on the Oxford campus.) Other than these exceptions, the schools above are on the Oxford campus.

      \n
      \n
      \n

      Public Service Announcement: UM Health Center Seeing Increase in Flu Cases MORE INFO

      \n
      \n
      • \n
        \"\"
        Hotty Toddy
        \n

        Martavious Newby celebrates with fans after Ole Miss' 86-78 win over Mississippi State.

        \n
      • \n
      • \n
        \"\"
        Moody's Amazing Night
        \n

        Stefan Moody celebrates at the end of Ole Miss' 86-78 win over Mississippi State. Moody finished his final game at The Pavilion on Senior Night with a career-high 43 points.

        \n
      • \n
      • \n
        \"\"
        Career Expo
        \n

        Students talk to prospective employers during an all-majors career fair held at The Inn at Ole Miss.

        \n
      • \n
      • \n
        \"\"
        Choir Rehearsal
        \n

        Members of the University of Mississippi Concert Singers prepare for a performance at the American Choral Directors Association convention March 10 in Chattanooga, Tenn.

        \n
      • \n
      • \n
        \"\"
        Dentist's Pledge
        \n

        Kendra Clark (right) and other students in the UMMC School of Dentistry Class of 2018 recite the Dentist's Pledge at the American College of Dentists White Coat Ceremony held Feb. 26 in Jackson.

        \n
      • \n
      \n

      45°

      \n

      Oxford, MS

      \n
      \n
      \n
      \n
      \n
      ALL NEWS\n

      Latest News

      \n
      \n

      UM Honors 150 Students with Who's Who Distinction

      \n
      \n

      UM Lazarus Project Attracts International Collaborations

      \n
      \n

      Schedule Set for BancorpSouth Rebel Road Trip

      \n
      ALL ANNOUNCEMENTS\n

      Announcements

      \n
      \n

      olemisssports.com\n

      UM Athletics

      \n
      \n
      \n

      Men's Basketball

      \n
      \"team Ole Miss 86
      \n
      \"team Miss. St. 78
      \n

      Wednesday, Mar. 2

      \n
      \n
      \n

      Men's Baseball

      \n
      \"team Ole Miss 9
      \n
      \"team Memphis 7
      \n

      Wednesday, Mar. 2

      \n
      \n
      \n

      Women's Basketball

      \n
      \"team Ole Miss 59
      \n
      \"team Vanderbilt 74
      \n

      Wednesday, Mar. 2

      \n
      \n
      \n