Skip to content

Instantly share code, notes, and snippets.

@TzuHanLiang
Created April 9, 2019 07:07
Show Gist options
  • Save TzuHanLiang/50ad76bc32cbe619dc05931c7ca6520d to your computer and use it in GitHub Desktop.
Save TzuHanLiang/50ad76bc32cbe619dc05931c7ca6520d to your computer and use it in GitHub Desktop.
const SHA1 = blob => {
// console.log("sha1 is called")
if(workers >= maxWorker){
// console.log("sha1 : check worker")
sha1Queue.push(SHA1(blob));
}else{
// console.log("sha1 : done about checking worker")
return new Promise((resolve, reject) => {
const worker = new Worker("../assets/js/plugins/rusha.min.js");
worker.postMessage({data: blob});
workers++;
// console.log(workers)
worker.onmessage = evt => {
console.log(evt)
resolve(evt.data);
// closeWorker(worker);
}
worker.onerror = evt => {
console.log(evt)
reject(evt.message);
// closeWorker(worker);
}
})
}
}
// 獲得某file的第 index 個加上 shardInfo 且 hash 的碎片,以及它要去的地方 👉 path
const getHashShard = async parseFile => {
// console.log(parseFile)
const file = parseFile.file;
const fid = parseFile.fid;
const index = parseFile.sliceIndex;
const count = parseFile.sliceCount;
const size = parseFile.size;
const sliceSize = parseFile.sliceSize;
const start = index * sliceSize;
let end;
if((index + 1) * sliceSize > size){
end = size;
}else{
end = (index + 1) * sliceSize;
}
const shardInfo = genShardInfo(count, index); // get shardInfo
// console.log(shardInfo)
const blob = slice(file, start, end); // 取得file第i個blob
// console.log(blob, file, start, end);
const shard = new Uint8Array(shardInfo.length + sliceSize); // 組合 shardInfo & blob 👉 shard
shard.set(shardInfo, 0);
shard.set(blob, shardInfo.length);
try{
const res = await SHA1(shard);
console.log(res);
parseFile.sliceIndex += 1 ; //紀錄進度
return ({
index,
path: `/file/${fid}/${res.hash}`,
blob: new Blob([res.hash]),
})
}catch(error){
console.log(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment