Skip to content

Commit

Permalink
Collect workspace data from guest users
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
simosathan9 committed Sep 7, 2024
1 parent d34f9bc commit c6de878
Show file tree
Hide file tree
Showing 4 changed files with 126 additions and 4 deletions.
78 changes: 75 additions & 3 deletions public/main.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -341,7 +344,6 @@ function loadWorkspace() {
}

function onWorkspaceChange(event) {
console.log('Saving Workspace...');
fetch('/auth-token')
.then((response) => response.json())
.then((data) => {
Expand All @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 () {
Expand Down
8 changes: 8 additions & 0 deletions public/styledark.css
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
25 changes: 25 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
19 changes: 18 additions & 1 deletion table_creation_queries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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
);
);

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';

0 comments on commit c6de878

Please sign in to comment.