1use crate::json::Json;
8use crate::types::{string_enum, JunkKind, Mode, VersionType};
9
10string_enum! {
11 #[non_exhaustive]
24 ModeOption {
25 Auto => "auto", Clean => "clean", Youtube => "youtube", Filename => "filename",
26 Tracklist => "tracklist",
27 }
28}
29
30string_enum! {
31 #[non_exhaustive]
45 SplitAnd { Auto => "auto", Always => "always", Never => "never" }
46}
47
48string_enum! {
49 #[non_exhaustive]
62 FeatPlacement { Source => "source", Artist => "artist", Title => "title", Omit => "omit" }
63}
64
65string_enum! {
66 #[non_exhaustive]
80 JoinerStyle { Original => "original", Canonical => "canonical" }
81}
82
83string_enum! {
84 #[non_exhaustive]
94 VersionsOption { All => "all", None => "none" }
95}
96
97#[allow(clippy::derivable_impls)] impl Default for ModeOption {
99 fn default() -> Self {
100 ModeOption::Auto
101 }
102}
103
104#[allow(clippy::derivable_impls)] impl Default for SplitAnd {
106 fn default() -> Self {
107 SplitAnd::Auto
108 }
109}
110
111#[allow(clippy::derivable_impls)] impl Default for FeatPlacement {
113 fn default() -> Self {
114 FeatPlacement::Source
115 }
116}
117
118#[allow(clippy::derivable_impls)] impl Default for JoinerStyle {
120 fn default() -> Self {
121 JoinerStyle::Original
122 }
123}
124
125#[allow(clippy::derivable_impls)] impl Default for VersionsOption {
127 fn default() -> Self {
128 VersionsOption::All
129 }
130}
131
132#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
148#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
149#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
150#[non_exhaustive]
151pub struct KeywordOptions {
152 #[cfg_attr(feature = "serde", serde(with = "crate::serde_support::pairs"))]
154 pub version_heads: Vec<(String, VersionType)>,
155 pub descriptors: Vec<String>,
157 pub genres: Vec<String>,
159 #[cfg_attr(feature = "serde", serde(with = "crate::serde_support::pairs"))]
161 pub junk: Vec<(String, JunkKind)>,
162 pub feat_markers: Vec<String>,
164}
165
166impl KeywordOptions {
167 pub fn new() -> Self {
169 Self::default()
170 }
171
172 pub fn version_head(mut self, key: impl Into<String>, version_type: VersionType) -> Self {
174 self.version_heads.push((key.into(), version_type));
175 self
176 }
177
178 pub fn descriptor(mut self, word: impl Into<String>) -> Self {
180 self.descriptors.push(word.into());
181 self
182 }
183
184 pub fn genre(mut self, word: impl Into<String>) -> Self {
186 self.genres.push(word.into());
187 self
188 }
189
190 pub fn junk(mut self, phrase: impl Into<String>, kind: JunkKind) -> Self {
192 self.junk.push((phrase.into(), kind));
193 self
194 }
195
196 pub fn feat_marker(mut self, marker: impl Into<String>) -> Self {
198 self.feat_markers.push(marker.into());
199 self
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
228#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
229#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
230#[non_exhaustive]
231pub struct ParseOptions {
232 pub mode: ModeOption,
234 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
237 pub uploader: Option<String>,
238 pub known_artists: Vec<String>,
240 pub split_and: SplitAnd,
242 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
244 pub keywords: Option<KeywordOptions>,
245}
246
247impl ParseOptions {
248 pub fn new() -> Self {
250 Self::default()
251 }
252
253 pub fn mode(mut self, mode: ModeOption) -> Self {
255 self.mode = mode;
256 self
257 }
258
259 pub fn uploader(mut self, uploader: impl Into<String>) -> Self {
261 self.uploader = Some(uploader.into());
262 self
263 }
264
265 pub fn known_artists<I, S>(mut self, names: I) -> Self
267 where
268 I: IntoIterator<Item = S>,
269 S: Into<String>,
270 {
271 self.known_artists = names.into_iter().map(Into::into).collect();
272 self
273 }
274
275 pub fn split_and(mut self, split_and: SplitAnd) -> Self {
277 self.split_and = split_and;
278 self
279 }
280
281 pub fn keywords(mut self, keywords: KeywordOptions) -> Self {
283 self.keywords = Some(keywords);
284 self
285 }
286}
287
288#[derive(Debug, Clone, PartialEq, Eq, Hash)]
304#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
305#[cfg_attr(feature = "serde", serde(default, rename_all = "camelCase"))]
306#[non_exhaustive]
307pub struct FormatOptions {
308 pub feat: FeatPlacement,
310 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
312 pub feat_marker: Option<String>,
313 pub joiners: JoinerStyle,
315 pub versions: VersionsOption,
317 pub producers: bool,
319 pub position: bool,
321 pub label: bool,
323}
324
325impl Default for FormatOptions {
326 fn default() -> Self {
327 FormatOptions {
328 feat: FeatPlacement::Source,
329 feat_marker: None,
330 joiners: JoinerStyle::Original,
331 versions: VersionsOption::All,
332 producers: true,
333 position: false,
334 label: true,
335 }
336 }
337}
338
339impl FormatOptions {
340 pub fn new() -> Self {
342 Self::default()
343 }
344
345 pub fn feat(mut self, feat: FeatPlacement) -> Self {
347 self.feat = feat;
348 self
349 }
350
351 pub fn feat_marker(mut self, marker: impl Into<String>) -> Self {
353 self.feat_marker = Some(marker.into());
354 self
355 }
356
357 pub fn joiners(mut self, joiners: JoinerStyle) -> Self {
359 self.joiners = joiners;
360 self
361 }
362
363 pub fn versions(mut self, versions: VersionsOption) -> Self {
365 self.versions = versions;
366 self
367 }
368
369 pub fn producers(mut self, producers: bool) -> Self {
371 self.producers = producers;
372 self
373 }
374
375 pub fn position(mut self, position: bool) -> Self {
377 self.position = position;
378 self
379 }
380
381 pub fn label(mut self, label: bool) -> Self {
383 self.label = label;
384 self
385 }
386}
387
388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub(crate) enum Requested {
395 Auto,
396 Mode(Mode),
397 Other,
398}
399
400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402pub(crate) enum SplitAndMode {
403 Auto,
404 Always,
405 Never,
406}
407
408#[derive(Debug, Clone, Default, PartialEq, Eq)]
411pub(crate) struct Keywords {
412 pub version_heads: Vec<(String, String)>,
413 pub descriptors: Vec<String>,
414 pub genres: Vec<String>,
415 pub junk: Vec<(String, String)>,
416 pub feat_markers: Vec<String>,
417}
418
419#[derive(Debug, Clone, PartialEq, Eq)]
420pub(crate) struct Resolved {
421 pub mode: Requested,
422 pub uploader: Option<String>,
423 pub known_artists: Vec<String>,
424 pub split_and: SplitAndMode,
425 pub keywords: Option<Keywords>,
427}
428
429impl Default for Resolved {
430 fn default() -> Self {
431 Resolved {
432 mode: Requested::Auto,
433 uploader: None,
434 known_artists: Vec::new(),
435 split_and: SplitAndMode::Auto,
436 keywords: None,
437 }
438 }
439}
440
441fn array_index(key: &str) -> Option<u64> {
443 if key.is_empty() || key.len() > 10 || !key.bytes().all(|b| b.is_ascii_digit()) {
444 return None;
445 }
446 if key.len() > 1 && key.starts_with('0') {
447 return None;
448 }
449 key.parse::<u64>().ok().filter(|n| *n <= 0xffff_fffe)
450}
451
452pub(crate) fn js_entries<V: Clone>(pairs: &[(String, V)]) -> Vec<(String, V)> {
456 let mut unique: Vec<(String, V)> = Vec::with_capacity(pairs.len());
457 let mut index: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
458 for (k, v) in pairs {
459 match index.get(k.as_str()).and_then(|&i| unique.get_mut(i)) {
460 Some(slot) => slot.1 = v.clone(),
461 None => {
462 index.insert(k.as_str(), unique.len());
463 unique.push((k.clone(), v.clone()));
464 }
465 }
466 }
467 let mut ints: Vec<(u64, (String, V))> = Vec::new();
468 let mut rest: Vec<(String, V)> = Vec::new();
469 for pair in unique {
470 match array_index(&pair.0) {
471 Some(n) => ints.push((n, pair)),
472 None => rest.push(pair),
473 }
474 }
475 ints.sort_by_key(|(n, _)| *n);
476 ints.into_iter().map(|(_, p)| p).chain(rest).collect()
477}
478
479pub(crate) fn string_list(value: Option<&Json>) -> Vec<String> {
481 match value {
482 Some(Json::Arr(items)) => {
483 items.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()
484 }
485 _ => Vec::new(),
486 }
487}
488
489pub(crate) fn string_entries(value: Option<&Json>) -> Vec<(String, String)> {
491 match value {
492 Some(Json::Obj(entries)) => js_entries(entries)
493 .into_iter()
494 .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_string())))
495 .collect(),
496 _ => Vec::new(),
497 }
498}
499
500impl Keywords {
501 fn from_json(value: &Json) -> Keywords {
502 Keywords {
503 version_heads: string_entries(value.get("versionHeads")),
504 descriptors: string_list(value.get("descriptors")),
505 genres: string_list(value.get("genres")),
506 junk: string_entries(value.get("junk")),
507 feat_markers: string_list(value.get("featMarkers")),
508 }
509 }
510
511 fn from_typed(k: &KeywordOptions) -> Keywords {
512 let heads: Vec<(String, String)> =
513 k.version_heads.iter().map(|(key, t)| (key.clone(), t.as_str().to_string())).collect();
514 let junk: Vec<(String, String)> =
515 k.junk.iter().map(|(key, kind)| (key.clone(), kind.as_str().to_string())).collect();
516 Keywords {
517 version_heads: js_entries(&heads),
518 descriptors: k.descriptors.clone(),
519 genres: k.genres.clone(),
520 junk: js_entries(&junk),
521 feat_markers: k.feat_markers.clone(),
522 }
523 }
524}
525
526impl Resolved {
527 pub(crate) fn from_json(options: &Json) -> Resolved {
529 if options.as_object().is_none() {
530 return Resolved::default(); }
532 let mode = match options.get("mode") {
533 None | Some(Json::Null) => Requested::Auto, Some(Json::Str(s)) if s == "auto" => Requested::Auto,
535 Some(Json::Str(s)) => Mode::from_name(s).map_or(Requested::Other, Requested::Mode),
536 Some(_) => Requested::Other,
537 };
538 let split_and = match options.get("splitAnd") {
539 None | Some(Json::Null) => SplitAndMode::Auto, Some(Json::Str(s)) if s == "auto" => SplitAndMode::Auto,
541 Some(Json::Str(s)) if s == "never" => SplitAndMode::Never,
542 Some(_) => SplitAndMode::Always,
543 };
544 let keywords = match options.get("keywords") {
546 Some(k @ Json::Obj(_)) => Some(Keywords::from_json(k)),
547 _ => None,
548 };
549 Resolved {
550 mode,
551 uploader: options.get("uploader").and_then(Json::as_str).map(str::to_string),
552 known_artists: string_list(options.get("knownArtists")),
553 split_and,
554 keywords,
555 }
556 }
557
558 pub(crate) fn from_typed(options: &ParseOptions) -> Resolved {
559 Resolved {
560 mode: match options.mode {
561 ModeOption::Auto => Requested::Auto,
562 ModeOption::Clean => Requested::Mode(Mode::Clean),
563 ModeOption::Youtube => Requested::Mode(Mode::Youtube),
564 ModeOption::Filename => Requested::Mode(Mode::Filename),
565 ModeOption::Tracklist => Requested::Mode(Mode::Tracklist),
566 },
567 uploader: options.uploader.clone(),
568 known_artists: options.known_artists.clone(),
569 split_and: match options.split_and {
570 SplitAnd::Auto => SplitAndMode::Auto,
571 SplitAnd::Always => SplitAndMode::Always,
572 SplitAnd::Never => SplitAndMode::Never,
573 },
574 keywords: options.keywords.as_ref().map(Keywords::from_typed),
575 }
576 }
577}
578
579#[derive(Debug, Clone, Copy, PartialEq, Eq)]
581pub(crate) enum FeatMode {
582 Source,
583 Artist,
584 Title,
585 Omit,
586}
587
588#[derive(Debug, Clone, PartialEq, Eq)]
589pub(crate) struct ResolvedFormat {
590 pub feat: FeatMode,
591 pub feat_marker: Option<String>,
592 pub canonical: bool,
593 pub versions: bool,
594 pub producers: bool,
595 pub position: bool,
596 pub label: bool,
597}
598
599fn truthy(v: &Json) -> bool {
601 match v {
602 Json::Null => false,
603 Json::Bool(b) => *b,
604 Json::Num(n) => *n != 0.0 && !n.is_nan(),
605 Json::Str(s) => !s.is_empty(),
606 Json::Arr(_) | Json::Obj(_) => true,
607 }
608}
609
610fn js_string(v: &Json) -> String {
612 match v {
613 Json::Null => "null".to_string(),
614 Json::Bool(b) => b.to_string(),
615 Json::Num(n) if n.is_nan() => "NaN".to_string(),
616 Json::Num(n) if n.is_infinite() => {
617 (if *n > 0.0 { "Infinity" } else { "-Infinity" }).to_string()
618 }
619 Json::Num(_) => v.write(),
620 Json::Str(s) => s.clone(),
621 Json::Arr(items) => items
623 .iter()
624 .map(|i| if matches!(i, Json::Null) { String::new() } else { js_string(i) })
625 .collect::<Vec<_>>()
626 .join(","),
627 Json::Obj(_) => "[object Object]".to_string(),
628 }
629}
630
631impl ResolvedFormat {
632 pub(crate) fn from_json(o: &Json) -> ResolvedFormat {
634 let get = |key: &str| match o.get(key) {
635 Some(Json::Null) | None => None,
636 Some(v) => Some(v),
637 };
638 ResolvedFormat {
639 feat: match get("feat") {
640 None => FeatMode::Source,
641 Some(Json::Str(s)) if s == "source" => FeatMode::Source,
642 Some(Json::Str(s)) if s == "artist" => FeatMode::Artist,
643 Some(Json::Str(s)) if s == "title" => FeatMode::Title,
644 Some(_) => FeatMode::Omit,
645 },
646 feat_marker: o.get("featMarker").map(js_string),
648 canonical: get("joiners").and_then(Json::as_str) == Some("canonical"),
649 versions: get("versions").map_or(true, |v| v.as_str() == Some("all")),
650 producers: get("producers").map_or(true, truthy),
651 position: get("position").is_some_and(truthy),
652 label: get("label").map_or(true, truthy),
653 }
654 }
655
656 pub(crate) fn from_typed(o: &FormatOptions) -> ResolvedFormat {
657 ResolvedFormat {
658 feat: match o.feat {
659 FeatPlacement::Source => FeatMode::Source,
660 FeatPlacement::Artist => FeatMode::Artist,
661 FeatPlacement::Title => FeatMode::Title,
662 FeatPlacement::Omit => FeatMode::Omit,
663 },
664 feat_marker: o.feat_marker.clone(),
665 canonical: o.joiners == JoinerStyle::Canonical,
666 versions: o.versions == VersionsOption::All,
667 producers: o.producers,
668 position: o.position,
669 label: o.label,
670 }
671 }
672}