Skip to content

Helpers

psengine.playbook_alerts.helpers

save_pba_images

save_pba_images(
    playbook_alerts: PBA_WITH_IMAGES_TYPE
    | list[PBA_WITH_IMAGES_TYPE],
    output_directory: str = DEFAULT_ALERTS_OUTPUT_DIR,
) -> None

Save images/screenshots to disk as a .png file.

PARAMETER DESCRIPTION
playbook_alerts

Single or list of alerts that contains images.

TYPE: PBA_WITH_IMAGES_TYPE | list[PBA_WITH_IMAGES_TYPE]

output_directory

A directory to save the images to.

TYPE: str DEFAULT: DEFAULT_ALERTS_OUTPUT_DIR

RAISES DESCRIPTION
TypeError

If alerts are not objects part of the PBA_WITH_IMAGES_TYPE tuple.

WriteFileError

If the image save fails with an OSError.

Source code in psengine/playbook_alerts/helpers.py
@debug_call
def save_pba_images(
    playbook_alerts: Annotated[
        PBA_WITH_IMAGES_TYPE | list[PBA_WITH_IMAGES_TYPE],
        Doc('Single or list of alerts that contains images.'),
    ],
    output_directory: Annotated[
        str, Doc('A directory to save the images to.')
    ] = DEFAULT_ALERTS_OUTPUT_DIR,
) -> None:
    """Save images/screenshots to disk as a `.png` file.

    Raises:
        TypeError: If alerts are not objects part of the PBA_WITH_IMAGES_TYPE tuple.
        WriteFileError: If the image save fails with an `OSError`.
    """
    if not isinstance(playbook_alerts, (list, *PBA_WITH_IMAGES_INST)):
        raise TypeError(f'Image saving is only supported by {PBA_WITH_IMAGES_INST} alerts')

    playbook_alerts = playbook_alerts if isinstance(playbook_alerts, list) else [playbook_alerts]
    if not all(isinstance(alert, PBA_WITH_IMAGES_INST) for alert in playbook_alerts):
        raise TypeError(f'Image saving is only supported by {PBA_WITH_IMAGES_INST} alerts')

    for alert in playbook_alerts:
        LOG.info(f'Saving {len(alert.images)} image(s) to disk for alert {alert.playbook_alert_id}')
        for image_id, meta in alert.images.items():
            file_name = f'{alert.playbook_alert_id[5:]}_{image_id[4:]}'
            _save_image(
                file_name=file_name,
                image_bytes=meta['image_bytes'],
                output_directory=output_directory,
            )