shoko/Protocols/FileProtoHandler.cs

56 lines
1.3 KiB
C#
Raw Normal View History

using System.Text;
using System.Web;
2023-10-09 02:27:47 +00:00
using HeyRed.Mime;
2023-10-02 18:49:24 +00:00
namespace Shoko;
[Protocol("file")]
class FileProtoHandler : ProtoHandler
{
public FileProtoHandler(Uri url)
{
URL = url;
}
public override void Load()
{
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))
{
var stream = new FileStream(file, FileMode.Open);
2023-10-09 02:27:47 +00:00
MediaType = MimeGuesser.GuessMimeType(stream);
Content = stream;
}
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-02 18:49:24 +00:00
Loaded = true;
}
public override void Render()
{
}
}