fix rss parser; add debug mode

This commit is contained in:
Simon Vieille 2021-04-23 13:15:11 +02:00
parent cb47510829
commit 1f3dbf92fc
2 changed files with 42 additions and 17 deletions

View File

@ -15,6 +15,8 @@ $ cp config.ini.dist config.ini
Example of `config.ini` :
```ini
debug = false
[feed]
url = "https://www.example.com/feed/"

View File

@ -2,48 +2,65 @@
chdir(__DIR__);
$options = getopt("c:");
$options = getopt('c:');
$config = parse_ini_file($options['c'] ?? 'config.ini', true);
$debug = (bool) ($config['debug'] ?? false);
$feedUrl = $config['feed']['url'];
$hookUrl = $config['mattermost']['hook_url'];
$cacheFile = $config['cache']['file'];
$template = $config['mattermost']['message_template'];
$cache = [];
$commands = [];
if (file_exists($cacheFile)) {
$cache = json_decode(file_get_contents($cacheFile), true);
if ($cache === null) {
if (null === $cache) {
$cache = [];
}
}
$feedContent = file_get_contents($feedUrl);
$xml = simplexml_load_file($feedUrl);
$entries = array_merge($xml->xpath('//entry'), $xml->xpath('//item'));
preg_match_all('#<title><!\[CDATA\[(.*)\]\]></title>#isU', $feedContent, $titles, PREG_SET_ORDER);
preg_match_all('#<link>(.*)</link>#isU', $feedContent, $links, PREG_SET_ORDER);
foreach ($entries as $entry) {
$title = (string) $entry->title;
$url = null;
$commands = [];
foreach ($entry->link as $link) {
if (null !== $url) {
continue;
}
foreach ($titles as $key => $title) {
$link = $links[$key] ?? null;
$attributes = $link->attributes();
$content = (string) $link;
$href = (string) ($attributes['href'] ?? '');
$type = (string) ($attributes['type'] ?? '');
if (!$link) {
if ('' !== $type && 'text/html' !== $type) {
continue;
}
if ('' !== $href) {
$url = $href;
} elseif ('' !== $content) {
$url = $content;
}
}
if (empty($url)) {
continue;
}
$title = $title[1];
$link = $link[1];
$hash = md5($title.$link);
$hash = md5($title.$url);
if (!isset($cache[$hash])) {
$cache[$hash] = true;
$json = json_encode([
'text' => sprintf($template, $title, $link),
'text' => sprintf($template, $title, $url),
]);
$commands[] = sprintf(
@ -54,8 +71,14 @@ foreach ($titles as $key => $title) {
}
}
file_put_contents($cacheFile, json_encode($cache));
if (!$debug) {
file_put_contents($cacheFile, json_encode($cache));
}
foreach ($commands as $command) {
shell_exec($command);
if ($debug) {
echo $command, "\n";
} else {
shell_exec($command);
}
}