umstellung auf requests

modul mastodon gegen requests getauscht, import exceptions eingefuegt,
InitException wieder entfernt
This commit is contained in:
+++ 2022-07-14 21:47:16 +02:00
parent 0eba169038
commit 9fe94d7e6e

View file

@ -2,81 +2,25 @@
# file: apistatusd.py
# date: 26.07.2019
# email: berhsi@web.de
# mail: berhsi@web.de
# Status server, listening for door status updates. The IPv4 address and port
# to listen on are configurable, by default localhost:10001 is used. The
# connection is secured by TLS and client side authentication.
import json
import logging
import os
import socket
import ssl
import sys
import threading
from mastodon import Mastodon
from time import time, localtime, strftime, sleep
import configparser
class InitException(Exception):
'''
If the initialisation from the mastodon instance failes then we raise
this exception.
'''
def __init__(self, error):
self.error = error
class Toot(threading.Thread):
'''
The thread to toot the status to mastodon.
'''
def __init__(self, status, timestamp, config):
'''
param1: boolean
param2: integer
param3: dictionary
'''
threading.Thread.__init__(self)
self.status = status
self.config = config
self.timestamp = timestamp
try:
self.mastodon = Mastodon(
api_base_url = self.config['mastodon']['host'],
access_token = self.config['mastodon']['token'])
except Exception as e:
logging.error('Exception occurred: {}'.format(e))
raise InitException('Mastodon instance initialisation failed')
def run(self):
'''
return: boolean
'''
msg = None
timeformat = '%d.%m.%Y %H:%M Uhr'
if self.status not in (True, False):
logging.error('Invalid status to toot')
return False
try:
timestring = strftime(timeformat, localtime(self.timestamp))
except Exception as e:
logging.error('Can not convert timestamp into timestring')
return False
logging.debug('Try to toot status to {}'.format(self.config['mastodon']['host']))
if self.status == True:
msg = 'The krautspace is open since: {}'.format(timestring)
elif self.status == False:
msg = 'The krautspace is closed since: {}'.format(timestring)
logging.debug('Send message: {}'.format(msg))
try:
mastodon.toot(mag)
return True
except Exception as e:
logging.error('Failed to toot status')
return False
return False
try:
import json
import logging
import os
import socket
import ssl
import sys
import requests
import threading
from time import time, localtime, strftime, sleep
import configparser
except ImportException as e:
print('Import error: {}'.format(e))
def certs_readable(config):
@ -93,7 +37,6 @@ def certs_readable(config):
return False
return True
def print_config(config):
'''
Logs the config with level debug.
@ -102,7 +45,10 @@ def print_config(config):
for section in config.sections():
logging.debug('Section {}'.format(section))
for i in config[section]:
logging.debug(' {}: {}'.format(i, config[section][i]))
if i == 'token':
logging.debug(' {}: {}'.format(i, 'aaaaa-bbbbb-ccccc-ddddd-eeeee'))
else:
logging.debug(' {}: {}'.format(i, config[section][i]))
def print_ciphers(cipherlist):
'''
@ -162,7 +108,6 @@ def receive_buffer_is_valid(raw_data):
logging.debug('Argument is not valid: {}'.format(raw_data))
return False
def change_status(status, timestamp, filename):
'''
Write the new status together with a timestamp into the Space API JSON.
@ -170,7 +115,6 @@ def change_status(status, timestamp, filename):
param 2: string
return: boolean
'''
logging.debug('Change status API')
# todo: use walrus operator := when migrating to python >= 3.8
data = read_api(filename)
@ -196,7 +140,6 @@ def change_status(status, timestamp, filename):
logging.info('API file successfull changed to {}'.format(status))
return True
def read_api(api):
'''
Reads the Space API JSON into a dict. Returns the dict on success and
@ -206,7 +149,6 @@ def read_api(api):
return: dict or boolean
'''
logging.debug('Open API file: {}'.format(api))
# return early if the API JSON cannot be read
if not os.access(api, os.R_OK):
logging.error('Failed to read API file')
@ -223,7 +165,6 @@ def read_api(api):
return False
return api_json_data
def get_status_and_time(raw_data):
'''
Create a timestamp, changes the value of the given byte into a string
@ -238,6 +179,83 @@ def get_status_and_time(raw_data):
str(timestamp), str(status)))
return (status, timestamp)
def join_path(host, api):
'''
Becomes two parts (host and api) of the mastodon url and concanate them
param1: string
param2: string
return: string
'''
url = ''
try:
if host[-1] == '/' and api[0] == '/':
url = ''.join((host, api[1:]))
elif host[-1] != '/' and api[0] != '/':
url = '/'.join((host, api))
else:
url = ''.join((host, api))
except TypeError as e:
logging.error('Can´t join path: {}'.format(e))
return url
class Toot(threading.Thread):
'''
The thread to toot the status to mastodon.
'''
def __init__(self, status, timestamp, config):
'''
param1: boolean
param2: integer
param3: dictionary
'''
threading.Thread.__init__(self)
self.status = status
self.config = config
self.timestamp = timestamp
self.api = '/api/v1/statuses'
self.auth = {'Authorization': ''}
self.data = {'status': ''}
self.url = ''
def run(self):
'''
return: boolean
'''
timeformat = '%d.%m.%Y %H:%M Uhr'
# check if status is valid
if self.status not in (True, False):
logging.error('Invalid status to toot')
return False
# convert seconds into timestring
try:
timestring = strftime(timeformat, localtime(self.timestamp))
except Exception as e:
logging.error('Can not convert timestamp into timestring')
return False
# set status message
if self.status == True:
self.data['status'] = 'Krautspace is open since: {}'.format(timestring)
elif self.status == False:
self.data['status'] = 'Krautspace is closed since: {}'.format(timestring)
logging.debug('Message: {}'.format(self.data['status']))
# build mastodon api url
self.url = join_path(self.config['mastodon']['host'], self.api)
# build authentcation header
self.auth['Authorization'] = 'Bearer {}'.format(
self.config['mastodon']['token'])
# and finaly send request to mastodon
try:
logging.debug('Try to toot status')
response = requests.post(self.url, data = self.data,
headers = self.auth)
if response.status_code == 200:
logging.info('Toot successful send')
return True
else:
logging.error('Failed to toot. Response: {}'.format(response.status_code))
except Exception as e:
logging.error('Exception occurred: {}'.format(e))
return False
def main():
'''
@ -248,7 +266,6 @@ def main():
OP_DONT_ISERT_EMPTY_FRAGMENTS: prevention agains CBC 4 attack
(cve-2011-3389)
'''
answer = '3'.encode(encoding='utf-8', errors='strict')
loglevel = logging.WARNING
formatstring = '%(asctime)s: %(levelname)s: %(message)s'