Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Privacy policy and usage manager #6

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions .github/workflows/test-plugin-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jobs:
uses: actions/checkout@v3
with:
repository: DraKen0009/care
ref: adding-camera-plugin
ref: provacy-consultation-bed-camera-plugin


# Update the plug_config.py file with the required content
Expand All @@ -33,14 +33,14 @@ jobs:
cat > ./plug_config.py <<EOL
from plugs.manager import PlugManager
from plugs.plug import Plug

camera_plugin = Plug(
name="camera",
package_name="git+https://github.com/ohcnetwork/care_camera_asset.git",
version="@${BRANCH_NAME}",
configs={},
)

plugs = [camera_plugin]
manager = PlugManager(plugs)
EOL
Expand All @@ -53,4 +53,4 @@ jobs:
# Run Django management command tests
- name: Run Django management command tests
run: |
docker compose exec backend bash -c "python manage.py test camera --keepdb --parallel --shuffle"
docker compose exec backend bash -c "python manage.py test camera --keepdb --parallel --shuffle"
2 changes: 1 addition & 1 deletion camera/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class Migration(migrations.Migration):
initial = True

dependencies = [
('facility', '0468_alter_asset_asset_class_alter_asset_meta'),
('facility', '0469_alter_asset_asset_class_alter_asset_meta'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

Expand Down
34 changes: 34 additions & 0 deletions camera/migrations/0004_assetbedboundary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Generated by Django 5.1.3 on 2024-12-28 18:51

import django.db.models.deletion
import uuid
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('camera', '0003_alter_positionpreset_created_date_and_more'),
('facility', '0469_alter_asset_asset_class_alter_asset_meta'),
]

operations = [
migrations.CreateModel(
name='AssetBedBoundary',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('external_id', models.UUIDField(db_index=True, default=uuid.uuid4, unique=True)),
('created_date', models.DateTimeField(auto_now_add=True, db_index=True, null=True)),
('modified_date', models.DateTimeField(auto_now=True, db_index=True, null=True)),
('deleted', models.BooleanField(db_index=True, default=False)),
('x0', models.IntegerField()),
('y0', models.IntegerField()),
('x1', models.IntegerField()),
('y1', models.IntegerField()),
('asset_bed', models.OneToOneField(on_delete=django.db.models.deletion.PROTECT, related_name='assetbed_camera_boundary', to='facility.assetbed')),
],
options={
'abstract': False,
},
),
]
1 change: 1 addition & 0 deletions camera/models/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from camera.models.asset_bed_boundary import AssetBedBoundary
48 changes: 48 additions & 0 deletions camera/models/asset_bed_boundary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from django.db import models
from django.core.exceptions import ValidationError
from jsonschema import validate
from jsonschema.exceptions import ValidationError as JSONSchemaValidationError
from camera.models.json_schema.boundary import ASSET_BED_BOUNDARY_SCHEMA
from care.facility.models import AssetBed
from care.utils.models.base import BaseModel



class AssetBedBoundary(BaseModel):
asset_bed = models.OneToOneField(
AssetBed, on_delete=models.PROTECT, related_name="assetbed_camera_boundary"
)
x0 = models.IntegerField()
y0 = models.IntegerField()
x1 = models.IntegerField()
y1 = models.IntegerField()

def save(self, *args, **kwargs):
if self.asset_bed.asset.asset_class != "ONVIF":
error="AssetBedBoundary is only applicable for AssetBeds with ONVIF assets."
raise ValidationError(error)

data = {
"x0": self.x0,
"y0": self.y0,
"x1": self.x1,
"y1": self.y1,
}

try:
validate(instance=data, schema=ASSET_BED_BOUNDARY_SCHEMA)
except JSONSchemaValidationError as e:
error=f"Invalid data: {str(e)}"
raise ValidationError(error) from e

super().save(*args, **kwargs)


def to_dict(self):
"""Serialize boundary data as a dictionary."""
return {
"x0": self.x0,
"y0": self.y0,
"x1": self.x1,
"y1": self.y1,
}
12 changes: 12 additions & 0 deletions camera/models/json_schema/boundary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
ASSET_BED_BOUNDARY_SCHEMA = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"x0": {"type": "number"},
"y0": {"type": "number"},
"x1": {"type": "number"},
"y1": {"type": "number"},
},
"required": ["x0", "y0", "x1", "y1"],
"additionalProperties": False,
}
118 changes: 118 additions & 0 deletions camera/tests/test_asset_usage_manager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
from unittest import mock

