Commit 520fd73d authored by Pietro Saccardi's avatar Pietro Saccardi

Sanitizing all settings values. This closes #1.

parent 9bee4ee7
Pipeline #335 passed with stage
in 6 minutes and 42 seconds
......@@ -83,21 +83,6 @@ class RatcamTelegramPlugin(TelegramProcessBase, MediaReceiver, MotionDetectorRes
super(RatcamTelegramPlugin, self).__enter__()
self._clear_plugins_cache()
@staticmethod
def _photo_timeout():
return max(SETTINGS.telegram.photo_timeout, 5.)
@staticmethod
def _video_timeout():
return max(SETTINGS.telegram.video_timeout, 5.)
@staticmethod
def _video_duration():
if SETTINGS.ratcam.video_duration is None:
return 8.
else:
return max(min(SETTINGS.ratcam.video_duration, 60.), 1.)
def _enum_recipient_chat_ids(self, info):
if info is None:
yield from self.root_telegram_plugin.authorized_chat_ids
......@@ -184,7 +169,8 @@ class RatcamTelegramPlugin(TelegramProcessBase, MediaReceiver, MotionDetectorRes
else:
_log.info('[%s] requested a video.', user_desc(upd))
self.set_manual_recording()
self.buffered_recorder_plugin.record(info=upd, stop_after_seconds=RatcamTelegramPlugin._video_duration())
self.buffered_recorder_plugin.record(info=upd, stop_after_seconds=SETTINGS.ratcam.get(
'video_duration', cast_to_type=float, ge=1., le=60., default=8.))
def handle_media(self, media):
if self.root_telegram_plugin is None or not os.path.isfile(media.path):
......@@ -198,11 +184,11 @@ class RatcamTelegramPlugin(TelegramProcessBase, MediaReceiver, MotionDetectorRes
try:
with open(media.path, 'rb') as fp:
if media.kind in _KNOWN_PHOTO_KINDS:
self.root_telegram_plugin.broadcast_photo(recipients, fp,
timeout=RatcamTelegramPlugin._photo_timeout())
self.root_telegram_plugin.broadcast_photo(recipients, fp, timeout=SETTINGS.telegram.get(
'photo_timeout', cast_to_type=float, ge=5., default=20.))
elif media.kind in _KNOWN_VIDEO_KINDS:
self.root_telegram_plugin.broadcast_video(recipients, fp,
timeout=RatcamTelegramPlugin._video_timeout())
self.root_telegram_plugin.broadcast_video(recipients, fp, timeout=SETTINGS.telegram.get(
'video_timeout', cast_to_type=float, ge=5., default=60.))
except OSError:
_log.exception('Could not load media file %s.', str(media.uuid))
except:
......
......@@ -128,7 +128,7 @@ class ProcessesHost:
for the ProcessPack to contain None entries. For example
plugins = {'root_plugin': ProcessPack(None, None, MySubclassOfPluginProcessInstanceBase)}
"""
self._socket_dir = TemporaryDirectory(dir=SETTINGS.temp_folder)
self._socket_dir = TemporaryDirectory(dir=SETTINGS.get('temp_folder', cast_to_type=str, allow_none=True))
self._plugin_instances = dict({k: None for k in plugins})
self._plugin_process_host_pack = ProcessPack(*[
self.__class__._create_host(self._socket_dir.name, plugins, process)
......
......@@ -43,7 +43,8 @@ class TemporaryMP4Muxer:
def _setup_new_temp(self):
with self._lock:
self._temp_file = NamedTemporaryFile(delete=False, dir=SETTINGS.temp_folder)
self._temp_file = NamedTemporaryFile(delete=False, dir=SETTINGS.get('temp_folder', cast_to_type=str,
allow_none=True))
_log.debug('Using new temporary MP4 %s', self._temp_file.name)
self._muxer = MP4StreamMuxer(self._temp_file)
self._muxer.begin()
......
......@@ -77,7 +77,8 @@ class BufferedRecorderPlugin(PiCameraProcessBase):
def buffer_max_age(self):
if self._buffer_max_age is None:
# Lazily load this value, because we must be sure that a camera is instantiated
self._buffer_max_age = 2 * self._camera.framerate * max(1., SETTINGS.camera.buffer)
self._buffer_max_age = 2 * self._camera.framerate * \
SETTINGS.camera.get('buffer', cast_to_type=float, default=2.0, ge=1.0)
return self._buffer_max_age
@pyro_expose
......@@ -90,7 +91,8 @@ class BufferedRecorderPlugin(PiCameraProcessBase):
def sps_header_max_age(self):
if self._sps_header_max_age is None:
# Lazily load this value, because we must be sure that a camera is instantiated
self._sps_header_max_age = self._camera.framerate * max(1., SETTINGS.camera.clip_length_tolerance)
self._sps_header_max_age = self._camera.framerate * SETTINGS.camera.get(
'clip_length_tolerance', cast_to_type=float, default=1.0, ge=1.0)
return self._sps_header_max_age
@pyro_expose
......
......@@ -101,11 +101,24 @@ class MotionDetectorCameraPlugin(MotionDetectorDispatcherPlugin, PiCameraProcess
self._triggered = False
self._cached_video_frame = None
self._capture_thread = CallbackQueueThreadHost('capture_motion_image_thread', self._take_motion_image_with_info)
def _sanitizer_tpl_of(typ, default):
def _sanitizer(value):
# noinspection PyBroadException
try:
return tuple(typ(v) for v in value)
except:
return default
return _sanitizer
# Load settings' defaults
self.trigger_thresholds = SETTINGS.detector.trigger_thresholds
self.trigger_area_fractions = SETTINGS.detector.trigger_area_fractions
self.time_window = SETTINGS.detector.time_window
self._jpeg_quality = clamp(int(100 * SETTINGS.camera.jpeg_quality), 0, 100)
self.trigger_thresholds = SETTINGS.detector.get('trigger_thresholds',
sanitizer=_sanitizer_tpl_of(int, (80, 20)))
self.trigger_area_fractions = SETTINGS.detector.get('trigger_area_fractions',
sanitizer=_sanitizer_tpl_of(float, (0.0001, 0.00002)))
self.time_window = SETTINGS.detector.get('time_window', cast_to_type=float, default=2.0, ge=1.0)
self._jpeg_quality = int(100 * SETTINGS.camera.get('jpeg_quality', cast_to_type=float, default=0.5, ge=0.0,
le=1.0))
def __enter__(self):
self._capture_thread.__enter__()
......@@ -180,7 +193,8 @@ class MotionDetectorCameraPlugin(MotionDetectorDispatcherPlugin, PiCameraProcess
def _take_motion_image_with_info(self, info):
self._prepare_video_frame_cache()
with NamedTemporaryFile(delete=False, dir=SETTINGS.temp_folder) as temp_file:
with NamedTemporaryFile(delete=False, dir=SETTINGS.get('temp_folder', cast_to_type=str, allow_none=True)) as \
temp_file:
media_path = temp_file.name
_log.info('Taking motion image with info %s to %s.', str(info), media_path)
self.root_picamera_plugin.camera.capture(self._cached_video_frame, format='rgb', use_video_port=True)
......
......@@ -97,8 +97,8 @@ class PiCameraRootPlugin(PluginProcessBase):
def __init__(self):
super(PiCameraRootPlugin, self).__init__()
self._camera = PiCamera()
self._bitrate = SETTINGS.camera.bitrate
self.framerate = SETTINGS.camera.framerate
self._bitrate = SETTINGS.camera.get('bitrate', cast_to_type=int, default=750000, ge=100)
self.framerate = SETTINGS.camera.get('framerate', cast_to_type=float, default=30., ge=0.1, le=90.)
self._warmup_thread = Thread(target=self._warmup, name='PiCamera warmup thread')
def __enter__(self):
......
......@@ -20,7 +20,7 @@ _log = logging.getLogger(camel_to_snake(STILL_PLUGIN_NAME))
@make_plugin(STILL_PLUGIN_NAME, Process.CAMERA)
class StillPlugin(PluginProcessBase):
def __init__(self):
self._jpeg_quality = SETTINGS.camera.jpeg_quality
self._jpeg_quality = SETTINGS.camera.get('jpeg_quality', cast_to_type=float, default=0.5, ge=0.0, le=1.0)
self._capture_thread = CallbackQueueThreadHost('capture_still_thread', self._take_still_with_info)
def __enter__(self):
......@@ -50,7 +50,8 @@ class StillPlugin(PluginProcessBase):
_log.error('No %s is running on CAMERA! Will not take a still with info %s.',
PICAMERA_ROOT_PLUGIN_NAME, str(info))
return
with NamedTemporaryFile(delete=False, dir=SETTINGS.temp_folder) as temp_file:
with NamedTemporaryFile(delete=False, dir=SETTINGS.get('temp_folder', cast_to_type=str, allow_none=True)) as \
temp_file:
media_path = temp_file.name
_log.info('Taking still picture with info %s to %s.', str(info), media_path)
camera.camera.capture(media_path, format='jpeg', use_video_port=True, quality=self._integral_jpg_quality)
......
......@@ -79,8 +79,8 @@ class TelegramProcessBase(PluginProcessBase, HandlerBase):
@make_plugin(TELEGRAM_ROOT_PLUGIN_NAME, Process.TELEGRAM)
class TelegramRootPlugin(TelegramProcessBase):
def _save_chat_auth_storage(self):
_log.info('Saving auth storage to %s', os.path.realpath(SETTINGS.telegram.auth_file))
save_chat_auth_storage(SETTINGS.telegram.auth_file, self._auth_storage, log=_log)
_log.info('Saving auth storage to %s', os.path.realpath(SETTINGS.telegram.get('auth_file', cast_to_type=str)))
save_chat_auth_storage(SETTINGS.telegram.get('auth_file', cast_to_type=str), self._auth_storage, log=_log)
def _setup_handlers(self):
def _collect_handlers():
......@@ -216,8 +216,8 @@ class TelegramRootPlugin(TelegramProcessBase):
def __init__(self):
super(TelegramRootPlugin, self).__init__()
self._updater = Updater(token=SETTINGS.telegram.token)
self._auth_storage = load_chat_auth_storage(SETTINGS.telegram.auth_file, log=_log)
self._updater = Updater(token=SETTINGS.telegram.get('token', cast_to_type=str))
self._auth_storage = load_chat_auth_storage(SETTINGS.telegram.get('auth_file', cast_to_type=str), log=_log)
self._auth_filters = dict({
status: AuthStatusFilter(self._auth_storage, status) for status in AuthStatus
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment