mirror of
https://github.com/i701/sarlink-portal-api.git
synced 2025-10-05 19:45:25 +00:00
fix(tasks): add device activation/deactivation & blocking/unblocking for background task 🐛
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 4m17s
All checks were successful
Build and Push Docker Images / Build and Push Docker Images (push) Successful in 4m17s
This commit is contained in:
70
api/tasks.py
70
api/tasks.py
@@ -11,6 +11,7 @@ from api.omada import Omada
|
||||
from apibase.env import env, BASE_DIR
|
||||
from procrastinate.contrib.django import app
|
||||
from procrastinate import builtin_tasks
|
||||
import time
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -36,22 +37,64 @@ async def remove_old_jobs(context, timestamp):
|
||||
|
||||
|
||||
@app.periodic(
|
||||
cron="0 0 */28 * *", queue="heavy_tasks", periodic_id="deactivate_expired_devices"
|
||||
cron="0 22 * * *",
|
||||
queue="heavy_tasks",
|
||||
periodic_id="deactivate_expired_devices_and_block_in_omada",
|
||||
) # type: ignore
|
||||
@app.task
|
||||
def deactivate_expired_devices():
|
||||
def deactivate_expired_devices_and_block_in_omada():
|
||||
expired_devices = Device.objects.filter(
|
||||
expiry_date__lte=timezone.localtime(timezone.now()), is_active=True
|
||||
).select_related("user")
|
||||
|
||||
print("Expired Devices: ", expired_devices)
|
||||
count = expired_devices.count()
|
||||
|
||||
if count == 0:
|
||||
return {"total_expired_devices": 0}
|
||||
|
||||
user_devices_map = {}
|
||||
devices_successfully_blocked = []
|
||||
devices_failed_to_block = []
|
||||
omada_client = Omada()
|
||||
|
||||
# Single loop to collect data and block devices
|
||||
for device in expired_devices:
|
||||
# Collect devices for SMS notifications
|
||||
if device.user and device.user.mobile:
|
||||
if device.user.mobile not in user_devices_map:
|
||||
user_devices_map[device.user.mobile] = []
|
||||
user_devices_map[device.user.mobile].append(device.name)
|
||||
|
||||
# Try to block device in Omada
|
||||
try:
|
||||
omada_client.block_device(mac_address=device.mac, operation="block")
|
||||
# Only prepare for update if Omada blocking succeeded
|
||||
device.blocked = True
|
||||
device.is_active = False
|
||||
devices_successfully_blocked.append(device)
|
||||
logger.info(f"Successfully blocked device {device.mac} in Omada")
|
||||
time.sleep(20) # Sleep to avoid rate limiting
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to block device [omada] {device.mac}: {e}")
|
||||
devices_failed_to_block.append(device)
|
||||
# Continue to next device without updating this one
|
||||
|
||||
# Bulk update only successfully blocked devices
|
||||
if devices_successfully_blocked:
|
||||
try:
|
||||
Device.objects.bulk_update(
|
||||
devices_successfully_blocked, ["is_active", "blocked"]
|
||||
)
|
||||
logger.info(
|
||||
f"Successfully updated {len(devices_successfully_blocked)} devices in database"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to bulk update devices in database: {e}")
|
||||
# You might want to handle this case - devices are blocked in Omada but not updated in DB
|
||||
|
||||
# Send SMS notifications
|
||||
sms_count = 0
|
||||
for mobile, device_names in user_devices_map.items():
|
||||
if not mobile:
|
||||
continue
|
||||
@@ -59,14 +102,25 @@ def deactivate_expired_devices():
|
||||
[f"{i + 1}. {name}" for i, name in enumerate(device_names)]
|
||||
)
|
||||
print("device list: ", device_list)
|
||||
send_sms(
|
||||
mobile,
|
||||
f"Dear {mobile}, \n\nThe following devices have expired: \n{device_list}. \n\nPlease make a payment to keep your devices active. \n\n- SAR Link",
|
||||
)
|
||||
# expired_devices.update(is_active=False)
|
||||
print(f"Total {count} expired devices.")
|
||||
try:
|
||||
send_sms(
|
||||
mobile,
|
||||
f"Dear {mobile}, \n\nThe following devices have expired: \n{device_list}. \n\nPlease make a payment to keep your devices active. \n\n- SAR Link",
|
||||
)
|
||||
sms_count += 1
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send SMS to {mobile}: {e}")
|
||||
|
||||
print(f"Total {count} expired devices processed.")
|
||||
print(f"Successfully blocked: {len(devices_successfully_blocked)}")
|
||||
print(f"Failed to block: {len(devices_failed_to_block)}")
|
||||
print(f"SMS notifications sent: {sms_count}")
|
||||
|
||||
return {
|
||||
"total_expired_devices": count,
|
||||
"successfully_blocked": len(devices_successfully_blocked),
|
||||
"failed_to_block": len(devices_failed_to_block),
|
||||
"sms_sent": sms_count,
|
||||
}
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user