-
Notifications
You must be signed in to change notification settings - Fork 2
/
getfile.go
71 lines (59 loc) · 1.78 KB
/
getfile.go
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
package main
import (
"context"
"fmt"
"io"
"net/http"
"time"
"github.com/go-telegram/bot"
)
type GetFile struct {
}
// WriteCounter counts the number of bytes written to it. It implements to the io.Writer interface
// and we can pass this into io.TeeReader() which will report progress on each write cycle.
type WriteCounter struct {
Ctx context.Context
GotBytes int64
TotalBytes int64
ProgressPrintInterval time.Duration
LastProgressPrintAt time.Time
}
func (wc *WriteCounter) Write(p []byte) (int, error) {
n := len(p)
wc.GotBytes += int64(n)
if time.Since(wc.LastProgressPrintAt) > wc.ProgressPrintInterval {
progressPercent := int(float64(wc.GotBytes) / float64(wc.TotalBytes) * 100)
fmt.Print(" progress: ", progressPercent, "%\n")
reqQueue.currentEntry.entry.sendReply(wc.Ctx, downloadingStr+" "+getProgressbar(progressPercent, progressBarLength))
wc.LastProgressPrintAt = time.Now()
}
return n, nil
}
func (g *GetFile) GetFile(ctx context.Context, fileID string) (d []byte, err error) {
fmt.Println(" downloading...")
f, err := telegramBot.GetFile(ctx, &bot.GetFileParams{
FileID: fileID,
})
if err != nil {
return nil, err
}
resp, err := http.Get("https://api.telegram.org/file/bot" + params.BotToken + "/" + f.FilePath)
if err != nil {
return nil, err
}
defer resp.Body.Close()
counter := &WriteCounter{
Ctx: ctx,
TotalBytes: int64(f.FileSize),
ProgressPrintInterval: groupChatProgressUpdateInterval,
}
if reqQueue.currentEntry.entry.Message.Chat.ID >= 0 {
counter.ProgressPrintInterval = privateChatProgressUpdateInterval
}
d, err = io.ReadAll(io.TeeReader(resp.Body, counter))
if err != nil {
return nil, err
}
fmt.Println(" downloading done")
return d, nil
}