Repository navigation
Expand file tree
/
Copy pathparse.go
More file actions
3188 lines (3063 loc) · 109 KB
/
Copy pathparse.go
File metadata and controls
3188 lines (3063 loc) · 109 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rls
import (
"bytes"
"html"
"regexp"
"slices"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unsafe"
"github.com/autobrr/rls/reutil"
"github.com/autobrr/rls/taginfo"
)
// TagParser is a release tag parser.
type TagParser struct {
tagParser
// load returns what the built-in default parser parses with, which it
// builds when first called (see DefaultParser), and tagParser is then not
// used. It is nil for every other parser. A copy of the default parser
// has the same load, so it parses with the same state, built once. Only
// SetBuilder writes load, and no parse may run beside that, as before.
load func() *tagParser
}
// tagParser is what a TagParser parses with.
type tagParser struct {
builder Builder
ellip []byte
once []LexFunc
multi []LexFunc
notFirst []bool
// dispatch gives the lexers of multi that can match at a position.
dispatch *dispatch
// pooled is whether the tags are lexed into scratch from the pool, which
// they are when every lexer is one of this package's. A lexer of a
// caller's may keep the slices it is handed, so a parser with one makes
// them for each parse alone.
pooled bool
// isDelim is delim as a byte table: every delimiter is a single ASCII
// byte, so membership is all the regexp ever decided.
isDelim [256]bool
}
// NewTagParser creates a new release tag parser.
func NewTagParser(infos map[string][]*taginfo.Taginfo, lexers ...Lexer) Parser {
return newTagParser(DefaultBuilder, infos, lexers...)
}
// newTagParser is NewTagParser with the builder to use.
func newTagParser(builder Builder, infos map[string][]*taginfo.Taginfo, lexers ...Lexer) *TagParser {
// delims
var v []string
for r := range rune(255) {
if isAnyDelim(r) {
v = append(v, string(r))
}
}
delim := regexp.MustCompile(`^((?:` + reutil.Join(true, v...) + ")+)")
// build short tags. A word that is a tag in any case is stored in upper
// case as true. A tag of one word whose regexp matches it only as written
// ('(?-i:MAX)') is stored as written, and in upper case when that matches,
// as false: the word in another case is a group ('[Max] Show - 01')
short := make(map[string]bool)
hdr := strings.ToLower(TagTypeHDR.String())
for typ, v := range infos {
if typ == hdr {
continue
}
for _, info := range v {
fields := strings.FieldsFunc(info.Tag(), isAnyDelim)
for _, field := range fields {
if len(field) >= 5 || strings.Contains(field, "$") {
continue
}
u := strings.ToUpper(field)
if len(fields) != 1 || info.Match(strings.ToLower(field)) {
short[u] = true
continue
}
for _, w := range []string{field, u} {
if _, ok := short[w]; !ok && info.Match(w) {
short[w] = false
}
}
}
}
}
// separate once and multi. The lexers of this package offer what they
// need at a position to match while they are initialized, see withGate
offer := &gateOffer{gates: make(map[unsafe.Pointer]*lexGate)}
gateOffers.Store(delim, offer)
defer gateOffers.Delete(delim)
var once, multi []LexFunc
var notFirst []bool
var gates []*lexGate
pooled := true
for _, lexer := range lexers {
f, o, nf := lexer.Initialize(infos, delim, short)
offer.mu.Lock()
gate, own := offer.gates[funcID(f)]
offer.mu.Unlock()
pooled = pooled && own
if o {
once = append(once, f)
} else {
multi = append(multi, f)
notFirst = append(notFirst, nf)
gates = append(gates, gate)
}
}
// init builder
if b, ok := builder.(interface {
Init(map[string][]*taginfo.Taginfo) Builder
}); ok {
builder = b.Init(infos)
}
p := &TagParser{tagParser: tagParser{
builder: builder,
ellip: []byte("..."),
once: once,
multi: multi,
notFirst: notFirst,
dispatch: newDispatch(gates),
pooled: pooled,
}}
for c := range 255 {
p.isDelim[c] = isAnyDelim(rune(c))
}
return p
}
// ParserOption is an option for NewParser.
type ParserOption func(*parserOptions)
// parserOptions are what the options given to NewParser change.
type parserOptions struct {
extras []map[string][]*taginfo.Taginfo
lexers []Lexer
}
// NewParser creates a tag parser with the built-in tag infos and the default
// lexers, changed by opts. With no options it builds the parser
// NewDefaultParser builds. It returns the concrete type, as ParseHint and
// SetBuilder are methods of it, and it can still be assigned to DefaultParser.
// The builder is DefaultBuilder, as with NewTagParser.
func NewParser(opts ...ParserOption) *TagParser {
var o parserOptions
for _, opt := range opts {
opt(&o)
}
lexers := o.lexers
if len(lexers) == 0 {
lexers = DefaultLexers()
}
return NewTagParser(taginfo.All(o.extras...), lexers...).(*TagParser)
}
// WithTaginfo adds tag infos to the built-in ones, keyed by tag type as
// taginfo.All keys them ('collection'), the way a caller adds the streaming
// services it knows. It may be given more than once, and the maps add up in
// the order given. The infos under a key the built-in infos already have are
// added after the built-in ones and do not replace them, so where a built-in
// and an extra info match the same text the built-in one is found. A nil map
// adds nothing, and a nil info in a map is left out, which is what a caller
// has that did not check the error of taginfo.New.
func WithTaginfo(extra map[string][]*taginfo.Taginfo) ParserOption {
return func(o *parserOptions) {
m := make(map[string][]*taginfo.Taginfo, len(extra))
for typ, infos := range extra {
for _, info := range infos {
if info != nil {
m[typ] = append(m[typ], info)
}
}
}
o.extras = append(o.extras, m)
}
}
// WithLexers replaces the default lexers. Given no lexers it changes nothing,
// and the default lexers, or those of an earlier WithLexers, stay in place, as
// a parser with no lexers would read every name as text. A lexer keeps what
// its parser gave it when it was built, so every parser needs lexers of its
// own: do not give the same Lexer values to two parsers.
func WithLexers(lexers ...Lexer) ParserOption {
return func(o *parserOptions) {
if len(lexers) != 0 {
o.lexers = lexers
}
}
}
// Hint is what a caller knows about a name before it is parsed, such as the
// category of the indexer section it was announced in.
type Hint struct {
// Type is the release type when the caller knows it. Unknown lets the
// parser decide, as ParseRelease does, and so does a value that is not
// one of the release types.
Type Type
// DayFirst reads a date written with two numbers and a year as day,
// month, year: '05.06.2024' is 5 June. Without it that is 6 May, and a
// date is read day first only when its first number cannot be a month
// ('13.06.2024').
DayFirst bool
// Sports says the name is a sports broadcast. It changes what Event
// returns and nothing else: Event then reports the round, the session
// and the rest of what it reads for any name of any type, where it
// otherwise wants a competition it knows and signs of an event. Type,
// Title and Subtitle are what they are without it.
Sports bool
}
// ParseHint parses a release from src with what the caller knows about it.
// The zero Hint gives what ParseRelease gives.
//
// The type in h is the release type, and the titles and the tags that are
// kept follow it. It is set when the parser's builder is a *TagBuilder; with
// any other Builder the release is what its Build returns, and the type in h
// has no effect. DayFirst applies to the date tags before any builder sees
// them, and Sports is kept for Event with any builder.
func (p *TagParser) ParseHint(src []byte, h Hint) Release {
tags, end := parseCopy(p, src)
return p.buildHint(tags, end, h)
}
// buildHint builds the release of tags that a parse of p made, with what the
// caller knows about the name.
func (p *TagParser) buildHint(tags []Tag, end int, h Hint) Release {
if h.DayFirst {
dayFirst(tags)
}
var r Release
builder := p.state().builder
if b, ok := builder.(*TagBuilder); ok {
r = b.build(tags, end, h)
} else {
r = builder.Build(tags, end)
}
r.sports = h.Sports
return r
}
// dayFirst swaps the month and day of each date tag that was written as two
// two-digit numbers and a four-digit year ('05.06.2024') and read month first,
// when the second number can also be a month. A date read day first already
// ('13.06.2024'), one whose second number is no month ('06.13.2024'), and one
// written year first, with a month name or with a two-digit year are left
// alone. The text as written stays, so the name still prints as given.
//
// The tags are those Parse made for this call alone, so changing their values
// in place is safe.
func dayFirst(tags []Tag) {
for i := range tags {
v := tags[i].v
// a range of years has a fifth value, and is written year first
if tags[i].typ != TagTypeDate || len(v) != 4 {
continue
}
s := v[0]
if len(s) != 10 || !isDateSep(s[2]) || !isDateSep(s[5]) || s[6:] != v[1] {
continue
}
// the lexer writes month and day with two digits, so the first
// number read as the month and the second as the day means the date
// was read month first, and a second number from 01 to 12 can be the
// month
if first, second := s[:2], s[3:5]; v[2] == first && v[3] == second && second >= "01" && second <= "12" {
v[2], v[3] = second, first
}
}
}
// isDateSep reports whether c separates the numbers of a date. A comma and a
// plus do too, since the lexers read them as spaces.
func isDateSep(c byte) bool {
return c == '-' || c == '.' || c == '_' || c == ' ' || c == ',' || c == '+'
}
// SetBuilder sets the builder for the tag parser.
func (p *TagParser) SetBuilder(builder Builder) {
if p.load != nil {
// the default parser, or a copy of it, gets a state of its own, so
// the builder is set for this parser alone
p.tagParser, p.load = *p.load(), nil
}
p.builder = builder
}
// state returns what p parses with: its own tagParser, or for the built-in
// default parser the one that load builds on first use.
func (p *TagParser) state() *tagParser {
if p.load != nil {
return p.load()
}
return &p.tagParser
}
// Parse parses tags in buf.
func (p *TagParser) Parse(src []byte) ([]Tag, int) {
return parseCopy(p, src)
}
// parseCopy parses the tags of a name that is the caller's, given as bytes or
// as a string. The name is copied into one piece of memory with its working
// copy, which the tags then share.
func parseCopy[T string | []byte](p *TagParser, name T) ([]Tag, int) {
mem := make([]byte, 2*len(name))
n := copy(mem, name)
return p.lex(mem[:n:n], mem[n:])
}
// parse parses the tags of src, which is the parser's to keep: the tags hold
// pieces of it and not copies. So it has to be bytes that nothing else holds
// and nothing writes to from here on, which a copy of what the caller gave
// is. The lexers of this package only read it. The tags keep it and the
// working copy alive, and nothing of the caller's.
func (p *TagParser) parse(src []byte) ([]Tag, int) {
return p.lex(src, make([]byte, len(src)))
}
// lex is parse with the room for the working copy, which is as long as src.
//
// The tags are lexed into scratch that the next parse uses again, and copied
// out of it: the tags a caller gets are a slice of their own that is exactly
// as long as they are, and nothing of the scratch. With a lexer of a caller's
// in the parser the room is made for the parse alone, as such a lexer may
// keep the slices it is handed.
func (p *TagParser) lex(src, buf []byte) ([]Tag, int) {
return p.state().run(src, buf)
}
// run is lex with the state of the parser.
func (p *tagParser) run(src, buf []byte) ([]Tag, int) {
// working buf
for i, c := range src {
switch c {
case '_', ',', '+':
c = ' '
}
buf[i] = c
}
i, n := 0, len(buf)
var sc *tagScratch
var start, end []Tag
if p.pooled {
sc = tagScratchPool.Get().(*tagScratch)
start, end = sc.take(len(src))
} else {
start = make([]Tag, 0, tagRoom(len(src)))
}
// once
for _, f := range p.once {
start, end, i, n, _ = f(src, buf, start, end, i, n)
}
// consume
notFirst := false
for i < n {
start, end, i, _ = p.next(src, buf, start, end, i, n, ¬First)
}
// start, and then end reversed
tags := make([]Tag, len(start)+len(end))
copy(tags, start)
for i, k := len(end), len(start); i > 0; i, k = i-1, k+1 {
tags[k] = end[i-1]
}
if sc != nil {
sc.give(start, end)
tagScratchPool.Put(sc)
}
return tags, len(start)
}
// tagScratch is the room a parse lexes its tags into: those read from the
// start of the name and those read from its end. A parse takes one from the
// pool and gives it back, so that the room is made once and not for every
// name, and is not what a caller keeps.
//
// A scratch only ever holds memory that take made. What the lexers hand back
// in its place, because they outgrew it or built a slice of their own, is
// used for that parse and then left to them.
type tagScratch struct {
start, end []Tag
}
var tagScratchPool = sync.Pool{New: func() any { return new(tagScratch) }}
// maxScratch is how many tags the scratch that goes back to the pool has
// room for. A name that needs more gets room of its own.
const maxScratch = 1024
// endScratch is the room for the tags read from the end of a name, which are
// few: the extension, the group, the meta suffixes and their delimiters.
const endScratch = 16
// tagRoom is how many tags to make room for in a name of n bytes: a name
// yields roughly one tag per three bytes, and room for one per two holds them
// without growing.
func tagRoom(n int) int {
return n/2 + 8
}
// take returns the room for the tags of a name of n bytes, empty.
func (sc *tagScratch) take(n int) (start, end []Tag) {
want := tagRoom(n)
switch {
case cap(sc.start) >= want:
case want <= maxScratch:
sc.start = make([]Tag, 0, max(want, 64))
default:
return make([]Tag, 0, want), sc.ends()
}
return sc.start[:0], sc.ends()
}
// ends returns the room for the tags read from the end of a name.
func (sc *tagScratch) ends() []Tag {
if sc.end == nil {
sc.end = make([]Tag, 0, endScratch)
}
return sc.end[:0]
}
// give takes the room back from a parse that lexed start and end into it,
// and empties it, so that the scratch keeps no name alive while it waits for
// the next parse.
func (sc *tagScratch) give(start, end []Tag) {
emptyScratch(sc.start, start)
emptyScratch(sc.end, end)
}
// emptyScratch clears the tags a parse left in room, which is the room of a
// scratch. used is what the lexers made of it: the same memory with tags in
// it, or other memory when the room was not theirs or they left it, in which
// case there is no telling how far they wrote.
func emptyScratch(room, used []Tag) {
if cap(room) != 0 && cap(used) != 0 && unsafe.SliceData(room) == unsafe.SliceData(used) {
clear(used)
return
}
clear(room[:cap(room)])
}
// next reads the next token from src up to the next delimiter. Iterates over
// the lexers until a match occurs. If none of the lexers match, then iterates
// over src, capturing all text, until src is exhausted or until a delimiter is
// encountered. Appends captured tags to start or end (where appropriate)
// returning the modified slices and new values of i, n.
//
// Lexers have the choice of matching against src or buf. Buf is the working
// version of src, with underscores and other runes replaced with spaces. Using
// buf allows lexers to matching with Go regexp `\b`.
func (p *tagParser) next(src, buf []byte, start, end []Tag, i, n int, notFirst *bool) ([]Tag, []Tag, int, int) {
// delimiter
if bytes.HasPrefix(src[i:n], p.ellip) {
return append(
start,
newTag(src, buf, TagTypeDelim, nil, p.ellip, p.ellip),
), end, i + len(p.ellip), n
} else if p.isDelim[src[i]] {
j := i + 1
for j < n && p.isDelim[src[j]] {
j++
}
return append(
start,
newTag(src, buf, TagTypeDelim, nil, src[i:j], src[i:j]),
), end, j, n
}
// run the lexers that can match here, in lexer order
startn, mask := len(start), p.dispatch.mask(buf, i, n)
for a := nextLexer(mask, 0); a < len(p.multi); a = nextLexer(mask, a+1) {
if p.notFirst[a] && !*notFirst {
continue
}
// a match has to consume input from one end or the other. One that
// does not would be offered the same input again without end, so it
// is taken as no match and the next lexer is tried
s, e, j, k, ok := p.multi[a](src, buf, start, end, i, n)
if !ok {
continue
}
if i <= j && j <= k && k <= n && (i < j || k < n) {
*notFirst = *notFirst || startn != len(s)
return s, e, j, k
}
// the tags of a match that is not taken are behind those that are.
// In scratch, which later parses use again, they are cleared
if p.pooled && len(s) > len(start) {
clear(s[len(start):])
}
if p.pooled && len(e) > len(end) {
clear(e[len(end):])
}
}
// text
j := i
for j < n && !p.isDelim[src[j]] {
j++
}
*notFirst = true
return append(
start,
newTag(src, buf, TagTypeText, nil, src[i:j], src[i:j]),
), end, j, n
}
// ParseRelease parses a release from src.
func (p *TagParser) ParseRelease(src []byte) Release {
tags, end := p.Parse(src)
return p.state().builder.Build(tags, end)
}
// TagBuilder is a release builder.
type TagBuilder struct {
// missing finds acronyms without periods.
missing *regexp.Regexp
// bad finds bad acronyms with periods.
bad *regexp.Regexp
// fix fixes issues with acronyms.
fix *regexp.Regexp
// spaces matches multiple spaces.
spaces *regexp.Regexp
// ellips matches multiple 3 or more periods (an ellipsis...).
ellips *regexp.Regexp
// sum matches a file checksum.
sum *regexp.Regexp
// digpre matches digit prefixes.
digpre *regexp.Regexp
// digsuf matches digit suffixes.
digsuf *regexp.Regexp
// containerf is the container find func.
containerf *finder
// audiof is the audio find func.
audiof *finder
// resolutionf is the resolution find func.
resolutionf *finder
// languagef is the language find func.
languagef *finder
// groupf is the group find func.
groupf *finder
}
// NewTagBuilder creates a new release builder.
func NewTagBuilder() *TagBuilder {
return &TagBuilder{
missing: regexp.MustCompile(`\b[A-Z][\. ][A-Z](?:[\. ][A-Z])*[\. ]?\b`),
bad: regexp.MustCompile(`[^A-Z][-\. ][A-Z]\.($|[^A-Z])`),
fix: regexp.MustCompile(`([A-Z])\.`),
spaces: regexp.MustCompile(`\s+`),
ellips: regexp.MustCompile(`\.{3,}`),
sum: regexp.MustCompile(`(?i)^[a-f0-9]{8}$`),
digpre: regexp.MustCompile(`^\d+`),
digsuf: regexp.MustCompile(`\d+$`),
}
}
// Init creates a new builder using the provided infos.
func (b *TagBuilder) Init(infos map[string][]*taginfo.Taginfo) Builder {
return &TagBuilder{
missing: b.missing,
bad: b.bad,
fix: b.fix,
spaces: b.spaces,
ellips: b.ellips,
sum: b.sum,
digpre: b.digpre,
digsuf: b.digsuf,
containerf: newFinder(TagTypeContainer, infos["container"]...),
audiof: newFinder(TagTypeAudio, infos["audio"]...),
resolutionf: newFinder(TagTypeResolution, infos["resolution"]...),
languagef: newFinder(TagTypeLanguage, infos["language"]...),
groupf: newFinder(TagTypeGroup, infos["group"]...),
}
}
// Build builds a release from tags.
func (b *TagBuilder) Build(tags []Tag, end int) Release {
return b.build(tags, end, Hint{})
}
// build builds a release from tags with what the caller knows about it. A
// type in h is set before specialDate, unset and titles, the steps that read
// the type, so that the tags that are unset and the titles that are read are
// those of that type. Nothing before them reads it.
func (b *TagBuilder) build(tags []Tag, end int, h Hint) Release {
// flags in brackets that open the name ('[REPACK] [Group] Show'), which
// only the meta lexer puts there, are left out of the build of the rest,
// so that the rest reads as if it opened the name
if k := leadingFlags(tags, end); k != 0 {
r := b.build(tags[k:], end-k, h)
var other []string
for _, tag := range tags[:k] {
if tag.Is(TagTypeOther) {
other = appendOnce(other, tag.Other())
}
}
for _, s := range r.Other {
other = appendOnce(other, s)
}
r.tags, r.end, r.Other = tags, end, other
for i := range r.dates {
r.dates[i] += k
}
for i := range r.unused {
r.unused[i] += k
}
return r
}
r := &Release{
tags: tags,
end: end,
path: isPath(tags),
}
// initialize / fix tags
b.init(r)
b.fixTailGroup(r)
b.fixBracketGroup(r)
// collect tags into release
b.collect(r)
// guess type. The type the caller gave replaces the guess, which is still
// made: inspect restores a platform or an arch that was reset when it
// finds no other sign of the type, and a hint that agrees with the guess
// has to give the same release
r.Type = b.inspect(r, true)
if Unknown < h.Type && h.Type <= Series {
r.Type = h.Type
}
// special
b.specialDate(r)
// unset tags
b.unset(r)
b.titleMusicSource(r)
b.titleCollection(r)
b.fixBracketTagGroup(r)
b.fixTrailingGroup(r)
b.remuxSource(r)
// read titles
i := b.titles(r)
// fansub style names carry the release group in a leading bracket, which is
// captured as a site meta tag. surface it as the group when no group was
// otherwise found. done before unused so the last-unused-text fallback in
// unused does not claim an unrelated token as the group.
b.leadingGroup(r)
// demarcate unused
b.unused(r, i)
b.trailingGroup(r)
leadingAlt(r)
return *r
}
// leadingFlags returns how many tags the flags in brackets that open the name
// take up ('[REPACK] [Group] Show'), with the delimiters after them, or 0 when
// nothing else is left.
func leadingFlags(tags []Tag, end int) int {
bracket := func(tag Tag, s string) bool {
return tag.Is(TagTypeDelim) && len(tag.Delim()) == 1 && strings.Contains(s, tag.Delim())
}
k := 0
for k+2 < end && bracket(tags[k], "[(") && bracket(tags[k+2], "])") && tags[k+1].Is(TagTypeOther) {
if info := tags[k+1].Info(); info == nil || !isReleaseFlag(info.Tag()) {
break
}
k += 3
if k < end && tags[k].Is(TagTypeDelim, TagTypeWhitespace) && !strings.ContainsAny(tags[k].Delim(), "[(") {
k++
}
}
if k >= end {
return 0
}
return k
}
// leadingAlt reads a leading bracket of CJK script as the title in that
// script when a scene group closes the name ('[港灯].Harbor.Lights.S01-GRP'),
// where the bracket would otherwise be the site. It is left alone when it is
// the group ('[桜都字幕组] Show - 01 [1080p]'), when it names a fansub group
// ('[桜都字幕组] Show.S01E01.1080p.WEB-DL-GRP'), and when another bracket or a
// title in CJK script follows it.
func leadingAlt(r *Release) {
if len(r.Alt) != 0 || r.Site == "" || r.Group == "" || r.Group == r.Site ||
strings.ContainsFunc(r.Title, isCJK) || !cjkOnly(r.Site) || fansubMark(r.Site) {
return
}
i := 0
for ; i < len(r.tags) && r.tags[i].Is(TagTypeWhitespace, TagTypeDelim); i++ {
}
if i == len(r.tags) || !r.tags[i].Is(TagTypeMeta) || !strings.HasPrefix(strings.TrimSpace(r.tags[i].v[0]), "[") {
return
}
if k, v := r.tags[i].Meta(); k != "site" || v != r.Site {
return
}
for i++; i < len(r.tags) && r.tags[i].Is(TagTypeWhitespace, TagTypeDelim); i++ {
if strings.ContainsAny(r.tags[i].v[0], "[(【(") {
return
}
}
if i == len(r.tags) || !r.tags[i].Is(TagTypeText) {
return
}
r.Alt, r.Site = []string{r.Site}, ""
}
// isCJK reports whether c is a letter of a CJK script.
func isCJK(c rune) bool {
return unicode.In(c, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul)
}
// cjkOnly reports whether s is written in CJK script, with spaces and CJK
// punctuation ('港灯', 'ハーバー・ライツ', '항구의 불빛').
func cjkOnly(s string) bool {
return strings.ContainsFunc(s, isCJK) && !strings.ContainsFunc(s, func(c rune) bool {
return !isCJK(c) && c != ' ' && c != '·' && !(' ' <= c && c <= '〿') && c != '・' && c != 'ー'
})
}
// fansubMark reports whether s names a fansub group: subtitles (字幕),
// translation (汉化, 漢化), a studio (工作室), or a group or club (组, 組, 社).
func fansubMark(s string) bool {
return strings.Contains(s, "字幕") || strings.Contains(s, "汉化") || strings.Contains(s, "漢化") ||
strings.Contains(s, "工作室") || strings.HasSuffix(s, "组") || strings.HasSuffix(s, "組") || strings.HasSuffix(s, "社")
}
// leadingGroup sets the group from a site meta tag appearing in a leading
// bracket (ie, '[SubsPlease] Show - 04 ...'), when no group was found. A flag
// in front of it is passed over ('[REPACK] [SubsPlease] Show - 04').
func (b *TagBuilder) leadingGroup(r *Release) {
if r.Group != "" || r.Site == "" {
return
}
for i := 0; i < len(r.tags); i++ {
switch {
// only the meta lexer puts an other tag in front of the site, and
// only a flag
case r.tags[i].Is(TagTypeWhitespace, TagTypeDelim, TagTypeOther):
continue
case r.tags[i].Is(TagTypeMeta):
if k, v := r.tags[i].Meta(); k == "site" && v == r.Site {
r.Group = v
}
}
return
}
}
// trailingGroup sets the group from a site in a bracket that closes the name
// (ie, 'Show - 04 [1080p][Group].mkv'), when nothing else gave a group. It
// runs last, so that a group named in the tags is preferred ('(BD 1080p -
// Encoder)[Uploader]').
func (b *TagBuilder) trailingGroup(r *Release) {
if r.Group != "" || r.Site == "" {
return
}
for _, tag := range slices.Backward(r.tags) {
switch {
case tag.Is(TagTypeWhitespace, TagTypeDelim, TagTypeExt):
continue
case tag.Is(TagTypeMeta):
// a site given by name ('[[site:name]]', '-={name}=-') is not
// a group
if k, v := tag.Meta(); k == "site" && v == r.Site {
if s := strings.TrimSpace(tag.v[0]); strings.HasPrefix(s, "[") && !strings.HasPrefix(s, "[[") {
r.Group = v
}
return
}
continue
}
return
}
}
// fixTailGroup hands a guessed group back to the name when the name opens
// with its group in a bracket. The group lexer takes whatever follows the last
// hyphen, which is a group after a tag ('[TGx] Movie.1080p.x264-GRP'). It is
// the end of the title after a word ('[Commie] Hataraku Maou-sama!'). After a
// hyphen set off by spaces it is a note after an edition ('[Group] Movie -
// 30th Anniversary - Patch Subs'), the title of the episode after a series
// tag ('[Group] Show Episode 00 - Prologue'), and a language when the word
// names one ('[Group] Movie (BD 1080p) - VOSTFR'), which it also is right
// after another language ('VF-VOSTFR').
func (b *TagBuilder) fixTailGroup(r *Release) {
i := 0
for ; i < len(r.tags) && r.tags[i].Is(TagTypeWhitespace, TagTypeDelim); i++ {
}
if i == len(r.tags) || !r.tags[i].Is(TagTypeMeta) {
return
}
if k, _ := r.tags[i].Meta(); k != "site" {
return
}
for g := i + 2; g < len(r.tags); g++ {
if !r.tags[g].Is(TagTypeGroup) || r.tags[g].f != nil || !r.tags[g-1].Is(TagTypeDelim) || r.tags[g-1].v[0] != "-" {
continue
}
p := g - 2
for ; p > i && r.tags[p].Is(TagTypeWhitespace, TagTypeDelim); p-- {
}
// the group tag holds the spaces after the hyphen, which go to the
// delimiter for the title to read 'Chaos - Prologue'
s, grp := r.tags[g].v[0], r.tags[g].v[1]
d := "-" + s[:len(s)-len(strings.TrimLeft(s, " \t_"))]
spaced := len(d) > 1 && p != g-2 && strings.HasSuffix(r.tags[g-2].v[0], " ")
var tag Tag
switch {
case r.tags[p].Is(TagTypeText), spaced && r.tags[p].Is(TagTypeSeries, TagTypeEdition):
tag = NewTag(TagTypeText, nil, []byte(s[len(d)-1:]), []byte(grp))
case len(d) == 1 && p == g-2 && r.tags[p].Is(TagTypeOther) && afterBracket(r.tags[p-1]) && isInitials(r.tags[p].v[0], r.tags[i]):
// a hyphenated word alone after the last bracket is the mark
// of the group in the leading bracket when it begins with the
// initials of that group ('[Hakata Ramen] Show (S2) 02 [1080p
// HEVC] HR-DR'). Its first half only looks like an other tag.
// Any other word there is the tag it looks like, with the
// group after it ('[TGx] Movie (2020) [1080p] REPACK-GRP')
r.tags[p] = r.tags[p].As(TagTypeText, nil)
tag = NewTag(TagTypeText, nil, []byte(s), []byte(grp))
case spaced || r.tags[p].Is(TagTypeLanguage):
// a builder that was not initialized has no language rows
if b.languagef == nil {
continue
}
// not a row that takes any word with 'sub' or 'dub' in it
if info := b.languagef.find(grp); info == nil || strings.Contains(info.Tag(), "$") {
continue
}
tag = NewTag(TagTypeLanguage, b.languagef.fn, []byte(s[len(d)-1:]), []byte(grp))
default:
continue
}
r.tags[g-1], r.tags[g] = NewTag(TagTypeDelim, nil, []byte(d), []byte(d)), tag
if r.end == g-1 {
r.end = g + 1
}
}
}
// fixBracketGroup reads the group of a scene name that a tracker wrote out
// with brackets of tags after it, ie 'Some.Title-GROUP (2019) [Windows /
// Multi-Language / Full ISO]'. The group lexer reads no group in front of a
// bracket, nor in front of the first year, as a hyphen there is part of the
// title ('Spider-Man (2002) [1080p]', 'Artist-Album (2019) [FLAC]'). A
// platform or an arch in the brackets is what sets the scene name apart, as a
// film or a record names neither. A known group gives its type ('-CODEX').
//
// A game can still end its title in a hyphenated word ('Half-Life (1998)
// [Windows]'), so the word is the group only when it is a known group, when
// the name joins its words with dots or underscores as a scene name does, or
// when it is not written as a word is ('GROUP', 'TiNYiSO', not 'Life').
func (b *TagBuilder) fixBracketGroup(r *Release) {
if slices.ContainsFunc(r.tags, func(tag Tag) bool { return tag.Is(TagTypeGroup) }) {
return
}
o := slices.IndexFunc(r.tags, func(tag Tag) bool {
return tag.Is(TagTypeDelim) && strings.ContainsAny(tag.Delim(), "()[]{}")
})
if o < 3 || !r.tags[o-1].Is(TagTypeText) || r.tags[o-1].Retyped() ||
!r.tags[o-2].Is(TagTypeDelim) || r.tags[o-2].Delim() != "-" || r.tags[o-3].Is(TagTypeDelim, TagTypeWhitespace) {
return
}
if s := strings.TrimLeft(r.tags[o].Delim(), " ._"); s == "" || (s[0] != '(' && s[0] != '[') {
return
}
// only tags in brackets after it, and a file extension, one of which names
// what it runs on. One in front of the year was reset, and may yet be
// restored
var platform bool
for i, depth := o, 0; i < len(r.tags); i++ {
switch {
case r.tags[i].Is(TagTypeDelim):
depth = bracketDepth(r.tags[i].Delim(), depth)
case r.tags[i].Is(TagTypeWhitespace, TagTypeExt):
case depth == 0:
return
default:
platform = platform || r.tags[i].Is(TagTypePlatform, TagTypeArch) || r.tags[i].Was(TagTypePlatform, TagTypeArch)
}
}
if !platform {
return
}
tag := r.tags[o-1].as(TagTypeGroup, b.groupf)
dotted := slices.ContainsFunc(r.tags[:o-2], func(tag Tag) bool {
return tag.Is(TagTypeDelim) && (tag.Delim() == "." || tag.Delim() == "_")
})
if tag.Info() == nil && !dotted && plainWord.MatchString(tag.Group()) {
return
}
r.tags[o-1] = tag
}
// plainWord matches a word written as words are, in lower case after its
// first letter.
var plainWord = regexp.MustCompile(`^[A-Za-z][a-z]*$`)
// isInitials reports whether s is the first letters of the words of the site
// that the meta tag site holds, without regard to case ('HR' of 'Hakata
// Ramen'). A site of one word has no initials to speak of.
func isInitials(s string, site Tag) bool {
_, v := site.Meta()
words := strings.FieldsFunc(v, func(r rune) bool {
return r == ' ' || r == '_' || r == '.' || r == '-'
})
if len(words) < 2 || len(words) != len(s) {
return false
}
for i, word := range words {
if !strings.EqualFold(word[:1], s[i:i+1]) {
return false
}
}
return true
}
// afterBracket reports whether tag is a delimiter that closes a bracket and
// then a space ('] ', ') ').
func afterBracket(tag Tag) bool {
if !tag.Is(TagTypeDelim) {
return false
}
d := strings.TrimRight(tag.Delim(), " \t")
return d != "" && len(d) < len(tag.Delim()) && strings.IndexByte("])}", d[len(d)-1]) != -1
}
// init fixes the initial tag set.
func (b *TagBuilder) init(r *Release) {
b.fixWindows(r)
b.fixHalfEpisode(r)
b.fixTitleRange(r)
b.fixAudioRange(r)
b.fixFirstDate(r)
// determine earliest pivot
m, pivot := b.pivots(r, TagTypeDate, TagTypeSource, TagTypeSeries, TagTypeResolution, TagTypeVersion)
date, series := m[TagTypeDate], m[TagTypeSeries]
// reset/collect dates
if date != -1 {
r.dates = append(r.dates, date)
}
if dates := b.reset(r, date, TagTypeDate); len(dates) != 0 {
r.dates = append(r.dates, dates...)
}
// fix special tags
if date != -1 || series != -1 {
i := min(date, series)
switch {
case date == -1:
i = series
case series == -1:
i = date
}
b.fixSpecial(r, i, series != -1)
b.fixEpisodeTitle(r, i)
}
// get first text prior to pivot
end := b.end(r, pivot)
// reset language/other/arch/platform prior to end
_ = b.reset(r, end, TagTypeLanguage, TagTypeArch, TagTypePlatform)
b.fixFirst(r)
b.fixSourceWeb(r)
b.fixSourceUHD(r)
start := b.start(r, 0)
b.fixBad(r, start, end)
b.fixNoText(r, end)
b.fixIsolated(r)
b.fixWords(r)
b.fixMusic(r)
}
// fixWindows reads a bare 'Windows' as a word, unless it is an item of a list
// of tags in the brackets that close the name, which is where a tracker names
// the platform ('Some.Title-GROUP (2019) [Windows / Multi-Language / Full
// ISO]'). Anywhere else it is a word of the title ('Broken.Windows.2020',
// 'Artist - Open Windows (2019) [FLAC]', '(Windows Edition)'). So is it in a
// name with a video or an audio tag, which a film, an episode or a record has
// ('Movie.2019.1080p.WEB.H264-GRP [Windows]'). It goes back to plain text,
// which no later step restores as a platform.
func (b *TagBuilder) fixWindows(r *Release) {
media := slices.ContainsFunc(r.tags, func(tag Tag) bool {
return tag.Is(
TagTypeSeries,
TagTypeSource,
TagTypeResolution,
TagTypeFrameRate,
TagTypeCodec,
TagTypeHDR,
TagTypeBitDepth,
TagTypeAudio,
TagTypeChannels,
)
})
for i, depth := 0, 0; i < len(r.tags); i++ {
tag := r.tags[i]
switch {
case tag.Is(TagTypeDelim):
depth = bracketDepth(tag.Delim(), depth)