shoko/Protocols/FileProtoHandler.cs

56 lines
1.3 KiB
C#

using System.Text;
using System.Web;
using HeyRed.Mime;
namespace Shoko;
[Protocol("file")]
class FileProtoHandler : ProtoHandler
{
public FileProtoHandler(Uri url)
{
URL = url;
}
public override void Load()
{
var file = HttpUtility.UrlDecode(URL.AbsolutePath);
if(URL.Host.Length > 0)
file = "//" + URL.Host + file;
MediaType = "text/plain";
Status = "OK";
if(File.Exists(file))
{
var stream = new FileStream(file, FileMode.Open);
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";
}
Loaded = true;
}
public override void Render()
{
}
}