-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmedia_store.go
376 lines (311 loc) · 8.74 KB
/
media_store.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package main
import (
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"unicode"
"github.com/google/uuid"
"golang.org/x/text/transform"
"golang.org/x/text/unicode/norm"
"gopkg.in/yaml.v2"
)
type MediaStore struct {
StoreLocation string
}
type Album struct {
ID string `yaml:"-"` // Not part of the YAML struct
Title string `yaml:"title"`
Date time.Time `yaml:"date"`
Media []Media `yaml:"-"` // Not part of the YAML struct
CoverMedia Media `yaml:"cover,omitempty"`
}
type Media struct {
Type string `yaml:"type"`
ID string `yaml:"id"`
Files []string `yaml:"-"` // Not part of the YAML struct
Caption string `yaml:"caption"`
Date time.Time `yaml:"date"`
}
// A media without ID will not be serialized in YAML
func (m *Media) IsZero() bool {
return m.ID == ""
}
func InitMediaStore(storeLocation string) (*MediaStore, error) {
err := os.MkdirAll(filepath.Join(storeLocation, ".current"), os.ModePerm)
if err != nil {
return nil, err
}
return &MediaStore{StoreLocation: storeLocation}, nil
}
func (store *MediaStore) GetUniqueID() string {
return uuid.New().String()
}
func (store *MediaStore) AddFile(fileName string) (*os.File, error) {
filename := filepath.Join(store.StoreLocation, ".current", fileName)
return os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)
}
func (store *MediaStore) CommitPhoto(id string, timestamp time.Time, caption string) error {
return store.commitMedia(id, timestamp, caption, "photo")
}
func (store *MediaStore) CommitVideo(id string, timestamp time.Time, caption string) error {
return store.commitMedia(id, timestamp, caption, "video")
}
func (store *MediaStore) commitMedia(id string, timestamp time.Time, caption string, mediaType string) error {
entry := [1]Media{{
Type: mediaType,
Date: timestamp,
Caption: caption,
ID: id,
}}
yamlData, err := yaml.Marshal(entry)
if err != nil {
return err
}
return appendToFile(filepath.Join(store.StoreLocation, ".current", "chat.yaml"), yamlData)
}
func appendToFile(filename string, data []byte) error {
f, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer f.Close()
if _, err = f.Write(data); err != nil {
return err
}
return nil
}
type AlbumList []Album
func (list AlbumList) Len() int {
return len(list)
}
func (list AlbumList) Less(i, j int) bool {
return list[i].Date.Before(list[j].Date)
}
func (list AlbumList) Swap(i, j int) {
list[i], list[j] = list[j], list[i]
}
func (store *MediaStore) ListAlbums() (AlbumList, error) {
files, err := ioutil.ReadDir(store.StoreLocation)
if err != nil {
return nil, err
}
albums := make([]Album, len(files))
for i, file := range files {
album, err := store.GetAlbum(file.Name(), true)
if err != nil {
log.Printf("ListAlbum: Cannot extract album info for '%s'", file.Name())
continue
}
albums[i] = *album
}
return albums, nil
}
func (store *MediaStore) OpenFile(albumName string, filename string) (*os.File, time.Time, error) {
if albumName == "" {
albumName = ".current"
}
path := filepath.Join(store.StoreLocation, albumName, filename)
stat, err := os.Stat(path)
if err != nil {
return nil, time.Time{}, err
}
fd, err := os.OpenFile(path, os.O_RDONLY, 0600)
if err != nil {
return nil, time.Time{}, err
}
return fd, stat.ModTime(), nil
}
func (store *MediaStore) GetAlbum(name string, metadataOnly bool) (*Album, error) {
var album Album
var filename string
if name == "" || name == ".current" {
filename = ".current"
} else {
filename = filepath.Base(name)
album.ID = filename
}
if !fileExists(filepath.Join(store.StoreLocation, filename)) {
return nil, fmt.Errorf("Unknown album '%s'", name)
}
err := store.fillAlbumMetadata(filename, &album)
if err != nil {
return nil, err
}
// If there is a cover media defined, find the corresponding files
if !album.CoverMedia.IsZero() {
paths, err := filepath.Glob(filepath.Join(store.StoreLocation, filename, album.CoverMedia.ID+".*"))
if err == nil { // Best effort
album.CoverMedia.Files = make([]string, len(paths))
for j, path := range paths {
album.CoverMedia.Files[j] = filepath.Base(path)
}
}
}
if metadataOnly {
return &album, nil
}
err = store.fillAlbumContent(filename, &album)
if err != nil {
return nil, err
}
if album.CoverMedia.IsZero() {
album.setDefaultCover()
}
return &album, nil
}
func (store *MediaStore) fillAlbumContent(filename string, album *Album) error {
yamlData, err := ioutil.ReadFile(filepath.Join(store.StoreLocation, filename, "chat.yaml"))
// if chat.yaml is not there, it may be because there is no media yet
// It is not an error.
if err != nil && !os.IsNotExist(err) {
return nil
}
err = yaml.UnmarshalStrict(yamlData, &album.Media)
if err != nil {
return err
}
// List all files in the album directory, looking for filenames starting by a UUID
// and build an association between the UUID and the filenames starting with this UUID.
files, err := ioutil.ReadDir(filepath.Join(store.StoreLocation, filename))
if err != nil {
return err
}
filesById := make(map[string][]string)
for _, file := range files {
n := file.Name()
if len(n) < 36 {
// Definitively not a UUID...
continue
}
filesById[n[0:36]] = append(filesById[n[0:36]], n)
}
// Find media files matching each id
for i := range album.Media {
if files, ok := filesById[album.Media[i].ID]; ok {
album.Media[i].Files = files
} else {
album.Media[i].Files = make([]string, 0)
}
}
return nil
}
func (store *MediaStore) fillAlbumMetadata(filename string, album *Album) error {
yamlData, err := ioutil.ReadFile(filepath.Join(store.StoreLocation, filename, "meta.yaml"))
// if meta.yaml is not there, it could be because the album has not yet
// been initialized. It is not an error.
if err != nil && !os.IsNotExist(err) {
return err
}
return yaml.UnmarshalStrict(yamlData, album)
}
func (store *MediaStore) GetMedia(albumName string, mediaId string) (*Media, error) {
album, err := store.GetAlbum(albumName, false)
if err != nil {
return nil, err
}
for _, media := range album.Media {
if media.ID == mediaId {
return &media, nil
}
}
return nil, nil
}
func (store *MediaStore) GetCurrentAlbum() (*Album, error) {
return store.GetAlbum("", true)
}
func (album *Album) setDefaultCover() {
if len(album.Media) > 0 {
var cover Media
for _, media := range album.Media {
if media.Type == "photo" { // use the first photo of the album as cover media
cover = media
break
}
if cover.IsZero() { // otherwise, fallback to the first media
cover = media
}
}
album.CoverMedia = cover
}
}
func (store *MediaStore) CloseAlbum() error {
album, err := store.GetAlbum("", false)
if err != nil {
return err
}
if album.CoverMedia.ID != "" {
// Write back the metadata
yamlData, err := yaml.Marshal(album)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(store.StoreLocation, ".current", "meta.yaml"), yamlData, 0644)
if err != nil {
return err
}
}
folderName := album.Date.Format("2006-01-02") + "-" + sanitizeAlbumName(album.Title)
err = os.Rename(filepath.Join(store.StoreLocation, ".current"), filepath.Join(store.StoreLocation, folderName))
if err != nil {
return err
}
err = os.MkdirAll(filepath.Join(store.StoreLocation, ".current"), os.ModePerm)
if err != nil {
return err
}
return nil
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return err == nil
}
func (store *MediaStore) NewAlbum(title string) error {
if fileExists(filepath.Join(store.StoreLocation, ".current")) {
if fileExists(filepath.Join(store.StoreLocation, ".current", "meta.yaml")) {
err := store.CloseAlbum()
if err != nil {
return err
}
}
}
err := os.MkdirAll(filepath.Join(store.StoreLocation, ".current"), os.ModePerm)
if err != nil {
return err
}
metadata := Album{
Title: title,
Date: time.Now(),
}
yamlData, err := yaml.Marshal(metadata)
if err != nil {
return err
}
err = ioutil.WriteFile(filepath.Join(store.StoreLocation, ".current", "meta.yaml"), yamlData, 0644)
if err != nil {
return err
}
return nil
}
func sanitizeAlbumName(albumName string) string {
albumName = strings.ToLower(albumName)
t := transform.Chain(norm.NFD, transform.RemoveFunc(func(r rune) bool {
return unicode.Is(unicode.Mn, r)
}), norm.NFC)
albumName, _, _ = transform.String(t, albumName)
reg, err := regexp.Compile("\\s+")
if err != nil {
panic(fmt.Errorf("Cannot compile regex: %s", err))
}
albumName = reg.ReplaceAllString(albumName, "-")
reg, err = regexp.Compile("[^-a-zA-Z0-9_]+")
if err != nil {
panic(fmt.Errorf("Cannot compile regex: %s", err))
}
albumName = reg.ReplaceAllString(albumName, "")
return albumName
}