index.html 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta name="description" content="RemdesKVM Management Interface">
  7. <meta name="author" content="imuslab">
  8. <title>Connected | RemdesKVM</title>
  9. <!-- OpenGraph Metadata -->
  10. <meta property="og:title" content="RemdesKVM Management Interface">
  11. <meta property="og:description" content="A web-based management interface for RemdesKVM">
  12. <meta property="og:type" content="website">
  13. <meta property="og:url" content="https://kvm.aroz.org">
  14. <meta property="og:image" content="https://kvm.aroz.org/og.jpg">
  15. <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
  16. <link rel="stylesheet" href="/main.css">
  17. </head>
  18. <body>
  19. <img id="remoteCapture" src="/stream" oncontextmenu="return false;"></img>
  20. <script>
  21. let socket;
  22. let protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
  23. let port = window.location.port ? window.location.port : (protocol === 'wss' ? 443 : 80);
  24. let socketURL = `${protocol}://${window.location.hostname}:${port}/hid`;
  25. let mouseMoveAbsolte = true; // Set to true for absolute mouse coordinates, false for relativeZ
  26. let mouseIsOutside = false;
  27. let audioFrontendStarted = false;
  28. /* Mouse events */
  29. function handleMouseMove(event) {
  30. const hidCommand = {
  31. event: 2,
  32. mouse_x: event.clientX,
  33. mouse_y: event.clientY,
  34. };
  35. const rect = event.target.getBoundingClientRect();
  36. const relativeX = event.clientX - rect.left;
  37. const relativeY = event.clientY - rect.top;
  38. if (relativeX < 0 || relativeY < 0 || relativeX > rect.width || relativeY > rect.height) {
  39. mouseIsOutside = true;
  40. return; // Mouse is outside the client rect
  41. }
  42. mouseIsOutside = false;
  43. const percentageX = (relativeX / rect.width) * 4096;
  44. const percentageY = (relativeY / rect.height) * 4096;
  45. hidCommand.mouse_x = Math.round(percentageX);
  46. hidCommand.mouse_y = Math.round(percentageY);
  47. //console.log(`Mouse move: (${event.clientX}, ${event.clientY})`);
  48. //console.log(`Mouse move relative: (${relativeX}, ${relativeY})`);
  49. //console.log(`Mouse move percentage: (${hidCommand.mouse_x}, ${hidCommand.mouse_y})`);
  50. if (socket && socket.readyState === WebSocket.OPEN) {
  51. socket.send(JSON.stringify(hidCommand));
  52. } else {
  53. console.error("WebSocket is not open.");
  54. }
  55. }
  56. function handleMousePress(event) {
  57. event.preventDefault();
  58. event.stopImmediatePropagation();
  59. if (mouseIsOutside) {
  60. console.warn("Mouse is outside the capture area, ignoring mouse press.");
  61. return;
  62. }
  63. const buttonMap = {
  64. 0: 1,
  65. 1: 3,
  66. 2: 2
  67. }; //Map javascript mouse buttons to HID buttons
  68. const hidCommand = {
  69. event: 3,
  70. mouse_button: buttonMap[event.button] || 0
  71. };
  72. // Log the mouse button state
  73. console.log(`Mouse down: ${hidCommand.mouse_button}`);
  74. if (socket && socket.readyState === WebSocket.OPEN) {
  75. socket.send(JSON.stringify(hidCommand));
  76. } else {
  77. console.error("WebSocket is not open.");
  78. }
  79. if (!audioFrontendStarted){
  80. startAudioWebSocket();
  81. audioFrontendStarted = true;
  82. }
  83. }
  84. function handleMouseRelease(event) {
  85. event.preventDefault();
  86. event.stopImmediatePropagation();
  87. if (mouseIsOutside) {
  88. console.warn("Mouse is outside the capture area, ignoring mouse press.");
  89. return;
  90. }
  91. const buttonMap = {
  92. 0: 1,
  93. 1: 3,
  94. 2: 2
  95. }; //Map javascript mouse buttons to HID buttons
  96. const hidCommand = {
  97. event: 4,
  98. mouse_button: buttonMap[event.button] || 0
  99. };
  100. console.log(`Mouse release: ${hidCommand.mouse_button}`);
  101. if (socket && socket.readyState === WebSocket.OPEN) {
  102. socket.send(JSON.stringify(hidCommand));
  103. } else {
  104. console.error("WebSocket is not open.");
  105. }
  106. }
  107. function handleMouseScroll(event) {
  108. const hidCommand = {
  109. event: 5,
  110. mouse_scroll: event.deltaY
  111. };
  112. if (mouseIsOutside) {
  113. console.warn("Mouse is outside the capture area, ignoring mouse press.");
  114. return;
  115. }
  116. console.log(`Mouse scroll: mouse_scroll=${event.deltaY}`);
  117. if (socket && socket.readyState === WebSocket.OPEN) {
  118. socket.send(JSON.stringify(hidCommand));
  119. } else {
  120. console.error("WebSocket is not open.");
  121. }
  122. }
  123. // Attach mouse event listeners
  124. let remoteCaptureEle = document.getElementById('remoteCapture');
  125. remoteCaptureEle.addEventListener('mousemove', handleMouseMove);
  126. remoteCaptureEle.addEventListener('mousedown', handleMousePress);
  127. remoteCaptureEle.addEventListener('mouseup', handleMouseRelease);
  128. remoteCaptureEle.addEventListener('wheel', handleMouseScroll);
  129. /* Keyboard */
  130. function isNumpadEvent(event) {
  131. return event.location === 3;
  132. }
  133. function handleKeyDown(event) {
  134. event.preventDefault();
  135. event.stopImmediatePropagation();
  136. const key = event.key;
  137. let hidCommand = {
  138. event: 0,
  139. keycode: event.keyCode
  140. };
  141. console.log(`Key down: ${key} (code: ${event.keyCode})`);
  142. // Check if the key is a modkey on the right side of the keyboard
  143. const rightModKeys = ['Control', 'Alt', 'Shift', 'Meta'];
  144. if (rightModKeys.includes(key) && event.location === 2) {
  145. hidCommand.is_right_modifier_key = true;
  146. }else if (key === 'Enter' && isNumpadEvent(event)) {
  147. //Special case for Numpad Enter
  148. hidCommand.is_right_modifier_key = true;
  149. }else{
  150. hidCommand.is_right_modifier_key = false;
  151. }
  152. if (socket && socket.readyState === WebSocket.OPEN) {
  153. socket.send(JSON.stringify(hidCommand));
  154. } else {
  155. console.error("WebSocket is not open.");
  156. }
  157. }
  158. function handleKeyUp(event) {
  159. event.preventDefault();
  160. event.stopImmediatePropagation();
  161. const key = event.key;
  162. let hidCommand = {
  163. event: 1,
  164. keycode: event.keyCode
  165. };
  166. console.log(`Key up: ${key} (code: ${event.keyCode})`);
  167. // Check if the key is a modkey on the right side of the keyboard
  168. const rightModKeys = ['Control', 'Alt', 'Shift', 'Meta'];
  169. if (rightModKeys.includes(key) && event.location === 2) {
  170. hidCommand.is_right_modifier_key = true;
  171. } else if (key === 'Enter' && isNumpadEvent(event)) {
  172. //Special case for Numpad Enter
  173. hidCommand.is_right_modifier_key = true;
  174. }else{
  175. hidCommand.is_right_modifier_key = false;
  176. }
  177. if (socket && socket.readyState === WebSocket.OPEN) {
  178. socket.send(JSON.stringify(hidCommand));
  179. } else {
  180. console.error("WebSocket is not open.");
  181. }
  182. }
  183. /* Start and Stop events */
  184. function startWebSocket(){
  185. if (socket){
  186. //Already started
  187. alert("Websocket already started");
  188. return;
  189. }
  190. const socketUrl = socketURL;
  191. socket = new WebSocket(socketUrl);
  192. socket.addEventListener('open', function(event) {
  193. console.log('WebSocket is connected.');
  194. });
  195. socket.addEventListener('message', function(event) {
  196. //console.log('Message from server ', event.data);
  197. });
  198. document.addEventListener('keydown', handleKeyDown);
  199. document.addEventListener('keyup', handleKeyUp);
  200. }
  201. function stopWebSocket(){
  202. if (!socket){
  203. alert("No ws connection to stop");
  204. return;
  205. }
  206. socket.close();
  207. console.log('WebSocket is disconnected.');
  208. document.removeEventListener('keydown', handleKeyDown);
  209. document.removeEventListener('keyup', handleKeyUp);
  210. }
  211. /* Audio Streaming Frontend */
  212. let audioSocket;
  213. let audioContext;
  214. let audioQueue = [];
  215. let audioPlaying = false;
  216. //accept low, standard, high quality audio mode
  217. function startAudioWebSocket(quality="standard") {
  218. if (audioSocket) {
  219. console.warn("Audio WebSocket already started");
  220. return;
  221. }
  222. let protocol = window.location.protocol === 'https:' ? 'wss' : 'ws';
  223. let port = window.location.port ? window.location.port : (protocol === 'wss' ? 443 : 80);
  224. let audioSocketURL = `${protocol}://${window.location.hostname}:${port}/audio?quality=${quality}`;
  225. audioSocket = new WebSocket(audioSocketURL);
  226. audioSocket.binaryType = 'arraybuffer';
  227. audioSocket.onopen = function() {
  228. console.log("Audio WebSocket connected");
  229. if (!audioContext) {
  230. audioContext = new (window.AudioContext || window.webkitAudioContext)({sampleRate: 24000});
  231. }
  232. };
  233. const MAX_AUDIO_QUEUE = 8;
  234. let PCM_SAMPLE_RATE;
  235. if (quality == "high"){
  236. PCM_SAMPLE_RATE = 48000; // Use 48kHz for high quality
  237. } else if (quality == "low") {
  238. PCM_SAMPLE_RATE = 16000; // Use 24kHz for low quality
  239. } else {
  240. PCM_SAMPLE_RATE = 24000; // Default to 24kHz for standard quality
  241. }
  242. let scheduledTime = 0;
  243. audioSocket.onmessage = function(event) {
  244. if (!audioContext) return;
  245. let pcm = new Int16Array(event.data);
  246. if (pcm.length === 0) {
  247. console.warn("Received empty PCM data");
  248. return;
  249. }
  250. if (pcm.length % 2 !== 0) {
  251. console.warn("Received PCM data with odd length, dropping last sample");
  252. pcm = pcm.slice(0, -1);
  253. }
  254. // Convert Int16 PCM to Float32 [-1, 1]
  255. let floatBuf = new Float32Array(pcm.length);
  256. for (let i = 0; i < pcm.length; i++) {
  257. floatBuf[i] = pcm[i] / 32768;
  258. }
  259. // Limit queue size to prevent memory overflow
  260. if (audioQueue.length >= MAX_AUDIO_QUEUE) {
  261. audioQueue.shift();
  262. }
  263. audioQueue.push(floatBuf);
  264. scheduleAudioPlayback();
  265. };
  266. audioSocket.onclose = function() {
  267. console.log("Audio WebSocket closed");
  268. audioSocket = null;
  269. audioPlaying = false;
  270. audioQueue = [];
  271. scheduledTime = 0;
  272. };
  273. audioSocket.onerror = function(e) {
  274. console.error("Audio WebSocket error", e);
  275. };
  276. function scheduleAudioPlayback() {
  277. if (!audioContext || audioQueue.length === 0) return;
  278. // Use audioContext.currentTime to schedule buffers back-to-back
  279. if (scheduledTime < audioContext.currentTime) {
  280. scheduledTime = audioContext.currentTime;
  281. }
  282. while (audioQueue.length > 0) {
  283. let floatBuf = audioQueue.shift();
  284. let frameCount = floatBuf.length / 2;
  285. let buffer = audioContext.createBuffer(2, frameCount, PCM_SAMPLE_RATE);
  286. for (let ch = 0; ch < 2; ch++) {
  287. let channelData = buffer.getChannelData(ch);
  288. for (let i = 0; i < frameCount; i++) {
  289. channelData[i] = floatBuf[i * 2 + ch];
  290. }
  291. }
  292. let source = audioContext.createBufferSource();
  293. source.buffer = buffer;
  294. source.connect(audioContext.destination);
  295. source.start(scheduledTime);
  296. scheduledTime += buffer.duration;
  297. }
  298. }
  299. }
  300. function stopAudioWebSocket() {
  301. if (!audioSocket) {
  302. console.warn("No audio WebSocket to stop");
  303. return;
  304. }
  305. if (audioSocket.readyState === WebSocket.OPEN) {
  306. audioSocket.send("exit");
  307. }
  308. audioSocket.onclose = null; // Prevent onclose from being called again
  309. audioSocket.onerror = null; // Prevent onerror from being called again
  310. audioSocket.close();
  311. audioSocket = null;
  312. audioPlaying = false;
  313. audioQueue = [];
  314. if (audioContext) {
  315. audioContext.close();
  316. audioContext = null;
  317. }
  318. }
  319. startWebSocket();
  320. window.addEventListener('beforeunload', function() {
  321. stopAudioWebSocket();
  322. });
  323. </script>
  324. </body>
  325. </html>