shoko/Protocols/FileProtoHandler.cs

60 lines
1.5 KiB
C#
Raw Permalink Normal View History

using System.Text;
using System.Web;
2023-10-09 02:27:47 +00:00
using HeyRed.Mime;
2023-10-20 04:59:28 +00:00
using Microsoft.Win32.SafeHandles;
2023-10-02 18:49:24 +00:00
namespace Shoko;
[Protocol("file")]
class FileProtoHandler : ProtoHandler
{
public FileProtoHandler(Uri url)
{
URL = url;
}
2023-10-20 04:59:28 +00:00
long _totalBytes = -1;
public override long TotalBytes => _totalBytes;
2023-10-02 18:49:24 +00:00
2023-10-20 04:59:28 +00:00
public override async Task Load()
2023-10-02 18:49:24 +00:00
{
2023-10-09 02:27:47 +00:00
var file = HttpUtility.UrlDecode(URL.AbsolutePath);
2023-10-02 18:49:24 +00:00
if(URL.Host.Length > 0)
file = "//" + URL.Host + file;
2023-10-02 18:49:24 +00:00
2023-10-09 02:27:47 +00:00
MediaType = "text/plain";
2023-10-02 18:49:24 +00:00
Status = "OK";
if(File.Exists(file))
{
2023-10-20 04:59:28 +00:00
var fi = new FileInfo(file);
_totalBytes = fi.Length;
var stream = fi.OpenRead();
Content = await Download(stream);
MediaType = MimeGuesser.GuessMimeType(Content);
}
else if(Directory.Exists(file))
{
MediaType = "text/gemini";
var str = "# "+file+"\r\n";
var entries = Directory.EnumerateFileSystemEntries(file);
foreach(var entry in entries)
{
var path = Path.GetFileName(entry);
str += string.Format("=>{0}/{1} {2}\r\n", URL.ToString(), HttpUtility.UrlEncode(path), path);
}
Content = new MemoryStream(Encoding.UTF8.GetBytes(str));
}
else
{
Content = new MemoryStream(Encoding.UTF8.GetBytes("file not found"));
Status = "not found";
}
2023-10-20 04:59:28 +00:00
OnLoaded();
2023-10-02 18:49:24 +00:00
}
public override void Render()
{
}
}