testing new uploader

This commit is contained in:
Janis Steiner
2025-02-28 17:00:53 +00:00
parent 7627f33503
commit c236b4a495
7 changed files with 704 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
<?php
//this file returns a list of available printers, theyr status and theyr color
session_start();
$file_path=$_SESSION["current_file"];
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$class=$_SESSION["class_id"];
include "../../config/config.php";
//check if printers are reserved right now or will be while print is running
$is_unsafe=check_file($file_path);
echo(json_encode(["status"=>$is_unsafe]));
function extract_param($gcode) {
// Match the pattern S followed by digits, capturing the digits
$matches = [];
$pattern = '/[S|T]([0-9]+)/';
if (preg_match($pattern, $gcode, $matches)) {
return (int)$matches[1]; // Return the first capture group as an integer
} else {
return false; // No match found
}
}
function check_file($path){//check file for temperature which are to high
$file = fopen($path, 'r');
$cnt=0;
while (!feof($file)&&$cnt!=2) {
$line = fgets($file);
// Extract parameter from lines with specific commands
if (strpos($line, 'M104') !== false || strpos($line, 'M140') !== false) {
$cnt++;
$parameter = extract_param($line);
if(strpos($line, 'M104') !== false){ //extruder_temp
$ex_temp=$parameter;
}
if(strpos($line, 'M140') !== false){ //bed temp
$bed_temp=$parameter;
}
}
}
//echo("bed:$bed_temp;ex:$ex_temp");
if($bed_temp>75 or $ex_temp>225){
return 1;
}else{
return 0;
}
}
?>

View File

@@ -0,0 +1,150 @@
<?php
date_default_timezone_set('Europe/Zurich');
//this file returns a list of available printers, theyr status and theyr color
session_start();
$file_path=$_SESSION["current_file"];
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$class=$_SESSION["class_id"];
include "../../config/config.php";
//check if printers are reserved right now or will be while print is running
$is_reserved=check_reservation_conflict($link, $class);
if($is_reserved==0){
$is_reserved=check_print_reservation_conflict($link, $class, $file_path);
}
echo(json_encode(["status"=>$is_reserved]));
function find_print_time($file) {
$handle = fopen($file, "r");
$targetPhrase = "; estimated printing time (normal mode) = ";
$time = null;
while (($line = fgets($handle)) !== false) {
if (strpos($line, $targetPhrase) !== false) {
// Extract the time after the target phrase
$time = trim(str_replace($targetPhrase, "", $line));
break; // Stop once the desired line is found
}
}
fclose($handle);
return $time;
}
function check_reservation_conflict($link, $class) {
$reservation_conflict = false;
$today = date("Y-m-d");
$time_now = date("H:i");
$for_class = [];
// Query for reservations that start today or extend into today
$sql = "
SELECT day, time_from, time_to, for_class
FROM reservations
WHERE day <= '$today' AND
(day = '$today' AND time_from <= '$time_now' OR day < '$today');
";
$stmt = $link->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// Calculate the actual end time of the reservation
$reservation_end = strtotime($row["day"] . " " . $row["time_to"]);
$current_time = strtotime("$today $time_now");
if ($current_time <= $reservation_end) {
$reservation_conflict = true;
$for_class[] = $row["for_class"];
}
}
// Default value for for_class if no conflicts are found
if (empty($for_class)) {
$for_class[] = 0;
}
// Determine the appropriate response based on the conflict status
$response = 0;
if ($reservation_conflict && !in_array($class, $for_class) && $class != 0) {
$response=1;
} elseif ($class == 0 && $reservation_conflict) {
$response=2;
}
return $response;
}
function check_print_reservation_conflict($link, $class, $path) {
$reservation_conflict = false;
$for_class = [];
$today = date("Y-m-d");
$time_now = date("H:i");
// Calculate the end time of the print
$print_time = find_print_time($path); // Assume this function is already defined
preg_match('/(\d+)h/', $print_time, $hours_match);
preg_match('/(\d+)m/', $print_time, $minutes_match);
$hours = isset($hours_match[1]) ? (int)$hours_match[1] : 0;
$minutes = isset($minutes_match[1]) ? (int)$minutes_match[1] : 0;
//echo("uses ".$minutes." Minutes and ".$hours." hours");
$start_time = DateTime::createFromFormat('H:i', $time_now);
$end_time = clone $start_time;
$end_time->modify("+{$hours} hour");
$end_time->modify("+{$minutes} minutes");
// Query to get all relevant reservations (today and future overlaps)
$sql = "
SELECT day, time_from, time_to, for_class
FROM reservations
WHERE day >= '$today';
";
$stmt = $link->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
// Check for conflicts with reservations
while ($row = $result->fetch_assoc()) {
$reservation_start = DateTime::createFromFormat('Y-m-d H:i', $row["day"] . ' ' . $row["time_from"]);
$reservation_end = DateTime::createFromFormat('Y-m-d H:i', $row["day"] . ' ' . $row["time_to"]);
// Adjust reservation end time for multi-day overlaps
if ($reservation_end < $reservation_start) {
$reservation_end->modify('+1 day');
}
// Check if the print overlaps with any reservation period
if ($start_time < $reservation_end && $end_time > $reservation_start) {
$reservation_conflict = true;
$for_class[] = $row["for_class"];
}
}
// Default value for for_class if no conflicts are found
if (empty($for_class)) {
$for_class[] = 0;
}
// Build response based on conflict and user access
$response = 0;
if ($reservation_conflict && !in_array($class, $for_class) && $class != 0) {
$response=1;
} elseif ($class == 0 && $reservation_conflict) {
$response=2;
}
return $response;
}
?>

