From c6de8780555faf80604097b9358a87575440e530 Mon Sep 17 00:00:00 2001 From: simosathan9 Date: Sat, 7 Sep 2024 20:00:02 +0300 Subject: [PATCH] Collect workspace data from guest users Add logic to track workspace data for guest (non-authenticated) users when they navigate to different tabs. This change introduces two new variables to track: 1. Whether the user executed the created block. 2. Whether the user modified the created block post-execution. These data points are collected alongside the workspace status for each tab navigation event. --- public/main.js | 78 ++++++++++++++++++++++++++++++++++++-- public/styledark.css | 8 ++++ server.js | 25 ++++++++++++ table_creation_queries.sql | 19 +++++++++- 4 files changed, 126 insertions(+), 4 deletions(-) diff --git a/public/main.js b/public/main.js index a45f6d9..b07d7d8 100644 --- a/public/main.js +++ b/public/main.js @@ -1,6 +1,9 @@ Blockly.JavaScript.init(workspace); Blockly.JavaScript = new Blockly.Generator('JavaScript'); var generator = javascript.javascriptGenerator; +let workspaceChangedAfterExecution = false; // Flag to track if the workspace has changed after execution +let hasExecuted = false; +let executedWorkspace = ''; window.onload = function () { initBlockly(); // Initialize your Blockly workspace @@ -341,7 +344,6 @@ function loadWorkspace() { } function onWorkspaceChange(event) { - console.log('Saving Workspace...'); fetch('/auth-token') .then((response) => response.json()) .then((data) => { @@ -352,15 +354,67 @@ function onWorkspaceChange(event) { saveWorkspace(); } }); + if (hasExecuted) { + // Compare the current workspace state with the executed workspace state + const currentWorkspaceState = + Blockly.serialization.workspaces.save(workspace); + const jsonCurrentState = JSON.stringify(currentWorkspaceState); + + if (jsonCurrentState !== executedWorkspace) { + workspaceChangedAfterExecution = true; + console.log('Workspace has changed since execution.'); + } else { + workspaceChangedAfterExecution = false; + console.log('Workspace has not changed since execution.'); + } + } } Blockly.getMainWorkspace().addChangeListener(onWorkspaceChange); function saveWorkspace() { + //used for saving the workspace in the local storage of the browser in case the user is not logged in const state = Blockly.serialization.workspaces.save(workspace); const jsonState = JSON.stringify(state); localStorage.setItem('blocklyWorkspace', jsonState); } -//window.addEventListener('beforeunload', saveWorkspace); + +// Used to collect workspace data from guest users when they close the tab. +function saveGuestWorkspaceData() { + const state = Blockly.serialization.workspaces.save(workspace); + const jsonState = JSON.stringify(state); + fetch('/auth-token') + .then((response) => response.json()) + .then((data) => { + const token = data.authToken; + if (!token && hasExecuted && jsonState !== executedWorkspace) { + workspaceChangedAfterExecution = true; + } + if (!token) { + fetch('/saveGuestWorkspace', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + workspaceData: jsonState, + executionStatus: hasExecuted, + changesAfterExecution: workspaceChangedAfterExecution + }) + }) + .then((response) => response.json()) + .then((result) => { + if (result.error) { + console.error('Error saving guest workspace:', result.error); + alert('Failed to save guest workspace. Please try again.'); + } + }) + .catch((error) => { + alert('Failed to save guest workspace. Please try again.'); + }); + } + }); +} +window.addEventListener('beforeunload', saveGuestWorkspaceData); //window.addEventListener('beforeunload', autoSaveWorkspace); // Global replacement map @@ -436,12 +490,13 @@ var filenameBlocks = ['filename', 'filenamesCreate', 'fileEndStart']; document .getElementById('executeButton') .addEventListener('click', function onExecuteButtonClick() { - console.log('Top blocks:', workspace.getTopBlocks()); // Start from the first block let currentBlock = workspace.getTopBlocks()[0]; let generatedCommand = ''; + let blockCount = 0; // Mark the workspace as executed if users clicks the execute button and there are blocks in the workspace while (currentBlock) { + blockCount++; var blockDef = window[currentBlock.type + 'Block']; // Generate the command for the current block try { @@ -477,6 +532,23 @@ document document.getElementById('resultsText').innerText = generatedCommand; console.log('Generated command:', generatedCommand); + if (blockCount > 0) { + fetch('/auth-token') + .then((response) => response.json()) + .then((data) => { + const token = data.authToken; + if (!token) { + hasExecuted = true; + console.log('It got executed'); + const state = Blockly.serialization.workspaces.save(workspace); + executedWorkspace = JSON.stringify(state); + } + console.log('Has executed ', hasExecuted); // Now inside the .then block + }); + } else { + console.log('Has executed ', hasExecuted); // Still log if no fetch occurs + } + console.log('Top blocks:', workspace.getTopBlocks()); }); document.getElementById('resetButton').addEventListener('click', function () { diff --git a/public/styledark.css b/public/styledark.css index 8514688..165164a 100644 --- a/public/styledark.css +++ b/public/styledark.css @@ -125,6 +125,14 @@ body { background-color: rgb(220, 120, 0); /* Darker orange on hover */ } +#saveButton { + background-color: rgb(123, 166, 230); +} + +#saveButton:hover { + background-color: rgb(44, 123, 197); +} + /* Navbar */ #navbar { diff --git a/server.js b/server.js index ce272d3..6434f89 100644 --- a/server.js +++ b/server.js @@ -281,6 +281,31 @@ app.post('/saveWorkspace', (req, res) => { }); }); +app.post('/saveGuestWorkspace', (req, res) => { + // Retrieve the workspace data and user ID from the request body + const { workspaceData, executionStatus, changesAfterExecution } = req.body; + if (!workspaceData) { + return res.status(400).json({ error: 'Missing workspace data.' }); + } + const query = `INSERT INTO guestsWorkspaces (workspaceData, executionStatus, changesAfterExecution) VALUES (?, ?, ?)`; + db.run( + query, + [workspaceData, executionStatus, changesAfterExecution], + function (err) { + if (err) { + console.error('Error inserting workspace data:', err.message); + return res + .status(500) + .json({ error: 'Failed to save workspace data.' }); + } + res.status(200).json({ + message: 'Workspace data saved successfully.', + workspaceId: this.lastID // Return the ID of the inserted workspace + }); + } + ); +}); + app.post('/autoSaveWorkspace', (req, res) => { const { workspaceData, userId } = req.body; diff --git a/table_creation_queries.sql b/table_creation_queries.sql index 14530a1..9b4a84d 100644 --- a/table_creation_queries.sql +++ b/table_creation_queries.sql @@ -14,4 +14,21 @@ CREATE TABLE IF NOT EXISTS workspaces ( workspaceName TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE -); \ No newline at end of file +); + +CREATE TABLE IF NOT EXISTS guestsWorkspaces ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + workspaceData TEXT NOT NULL, + executionStatus BOOLEAN DEFAULT 0, -- Field to track if execution was performed (0 for no, 1 for yes) + changesAfterExecution BOOLEAN DEFAULT 0, -- Field to track if changes were made after execution (0 for no, 1 for yes) + created_at DATETIME DEFAULT CURRENT_TIMESTAMP +); + +--DELETE FROM users; +--DELETE FROM workspaces; +-- delete table guestsWorkspaces not only its data +--DROP TABLE IF EXISTS guestsWorkspaces; +--DELETE FROM guestsWorkspaces; + +-- delete the data of guestsWorkspaces table +--DELETE FROM sqlite_sequence WHERE name='guestsWorkspaces'; \ No newline at end of file