|
1 |
| -from copy import copy |
| 1 | +import importlib |
| 2 | +from copy import copy, deepcopy |
2 | 3 | from itertools import repeat
|
3 | 4 | from typing import List, NamedTuple, Optional, Sequence, Union
|
4 | 5 |
|
5 | 6 | from django.db import models
|
6 | 7 | from django.utils.translation import gettext_lazy as _
|
7 | 8 | from firebase_admin import messaging
|
8 | 9 | from firebase_admin.exceptions import FirebaseError, InvalidArgumentError
|
9 |
| - |
10 | 10 | from fcm_django.settings import FCM_DJANGO_SETTINGS as SETTINGS
|
11 | 11 |
|
12 | 12 | # Set by Firebase. Adjust when they adjust; developers can override too if we don't
|
@@ -346,6 +346,49 @@ def deactivate_devices_with_error_result(
|
346 | 346 |
|
347 | 347 |
|
348 | 348 | class FCMDevice(AbstractFCMDevice):
|
| 349 | + |
| 350 | + # https://github.com/Tournafest/django_backend/blob/aab3250c70fad0fdd25dad7bf472d2d1c188989d/utils/models.py#L131 |
| 351 | + # Followed this strategy to overwrite the save method |
| 352 | + |
| 353 | + def __init__(self, *args, **kwargs) -> None: |
| 354 | + super().__init__(*args, **kwargs) |
| 355 | + self.original_object = deepcopy(self) |
| 356 | + self.ALLOW_RUN_POST_SAVE_TRIGGERS = True |
| 357 | + self.COUNT_RUN_SAVE = 0 |
| 358 | + self.IGNORE_COUNT_RUN_SAVE = False |
| 359 | + |
| 360 | + def save(self, *args, **kwargs): |
| 361 | + |
| 362 | + self.COUNT_RUN_SAVE += 1 |
| 363 | + if "ALLOW_RUN_POST_SAVE_TRIGGERS" in kwargs: |
| 364 | + _ALLOW_RUN_POST_SAVE_TRIGGERS = kwargs.pop("ALLOW_RUN_POST_SAVE_TRIGGERS") |
| 365 | + else: |
| 366 | + _ALLOW_RUN_POST_SAVE_TRIGGERS = self.ALLOW_RUN_POST_SAVE_TRIGGERS |
| 367 | + |
| 368 | + if "IGNORE_COUNT_RUN_SAVE" in kwargs: |
| 369 | + _IGNORE_COUNT_RUN_SAVE = kwargs.pop("IGNORE_COUNT_RUN_SAVE") |
| 370 | + else: |
| 371 | + _IGNORE_COUNT_RUN_SAVE = self.IGNORE_COUNT_RUN_SAVE |
| 372 | + |
| 373 | + # Save the object |
| 374 | + super().save(*args, **kwargs) |
| 375 | + |
| 376 | + # Process changes only for the first time the object is saved on an object |
| 377 | + if _ALLOW_RUN_POST_SAVE_TRIGGERS and ( |
| 378 | + _IGNORE_COUNT_RUN_SAVE or (self.COUNT_RUN_SAVE == 1) |
| 379 | + ): |
| 380 | + # Post save processing |
| 381 | + self.process_db_object_saved() |
| 382 | + |
| 383 | + def process_db_object_saved(self): |
| 384 | + if SETTINGS["FCM_POST_SAVE_FUNCTION"]: |
| 385 | + module_name, function_name = SETTINGS["FCM_POST_SAVE_FUNCTION"].rsplit( |
| 386 | + ".", 1 |
| 387 | + ) |
| 388 | + module = importlib.import_module(module_name) |
| 389 | + function = getattr(module, function_name) |
| 390 | + function(self.original_object, self) |
| 391 | + |
349 | 392 | class Meta:
|
350 | 393 | verbose_name = _("FCM device")
|
351 | 394 | verbose_name_plural = _("FCM devices")
|
0 commit comments