-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
302 lines (265 loc) · 6.62 KB
/
main.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
package main
import (
"context"
"crypto/sha1"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/patrickmn/go-cache"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"cloud.google.com/go/storage"
"github.com/eknkc/pug"
"google.golang.org/api/iterator"
)
type Category struct {
Name string `json:"name"`
Stub string `json:"stub"`
Galleries []Gallery `json:"galleries"`
}
type Gallery struct {
Name string `json:"name"`
Category string `json:"category"`
Stub string `json:"-"`
Videos []Video `json:"videos"`
}
type Video struct {
Name string `json:"name"`
Category string `json:"-"`
Gallery string `json:"-"`
Url string `json:"url"`
Thumbnail *string `json:"thumbnail,omitempty"`
}
type Index struct {
Categories []Category
}
func getCategories() []Category {
var categories []Category
for _, gallery := range getGalleries() {
category := gallery.Category
// Check if category already exists
exists := false
for i, c := range categories {
if c.Name == category {
categories[i].Galleries = append(categories[i].Galleries, gallery)
exists = true
break
}
}
if !exists {
categories = append(categories, Category{
Name: category,
Stub: category,
Galleries: []Gallery{gallery},
})
}
}
return categories
}
func getGallery(stub string) (Gallery, error) {
// Get gallery
for _, gallery := range getGalleries() {
if gallery.Stub == stub {
return gallery, nil
}
}
return Gallery{}, fmt.Errorf("gallery not found")
}
func getGalleries() []Gallery {
videos := getVideos()
secretKey := os.Getenv("SECRET_KEY")
var galleries []Gallery
for _, video := range videos {
category := video.Category
gallery := video.Gallery
// Check if gallery already exists
exists := false
for i, g := range galleries {
if g.Name == gallery {
galleries[i].Videos = append(galleries[i].Videos, video)
exists = true
break
}
}
if !exists {
// Generate Hash
hash := sha1.New()
hash.Write([]byte(gallery + secretKey))
secretKey := base64.URLEncoding.EncodeToString(hash.Sum(nil))[0:4]
galleries = append(galleries, Gallery{
Name: gallery,
Category: category,
Stub: "/gallery/" + secretKey,
Videos: []Video{video},
})
}
}
return galleries
}
var videoCache = cache.New(5*time.Minute, 10*time.Minute)
func getVideos() []Video {
// Check if Videos are cached
if cachedVideos, found := videoCache.Get("videos"); found {
log.Println("Using Cached Videos")
return cachedVideos.([]Video)
}
log.Println("Getting Videos")
// Get Environment Variables
bucketName := os.Getenv("BUCKET_NAME")
if bucketName == "" {
panic("BUCKET_NAME not set")
}
// Initialize Cloud Storage
storageClient, err := storage.NewClient(context.Background())
if err != nil {
log.Fatal(err)
}
bucket := storageClient.Bucket(bucketName)
files := bucket.Objects(context.Background(), nil)
videosMap := make(map[string]Video)
// Allowed Extensions
videoExtensions := []string{".mp4", ".m4v", ".webm", ".mov", ".avi"}
imageExtensions := []string{".jpg", ".jpeg", ".png"}
extensionRegex, _ := regexp.Compile(`\.[a-zA-Z0-9]+$`)
// Iterate through videos
for {
file, err := files.Next()
if errors.Is(err, iterator.Done) {
break
}
if err != nil {
log.Fatal(err)
}
parts := strings.Split(file.Name, "/")
if len(parts) == 3 && parts[2] != "" {
category := parts[0]
gallery := parts[1]
filename := parts[2]
// Create Signed 24 Hour URL
signedUrl, err := bucket.SignedURL(file.Name, &storage.SignedURLOptions{
Expires: time.Now().Add(24 * time.Hour),
Method: "GET",
})
if err != nil {
log.Fatal(err)
}
// Remove extension from filename
fileBase := extensionRegex.ReplaceAll([]byte(filename), []byte(""))
// If Video doesn't exist
if _, ok := videosMap[string(fileBase)]; !ok {
videosMap[string(fileBase)] = Video{
Name: string(fileBase),
Category: category,
Gallery: gallery,
}
}
// Check if video already exists
if video, ok := videosMap[string(fileBase)]; ok {
for _, extension := range videoExtensions {
if strings.HasSuffix(filename, extension) {
videosMap[string(fileBase)] = Video{
Name: video.Name,
Category: video.Category,
Gallery: video.Gallery,
Url: signedUrl,
Thumbnail: video.Thumbnail,
}
}
}
for _, extension := range imageExtensions {
if strings.HasSuffix(filename, extension) {
videosMap[string(fileBase)] = Video{
Name: video.Name,
Category: video.Category,
Gallery: video.Gallery,
Url: video.Url,
Thumbnail: &signedUrl,
}
}
}
}
}
}
// Convert Map to Array
var videos []Video
for _, video := range videosMap {
videos = append(videos, video)
}
// Cache Videos
videoCache.Set("videos", videos, cache.DefaultExpiration)
return videos
}
func galleryHandler(w http.ResponseWriter, _ *http.Request) {
log.Println("Generating Index")
template, err := pug.CompileFile("./views/index.pug", pug.Options{})
if err != nil {
panic(err)
}
err = template.Execute(w, Index{
Categories: getCategories(),
})
if err != nil {
panic(err)
}
}
func feedHandler(w http.ResponseWriter, _ *http.Request) {
log.Println("Generating Feed")
galleries := getGalleries()
// Convert to JSON
jsonString, err := json.Marshal(galleries)
if err != nil {
panic(err)
}
// Write JSON
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(jsonString)
if err != nil {
return
}
}
func pageHandler(w http.ResponseWriter, r *http.Request) {
// Get path
path := r.URL.String()
gallery, err := getGallery(path)
if err != nil {
log.Println("Gallery not found: " + path)
http.NotFound(w, r)
return
}
log.Println("Generating Gallery Page: " + path)
template, err := pug.CompileFile("./views/gallery.pug", pug.Options{})
if err != nil {
panic(err)
}
err = template.Execute(w, gallery)
if err != nil {
panic(err)
}
}
func main() {
secretKey := os.Getenv("SECRET_KEY")
if secretKey == "" {
panic("SECRET_KEY not set")
}
log.Println("Starting with Key: " + secretKey)
// Service
fileServer := http.FileServer(http.Dir("./public"))
http.Handle("/", fileServer)
http.HandleFunc("/gallery/", pageHandler)
http.HandleFunc("/"+secretKey+"/index", galleryHandler)
http.HandleFunc("/"+secretKey+"/feed", feedHandler)
// Read Environment Variables
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
fmt.Printf("Starting server at port " + port + "\n")
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}