View File

@@ -0,0 +1,10 @@
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$username=$_SESSION["username"];
$path = "/var/www/html/user_files/$username/";
$_SESSION["current_file"]=$path.$_GET["file"];
?>

View File

@@ -0,0 +1,29 @@
<?php
//this file returns a list of available printers, theyr status and theyr color
session_start();
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$sql = "SELECT p.id, f.name AS color, p.free, p.system_status
FROM printer p
LEFT JOIN filament f ON p.color = f.internal_id
ORDER BY p.id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$printers = [];
while ($row = mysqli_fetch_assoc($result)) {
$printers[] = [
'id' => $row['id'],
'free' => $row['free'],
'error_status' => $row['system_status'],
'color' => htmlspecialchars($row['color'], ENT_QUOTES, 'UTF-8')
];
}
echo json_encode($printers);
?>

View File

@@ -0,0 +1,373 @@
<?php
//auth stuff
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
header("location: /login/login.php");
exit;
}
$username=htmlspecialchars($_SESSION["username"]);
?>
<!DOCTYPE html>
<html lang="de" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>System0 - Print</title>
<?php include "../../assets/components.php"; ?>
</head>
<body>
<script src="/assets/js/load_page.js"></script>
<script>
function load_user()
{
$(document).ready(function(){
$('#content').load("/assets/php/user_page.php");
});
$(document).ready(function(){
$('#footer').load("/assets/html/footer.html");
});
}
</script>
<script type='text/javascript' >load_user()</script>
<?php
if(isset($_GET["cloudprint"])){
echo("<script>let cloudprint=1;</script>");
}else{
echo("<script>let cloudprint=0;</script>");
}
?>
<!-- navbar -->
<div id="content"></div>
<!-- div where all our content goes -->
<div style="min-height:95vh">
<!-- we need to show a file upload thing and offer the selectnio of printers -->
<div class="container mt-5 d-flex justify-content-center">
<form>
<div class="mb-3">
<label for="fileUpload" class="form-label">3D-Druck Datei</label>
<?php
if(isset($_GET["cloudprint"])){
echo('<input type="text" value="'.$_GET["cloudprint"].'" class="form-control" disabled id="file_upload">');
}else{
echo('<input type="file" class="form-control" accept=".gcode" id="file_upload">');
}
?>
</div>
<div class="mb-3">
<label for="selectOption" class="form-label">Drucker</label>
<select class="form-select" id="selectOption">
<option selected value="not_set">Bitte wähle einen Drucker</option>
</select>
</div>
<a style="cursor: pointer" onclick="start_upload(1)" class="btn btn-primary">Drucken</a>
</form>
</div>
</div>
<!-- footer -->
<div id="footer"></div>
<script>
let global_error="";
//js to handle backend requests
//load printers
document.addEventListener("DOMContentLoaded", function () {
const selectElement = document.getElementById("selectOption");
const apiUrl = "/api/uploader/fetch_printers.php"; // Replace with your actual API URL
function getUrlParam(name) {
const urlParams = new URLSearchParams(window.location.search);
return urlParams.get(name);
}
const preselectId = getUrlParam("preselect"); // Get "preselect" value from URL
fetch(apiUrl)
.then(response => response.json())
.then(data => {
data.forEach(item => {
const option = document.createElement("option");
option.value = item.id;
if(item.free==0){
option.textContent = `Drucker ${item.id} - ${item.color}`;
}else{
option.textContent = `Drucker ${item.id} - ${item.color} - Warteschlange`;
}
if (item.id == preselectId) {
option.selected = true;
}
selectElement.appendChild(option);
});
})
.catch(error => console.error("Error fetching data:", error));
});
async function start_upload(use_checks){
//main function handles the steps from user pressing upload button via checking params to starting job via api
//we have a modal that shows progress to the user
document.getElementById("close_progress_modal").style.display = "none";
document.getElementById("close_progress_modal2").style.display = "none";
let steps = [
"Initialisierung",
"Datei auf System0 Hochladen",
"Nach Reservationskonflikten suchen",
"Nach Invaliden Druckeinstellungen suchen",
"Job an Drucker senden",
"Fertig!"
];
let progressContent = document.getElementById("progressContent");
progressContent.innerHTML = ""; // Clear previous content
let modal = new bootstrap.Modal(document.getElementById("progressModal"));
modal.show();
add_step(0,progressContent,steps);
//initialising => set all vars to 0 etc
finish_step(0,progressContent,steps);
if(cloudprint==0){
add_step(1,progressContent,steps);
//upload file to system0
if(await upload_file()==0){
finish_step(1,progressContent,steps);
}else{
add_error("Fehler beim Upload der Datei - "+global_error,progressContent);
cancel_step(1,progressContent,steps);
show_close_button();
return;
}
}else{
//just tell the server what the file is.
await fetch("/api/uploader/cloudprint.php?file=<?php echo($_GET['cloudprint']); ?>");
}
global_error="";
//check if there is a reservation ongoing during this print
add_step(2,progressContent,steps);
let status=await check_reservations();
if(status==0){
finish_step(2,progressContent,steps);
}else if(status==1){
//reserved and user is student
add_error("Die Drucker sind zurzeit reserviert. Bitte versuche es später erneut.");
cancel_step(2,progressContent,steps);
show_close_button();
return;
}else if(status==2){
//reserved but user is admin
add_warning("Die Drucker sind Zurzeit reserviert. Als Lehrperson wird ihr Druck allerdings trozdem gedruckt. Bitte gehen Sie sicher, dass nicht eine Klasse beeinträchtigt wird.",progressContent);
finish_step(2,progressContent,steps);
}else{
add_error("Fehler beim überprüfen der Reservationen - "+global_error,progressContent);
cancel_step(2,progressContent,steps);
show_close_button();
return;
}
global_error="";
//search for invalid print settings.
add_step(3,progressContent,steps);
status=await check_illegal_settings(progressContent);
if(status==0){
finish_step(3,progressContent,steps);
}else if(use_checks==0){
add_warning("Warnung: Dieser Druck wird mit sehr hohen Temparaturen gedruckt. Dies kann zur zerstörung des Druckers führen!",progressContent);
finish_step(3,progressContent,steps);
}else if(status==1){
add_error("Achtung deine Drucktemparatur ist sehr hoch eingestellt. Dies kann zur zerstörung des Druckers führen! Bitte fahre nur fort, wenn du dir sicher bist, was du tust!",progressContent);
add_circumvent_link(progressContent);
cancel_step(3,progressContent,steps);
show_close_button();
return;
}else{
add_error("Fehler beim prüfen der Druckeinstellungen",progressContent);
cancel_step(3,progressContent,steps);
show_close_button();
return;
}
global_error="";
//send to printer
add_step(4,progressContent,steps);
status=await start_job();
if(status==0){
finish_step(4,progressContent,steps);
add_step(5,progressContent,steps);
finish_step(5,progressContent,steps);
add_success("Job erfolgreich gestartet",progressContent);
}else{
add_error("Fehler beim starten des Jobs. "+global_error, progressContent);
cancel_step(4,progressContent,steps);
show_close_button();
return;
}
}
function add_circumvent_link(progressContent) {
let stepHtml = `
<div>
<a onclick="start_upload(0);" target="_blank" class="step-link">Drücke hier, um alle überprüfungen zu umgehen</a>
</div>
`;
progressContent.innerHTML += stepHtml;
}
function finish_step(index,progressContent,steps){
let stepId = "step-" + index;
let stepElement = document.getElementById(stepId);
if (stepElement) {
stepElement.innerHTML = `
<span class="text-success fw-bold">✔</span>
<span>${steps[index]}</span>
`;
}
if (index >= steps.length-1){
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
}
function show_close_button(){
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
function cancel_step(index,progressContent,steps){
let stepId = "step-" + index;
let stepElement = document.getElementById(stepId);
if (stepElement) {
stepElement.innerHTML = `
<span class="text-success fw-bold">❌</span>
<span>${steps[index]}</span>
`;
}
document.getElementById("close_progress_modal").style.display = "block";
document.getElementById("close_progress_modal2").style.display = "block";
}
function add_error(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-danger' role='alert'>Fehler - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_success(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-success' role='alert'>Erfolg - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_warning(msg,progressContent){
let errorHtml = `
<br>
<div class='alert alert-warning' role='alert'>Warnung - ${msg}</div>
`;
progressContent.innerHTML += errorHtml;
}
function add_step(index,progressContent,steps) {
let stepId = "step-" + index;
let stepHtml = `
<div class="step-container" id="${stepId}">
<span class="spinner-border text-primary" role="status"></span>
<span>${steps[index]}</span>
</div>
`;
progressContent.innerHTML += stepHtml;
}
async function check_illegal_settings(progressContent){
try {
const response = await fetch("/api/uploader/check_illegal_settings.php");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
if(data["status"]!=0){
global_error="Dieser Fehler ist auf dem Drucker. Warte einige Minuten und versuche es erneut.";
}
return data["status"];
} catch (error) {
return 4;
}
}
async function start_job(){
let printer_id=document.getElementById("selectOption").value;
if(printer_id=="not_set"){
global_error="Kein Drucker ausgewählt";
return 5;
}
try {
const response = await fetch("/api/uploader/start_job.php?printer="+printer_id);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data["status"];
} catch (error) {
return 5;
}
}
async function upload_file(){
const fileInput = document.getElementById('file_upload');
const file = fileInput.files[0];
if (!file) {
global_error="Keine Datei ausgewählt";
return 1;
}
const formData = new FormData();
formData.append('file', file);
try {
const response = await fetch('/api/uploader/upload_file.php', {
method: 'POST',
body: formData,
});
if (response.ok) {
const result = await response.json();
if(result.status=="error"){
global_error=result.message;
return 1;
}
} else {
return 1;
}
} catch (error) {
return 1;
}
return 0;
}
async function check_reservations() {
try {
const response = await fetch("/api/uploader/check_reservations.php");
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data["status"];
} catch (error) {
return 4;
}
}
</script>
<!-- progress modal -->
<div class="modal fade" id="progressModal" tabindex="1" data-bs-backdrop="static" data-bs-keyboard="false" role="dialog" aria-labelledby="progressModalLabel" aria-hidden="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="progressModalLabel">Fortschritt</h5>
<button id="close_progress_modal" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Schliessen"></button>
</div>
<div class="modal-body">
<div id="progressContent"></div>
</div>
<div class="modal-footer">
<button id="close_progress_modal2" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Schliessen</button>
</div>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,57 @@
<?php
//this file returns a list of available printers, theyr status and theyr color
session_start();
$file_path=$_SESSION["current_file"];
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
include "../../config/config.php";
//if printer is ready, upload to printer, else upload to queue
//return 0 if success, else return any int
$printer_id=intval($_GET["printer_id"]);
//check if printer is ready
$sql="select printer_url, free, system_status,apikey,printer_url from printer where id=$printer_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt, $url,$free,$status,$apikey,$printer_url);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
$result=1;
$username=$_SESSION["username"];
$userid=$_SESSION["id"];
if($free==1 && $status==0){
//upload to printer
exec('curl -k -H "X-Api-Key: '.$apikey.'" -F "select=true" -F "print=true" -F "file=@'.$path.'" "'.$printer_url.'/api/files/local" > /var/www/html/user_files/'.$username.'/json.json');
$fg=file_get_contents("/var/www/html/user_files/$username/json.json");
$json=json_decode($fg,true);
if($json['effectivePrint']==false or $json["effectiveSelect"]==false)
{
$result=1;
}
else
{
$sql="update printer set free=0, printing=1,mail_sent=0, used_by_userid=$userid where id=$printer_id";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$result=0;
}
}else if($free!=1 && $status==0){
//upload to queue
$path=$_SESSION["current_file"];
$sql="INSERT INTO queue (from_userid,filepath,print_on) VALUES (?,?,?)";
$stmt = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($stmt, "isi", $userid,$path,$printer_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
$result=0;
}else{
//error
$result=1;
}
echo(json_encode(["status"=>$result]));
?>

View File

@@ -0,0 +1,33 @@
<?php
session_start();
include "../../config/config.php";
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true or $_SESSION["role"][0]!=="1"){
die("no_auth");
exit;
}
$username=$_SESSION["username"];
$path = "/var/www/html/user_files/$username/";
if ($_SERVER["REQUEST_METHOD"] === "POST") {
if (isset($_FILES["file"]) && $_FILES["file"]["error"] === UPLOAD_ERR_OK) {
$fileTmpPath = $_FILES["file"]["tmp_name"];
$fileName = basename($_FILES["file"]["name"]);
$filePath = $path . $fileName;
$filetype = strtolower(pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION));
if($filetype==="gcode"){
if (move_uploaded_file($fileTmpPath, $filePath)) {
echo json_encode(["status" => "success", "message" => "Datei hochgeladen", "file" => $filePath]);
$_SESSION["current_file"]="$filePath";
} else {
echo json_encode(["status" => "error", "message" => "Konnte datei nicht in Benutzerordner verschieben"]);
}
}else{
echo json_encode(["status" => "error", "message" => "Dieser Dateityp wird nicht unterstützt"]);
}
} else {
echo json_encode(["status" => "error", "message" => "Unbekannter Fehler"]);
}
} else {
echo json_encode(["status" => "error", "message" => "Invalide Anfrage"]);
}
?>