--- /dev/null
+"""Parse fortune database files and get fortunes.
+
+Open and parse fortunes-mod database files into a
+cache and get random fortunes from that cache.
+
+Example:
+ for db in ["de/unfug", "de/computer"]:
+ bbs.fortune.load_database(db)
+ print(bbs.fortune.get())
+"""
+
+import os
+import re
+import random
+
+
+# All fortunes read from databases using `load_database()`.
+fortunes = []
+
+
+def load_database(db: str, db_location: str = "/usr/share/games/fortunes"):
+ """Parse a fortunes-mod database and add the fortunes to a cache.
+
+ Read all fortunes from a database file and store them in the global
+ variable *fortunes*.
+
+ Args:
+ db: The database name, like "bofh-excuses" or "de/computer"
+ db_location: The direcory where your fortunes databases are stored.
+ Defaults to /usr/share/games/fortunes, which is used on Debian.
+ """
+ global fortunes
+
+ dbfile = os.path.join(db_location, db)
+ f = open(dbfile, "r")
+ db_fortunes = re.split(r'\r?\n%\r?\n', f.read())
+ f.close()
+
+ fortunes += db_fortunes
+
+ # # @see https://codeberg.org/jamesansley/fortune
+ # text = [fortune for fortune in text if fortune.strip("\n\r")]
+ # fortunes += text
+
+
+def get():
+ global fortunes
+ if len(fortunes) < 1:
+ load_database()
+
+ return random.choice(fortunes)
+
+
+def main():
+ if len(sys.argv) > 1:
+ for arg in sys.argv[1:]:
+ if arg[0] != "-":
+ load_database(arg)
+
+ print(get())
+
+
+if __name__ == "__main__":
+ main()
+
--- /dev/null
+"""QOTD server using socketserver.
+
+TODO
+"""
+
+
+import sys
+import os
+import socketserver
+import bbs.fortune
+
+
+class QOTDHandler(socketserver.StreamRequestHandler):
+ def handle(self):
+ quote = bbs.fortune.get()
+ self.wfile.write(quote.encode("utf-8") + b"\n")
+
+
+def main(fortune_databases: list = ["bofh-excuses", "de/unfug", "de/computer"]):
+ try:
+ PORT = int(os.getenv("QOTD_PORT", 17))
+ except ValueError:
+ print("Environment variable QOTD_PORT is not a valid integer. Falling back to port 17.", file=sys.stderr)
+ PORT = 17
+
+ for db in fortune_databases:
+ bbs.fortune.load_database(db)
+
+ listen_on = ("", PORT)
+
+ try:
+ server = socketserver.TCPServer(
+ listen_on,
+ QOTDHandler
+ )
+ except OSError:
+ print("Failed to bind to TCP socket " + str(listen_on), file=sys.stderr)
+ sys.exit(2)
+
+ try:
+ server.serve_forever()
+
+ except KeyboardInterrupt:
+ print("\nCtr+C pressed.\nStopping...")
+ server.shutdown()
+ server.server_close()
+
+
+if __name__=='__main__':
+ main()
+