-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathsession.go
More file actions
79 lines (70 loc) · 1.67 KB
/
Copy pathsession.go
File metadata and controls
79 lines (70 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package getparty
import (
"cmp"
"encoding/json"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/vbauerster/mpb/v8/decor"
)
// Session represents download session state
type Session struct {
URL string
OutputName string
AcceptRanges string
ContentType string
StatusCode int
ContentLength int64
Elapsed time.Duration
Headers map[string]string
Parts []*Part
Single bool
restored bool
location string
dir string
}
func (s *Session) loadState(name string) error {
f, err := os.Open(name)
if err != nil {
return err
}
return cmp.Or(json.NewDecoder(f).Decode(s), f.Close())
}
func (s *Session) dumpState(name string) error {
f, err := os.Create(name)
if err != nil {
return err
}
return cmp.Or(json.NewEncoder(f).Encode(s), f.Close())
}
func (s Session) isResumable() bool {
return strings.EqualFold(s.AcceptRanges, "bytes") && s.ContentLength >= 0
}
func (s Session) totalWritten() int64 {
var total int64
for _, p := range s.Parts {
total += p.Written
}
return total
}
func (s Session) summary(loggers [lEVELS]*log.Logger) {
format := fmt.Sprintf("Length: %%s [%s]", s.ContentType)
switch {
case s.isResumable():
summary := fmt.Sprintf("%d (%.1f)", s.ContentLength, decor.SizeB1024(s.ContentLength))
loggers[INFO].Printf(format, summary)
if tw := s.totalWritten(); tw != 0 {
remaining := s.ContentLength - tw
loggers[INFO].Printf("Remaining: %d (%.1f)", remaining, decor.SizeB1024(remaining))
}
case s.ContentLength < 0:
loggers[INFO].Printf(format, "unknown")
fallthrough
default:
message := "Session is not resumable"
loggers[WARN].Println(message)
loggers[DBUG].Println(message)
}
}