-
Notifications
You must be signed in to change notification settings - Fork 0
/
session.go
96 lines (82 loc) · 2.48 KB
/
session.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
package phace
import (
"fmt"
"image"
"os"
"path/filepath"
// TODO Should callers be responsible for this?
_ "image/jpeg"
_ "image/png"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
)
// Session wraps the photos library folder and sqlite connections.
type Session struct {
// Path to the root *.photoslibrary folder.
Path string
// LibraryDB is the sqlite connection with photo data.
LibraryDB *sqlx.DB
// PersonDB is the sqlite connectin with face data.
PersonDB *sqlx.DB
}
// OpenSession connects to the embedded sqlite databases.
func OpenSession(path string) (*Session, error) {
dbPath := filepath.Join(path, "database")
libraryDB, err := openDB(filepath.Join(dbPath, "Library.apdb"))
if err != nil {
return nil, err
}
personDB, err := openDB(filepath.Join(dbPath, "Person.db"))
if err != nil {
return nil, err
}
return &Session{path, libraryDB, personDB}, nil
}
// ImagePath returns the on-disk path to the master image.
func (s *Session) ImagePath(p *Photo) string {
return filepath.Join(s.Path, "Masters", p.Path)
}
// Image opens the master image file in the library.
func (s *Session) Image(p *Photo) (image.Image, error) {
f, err := os.Open(s.ImagePath(p))
if err != nil {
return nil, err
}
defer f.Close()
m, _, err := image.Decode(f)
return m, err
}
// Photos gets all the photo records in the library.
func (s *Session) Photos() ([]*Photo, error) {
photos := make([]*Photo, 0)
err := s.LibraryDB.Select(&photos, `
SELECT v.uuid, v.masterUuid, m.fingerprint, m.imagePath, v.orientation, v.type, v.hasAdjustments
FROM RKVersion v
JOIN RKMaster m ON m.uuid = v.masterUuid
`)
return photos, err
}
// Faces gets all the face records in the library.
func (s *Session) Faces() ([]*Face, error) {
faces := make([]*Face, 0)
err := s.PersonDB.Select(&faces, `
SELECT f.uuid, fg.uuid AS groupId, f.imageId, f.centerX, f.centerY, f.size
FROM RKFace f
JOIN RKFaceGroupFace fgf ON fgf.faceId = f.modelId
JOIN RKFaceGroup fg ON fg.modelId = fgf.faceGroupId
`)
return faces, err
}
// FaceGroups gets all the group records in the library.
func (s *Session) FaceGroups() ([]*FaceGroup, error) {
return nil, fmt.Errorf("todo")
}
// openDB creates a sqlite connection and issues a test query to ensure
// the database isn't locked.
func openDB(path string) (*sqlx.DB, error) {
db, err := sqlx.Connect("sqlite3", path)
if err != nil {
return nil, fmt.Errorf("phace: %s: %v", path, err)
}
return db, err
}