-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcollect.go
More file actions
431 lines (378 loc) · 10.8 KB
/
collect.go
File metadata and controls
431 lines (378 loc) · 10.8 KB
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package main
import (
"context"
"strings"
"unicode"
)
// Run performs the main collection logic and returns the results.
func RunCollection(ctx context.Context, pc *Client, o Options) (Output, error) {
// --- discover sections ---
var (
sections []Directory
err error
)
if o.SectionsCSV != "" {
for _, s := range strings.Split(o.SectionsCSV, ",") {
s = strings.TrimSpace(s)
if s == "" {
continue
}
sections = append(sections, Directory{
Key: s,
Type: "movie",
Title: "(manual " + s + ")",
})
}
} else {
sections, err = pc.DiscoverSections(ctx, o.IncludeShows)
if err != nil {
return Output{}, err
}
if len(sections) == 0 {
return Output{}, ErrNoSections
}
}
// --- collect and summarize ---
out := Output{
Server: pc.BaseURL(),
}
ignored := make([]IgnoredItem, 0)
totalItems := 0
totalVersions := 0
totalGhosts := 0
totalVariantsExcluded := 0
var libSummaries []LibrarySummary
for _, sec := range sections {
vids, err := pc.FetchDuplicatesForSection(ctx, sec.Key)
if err != nil {
// Skip this library on error; continue with others
continue
}
sectionRes := SectionResult{
SectionID: sec.Key,
SectionTitle: sec.Title,
Type: sec.Type,
}
secGhostParts := 0
secItemsWithGhosts := 0
secTotalVersions := 0
secVariantsExcluded := 0
for _, v := range vids {
// deep fetch for parts and verification flags (if enabled)
var vv *Video
if o.Deep {
vv, err = pc.DeepFetchItem(ctx, v.RatingKey, o.Verify)
if err != nil {
vv = &v
}
} else {
vv = &v
}
item := Item{
RatingKey: vv.RatingKey,
Title: fallback(vv.Title, v.Title),
Year: vv.Year,
Guid: vv.Guid,
}
itemGhosts := 0
for _, m := range vv.Media {
ver := Version{
ID: m.ID,
Container: m.Container,
VideoCodec: m.VideoCodec,
AudioCodec: m.AudioCodec,
VideoResolution: m.VideoResolution,
Bitrate: m.Bitrate,
Width: m.Width,
Height: m.Height,
}
// build parts first, and detect if this entire version is in an Extras folder
versionGhosts := 0
versionIsExtra := false
for _, p := range m.Part {
if o.IgnoreExtras && isExtraPath(p.File) {
versionIsExtra = true
}
exists := p.ExistsInt == 1
accessible := p.AccessibleInt == 1
verified := exists && accessible
ver.Parts = append(ver.Parts, PartOut{
ID: p.ID,
File: p.File,
Size: p.Size,
Duration: p.Duration,
VerifiedOnDisk: verified,
Exists: exists,
Accessible: accessible,
})
if o.Verify && !verified {
versionGhosts++
}
}
// If ignoring extras and this version lives under Extras/Featurettes store it and skip it
if o.IgnoreExtras && versionIsExtra {
// Record this dropped version as an ignored Extra
ignored = append(ignored, IgnoredItem{
SectionID: sec.Key,
SectionTitle: sec.Title,
Reason: "extra_version",
Item: Item{
RatingKey: vv.RatingKey,
Title: fallback(vv.Title, v.Title),
Year: vv.Year,
Guid: vv.Guid,
Versions: []Version{ver},
},
})
continue // skip adding this version to the item
}
itemGhosts += versionGhosts
item.Versions = append(item.Versions, ver)
}
// If extras filtering left fewer than 2 versions, it's no longer a duplicate.
if len(item.Versions) < 2 {
secVariantsExcluded++
continue
}
// Ignore EXACT 4K+HD pair (only that case)
if shouldExcludeAs4kHdPair(item, o.DupPolicy) {
secVariantsExcluded++
ignored = append(ignored, IgnoredItem{
SectionID: sec.Key,
SectionTitle: sec.Title,
Reason: "4k+hd_pair",
Item: item,
})
continue
}
// Count only kept items
secTotalVersions += len(item.Versions)
if itemGhosts > 0 {
secItemsWithGhosts++
}
secGhostParts += itemGhosts
sectionRes.Items = append(sectionRes.Items, item)
}
libSummaries = append(libSummaries, LibrarySummary{
SectionID: sec.Key,
SectionTitle: sec.Title,
Type: sec.Type,
DuplicateItems: len(sectionRes.Items),
TotalVersions: secTotalVersions,
GhostParts: secGhostParts,
ItemsWithGhosts: secItemsWithGhosts,
VariantsExcluded: secVariantsExcluded,
})
totalItems += len(sectionRes.Items)
totalVersions += secTotalVersions
totalGhosts += secGhostParts
totalVariantsExcluded += secVariantsExcluded
out.Sections = append(out.Sections, sectionRes)
}
out.TotalItems = totalItems
out.TotalVersions = totalVersions
out.TotalGhosts = totalGhosts
out.Summary = Summary{
VerificationPerformed: o.Verify,
TotalLibraries: len(out.Sections),
TotalDuplicateItems: totalItems,
TotalGhostParts: totalGhosts,
DuplicatePolicy: o.DupPolicy,
VariantItemsExcluded: totalVariantsExcluded,
Libraries: libSummaries,
}
out.Ignored = ignored
return out, nil
}
// ErrNoSections is returned when no movie/show sections are found.
var ErrNoSections = &noSectionsErr{}
type noSectionsErr struct{}
func (*noSectionsErr) Error() string { return "no movie/show sections found" }
// Exclude when there are exactly two versions and they are:
// one 4K (2160) + one HD-ish (1080 or 720, including mislabels).
func shouldExcludeAs4kHdPair(it Item, policy string) bool {
if strings.ToLower(policy) != "ignore-4k-1080" {
return false // 'plex' or anything else: keep Plex behavior
}
if len(it.Versions) != 2 {
return false
}
v1, v2 := it.Versions[0], it.Versions[1]
is4k1 := normalizeResKey(v1) == "2160"
is4k2 := normalizeResKey(v2) == "2160"
// One must be 4K, the other must be HD-ish
if is4k1 && isHDVersion(v2) {
return true
}
if is4k2 && isHDVersion(v1) {
return true
}
return false
}
// isHDVersion returns true for 1080/720, including common mislabels.
// It avoids classifying typical SD (720x480, 720x576) as HD.
func isHDVersion(v Version) bool {
key := normalizeResKey(v)
if key == "1080" || key == "720" {
return true
}
// Dimension-based fallback (handles weird labels like "sd (720×388)")
w, h := v.Width, v.Height
if w < h {
w, h = h, w // w = long side
}
// Explicitly exclude common SD DVD sizes
if (w == 720 && (h == 480 || h == 576)) || (h == 720 && (w == 480 || w == 576)) {
return false
}
// Clearly 1080-ish mislabels
if w >= 1700 || h >= 1000 {
return true
}
// 720-ish: long side >= 700 and short side >= 380
// (captures 720×388 / 704×396 scope-y encodes, but not tiny SD)
if w >= 700 && h >= 380 {
return true
}
return false
}
// Normalize resolution label to a key we can compare.
// (Make sure this matches 4K short-side tweak of 1580 to account for cinemascope aspect ratios etc)
func normalizeResKey(v Version) string {
r := strings.ToLower(strings.TrimSpace(v.VideoResolution))
switch {
case r == "4k" || strings.Contains(r, "2160") || strings.Contains(r, "uhd"):
return "2160"
case strings.Contains(r, "1080"):
return "1080"
case strings.Contains(r, "720"):
return "720"
case r == "sd" || strings.Contains(r, "480"):
return "480"
}
// Fallback by dimensions (long/short side)
w, h := v.Width, v.Height
if w < h {
w, h = h, w
}
const (
th4kLong = 3200
th4kShort = 1580
th1080Long = 1700
th1080Short = 900
th720Long = 1200
th720Short = 650
)
switch {
case w >= th4kLong || h >= th4kShort:
return "2160"
case w >= th1080Long || h >= th1080Short:
return "1080"
case w >= th720Long || h >= th720Short:
return "720"
case h > 0 || w > 0:
return "480"
default:
return "unknown"
}
}
// Known Extra folder names (case-insensitive, per path segment)
// Plex standard: https://support.plex.tv/articles/local-files-for-trailers-and-extras/
var extraDirNames = map[string]struct{}{
"extras": {}, "featurettes": {}, "interviews": {}, "shorts": {}, "deleted": {},
"deleted scenes": {}, "trailers": {}, "behind the scenes": {}, "other": {}, "scenes": {},
}
// Allowed Plex standardized tokens for filename suffix (case-insensitive)
// Plex standard: https://support.plex.tv/articles/local-files-for-trailers-and-extras/
var extraTokens = map[string]struct{}{
"behindthescenes": {}, "deleted": {}, "featurette": {}, "deletedscene": {}, "interviews": {},
"interview": {}, "scene": {}, "short": {}, "trailer": {}, "other": {}, "deletedscenes": {},
}
// isExtraPath returns true if the path is inside an Extras-like folder OR
// the basename ends with a standardized Plex suffix (with/without extension).
func isExtraPath(p string) bool {
if p == "" {
return false
}
// Normalize separators to forward slashes
s := strings.ReplaceAll(p, "\\", "/")
parts := strings.Split(s, "/")
if len(parts) == 0 {
return false
}
// Folder-based detection on parent dirs
for _, seg := range parts[:len(parts)-1] {
seg = strings.TrimSpace(strings.ToLower(seg))
if seg == "" {
continue
}
if _, ok := extraDirNames[seg]; ok {
return true
}
}
// Filename-based detection (hyphen-suffix token), with or without extension
base := parts[len(parts)-1] // keep extension; we handle both cases below
return isExtraBasename(base)
}
// isExtraBasename checks only the basename (may include extension).
// Matches “…-token” or “…-token-<digits>” (also _, ., or space before digits), case-insensitive.
func isExtraBasename(name string) bool {
if name == "" {
return false
}
// Strip extension if present (optional; we accept with or without)
if dot := strings.LastIndexByte(name, '.'); dot > 0 {
name = name[:dot]
}
name = strings.TrimSpace(name)
// Must have a hyphen introducing the token
idx := strings.LastIndexByte(name, '-')
if idx == -1 || idx == len(name)-1 {
return false
}
suffix := strings.ToLower(strings.TrimSpace(name[idx+1:]))
if suffix == "" {
return false
}
// Exact token match
if _, ok := extraTokens[suffix]; ok {
return true
}
// Token followed by one separator and digits
for tok := range extraTokens {
if strings.HasPrefix(suffix, tok) {
rest := strings.TrimSpace(suffix[len(tok):])
if rest == "" {
return true
}
// one leading separator then digits (e.g., -trailer-2, -trailer_01, -trailer 3, -trailer.4)
if len(rest) >= 2 && (rest[0] == '-' || rest[0] == '_' || rest[0] == '.' || rest[0] == ' ') {
digits := strings.TrimSpace(rest[1:])
if allDigits(digits) {
return true
}
}
}
}
return false
}
// allDigits returns true if s is non-empty and consists only of digit runes.
func allDigits(s string) bool {
if s == "" {
return false
}
for _, r := range s {
if !unicode.IsDigit(r) {
return false
}
}
return true
}
// fallback returns a if it's not the zero value, otherwise b.
func fallback[T comparable](a, b T) T {
var zero T
if a != zero {
return a
}
return b
}