1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00

77 lines
2.4 KiB
Python
Raw Normal View History

2020-02-03 02:35:11 -07:00
"""Validate OpenGraph Configuration Parameters."""
# Standard Library
2020-01-16 02:52:00 -07:00
from typing import Optional
2020-02-03 02:35:11 -07:00
from pathlib import Path
2020-01-16 02:52:00 -07:00
2020-02-03 02:35:11 -07:00
# Third Party
2020-01-16 02:52:00 -07:00
import PIL.Image as PilImage
2020-02-03 02:35:11 -07:00
from pydantic import FilePath, StrictInt, root_validator
2020-01-16 02:52:00 -07:00
2020-02-03 02:35:11 -07:00
# Project
2020-01-16 02:52:00 -07:00
from hyperglass.configuration.models._utils import HyperglassModel
class OpenGraph(HyperglassModel):
2020-01-28 08:59:27 -07:00
"""Validation model for params.opengraph."""
2020-01-16 02:52:00 -07:00
width: Optional[StrictInt]
height: Optional[StrictInt]
image: Optional[FilePath]
2020-02-01 16:11:01 -10:00
@root_validator
def validate_image(cls, values):
2020-01-16 02:52:00 -07:00
"""Set default opengraph image location.
Arguments:
value {FilePath} -- Path to opengraph image file.
Returns:
{Path} -- Opengraph image file path object
"""
2020-02-01 16:11:01 -10:00
supported_extensions = (".jpg", ".jpeg", ".png")
if (
2020-02-03 02:35:11 -07:00
values["image"] is not None
and values["image"].suffix not in supported_extensions
2020-02-01 16:11:01 -10:00
):
raise ValueError(
"OpenGraph image must be one of {e}".format(
e=", ".join(supported_extensions)
)
)
if values["image"] is None:
image = (
2020-01-16 02:52:00 -07:00
Path(__file__).parent.parent.parent
2020-01-17 02:50:57 -07:00
/ "static/images/hyperglass-opengraph.png"
2020-01-16 02:52:00 -07:00
)
2020-02-01 16:11:01 -10:00
values["image"] = "".join(str(image).split("static")[1::])
with PilImage.open(image) as img:
2020-01-16 02:52:00 -07:00
width, height = img.size
2020-02-01 16:11:01 -10:00
if values["width"] is None:
values["width"] = width
if values["height"] is None:
values["height"] = height
return values
class Config:
"""Pydantic model configuration."""
2020-01-16 02:52:00 -07:00
2020-02-01 16:11:01 -10:00
title = "OpenGraph"
description = "OpenGraph configuration parameters"
fields = {
"width": {
"title": "Width",
"description": "Width of OpenGraph image. If unset, the width will be automatically derived by reading the image file.",
},
"height": {
"title": "Height",
"description": "Height of OpenGraph image. If unset, the height will be automatically derived by reading the image file.",
},
"image": {
"title": "Image File",
"description": "Valid path to a JPG or PNG file to use as the OpenGraph image.",
},
}