-
Notifications
You must be signed in to change notification settings - Fork 0
/
NotificationSchema.py
91 lines (78 loc) · 2.42 KB
/
NotificationSchema.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import yaml
import json
from enum import Enum
from typing import Optional
from uuid import UUID
from datetime import datetime
from pydantic import BaseModel, Field, HttpUrl, RootModel, model_validator
class ChannelEnum(str, Enum):
default = "default"
esr = "esr"
release = "release"
beta = "beta"
daily = "daily"
class OperatingSystemEnum(str, Enum):
win = "win"
macosx = "macosx"
linux = "linux"
freebsd = "freebsd"
openbsd = "openbsd"
netbsd = "netbsd"
solaris = "solaris"
other = "other"
class Profile(BaseModel):
locales: list[str] | None = None
versions: list[str] | None = None
channels: list[ChannelEnum] | None = None
operating_systems: list[OperatingSystemEnum] | None = None
class SeverityEnum(int, Enum):
one = 1
two = 2
three = 3
four = 4
five = 5
class TypeEnum(str, Enum):
donation = "donation"
message = "message"
security = "security"
blog = "blog"
class Targeting(BaseModel):
percent_chance: Optional[float] = Field(None, ge=0, le=100)
exclude: list[Profile] | None = None
include: list[Profile] | None = None
class Notification(BaseModel):
id: UUID
start_at: datetime
end_at: datetime
title: str
description: str
URL: HttpUrl | None = None
CTA: str | None = None
severity: SeverityEnum
type: TypeEnum
targeting: Targeting
@model_validator(mode="after")
def cta_requires_url(self):
if self.CTA and not self.URL:
raise ValueError("if 'CTA' is present, 'URL' must be present too")
return self
class NotificationSchema(RootModel):
root: list[Notification]
def yaml_to_data(yaml_str):
"""Static method to load YAML from a string and return the corresponding python object"""
try:
return yaml.safe_load(yaml_str)
except yaml.YAMLError as e:
print(f'Error parsing YAML file: {e}')
return None
def from_yaml(file_name):
"""Static method to generate NotificationSchema from a yaml file"""
with open(file_name, "r") as fh:
contents = fh.read()
data = NotificationSchema.yaml_to_data(contents)
return NotificationSchema(data)
def generate_json_schema(schema_file_name):
"""Static method to write a JSON schema file based on pydantic model"""
schema = NotificationSchema.model_json_schema()
with open(schema_file_name, "w") as f:
f.write(json.dumps(schema, indent=2))