WIP with option and result types
This commit is contained in:
parent
dfd9a873f8
commit
1d5a3c1c7a
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "bit-badger/feed-reader-central",
|
||||
"minimum-stability": "dev",
|
||||
"minimum-stability": "beta",
|
||||
"require": {
|
||||
"php": ">=8.2",
|
||||
"bit-badger/pdo-document": "^1",
|
||||
@ -8,7 +8,8 @@
|
||||
"ext-dom": "*",
|
||||
"ext-pdo": "*",
|
||||
"ext-readline": "*",
|
||||
"ext-sqlite3": "*"
|
||||
"ext-sqlite3": "*",
|
||||
"graham-campbell/result-type": "^1.1"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
153
src/composer.lock
generated
153
src/composer.lock
generated
@ -4,20 +4,21 @@
|
||||
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
|
||||
"This file is @generated automatically"
|
||||
],
|
||||
"content-hash": "4f0add59e384feb6787acf3685c9e031",
|
||||
"content-hash": "d5b7f01ef79cdce09364eed3dca3281d",
|
||||
"packages": [
|
||||
{
|
||||
"name": "bit-badger/pdo-document",
|
||||
"version": "v1.0.0-alpha2",
|
||||
"version": "v1.0.0-beta2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://git.bitbadger.solutions/bit-badger/pdo-document",
|
||||
"reference": "330e27218756df8b93081a17dead8aaec789b071"
|
||||
"reference": "50854275a8b39074966cf00370f30b3e68edc6e7"
|
||||
},
|
||||
"require": {
|
||||
"ext-pdo": "*",
|
||||
"netresearch/jsonmapper": "^4",
|
||||
"php": ">=8.2"
|
||||
"php": ">=8.2",
|
||||
"phpoption/phpoption": "^1.9"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^11"
|
||||
@ -42,11 +43,12 @@
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "Treat SQLite (and soon PostgreSQL) as a document store",
|
||||
"description": "Treat SQLite and PostgreSQL as document stores",
|
||||
"keywords": [
|
||||
"database",
|
||||
"document",
|
||||
"pdo",
|
||||
"postgresql",
|
||||
"sqlite"
|
||||
],
|
||||
"support": {
|
||||
@ -54,7 +56,69 @@
|
||||
"rss": "https://git.bitbadger.solutions/bit-badger/pdo-document.rss",
|
||||
"source": "https://git.bitbadger.solutions/bit-badger/pdo-document"
|
||||
},
|
||||
"time": "2024-06-11T11:07:56+00:00"
|
||||
"time": "2024-06-25T14:42:26+00:00"
|
||||
},
|
||||
{
|
||||
"name": "graham-campbell/result-type",
|
||||
"version": "v1.1.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/GrahamCampbell/Result-Type.git",
|
||||
"reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/GrahamCampbell/Result-Type/zipball/fbd48bce38f73f8a4ec8583362e732e4095e5862",
|
||||
"reference": "fbd48bce38f73f8a4ec8583362e732e4095e5862",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": "^7.2.5 || ^8.0",
|
||||
"phpoption/phpoption": "^1.9.2"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
|
||||
},
|
||||
"type": "library",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"GrahamCampbell\\ResultType\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
}
|
||||
],
|
||||
"description": "An Implementation Of The Result Type",
|
||||
"keywords": [
|
||||
"Graham Campbell",
|
||||
"GrahamCampbell",
|
||||
"Result Type",
|
||||
"Result-Type",
|
||||
"result"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/GrahamCampbell/Result-Type/issues",
|
||||
"source": "https://github.com/GrahamCampbell/Result-Type/tree/v1.1.2"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://github.com/GrahamCampbell",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://tidelift.com/funding/github/packagist/graham-campbell/result-type",
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2023-11-12T22:16:48+00:00"
|
||||
},
|
||||
{
|
||||
"name": "netresearch/jsonmapper",
|
||||
@ -106,11 +170,86 @@
|
||||
"source": "https://github.com/cweiske/jsonmapper/tree/v4.4.1"
|
||||
},
|
||||
"time": "2024-01-31T06:18:54+00:00"
|
||||
},
|
||||
{
|
||||
"name": "phpoption/phpoption",
|
||||
"version": "1.9.2",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/schmittjoh/php-option.git",
|
||||
"reference": "80735db690fe4fc5c76dfa7f9b770634285fa820"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/schmittjoh/php-option/zipball/80735db690fe4fc5c76dfa7f9b770634285fa820",
|
||||
"reference": "80735db690fe4fc5c76dfa7f9b770634285fa820",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"php": "^7.2.5 || ^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"bamarni/composer-bin-plugin": "^1.8.2",
|
||||
"phpunit/phpunit": "^8.5.34 || ^9.6.13 || ^10.4.2"
|
||||
},
|
||||
"type": "library",
|
||||
"extra": {
|
||||
"bamarni-bin": {
|
||||
"bin-links": true,
|
||||
"forward-command": true
|
||||
},
|
||||
"branch-alias": {
|
||||
"dev-master": "1.9-dev"
|
||||
}
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"PhpOption\\": "src/PhpOption/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"Apache-2.0"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Johannes M. Schmitt",
|
||||
"email": "schmittjoh@gmail.com",
|
||||
"homepage": "https://github.com/schmittjoh"
|
||||
},
|
||||
{
|
||||
"name": "Graham Campbell",
|
||||
"email": "hello@gjcampbell.co.uk",
|
||||
"homepage": "https://github.com/GrahamCampbell"
|
||||
}
|
||||
],
|
||||
"description": "Option Type for PHP",
|
||||
"keywords": [
|
||||
"language",
|
||||
"option",
|
||||
"php",
|
||||
"type"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/schmittjoh/php-option/issues",
|
||||
"source": "https://github.com/schmittjoh/php-option/tree/1.9.2"
|
||||
},
|
||||
"funding": [
|
||||
{
|
||||
"url": "https://github.com/GrahamCampbell",
|
||||
"type": "github"
|
||||
},
|
||||
{
|
||||
"url": "https://tidelift.com/funding/github/packagist/phpoption/phpoption",
|
||||
"type": "tidelift"
|
||||
}
|
||||
],
|
||||
"time": "2023-11-12T21:59:55+00:00"
|
||||
}
|
||||
],
|
||||
"packages-dev": [],
|
||||
"aliases": [],
|
||||
"minimum-stability": "dev",
|
||||
"minimum-stability": "beta",
|
||||
"stability-flags": [],
|
||||
"prefer-stable": false,
|
||||
"prefer-lowest": false,
|
||||
|
105
src/lib/Feed.php
105
src/lib/Feed.php
@ -6,6 +6,10 @@ use BitBadger\PDODocument\{
|
||||
Configuration, Custom, Document, DocumentException, DocumentList, Exists, Field, Find, Parameters, Patch, Query
|
||||
};
|
||||
use DateTimeInterface;
|
||||
use GrahamCampbell\ResultType\Error;
|
||||
use GrahamCampbell\ResultType\Result;
|
||||
use GrahamCampbell\ResultType\Success;
|
||||
use PhpOption\Option;
|
||||
|
||||
/**
|
||||
* An RSS or Atom feed
|
||||
@ -64,16 +68,17 @@ class Feed
|
||||
* @param int $feedId The ID of the feed to which these items belong
|
||||
* @param ParsedFeed $parsed The extracted Atom or RSS feed items
|
||||
* @param DateTimeInterface $lastChecked When this feed was last checked (only new items will be added)
|
||||
* @return array ['ok' => true] if successful, ['error' => message] if not
|
||||
* @return Result<true, string> True if successful, an error message if not
|
||||
*/
|
||||
public static function updateItems(int $feedId, ParsedFeed $parsed, DateTimeInterface $lastChecked): array
|
||||
public static function updateItems(int $feedId, ParsedFeed $parsed, DateTimeInterface $lastChecked): Result
|
||||
{
|
||||
$results =
|
||||
array_map(function ($item) use ($feedId) {
|
||||
try {
|
||||
$existing = Find::firstByFields(Table::ITEM,
|
||||
$tryExisting = Find::firstByFields(Table::ITEM,
|
||||
[Field::EQ('feed_id', $feedId), Field::EQ('item_guid', $item->guid)], Item::class);
|
||||
if ($existing) {
|
||||
if ($tryExisting->isDefined()) {
|
||||
$existing = $tryExisting->get();
|
||||
if ($existing->published_on != $item->publishedOn
|
||||
|| ($existing->updated_on != ($item->updatedOn ?? ''))) {
|
||||
Item::update($existing->id, $item);
|
||||
@ -81,26 +86,28 @@ class Feed
|
||||
} else {
|
||||
Item::add($feedId, $item);
|
||||
}
|
||||
return ['ok' => true];
|
||||
return Success::create(true);
|
||||
} catch (DocumentException $ex) {
|
||||
return ['error' => "$ex"];
|
||||
return Error::create("$ex");
|
||||
}
|
||||
}, array_filter($parsed->items,
|
||||
fn($it) => date_create_immutable($it->updatedOn ?? $it->publishedOn) >= $lastChecked));
|
||||
$errors = array_map(fn($it) => $it['error'], array_filter($results, fn($it) => array_key_exists('error', $it)));
|
||||
return sizeof($errors) > 0 ? ['error' => implode("\n", $errors)] : ['ok' => true];
|
||||
fn(ParsedItem $it) => date_create_immutable($it->updatedOn ?? $it->publishedOn) >= $lastChecked));
|
||||
$errors = array_map(fn(Result $it) => $it->error()->get(),
|
||||
array_filter($results, fn(Result $it) => $it->error()->isDefined()));
|
||||
return sizeof($errors) > 0 ? Error::create(implode("\n", $errors)) : Success::create(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Purge items for a feed
|
||||
*
|
||||
* @param int $feedId The ID of the feed to be purged
|
||||
* @return array|string[]|true[] ['ok' => true] if purging was successful, ['error' => message] if not
|
||||
* @return Result<true, string> True if purging was successful, an error message if not
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
private static function purgeItems(int $feedId): array
|
||||
private static function purgeItems(int $feedId): Result
|
||||
{
|
||||
if (!array_search(PURGE_TYPE, [self::PURGE_READ, self::PURGE_BY_DAYS, self::PURGE_BY_COUNT])) {
|
||||
return ['error' => 'Unrecognized purge type ' . PURGE_TYPE];
|
||||
return Error::create('Unrecognized purge type ' . PURGE_TYPE);
|
||||
}
|
||||
|
||||
$fields = [Field::EQ('feed_id', $feedId, ':feed'), Data::bookmarkField(false)];
|
||||
@ -127,9 +134,9 @@ class Feed
|
||||
}
|
||||
try {
|
||||
Custom::nonQuery($sql, Parameters::addFields($fields, []));
|
||||
return ['ok' => true];
|
||||
return Success::create(true);
|
||||
} catch (DocumentException $ex) {
|
||||
return ['error' => "$ex"];
|
||||
return Error::create("$ex");
|
||||
}
|
||||
}
|
||||
|
||||
@ -138,21 +145,22 @@ class Feed
|
||||
*
|
||||
* @param int $feedId The ID of the feed to be refreshed
|
||||
* @param string $url The URL of the feed to be refreshed
|
||||
* @return array|string[]|true[] ['ok' => true] if successful, ['error' => message] if not
|
||||
* @return Result<true, string> True if successful, an error message if not
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
public static function refreshFeed(int $feedId, string $url): array
|
||||
public static function refreshFeed(int $feedId, string $url): Result
|
||||
{
|
||||
$feedRetrieval = ParsedFeed::retrieve($url);
|
||||
if (key_exists('error', $feedRetrieval)) return $feedRetrieval;
|
||||
$feed = $feedRetrieval['ok'];
|
||||
$tryRetrieve = ParsedFeed::retrieve($url);
|
||||
if ($tryRetrieve->error()->isDefined()) return $tryRetrieve->error()->get();
|
||||
$feed = $tryRetrieve->success()->get();
|
||||
|
||||
try {
|
||||
$feedDoc = Find::byId(Table::FEED, $feedId, self::class);
|
||||
if (!$feedDoc) return ['error' => 'Could not derive date last checked for feed'];
|
||||
$lastChecked = date_create_immutable($feedDoc->checked_on ?? WWW_EPOCH);
|
||||
if ($feedDoc->isEmpty()) return Error::create('Could not derive date last checked for feed');
|
||||
$lastChecked = date_create_immutable($feedDoc->get()->checked_on ?? WWW_EPOCH);
|
||||
|
||||
$itemUpdate = self::updateItems($feedId, $feed, $lastChecked);
|
||||
if (key_exists('error', $itemUpdate)) return $itemUpdate;
|
||||
if ($itemUpdate->error()->isDefined()) return $itemUpdate->error()->get();
|
||||
|
||||
$patch = [
|
||||
'title' => $feed->title,
|
||||
@ -162,42 +170,40 @@ class Feed
|
||||
if ($url == $feed->url) $patch['url'] = $feed->url;
|
||||
Patch::byId(Table::FEED, $feedId, $patch);
|
||||
} catch (DocumentException $ex) {
|
||||
return ['error' => "$ex"];
|
||||
return Error::create("$ex");
|
||||
}
|
||||
|
||||
return PURGE_TYPE == self::PURGE_NONE ? ['ok' => true] : self::purgeItems($feedId);
|
||||
return PURGE_TYPE == self::PURGE_NONE ? Success::create(true) : self::purgeItems($feedId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add an RSS feed
|
||||
*
|
||||
* @param string $url The URL of the RSS feed to add
|
||||
* @return array ['ok' => feedId] if successful, ['error' => message] if not
|
||||
* @return Result<int, string> The feed ID if successful, an error message if not
|
||||
*/
|
||||
public static function add(string $url): array
|
||||
public static function add(string $url): Result
|
||||
{
|
||||
$feedExtract = ParsedFeed::retrieve($url);
|
||||
if (key_exists('error', $feedExtract)) return $feedExtract;
|
||||
|
||||
$feed = $feedExtract['ok'];
|
||||
$tryRetrieve = ParsedFeed::retrieve($url);
|
||||
if ($tryRetrieve->error()->isDefined()) return $tryRetrieve->error()->get();
|
||||
$feed = $tryRetrieve->success()->get();
|
||||
|
||||
try {
|
||||
$fields = [Field::EQ('user_id', $_SESSION[Key::USER_ID]), Field::EQ('url', $feed->url)];
|
||||
if (Exists::byFields(Table::FEED, $fields)) {
|
||||
return ['error' => "Already subscribed to feed $feed->url"];
|
||||
return Error::create("Already subscribed to feed $feed->url");
|
||||
}
|
||||
|
||||
Document::insert(Table::FEED, self::fromParsed($feed));
|
||||
|
||||
$doc = Find::firstByFields(Table::FEED, $fields, static::class);
|
||||
if (!$doc) return ['error' => 'Could not retrieve inserted feed'];
|
||||
$tryDoc = Find::firstByFields(Table::FEED, $fields, static::class);
|
||||
if ($tryDoc->isEmpty()) return Error::create('Could not retrieve inserted feed');
|
||||
$doc = $tryDoc->get();
|
||||
|
||||
$result = self::updateItems($doc->id, $feed, date_create_immutable(WWW_EPOCH));
|
||||
if (key_exists('error', $result)) return $result;
|
||||
|
||||
return ['ok' => $doc->id];
|
||||
return $result->error()->isDefined() ? $result->error()->get() : Success::create($doc->id);
|
||||
} catch (DocumentException $ex) {
|
||||
return ['error' => "$ex"];
|
||||
return Error::create("$ex");
|
||||
}
|
||||
}
|
||||
|
||||
@ -206,9 +212,9 @@ class Feed
|
||||
*
|
||||
* @param Feed $existing The existing feed
|
||||
* @param string $url The URL with which the existing feed should be modified
|
||||
* @return bool[]|string[] [ 'ok' => true ] if successful, [ 'error' => message ] if not
|
||||
* @return Result<true, string> True if successful, an error message if not
|
||||
*/
|
||||
public static function update(Feed $existing, string $url): array
|
||||
public static function update(Feed $existing, string $url): Result
|
||||
{
|
||||
try {
|
||||
Patch::byFields(Table::FEED,
|
||||
@ -217,7 +223,7 @@ class Feed
|
||||
|
||||
return self::refreshFeed($existing->id, $url);
|
||||
} catch (DocumentException $ex) {
|
||||
return ['error' => "$ex"];
|
||||
return Error::create("$ex");
|
||||
}
|
||||
}
|
||||
|
||||
@ -238,10 +244,9 @@ class Feed
|
||||
/**
|
||||
* Refresh all feeds
|
||||
*
|
||||
* @return array|true[]|string[] ['ok' => true] if successful,
|
||||
* ['error' => message] if not (may have multiple error lines)
|
||||
* @return Result<true, string> True if successful an error message if not (may have multiple error lines)
|
||||
*/
|
||||
public static function refreshAll(): array
|
||||
public static function refreshAll(): Result
|
||||
{
|
||||
try {
|
||||
$feeds = self::retrieveAll($_SESSION[Key::USER_ID]);
|
||||
@ -249,25 +254,25 @@ class Feed
|
||||
$errors = [];
|
||||
foreach ($feeds->items() as $feed) {
|
||||
$result = self::refreshFeed($feed->id, $feed->url);
|
||||
if (key_exists('error', $result)) $errors[] = $result['error'];
|
||||
if ($result->error()->isDefined()) $errors[] = $result->error()->get();
|
||||
}
|
||||
} catch (DocumentException $ex) {
|
||||
return ['error' => "$ex"];
|
||||
return Error::create("$ex");
|
||||
}
|
||||
|
||||
return sizeof($errors) == 0 ? ['ok' => true] : ['error' => implode("\n", $errors)];
|
||||
return sizeof($errors) == 0 ? Success::create(true) : Error::create(implode("\n", $errors));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a feed by its ID for the current user
|
||||
*
|
||||
* @param int $feedId The ID of the feed to retrieve
|
||||
* @return static|false The data for the feed if found, false if not found
|
||||
* @return Option<static> A `Some` value with the data for the feed if found, `None` otherwise
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
public static function retrieveById(int $feedId): static|false
|
||||
public static function retrieveById(int $feedId): Option
|
||||
{
|
||||
$doc = Find::byId(Table::FEED, $feedId, static::class);
|
||||
return $doc && $doc->user_id == $_SESSION[Key::USER_ID] ? $doc : false;
|
||||
return Find::byId(Table::FEED, $feedId, static::class)
|
||||
->filter(fn ($it) => $it->user_id == $_SESSION[Key::USER_ID]);
|
||||
}
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ namespace FeedReaderCentral;
|
||||
|
||||
use BitBadger\PDODocument\{Configuration, Custom, DocumentException, Field, Parameters, Query};
|
||||
use BitBadger\PDODocument\Mapper\{DocumentMapper, ExistsMapper};
|
||||
use PhpOption\Option;
|
||||
|
||||
/**
|
||||
* A combined item and feed (used for lists)
|
||||
@ -55,10 +56,10 @@ class ItemWithFeed extends Item
|
||||
* Retrieve an item via its ID
|
||||
*
|
||||
* @param int $id The ID of the item to be retrieved
|
||||
* @return ItemWithFeed|false The item if it is found, false if not
|
||||
* @return Option<ItemWithFeed> A `Some` value with the item if it is found, `None` otherwise
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
public static function retrieveById(int $id): ItemWithFeed|false
|
||||
public static function retrieveById(int $id): Option
|
||||
{
|
||||
$fields = self::idAndUserFields($id);
|
||||
return Custom::single(self::SELECT_WITH_FEED . ' WHERE ' . Query::whereByFields($fields),
|
||||
|
@ -6,6 +6,9 @@ use DOMDocument;
|
||||
use DOMElement;
|
||||
use DOMException;
|
||||
use DOMNode;
|
||||
use GrahamCampbell\ResultType\Error;
|
||||
use GrahamCampbell\ResultType\Result;
|
||||
use GrahamCampbell\ResultType\Success;
|
||||
|
||||
class ParsedFeed
|
||||
{
|
||||
@ -53,16 +56,16 @@ class ParsedFeed
|
||||
* Parse a feed into an XML tree
|
||||
*
|
||||
* @param string $content The feed's RSS content
|
||||
* @return array|DOMDocument[]|string[] ['ok' => feed] if successful, ['error' => message] if not
|
||||
* @return Result<DOMDocument, string> The feed if successful, an error message if not
|
||||
*/
|
||||
public static function parseFeed(string $content): array {
|
||||
public static function parseFeed(string $content): Result {
|
||||
set_error_handler(self::xmlParseError(...));
|
||||
try {
|
||||
$feed = new DOMDocument();
|
||||
$feed->loadXML($content);
|
||||
return ['ok' => $feed];
|
||||
return Success::create($feed);
|
||||
} catch (DOMException $ex) {
|
||||
return ['error' => $ex->getMessage()];
|
||||
return Error::create($ex->getMessage());
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
@ -85,13 +88,13 @@ class ParsedFeed
|
||||
*
|
||||
* @param DOMDocument $xml The XML received from the feed
|
||||
* @param string $url The actual URL for the feed
|
||||
* @return array|Feed[]|string[] ['ok' => feed] if successful, ['error' => message] if not
|
||||
* @return Result<Feed, string> The feed if successful, an error message if not
|
||||
*/
|
||||
private static function fromRSS(DOMDocument $xml, string $url): array {
|
||||
private static function fromRSS(DOMDocument $xml, string $url): Result {
|
||||
$channel = $xml->getElementsByTagName('channel')->item(0);
|
||||
if (!($channel instanceof DOMElement)) {
|
||||
$type = $channel?->nodeType ?? -1;
|
||||
return ['error' => "Channel element not found ($type)"];
|
||||
return Error::create("Channel element not found ($type)");
|
||||
}
|
||||
|
||||
// The Atom namespace provides a lastBuildDate, which contains the last time an item in the feed was updated; if
|
||||
@ -108,7 +111,7 @@ class ParsedFeed
|
||||
$feed->updatedOn = Data::formatDate($updatedOn);
|
||||
foreach ($channel->getElementsByTagName('item') as $item) $feed->items[] = ParsedItem::fromRSS($item);
|
||||
|
||||
return ['ok' => $feed];
|
||||
return Success::create($feed);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -150,7 +153,7 @@ class ParsedFeed
|
||||
*
|
||||
* @param DOMDocument $xml The XML received from the feed
|
||||
* @param string $url The actual URL for the feed
|
||||
* @return array|Feed[] ['ok' => feed]
|
||||
* @return Result<Feed, string> The feed (does not have any error handling)
|
||||
*/
|
||||
private static function fromAtom(DOMDocument $xml, string $url): array {
|
||||
$root = $xml->getElementsByTagNameNS(self::ATOM_NS, 'feed')->item(0);
|
||||
@ -162,91 +165,101 @@ class ParsedFeed
|
||||
$feed->updatedOn = Data::formatDate($updatedOn);
|
||||
foreach ($root->getElementsByTagName('entry') as $entry) $feed->items[] = ParsedItem::fromAtom($entry);
|
||||
|
||||
return ['ok' => $feed];
|
||||
return Success::create($feed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve a document (http/https)
|
||||
*
|
||||
* @param string $url The URL of the document to retrieve
|
||||
* @return array ['content' => document content, 'error' => error message, 'code' => HTTP response code,
|
||||
* 'url' => effective URL]
|
||||
* @return Result<array, string> ['content' => doc content, 'code' => HTTP response code, 'url' => effective URL] if
|
||||
* successful, an error message if not
|
||||
*/
|
||||
private static function retrieveDocument(string $url): array {
|
||||
private static function retrieveDocument(string $url): Result {
|
||||
$docReq = curl_init($url);
|
||||
curl_setopt($docReq, CURLOPT_FOLLOWLOCATION, true);
|
||||
curl_setopt($docReq, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($docReq, CURLOPT_CONNECTTIMEOUT, 5);
|
||||
curl_setopt($docReq, CURLOPT_TIMEOUT, 15);
|
||||
curl_setopt($docReq, CURLOPT_USERAGENT, self::USER_AGENT);
|
||||
try {
|
||||
curl_setopt($docReq, CURLOPT_FOLLOWLOCATION, true);
|
||||
curl_setopt($docReq, CURLOPT_RETURNTRANSFER, true);
|
||||
curl_setopt($docReq, CURLOPT_CONNECTTIMEOUT, 5);
|
||||
curl_setopt($docReq, CURLOPT_TIMEOUT, 15);
|
||||
curl_setopt($docReq, CURLOPT_USERAGENT, self::USER_AGENT);
|
||||
|
||||
$result = [
|
||||
'content' => curl_exec($docReq),
|
||||
'error' => curl_error($docReq),
|
||||
'code' => curl_getinfo($docReq, CURLINFO_RESPONSE_CODE),
|
||||
'url' => curl_getinfo($docReq, CURLINFO_EFFECTIVE_URL)
|
||||
];
|
||||
$error = curl_error($docReq);
|
||||
if ($error <> '') return Error::create($error);
|
||||
|
||||
curl_close($docReq);
|
||||
return $result;
|
||||
return Success::create([
|
||||
'content' => curl_exec($docReq),
|
||||
'code' => curl_getinfo($docReq, CURLINFO_RESPONSE_CODE),
|
||||
'url' => curl_getinfo($docReq, CURLINFO_EFFECTIVE_URL)
|
||||
]);
|
||||
} finally {
|
||||
curl_close($docReq);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a feed URL from an HTML document
|
||||
*
|
||||
* @param string $content The HTML document content from which to derive a feed URL
|
||||
* @return array|string[] ['ok' => feed URL] if successful, ['error' => message] if not
|
||||
* @return Result<string, string> The feed URL if successful, an error message if not
|
||||
*/
|
||||
private static function deriveFeedFromHTML(string $content): array {
|
||||
private static function deriveFeedFromHTML(string $content): Result {
|
||||
$html = new DOMDocument();
|
||||
$html->loadHTML(substr($content, 0, strpos($content, '</head>') + 7));
|
||||
$headTags = $html->getElementsByTagName('head');
|
||||
if ($headTags->length < 1) return ['error' => 'Cannot find feed at this URL'];
|
||||
if ($headTags->length < 1) return Error::create('Cannot find feed at this URL');
|
||||
$head = $headTags->item(0);
|
||||
foreach ($head->getElementsByTagName('link') as $link) {
|
||||
if (self::attrValue($link, 'rel') == 'alternate') {
|
||||
$type = self::attrValue($link, 'type');
|
||||
if ($type == 'application/rss+xml' || $type == 'application/atom+xml') {
|
||||
return ['ok' => self::attrValue($link, 'href')];
|
||||
return Success::create(self::attrValue($link, 'href'));
|
||||
}
|
||||
}
|
||||
}
|
||||
return ['error' => 'Cannot find feed at this URL'];
|
||||
return Error::create('Cannot find feed at this URL');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the feed
|
||||
*
|
||||
* @param string $url The URL of the feed to retrieve
|
||||
* @return array|ParsedFeed[]|string[] ['ok' => feed] if successful, ['error' => message] if not
|
||||
* @return Result<ParsedFeed, string> The feed if successful, an error message if not
|
||||
*/
|
||||
public static function retrieve(string $url): array {
|
||||
$doc = self::retrieveDocument($url);
|
||||
public static function retrieve(string $url): Result {
|
||||
$tryDoc = self::retrieveDocument($url);
|
||||
|
||||
if ($doc['error'] != '') return ['error' => $doc['error']];
|
||||
if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get();
|
||||
$doc = $tryDoc->success()->get();
|
||||
if ($doc['code'] != 200) {
|
||||
return ['error' => "Prospective feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}"];
|
||||
return Error::create("Prospective feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}");
|
||||
}
|
||||
|
||||
$start = strtolower(strlen($doc['content']) >= 9 ? substr($doc['content'], 0, 9) : $doc['content']);
|
||||
if ($start == '<!doctype' || str_starts_with($start, '<html')) {
|
||||
$derivedURL = self::deriveFeedFromHTML($doc['content']);
|
||||
if (key_exists('error', $derivedURL)) return ['error' => $derivedURL['error']];
|
||||
$feedURL = $derivedURL['ok'];
|
||||
if ($derivedURL->error()->isDefined()) return $derivedURL->error()->get();
|
||||
$feedURL = $derivedURL->success()->get();
|
||||
if (!str_starts_with($feedURL, 'http')) {
|
||||
// Relative URL; feed should be retrieved in the context of the original URL
|
||||
$original = parse_url($url);
|
||||
$port = key_exists('port', $original) ? ":{$original['port']}" : '';
|
||||
$feedURL = $original['scheme'] . '://' . $original['host'] . $port . $feedURL;
|
||||
}
|
||||
$doc = self::retrieveDocument($feedURL);
|
||||
$tryDoc = self::retrieveDocument($feedURL);
|
||||
if ($tryDoc->error()->isDefined()) return $tryDoc->error()->get();
|
||||
$doc = $tryDoc->success()->get();
|
||||
if ($doc['code'] != 200) {
|
||||
return Error::create("Derived feed URL $url returned HTTP Code {$doc['code']}: {$doc['content']}");
|
||||
}
|
||||
}
|
||||
|
||||
$parsed = self::parseFeed($doc['content']);
|
||||
if (key_exists('error', $parsed)) return ['error' => $parsed['error']];
|
||||
$tryParse = self::parseFeed($doc['content']);
|
||||
if ($tryParse->error()->isDefined()) return $tryParse->error()->get();
|
||||
|
||||
$extract = $parsed['ok']->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0
|
||||
$parsed = $tryParse->success()->get();
|
||||
$extract = $parsed->getElementsByTagNameNS(self::ATOM_NS, 'feed')->length > 0
|
||||
? self::fromAtom(...) : self::fromRSS(...);
|
||||
return $extract($parsed['ok'], $doc['url']);
|
||||
return $extract($parsed, $doc['url']);
|
||||
}
|
||||
}
|
||||
|
@ -66,7 +66,7 @@ class Security
|
||||
$dbEmail = $email;
|
||||
}
|
||||
$user = User::findByEmail($dbEmail);
|
||||
if ($user) self::verifyPassword($user, $password, $returnTo);
|
||||
if ($user->isDefined()) self::verifyPassword($user->get(), $password, $returnTo);
|
||||
add_error('Invalid credentials; log on unsuccessful');
|
||||
}
|
||||
|
||||
@ -89,11 +89,11 @@ class Security
|
||||
*/
|
||||
private static function logOnSingleUser(): void {
|
||||
$user = User::findByEmail(self::SINGLE_USER_EMAIL);
|
||||
if (!$user) {
|
||||
if ($user->isEmpty()) {
|
||||
User::add(self::SINGLE_USER_EMAIL, self::SINGLE_USER_PASSWORD);
|
||||
$user = User::findByEmail(self::SINGLE_USER_EMAIL);
|
||||
}
|
||||
self::verifyPassword($user, self::SINGLE_USER_PASSWORD, $_GET['returnTo']);
|
||||
self::verifyPassword($user->get(), self::SINGLE_USER_PASSWORD, $_GET['returnTo']);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -4,6 +4,7 @@ namespace FeedReaderCentral;
|
||||
|
||||
use BitBadger\PDODocument\{Custom, Document, DocumentException, Field, Find, Parameters, Query};
|
||||
use BitBadger\PDODocument\Mapper\ExistsMapper;
|
||||
use PhpOption\Option;
|
||||
|
||||
/**
|
||||
* A user of Feed Reader Central
|
||||
@ -23,10 +24,10 @@ class User
|
||||
* Find a user by their e=mail address
|
||||
*
|
||||
* @param string $email The e-mail address of the user to retrieve
|
||||
* @return User|false The user information, or null if the user is not found
|
||||
* @return Option<User> A `Some` value with the user information if found, `None` otherwise
|
||||
* @throws DocumentException If any is encountered
|
||||
*/
|
||||
public static function findByEmail(string $email): User|false
|
||||
public static function findByEmail(string $email): Option
|
||||
{
|
||||
return Find::firstByFields(Table::USER, [Field::EQ('email', $email)], User::class);
|
||||
}
|
||||
|
@ -13,9 +13,8 @@ include '../start.php';
|
||||
|
||||
FeedReaderCentral\Security::verifyUser();
|
||||
|
||||
$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
|
||||
|
||||
if (!$item = ItemWithFeed::retrieveById($id)) not_found();
|
||||
$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
|
||||
$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...));
|
||||
|
||||
if (key_exists('action', $_GET)) {
|
||||
$flag = match ($_GET['action']) {
|
||||
|
@ -8,6 +8,7 @@
|
||||
|
||||
use BitBadger\PDODocument\{Delete, DocumentException, Field};
|
||||
use FeedReaderCentral\{Feed, Security, Table};
|
||||
use GrahamCampbell\ResultType\Error;
|
||||
|
||||
include '../../start.php';
|
||||
|
||||
@ -17,7 +18,7 @@ $feedId = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
|
||||
try {
|
||||
if (!($feed = Feed::retrieveById($feedId))) not_found();
|
||||
$feed = Feed::retrieveById($feedId)->getOrCall(not_found(...));
|
||||
Delete::byFields(Table::ITEM, [Field::EQ('feed_id', $feed->id)]);
|
||||
Delete::byId(Table::FEED, $feed->id);
|
||||
add_info('Feed “' . htmlentities($feed->title) . '” deleted successfully');
|
||||
@ -35,15 +36,15 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') {
|
||||
} else {
|
||||
$feedId = (int)$_POST['id'];
|
||||
$toEdit = Feed::retrieveById($feedId);
|
||||
$result = $toEdit
|
||||
? Feed::update($toEdit, $_POST['url'])
|
||||
: ['error' => "Feed $feedId not found"];
|
||||
$result = $toEdit->isDefined()
|
||||
? Feed::update($toEdit->get(), $_POST['url'])
|
||||
: Error::create("Feed $feedId not found");
|
||||
}
|
||||
if (key_exists('ok', $result)) {
|
||||
if ($result->success()->isDefined()) {
|
||||
add_info('Feed saved successfully');
|
||||
frc_redirect('/feeds');
|
||||
}
|
||||
add_error($result['error']);
|
||||
add_error($result->error()->get());
|
||||
$feedId = 'error';
|
||||
} catch (DocumentException $ex) {
|
||||
add_error("$ex");
|
||||
@ -55,9 +56,9 @@ if ($feedId == -1) {
|
||||
$feed = new Feed(id: -1);
|
||||
} else {
|
||||
$title = 'Edit RSS Feed';
|
||||
if ($feedId == 'error') {
|
||||
$feed = new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? '');
|
||||
} elseif (!($feed = Feed::retrieveById((int)$feedId))) not_found();
|
||||
$feed = $feedId == 'error'
|
||||
? new Feed(id: (int)$_POST['id'], url: $_POST['url'] ?? '')
|
||||
: Feed::retrieveById((int)$feedId)->getOrCall(not_found(...));
|
||||
}
|
||||
|
||||
page_head($title); ?>
|
||||
|
@ -13,7 +13,7 @@ include '../../start.php';
|
||||
FeedReaderCentral\Security::verifyUser();
|
||||
|
||||
$id = key_exists('id', $_GET) ? (int)$_GET['id'] : -1;
|
||||
if (!($feed = Feed::retrieveById($id))) not_found();
|
||||
$feed = Feed::retrieveById($id)->getOrCall(not_found(...));
|
||||
|
||||
$list = match (true) {
|
||||
key_exists('unread', $_GET) => ItemList::unreadForFeed($feed->id),
|
||||
|
@ -26,7 +26,7 @@ foreach ($feeds->items() as /** @var Feed $feed */ $feed) {
|
||||
SELECT (SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed) AS total,
|
||||
(SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_read' = 0) AS unread,
|
||||
(SELECT COUNT(*) FROM $item WHERE data->>'feed_id' = :feed AND data->>'is_bookmarked' = 1) AS marked
|
||||
SQL, [':feed' => $feed->id], new ArrayMapper()) ?? ['total' => 0, 'unread' => 0, 'marked' => 0];
|
||||
SQL, [':feed' => $feed->id], new ArrayMapper())->getOrElse(['total' => 0, 'unread' => 0, 'marked' => 0]);
|
||||
echo '<p><strong>' . htmlentities($feed->title) . '</strong><br>'
|
||||
. '<span class=meta><em>Last Updated ' . date_time($feed->updated_on) . ' • '
|
||||
. 'As of ' . date_time($feed->checked_on) . '</em><br>' . hx_get("/feed/?id=$feed->id", 'Edit') . ' • '
|
||||
|
@ -14,10 +14,10 @@ FeedReaderCentral\Security::verifyUser();
|
||||
|
||||
if (key_exists('refresh', $_GET)) {
|
||||
$refreshResult = Feed::refreshAll();
|
||||
if (key_exists('ok', $refreshResult)) {
|
||||
if ($refreshResult->success()->isDefined()) {
|
||||
add_info('All feeds refreshed successfully');
|
||||
} else {
|
||||
add_error(nl2br($refreshResult['error']));
|
||||
add_error(nl2br($refreshResult->error()->get()));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -42,7 +42,7 @@ if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
|
||||
frc_redirect($from);
|
||||
}
|
||||
|
||||
if (!$item = ItemWithFeed::retrieveById($id)) not_found();
|
||||
!$item = ItemWithFeed::retrieveById($id)->getOrCall(not_found(...));
|
||||
try {
|
||||
Patch::byId(Table::ITEM, $id, ['is_read' => 1]);
|
||||
} catch (DocumentException $ex) {
|
||||
|
@ -41,7 +41,8 @@ function display_help(): never
|
||||
function json_column_exists(): bool
|
||||
{
|
||||
try {
|
||||
$table = Custom::single("SELECT sql FROM sqlite_master WHERE tbl_name='frc_user'", [], new ArrayMapper());
|
||||
$table = Custom::single("SELECT sql FROM sqlite_master WHERE tbl_name='frc_user'", [], new ArrayMapper())
|
||||
->getOrElse(['sql' => '']);
|
||||
return $table && substr_compare(strtolower($table['sql']), 'data text not null', 0) >= 0;
|
||||
} catch (DocumentException $ex) {
|
||||
printfn("ERR $ex");
|
||||
|
@ -37,10 +37,13 @@ function refresh_all(): void
|
||||
foreach (Feed::retrieveAll()->items() as /** @var Feed $feed */ $feed) {
|
||||
$result = Feed::refreshFeed($feed->id, $feed->url);
|
||||
$userKey = "$feed->user_id";
|
||||
if (!key_exists($userKey, $users)) $users[$userKey] = Find::byId(Table::USER, $feed->user_id, User::class);
|
||||
if (array_key_exists('error', $result)) {
|
||||
if (!key_exists($userKey, $users)) {
|
||||
$users[$userKey] = Find::byId(Table::USER, $feed->user_id, User::class)
|
||||
->getOrElse(new User(email: 'user-not-found'));
|
||||
}
|
||||
if ($result->error()->isDefined()) {
|
||||
printfn('ERR (%s) %s', $users[$userKey]->email, $feed->url);
|
||||
printfn(' %s', $result['error']);
|
||||
printfn(' %s', $result->error()->get());
|
||||
} else {
|
||||
printfn('OK (%s) %s', $users[$userKey]->email, $feed->url);
|
||||
}
|
||||
|
@ -92,7 +92,7 @@ function add_user(): void
|
||||
try {
|
||||
// Ensure there is not already a user with this e-mail address
|
||||
$user = User::findByEmail($argv[2]);
|
||||
if ($user) {
|
||||
if ($user->isDefined()) {
|
||||
printfn('A user with e-mail address "%s" already exists', $argv[2]);
|
||||
return;
|
||||
}
|
||||
@ -126,7 +126,7 @@ function set_password(string $email, string $password): void
|
||||
|
||||
// Ensure this user exists
|
||||
$user = User::findByEmail($email);
|
||||
if (!$user) {
|
||||
if ($user->isEmpty()) {
|
||||
printfn('No %s exists', $displayUser);
|
||||
return;
|
||||
}
|
||||
@ -152,12 +152,13 @@ function delete_user(string $email): void
|
||||
$displayUser = display_user($email);
|
||||
|
||||
// Get the user for the provided e-mail address
|
||||
$user = User::findByEmail($email);
|
||||
if (!$user) {
|
||||
$tryUser = User::findByEmail($email);
|
||||
if ($tryUser->isEmpty()) {
|
||||
printfn('No %s exists', $displayUser);
|
||||
return;
|
||||
}
|
||||
|
||||
$user = $tryUser->get();
|
||||
try {
|
||||
$feedCount = Count::byFields(Table::FEED, [Field::EQ('user_id', $user->id)]);
|
||||
} catch (DocumentException $ex) {
|
||||
@ -196,12 +197,13 @@ function migrate_single_user(): void
|
||||
global $argv;
|
||||
|
||||
try {
|
||||
if (!$single = User::findByEmail(Security::SINGLE_USER_EMAIL)) {
|
||||
$single = User::findByEmail(Security::SINGLE_USER_EMAIL);
|
||||
if ($single->isEmpty()) {
|
||||
printfn('There is no single-user mode user to be migrated');
|
||||
return;
|
||||
}
|
||||
|
||||
Patch::byId(Table::USER, $single->id,
|
||||
Patch::byId(Table::USER, $single->get()->id,
|
||||
['email' => $argv[2], 'password' => password_hash($argv[3], Security::PW_ALGORITHM)]);
|
||||
|
||||
printfn('The single user has been moved to "%s", with password "%s"', $argv[2], $argv[3]);
|
||||
|
Loading…
Reference in New Issue
Block a user