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.directories io.encodings.binary io.files
5 io.files.info io.files.unique io.pathnames kernel math
6 math.order math.parser present sequences shuffle splitting ;
10 : file-too-old-or-not-exists? ( path duration -- ? )
11 [ ?file-info [ created>> ] ?call ]
13 over [ before? ] [ 2drop t ] if ;
15 : delete-when-old ( path duration -- deleted? )
16 dupd file-too-old-or-not-exists? [ ?delete-file t ] [ drop f ] if ;
18 : file-matches-checksum? ( path checksum-type bytes -- ? )
19 [ checksum-file ] dip = ;
21 : delete-when-checksum-mismatches ( path checksum-type bytes -- deleted? )
22 dupdd file-matches-checksum? [ drop f ] [ ?delete-file t ] if ;
24 : file-size= ( path n -- ? ) [ ?file-info [ size>> ] ?call ] dip = ;
26 : file-zero-size? ( path -- ? ) 0 file-size= ;
28 : delete-when-zero-size ( path -- deleted-or-not-exists? )
30 dup file-zero-size? [ ?delete-file t ] [ drop f ] if
35 : delete-when-file-size-mismatches? ( path size -- deleted? )
36 dupd file-size= [ drop f ] [ ?delete-file t ] if ;
38 : download-name ( url -- name )
39 present file-name "?" split1 drop "/" ?tail drop ;
43 : increment-file-extension ( path -- path' )
48 [ 1 + number>string append ]
52 : ?parenthesis-number ( str -- n/f )
57 [ rest but-last string>number ]
59 ] [ drop f ] ?unless ;
61 : increment-file-name ( path -- path' )
63 file-stem " " split1-last
64 [ ?parenthesis-number ]
65 [ 1 + number>string "(" ")" surround " " glue ]
66 [ "(1)" append " " glue ] ?if
71 : find-next-incremented-name ( path -- path' )
73 increment-file-name find-next-incremented-name
76 : next-download-name ( url -- name )
77 download-name find-next-incremented-name ;
79 : http-write-request ( url -- )
80 <get-request> [ write ] with-http-request drop ;
82 : download-temporary-name ( url -- prefix suffix )
83 [ "temp." ".temp" ] dip download-name prepend ;
87 : download-to ( url path -- path )
89 [ download-temporary-name binary ] keep
90 '[ _ http-write-request ] with-unique-file-writer
91 ] dip [ move-file ] keep ;
93 : download-once-to ( url path -- path )
94 dup file-exists? [ nip ] [ download-to ] if ;
96 : download-once ( url -- path )
97 dup download-name download-once-to ;
99 : download-outdated-to ( url path duration -- path )
100 2dup delete-when-old [ drop download-to ] [ drop nip ] if ;
102 : download ( url -- path )
103 dup download-name download-to ;