matrix-procmonitor/procmon.php

67 lines
2.4 KiB
PHP
Raw Permalink Normal View History

2024-07-09 01:22:43 +00:00
<?php
// NOTE!: You will need to make the following files to configure matrix-procmonitor to use your Matrix room:
// token.txt: get access token from a logged-in Element (Settings -> Help & About -> Access Token)
// homeserver.txt: the homeserver of the user the token is for
// room_server.txt: the server the room is on (Room Options -> Settings -> Advanced -> Internal Room ID, after colon)
// room_id.txt: the room ID on the server (Room Options -> Settings -> Advanced -> Internal Room ID, before colon, no !)
// consider setting this to contain your username so that you will be notified
$notify_string = "yourusername:";
$search_string = "Found Something!";
$monitor_command = "php test-process.php 2>&1";
//older PHPs don't have str_contains so we have this
function instr($haystack, $needle){
return(strpos($haystack, $needle) !== false);
}
function matrix_post($content){
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => '{"msgtype":"m.text", "body": "' . $content . '"}',
)
);
$context = stream_context_create($options);
file_get_contents("https://" . $GLOBALS['homeserver'] . ":8448/_matrix/client/r0/rooms/%21" . $GLOBALS['room_id'] . ":" . $GLOBALS['room_server'] . "/send/m.room.message?access_token=" . $GLOBALS['token'], false, $context);
}
$GLOBALS['token'] = trim(file_get_contents("token.txt"));
$GLOBALS['room_id'] = trim(file_get_contents("room_id.txt"));
$GLOBALS['room_server'] = trim(file_get_contents("room_server.txt"));
$GLOBALS['homeserver'] = trim(file_get_contents("homeserver.txt"));
matrix_post("$notify_string ProcMonitor started.");
// Set up for the monitored process
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a file to write to
);
$cwd = './';
$env = array();
// Start the process to monitor
$process = proc_open($monitor_command, $descriptorspec, $pipes, $cwd, $env);
while(is_resource($process)){
$line = stream_get_line($pipes[1], 0, "\n");
echo("GOT LINE: $line\n");
matrix_post($line);
if(instr($line, $search_string)){
matrix_post("$notify_string Search String Found! See above post.");
}
}
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);