aboutsummaryrefslogtreecommitdiff
path: root/cgi-bin/webring_redirect.cgi
blob: 2b114cc2ba2aa01fd5bd30366de6a4b749ad9a24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#! /usr/bin/env python

import cgi
import requests
import random
import json

WEBSITE_URL = "http://nathansmith117.beevomit.org"

def handle_be_crime_do_gay_webring():
    try:
        # https://codeberg.org/artemislena/artemislena.eu#be-crime-do-gay-webring
        req = requests.get("https://artemislena.eu/services/downloads/beCrimeDoGay.json", timeout=5)
        req.raise_for_status
        return req.json()
    except requests.exceptions.Timeout:
        return "Status: 503 Service Unavailable"
    except Exception:
        return "Status: 500 Internal Error"

def handle_fields():
    form = cgi.FieldStorage()

    # Name of the webring name and direction.
    name = form.getvalue("name")
    direction = form.getvalue("direction")

    if name is None or direction is None:
        return "Not enough optinos"

    # Callbacks to handle webrings.
    webrings = {
        "gay": handle_be_crime_do_gay_webring
    }

    website_list = webrings[name]()

    if website_list == None or website_list == []:
        return "Can't get website list for webring"
    if type(website_list) is str:
        return website_list

    # Find this website in webring.
    position = 0
    
    try:
        position = website_list.index(WEBSITE_URL)
    except ValueError:
        return "Website not in webring"

    # Handle direction
    redirect_website = ""

    if direction == "next":
        redirect_website = website_list[(position + 1) % len(website_list)]
    elif direction == "previous":
        redirect_website = website_list[(position - 1) % len(website_list)]
    elif direction == "random":
        website_list.pop(position)
        redirect_website = random.choice(website_list)
    else:
        return "Invalid direction"

    return [
        f"redirecting to <a href=\"{redirect_website}\">{redirect_website}</a>",
        f"<meta http-equiv=\"refresh\" content=\"0; URL={redirect_website}\"/>"
    ]

def display_html(fields_reponse):
    print("Content-Type: text/html")

    html_text = """
        <!DOCTYPE html>
        <html>
        
        <head>
            {redirect}
            <title>Webrings</title>
        </head>

        <body>
            {fields_reponse}
        </body>
        </html>
    """

    if type(fields_reponse) is list:
        html_text = html_text.format(fields_reponse=fields_reponse[0], redirect=fields_reponse[1])
    else:
        html_text = html_text.format(fields_reponse=fields_reponse, redirect="")
        
    print(html_text)

fields_reponse = handle_fields()
display_html(fields_reponse)