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` : Example of `config.ini` :
```ini ```ini
debug = false
[feed] [feed]
url = "https://www.example.com/feed/" url = "https://www.example.com/feed/"

View file

@ -2,48 +2,65 @@
chdir(__DIR__); chdir(__DIR__);
$options = getopt("c:"); $options = getopt('c:');
$config = parse_ini_file($options['c'] ?? 'config.ini', true); $config = parse_ini_file($options['c'] ?? 'config.ini', true);
$debug = (bool) ($config['debug'] ?? false);
$feedUrl = $config['feed']['url']; $feedUrl = $config['feed']['url'];
$hookUrl = $config['mattermost']['hook_url']; $hookUrl = $config['mattermost']['hook_url'];
$cacheFile = $config['cache']['file']; $cacheFile = $config['cache']['file'];
$template = $config['mattermost']['message_template']; $template = $config['mattermost']['message_template'];
$cache = [];
$commands = [];
if (file_exists($cacheFile)) { if (file_exists($cacheFile)) {
$cache = json_decode(file_get_contents($cacheFile), true); $cache = json_decode(file_get_contents($cacheFile), true);
if ($cache === null) { if (null === $cache) {
$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); foreach ($entries as $entry) {
preg_match_all('#<link>(.*)</link>#isU', $feedContent, $links, PREG_SET_ORDER); $title = (string) $entry->title;
$url = null;
$commands = []; foreach ($entry->link as $link) {
if (null !== $url) {
continue;
}
foreach ($titles as $key => $title) { $attributes = $link->attributes();
$link = $links[$key] ?? null; $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; continue;
} }
$title = $title[1]; $hash = md5($title.$url);
$link = $link[1];
$hash = md5($title.$link);
if (!isset($cache[$hash])) { if (!isset($cache[$hash])) {
$cache[$hash] = true; $cache[$hash] = true;
$json = json_encode([ $json = json_encode([
'text' => sprintf($template, $title, $link), 'text' => sprintf($template, $title, $url),
]); ]);
$commands[] = sprintf( $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) { foreach ($commands as $command) {
shell_exec($command); if ($debug) {
echo $command, "\n";
} else {
shell_exec($command);
}
} }