Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
User client recieves messages and displays them successfully + cleanu…
…p of code.

- TODO , IPFS download file to clients computer via CID, must be private and not a direct download
  • Loading branch information
joeiacono2021 committed Mar 7, 2023
commit 9953c4689259d2a11fd9aa08de10e6f70dfb4dd4
45 changes: 0 additions & 45 deletions ipfs-service-provider-tutorial/service-provider/src/.gitignore

This file was deleted.

40 changes: 5 additions & 35 deletions ipfs-service-provider-tutorial/service-provider/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import WebSocket, { MessageEvent } from "ws";
import { IPFS, create } from 'ipfs-core'
import type { CID } from 'multiformats/cid'
import fetch from 'node-fetch';
import { fileURLToPath } from "url";

var ourAddress: string;
var websocketConnection: any;
Expand Down Expand Up @@ -31,22 +30,7 @@ async function main() {
ipfsNode = await create();
ipfsVersion = await ipfsNode.version();

console.log('IPFS Version:', ipfsVersion.version)

///doIpfs();
}


const readFile = async (ipfs: IPFS, cid: CID): Promise<string> => {
const decoder = new TextDecoder()
let content = ''

for await (const chunk of ipfs.cat(cid)) {
content += decoder.decode(chunk, {
stream: true
})
}
return content
console.log('IPFS Version:', ipfsVersion.version);
}