from camera.utils.usage_manager import UsageManager
from rest_framework.test import APITestCase

from care.users.models import User
from care.utils.tests.test_utils import TestUtils


class UsageManagerTestCase(TestUtils, APITestCase):
@classmethod
def setUpTestData(cls):
cls.state = cls.create_state()
cls.district = cls.create_district(cls.state)
cls.local_body = cls.create_local_body(cls.district)
cls.super_user = cls.create_super_user("su", cls.district)
cls.facility = cls.create_facility(cls.super_user, cls.district, cls.local_body)
cls.asset_location = cls.create_asset_location(cls.facility)
cls.asset = cls.create_asset(cls.asset_location)

def setUp(self):
self.user1 = self.create_user(
username="test_user_1",
state=self.state,
district=self.district,
user_type=User.TYPE_VALUE_MAP["StateAdmin"],
)
self.user2 = self.create_user(
username="test_user_2",
state=self.state,
district=self.district,
user_type=User.TYPE_VALUE_MAP["StateAdmin"],
)

self.mock_cache = mock.MagicMock()
self.cache_patcher = mock.patch(
"camera.utils.usage_manager.cache", self.mock_cache
)
self.cache_patcher.start()

self.usage_manager_user1 = UsageManager(
asset_id=self.asset.external_id, user=self.user1
)
self.usage_manager_user2 = UsageManager(
asset_id=self.asset.external_id, user=self.user2
)

self.mock_redis_client = mock.MagicMock()
self.usage_manager_user1.redis_client = self.mock_redis_client
self.usage_manager_user2.redis_client = self.mock_redis_client

def tearDown(self):
self.cache_patcher.stop()

def test_has_access(self):
self.mock_cache.get.return_value = None
self.assertTrue(self.usage_manager_user1.has_access())

self.mock_cache.get.return_value = self.user1.id
self.assertTrue(self.usage_manager_user1.has_access())

self.mock_cache.get.return_value = self.user2.id
self.assertFalse(self.usage_manager_user1.has_access())

def test_unlock_camera(self):
self.mock_cache.get.return_value = self.user1.id

with mock.patch.object(
self.usage_manager_user1, "notify_waiting_list_on_asset_availabe"
) as mock_notify:
self.usage_manager_user1.unlock_camera()

self.mock_cache.delete.assert_called_once_with(
self.usage_manager_user1.current_user_cache_key
)

mock_notify.assert_called_once()

def test_request_access(self):
self.mock_cache.get.return_value = None
self.assertTrue(self.usage_manager_user1.request_access())

self.mock_cache.get.return_value = self.user2.id
with mock.patch(
"care.utils.notification_handler.send_webpush"
) as mock_send_webpush:
result = self.usage_manager_user1.request_access()
self.assertFalse(result)
mock_send_webpush.assert_called_once()

def test_lock_camera(self):
self.mock_cache.get.return_value = None
self.assertTrue(self.usage_manager_user1.lock_camera())
self.mock_cache.set.assert_called_once_with(
self.usage_manager_user1.current_user_cache_key,
self.user1.id,
timeout=60 * 5,
)

self.mock_cache.get.return_value = self.user2.id
self.assertFalse(self.usage_manager_user1.lock_camera())

def test_current_user(self):
self.mock_cache.get.return_value = self.user1.id

mock_serializer = mock.MagicMock()
mock_serializer.data = {
"id": self.user1.id,
"username": self.user1.username,
}

with mock.patch(
"care.facility.api.serializers.asset.UserBaseMinimumSerializer",
return_value=mock_serializer,
):
current_user_data = self.usage_manager_user1.current_user()
self.assertIsNotNone(current_user_data)
self.assertEqual(current_user_data["id"], self.user1.id)
4 changes: 2 additions & 2 deletions camera/tests/test_camera_preset_apis.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,15 +170,15 @@ def test_list_bed_with_deleted_assetbed(self):
format="json",
)
self.assertEqual(res.status_code, status.HTTP_201_CREATED)

