1010
1111
1212@shared_task
13- def manage_estimated_locations (device_pk , ip_address , add_existing = False ):
13+ def manage_estimated_locations (device_pk , ip_address ):
1414 """
1515 Creates/updates estimated location for a device based on the latitude and
16- longitude or attaches an existing location if `add_existing` is True .
16+ longitude or attaches an existing location.
1717 Existing location here means a location of another device whose last_ip matches
1818 the given ip_address.
19+ Does not alters the existing location if it is not estimated.
1920
20- When `add_existing` is True:
21- - If the current device has no location, attach the existing one; if it does,
22- update it with the existing one only if it is estimated (fuzzy).
21+ - If the current device has no location or location is estimate, either update
22+ to an existing location; if it exists, else
2323
24- When `add_existing` is False:
2524 - A new location is created if no location exists for current device, or
26- existing one is updated using coords from WHOIS record if it is estimated (fuzzy).
25+ existing one is updated using coords from WHOIS record if it is estimated.
26+
27+ In case of multiple devices with same last_ip, the task will send a notification
28+ to the user to resolve the conflict manually.
2729 """
2830 Device = load_model ("config" , "Device" )
2931 Location = load_model ("geo" , "Location" )
@@ -123,10 +125,14 @@ def _handle_attach_existing_location(
123125 )
124126
125127 whois_obj = WHOISInfo .objects .filter (ip_address = ip_address ).first ()
126- device = Device .objects .get (pk = device_pk )
127- device_location , _ = DeviceLocation .objects .select_related (
128- "location"
129- ).get_or_create (content_object_id = device_pk )
128+ device = (
129+ Device .objects .select_related ("devicelocation__location" , "organization" )
130+ .only ("organization_id" , "devicelocation" )
131+ .get (pk = device_pk )
132+ )
133+
134+ if not (device_location := getattr (device , "devicelocation" , None )):
135+ device_location = DeviceLocation (content_object = device )
130136
131137 attached_devices_exists = False
132138 if current_location := device_location .location :
@@ -136,12 +142,7 @@ def _handle_attach_existing_location(
136142 .exists ()
137143 )
138144
139- if add_existing and ( not current_location or current_location .is_estimated ) :
145+ if not current_location or current_location .is_estimated :
140146 _handle_attach_existing_location (
141147 device , device_location , whois_obj , attached_devices_exists
142148 )
143-
144- else :
145- _update_or_create_estimated_location (
146- device_location , whois_obj , attached_devices_exists
147- )
0 commit comments