// Handle any messages that come back down the websocket.
Expand All @@ -73,7 +57,7 @@ function handleResponse(responseMessageEvent : MessageEvent) {
console.log('\x1b[93mUploading file to IPFS... \x1b[0m')

uploadToIPFS(messageContent,response.senderTag)
//sendMessageToMixnet(response.senderTag)

}
} catch (_) {
console.log('something went wrong in handleResponse')
Expand All @@ -82,16 +66,8 @@ function handleResponse(responseMessageEvent : MessageEvent) {

async function uploadToIPFS(dataToUpload : any,senderTag : string) {
let fileContent;
/*
const file = await ipfsNode.add({
path: dataToUpload.name,
content: new TextEncoder().encode(dataToUpload.dataUrl)
})
*/

if (dataToUpload.type.startsWith('text')) {
// For text files, encode the content as a Uint8Array
//console.log(dataToUpload);
//fileContent = new TextEncoder().encode(dataToUpload.dataUrl);

const blob = await fetch(dataToUpload.dataUrl).then((response: { blob: () => any; }) => response.blob());
fileContent = await blob.arrayBuffer();
Expand All @@ -101,7 +77,7 @@ async function uploadToIPFS(dataToUpload : any,senderTag : string) {
const blob = await fetch(dataToUpload.dataUrl).then((response: { blob: () => any; }) => response.blob());
fileContent = await blob.arrayBuffer();
} else {
// For all other file types, pass the data URL string as the content

fileContent = dataToUpload.dataUrl;
}

Expand All @@ -114,12 +90,9 @@ async function uploadToIPFS(dataToUpload : any,senderTag : string) {
try {
file.cid.toUpperCase()
} catch (error) {

console.log(error)
}

//const content = await readFile(ipfsNode, file.cid)

//console.log('Added file contents:', content)
sendMessageToMixnet(file.path,file.cid.toString(),senderTag)
}

Expand Down Expand Up @@ -184,10 +157,7 @@ function connectWebsocket(url : string) {
server.onerror = function (err) {
reject(err);
};

});
}



main();
80 changes: 33 additions & 47 deletions ipfs-service-provider-tutorial/user-client/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ async function main() {
fileInput.addEventListener('change', onFileChange, false);
}

// Get our own client address to log in the activity log so we know what our address is in the mixnet via our application UI
/*
Get our own client address to log in the activity log so we know what our address is in the mixnet via our application UI
*/
function sendSelfAddressRequest() {
var selfAddress = {
type: "selfAddress"
Expand All @@ -55,7 +57,9 @@ function readAndSendFile(event) {
sendMessageToMixnet(blobResult);
}

// Function that gets the form data and sends that to the mixnet in a stringified JSON format.
/*
Function that gets the form data and sends that to the mixnet in a stringified JSON format.
*/
function sendMessageToMixnet(payload) {

var messageContentToSend = {
Expand All @@ -82,20 +86,11 @@ function sendMessageToMixnet(payload) {
websocketConnection.send(JSON.stringify(message));
}

// Display responses into our activity log.
/*
Display responses into our activity log.
*/
function displayJsonSend(message) {

/*
let sendDiv = document.createElement("div")
let paragraph = document.createElement("p")
paragraph.setAttribute('style', 'color: #36d481')
let paragraphContent = document.createTextNode("sent >>> " + JSON.stringify(message))
paragraph.appendChild(paragraphContent)

sendDiv.appendChild(paragraph)
document.getElementById("output").appendChild(sendDiv)
*/

let sendDiv = document.createElement("div")
let messageLog = document.createElement("p")

Expand All @@ -119,7 +114,9 @@ function displayJsonSend(message) {
document.getElementById("output").appendChild(sendDiv)
}

// Connect to a websocket.
/*
Connect to a websocket.
*/
function connectWebsocket(url) {
return new Promise(function (resolve, reject) {
var server = new WebSocket(url);
Expand All @@ -133,57 +130,45 @@ function connectWebsocket(url) {
});
}

// Display messages that relate to initialising our client + client status in our activity log.
/*
Handle any messages that come back down the websocket.
*/
function displayClientMessage(message) {
document.getElementById("output").innerHTML += "<p>" + message + "</p >";
}

// Handle any messages that come back down the websocket.
/*
Handle any messages that come back down the websocket.
*/
function handleResponse(resp) {
let response = JSON.parse(resp.data);
try {
//let response = JSON.parse(resp.data);
console.log(response);
if (response.type == "error") {
displayJsonResponse("Server responded with error: " + response.message);
}
//else if (response.type == "selfAddress") {
// ourAddress = response.address;
//displayClientMessage("Our address is: " + ourAddress);
// displayJsonReceived(response);
//} else if (response.type == "received") {
// handleReceivedTextMessage(response)
//}
else if (response.type == "selfAddress" || response.type == "received"){
displayJsonReceived(response);
} else if (response.type == "selfAddress"){
displayJsonResponse(response);
} else if (response.type == "received"){
handleReceivedTextMessage(response);
}
} catch (_) {
displayJsonReceived(response);
displayJsonResponse(response);
}
}

// Handle any string message values that are received through messages sent back to us.
/*
Handle any string message values that are received through messages sent back to us.
*/
function handleReceivedTextMessage(message) {
const text = JSON.parse(message.message)
displayJsonResponse(text)
}

// Display websocket responses in the Activity Log.
function displayJsonResponse(message) {
let receivedDiv = document.createElement("div")
let paragraph = document.createElement("p")
paragraph.setAttribute('style', 'color: orange')
let textNode = document.createTextNode("received >>> " + message.text)
paragraph.appendChild(textNode)

receivedDiv.appendChild(paragraph)
document.getElementById("output").appendChild(receivedDiv)
}

/*
Functions that will display 'send' related event logs into our activity log.
*/
function displayJsonReceived(message) {
function displayJsonResponse(message) {
//Variables that will get us the date and time value of when we receive the uploaded file.
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
Expand All @@ -204,18 +189,21 @@ function displayJsonReceived(message) {

if (message.type == 'selfAddress'){
//Display our self address.
ourAddress = message.address;
line1Contents = document.createTextNode("Initialized Mixnet Websocket.");
line2Contents = document.createTextNode('Our address : ' + message.address);
}

if (message.type == 'recieved'){
if (message.type == 'received'){
//Display the time and name of the uploaded file.
let parsedMessageContents = JSON.parse(message.message);

console.log(parsedMessageContents);

//Creating a data log object to display on our UI
let dataLog = {
url : 'https://ipfs.io/ipfs/' + parsedMessageContents.cid,
name: parsedMessageContents.name,
url : 'https://ipfs.io/ipfs/' + parsedMessageContents.fileCid,
name: parsedMessageContents.filePath,
time : today.toUTCString()
}

Expand All @@ -231,6 +219,4 @@ function displayJsonReceived(message) {
document.getElementById("output").appendChild(receivedDiv);
}



main();