@@ -5,11 +5,56 @@ import {
55 downloadFile ,
66 deleteFile ,
77 store ,
8+ EventName ,
9+ events
810} from "@janhq/core" ;
911import { parseToModel } from "./helper" ;
1012
11- const downloadModel = ( product ) =>
13+ const downloadModel = ( product ) => {
1214 downloadFile ( product . downloadUrl , product . fileName ) ;
15+ checkDownloadProgress ( product . fileName ) ;
16+ }
17+
18+ async function checkDownloadProgress ( fileName : string ) {
19+ if ( typeof window !== "undefined" && typeof ( window as any ) . electronAPI === "undefined" ) {
20+ const intervalId = setInterval ( ( ) => {
21+ fetchDownloadProgress ( fileName , intervalId ) ;
22+ } , 3000 ) ;
23+ }
24+ }
25+
26+ async function fetchDownloadProgress ( fileName : string , intervalId : NodeJS . Timeout ) : Promise < string > {
27+ const response = await fetch ( "/api/v1/downloadProgress" , {
28+ method : 'POST' ,
29+ body : JSON . stringify ( { fileName : fileName } ) ,
30+ headers : { 'Content-Type' : 'application/json' , 'Authorization' : '' }
31+ } ) ;
32+
33+ if ( ! response . ok ) {
34+ events . emit ( EventName . OnDownloadError , null ) ;
35+ clearInterval ( intervalId ) ;
36+ return ;
37+ }
38+ const json = await response . json ( ) ;
39+ if ( isEmptyObject ( json ) ) {
40+ if ( ! fileName && intervalId ) {
41+ clearInterval ( intervalId ) ;
42+ }
43+ return Promise . resolve ( "" ) ;
44+ }
45+ if ( json . success === true ) {
46+ events . emit ( EventName . OnDownloadSuccess , json ) ;
47+ clearInterval ( intervalId ) ;
48+ return Promise . resolve ( "" ) ;
49+ } else {
50+ events . emit ( EventName . OnDownloadUpdate , json ) ;
51+ return Promise . resolve ( json . fileName ) ;
52+ }
53+ }
54+
55+ function isEmptyObject ( ojb : any ) : boolean {
56+ return Object . keys ( ojb ) . length === 0 ;
57+ }
1358
1459const deleteModel = ( path ) => deleteFile ( path ) ;
1560
@@ -87,6 +132,7 @@ function getModelById(modelId: string): Promise<any> {
87132
88133function onStart ( ) {
89134 store . createCollection ( "models" , { } ) ;
135+ fetchDownloadProgress ( null , null ) . then ( ( fileName : string ) => fileName && checkDownloadProgress ( fileName ) ) ;
90136}
91137
92138// Register all the above functions and objects with the relevant extension points
0 commit comments