This commit is contained in:
rune 2023-04-11 13:01:37 +02:00
parent f7818ff2a8
commit 3351ca9b98

201
malias.py
View File

@ -44,45 +44,109 @@ def connect_database():
c.execute('''CREATE TABLE IF NOT EXISTS apikey c.execute('''CREATE TABLE IF NOT EXISTS apikey
(id integer NOT NULL PRIMARY KEY, (id integer NOT NULL PRIMARY KEY,
api text NOT NULL)''') api text NOT NULL)''')
c.execute('''CREATE TABLE IF NOT EXISTS settings (
id INTEGER NOT NULL PRIMARY KEY,
first_run INTEGER DEFAULT 0,
server TEXT DEFAULT "TEST"
)''')
c.execute('''CREATE TABLE IF NOT EXISTS aliases c.execute('''CREATE TABLE IF NOT EXISTS aliases
(id integer NOT NULL PRIMARY KEY, (id integer NOT NULL PRIMARY KEY,
alias text NOT NULL, alias text NOT NULL,
created text NOT NULL)''') goto text NOT NULL,
created text NOT NULL)''')
conn.commit()
first_run(conn)
return conn return conn
def first_run(conn):
now = datetime.now().strftime("%m-%d-%Y %H:%M")
cursor = conn.cursor()
cursor.execute('SELECT count(*) FROM settings')
count = cursor.fetchone()[0]
if count == 0:
logging.error(now + ' - First run!')
cursor.execute('INSERT INTO settings values(?,?,?)', (1, 1, 'dummy.server'))
cursor.execute('INSERT INTO apikey values(?,?)', (1, 'DUMMY_KEY'))
conn.commit()
return None
def get_settings(kind):
cursor = conn.cursor()
cursor.execute('SELECT * FROM settings')
data = cursor.fetchall()
first_run_status = data[0][1]
mail_server = data[0][2]
if kind == 'mail_server':
if mail_server == 'dummy.server':
print('Error: No MailCow server active. Please add one with [b]malias -m [i]your.server[/i][/b]')
exit(0)
else:
return mail_server
if kind == 'first_run_status':
return first_run_status
def get_api(): def get_api():
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM apikey') cursor.execute('SELECT api FROM apikey')
count = cursor.fetchone()[0] apikey = cursor.fetchone()[0]
if count == 0: if apikey == 'DUMMY_KEY':
return None print('Missing API key. Please add with [b]malias -k [i]YOUR-API-KEY[/i][/b]')
exit(0)
else: else:
cursor.execute('SELECT * FROM apikey') return apikey
rows = cursor.fetchone()
return rows[1]
def set_mailserver(server):
now = datetime.now().strftime("%m-%d-%Y %H:%M")
cursor = conn.cursor()
cursor.execute('UPDATE settings SET server = ? WHERE id = 1',(server,))
logging.info(now + ' - Info : MailCow server updated')
print('Your mail server has been updated.')
conn.commit()
def apikey(key): def apikey(key):
now = datetime.now().strftime("%m-%d-%Y %H:%M")
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM apikey') cursor.execute('UPDATE apikey SET api = ? WHERE id = 1',(key,))
count = cursor.fetchone()[0] logging.info(now + ' - Info : API key updated')
if count == 0: print('Your API key has been updated.')
cursor.execute('INSERT INTO apikey values(?,?)', (1, key))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : API key added')
print('Your API key has been added.')
else:
cursor.execute('UPDATE apikey SET api = ? WHERE id = 1',(key,))
logging.info(time.strftime("%Y-%m-%d %H:%M") + ' - Info : API key updated')
print('Your API key has been updated.')
conn.commit() conn.commit()
def create(alias): def create(alias,to_address):
print('Create : '+ alias) now = datetime.now().strftime("%m-%d-%Y %H:%M")
server = get_settings('mail_server')
apikey = get_api()
if checklist(alias) == True:
logging.error(now + ' - Error : alias %s exists on the MailCow instance %s ' %(alias,server))
print('\n[b]Error[/b] : alias %s exists on the MailCow instance %s \n' %(alias,server))
exit(0)
else:
values = """
{
"address": alias,
"goto": to_address,
"active": "1"
}
"""
headers = {
'Content-Type': 'application/json',
'X-API-Key': apikey
}
request = Request('https://rune.pm/api/v1/add/alias', data=values, headers=headers)
response_body = urlopen(request).read()
print (response_body)
def delete(alias): def delete(alias):
@ -91,7 +155,8 @@ def delete(alias):
def checklist(alias): def checklist(alias):
apikey = get_api() apikey = get_api()
req = urllib.request.Request('https://rune.pm/api/v1/get/alias/all') mail_server = get_settings('mail_server')
req = urllib.request.Request('https://'+mail_server+'/api/v1/get/alias/all')
req.add_header('Content-Type', 'application/json') req.add_header('Content-Type', 'application/json')
req.add_header('X-API-Key', apikey) req.add_header('X-API-Key', apikey)
current = urllib.request.urlopen(req) current = urllib.request.urlopen(req)
@ -105,18 +170,70 @@ def checklist(alias):
return None return None
def number_of_aliases_on_server():
apikey = get_api()
mail_server = get_settings('mail_server')
req = urllib.request.Request('https://'+mail_server+'/api/v1/get/alias/all')
req.add_header('Content-Type', 'application/json')
req.add_header('X-API-Key', apikey)
current = urllib.request.urlopen(req)
remote = current.read().decode('utf-8')
remoteData = json.loads(remote)
i = 0
for count in remoteData:
i=i+1
return i
def number_of_aliases_in_db():
cursor = conn.cursor()
cursor.execute('SELECT count(*) FROM aliases')
count = cursor.fetchone()[0]
return count
def search(alias): def search(alias):
print('Search for : ' + alias) results = checklist(alias)
result = checklist(alias) mail_server = get_settings('mail_server')
print(result) if results == True:
print('\n\nThe mail address %s exists. Using the MailCow instance : %s\n\n'%(alias,mail_server))
else:
print('\n\nThe mail address %s [b]does not[/b] exists. Using the MailCow instance : %s\n\n'%(alias,mail_server))
def show_current_info():
API = get_api()
mail_server = get_settings('mail_server')
if API == 'DUMMY_KEY':
API = 'Missing API Key!'
if mail_server == 'dummy.server':
mail_server = 'Missing address to MailCow instance!'
aliases_server = number_of_aliases_on_server()
alias_db = number_of_aliases_in_db()
print('\n[b]malias[/b] - Manage aliases on MailCow Instance.')
print('===================================================')
print('API key : [b]%s[/b]' % (API))
print('MailCow Instance : [b]%s[/b]' % (mail_server))
print('Logfile : [b]%s[/b]' % (logfile))
print('Aliases on server : [b]%s[/b]' % (aliases_server))
print('Aliases in DB : [b]%s[/b]' % (alias_db))
print('')
print('App version : [b]%s[/b] (https://gitlab.pm/rune/malias)' % (app_version))
print('')
conn = connect_database() conn = connect_database()
# updatedb()
parser = argparse.ArgumentParser(prog='malias', parser = argparse.ArgumentParser(prog='malias',
description='Application descript', description='Application description',
formatter_class=RawTextHelpFormatter, formatter_class=RawTextHelpFormatter,
epilog='Making Mailcow easier...') epilog='Making MailCow easier...')
parser.add_argument('-k', '--api', help='Add/Change API key.\n\n', parser.add_argument('-k', '--api', help='Add/Change API key.\n\n',
nargs=1, metavar=('APIkey'), required=False, action="append") nargs=1, metavar=('APIkey'), required=False, action="append")
@ -124,17 +241,31 @@ parser.add_argument('-k', '--api', help='Add/Change API key.\n\n',
parser.add_argument('-s', '--search', help='Search for alias.\n\n', parser.add_argument('-s', '--search', help='Search for alias.\n\n',
nargs=1, metavar=('alias@domain.com'), required=False, action="append") nargs=1, metavar=('alias@domain.com'), required=False, action="append")
parser.add_argument('-m', '--server', help='Add/Uppdate MailCow instance.\n\n',
nargs=1, metavar=('alias@domain.com'), required=False, action="append")
parser.add_argument('-a', '--add', help='Add new alias.\n\n',
nargs=2, metavar=('alias@domain.com', 'to@domain.com'), required=False, action="append")
parser.add_argument('-v', '--version', help='Show current version and config info\n\n',
required=False, action='store_true')
args = vars(parser.parse_args()) args = vars(parser.parse_args())
if len(args)<1:
parser.print_help(sys.stderr)
sys.exit(1)
if args['api']: if args['api']:
apikey(args['api'][0][0]) apikey(args['api'][0][0])
elif args['search']: elif args['search']:
search(args['search'][0][0]) search(args['search'][0][0])
elif args['server']:
set_mailserver(args['server'][0][0])
elif args['add']:
create(args['add'][0][0],args['add'][0][1])
elif args['version']:
show_current_info()
else: else:
print('Error ') # get_settings(first_run_status)
get_api()
print('\n\nError use [b]malias -h[/b] to see the help screen!\n\n\n')