deployment-dcdn/assets/webhook.php

71 lines
1.9 KiB
PHP
Raw Permalink Normal View History

2024-02-25 19:17:44 +01:00
<?php
2024-05-02 23:54:06 +02:00
// https://docs.gitea.com/usage/webhooks
2024-02-25 19:17:44 +01:00
// check for POST request
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
error_log('FAILED - not POST - '. $_SERVER['REQUEST_METHOD']);
exit();
}
// get content type
$content_type = isset($_SERVER['CONTENT_TYPE']) ? strtolower(trim($_SERVER['CONTENT_TYPE'])) : '';
if ($content_type != 'application/json') {
error_log('FAILED - not application/json - '. $content_type);
exit();
}
// get payload
$payload = trim(file_get_contents("php://input"));
if (empty($payload)) {
error_log('FAILED - no payload');
exit();
}
// convert json to array
$decoded = json_decode($payload, true);
// check for json decode errors
if (json_last_error() !== JSON_ERROR_NONE) {
error_log('FAILED - json decode - '. json_last_error());
exit();
}
// success, do something
2024-05-02 23:54:06 +02:00
$current_date = date('d-m-y_H-i-s', time());
$log_directory = '../webhook/logs';
// create the log folder if needed
if (!file_exists($log_directory)) {
mkdir($log_directory, 0777, true);
}
// clean the log folder if needed
if (count(scandir($log_directory)) > 10) {
$files = scandir($log_directory);
$log_files = array_diff($files, array('.', '..'));
usort($files, function($a, $b) use ($log_directory) {
return filemtime("$log_directory/$a") - filemtime("$log_directory/$b");
});
for ($i = 0; $i < 5; $i++) {
unlink("$log_directory/{$files[$i]}");
}
}
if (isset($decoded['repository'])) {
// git hook
echo shell_exec('bash ../webhook/webhook.sh ' . 'git' . ' >> ' . $log_directory . '/webhook_' . $current_date . '.log 2>&1');
} else {
// directus hook
$debounce_delay = 1 * 60;
file_put_contents("debounce_hook", time());
sleep($debounce_delay);
if (time() >= intval(file_get_contents('debounce_hook')) + $debounce_delay) {
echo shell_exec('bash ../webhook/webhook.sh ' . 'directus' . ' >> ' . $log_directory . '/webhook_' . $current_date . '.log 2>&1');
}
}
?>