/
label.go
244 lines (193 loc) Β· 6.49 KB
/
label.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
package entity
import (
"sync"
"time"
"github.com/jinzhu/gorm"
"github.com/photoprism/photoprism/internal/classify"
"github.com/photoprism/photoprism/internal/event"
"github.com/photoprism/photoprism/pkg/clean"
"github.com/photoprism/photoprism/pkg/rnd"
"github.com/photoprism/photoprism/pkg/txt"
)
const (
LabelUID = byte('l')
)
var labelMutex = sync.Mutex{}
var labelCategoriesMutex = sync.Mutex{}
type Labels []Label
// Label is used for photo, album and location categorization
type Label struct {
ID uint `gorm:"primary_key" json:"ID" yaml:"-"`
LabelUID string `gorm:"type:VARBINARY(42);unique_index;" json:"UID" yaml:"UID"`
LabelSlug string `gorm:"type:VARBINARY(160);unique_index;" json:"Slug" yaml:"-"`
CustomSlug string `gorm:"type:VARBINARY(160);index;" json:"CustomSlug" yaml:"-"`
LabelName string `gorm:"type:VARCHAR(160);" json:"Name" yaml:"Name"`
LabelPriority int `json:"Priority" yaml:"Priority,omitempty"`
LabelFavorite bool `json:"Favorite" yaml:"Favorite,omitempty"`
LabelDescription string `gorm:"type:VARCHAR(2048);" json:"Description" yaml:"Description,omitempty"`
LabelNotes string `gorm:"type:VARCHAR(1024);" json:"Notes" yaml:"Notes,omitempty"`
LabelCategories []*Label `gorm:"many2many:categories;association_jointable_foreignkey:category_id" json:"-" yaml:"-"`
PhotoCount int `gorm:"default:1" json:"PhotoCount" yaml:"-"`
Thumb string `gorm:"type:VARBINARY(128);index;default:''" json:"Thumb" yaml:"Thumb,omitempty"`
ThumbSrc string `gorm:"type:VARBINARY(8);default:''" json:"ThumbSrc,omitempty" yaml:"ThumbSrc,omitempty"`
CreatedAt time.Time `json:"CreatedAt" yaml:"-"`
UpdatedAt time.Time `json:"UpdatedAt" yaml:"-"`
PublishedAt *time.Time `sql:"index" json:"PublishedAt,omitempty" yaml:"PublishedAt,omitempty"`
DeletedAt *time.Time `sql:"index" json:"DeletedAt,omitempty" yaml:"-"`
New bool `gorm:"-" json:"-" yaml:"-"`
}
// TableName returns the entity table name.
func (Label) TableName() string {
return "labels"
}
// BeforeCreate creates a random UID if needed before inserting a new row to the database.
func (m *Label) BeforeCreate(scope *gorm.Scope) error {
if rnd.IsUnique(m.LabelUID, LabelUID) {
return nil
}
return scope.SetColumn("LabelUID", rnd.GenerateUID(LabelUID))
}
// NewLabel returns a new label.
func NewLabel(name string, priority int) *Label {
labelName := txt.Clip(name, txt.ClipDefault)
if labelName == "" {
labelName = "Unknown"
}
labelName = txt.Title(labelName)
labelSlug := txt.Slug(labelName)
result := &Label{
LabelSlug: labelSlug,
CustomSlug: labelSlug,
LabelName: txt.Clip(labelName, txt.ClipName),
LabelPriority: priority,
PhotoCount: 1,
}
return result
}
// Save updates the record in the database or inserts a new record if it does not already exist.
func (m *Label) Save() error {
labelMutex.Lock()
defer labelMutex.Unlock()
return Db().Save(m).Error
}
// Create inserts the label to the database.
func (m *Label) Create() error {
labelMutex.Lock()
defer labelMutex.Unlock()
return Db().Create(m).Error
}
// Delete removes the label from the database.
func (m *Label) Delete() error {
Db().Where("label_id = ? OR category_id = ?", m.ID, m.ID).Delete(&Category{})
Db().Where("label_id = ?", m.ID).Delete(&PhotoLabel{})
return Db().Delete(m).Error
}
// Deleted returns true if the label is deleted.
func (m *Label) Deleted() bool {
if m.DeletedAt == nil {
return false
}
return !m.DeletedAt.IsZero()
}
// Restore restores the label in the database.
func (m *Label) Restore() error {
if m.Deleted() {
return UnscopedDb().Model(m).Update("DeletedAt", nil).Error
}
return nil
}
// Update a label property in the database.
func (m *Label) Update(attr string, value interface{}) error {
return UnscopedDb().Model(m).UpdateColumn(attr, value).Error
}
// FirstOrCreateLabel returns the existing label, inserts a new label or nil in case of errors.
func FirstOrCreateLabel(m *Label) *Label {
result := Label{}
if err := UnscopedDb().Where("label_slug = ? OR custom_slug = ?", m.LabelSlug, m.CustomSlug).First(&result).Error; err == nil {
return &result
} else if createErr := m.Create(); createErr == nil {
if m.LabelPriority >= 0 {
event.EntitiesCreated("labels", []*Label{m})
event.Publish("count.labels", event.Data{
"count": 1,
})
}
return m
} else if err := UnscopedDb().Where("label_slug = ? OR custom_slug = ?", m.LabelSlug, m.CustomSlug).First(&result).Error; err == nil {
return &result
} else {
log.Errorf("label: %s (find or create %s)", createErr, m.LabelSlug)
}
return nil
}
// FindLabel returns an existing row if exists.
func FindLabel(s string) *Label {
labelSlug := txt.Slug(s)
result := Label{}
if err := Db().Where("label_slug = ? OR custom_slug = ?", labelSlug, labelSlug).First(&result).Error; err == nil {
return &result
}
return nil
}
// AfterCreate sets the New column used for database callback
func (m *Label) AfterCreate(scope *gorm.Scope) error {
m.New = true
return nil
}
// SetName changes the label name.
func (m *Label) SetName(name string) {
name = clean.NameCapitalized(name)
if name == "" {
return
}
m.LabelName = txt.Clip(name, txt.ClipName)
m.CustomSlug = txt.Slug(name)
}
// UpdateClassify updates a label if necessary
func (m *Label) UpdateClassify(label classify.Label) error {
save := false
db := Db()
if m.LabelPriority != label.Priority {
m.LabelPriority = label.Priority
save = true
}
if m.CustomSlug == "" {
m.CustomSlug = m.LabelSlug
save = true
} else if m.LabelSlug == "" {
m.LabelSlug = m.CustomSlug
save = true
}
if m.CustomSlug == m.LabelSlug && label.Title() != m.LabelName {
m.SetName(label.Title())
save = true
}
// Save label.
if save {
if err := db.Save(m).Error; err != nil {
return err
}
}
// Update label categories.
if len(label.Categories) > 0 {
labelCategoriesMutex.Lock()
defer labelCategoriesMutex.Unlock()
for _, category := range label.Categories {
sn := FirstOrCreateLabel(NewLabel(txt.Title(category), -3))
if sn == nil {
continue
}
if sn.Deleted() {
continue
}
if err := db.Model(m).Association("LabelCategories").Append(sn).Error; err != nil {
log.Debugf("index: failed saving label category %s (%s)", clean.Log(category), err)
}
}
}
return nil
}
// Links returns all share links for this entity.
func (m *Label) Links() Links {
return FindLinks("", m.LabelUID)
}