res = self.client.get(f"/api/camera/position-presets/?bed_external_id={self.bed.external_id}")
self.assertEqual(len(res.json()["results"]), 2)

self.asset_bed1.delete()
self.asset_bed1.refresh_from_db()
res = self.client.get(f"/api/camera/position-presets/?bed_external_id={self.bed.external_id}")
self.assertEqual(len(res.json()["results"]), 1)

def test_meta_validations_for_onvif_asset(self):
valid_meta = {
"local_ip_address": "192.168.0.1",
Expand Down
62 changes: 60 additions & 2 deletions camera/utils/onvif.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import enum

from rest_framework.exceptions import ValidationError
from camera.utils.usage_manager import UsageManager
from rest_framework.exceptions import ValidationError,PermissionDenied

from care.facility.models.bed import AssetBed
from care.utils.assetintegration.base import ActionParams, BaseAssetIntegration


Expand All @@ -16,6 +18,11 @@ class OnvifActions(enum.Enum):
RELATIVE_MOVE = "relative_move"
GET_STREAM_TOKEN = "get_stream_token"

LOCK_CAMERA = "lock_camera"
UNLOCK_CAMERA = "unlock_camera"
REQUEST_ACCESS = "request_access"
TAKE_CONTROL = "take_control"

def __init__(self, meta):
try:
super().__init__(meta)
Expand All @@ -27,10 +34,12 @@ def __init__(self, meta):
{key: f"{key} not found in asset metadata" for key in e.args}
) from e

def handle_action(self, **kwargs: ActionParams):
def handle_action(self,user, **kwargs: ActionParams):
action_type = kwargs["type"]
action_data = kwargs.get("data", {})
action_options = kwargs.get("options", {})
timeout = kwargs.get("timeout")
camera_manager = UsageManager(self.id, user)

request_body = {
"hostname": self.host,
Expand All @@ -41,6 +50,42 @@ def handle_action(self, **kwargs: ActionParams):
**action_data,
}

if action_type == self.OnvifActions.LOCK_CAMERA.value:
if camera_manager.lock_camera():
return {
"message": "You now have access to the camera controls, the camera is locked for other users",
"camera_user": camera_manager.current_user(),
}

raise PermissionDenied(
{
"message": "Camera is currently in used by another user, you have been added to the waiting list for camera controls access",
"camera_user": camera_manager.current_user(),
}
)
if action_type == self.OnvifActions.UNLOCK_CAMERA.value:
camera_manager.unlock_camera()
return {"message": "Camera controls unlocked"}

if action_type == self.OnvifActions.REQUEST_ACCESS.value:
if camera_manager.request_access():
return {
"message": "Access to camera camera controls granted",
"camera_user": camera_manager.current_user(),
}

return {
"message": "Requested access to camera controls, waiting for current user to release",
"camera_user": camera_manager.current_user(),
}
if not camera_manager.has_access():
raise PermissionDenied(
{
"message": "Camera is currently in used by another user, you have been added to the waiting list for camera controls access",
"camera_user": camera_manager.current_user(),
}
)

if action_type == self.OnvifActions.GET_CAMERA_STATUS.value:
return self.api_get(self.get_url("status"), request_body, timeout)

Expand All @@ -54,6 +99,19 @@ def handle_action(self, **kwargs: ActionParams):
return self.api_post(self.get_url("absoluteMove"), request_body, timeout)

if action_type == self.OnvifActions.RELATIVE_MOVE.value:
action_asset_bed_id = action_options.get("asset_bed_id")

if action_asset_bed_id:
asset_bed = AssetBed.objects.filter(
external_id=action_asset_bed_id
).first()

if not asset_bed:
raise ValidationError({"asset_bed_id": "Invalid Asset Bed ID"})

if hasattr(asset_bed, "assetbed_camera_boundary"):
boundary = asset_bed.assetbed_camera_boundary.to_dict()
request_body.update({"boundary": boundary})
return self.api_post(self.get_url("relativeMove"), request_body, timeout)

if action_type == self.OnvifActions.GET_STREAM_TOKEN.value:
Expand Down
Loading
Loading