webmusic/Pages/Index.cshtml.cs
2021-07-25 23:35:22 +02:00

107 lines
3.1 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace webmusic.Pages {
public class IndexModel : PageModel {
private const string Root = "music";
public List<string> Dirs = new();
public string Displaypath = "";
public List<string> Files = new();
public string Fullpath = "";
public string Path = "";
public string PathOneup = "";
public void OnGet() {
if (Request.QueryString.HasValue)
if (Request.QueryString.Value != null)
Path = HttpUtility.UrlDecode(Request.QueryString.Value.TrimStart('?').Replace("+", "%2B"));
if (Path.Contains("/..")) {
Response.Redirect("/Error");
return;
}
if (Path.EndsWith(".m3u"))
Path = Path.Substring(0, Path.Length - 4);
if (Path.EndsWith(".lrc"))
return;
PathOneup = Regex.Match(Path, @".*(?=\/)").Value;
Fullpath = Root + Path;
Displaypath = string.IsNullOrWhiteSpace(Path) ? "/" : Path;
Dirs = Directory.GetDirectories(Fullpath).Select(System.IO.Path.GetFileName).ToList();
Dirs.RemoveAll(p => p.StartsWith("."));
Dirs.Sort();
Files = Directory.GetFiles(Fullpath).Select(System.IO.Path.GetFileName).ToList();
Files.RemoveAll(p => p.EndsWith(".m3u"));
Files.RemoveAll(p => p.EndsWith(".lrc"));
Files.RemoveAll(p => p.StartsWith("."));
Files.Sort(new NaturalSortComparer());
}
public static string Encode(string str) => str.Replace("\"", "%22").Replace("'", "%27").Replace("?", "%3F").Replace("&", "%26").Replace(" ", "%20");
private class NaturalSortComparer : IComparer<string>, IDisposable {
private readonly bool _isAscending;
public NaturalSortComparer(bool inAscendingOrder = true) {
_isAscending = inAscendingOrder;
}
int IComparer<string>.Compare(string x, string y) {
if (x == y)
return 0;
if (!_table.TryGetValue(x!, out var x1)) {
x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
_table.Add(x, x1);
}
if (!_table.TryGetValue(y!, out var y1)) {
y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
_table.Add(y, y1);
}
int returnVal;
for (var i = 0; i < x1.Length && i < y1.Length; i++) {
if (x1[i] != y1[i]) {
returnVal = PartCompare(x1[i], y1[i]);
return _isAscending ? returnVal : -returnVal;
}
}
if (y1.Length > x1.Length) {
returnVal = 1;
}
else if (x1.Length > y1.Length) {
returnVal = -1;
}
else {
returnVal = 0;
}
return _isAscending ? returnVal : -returnVal;
}
private static int PartCompare(string left, string right) {
if (!int.TryParse(left, out var x))
return string.Compare(left, right, StringComparison.Ordinal);
return !int.TryParse(right, out var y) ? string.Compare(left, right, StringComparison.Ordinal) : x.CompareTo(y);
}
private Dictionary<string, string[]> _table = new();
public void Dispose() {
_table.Clear();
_table = null;
}
}
}
}