From e5c4c12ac6713e6ce9471c01bad97b3b9412f911 Mon Sep 17 00:00:00 2001 From: Antoine Martin Date: Thu, 29 Feb 2024 16:37:04 -0500 Subject: [PATCH] main.py: add is_active syncing --- main.py | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/main.py b/main.py index a765173..23dce3b 100755 --- a/main.py +++ b/main.py @@ -27,7 +27,7 @@ def authentik_get_users(): def listmonk_create_subscriber(email, username, status, lists): url = listmonk_api_url + '/subscribers' - payload = {"email": email, "name": username, "status": print(status), "lists": lists} + payload = {"email": email, "name": username, "status": status, "lists": lists, "preconfirm_subscriptions": True} headers = {'Content-Type': 'application/json'} resp = requests.post(url, data=json.dumps(payload), headers=headers, auth=(listmonk_api_usr, listmonk_api_key)) json_object = json.loads(resp._content) @@ -35,7 +35,7 @@ def listmonk_create_subscriber(email, username, status, lists): def listmonk_set_subscriber(subscriber_id, email, username, status, lists): url = listmonk_api_url + '/subscribers/' + str(subscriber_id) - payload = {"email": email, "name": username, "status": print(status), "lists": lists} + payload = {"email": email, "name": username, "status": status, "lists": lists} headers = {'Content-Type': 'application/json'} resp = requests.put(url, data=json.dumps(payload), headers=headers, auth=(listmonk_api_usr, listmonk_api_key)) json_object = json.loads(resp._content) @@ -56,19 +56,32 @@ def listmonk_get_subscriber(username): for user_info in authentik_get_users(): print('>>> Checking ' + user_info['username']) + + if user_info['is_active'] == True: + user_active = "enabled" + else: + user_active = "disabled" + try: subscriber_info = listmonk_get_subscriber(user_info['username']) print(subscriber_info) + # if get user info fails, assume that we have to create a new one + # TOOD: only create if the error is indeed user-existence related except Exception as e: print('> Failed to find username, creating subscriber') - create_resp = listmonk_create_subscriber(user_info['email'], user_info['username'], user_info['is_active'], lists=[1]) + create_resp = listmonk_create_subscriber(user_info['email'], user_info['username'], status=user_active, lists=[1]) print(create_resp) continue + # checks if user email matches subscriber email if user_info['email'] != subscriber_info['email']: print('> Email check failed, updating') set_resp = listmonk_set_subscriber(subscriber_info['id'], user_info['email'], user_info['username'], subscriber_info['status'], lists=[1]) print(set_resp) - + # check if user and subscriber info match as it relates to status + if user_active != subscriber_info['status'] and subscriber_info['status'] != "blocklisted": + print('> User status check failed, updating') + set_resp = listmonk_set_subscriber(subscriber_info['id'], user_info['email'], user_info['username'], status=user_active, lists=[1]) + print(set_resp)