From f653a20d35b3f0d9acdde639b2676b6144bff923 Mon Sep 17 00:00:00 2001 From: rune Date: Mon, 4 Sep 2023 15:12:57 +0200 Subject: [PATCH] Added function updating local DB from aliases on Mailcow instance --- malias.py | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/malias.py b/malias.py index 87bc285..0500b59 100755 --- a/malias.py +++ b/malias.py @@ -29,7 +29,7 @@ database = filepath.joinpath('malias.db') logfile = filepath.joinpath('malias.log') Path(filepath).mkdir(parents=True, exist_ok=True) logging.basicConfig(filename=logfile,level=logging.INFO,format='%(message)s') -app_version = '0.2.3' +app_version = '0.2.4' def connect_database(): @@ -230,8 +230,42 @@ def copy_data(): logging.info(now + ' - Info : aliases imported from the mailcow instance %s to local DB' %(mail_server)) print('\n[b]Info[/b] : aliases imported from the mailcow instance %s to local DB\n' %(mail_server)) else: - print('\n[b]Info[/b] : aliases alreday imported from the mailcow instance %s to local DB\n' %(mail_server)) - + print('\n[b]Info[/b] : aliases alreday imported from the mailcow instance %s to local DB\n\n[i]Updating with any missing aliases![/i]' %(mail_server)) + update_data() + + +def update_data(): + apikey = get_api() + mail_server = get_settings('mail_server') + if get_settings('copy_status') == 1: + now = datetime.now().strftime("%m-%d-%Y %H:%M") + cursor = conn.cursor() + 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 + count_alias = 0 + cursor = conn.cursor() + for data in remoteData: + cursor.execute('SELECT count(*) FROM aliases where alias like ? and goto like ?', (remoteData[i]['address'],remoteData[i]['goto'],)) + count = cursor.fetchone()[0] + if count >= 1 : + i+=1 + else: + cursor.execute('INSERT INTO aliases values(?,?,?,?)', (remoteData[i]['id'], remoteData[i]['address'],remoteData[i]['goto'],now)) + count_alias+=1 + i+=1 + conn.commit() + if count_alias > 0: + logging.info(now + ' - Info : Local DB updated with %s new aliases from %s ' %(str(count_alias),mail_server)) + print('\n[b]Info[/b] : Local DB update with %s new aliases from %s \n' %(str(count_alias),mail_server)) + else: + print('\n[b]Info[/b] : No missing aliases from local DB \n') + + def checklist(alias): alias_exist = None @@ -417,7 +451,7 @@ def show_current_info(): 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('App version : [b]%s[/b] (https://iurl.no/malias)' % (app_version)) print('')