diff --git a/bin/handlers/README.md b/bin/handlers/README.md index a2c28c2b..60d8e23c 100644 --- a/bin/handlers/README.md +++ b/bin/handlers/README.md @@ -21,6 +21,7 @@ each plugin must define a `main()` which takes 3 arguments; ## on404 * [redirect.py](redirect.py) sends an HTTP 301 or 302, redirecting the client to another page/file +* [randpic.py](randpic.py) redirects `/foo/bar/randpic.jpg` to a random pic in `/foo/bar/` * [sorry.py](answer.py) replies with a custom message instead of the usual 404 * [nooo.py](nooo.py) replies with an endless noooooooooooooo * [never404.py](never404.py) 100% guarantee that 404 will never be a thing again as it automatically creates dummy files whenever necessary diff --git a/bin/handlers/randpic.py b/bin/handlers/randpic.py new file mode 100644 index 00000000..43ec9125 --- /dev/null +++ b/bin/handlers/randpic.py @@ -0,0 +1,35 @@ +import os +import random +from urllib.parse import quote + + +# assuming /foo/bar/ is a valid URL but /foo/bar/randpic.png does not exist, +# hijack the 404 with a redirect to a random pic in that folder +# +# thx to lia & kipu for the idea + + +def main(cli, vn, rem): + req_fn = rem.split("/")[-1] + if not cli.can_read or not req_fn.startswith("randpic"): + return + + req_abspath = vn.canonical(rem) + req_ap_dir = os.path.dirname(req_abspath) + files_in_dir = os.listdir(req_ap_dir) + + if "." in req_fn: + file_ext = "." + req_fn.split(".")[-1] + files_in_dir = [x for x in files_in_dir if x.lower().endswith(file_ext)] + + if not files_in_dir: + return + + selected_file = random.choice(files_in_dir) + + req_url = "/".join([vn.vpath, rem]).strip("/") + req_dir = req_url.rsplit("/", 1)[0] + new_url = "/".join([req_dir, quote(selected_file)]).strip("/") + + cli.reply(b"redirecting...", 302, headers={"Location": "/" + new_url}) + return "true"