Add util docstring and url validator

This commit is contained in:
sosokker 2024-04-28 02:37:41 +07:00
parent adb6ec6497
commit a44378a115

View File

@ -1,10 +1,17 @@
"""
This module contains utility functions that are used in the project.
"""
import re
import json import json
from typing import Never from typing import Never
from pydantic import BaseModel from pydantic import BaseModel
from scheme import Camera from scheme import Camera
def serialize_value(value) -> any: def serialize_value(value) -> any:
"""Serialize the given value to a JSON serializable value."""
if isinstance(value, list): if isinstance(value, list):
if all(isinstance(item, BaseModel) for item in value): if all(isinstance(item, BaseModel) for item in value):
return [item.dict() for item in value] return [item.dict() for item in value]
@ -17,6 +24,7 @@ def serialize_value(value) -> any:
def save_to_config(key, value) -> None: def save_to_config(key, value) -> None:
"""Save the given key-value pair to the config file."""
try: try:
with open('config.json', 'r') as file: with open('config.json', 'r') as file:
config_data = json.load(file) config_data = json.load(file)
@ -29,6 +37,7 @@ def save_to_config(key, value) -> None:
def read_cameras_from_config(file_path) -> list[Camera] | list[Never]: def read_cameras_from_config(file_path) -> list[Camera] | list[Never]:
"""Read the cameras data from the config file."""
try: try:
with open(file_path, 'r') as file: with open(file_path, 'r') as file:
config_data = json.load(file) config_data = json.load(file)
@ -38,4 +47,15 @@ def read_cameras_from_config(file_path) -> list[Camera] | list[Never]:
cameras_data = config_data.get('cameras', []) cameras_data = config_data.get('cameras', [])
cameras = [Camera(**cam_data) for cam_data in cameras_data] cameras = [Camera(**cam_data) for cam_data in cameras_data]
return cameras return cameras
def video_url_validation(url: str) -> bool:
"""Validate if the given URL is a rtsp/rtmp URL or not."""
rtmp_pattern = r'^rtmp://.*$'
rtsp_pattern = r'^rtsp://.*$'
if re.match(rtmp_pattern, url) or re.match(rtsp_pattern, url):
return True
else:
return False