Skip to content
Open
Show file tree
Hide file tree
Changes from 6 commits
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
126 changes: 85 additions & 41 deletions docs/examples/p2pad/dweb.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,74 +34,112 @@ uploadButton.addEventListener('click', assembleCode);
// Upload code to Dweb
async function uploadFile(file) {
const protocol = protocolSelect.value;
console.log(`[uploadFile] Uploading ${file.name}, protocol: ${protocol}`);

const formData = new FormData();

// Append file to the FormData
formData.append('file', file, file.name);


// Construct the URL based on the protocol
let url;
if (protocol === 'hyper') {
const hyperdriveUrl = await generateHyperdriveKey('p2pad');
url = `${hyperdriveUrl}`;
const hyperdriveUrl = await generateHyperdriveKey();
const url = `${hyperdriveUrl}${encodeURIComponent(file.name)}`;
const cleanUrl = url.replace(/index\.html$/, '');
console.log(`[uploadFile] Hyper URL: ${url}`);

try {
const response = await fetch(url, {
method: 'PUT',
body: file, // Send raw file bytes
headers: {
'Content-Type': file.type || 'text/html'
}
});

console.log(`[uploadFile] Response status: ${response.status}, ok: ${response.ok}`);
if (!response.ok) {
const errorText = await response.text();
console.error(`[uploadFile] Error uploading ${file.name}: ${errorText}`);
addError(file.name, errorText);
return;
}

addURL(cleanUrl);
} catch (error) {
console.error(`[uploadFile] Error uploading ${file.name}:`, error);
addError(file.name, error.message);
} finally {
showSpinner(false);
}
} else {
url = `ipfs://bafyaabakaieac/`;
}

// Perform the upload for each file
try {
const response = await fetch(url, {
method: 'PUT',
body: formData,
});

if (!response.ok) {
addError(file, await response.text());
// IPFS upload with FormData
const formData = new FormData();
console.log(`[uploadFile] Appending file for IPFS: ${file.name}`);
formData.append('file', file, file.name);

const url = `ipfs://bafyaabakaieac/`;
console.log(`[uploadFile] IPFS URL: ${url}`);

try {
const response = await fetch(url, {
method: 'PUT',
body: formData,
});

console.log(`[uploadFile] IPFS Response status: ${response.status}, ok: ${response.ok}`);
if (!response.ok) {
const errorText = await response.text();
console.error(`[uploadFile] IPFS Error: ${errorText}`);
addError(file.name, errorText);
return;
}

const locationHeader = response.headers.get('Location');
console.log(`[uploadFile] IPFS Location header: ${locationHeader}`);
addURL(locationHeader);
} catch (error) {
console.error(`[uploadFile] Error uploading to IPFS:`, error);
addError(file.name, error.message);
} finally {
showSpinner(false);
}
const urlResponse = protocol === 'hyper' ? response.url : response.headers.get('Location');
addURL(urlResponse);
} catch (error) {
console.error(`Error uploading ${file}:`, error);
} finally {
showSpinner(false);
}
}

async function generateHyperdriveKey() {
// Generate a unique name using timestamp and random string
const timestamp = Date.now();
const randomStr = Math.random().toString(36).substring(2, 8);
const uniqueName = `p2p-editor-${timestamp}-${randomStr}`;
console.log(`[generateHyperdriveKey] Generating key for name: ${uniqueName}`);


async function generateHyperdriveKey(name) {
try {
const response = await fetch(`hyper://localhost/?key=${name}`, { method: 'POST' });
const response = await fetch(`hyper://localhost/?key=${encodeURIComponent(uniqueName)}`, { method: 'POST' });
if (!response.ok) {
throw new Error(`Failed to generate Hyperdrive key: ${response.statusText}`);
}
return await response.text(); // This returns the hyper:// URL
const hyperUrl = await response.text();
console.log(`[generateHyperdriveKey] Hyperdrive URL: ${hyperUrl}`);
return hyperUrl; // Returns the hyper:// URL
} catch (error) {
console.error('Error generating Hyperdrive key:', error);
console.error('[generateHyperdriveKey] Error generating Hyperdrive key:', error);
throw error;
}
}


function addURL(url) {
console.log(`[addURL] Adding URL: ${url}`);
const listItem = document.createElement('li');
const link = document.createElement('a');
link.href = url;
link.textContent = url;

const copyContainer = document.createElement('span');
const copyIcon = '⊕'
const copyIcon = '⊕';
copyContainer.innerHTML = copyIcon;
copyContainer.onclick = function() {
navigator.clipboard.writeText(url).then(() => {
copyContainer.textContent = '';
copyContainer.textContent = ' Copied!';
setTimeout(() => {
copyContainer.innerHTML = copyIcon;
}, 3000);
}).catch(err => {
console.error('Error in copying text: ', err);
console.error('[addURL] Error in copying text: ', err);
});
};

Expand All @@ -110,13 +148,14 @@ function addURL(url) {
uploadListBox.appendChild(listItem);
}


function addError(name, text) {
uploadListBox.innerHTML += `<li class="log">Error in ${name}: ${text}</li>`
console.log(`[addError] Error in ${name}: ${text}`);
uploadListBox.innerHTML += `<li class="log">Error in ${name}: ${text}</li>`;
}

// The fetchFromDWeb function detects which protocol is used and fetches the content
async function fetchFromDWeb(url) {
console.log(`[fetchFromDWeb] Fetching URL: ${url}`);
if (!url) {
alert("Please enter a CID or Name.");
return;
Expand All @@ -129,10 +168,11 @@ async function fetchFromDWeb(url) {

try {
const response = await fetch(url);
console.log(`[fetchFromDWeb] Response status: ${response.status}`);
const data = await response.text();
parseAndDisplayData(data);
} catch (error) {
console.error("Error fetching from DWeb:", error);
console.error("[fetchFromDWeb] Error fetching from DWeb:", error);
alert("Failed to fetch from DWeb.");
}
}
Expand All @@ -145,6 +185,7 @@ fetchButton.addEventListener('click', () => {

// Parse the data and display it in the code editor
function parseAndDisplayData(data) {
console.log(`[parseAndDisplayData] Parsing received data`);
const parser = new DOMParser();
const doc = parser.parseFromString(data, 'text/html');

Expand All @@ -165,8 +206,11 @@ function parseAndDisplayData(data) {
const htmlContent = doc.body.innerHTML; // Get the content inside the body tag without script/style tags

// Displaying the content in respective textareas
console.log(`[parseAndDisplayData] Setting HTML: ${htmlContent.substring(0, 50)}...`);
console.log(`[parseAndDisplayData] Setting CSS: ${cssContent.substring(0, 50)}...`);
console.log(`[parseAndDisplayData] Setting JS: ${jsContent.substring(0, 50)}...`);
$('#htmlCode').value = htmlContent;
$('#cssCode').value = cssContent;
$('#javascriptCode').value = jsContent;
update(0);
}
}
8 changes: 5 additions & 3 deletions explore.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ Feel free to [submit a pull request](https://github.com/AgregoreWeb/website/) on
- [Drag and Drop File Uploads](/docs/examples/drag-and-drop/)
- [Theme Builder](/docs/examples/themebuilder)
- [Pin Manager](https://agregoreweb.github.io/pin-manager/) for talking to IPFS pinning services
- [Sutty CMS, static site generator with dweb publishing](https://sutty.nl/en/)
- [P2Pad Code Editor](/docs/examples/p2pad/)
- [Sutty CMS, static site generator with dweb publishing](https://sutty.nl/en/)
- [Distributed Press Social Reader](//reader.distributed.press/)
- [LLM App Generator](/docs//examples/llm-appgen/)
- [Distributed Press CLI](https://github.com/hyphacoop/distributed-press-cli/)
- [DWeb Explorer](https://explore.distributed.press/)
- [LLM App Generator](/docs//examples/llm-appgen/)
- [LLM Chat Example](/docs/examples/llm-chat.html)
- [LLM Tonal Lenses](/docs/examples/llm-lenses-chat/)
- [Quick Code Snippet Generator](/docs/examples/quickcode.html)
Expand Down Expand Up @@ -43,7 +44,8 @@ Feel free to [submit a pull request](https://github.com/AgregoreWeb/website/) on
### Other browsers:

- [Peersky](https://peersky.p2plabs.xyz/)
- [IPFS in Brave](https://blog.ipfs.io/2021-01-21-how-we-put-ipfs-in-brave/)
- ~~[IPFS in Brave](https://github.com/brave/brave-browser/issues/37735)~~
- [Galacteek](https://galacteek.gitlab.io/)
- [Hybrid](https://github.com/HybridWare/hybrid-browser)

---
Expand Down