-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpixie.go
362 lines (334 loc) · 10.9 KB
/
pixie.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
package main
import (
"./backend"
"./cp"
"crypto/md5"
"database/sql"
"encoding/json"
"errors"
"fmt"
"github.com/Dieterbe/gothum/workers"
_ "github.com/mattn/go-sqlite3"
"github.com/stvp/go-toml-config"
"io"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"os/exec"
"os/user"
"path"
"path/filepath"
"strconv"
"strings"
)
var ptr_thumbnail_dir = config.String("thumbnail_dir", "")
var ptr_exports_dir = config.String("exports_dir", "") // only used by export script, but go-toml-config insists on declaring all vars
var ptr_tmsu_file = config.String("tmsu_file", "")
var ptr_editor = config.String("editor", "gimp")
var ptr_addr = config.String("addr", "localhost:8080")
var thumbnail_dir, tmsu_file, editor, addr string
type Photo struct {
Id int `json:"id"`
Dir string `json:"dir"`
Name string `json:"name"`
Ext string `json:"-"`
Tags []string `json:"tags"`
Edits map[string]*Photo `json:"edits"`
}
func Expand(in string) (out string) {
if strings.HasPrefix(in, "~/") {
usr, _ := user.Current()
home_dir := usr.HomeDir
out := strings.Replace(in, "~/", home_dir+"/", 1)
return out
}
return in
}
func (p *Photo) String() string {
return fmt.Sprintf("Photo {Id: %d, Dir: '%s', Name: '%s', Ext: '%s', Tags: '%s'}", p.Id, p.Dir, p.Name, p.Ext, p.Tags)
}
func NewPhoto(id int, dir string, name string, ext string, filetags map[string]string, edits_dir string, edits_filetags map[string]string) (p *Photo, err error) {
// get our tags
var tags_slice []string
tags_str, ok := filetags[name]
if ok {
tags_slice = strings.Split(tags_str, ",")
} else {
tags_slice = make([]string, 0, 0)
}
p = &Photo{id, dir, name, ext, tags_slice, nil}
if edits_dir != "" {
err = p.LoadEdits(edits_dir, edits_filetags)
if err != nil {
return nil, errors.New(fmt.Sprintf("WARNING: failed to load edits: %s\n", err))
}
}
return p, nil
}
func (p *Photo) LoadEdits(edits_dir string, edits_filetags map[string]string) error {
// /bleh/originals/foo/bar.jpg ->
// /bleh/edits/foo/bar.jpg (standard edit)
// /bleh/edits/foo/bar-speficier.jpg (specified edit)
if edits_dir == "" {
return nil
}
basename := p.Name[:len(p.Name)-len(p.Ext)]
edit_base := path.Join(edits_dir, basename)
glob_pattern := fmt.Sprintf("%s*%s", edit_base, p.Ext)
p.Edits = make(map[string]*Photo)
matches, err := filepath.Glob(glob_pattern)
if err != nil {
return err
}
// note i is not really used
for i, match_path := range matches {
key := strings.Replace(match_path, edit_base, "", 1)
key = strings.Replace(key, p.Ext, "", 1)
if key == "" {
key = "unnamed"
} else {
key = key[1:] // strip leading '_', '-', etc
}
edit, err := NewPhoto(i, edits_dir, path.Base(match_path), p.Ext, edits_filetags, "", nil)
if err != nil {
return errors.New(fmt.Sprintf("could not initialize edit %s for %s: %s", key, p, err))
}
p.Edits[key] = edit
}
return nil
}
// [un]tag a given fname with a given tag
func api_photo_handler(w http.ResponseWriter, r *http.Request, conn_sqlite *sql.DB) {
err := r.ParseForm()
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Invalid request: %s", err)}, 503)
return
}
tag := r.Form.Get("tag")
untag := r.Form.Get("untag")
dir := r.Form.Get("dir")
name := r.Form.Get("name")
if dir == "" || name == "" {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Invalid request: %s", err)}, 503)
return
}
if tag == "" && untag == "" {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Invalid request: %s", err)}, 503)
return
}
if tag != "" && untag != "" {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Invalid request: %s", err)}, 503)
return
}
if tag != "" {
backend.Tag(w, r, conn_sqlite, path.Join(dir, name), tag)
} else {
backend.UnTag(w, r, conn_sqlite, path.Join(dir, name), untag)
}
}
func find_edits_dir(dir string) (string, error) {
edits_dir := strings.Replace(dir, "originals", "edits", 1)
edits_dir = strings.Replace(edits_dir, "originals-generated", "edits", 1)
if edits_dir == dir {
fmt.Fprintf(os.Stderr, "WARNING: '%s' not in a format that allows finding an edits dir (needs 'originals' subdir)\n", dir)
return "", nil
}
_, err := os.Stat(edits_dir)
if err == nil {
return edits_dir, nil
}
if !os.IsNotExist(err) {
return "", err
}
err = os.MkdirAll(edits_dir, os.ModeDir)
if err != nil {
fmt.Fprintf(os.Stderr, "WARNING: Failed to (recursively) create edits_dir '%s': %s\n", edits_dir, err)
return "", nil
}
return edits_dir, nil
}
func IsPhoto(f os.FileInfo) (isPhoto bool, name string, ext string) {
name = f.Name()
ext = filepath.Ext(name)
isPhoto = strings.HasPrefix(mime.TypeByExtension(strings.ToLower(ext)), "image/")
return
}
// get a list of photos (with tags) for a given dir
func api_photos_handler(w http.ResponseWriter, r *http.Request, conn_sqlite *sql.DB) {
dir := strings.Replace(r.URL.Path, "/api/photos", "", 1)
fmt.Printf("reading dir '%s'\n", dir)
list, err := ioutil.ReadDir(dir)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Cannot read directory: '%s': %s", dir, err)}, 503)
return
}
edits_dir, err := find_edits_dir(dir)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Edits directory '%s' seems to exist but unable to read: %s", edits_dir, err)}, 503)
return
}
photos := make([]*Photo, 0, len(list))
dir, err = filepath.Abs(dir)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Cannot figure out directory abspath: '%s': %s", dir, err)}, 503)
return
}
filetags, err := backend.GetFileTags(dir, conn_sqlite)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Cannot get file tags for main dir '%s': %s", dir, err)}, 503)
return
}
edits_filetags := make(map[string]string)
if edits_dir != "" {
edits_filetags, err = backend.GetFileTags(edits_dir, conn_sqlite)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Cannot get file tags for edits_dir '%s': %s", dir, err)}, 503)
return
}
}
id := 0
for _, f := range list {
if isPhoto, name, ext := IsPhoto(f); isPhoto {
p, err := NewPhoto(id, dir, name, ext, filetags, edits_dir, edits_filetags)
if err != nil {
fmt.Printf("WARNING: failed to create Photo instance: %s\n", err)
}
id++
photos = append(photos, p)
}
}
enc := json.NewEncoder(w)
err = enc.Encode(photos)
if err != nil {
fmt.Printf("WARNING: failed to encode/write json: %s\n", err)
}
}
func api_edit_handler(w http.ResponseWriter, r *http.Request, conn_sqlite *sql.DB) {
// this could be more elegant by getting entire photo as json and just converting json to go object.
err := r.ParseForm()
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Invalid request: %s", err)}, 503)
return
}
id, err := strconv.Atoi(r.Form.Get("id"))
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Cannot parse id: %s", err)}, 503)
}
dir := r.Form.Get("dir")
name := r.Form.Get("name")
start_from := r.Form.Get("start_from")
if dir == "" || name == "" {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Invalid request: %s", err)}, 503)
return
}
edits_dir, err := find_edits_dir(dir)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Edits directory '%s' seems to exist but unable to read: %s", edits_dir, err)}, 503)
return
}
if edits_dir == "" {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("dir is not in a format that supports an edits dir")}, 409)
return
}
var start_from_name string
if start_from != "" {
start_from_name = path.Base(start_from)
} else {
start_from = path.Join(dir, name)
start_from_name = name
}
start_from_ext := path.Ext(start_from_name)
tmp := path.Join(edits_dir, start_from_name[:len(start_from_name)-len(start_from_ext)]+"-save-your-edit-to-a-new-file"+start_from_ext)
err = cp.Cp(tmp, start_from)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Could not copy %s to %s because: %s", start_from, tmp, err)}, 503)
return
}
// this doesn't actually help with preventing write. but I guess that doesn't really matter anyway.
// the filename speaks for itself.
err = os.Chmod(tmp, 0000)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Could not make %s unwriteable: %s", tmp, err)}, 503)
return
}
err = exec.Command(editor, tmp).Run()
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Edit did not complete successfully: %s", err)}, 503)
return
}
err = os.Remove(tmp)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Could not remove tmp file %s: %s", tmp, err)}, 503)
return
}
filetags, err := backend.GetFileTags(dir, conn_sqlite)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Cannot get file tags: '%s': %s", dir, err)}, 503)
return
}
edits_filetags, err := backend.GetFileTags(edits_dir, conn_sqlite)
if err != nil {
backend.ErrorJson(w, backend.Resp{fmt.Sprintf("Cannot get file tags: '%s': %s", edits_dir, err)}, 503)
return
}
p, err := NewPhoto(id, dir, name, path.Ext(name), filetags, edits_dir, edits_filetags)
if err != nil {
fmt.Printf("WARNING: failed to create Photo instance: %s\n", err)
}
enc := json.NewEncoder(w)
err = enc.Encode(p)
if err != nil {
fmt.Printf("WARNING: failed to encode/write json: %s\n", err)
}
}
func serveThumb() http.Handler {
h := http.FileServer(http.Dir(thumbnail_dir))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := workers.Resize("pixie-gothum", r.URL.Path, thumbnail_dir)
if err != nil {
http.Error(w, err.Error(), 500)
} else {
fmt.Println(r.URL.Path)
// generate the thumb path again. we can optimize this later.
fileUri_in := fmt.Sprintf("file://%s", r.URL.Path)
hash := md5.New()
io.WriteString(hash, fileUri_in)
pathmd5 := fmt.Sprintf("%x", hash.Sum(nil))
path_out := pathmd5 + ".png"
r.URL.Path = path_out
fmt.Println(r.URL.Path)
h.ServeHTTP(w, r)
}
})
}
func main() {
fmt.Println("Starting...")
err := config.Parse(Expand("~/.pixie/config.ini"))
if err != nil {
log.Fatal("could not load config '~/.pixie/config.ini': " + err.Error() + " (did you set up as per the README?)")
}
thumbnail_dir = Expand(*ptr_thumbnail_dir)
tmsu_file = Expand(*ptr_tmsu_file)
addr = *ptr_addr
editor = *ptr_editor
conn_sqlite, err := sql.Open("sqlite3", tmsu_file)
if err != nil {
log.Fatal("could not open database: ", err.Error())
}
http.HandleFunc("/api/photos/", func(w http.ResponseWriter, r *http.Request) {
api_photos_handler(w, r, conn_sqlite)
})
http.HandleFunc("/api/photo", func(w http.ResponseWriter, r *http.Request) {
api_photo_handler(w, r, conn_sqlite)
})
http.HandleFunc("/api/edit", func(w http.ResponseWriter, r *http.Request) {
api_edit_handler(w, r, conn_sqlite)
})
http.Handle("/api/config/binds", http.StripPrefix("/api/config", http.FileServer(http.Dir(Expand("~/.pixie")))))
http.Handle("/thumbnails/", http.StripPrefix("/thumbnails", serveThumb()))
http.Handle("/", http.FileServer(http.Dir(".")))
fmt.Printf("starting up on %s\n", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}