-
Notifications
You must be signed in to change notification settings - Fork 0
/
FilterQueryParser.cs
466 lines (375 loc) · 18.4 KB
/
FilterQueryParser.cs
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
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Screens.Select
{
/// <summary>
/// Utility class used for parsing song select filter queries entered via the search box.
/// </summary>
public static class FilterQueryParser
{
private static readonly Regex query_syntax_regex = new Regex(
@"\b(?<key>\w+)(?<op>(:|=|(>|<)(:|=)?))(?<value>("".*"")|(\S*))",
RegexOptions.Compiled | RegexOptions.IgnoreCase);
internal static void ApplyQueries(FilterCriteria criteria, string query)
{
foreach (Match match in query_syntax_regex.Matches(query))
{
string key = match.Groups["key"].Value.ToLowerInvariant();
var op = parseOperator(match.Groups["op"].Value);
string value = match.Groups["value"].Value;
if (tryParseKeywordCriteria(criteria, key, value, op))
query = query.Replace(match.ToString(), "");
}
criteria.SearchText = query;
}
private static bool tryParseKeywordCriteria(FilterCriteria criteria, string key, string value, Operator op)
{
switch (key)
{
case "star":
case "stars":
return TryUpdateCriteriaRange(ref criteria.StarDifficulty, op, value, 0.01d / 2);
case "ar":
return TryUpdateCriteriaRange(ref criteria.ApproachRate, op, value);
case "dr":
case "hp":
return TryUpdateCriteriaRange(ref criteria.DrainRate, op, value);
case "cs":
return TryUpdateCriteriaRange(ref criteria.CircleSize, op, value);
case "od":
return TryUpdateCriteriaRange(ref criteria.OverallDifficulty, op, value);
case "bpm":
return TryUpdateCriteriaRange(ref criteria.BPM, op, value, 0.01d / 2);
case "length":
return tryUpdateLengthRange(criteria, op, value);
case "played":
case "lastplayed":
return tryUpdateDateRange(ref criteria.LastPlayed, op, value);
case "divisor":
return TryUpdateCriteriaRange(ref criteria.BeatDivisor, op, value, tryParseInt);
case "status":
return TryUpdateCriteriaRange(ref criteria.OnlineStatus, op, value, tryParseEnum);
case "creator":
return TryUpdateCriteriaText(ref criteria.Creator, op, value);
case "artist":
return TryUpdateCriteriaText(ref criteria.Artist, op, value);
default:
return criteria.RulesetCriteria?.TryParseCustomKeywordCriteria(key, op, value) ?? false;
}
}
private static Operator parseOperator(string value)
{
switch (value)
{
case "=":
case ":":
return Operator.Equal;
case "<":
return Operator.Less;
case "<=":
case "<:":
return Operator.LessOrEqual;
case ">":
return Operator.Greater;
case ">=":
case ">:":
return Operator.GreaterOrEqual;
default:
throw new ArgumentOutOfRangeException(nameof(value), $"Unsupported operator {value}");
}
}
private static int getLengthScale(string value) =>
value.EndsWith("ms", StringComparison.Ordinal) ? 1 :
value.EndsWith('s') ? 1000 :
value.EndsWith('m') ? 60000 :
value.EndsWith('h') ? 3600000 :
value.EndsWith('d') ? 86400000 : 1000;
private static bool tryParseFloatWithPoint(string value, out float result) =>
float.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result);
private static bool tryParseDoubleWithPoint(string value, out double result) =>
double.TryParse(value, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out result);
private static bool tryParseInt(string value, out int result) =>
int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out result);
private static bool tryParseEnum<TEnum>(string value, out TEnum result) where TEnum : struct
{
// First try an exact match.
if (Enum.TryParse(value, true, out result))
return true;
// Then try a prefix match.
string? prefixMatch = Enum.GetNames(typeof(TEnum)).FirstOrDefault(name => name.StartsWith(value, true, CultureInfo.InvariantCulture));
if (prefixMatch == null)
return false;
return Enum.TryParse(prefixMatch, true, out result);
}
private static GroupCollection? tryMatchRegex(string value, string regex)
{
Match matches = Regex.Match(value, regex);
if (matches.Success)
return matches.Groups;
return null;
}
/// <summary>
/// Attempts to parse a keyword filter with the specified <paramref name="op"/> and textual <paramref name="value"/>.
/// If the value indicates a valid textual filter, the function returns <c>true</c> and the resulting data is stored into
/// <paramref name="textFilter"/>.
/// </summary>
/// <param name="textFilter">The <see cref="FilterCriteria.OptionalTextFilter"/> to store the parsed data into, if successful.</param>
/// <param name="op">
/// The operator for the keyword filter.
/// Only <see cref="Operator.Equal"/> is valid for textual filters.
/// </param>
/// <param name="value">The value of the keyword filter.</param>
public static bool TryUpdateCriteriaText(ref FilterCriteria.OptionalTextFilter textFilter, Operator op, string value)
{
switch (op)
{
case Operator.Equal:
textFilter.SearchTerm = value.Trim('"');
return true;
default:
return false;
}
}
/// <summary>
/// Attempts to parse a keyword filter of type <see cref="float"/>
/// from the specified <paramref name="op"/> and <paramref name="val"/>.
/// If <paramref name="val"/> can be parsed as a <see cref="float"/>, the function returns <c>true</c>
/// and the resulting range constraint is stored into <paramref name="range"/>.
/// </summary>
/// <param name="range">
/// The <see cref="float"/>-typed <see cref="FilterCriteria.OptionalRange{T}"/>
/// to store the parsed data into, if successful.
/// </param>
/// <param name="op">The operator for the keyword filter.</param>
/// <param name="val">The value of the keyword filter.</param>
/// <param name="tolerance">Allowed tolerance of the parsed range boundary value.</param>
public static bool TryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<float> range, Operator op, string val, float tolerance = 0.05f)
=> tryParseFloatWithPoint(val, out float value) && tryUpdateCriteriaRange(ref range, op, value, tolerance);
private static bool tryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<float> range, Operator op, float value, float tolerance = 0.05f)
{
switch (op)
{
default:
return false;
case Operator.Equal:
range.Min = value - tolerance;
range.Max = value + tolerance;
break;
case Operator.Greater:
range.Min = value + tolerance;
break;
case Operator.GreaterOrEqual:
range.Min = value - tolerance;
break;
case Operator.Less:
range.Max = value - tolerance;
break;
case Operator.LessOrEqual:
range.Max = value + tolerance;
break;
}
return true;
}
/// <summary>
/// Attempts to parse a keyword filter of type <see cref="double"/>
/// from the specified <paramref name="op"/> and <paramref name="val"/>.
/// If <paramref name="val"/> can be parsed as a <see cref="double"/>, the function returns <c>true</c>
/// and the resulting range constraint is stored into <paramref name="range"/>.
/// </summary>
/// <param name="range">
/// The <see cref="double"/>-typed <see cref="FilterCriteria.OptionalRange{T}"/>
/// to store the parsed data into, if successful.
/// </param>
/// <param name="op">The operator for the keyword filter.</param>
/// <param name="val">The value of the keyword filter.</param>
/// <param name="tolerance">Allowed tolerance of the parsed range boundary value.</param>
public static bool TryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<double> range, Operator op, string val, double tolerance = 0.05)
=> tryParseDoubleWithPoint(val, out double value) && tryUpdateCriteriaRange(ref range, op, value, tolerance);
private static bool tryUpdateCriteriaRange(ref FilterCriteria.OptionalRange<double> range, Operator op, double value, double tolerance = 0.05)
{
switch (op)
{
default:
return false;
case Operator.Equal:
range.Min = value - tolerance;
range.Max = value + tolerance;
break;
case Operator.Greater:
range.Min = value + tolerance;
break;
case Operator.GreaterOrEqual:
range.Min = value - tolerance;
break;
case Operator.Less:
range.Max = value - tolerance;
break;
case Operator.LessOrEqual:
range.Max = value + tolerance;
break;
}
return true;
}
/// <summary>
/// Used to determine whether the string value <paramref name="val"/> can be converted to type <typeparamref name="T"/>.
/// If conversion can be performed, the delegate returns <c>true</c>
/// and the conversion result is returned in the <c>out</c> parameter <paramref name="parsed"/>.
/// </summary>
/// <param name="val">The string value to attempt parsing for.</param>
/// <param name="parsed">The parsed value, if conversion is possible.</param>
public delegate bool TryParseFunction<T>(string val, out T parsed);
/// <summary>
/// Attempts to parse a keyword filter of type <typeparamref name="T"/>,
/// from the specified <paramref name="op"/> and <paramref name="val"/>.
/// If <paramref name="val"/> can be parsed into <typeparamref name="T"/> using <paramref name="parseFunction"/>, the function returns <c>true</c>
/// and the resulting range constraint is stored into <paramref name="range"/>.
/// </summary>
/// <param name="range">The <see cref="FilterCriteria.OptionalRange{T}"/> to store the parsed data into, if successful.</param>
/// <param name="op">The operator for the keyword filter.</param>
/// <param name="val">The value of the keyword filter.</param>
/// <param name="parseFunction">Function used to determine if <paramref name="val"/> can be converted to type <typeparamref name="T"/>.</param>
public static bool TryUpdateCriteriaRange<T>(ref FilterCriteria.OptionalRange<T> range, Operator op, string val, TryParseFunction<T> parseFunction)
where T : struct
=> parseFunction.Invoke(val, out var converted) && tryUpdateCriteriaRange(ref range, op, converted);
private static bool tryUpdateCriteriaRange<T>(ref FilterCriteria.OptionalRange<T> range, Operator op, T value)
where T : struct
{
switch (op)
{
default:
return false;
case Operator.Equal:
range.IsLowerInclusive = range.IsUpperInclusive = true;
range.Min = value;
range.Max = value;
break;
case Operator.Greater:
range.IsLowerInclusive = false;
range.Min = value;
break;
case Operator.GreaterOrEqual:
range.IsLowerInclusive = true;
range.Min = value;
break;
case Operator.Less:
range.IsUpperInclusive = false;
range.Max = value;
break;
case Operator.LessOrEqual:
range.IsUpperInclusive = true;
range.Max = value;
break;
}
return true;
}
private static bool tryUpdateLengthRange(FilterCriteria criteria, Operator op, string val)
{
List<string> parts = new List<string>();
GroupCollection? match = null;
match ??= tryMatchRegex(val, @"^((?<hours>\d+):)?(?<minutes>\d+):(?<seconds>\d+)$");
match ??= tryMatchRegex(val, @"^((?<hours>\d+(\.\d+)?)h)?((?<minutes>\d+(\.\d+)?)m)?((?<seconds>\d+(\.\d+)?)s)?$");
match ??= tryMatchRegex(val, @"^(?<seconds>\d+(\.\d+)?)$");
if (match == null)
return false;
if (match["seconds"].Success)
parts.Add(match["seconds"].Value + "s");
if (match["minutes"].Success)
parts.Add(match["minutes"].Value + "m");
if (match["hours"].Success)
parts.Add(match["hours"].Value + "h");
double totalLength = 0;
int minScale = 3600000;
for (int i = 0; i < parts.Count; i++)
{
string part = parts[i];
string partNoUnit = part.TrimEnd('m', 's', 'h');
if (!tryParseDoubleWithPoint(partNoUnit, out double length))
return false;
if (i != parts.Count - 1 && length >= 60)
return false;
if (i != 0 && partNoUnit.Contains('.'))
return false;
int scale = getLengthScale(part);
totalLength += length * scale;
minScale = Math.Min(minScale, scale);
}
return tryUpdateCriteriaRange(ref criteria.Length, op, totalLength, minScale / 2.0);
}
private static bool tryUpdateDateRange(ref FilterCriteria.OptionalRange<DateTimeOffset> dateRange, Operator op, string val)
{
GroupCollection? match = null;
match ??= tryMatchRegex(val, @"^((?<years>\d+(\.\d+)?)y)?((?<months>\d+(\.\d+)?)M)?((?<days>\d+(\.\d+)?)d)?((?<hours>\d+(\.\d+)?)h)?((?<minutes>\d+(\.\d+)?)m)?((?<seconds>\d+(\.\d+)?)s)?$");
match ??= tryMatchRegex(val, @"^(?<days>\d+(\.\d+)?)$");
if (match == null)
return false;
DateTimeOffset dateTimeOffset = DateTimeOffset.Now;
try
{
List<string> keys = new List<string> { "seconds", "minutes", "hours", "days", "months", "years" };
foreach (string key in keys)
{
if (match[key].Success)
{
if (!tryParseDoubleWithPoint(match[key].Value, out double length))
return false;
switch (key)
{
case "seconds":
dateTimeOffset = dateTimeOffset.AddSeconds(-length);
break;
case "minutes":
dateTimeOffset = dateTimeOffset.AddMinutes(-length);
break;
case "hours":
dateTimeOffset = dateTimeOffset.AddHours(-length);
break;
case "days":
dateTimeOffset = dateTimeOffset.AddDays(-length);
break;
case "months":
dateTimeOffset = dateTimeOffset.AddMonths(-(int)Math.Floor(length));
dateTimeOffset = dateTimeOffset.AddDays(-30 * (length - Math.Floor(length)));
break;
case "years":
dateTimeOffset = dateTimeOffset.AddYears(-(int)Math.Floor(length));
dateTimeOffset = dateTimeOffset.AddDays(-365 * (length - Math.Floor(length)));
break;
}
}
}
}
// If DateTime to compare is out-scope put it to Min
catch (Exception)
{
dateTimeOffset = DateTimeOffset.MinValue;
dateTimeOffset = dateTimeOffset.AddMilliseconds(1);
}
return tryUpdateCriteriaRange(ref dateRange, invert(op), dateTimeOffset);
}
// Function to reverse an Operator
private static Operator invert(Operator ope)
{
switch (ope)
{
default:
return Operator.Equal;
case Operator.Equal:
return Operator.Equal;
case Operator.Greater:
return Operator.Less;
case Operator.GreaterOrEqual:
return Operator.LessOrEqual;
case Operator.Less:
return Operator.Greater;
case Operator.LessOrEqual:
return Operator.GreaterOrEqual;
}
}
}
}