-
Notifications
You must be signed in to change notification settings - Fork 1
/
playlist_zip.go
72 lines (61 loc) · 1.51 KB
/
playlist_zip.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
package main
import (
"archive/zip"
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
)
// This won't be very robust
// Needs an index.json, referencing the rest of the files
func readZipFile(zf *zip.File) ([]byte, error) {
f, err := zf.Open()
if err != nil {
return nil, err
}
defer f.Close()
return io.ReadAll(f)
}
func NewPlaylistFromZip(zipFilename string) (*Playlist, error) {
data, err := os.ReadFile(zipFilename)
if err != nil {
return nil, err
}
zipReader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, err
}
// Read all the files from zip archive
files := make(map[string][]byte)
for _, zipFile := range zipReader.File {
files[zipFile.Name], err = readZipFile(zipFile)
if err != nil {
log.Println(err)
continue
}
}
var playlist *Playlist
indexData, ok := files[`index.json`]
if !ok {
fmt.Println("No index.json found, so adding zipfile contents without metadata")
playlist = NewPlaylist()
for location, codeData := range files {
playlist.items = append(playlist.items, PlaylistItem{location: location, code: codeData})
}
} else {
playlist, err = NewPlaylistFromJSON(indexData)
if err != nil {
return nil, err
}
for key, item := range playlist.items {
codeData, ok := files[item.location]
if !ok {
return nil, errors.New(fmt.Sprintf("File not found (%s)", item.location))
}
playlist.items[key].code = codeData
}
}
return playlist, nil
}