Debian Codegraph @

file.go

raw
1 package b2
2
3 import (
4 "encoding/json"
5 "errors"
6 "time"
7 )
8
9 // DeleteFile deletes a file version.
10 func (c *Client) DeleteFile(id, name string) error {
11 res, err := c.doRequest("b2_delete_file_version", map[string]interface{}{
12 "fileId": id, "fileName": name,
13 })
14 if err != nil {
15 return err
16 }
17 drainAndClose(res.Body)
18 return nil
19 }
20
21 // A FileInfo is the metadata associated with a specific file version.
22 type FileInfo struct {
23 ID string
24 Name string
25
26 // Had to remove BucketID since it is not returned by b2_download_file_by_*
27 // BucketID string
28
29 ContentSHA1 string // hex encoded
30 ContentLength int
31 ContentType string
32
33 CustomMetadata map[string]interface{}
34 UploadTimestamp time.Time
35
36 // If Action is "hide", this ID does not refer to a file version
37 // but to an hiding action. Otherwise "upload".
38 Action string
39 }
40
41 type fileInfoObj struct {
42 AccountID string `json:"accountId"`
43 BucketID string `json:"bucketId"`
44 ContentLength int `json:"contentLength"`
45 ContentSHA1 string `json:"contentSha1"`
46 ContentType string `json:"contentType"`
47 FileID string `json:"fileId"`
48 FileInfo map[string]interface{} `json:"fileInfo"`
49 FileName string `json:"fileName"`
50 UploadTimestamp int64 `json:"uploadTimestamp"`
51 Action string `json:"action"`
52 }
53
54 func (fi *fileInfoObj) makeFileInfo() *FileInfo {
55 return &FileInfo{
56 ID: fi.FileID,
57 Name: fi.FileName,
58 ContentLength: fi.ContentLength,
59 ContentSHA1: fi.ContentSHA1,
60 ContentType: fi.ContentType,
61 CustomMetadata: fi.FileInfo,
62 Action: fi.Action,
63 UploadTimestamp: time.Unix(fi.UploadTimestamp/1e3, fi.UploadTimestamp%1e3*1e6),
64 }
65 }
66
67 // GetFileInfoByID obtains a FileInfo for a given ID.
68 //
69 // The ID can refer to any file version or "hide" action in any bucket.
70 func (c *Client) GetFileInfoByID(id string) (*FileInfo, error) {
71 res, err := c.doRequest("b2_get_file_info", map[string]interface{}{
72 "fileId": id,
73 })
74 if err != nil {
75 return nil, err
76 }
77 defer drainAndClose(res.Body)
78 var fi *fileInfoObj
79 if err := json.NewDecoder(res.Body).Decode(&fi); err != nil {
80 return nil, err
81 }
82 return fi.makeFileInfo(), nil
83 }
84
85 var FileNotFoundError = errors.New("no file with the given name in the bucket")
86
87 // GetFileInfoByName obtains a FileInfo for a given name.
88 //
89 // If the file doesn't exist, FileNotFoundError is returned.
90 // If multiple versions of the file exist, only the latest is returned.
91 func (b *Bucket) GetFileInfoByName(name string) (*FileInfo, error) {
92 l := b.ListFiles(name)
93 l.SetPageCount(1)
94 if l.Next() {
95 if l.FileInfo().Name == name {
96 return l.FileInfo(), nil
97 }
98 }
99 if err := l.Err(); err != nil {
100 return nil, l.Err()
101 }
102 return nil, FileNotFoundError
103 }
104
105 // A Listing is the result of (*Bucket).ListFiles[Versions].
106 // It works like sql.Rows: use Next to advance and then FileInfo.
107 // Check Err once Next returns false.
108 //
109 // l := b.ListFiles("")
110 // for l.Next() {
111 // fi := l.FileInfo()
112 // ...
113 // }
114 // if err := l.Err(); err != nil {
115 // ...
116 // }
117 //
118 // A Listing handles pagination transparently, so it iterates until
119 // the last file in the bucket. To limit the number of results, do this.
120 //
121 // for i := 0; i < limit && l.Next(); i++ {
122 //
123 type Listing struct {
124 b *Bucket
125 versions bool
126 nextPageCount int
127 nextName, nextID *string
128 objects []*FileInfo // in reverse order
129 err error
130 }
131
132 // SetPageCount controls the number of results to be fetched with each API
133 // call. The maximum n is 1000, higher values are automatically limited to 1000.
134 //
135 // SetPageCount does not limit the number of results returned by a Listing.
136 func (l *Listing) SetPageCount(n int) {
137 if n > 1000 {
138 n = 1000
139 }
140 l.nextPageCount = n
141 }
142
143 // Next calls the list API if needed and prepares the FileInfo results.
144 // It returns true on success, or false if there is no next result
145 // or an error happened while preparing it. Err should be
146 // consulted to distinguish between the two cases.
147 func (l *Listing) Next() bool {
148 if l.err != nil {
149 return false
150 }
151 if len(l.objects) > 0 {
152 l.objects = l.objects[:len(l.objects)-1]
153 }
154 if len(l.objects) > 0 {
155 return true
156 }
157 if l.nextName == nil {
158 return false // end of iteration
159 }
160
161 data := map[string]interface{}{
162 "bucketId": l.b.ID,
163 "startFileName": *l.nextName,
164 "maxFileCount": l.nextPageCount,
165 }
166 endpoint := "b2_list_file_names"
167 if l.versions {
168 endpoint = "b2_list_file_versions"
169 }
170 if l.nextID != nil && *l.nextID != "" {
171 data["startFileId"] = *l.nextID
172 }
173 r, err := l.b.c.doRequest(endpoint, data)
174 if err != nil {
175 l.err = err
176 return false
177 }
178 defer drainAndClose(r.Body)
179
180 var x struct {
181 Files []fileInfoObj
182 NextFileName *string
183 NextFileID *string
184 }
185 if l.err = json.NewDecoder(r.Body).Decode(&x); l.err != nil {
186 return false
187 }
188
189 l.objects = make([]*FileInfo, len(x.Files))
190 for i, f := range x.Files {
191 l.objects[len(l.objects)-1-i] = f.makeFileInfo()
192 }
193 l.nextName, l.nextID = x.NextFileName, x.NextFileID
194 return len(l.objects) > 0
195 }
196
197 // FileInfo returns the FileInfo object made available by Next.
198 //
199 // FileInfo must only be called after a call to Next returned true.
200 func (l *Listing) FileInfo() *FileInfo {
201 return l.objects[len(l.objects)-1]
202 }
203
204 // Err returns the error, if any, that was encountered while listing.
205 func (l *Listing) Err() error {
206 return l.err
207 }
208
209 // ListFiles returns a Listing of files in the Bucket, alphabetically sorted,
210 // starting from the file named fromName (included if it exists). To start from
211 // the first file in the bucket, set fileName to "".
212 //
213 // ListFiles only returns the most recent version of each (non-hidden) file.
214 // If you want to fetch all versions, use ListFilesVersions.
215 func (b *Bucket) ListFiles(fromName string) *Listing {
216 return &Listing{
217 b: b,
218 nextName: &fromName,
219 }
220 }
221
222 // ListFilesVersions is like ListFiles, but returns all file versions,
223 // alphabetically sorted first, and by reverse of date/time uploaded then.
224 //
225 // If fromID is specified, the name-and-id pair is the starting point.
226 func (b *Bucket) ListFilesVersions(fromName, fromID string) *Listing {
227 if fromName == "" && fromID != "" {
228 return &Listing{
229 err: errors.New("can't set fromID if fromName is not set"),
230 }
231 }
232 return &Listing{
233 b: b,
234 versions: true,
235 nextName: &fromName,
236 nextID: &fromID,
237 }
238 }