Add error handling to desktop server

Change desktop paths
refactor desktop file structure
move WebApp functionalities to express server
Remove unused interfaces
This commit is contained in:
Loui Molina committed 2021-11-30 19:30:58 -03:00
1 parent c600f77b84
commit e771458a32
26 files changed
+309 -2861

No files matched your search

+10 -26
View File
@@ -1,3 +1,4 @@
const express = require("./backend/src/index");
exports.newDesktopApp = function newDesktopApp() {
let thisObject = {
@@ -63,35 +64,18 @@ exports.newDesktopApp = function newDesktopApp() {
*/
thisObject.socialGraph = DK.projects.socialTrading.modules.socialGraph.newSocialTradingModulesSocialGraph() //
await thisObject.socialGraph.initialize()
/* /!*
These are the Network Interfaces by which the Web App interacts with this Desktop Client.
*!/
thisObject.webSocketsInterface = DK.projects.socialTrading.modules.webSocketsInterface.newDesktopModulesWebSocketsInterface()
thisObject.webSocketsInterface.initialize()
console.log('Desktop Client Web Sockets Interface ......................................... Listening at port ' + JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webSocketsPort)
*/
/* TODO refactor this into something better */
/*
require('./src/UI/WebAppPreLoader').loadSuperalgos();
*/
let express = require('./backend/src/index')
let expressPort = JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webPort;
express.startExpress(expressPort,SA);
console.log('express Interface ................................................ Listening at port ' + expressPort);
/*
thisObject.httpInterface = DK.projects.socialTrading.modules.httpInterface.newDesktopModulesHttpInterface()
thisObject.httpInterface.initialize()
let react = require('./frontend/scripts/start');
react.start(JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webPort+1);
*/
let express = require("./UI/WebAppPreLoader")
express.loadSuperalgos(+JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webPort + +2);
console.log('Desktop Client Http Interface ................................................ Listening at port ' + JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webPort)
/*TODO change this to have a definite port number*/
let react = require('./frontend/scripts/start')
let reactPort = (+JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webPort + 1);
react.start(reactPort);
console.log('react Interface ................................................ Listening at port ' + reactPort);
}
}
}
-16
View File
@@ -1,16 +0,0 @@
/* Root object*/
/* Root objects*/
exports.UI = {
projects: {},
schemas: { projectSchema: undefined },
environment: undefined,
clientNode: undefined,
webApp: undefined
}
exports.SA = { projects: {} }
/*
We will use this to load functions originally intended for Nodejs
*/
+174 -224
View File
@@ -5,7 +5,7 @@ function newWebApp() {
Everything is being coded here until some structure emerges.
*/
let thisObject = {
messageReceived: messageReceived,
messageReceived: messageReceived,
initialize: initialize,
finalize: finalize
}
@@ -29,239 +29,180 @@ function newWebApp() {
}
}
function setupRootObject(rootObject, rootObjectName) {
/*
Here we will setup the UI object, with all the
projects and spaces.
*/
for (let i = 0; i < UI.schemas.projectSchema.length; i++) {
let projectDefinition = UI.schemas.projectSchema[i]
rootObject.projects[projectDefinition.propertyName] = {}
let projectInstance = rootObject.projects[projectDefinition.propertyName]
/*
function setupRootObject(rootObject, rootObjectName) {
/!*
Here we will setup the UI object, with all the
projects and spaces.
*!/
for (let i = 0; i < UI.schemas.projectSchema.length; i++) {
let projectDefinition = UI.schemas.projectSchema[i]
rootObject.projects[projectDefinition.propertyName] = {}
let projectInstance = rootObject.projects[projectDefinition.propertyName]
projectInstance.utilities = {}
projectInstance.globals = {}
projectInstance.functionLibraries = {}
projectInstance.modules = {}
projectInstance.utilities = {}
projectInstance.globals = {}
projectInstance.functionLibraries = {}
projectInstance.modules = {}
if (projectDefinition[rootObjectName] === undefined) { continue }
/* Set up Globals of this Project */
if (projectDefinition[rootObjectName].globals !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].globals.length; j++) {
let globalDefinition = projectDefinition[rootObjectName].globals[j]
if (exports[globalDefinition.functionName] === undefined) {
projectInstance.globals[globalDefinition.propertyName] = eval(globalDefinition.functionName + '()')
} else {
projectInstance.globals[globalDefinition.propertyName] = eval('exports.' + globalDefinition.functionName + '()')
}
if (projectDefinition[rootObjectName] === undefined) {
continue
}
}
/* Set up Utilities of this Project */
if (projectDefinition[rootObjectName].utilities !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].utilities.length; j++) {
let utilityDefinition = projectDefinition[rootObjectName].utilities[j]
/!* Set up Globals of this Project *!/
if (projectDefinition[rootObjectName].globals !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].globals.length; j++) {
let globalDefinition = projectDefinition[rootObjectName].globals[j]
if (exports[utilityDefinition.functionName] === undefined) {
projectInstance.utilities[utilityDefinition.propertyName] = eval(utilityDefinition.functionName + '()')
} else {
projectInstance.utilities[utilityDefinition.propertyName] = eval('exports.' + utilityDefinition.functionName + '()')
}
}
}
/* Set up Function Libraries of this Project */
if (projectDefinition[rootObjectName].functionLibraries !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].functionLibraries.length; j++) {
let functionLibraryDefinition = projectDefinition[rootObjectName].functionLibraries[j]
if (exports[functionLibraryDefinition.functionName] === undefined) {
projectInstance.functionLibraries[functionLibraryDefinition.propertyName] = eval(functionLibraryDefinition.functionName + '()')
} else {
projectInstance.functionLibraries[functionLibraryDefinition.propertyName] = eval('exports.' + functionLibraryDefinition.functionName + '()')
}
}
}
/* Set up Modules of this Project */
if (projectDefinition[rootObjectName].modules !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].modules.length; j++) {
let functionLibraryDefinition = projectDefinition[rootObjectName].modules[j]
if (exports[functionLibraryDefinition.functionName] === undefined) {
projectInstance.modules[functionLibraryDefinition.propertyName] = eval(functionLibraryDefinition.functionName + '()')
} else {
projectInstance.modules[functionLibraryDefinition.propertyName] = eval('exports.' + functionLibraryDefinition.functionName + '()')
}
}
}
}
}
async function loadWUserProfileTimeline() {
let queryMessage = {
queryType: SA.projects.socialTrading.globals.queryTypes.EVENTS,
emitterUserProfileId: undefined,
initialIndex: SA.projects.socialTrading.globals.queryConstants.INITIAL_INDEX_LAST,
amountRequested: 100,
direction: SA.projects.socialTrading.globals.queryConstants.DIRECTION_PAST
}
let query = {
requestType: 'Query',
queryMessage: JSON.stringify(queryMessage)
}
await UI.projects.socialTrading.modules.webSocketsWebAppClient.sendMessage(
JSON.stringify(query)
)
.then(console.log)
.catch(onError)
function onError(errorMessage) {
console.log('[ERROR] Query not executed. ' + errorMessage)
console.log('[ERROR] query = ' + JSON.stringify(query))
}
function addToContentDiv(events) {
try {
let contentDiv = document.getElementById('content-div')
/*
Delete al current content.
*/
while (contentDiv.childNodes.length > 4) {
let childToRemove = contentDiv.childNodes[contentDiv.childNodes.length - 1]
contentDiv.removeChild(childToRemove)
}
/*
Render the timeline.
*/
for (let i = 0; i < events.length; i++) {
let event = events[i]
let postDiv = document.createElement("div")
postDiv.setAttribute("class", "post-div")
let textNode
switch (event.eventType) {
case SA.projects.socialTrading.globals.eventTypes.NEW_USER_POST: {
textNode = document.createTextNode(event.emitterUserProfile.userProfileHandle + " POSTED " + event.postText)
break
}
case SA.projects.socialTrading.globals.eventTypes.FOLLOW_USER_PROFILE: {
textNode = document.createTextNode(event.emitterUserProfile.userProfileHandle + " FOLLOWED " + event.targetUserProfile.userProfileHandle)
break
}
case SA.projects.socialTrading.globals.eventTypes.UNFOLLOW_USER_PROFILE: {
textNode = document.createTextNode(event.emitterUserProfile.userProfileHandle + " UNFOLLOWED " + event.targetUserProfile.userProfileHandle)
break
if (exports[globalDefinition.functionName] === undefined) {
projectInstance.globals[globalDefinition.propertyName] = eval(globalDefinition.functionName + '()')
} else {
projectInstance.globals[globalDefinition.propertyName] = eval('exports.' + globalDefinition.functionName + '()')
}
}
postDiv.appendChild(textNode)
contentDiv.appendChild(postDiv)
}
}
catch (err) {
console.log('[ERROR] err.stack = ' + err.stack)
}
}
}
async function loadWhoToFollow() {
let queryMessage = {
queryType: SA.projects.socialTrading.globals.queryTypes.UNFOLLOWED_USER_PROFILES,
emitterUserProfileId: undefined,
initialIndex: SA.projects.socialTrading.globals.queryConstants.INITIAL_INDEX_FIRST,
amountRequested: 3,
direction: SA.projects.socialTrading.globals.queryConstants.DIRECTION_UP
}
let query = {
requestType: 'Query',
queryMessage: JSON.stringify(queryMessage)
}
await UI.projects.socialTrading.modules.webSocketsWebAppClient.sendMessage(
JSON.stringify(query)
)
.then(addWhoToFollowTable)
.catch(onError)
function onError(errorMessage) {
console.log('[ERROR] Query not executed. ' + errorMessage)
console.log('[ERROR] query = ' + JSON.stringify(query))
}
function addWhoToFollowTable(profiles) {
let contextCell = document.getElementById('who-to-follow-cell')
let table = document.createElement("table")
let tblBody = document.createElement("tbody")
for (let i = 0; i < profiles.length; i++) {
let profile = profiles[i]
let row = document.createElement("tr")
let cell = document.createElement("td")
addProfileToFollowTable(cell, profile)
row.appendChild(cell)
tblBody.appendChild(row)
}
table.appendChild(tblBody)
contextCell.appendChild(table)
table.setAttribute("class", "who-to-follow-table")
function addProfileToFollowTable(htmlElement, profile) {
let table = document.createElement("table")
let tblBody = document.createElement("tbody")
let row = document.createElement("tr")
{
let cell = document.createElement("td")
let textNode = document.createTextNode('Profile Picture')
cell.appendChild(textNode)
row.appendChild(cell)
}
{
let cell = document.createElement("td")
let textNode = document.createTextNode(profile.userProfileHandle)
cell.appendChild(textNode)
row.appendChild(cell)
}
{
let cell = document.createElement("td")
let span = document.createElement("span")
let button = document.createElement("button")
let text = document.createTextNode('Follow')
span.setAttribute("id", "profile-to-follow-span-" + profile.userProfileId)
button.setAttribute("id", "profile-to-follow-button-" + profile.userProfileId)
button.name = 'Follow Profile'
button.userProfileId = profile.userProfileId
span.setAttribute("class", "profile-to-follow-span")
button.setAttribute("class", "profile-to-follow-button")
button.appendChild(text)
span.appendChild(button)
cell.appendChild(span)
row.appendChild(cell)
}
tblBody.appendChild(row)
/!* Set up Utilities of this Project *!/
if (projectDefinition[rootObjectName].utilities !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].utilities.length; j++) {
let utilityDefinition = projectDefinition[rootObjectName].utilities[j]
table.appendChild(tblBody)
htmlElement.appendChild(table)
table.setAttribute("class", "profile-to-follow-table")
if (exports[utilityDefinition.functionName] === undefined) {
projectInstance.utilities[utilityDefinition.propertyName] = eval(utilityDefinition.functionName + '()')
} else {
projectInstance.utilities[utilityDefinition.propertyName] = eval('exports.' + utilityDefinition.functionName + '()')
}
}
}
/!* Set up Function Libraries of this Project *!/
if (projectDefinition[rootObjectName].functionLibraries !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].functionLibraries.length; j++) {
let functionLibraryDefinition = projectDefinition[rootObjectName].functionLibraries[j]
if (exports[functionLibraryDefinition.functionName] === undefined) {
projectInstance.functionLibraries[functionLibraryDefinition.propertyName] = eval(functionLibraryDefinition.functionName + '()')
} else {
projectInstance.functionLibraries[functionLibraryDefinition.propertyName] = eval('exports.' + functionLibraryDefinition.functionName + '()')
}
}
}
/!* Set up Modules of this Project *!/
if (projectDefinition[rootObjectName].modules !== undefined) {
for (let j = 0; j < projectDefinition[rootObjectName].modules.length; j++) {
let functionLibraryDefinition = projectDefinition[rootObjectName].modules[j]
if (exports[functionLibraryDefinition.functionName] === undefined) {
projectInstance.modules[functionLibraryDefinition.propertyName] = eval(functionLibraryDefinition.functionName + '()')
} else {
projectInstance.modules[functionLibraryDefinition.propertyName] = eval('exports.' + functionLibraryDefinition.functionName + '()')
}
}
}
}
}
}
*/
/*
async function loadWUserProfileTimeline() {
let queryMessage = {
queryType: SA.projects.socialTrading.globals.queryTypes.EVENTS,
emitterUserProfileId: undefined,
initialIndex: SA.projects.socialTrading.globals.queryConstants.INITIAL_INDEX_LAST,
amountRequested: 100,
direction: SA.projects.socialTrading.globals.queryConstants.DIRECTION_PAST
}
let query = {
requestType: 'Query',
queryMessage: JSON.stringify(queryMessage)
}
await UI.projects.socialTrading.modules.webSocketsWebAppClient.sendMessage(
JSON.stringify(query)
)
.then(console.log)
.catch(onError)
function onError(errorMessage) {
console.log('[ERROR] Query not executed. ' + errorMessage)
console.log('[ERROR] query = ' + JSON.stringify(query))
}
function addToContentDiv(events) {
try {
let contentDiv = document.getElementById('content-div')
/!*
Delete al current content.
*!/
while (contentDiv.childNodes.length > 4) {
let childToRemove = contentDiv.childNodes[contentDiv.childNodes.length - 1]
contentDiv.removeChild(childToRemove)
}
/!*
Render the timeline.
*!/
for (let i = 0; i < events.length; i++) {
let event = events[i]
let postDiv = document.createElement("div")
postDiv.setAttribute("class", "post-div")
let textNode
switch (event.eventType) {
case SA.projects.socialTrading.globals.eventTypes.NEW_USER_POST: {
textNode = document.createTextNode(event.emitterUserProfile.userProfileHandle + " POSTED " + event.postText)
break
}
case SA.projects.socialTrading.globals.eventTypes.FOLLOW_USER_PROFILE: {
textNode = document.createTextNode(event.emitterUserProfile.userProfileHandle + " FOLLOWED " + event.targetUserProfile.userProfileHandle)
break
}
case SA.projects.socialTrading.globals.eventTypes.UNFOLLOW_USER_PROFILE: {
textNode = document.createTextNode(event.emitterUserProfile.userProfileHandle + " UNFOLLOWED " + event.targetUserProfile.userProfileHandle)
break
}
}
postDiv.appendChild(textNode)
contentDiv.appendChild(postDiv)
}
}
catch (err) {
console.log('[ERROR] err.stack = ' + err.stack)
}
}
}
*/
/*
async function loadWhoToFollow() {
let queryMessage = {
queryType: SA.projects.socialTrading.globals.queryTypes.UNFOLLOWED_USER_PROFILES,
emitterUserProfileId: undefined,
initialIndex: SA.projects.socialTrading.globals.queryConstants.INITIAL_INDEX_FIRST,
amountRequested: 3,
direction: SA.projects.socialTrading.globals.queryConstants.DIRECTION_UP
}
let query = {
requestType: 'Query',
queryMessage: JSON.stringify(queryMessage)
}
await UI.projects.socialTrading.modules.webSocketsWebAppClient.sendMessage(
JSON.stringify(query)
)
.then(addWhoToFollowTable)
.catch(onError)
function onError(errorMessage) {
console.log('[ERROR] Query not executed. ' + errorMessage)
console.log('[ERROR] query = ' + JSON.stringify(query))
}
}
*/
function setupEventHandlers() {
/*
@@ -285,6 +226,7 @@ function newWebApp() {
function updateTextArea() {
textArea.value = ""
}
break
}
case 'Follow Profile': {
@@ -302,6 +244,7 @@ function newWebApp() {
button.setAttribute("class", "profile-to-unfollow-button")
button.name = 'Unfollow Profile'
}
break
}
case 'Unfollow Profile': {
@@ -312,6 +255,7 @@ function newWebApp() {
.then(updateButton)
.catch(onError)
/*
function updateButton() {
let span = document.getElementById('profile-to-follow-span-' + event.target.userProfileId)
let button = document.getElementById('profile-to-follow-button-' + event.target.userProfileId)
@@ -319,6 +263,8 @@ function newWebApp() {
button.setAttribute("class", "profile-to-follow-button")
button.name = 'Follow Profile'
}
*/
break
}
}
@@ -343,7 +289,9 @@ function newWebApp() {
eventType
) {
return new Promise((resolve, reject) => { asyncCall(resolve, reject) })
return new Promise((resolve, reject) => {
asyncCall(resolve, reject)
})
async function asyncCall(resolve, reject) {
let eventMessage
@@ -379,7 +327,9 @@ function newWebApp() {
postText
) {
return new Promise((resolve, reject) => { asyncCall(resolve, reject) })
return new Promise((resolve, reject) => {
asyncCall(resolve, reject)
})
async function asyncCall(resolve, reject) {
let eventMessage
-118
View File
@@ -1,118 +0,0 @@
exports.newWebAppLoader = ({port, SA, UI}) => {
let thisObject = {
loadModules: loadModules
}
return thisObject
async function loadModules() {
try {
let modulesArray = [
'WebDebugLog.js',
'WebApp.js'
]
for (let i = 0; i < UI.schemas.projectSchema.length; i++) {
let project = UI.schemas.projectSchema[i]
if (project.UI !== undefined) {
if (project.UI.functionLibraries !== undefined) {
for (let j = 0; j < project.UI.functionLibraries.length; j++) {
let fileName = project.UI.functionLibraries[j].fileName
if (fileName === undefined) {fileName = project.UI.functionLibraries[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'UI' + '/' + 'Function-Libraries' + '/' + fileName)
}
}
if (project.UI.utilities !== undefined) {
for (let j = 0; j < project.UI.utilities.length; j++) {
let fileName = project.UI.utilities[j].fileName
if (fileName === undefined) {fileName = project.UI.utilities[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'UI' + '/' + 'Utilities' + '/' + fileName)
}
}
if (project.UI.globals !== undefined) {
for (let j = 0; j < project.UI.globals.length; j++) {
let fileName = project.UI.globals[j].fileName
if (fileName === undefined) {fileName = project.UI.globals[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'UI' + '/' + 'Globals' + '/' + fileName)
}
}
if (project.UI.modules !== undefined) {
for (let j = 0; j < project.UI.modules.length; j++) {
let fileName = project.UI.modules[j].fileName
if (fileName === undefined) {fileName = project.UI.modules[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'UI' + '/' + 'Modules' + '/' + fileName)
}
}
}
if (project.SA !== undefined) {
if (project.SA.functionLibraries !== undefined) {
for (let j = 0; j < project.SA.functionLibraries.length; j++) {
let fileName = project.SA.functionLibraries[j].fileName
if (fileName === undefined) {fileName = project.SA.functionLibraries[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'SA' + '/' + 'Function-Libraries' + '/' + fileName)
}
}
if (project.SA.utilities !== undefined) {
for (let j = 0; j < project.SA.utilities.length; j++) {
let fileName = project.SA.utilities[j].fileName
if (fileName === undefined) {fileName = project.SA.utilities[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'SA' + '/' + 'Utilities' + '/' + fileName)
}
}
if (project.SA.globals !== undefined) {
for (let j = 0; j < project.SA.globals.length; j++) {
let fileName = project.SA.globals[j].fileName
if (fileName === undefined) {fileName = project.SA.globals[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'SA' + '/' + 'Globals' + '/' + fileName)
}
}
if (project.SA.modules !== undefined) {
for (let j = 0; j < project.SA.modules.length; j++) {
let fileName = project.SA.modules[j].fileName
if (fileName === undefined) {fileName = project.SA.modules[j].name.replaceAll(' ', '') + '.js'}
modulesArray.push('Projects' + '/' + project.name + '/' + 'SA' + '/' + 'Modules' + '/' + fileName)
}
}
}
}
downloadIncludedFiles()
function downloadIncludedFiles() {
let downloadedCounter = 0
for (let i = 0; i < modulesArray.length; i++) {
let path = modulesArray[i]
UI.projects = require(path);
function onRequired(pModule) {
try {
downloadedCounter++
if (downloadedCounter === modulesArray.length) {
setTimeout(() => {
UI.webApp = require("../backend/src/index");
UI.webApp.startExpress();
}, 500)
}
} catch (err) {
console.log('[ERROR] loadModules -> onRequired -> err = ' + err.stack)
}
}
}
}
} catch (err) {
console.log('[ERROR] loadModules -> err = ' + err.stack)
}
}
}
-30
View File
@@ -1,30 +0,0 @@
exports.loadSuperalgos = (port) => {
loadGlobals()
function loadGlobals() {
let {UI} = require('./Globals');
setupEnvironment(UI);
}
function setupEnvironment(UI) {
let ENVIRONMENT = require('../../Environment');
UI.environment = ENVIRONMENT.newEnvironment();
setupClientNode(UI);
}
function setupClientNode(UI) {
UI.clientNode = DK.desktopApp.p2pNetworkClient.node;
setupProjectsSchema(UI);
}
function setupProjectsSchema(UI) {
UI.schemas.projectSchema = require('../../Projects/ProjectsSchema.json');
loadModules(UI)
}
function loadModules(UI) {
let APP_LOADER_MODULE = require('./WebAppLoader');
APP_LOADER_MODULE.newWebAppLoader({port, SA, UI}).loadModules();
}
}
-21
View File
@@ -1,21 +0,0 @@
function newWebDebugLog() {
try {
let thisObject = {
write: write,
fileName: 'undefined'
}
return thisObject
function write(pText) {
console.log(spacePad(thisObject.fileName, 50) + ' : ' + pText)
function spacePad(str, max) {
str = str.toString()
return str.length < max ? spacePad(' ' + str, max) : str
}
}
} catch (err) {
console.log(spacePad(MODULE_NAME, 50) + ' : ' + '[ERROR] WebDebugLog --> err = ' + err.stack)
}
}
File diff suppressed because it is too large. Load diff
-10
View File
@@ -1,10 +0,0 @@
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body >
</body>
</html>
+99 -24
View File
@@ -1,42 +1,117 @@
exports.startExpress = (port, SA, UI) => {
exports.startExpress = (port, SA) => {
const express = require("express");
const app = express();
const newSocialTradingModulesWebAppInterface = DK.projects.socialTrading.modules.webAppInterface.newSocialTradingModulesWebAppInterface();
const webAppInterface = DK.projects.socialTrading.modules.webAppInterface.newSocialTradingModulesWebAppInterface();
// define a route handler for the default home page
app.use(express.json());
// define a route handler for the default home page
app.get("/health-check", (req, res) => {
res.send("all good");
});
app.get("/profiles", async (req, res) => {
let userProfileTimeLine = loadUserProfileTimeline(SA, UI);
res.send(userProfileTimeLine);
})
// start the Express server
app.listen(port, () => {
console.log(`server started at http://localhost:${port} `);
let profiles = await whoToFollow();
console.log(profiles)
res.send(profiles);
});
app.post("/follow", async (req, res) => {
let follow = followProfile(req.body.userProfileId, req.body.eventType);
async function loadUserProfileTimeline(SA, UI) {
let queryMessage = {
queryType: SA.projects.socialTrading.globals.queryTypes.UNFOLLOWED_USER_PROFILES,
emitterUserProfileId: undefined,
initialIndex: SA.projects.socialTrading.globals.queryConstants.INITIAL_INDEX_FIRST,
amountRequested: 3,
direction: SA.projects.socialTrading.globals.queryConstants.DIRECTION_UP
});
app.post("/unFollow", async (req, res) => {
let unFollow = asda;
});
app.post("/post", async (req, res) => {
console.log(req)
let post = createPost(req);
res.send(post)
});
// start the Express server
app.listen(port, () => {
console.log(`server started at http://localhost:${port}`);
});
async function createPost(postText) {
try {
let eventMessage;
let event;
eventMessage = {
eventType: SA.projects.socialTrading.globals.eventTypes.NEW_USER_POST,
eventId: SA.projects.foundations.utilities.miscellaneousFunctions.genereteUniqueId(),
postText: postText,
timestamp: (new Date()).valueOf()
}
event = {
requestType: 'Event',
eventMessage: JSON.stringify(eventMessage)
}
return await webAppInterface.sendMessage(
JSON.stringify(event)
);
} catch (e) {
console.log(e);
return undefined;
}
}
let query = {
requestType: 'Query',
queryMessage: JSON.stringify(queryMessage)
async function whoToFollow() {
try {
let queryMessage = {
queryType: SA.projects.socialTrading.globals.queryTypes.UNFOLLOWED_USER_PROFILES,
emitterUserProfileId: undefined,
initialIndex: SA.projects.socialTrading.globals.queryConstants.INITIAL_INDEX_FIRST,
amountRequested: 3,
direction: SA.projects.socialTrading.globals.queryConstants.DIRECTION_UP
}
let query = {
requestType: 'Query',
queryMessage: JSON.stringify(queryMessage)
}
return await webAppInterface.messageReceived(
JSON.stringify(query)
);
} catch (e) {
console.log(e);
return undefined;
}
}
let profiles = await newSocialTradingModulesWebAppInterface.messageReceived(
JSON.stringify(query)
);
return profiles;
async function followProfile(userProfileId, eventType) {
try {
let queryMessage = {
queryType: SA.projects.socialTrading.globals.queryTypes.UNFOLLOWED_USER_PROFILES,
emitterUserProfileId: undefined,
initialIndex: SA.projects.socialTrading.globals.queryConstants.INITIAL_INDEX_FIRST,
amountRequested: 3,
direction: SA.projects.socialTrading.globals.queryConstants.DIRECTION_UP
}
let query = {
requestType: 'Query',
queryMessage: JSON.stringify(queryMessage)
}
return await webAppInterface.messageReceived(
JSON.stringify(query)
);
} catch (e) {
console.log(e);
return undefined;
}
}
}
+4 -8
View File
@@ -56,17 +56,13 @@ module.exports = {
dotenv: resolveApp('.env'),
appPath: resolveApp('.'),
appBuild: resolveApp(buildPath),
appPublic: resolveApp('Desktop/public'),
appHtml: resolveApp('Desktop/public/index.html'),
appIndexJs: resolveModule(resolveApp, 'Desktop/src/index'),
appPublic: resolveApp('Desktop/frontend/public'),
appHtml: resolveApp('Desktop/frontend/public/index.html'),
appIndexJs: resolveModule(resolveApp, 'Desktop/frontend/src/index'),
appPackageJson: resolveApp('package.json'),
appSrc: resolveApp('Desktop/src'),
appSrc: resolveApp('Desktop/frontend/src'),
appNodeModules: resolveApp('node_modules'),
publicUrlOrPath,
};
/* globals: resolveApp('Desktop/UI/Globals'),
projects: resolveApp('Projects'),
environment: resolveApp('Environments'),
schema: resolveApp('Projects/ProjectsSchema'),*/
module.exports.moduleFileExtensions = moduleFileExtensions;
File renamed without changes.
+1 -1
View File
@@ -3,7 +3,7 @@ import Sidebar from "../sidebar/Sidebar";
import UsersSidebar from "../UsersSidebar/UsersSidebar";
import {Stack} from "@mui/material";
import {Outlet} from "react-router-dom";
import {getProfiles} from '../../../api/service'
import {getProfiles} from '../../api/service'
function App() {
getProfiles().then( response => {
File renamed without changes.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

File renamed without changes.
-12
View File
@@ -1637,18 +1637,6 @@
"DK": {
"globals": [],
"modules": [
{
"name": "Http Interface",
"propertyName": "httpInterface",
"functionName": "newDesktopModulesHttpInterface",
"fileName": "HttpInterface.js"
},
{
"name": "Web Sockets Interface",
"propertyName": "webSocketsInterface",
"functionName": "newDesktopModulesWebSocketsInterface",
"fileName": "WebSocketsInterface.js"
},
{
"name": "Web App Interface",
"propertyName": "webAppInterface",
@@ -7,14 +7,12 @@ exports.newSocialTradingModulesWebAppInterface = function newSocialTradingModule
Later, it will try to use the personal social graph as a cache,
so as to minimize the requests to Network Nodes.
*/
let thisObject = {
return {
messageReceived: messageReceived,
initialize: initialize,
finalize: finalize
}
return thisObject
function finalize() {
}
@@ -191,34 +189,32 @@ exports.newSocialTradingModulesWebAppInterface = function newSocialTradingModule
the Network Nodes do not store that info themselves, they just
store the structure of the social graph.
*/
let promise = new Promise((resolve, reject) => {
return new Promise((resolve, reject) => {
const fileName = postHash + ".json"
const filePath = 'My-Social-Trading-Data/main/User-Posts/' + SA.projects.foundations.utilities.filesAndDirectories.pathFromDate(timestamp)
const fileName = postHash + ".json"
const filePath = 'My-Social-Trading-Data/main/User-Posts/' + SA.projects.foundations.utilities.filesAndDirectories.pathFromDate(timestamp)
const fetch = SA.nodeModules.nodeFetch
let url = 'https://raw.githubusercontent.com/' + userProfileHandle + '/' + filePath + '/' + fileName
const fetch = SA.nodeModules.nodeFetch
let url = 'https://raw.githubusercontent.com/' + userProfileHandle + '/' + filePath + '/' + fileName
fetch(url)
.then((response) => {
fetch(url)
.then((response) => {
if (response.status != 200) {
reject('Github.com responded with status ' + response.status)
return
}
if (response.status !== 200) {
reject('Github.com responded with status ' + response.status)
return
}
response.text().then(body => {
post = JSON.parse(body)
resolve(post.postText)
response.text().then(body => {
post = JSON.parse(body)
resolve(post.postText)
})
})
.catch(err => {
resolve('Post Text could not be fetched. ' + err.message)
})
})
.catch(err => {
resolve('Post Text could not be fetched. ' + err.message)
})
}
}
)
return promise
}
}
@@ -1,103 +0,0 @@
exports.newDesktopModulesWebSocketsInterface = function newDesktopModulesWebSocketsInterface() {
/*
This module handles the websockets communication between the
Desktop App's Client and the Desktop App's Web App.
*/
let thisObject = {
sendToWebApp: sendToWebApp,
initialize: initialize,
finalize: finalize
}
let socketServer
let webApp
return thisObject
function finalize() {
socketServer = undefined
webApp = undefined
}
function initialize() {
let port = JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webSocketsPort
socketServer = new SA.nodeModules.ws.Server({ port: port })
setUpWebSocketServer()
}
function setUpWebSocketServer() {
try {
socketServer.on('connection', onConnectionOpened)
function onConnectionOpened(socket)
/*
This function is executed every time a new Websockets connection
is established.
*/ {
if (webApp !== undefined) {
console.log('[ERROR] Only one websockets client allowed.')
return
}
webApp = {
socket: socket
}
console.log('Desktop Web App Connected to Web Sockets Interface ........................... Connected to port ' + global.env.DESKTOP_WEB_SOCKETS_INTERFACE_PORT)
webApp.socket.on('close', onConnectionClosed)
webApp.socket.on('message', onMenssage)
async function onMenssage(message) {
try {
let messageHeader
try {
messageHeader = JSON.parse(message)
} catch (err) {
let response = {
messageId: messageHeader.messageId,
result: 'Error',
message: 'messageHeader Not Coorrect JSON Format.'
}
webApp.socket.send(JSON.stringify(response))
return
}
await DK.desktopApp.webAppInterface.messageReceived(messageHeader.payload)
.then(sendResponseToWebApp)
.catch(onError)
function sendResponseToWebApp(response) {
response.messageId = messageHeader.messageId
webApp.socket.send(JSON.stringify(response))
}
function onError(errorMessage) {
console.log('[ERROR] Web Sockets Interface -> onMenssage -> errorMessage = ' + errorMessage)
let response = {
messageId: messageHeader.messageId,
result: 'Error',
message: errorMessage
}
webApp.socket.send(JSON.stringify(response))
}
} catch (err) {
console.log('[ERROR] Web Sockets Interface -> onMenssage -> err.stack = ' + err.stack)
}
}
}
function onConnectionClosed() {
webApp = undefined
console.log('Desktop Web App Discoonnected from Web Sockets Interface ................... Disonnected from port ' + global.env.DESKTOP_WEB_SOCKETS_INTERFACE_PORT)
}
} catch (err) {
console.log('[ERROR] Web Sockets Interface -> setUpWebSocketServer -> err.stack = ' + err.stack)
}
}
function sendToWebApp(message) {
webApp.socket.send(JSON.stringify(message))
}
}
@@ -1,99 +0,0 @@
exports.newDesktopModulesHttpInterface = function newDesktopModulesHttpInterface() {
/*
This module represent the HTTP API of the
Desktop App Client. All HTTP request are processed
by this module.
*/
let thisObject = {
initialize: initialize,
finalize: finalize
}
return thisObject
function finalize() {
}
function initialize() {
let port = JSON.parse(DK.desktopApp.p2pNetworkClient.node.config).webPort
/*
We will create an HTTP Server and leave it running forever.
*/
SA.nodeModules.http.createServer(onHttpRequest).listen(port)
/* Starting the browser now is optional */
if (process.argv.includes("noBrowser")) {
//Running Client only with no UI.
} else {
// no ui needed
// SA.nodeModules.open('http://localhost:' + port)
}
}
function onHttpRequest(httpRequest, httpResponse) {
try {
let requestPathAndParameters = httpRequest.url.split('?') // Remove version information
let requestPath = requestPathAndParameters[0].split('/')
let endpointOrFile = requestPath[1]
switch (endpointOrFile) {
case 'Environment':
{
SA.projects.foundations.utilities.httpResponses.respondWithContent(JSON.stringify(global.env), httpResponse)
}
break
case 'ClientNode':
{
SA.projects.foundations.utilities.httpResponses.respondWithContent(JSON.stringify(DK.desktopApp.p2pNetworkClient.node), httpResponse)
}
break
case 'ProjectsSchema':
{
let path = global.env.PATH_TO_PROJECTS + '/' + 'ProjectsSchema.json'
SA.projects.foundations.utilities.httpResponses.respondWithFile(path, httpResponse)
}
break
case 'Projects':
{
let path = ''
for (let i = 2; i < 10; i++) {
if (requestPath[i] !== undefined) {
let parameter = unescape(requestPath[i])
path = path + '/' + parameter
}
}
let filePath = global.env.PATH_TO_PROJECTS + path
SA.projects.foundations.utilities.httpResponses.respondWithFile(filePath, httpResponse)
}
break
case 'Images': // This means the Images folder.
{
let path = global.env.PATH_TO_DESKTOP + '/WebServer/Images/' + requestPath[2]
if (requestPath[3] !== undefined) {
path = path + '/' + requestPath[3]
}
if (requestPath[4] !== undefined) {
path = path + '/' + requestPath[4]
}
if (requestPath[5] !== undefined) {
path = path + '/' + requestPath[5]
}
path = unescape(path)
SA.projects.foundations.utilities.httpResponses.respondWithImage(path, httpResponse)
}
break
default:
{
SA.projects.foundations.utilities.httpResponses.respondWithWebFile(httpResponse, endpointOrFile, global.env.PATH_TO_DESKTOP)
}
}
} catch (err) {
console.log(err.stack)
}
}
}
+1
View File
@@ -14,6 +14,7 @@
"postsetup": "npm start",
"dist": "electron-builder -c build/electron-builder.json",
"postinstall": "electron-builder install-app-deps",
"startNetwork" : "node network",
"startDesktop": "node desktop"
},
"dependencies": {