/
import.go
324 lines (260 loc) Β· 8.09 KB
/
import.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
package photoprism
import (
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"runtime/debug"
"sort"
"sync"
"github.com/karrick/godirwalk"
"github.com/photoprism/photoprism/internal/config"
"github.com/photoprism/photoprism/internal/entity"
"github.com/photoprism/photoprism/internal/event"
"github.com/photoprism/photoprism/internal/mutex"
"github.com/photoprism/photoprism/pkg/clean"
"github.com/photoprism/photoprism/pkg/fs"
"github.com/photoprism/photoprism/pkg/media"
)
// Import represents an importer that can copy/move MediaFiles to the originals directory.
type Import struct {
conf *config.Config
index *Index
convert *Convert
}
// NewImport returns a new importer and expects its dependencies as arguments.
func NewImport(conf *config.Config, index *Index, convert *Convert) *Import {
instance := &Import{
conf: conf,
index: index,
convert: convert,
}
return instance
}
// originalsPath returns the original media files path as string.
func (imp *Import) originalsPath() string {
return imp.conf.OriginalsPath()
}
// thumbPath returns the thumbnails cache path as string.
func (imp *Import) thumbPath() string {
return imp.conf.ThumbCachePath()
}
// Start imports media files from a directory and converts/indexes them as needed.
func (imp *Import) Start(opt ImportOptions) fs.Done {
defer func() {
if r := recover(); r != nil {
log.Errorf("import: %s (panic)\nstack: %s", r, debug.Stack())
}
}()
var directories []string
done := make(fs.Done)
if imp.conf == nil {
log.Errorf("import: config is not set")
return done
}
ind := imp.index
importPath := opt.Path
// Check if the import folder exists.
if !fs.PathExists(importPath) {
event.Error(fmt.Sprintf("import: directory %s not found", importPath))
return done
}
// Make sure to run import only once, unless otherwise requested.
if !opt.NonBlocking {
if err := mutex.MainWorker.Start(); err != nil {
event.Warn(fmt.Sprintf("import: %s", err.Error()))
return done
}
defer mutex.MainWorker.Stop()
}
if err := ind.tensorFlow.Init(); err != nil {
log.Errorf("import: %s", err.Error())
return done
}
jobs := make(chan ImportJob)
// Start a fixed number of goroutines to import files.
var wg sync.WaitGroup
var numWorkers = imp.conf.Workers()
wg.Add(numWorkers)
for i := 0; i < numWorkers; i++ {
go func() {
ImportWorker(jobs)
wg.Done()
}()
}
filesImported := 0
settings := imp.conf.Settings()
convert := settings.Index.Convert && imp.conf.SidecarWritable()
indexOpt := NewIndexOptions("/", true, convert, true, false, false)
indexOpt.UID = opt.UID
indexOpt.Action = opt.Action
skipRaw := imp.conf.DisableRaw()
ignore := fs.NewIgnoreList(fs.PPIgnoreFilename, true, false)
if err := ignore.Dir(importPath); err != nil {
log.Infof("import: %s", err)
}
ignore.Log = func(fileName string) {
log.Infof(`import: ignored "%s"`, fs.RelName(fileName, importPath))
}
err := godirwalk.Walk(importPath, &godirwalk.Options{
ErrorCallback: func(fileName string, err error) godirwalk.ErrorAction {
return godirwalk.SkipNode
},
Callback: func(fileName string, info *godirwalk.Dirent) error {
defer func() {
if r := recover(); r != nil {
log.Errorf("import: %s (panic)\nstack: %s", r, debug.Stack())
}
}()
if mutex.MainWorker.Canceled() {
return errors.New("canceled")
}
isDir, _ := info.IsDirOrSymlinkToDir()
isSymlink := info.IsSymlink()
if skip, result := fs.SkipWalk(fileName, isDir, isSymlink, done, ignore); skip {
if !isDir || errors.Is(result, filepath.SkipDir) {
return result
}
if fileName != importPath {
directories = append(directories, fileName)
}
folder := entity.NewFolder(entity.RootImport, fs.RelName(fileName, imp.conf.ImportPath()), fs.ModTime(fileName))
if err := folder.Create(); err == nil {
log.Infof("import: added folder /%s", folder.Path)
}
return result
}
done[fileName] = fs.Found
if !media.MainFile(fileName) {
return nil
}
mf, err := NewMediaFile(fileName)
// Check if file exists and is not empty.
if err != nil {
log.Warnf("import: %s", clean.Error(err))
return nil
} else if mf.Empty() {
return nil
}
// Ignore RAW images?
if mf.IsRaw() && skipRaw {
log.Infof("import: skipped raw %s", clean.Log(mf.RootRelName()))
return nil
}
// Report files that have a missing or invalid filename extension,
// see https://github.com/photoprism/photoprism/issues/3518.
if typeErr := mf.CheckType(); typeErr != nil {
log.Warnf("import: %s has %s", clean.Log(mf.RootRelName()), typeErr)
}
// Create JSON sidecar file, if needed.
if err = mf.CreateExifToolJson(imp.convert); err != nil {
log.Warnf("import: %s", clean.Error(err))
}
// Find related files to import.
related, err := mf.RelatedFiles(imp.conf.Settings().StackSequences())
if err != nil {
event.Error(fmt.Sprintf("import: %s", err))
return nil
}
var files MediaFiles
for _, f := range related.Files {
if f.FileSize() == 0 || done[f.FileName()].Processed() {
continue
}
files = append(files, f)
filesImported++
done[f.FileName()] = fs.Processed
}
done[fileName] = fs.Processed
related.Files = files
jobs <- ImportJob{
FileName: fileName,
Related: related,
IndexOpt: indexOpt,
ImportOpt: opt,
Imp: imp,
}
return nil
},
Unsorted: false,
FollowSymbolicLinks: true,
})
close(jobs)
wg.Wait()
sort.Slice(directories, func(i, j int) bool {
return len(directories[i]) > len(directories[j])
})
if opt.RemoveEmptyDirectories {
// Remove empty directories from import path.
for _, directory := range directories {
if fs.DirIsEmpty(directory) {
if err := os.Remove(directory); err != nil {
log.Errorf("import: failed deleting empty folder %s (%s)", clean.Log(fs.RelName(directory, importPath)), err)
} else {
log.Infof("import: deleted empty folder %s", clean.Log(fs.RelName(directory, importPath)))
}
}
}
}
if opt.RemoveDotFiles {
// Remove hidden .files if option is enabled.
for _, file := range ignore.Hidden() {
if !fs.FileExists(file) {
continue
}
if err := os.Remove(file); err != nil {
log.Errorf("import: failed removing %s (%s)", clean.Log(fs.RelName(file, importPath)), err.Error())
}
}
}
if err != nil {
log.Error(err.Error())
}
if filesImported > 0 {
// Run face recognition if enabled.
if w := NewFaces(imp.conf); w.Disabled() {
log.Debugf("import: skipping face recognition")
} else if err := w.Start(FacesOptionsDefault()); err != nil {
log.Errorf("import: %s", err)
}
// Update photo counts and visibilities.
if err := entity.UpdateCounts(); err != nil {
log.Warnf("index: %s (update counts)", err)
}
}
runtime.GC()
return done
}
// Cancel stops the current import operation.
func (imp *Import) Cancel() {
mutex.MainWorker.Cancel()
}
// DestinationFilename returns the destination filename of a MediaFile to be imported.
func (imp *Import) DestinationFilename(mainFile *MediaFile, mediaFile *MediaFile, folder string) (string, error) {
fileName := mainFile.CanonicalName()
fileExtension := mediaFile.Extension()
dateCreated := mainFile.DateCreated()
if !mediaFile.IsSidecar() {
if f, err := entity.FirstFileByHash(mediaFile.Hash()); err == nil {
existingFilename := FileName(f.FileRoot, f.FileName)
if fs.FileExists(existingFilename) {
return existingFilename, fmt.Errorf("%s is identical to %s (sha1 %s)", clean.Log(filepath.Base(mediaFile.FileName())), clean.Log(f.FileName), mediaFile.Hash())
} else {
return existingFilename, nil
}
}
}
// Find and return available filename.
iteration := 0
pathName := filepath.Join(imp.originalsPath(), folder, dateCreated.Format("2006/01"))
result := filepath.Join(pathName, fileName+fileExtension)
for fs.FileExists(result) {
if mediaFile.Hash() == fs.Hash(result) {
return result, fmt.Errorf("%s already exists", clean.Log(fs.RelName(result, imp.originalsPath())))
}
iteration++
result = filepath.Join(pathName, fileName+"."+fmt.Sprintf("%05d", iteration)+fileExtension)
}
return result, nil
}