Skip to content

Commit

Permalink
🚸 Add ebook download progress
Browse files Browse the repository at this point in the history
  • Loading branch information
williamchong committed Jun 24, 2024
1 parent bd0de6f commit d469a00
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 3 deletions.
53 changes: 50 additions & 3 deletions src/mixins/reader.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
export default {
data() {
return {
totalSize: 0,
progressSize: 0,
};
},
props: {
classId: {
type: String,
Expand All @@ -17,8 +23,23 @@ export default {
default: '',
},
},
computed: {
progressPercent() {
return this.totalSize
? Math.round((this.progressSize * 100.0) / this.totalSize)
: 0;
},
progressSizeInMB() {
return (this.progressSize / (1024 * 1024)).toFixed(2);
},
totalSizeInMB() {
return (this.totalSize / (1024 * 1024)).toFixed(2);
},
},
methods: {
async getFileBuffer(cacheKey) {
this.totalSize = 0;
this.progressSize = 0;
let res;
const req = new Request(this.corsUrl);
if (window.caches) {
Expand All @@ -38,15 +59,41 @@ export default {
if (window.caches) {
try {
const cache = await caches.open(cacheKey);
await cache.put(req, res.clone());
cache.put(req, res.clone());
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
}
}
const buffer = await res.arrayBuffer();
return buffer;
const reader = res.body.getReader();

const contentLength = +res.headers.get('X-Original-Content-Length');
if (contentLength) {
this.totalSize = contentLength;
}

let receivedLength = 0;
const chunks = [];
while (true) {
// eslint-disable-next-line no-await-in-loop
const { done, value } = await reader.read();
if (done) {
break;
}
chunks.push(value);
receivedLength += value.length;
this.progressSize = receivedLength;
}

const chunksAll = new Uint8Array(receivedLength);
let position = 0;
chunks.forEach(chunk => {
chunksAll.set(chunk, position);
position += chunk.length;
});

return chunksAll.buffer;
},
},
};
3 changes: 3 additions & 0 deletions src/pages/reader/epub.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
class="fixed inset-0 flex flex-col justify-center items-center"
>
<ProgressIndicator />
<div class="text-like-green">
{{ progressSizeInMB }} / {{ totalSizeInMB }}MB ({{ progressPercent }}%)
</div>
</div>
<div v-else class="flex items-center justify-between">
<div class="grow" />
Expand Down
3 changes: 3 additions & 0 deletions src/pages/reader/pdf.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
class="fixed inset-0 flex flex-col justify-center items-center"
>
<ProgressIndicator />
<div class="text-white">
{{ progressSizeInMB }} / {{ totalSizeInMB }}MB ({{ progressPercent }}%)
</div>
</div>
<iframe
ref="pdfIframe"
Expand Down

0 comments on commit d469a00

Please sign in to comment.