Skip to content

Commit

Permalink
Pull from origin main
Browse files Browse the repository at this point in the history
  • Loading branch information
jamiehewitt15 committed Oct 31, 2024
2 parents ad0fd06 + 856598f commit 829e263
Show file tree
Hide file tree
Showing 5 changed files with 215 additions and 58 deletions.
2 changes: 1 addition & 1 deletion metadata/simpleDownloadDataset.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"id": "",
"nftAddress": "",
"version": "4.1.0",
"chainId": 80001,
"chainId": 11155420,
"metadata": {
"created": "2021-12-20T14:35:20Z",
"updated": "2021-12-20T14:35:20Z",
Expand Down
15 changes: 0 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

112 changes: 74 additions & 38 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as vscode from 'vscode'
import { Aquarius, Asset, ConfigHelper } from '@oceanprotocol/lib'
import { Aquarius, Asset } from '@oceanprotocol/lib'
import { OceanProtocolViewProvider } from './viewProvider'
import { ethers } from 'ethers'
import * as fs from 'fs'
import { createAsset } from './helpers/publish'
import fetch from 'cross-fetch'
import { OceanP2P } from './helpers/oceanNode'
import { download } from './helpers/download'

globalThis.fetch = fetch
const node = new OceanP2P()
Expand Down Expand Up @@ -80,6 +81,10 @@ export async function activate(context: vscode.ExtensionContext) {
let publishAsset = vscode.commands.registerCommand(
'ocean-protocol.publishAsset',
async (config: any, filePath: string, privateKey: string) => {
if (!config) {
vscode.window.showErrorMessage('No config provided.')
return
}
if (!filePath) {
vscode.window.showErrorMessage('No file path provided.')
return
Expand All @@ -100,47 +105,12 @@ export async function activate(context: vscode.ExtensionContext) {
console.log('Asset JSON parsed successfully.')

// Set up the signer
console.log(config.rpcUrl)
const provider = new ethers.providers.JsonRpcProvider(config.rpcUrl)

console.log('RPC URL:', config.rpcUrl)

console.log('NFT Factory Address:', config.nftFactoryAddress)
console.log('Ocean Token Address:', config.oceanTokenAddress)

const signer = new ethers.Wallet(privateKey, provider)
console.log('Signer:', signer)
const chainId = await signer.getChainId()
console.log('Chain ID:', chainId)

// Test provider connectivity
try {
<<<<<<< HEAD
const network = await provider.getNetwork()
vscode.window.showInformationMessage(`Connected to network: ${network.name}`)
=======
const network = provider.network
console.log(`Connected to network: ${network}`)
>>>>>>> 371c67148e1a76b101bb8f9debd8eb0f13eabcd5
} catch (networkError) {
console.error('Error connecting to network:', networkError)
vscode.window.showErrorMessage(
`Error connecting to network: ${networkError.message}`
)
return
}
try {
const blockNumber = await provider.getBlockNumber()
console.log('Current block number:', blockNumber)
} catch (error) {
console.error('Error connecting to provider:', error)
}

const aquarius = new Aquarius(config.aquariusUrl)
console.log('Chain ID:', chainId)
const oceanConfig = new ConfigHelper().getConfig(chainId)

console.log('Ocean Config:', oceanConfig)
console.log('creating asset:', asset)

const urlAssetId = await createAsset(
asset.nft.name,
Expand Down Expand Up @@ -193,5 +163,71 @@ export async function activate(context: vscode.ExtensionContext) {
}
)

context.subscriptions.push(getAssetDetails, publishAsset, getOceanPeers)
let downloadAsset = vscode.commands.registerCommand(
'ocean-protocol.downloadAsset',
async (config: any, filePath: string, privateKey: string, assetDid: string) => {
if (!config) {
vscode.window.showErrorMessage('No config provided.')
return
}
if (!assetDid) {
vscode.window.showErrorMessage('No DID provided.')
return
}
if (!filePath) {
vscode.window.showErrorMessage('No file path provided.')
return
}

if (!privateKey) {
vscode.window.showErrorMessage('No private key provided.')
return
}

try {
// Set up the signer
const provider = new ethers.providers.JsonRpcProvider(config.rpcUrl)
const signer = new ethers.Wallet(privateKey, provider)
console.log(`Signer: ${signer}`)

// Test provider connectivity
try {
const network = provider.network
vscode.window.showInformationMessage(`Connected to network: ${network}`)
} catch (networkError) {
console.error('Error connecting to network:', networkError)
vscode.window.showErrorMessage(
`Error connecting to network: ${networkError.message}`
)
return
}

const aquarius = new Aquarius(config.aquariusUrl)

await download(
assetDid,
signer,
filePath,
aquarius,
undefined,
config.providerUrl
)

vscode.window.showInformationMessage(
`Asset download successfully. Path: ${filePath}`
)
} catch (error) {
console.error('Error details:', error)
if (error instanceof Error) {
vscode.window.showErrorMessage(`Error downloading asset: ${error.message}`)
} else {
vscode.window.showErrorMessage(
`An unknown error occurred while downloading the asset.`
)
}
}
}
)

context.subscriptions.push(getAssetDetails, publishAsset, downloadAsset, getOceanPeers)
}
99 changes: 99 additions & 0 deletions src/helpers/download.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import {
Aquarius,
Datatoken,
ProviderInstance,
ConfigHelper,
orderAsset
} from '@oceanprotocol/lib'
import { Signer } from 'ethers'
import { promises as fs } from 'fs'
import * as path from 'path'

export async function downloadFile(
url: string,
downloadPath: string,
index?: number
): Promise<any> {
const response = await fetch(url)
if (!response.ok) {
throw new Error('Response error.')
}

const defaultName = !isNaN(index) && index > -1 ? `file_${index}.out` : 'file.out'
let filename: string

try {
// try to get it from headers
filename = response.headers
.get('content-disposition')
.match(/attachment;filename=(.+)/)[1]
} catch {
filename = defaultName
}

const filePath = path.join(downloadPath, filename)
const data = await response.arrayBuffer()

try {
await fs.writeFile(filePath, Buffer.from(data))
} catch (err) {
throw new Error('Error while saving the file:', err.message)
}

return filename
}

export async function download(
did: string,
owner: Signer,
pathString: string = '.',
aquariusInstance: Aquarius,
macOsProviderUrl?: string,
providerUrl?: string
) {
const dataDdo = await aquariusInstance.waitForAqua(did)
if (!dataDdo) {
console.error('Error fetching DDO ' + did + '. Does this asset exists?')
return
}
let providerURI
if (!providerUrl) {
providerURI =
macOsProviderUrl && dataDdo.chainId === 8996
? macOsProviderUrl
: dataDdo.services[0].serviceEndpoint
} else {
providerURI = providerUrl
}
console.log('Downloading asset using provider: ', providerURI)
const { chainId } = await owner.provider.getNetwork()
console.log('Chain ID:', chainId)
const config = new ConfigHelper().getConfig(chainId)
console.log('Config:', config)
const datatoken = new Datatoken(owner, chainId)

const tx = await orderAsset(dataDdo, owner, config, datatoken, providerURI)

if (!tx) {
console.error('Error ordering access for ' + did + '. Do you have enough tokens?')
return
}

const orderTx = await tx.wait()

const urlDownloadUrl = await ProviderInstance.getDownloadUrl(
dataDdo.id,
dataDdo.services[0].id,
0,
orderTx.transactionHash,
providerURI,
owner
)
try {
const path = pathString ? pathString : '.'
const { filename } = await downloadFile(urlDownloadUrl, path)
console.log('File downloaded successfully:', path + '/' + filename)
} catch (e) {
console.log(`Download url dataset failed: ${e}`)
}
}
45 changes: 41 additions & 4 deletions src/viewProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ export class OceanProtocolViewProvider implements vscode.WebviewViewProvider {
data.privateKey
)
break
case 'downloadAsset':
vscode.commands.executeCommand(
'ocean-protocol.downloadAsset',
data.config,
data.filePath,
data.privateKey,
data.assetDid
)
break
case 'openFilePicker':
this.openFilePicker()
break
Expand Down Expand Up @@ -166,8 +175,10 @@ export class OceanProtocolViewProvider implements vscode.WebviewViewProvider {
<input id="rpcUrl" placeholder="RPC URL" value="http://127.0.0.1:8545" />
<label for="nodeUrl">Ocean Node URL</label>
<input id="nodeUrl" placeholder="Ocean Node URL" value="http://127.0.0.1:8001" />
<input id="nodeUrl" placeholder="Ocean Node URL" value="http://127.0.0.1:8000" />
<label for="privateKeyInput">Private Key</label>
<input id="privateKeyInput" type="password" placeholder="Enter your private key" />
</div>
</div>
</div>
Expand All @@ -194,9 +205,6 @@ export class OceanProtocolViewProvider implements vscode.WebviewViewProvider {
<button id="selectFileBtn">Select Asset File</button>
<div id="selectedFilePath"></div>
<label for="privateKeyInput">Private Key</label>
<input id="privateKeyInput" type="password" placeholder="Enter your private key" />
<button id="publishAssetBtn">Publish Asset</button>
</div>
</div>
Expand All @@ -215,6 +223,19 @@ export class OceanProtocolViewProvider implements vscode.WebviewViewProvider {
</div>
</div>
</div>
<div id="downloadHeader" class="section-header">
<span class="chevron">&#9658;</span>Download Asset
</div>
<div id="download" class="section-content">
<div class="container">
<label for="assetDidInput">Asset DID</label>
<input id="assetDidInput" placeholder="Enter your asset DID" />
<label for="pathInput">File Path</label>
<input id="pathInput" placeholder="Enter your file path" />
<button id="downloadAssetBtn">Download Asset</button>
</div>
</div>
</div>
<script>
const vscode = acquireVsCodeApi();
Expand Down Expand Up @@ -244,6 +265,7 @@ export class OceanProtocolViewProvider implements vscode.WebviewViewProvider {
document.getElementById('getOceanPeersBtn').addEventListener('click', () => {
vscode.postMessage({ type: 'getOceanPeers' });
});
document.getElementById('downloadHeader').addEventListener('click', () => toggleSection('download'));
});
document.getElementById('getAssetDetailsBtn').addEventListener('click', () => {
Expand Down Expand Up @@ -283,7 +305,22 @@ export class OceanProtocolViewProvider implements vscode.WebviewViewProvider {
break;
}
});
document.getElementById('downloadAssetBtn').addEventListener('click', () => {
const config = getConfig();
const privateKey = document.getElementById('privateKeyInput').value;
const assetDidSelected = document.getElementById('assetDidInput').value;
const pathSelected = document.getElementById('pathInput').value;
vscode.postMessage({
type: 'downloadAsset',
config: config,
filePath: pathSelected,
privateKey: privateKey,
assetDid: assetDidSelected
});
});
</script>
</body>
</html>
`
Expand Down

0 comments on commit 829e263

Please sign in to comment.