Files
add-to-tytd/src/program.tcross
2026-07-20 18:37:42 -05:00

68 lines
1.4 KiB
Plaintext

class MyWebApp {
private fileServer;
private mountable;
private pages;
public MyWebApp()
{
this.fileServer = new FileServer(embeddir("/"), true, false);
this.mountable = new MountableServer((ctx)=>{
const page = this.pages.[ctx.Path];
if(TypeIsDefined(page)) return page(ctx);
return false;
});
this.mountable.Mount("/dist/",this.fileServer);
this.pages = {
.["/"] = Index,
.["/ratelimit"] = RateLimit
};
}
public Handle(ctx)
{
return this.mountable.Handle(ctx);
}
public Close()
{
this.mountable = null;
}
}
const tytd_url = Env["TYTD_URL"];
const tytd_apikey = Env["TYTD_APIKEY"];
func WebAppMain(args)
{
if(!TypeIsString(tytd_url) || !TypeIsString(tytd_apikey))
{
Console.WriteLine("Define the environment variables TYTD_URL and TYTD_APIKEY");
return 1;
}
return new MyWebApp();
}
func RateLimit(ctx)
{
ctx.WithMimeType("text/html").SendStream(embedstrm("ratelimit.html"));
return true;
}
const mtx = new Mutex();
var lastRequest = 0;
func needsToRateLimit()
{
const time = DateTime.Now;
mtx.Lock();
const lastTime = lastRequest;
mtx.Unlock();
if(lastTime + 10 > time)
return true;
mtx.Lock();
lastRequest = time;
mtx.Unlock();
return false;
}