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-or-not-exists? )
29 dup file-zero-size? [ ?delete-file t ] [ drop f ] if
34 : delete-when-file-size-mismatches? ( file size -- deleted? )
35 dupd file-size= [ drop f ] [ ?delete-file t ] if ;
37 : download-name ( url -- name )
38 present file-name "?" split1 drop "/" ?tail drop ;
42 : increment-file-extension ( path -- path' )
47 [ 1 + number>string append ]
51 : ?parenthesis-number ( str -- n/str ? )
52 dup { [ "(" head? ] [ ")" tail? ] } 1&&
53 [ rest but-last ?string>number ] [ f ] if ;
55 : increment-file-name ( path -- path' )
57 file-stem " " split1-last
59 [ 1 + number>string "(" ")" surround " " glue ]
60 [ "(1)" append " " glue ] if
65 : find-next-incremented-name ( path -- path' )
67 increment-file-name find-next-incremented-name
70 : next-download-name ( url -- name )
71 download-name find-next-incremented-name ;
73 : http-write-request ( url -- )
74 <get-request> [ write ] with-http-request drop ;
76 : download-temporary-name ( url -- prefix suffix )
77 [ "temp." ".temp" ] dip download-name prepend ;
79 : download-file-to ( url file -- path )
81 [ download-temporary-name binary ] keep
82 '[ _ http-write-request ] with-unique-file-writer
83 ] dip [ move-file ] keep ;
87 : download-to ( url file -- path )
88 dup file-exists? [ nip ] [ download-file-to ] if ;
90 : download-outdated-to ( url file duration -- path )
91 2dup delete-when-old [ drop download-to ] [ drop nip ] if ;
93 : download ( url -- path )
94 dup download-name download-to ;