Skip to content

Commit

Permalink
feat: add function deleteFileByGateway
Browse files Browse the repository at this point in the history
  • Loading branch information
fage2022 committed Sep 4, 2024
1 parent bc06d2e commit f4439a9
Show file tree
Hide file tree
Showing 6 changed files with 105 additions and 38 deletions.
18 changes: 9 additions & 9 deletions dist/index.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"license": "MIT",
"version": "0.2.10",
"description": "A js-sdk for Cess Project with file storage",
"main": "./dist/index.js",
"module": "./dist/index.js",
"main": "./src/index.js",
"module": "./src/index.js",
"type": "module",
"types": "dist/types.d.ts",
"repository": {
Expand Down
55 changes: 55 additions & 0 deletions src/api/file.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,10 @@ export default class File extends ControlBase {
msg: "sign error",
};
}

if (!progressCb || typeof progressCb != "function") {
progressCb = () => { };
}
const headers = {
Territory: territory,
Bucket: 'cess',
Expand All @@ -208,6 +212,20 @@ export default class File extends ControlBase {
if (headers.FileName.length > 63) {
headers.FileName = headers.FileName.slice(-63);
}
progressCb({
percentComplete: 0,
speed: 0,
speedUnit: "KB/s",
blockIndex: 0,
chunkCount: 10,
message: message,
signedMsg: sign,
xhr: {
abort: () => { },
pause: () => { },
resume: () => { },
}
});
console.log('upload by chunk to ', this.gatewayURL);
const ret = await fileHelper.uploadWithChunk(
this.gatewayURL,
Expand All @@ -234,4 +252,41 @@ export default class File extends ControlBase {
const extrinsic = this.api.tx.fileBank.deleteFile(accountId32, fileHash);
return await this.signAndSend(accountId32, extrinsic, subState);
}
async deleteFileByGateway(accountId32, fid, message = null, sign = null, acc, evmacc) {
try {
if (!sign) {
message = "<Bytes>cess-js-sdk-frontend-" + new Date().valueOf() + "</Bytes>";
const { bs58Str } = await this.authSign(accountId32, message);
if (!bs58Str) {
return {
msg: "sign error",
};
}
sign = bs58Str;
}
if (!sign) {
console.log("sign error");
return {
msg: "sign error",
};
}
const headers = {
Account: accountId32,
Message: message,
Signature: sign
};
if (acc) {
headers.ACC = acc;
}
if (evmacc) {
headers.ETHACC = evmacc;
}
console.log('delete file from gateway ', this.gatewayURL);
const ret = await fileHelper.deleteFile(this.gatewayURL + '/file/' + fid, headers);
return ret;
} catch (e) {
console.log(e);
return { msg: "error", error: e };
}
}
};
27 changes: 12 additions & 15 deletions src/control-base.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { web3Accounts, web3Enable, web3FromAddress, web3FromSource } from '@polkadot/extension-dapp';
import { stringToHex, hexToU8a } from "@polkadot/util";
import { encodeAddress } from '@polkadot/util-crypto';

import bs58 from "bs58";

export default class ControlBase {
constructor(api, keyring, isDebug = false) {
Expand Down Expand Up @@ -97,6 +97,11 @@ export default class ControlBase {
async authSign(accountId32, msg) {
await web3Enable("cess");
const allAccounts = await web3Accounts();
let ret = {
signU8A: null,
signStr: null,
bs58Str: null
};

allAccounts.forEach((t) => {
// t.setSS58Format(11330);
Expand All @@ -107,18 +112,12 @@ export default class ControlBase {
account = allAccounts[0];
console.log("account not found:", allAccounts);
// return { msg: "account not found!" };
return {
signU8A: null,
signStr: null
};
return ret;
}
const injector = await web3FromSource(account.meta.source);
const signRaw = injector?.signer?.signRaw;
if (!signRaw) {
return {
signU8A: null,
signStr: null
};
return ret;
}
// after making sure that signRaw is defined
// we can use it to sign our message
Expand All @@ -127,13 +126,11 @@ export default class ControlBase {
data: stringToHex(msg),
type: "bytes",
});
ret.signStr = signature;
// console.log({ signature });
let signU8A = hexToU8a(signature);

return {
signU8A,
signStr: signature
};
ret.signU8A = signature ? hexToU8a(signature) : "";
ret.bs58Str = ret.signU8A ? bs58.encode(ret.signU8A) : "";
return ret;
}

formatAccountId(accountId32) {
Expand Down
6 changes: 3 additions & 3 deletions src/default-config.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

// export default {
// nodeURL: [
// 'wss://testnet-rpc.cess.cloud/ws/',
// 'wss://testnet-rpc.cess.network/ws/',
// 'wss://testnet-rpc.cess.cloud/ws/',
// 'wss://testnet-rpc.cess.network/ws/',
// ],
// keyringOption: { type: "sr25519", ss58Format: 11330 },
// gatewayURL: "http://deoss-pub-gateway.cess.cloud/",
// gatewayURL: "http://192.168.110.247:8080",
// gatewayAddr: "cXhwBytXqrZLr1qM5NHJhCzEMckSTzNKw17ci2aHft6ETSQm9",
// };

Expand Down
33 changes: 24 additions & 9 deletions src/util/file-helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*
*/
import { sleep } from "./index.js";
const CHUNK_SIZE = 1024 * 1024 * 50;
const CHUNK_SIZE = 1024 * 1024 * 5;
export function download(url, savePath, log) {
return new Promise(async (resolve, reject) => {
try {
Expand Down Expand Up @@ -187,9 +187,6 @@ export async function uploadWithChunk(url, file, header, log, progressCb, blockI
if (res.msg != 'ok') {
return res;
}
if (!progressCb || typeof progressCb != "function") {
continue;
}
let percentComplete = Math.ceil(((i + 1) / chunkCount) * 100);
let endTime = new Date().getTime();
let dTime = (endTime - stime) / 1000;
Expand Down Expand Up @@ -231,11 +228,12 @@ function postFile(url, file, header, start, end) {
});
xhr.onload = function () {
let data = 'response' in xhr ? xhr.response : xhr.responseText;
if (xhr.status === 200 || xhr.status === 308) {
resolve({ msg: "ok", data });
} else {
resolve({ msg: data || xhr.statusText });
}
try {
if (typeof data == 'string') {
data = JSON.parse(data);
}
} catch (e) { }
resolve(data);
};
xhr.onerror = function (e) {
resolve({ msg: e.response?.data || e.message });
Expand All @@ -260,4 +258,21 @@ function saveFile(blob, name) {
a.remove();
window?.URL?.revokeObjectURL(blob);//because window is null in the next.js
}
}
export async function deleteFile(url, header) {
return new Promise(async (resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("DELETE", url, true);
Object.keys(header).forEach((key) => {
xhr.setRequestHeader(key, header[key]);
});
xhr.onload = function () {
let data = 'response' in xhr ? xhr.response : xhr.responseText;
resolve({ msg: xhr.status == 200 ? 'ok' : data });
};
xhr.onerror = function (e) {
resolve({ msg: e.response?.data || e.message });
};
xhr.send();
});
}

0 comments on commit f4439a9

Please sign in to comment.