package com.example.process.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebBrowserController {
@GetMapping("/start")
public void startBrowser(@RequestParam("browser") String browser, @RequestParam("url") String url) throws Exception {
ProcessBuilder processBuilder = new ProcessBuilder(browser, url);
processBuilder.start();
}
@GetMapping("/stop")
public void stopBrowser(@RequestParam("browser") String browser) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder("pkill", browser);
processBuilder.start();
}
@GetMapping("/getUrl")
public String getActiveTabUrl(@RequestParam("browser") String browser) throws IOException {
try {
ProcessBuilder processBuilder = new ProcessBuilder(
"xdotool",
"search",
"--onlyvisible",
"--class",
browser.toLowerCase(),
"windowactivate",
"key",
"--clearmodifiers",
"ctrl+l",
"ctrl+c"
);
Process process = processBuilder.start();
process.waitFor();
Thread.sleep(100);
ProcessBuilder clipboardProcess = new ProcessBuilder("xclip", "-o", "-selection", "clipboard");
Process getClipboardProcess = clipboardProcess.start();
BufferedReader reader = new BufferedReader(
new InputStreamReader(getClipboardProcess.getInputStream())
);
String activeTabUrl = reader.readLine();
reader.close();
System.out.println("Active browser URL: " + activeTabUrl);
return activeTabUrl;
} catch (Exception e) {
e.printStackTrace();
return "Error: " + e.getMessage();
}
}
@GetMapping("/cleanup")
public String cleanupBrowserSession(@RequestParam("browser") String browser) {
try {
ProcessBuilder processBuilder = new ProcessBuilder(
"xdotool",
"search",
"--class",
browser.toLowerCase(),
"windowkill"
);
Process process = processBuilder.start();
int exitCode = process.waitFor();
if (exitCode == 0) {
return "Successfully cleaned up " + browser + " sessions";
} else {
return "No active " + browser + " sessions found to clean up";
}
} catch (Exception e) {
e.printStackTrace();
return "Error during cleanup: " + e.getMessage();
}
}
}