Skip to content

Commit

Permalink
generate mark for new devices
Browse files Browse the repository at this point in the history
  • Loading branch information
KwikKill committed Oct 11, 2024
1 parent ff2cd7c commit 77b7156
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
30 changes: 27 additions & 3 deletions backend/langate/network/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ def create_user_device(user: User, ip, name=None):

netcontrol.query("connect_user", { "mac": mac, "name": user.username })

mark = get_mark()
netcontrol.query("set_mark", { "mac": mac, "mark": mark })

logger.info(
"Connected device %s (owned by %s) at %s to the internet.",
mac,
Expand All @@ -117,7 +120,7 @@ def create_user_device(user: User, ip, name=None):
)

try:
device = UserDevice.objects.create(mac=mac, name=name, user=user, ip=ip, area=area)
device = UserDevice.objects.create(mac=mac, name=name, user=user, ip=ip, area=area, mark=mark)
device.save()
return device
except Exception as e:
Expand All @@ -134,9 +137,9 @@ def delete_user_device(Device):
return DeviceManager.delete_device(Device.mac)

@staticmethod
def edit_whitelist_device(device: Device, mac, name, mark=None):
def edit_device(device: Device, mac, name, mark=None):
"""
Edit the whitelist status of a device
Edit the status of a device
"""
# If name is provided, update it
if name and name != device.name:
Expand All @@ -150,7 +153,11 @@ def edit_whitelist_device(device: Device, mac, name, mark=None):
netcontrol.query("connect", { "mac": mac, "name": device.name })
device.mac = mac
if mark and mark != device.mark:
# Check if the mark is valid
if mark not in [m["value"] for m in SETTINGS["marks"]]:
raise ValidationError(_("Invalid mark"))
device.mark = mark
netcontrol.query("set_mark", { "mac": device.mac, "mark": mark })

device.save()

Expand All @@ -174,3 +181,20 @@ def generate_dev_name():

except FileNotFoundError:
return "MISSINGNO"

def get_mark():
"""
Get a mark from the settings based on random probability
"""
# Get random between 0 and 1
random_choice = random.random()

# for each mark in the settings
total = 0
for mark in SETTINGS["marks"]:
if random_choice <= mark["priority"] + total:
return mark["value"]
total += mark["priority"]

# It should never reach this point but if it does, return the first mark
return SETTINGS["marks"][0]["value"]
2 changes: 1 addition & 1 deletion backend/langate/network/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ def patch(self, request, pk):
"""
try:
device = Device.objects.get(pk=pk)
DeviceManager.edit_whitelist_device(
DeviceManager.edit_device(
device,
request.data.get("mac", device.mac),
request.data.get("name", device.name),
Expand Down

0 comments on commit 77b7156

Please sign in to comment.