-
Notifications
You must be signed in to change notification settings - Fork 0
/
feedgen.py
executable file
·181 lines (157 loc) · 4.96 KB
/
feedgen.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/usr/bin/python3
#
# media.ccc.de Roku feed generator
#
# Copyright 2019 Ben Combee
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# ------------------------------------
#
# This takes a feed configuration file, fetches the feed information from the
# media.ccc.de API endpoints, and generates a Roku-compatible feed.json file
# that can be provided to Direct Publisher.
#
# input is specified in config.yaml file. See the version in the repo
# for options and documentation.
from importlib import invalidate_caches
import sys
import re
import yaml
import json
from datetime import datetime, timezone
import requests
from cachecontrol import CacheControl
from cachecontrol.caches.file_cache import FileCache
import urllib
import langcodes
import textwrap
def nonempty_string(s):
if isinstance(s, str):
out = s.strip()
if len(out) != 0:
return out
return None
def read_config(config_filename):
stream = open(config_filename, 'r')
return yaml.safe_load(stream)
def process_recording(recording):
output = {
"dateAdded": recording["updated_at"],
"videos": [
{
"url": recording["recording_url"],
"quality": "HD",
"videoType": "MP4"
}
],
"duration": recording["length"],
"language": langcodes.standardize_tag(recording["language"])
}
return output
slug_eventid_parser = re.compile(r"\w+-(\d+)-.*")
def process_event(event):
episodeNumber = 0
match = slug_eventid_parser.match(event["slug"])
if (match):
episodeNumber = int(match.group(1))
output = {
"id": event["guid"],
"title": event["title"],
"episodeNumber": episodeNumber,
"releaseDate": event["release_date"],
"credits": [],
"content": {},
"thumbnail": event["poster_url"],
"shortDescription": textwrap.shorten(
nonempty_string(event["subtitle"]) or nonempty_string(event["description"]) or event["title"],
width=200,
placeholder="..."),
"longDescription": textwrap.shorten(
nonempty_string(event["description"]) or event["title"],
width=500,
placeholder="...")
}
print("Loading event ", event["url"], file=sys.stderr)
r = sess.get(event["url"])
r.raise_for_status()
event_data = r.json()
for person in event_data["persons"]:
output["credits"].append({
"role": "actor",
"name": person
})
for recording in event_data["recordings"]:
if recording["language"] in languages \
and recording["folder"] == "h264-hd":
output["content"] = process_recording(recording)
break
# don't allow items with no content
if output["content"] == {}:
raise RuntimeError
return output
def process_conference(conf, languages, genres):
print("Loading conf ", conf["url"], file=sys.stderr)
r = sess.get(conf["url"])
r.raise_for_status()
conf_data = r.json()
season = {
"seasonNumber": 1,
"episodes": []
}
output = {
"id": conf_data["slug"],
"title": conf_data["title"],
"genres": genres,
"tags": conf["tags"],
"thumbnail": conf["thumbnail"],
"releaseDate": conf["releaseDate"],
"shortDescription": conf["shortDescription"],
"seasons": [ {
"seasonNumber": 1,
"episodes": []
} ]
}
for event in conf_data["events"]:
if event["original_language"] in languages:
try:
output["seasons"][0]["episodes"].append(process_event(event))
except RuntimeError:
print("Error: no content", file=sys.stderr)
return output
#
# main program code
#
sess = CacheControl(requests.Session(),
cache=FileCache('.web_cache', forever=True))
config = read_config("configuration.yaml")
urlPrefix = config["apiroot"]
languages = config["languages"]
genres = config["genres"]
output = config["feedHeader"]
output["lastUpdated"] = datetime.now(timezone.utc).isoformat()
output["series"] = []
for conf in config["conferences"]:
conf["url"] = urllib.parse.urljoin(urlPrefix, conf["url"])
output["series"].append(
process_conference(
conf,
languages,
genres))
print(json.dumps(output, indent=2))