-
Notifications
You must be signed in to change notification settings - Fork 0
/
media.go
103 lines (95 loc) · 2.29 KB
/
media.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
)
// getLocalMedia reads media from local directory
func getLocalMedia() (media []Media) {
files, err := ioutil.ReadDir("./media")
if err != nil {
log.Info("Error reading directory", err)
}
for _, file := range files {
if strings.Contains(file.Name(), ".jpg") {
m := Media{}
m.LocalFile = file.Name()
media = append(media, m)
}
}
return media
}
// getRemoteMedia reads media from json file
func getRemoteMedia() (media []Media) {
// check if file exists, return empty
// likely scenario would be first run
if _, err := os.Stat("media.json"); os.IsNotExist(err) {
if !setup { // dont alert about missing file when known init
log.Debug("media.json does not exist, first run?")
}
return media
}
file, err := ioutil.ReadFile("media.json")
if err != nil {
log.Warn("Error reading media.json, permissions?", err)
} else {
if err := json.Unmarshal(file, &media); err != nil {
log.Warn("Error parsing JSON from media.json", err)
}
}
return media
}
func compareMedia(local, remote []Media) (media []Media) {
for _, m := range local {
exists := false
for _, r := range remote {
if m.LocalFile == r.LocalFile {
exists = true
log.Debug("Skipping ", m.LocalFile)
}
}
if !exists {
media = append(media, m)
}
}
return media
}
func uploadMediaItems(media []Media) (uploadedMedia []Media) {
for _, m := range media {
if confirmPrompt(fmt.Sprintf("Upload %s, Continue (y/N)? ", m.LocalFile)) {
upm, err := uploadMedia(m)
if err == nil {
upm.LocalFile = m.LocalFile
log.Info(fmt.Sprintf("Uploaded: %s %s", m.LocalFile, upm.URL))
uploadedMedia = append(uploadedMedia, upm)
} else {
log.Warn("Upload Error", err)
}
}
}
return uploadedMedia
}
// writeRemoteMedia
func writeRemoteMedia(media []Media) {
if len(media) == 0 {
log.Info("No new media to upload.")
return
}
// append new post json
existingMedia := getRemoteMedia()
existingMedia = append(existingMedia, media...)
// write file
json, err := json.Marshal(existingMedia)
if err != nil {
log.Warn("Encoding Error", err)
} else {
err = ioutil.WriteFile("media.json", json, 0644)
if err != nil {
log.Warn("Error writing media.json", err)
} else {
log.Warn("media.json written")
}
}
}