-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathosdb.go
97 lines (84 loc) · 1.86 KB
/
osdb.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*
Package osdb is an API client for opensubtitles.org
This is a client for the OSDb protocol. Currently the package only allows movie
identification, subtitles search, and download.
*/
package osdb
import (
"bytes"
"encoding/binary"
"fmt"
"os"
"github.com/kolo/xmlrpc"
)
const (
// ChunkSize = 64k
ChunkSize = 65536
)
// NewClient allocates a new OSDB client.
func NewClient() (*Client, error) {
osdbServer := os.Getenv("OSDB_SERVER")
if osdbServer == "" {
osdbServer = DefaultOSDBServer
}
rpc, err := xmlrpc.NewClient(osdbServer, nil)
if err != nil {
return nil, err
}
c := &Client{
UserAgent: DefaultUserAgent,
Client: rpc, // xmlrpc.Client
}
return c, nil
}
// HashFile generates an OSDB hash for an *os.File.
func HashFile(file *os.File) (hash uint64, err error) {
fi, err := file.Stat()
if err != nil {
return
}
if fi.Size() < ChunkSize {
return 0, fmt.Errorf("File is too small")
}
// Read head and tail blocks.
buf := make([]byte, ChunkSize*2)
err = readChunk(file, 0, buf[:ChunkSize])
if err != nil {
return
}
err = readChunk(file, fi.Size()-ChunkSize, buf[ChunkSize:])
if err != nil {
return
}
// Convert to uint64, and sum.
var nums [(ChunkSize * 2) / 8]uint64
reader := bytes.NewReader(buf)
err = binary.Read(reader, binary.LittleEndian, &nums)
if err != nil {
return 0, err
}
for _, num := range nums {
hash += num
}
return hash + uint64(fi.Size()), nil
}
// Hash generates an OSDB hash for a file.
func Hash(path string) (uint64, error) {
file, err := os.Open(path)
if err != nil {
return 0, err
}
defer file.Close()
return HashFile(file)
}
// Read a chunk of a file at `offset` so as to fill `buf`.
func readChunk(file *os.File, offset int64, buf []byte) (err error) {
n, err := file.ReadAt(buf, offset)
if err != nil {
return
}
if n != ChunkSize {
return fmt.Errorf("Invalid read %v", n)
}
return
}