1 ! Copyright (C) 2024 Doug Coleman.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors calendar checksums combinators.short-circuit
4 http.client io io.backend io.directories io.encodings.binary
5 io.files io.files.info io.files.unique io.pathnames kernel math
6 math.order math.parser present sequences shuffle splitting ;
9 : file-too-old-or-not-exists? ( file duration -- ? )
10 [ ?file-info [ created>> ] ?call ]
12 over [ before? ] [ 2drop t ] if ;
14 : delete-when-old ( file duration -- deleted? )
15 dupd file-too-old-or-not-exists? [ ?delete-file t ] [ drop f ] if ;
17 : file-matches-checksum? ( file checksum-type bytes -- ? )
18 [ checksum-file ] dip = ;
20 : delete-when-checksum-mismatches ( file checksum-type bytes -- deleted? )
21 dupdd file-matches-checksum? [ drop f ] [ ?delete-file t ] if ;
23 : file-size= ( path n -- ? ) [ ?file-info [ size>> ] ?call ] dip = ;
25 : file-zero-size? ( path -- ? ) 0 file-size= ;
27 : delete-when-zero-size ( path -- deleted? )
28 dup file-zero-size? [ ?delete-file t ] [ drop f ] if ;
30 : delete-when-file-size-mismatches? ( file size -- deleted? )
31 dupd file-size= [ drop f ] [ ?delete-file t ] if ;
33 : download-name ( url -- name )
34 present file-name "?" split1 drop "/" ?tail drop ;
38 : increment-file-extension ( path -- path' )
43 [ 1 + number>string append ]
47 : ?parenthesis-number ( str -- n/str ? )
48 dup { [ "(" head? ] [ ")" tail? ] } 1&&
49 [ rest but-last ?string>number ] [ f ] if ;
51 : increment-file-name ( path -- path' )
53 file-stem " " split1-last
55 [ 1 + number>string "(" ")" surround " " glue ]
56 [ "(1)" append " " glue ] if
61 : find-next-incremented-name ( path -- path' )
63 increment-file-name find-next-incremented-name
66 : next-download-name ( url -- name )
67 download-name find-next-incremented-name ;
69 : http-write-request ( url -- )
70 <get-request> [ write ] with-http-request drop ;
72 : download-temporary-name ( url -- prefix suffix )
73 [ "temp." ".temp" ] dip download-name prepend ;
75 : download-file-to ( url file -- path )
77 [ download-temporary-name binary ] keep
78 '[ _ http-write-request ] with-unique-file-writer
79 ] dip [ move-file ] keep ;
83 : download-to ( url file -- path )
84 dup file-exists? [ nip ] [ download-file-to ] if ;
86 : download-outdated-to ( url file duration -- path )
87 2dup delete-when-old [ drop download-to ] [ drop nip ] if ;
89 : download ( url -- path )
90 dup download-name download-to ;