This repository has been archived on 2021-12-22. You can view files and clone it, but cannot push or open issues or pull requests.
tkGemini/gemini.py

71 lines
2.5 KiB
Python

# Copyright 2020 Romain de Laage
#
# This file is part of tkGemini.
#
# tkGemini is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# any later version.
#
# tkGemini is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with tkGemini. If not, see <https://www.gnu.org/licenses/>.
import socket
import ssl
import urllib.parse
# See https://tildegit.org/solderpunk/gemini-demo-1/src/branch/master/gemini-demo.py
# See also https://gemini.circumlunar.space/docs/specification.html for more details
class Request():
def __init__(self, url):
self.url = url
parsed_url = urllib.parse.urlparse(self.url)
if ":" in parsed_url.netloc:
self.hostname, self.port = parsed_url.netloc.split(":")
else:
self.hostname = parsed_url.netloc
self.port = 1965
def makeRequest(self):
try:
# Create socket
s = socket.create_connection((self.hostname, self.port))
context = ssl.SSLContext()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
s = context.wrap_socket(s, server_hostname = self.hostname)
# Send request
s.sendall((self.url + '\r\n').encode("UTF-8"))
# Receive the answer
fp = s.makefile("rb")
# Read header
self.header = fp.readline().decode("UTF-8").strip()
self.status = self.header[0:2]
self.meta = self.header[3:]
# Handle errors
if self.status[0] == "4" or self.status[0] == "5":
# There is an error and no content so we display error code and error message
self.content = "Error " + self.status + " : " + self.meta
else:
# Read the content
self.content = fp.read().decode("UTF-8")
# Return the status code
return self.status
# Something went wrong during the connecgtion to the server
except Exception as err:
self.meta = err
self.content = str(err)
return "err"