-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
339 lines (310 loc) · 9.27 KB
/
main.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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""Stores daily data from ACRCloud's broadcast monitoring service in ownCloud."""
from __future__ import annotations
import json
from datetime import datetime, timedelta
from functools import cache
from io import BytesIO
from logging import getLogger
from pathlib import Path
from typing import Any
import urllib3
from acrclient import Client as ACRClient
from acrclient.models import GetBmCsProjectsResultsParams
from configargparse import ArgParser # type: ignore[import-untyped]
from minio import Minio # type: ignore[import-untyped]
from minio.error import S3Error # type: ignore[import-untyped]
from owncloud import Client as OwnCloudClient # type: ignore[import-untyped]
from owncloud.owncloud import HTTPResponseError # type: ignore[import-untyped]
# type: ignore[import-untyped]
from tqdm import tqdm
logger = getLogger(__name__)
def daterange(start_date: datetime, end_date: datetime) -> list[datetime]:
"""Get range to load."""
return [start_date + timedelta(n) for n in range(int((end_date - start_date).days))]
@cache
def oc_mkdir(oc: OwnCloudClient, path: str) -> bool:
"""Create a dir on ownCloud."""
try:
return oc.mkdir(path)
except HTTPResponseError as ex: # pragma: no cover
if str(ex) != "HTTP error: 405":
logger.exception("Failed to mkdir")
return True
@cache
def oc_file_exists(oc: OwnCloudClient, path: str) -> bool:
"""Check if file exists on ownCloud."""
try:
oc.file_info(path)
except HTTPResponseError as ex:
if str(ex) != "HTTP error: 404": # pragma: no cover
logger.exception("File missing")
return False
else:
return True
def oc_check(oc: OwnCloudClient, oc_path: str) -> list[datetime]:
"""Check ownCloud for missing files."""
missing = []
start = datetime.now() - timedelta(7) # noqa: DTZ005
for requested in tqdm(
daterange(start, datetime.now()), # noqa: DTZ005
desc="Checking ownCloud",
):
oc_mkdir(oc, oc_path)
oc_mkdir(oc, str(Path(oc_path) / str(requested.year)))
oc_mkdir(oc, str(Path(oc_path) / str(requested.year) / str(requested.month)))
status = oc_file_exists(
oc,
str(
Path(oc_path)
/ str(requested.year)
/ str(requested.month)
/ requested.strftime("%Y-%m-%d.json"),
),
)
if not status:
missing.append(requested)
return missing
def mc_check(mc: Minio, bucket: str) -> list[datetime]:
"""Check MinIO for missing files."""
missing = []
start = datetime.now() - timedelta(7) # noqa: DTZ005
for requested in tqdm(
daterange(start, datetime.now()), # noqa: DTZ005
desc="Checking MinIO",
):
try:
mc.stat_object(bucket, requested.strftime("%Y-%m-%d.json"))
except S3Error as ex: # noqa: PERF203
if ex.code == "NoSuchKey":
missing.append(requested)
return missing
@cache
def fetch_one(
acr: ACRClient,
acr_project_id: str,
acr_stream_id: str,
requested: str,
) -> Any: # noqa: ANN401
"""Fetch one "day" from ACRCloud."""
return acr.get_bm_cs_projects_results(
project_id=int(acr_project_id),
stream_id=acr_stream_id,
params=GetBmCsProjectsResultsParams(
type="day",
date=requested,
min_duration=0,
max_duration=3600,
isrc_country="",
),
)
def oc_fetch( # noqa: PLR0913
missing: list[datetime],
acr: ACRClient,
oc: OwnCloudClient,
acr_project_id: str,
acr_stream_id: str,
oc_path: str,
) -> None:
"""Fetch missing data from ACRCloud and stores it in ownCloud."""
for requested in tqdm(missing, desc="Loading into ownCloud from ACRCloud"):
target = str(
Path(oc_path)
/ str(requested.year)
/ str(requested.month)
/ requested.strftime("%Y-%m-%d.json"),
)
oc.put_file_contents(
target,
json.dumps(
fetch_one(
acr=acr,
acr_project_id=acr_project_id,
acr_stream_id=acr_stream_id,
requested=requested.strftime("%Y%m%d"),
),
),
)
def mc_fetch( # noqa: PLR0913
missing: list[datetime],
acr: ACRClient,
mc: Minio,
acr_project_id: str,
acr_stream_id: str,
bucket: str,
) -> None:
"""Fetch missing data from ACRCloud and stores it in MinIO."""
for requested in tqdm(missing, desc="Loading into MinIO from ACRCloud"):
_as_bytes = json.dumps(
fetch_one(
acr=acr,
acr_project_id=acr_project_id,
acr_stream_id=acr_stream_id,
requested=requested.strftime("%Y%m%d"),
),
).encode("utf-8")
mc.put_object(
bucket,
requested.strftime("%Y-%m-%d.json"),
BytesIO(_as_bytes),
length=len(_as_bytes),
content_type="application/json",
)
def main() -> None: # pragma: no cover
"""Fetch data from ACRCloud and stores it on-premise."""
p = ArgParser(
description=__doc__,
default_config_files=[
"/etc/acrloader.conf",
"~/.acrloader.conf",
"acrloader.conf",
],
)
p.add(
"-c",
"--my-config",
is_config_file=True,
help="config file path",
)
p.add(
"--acr-bearer-token",
required=True,
env_var="ACR_BEARER_TOKEN",
help="ACRCloud bearer token",
)
p.add(
"--acr-project-id",
required=True,
env_var="ACR_PROJECT_ID",
help="ACRCloud project id",
)
p.add(
"--acr-stream-id",
required=True,
env_var="ACR_STREAM_ID",
help="ACRCloud stream id",
)
p.add(
"--oc",
default=False,
action="store_true",
env_var="OC_ENABLE",
help="Enable ownCloud",
)
p.add(
"--oc-url",
default="https://share.rabe.ch",
env_var="OC_URL",
help="ownCloud URL",
)
p.add(
"--oc-user",
required=True,
env_var="OC_USER",
help="ownCloud user",
)
p.add(
"--oc-pass",
required=True,
env_var="OC_PASS",
help="ownCloud pass",
)
p.add(
"--oc-path",
default="IT/Share/ACRCloud Data",
env_var="OC_PATH",
help="ownCloud path",
)
p.add(
"--minio",
default=False,
action="store_true",
env_var="MINIO_ENABLE",
help="Enable MinIO",
)
p.add(
"--minio-url",
default="minio.service.int.rabe.ch:9000",
env_var="MINIO_HOST",
help="MinIO Hostname",
)
p.add(
"--minio-secure",
default=True,
env_var="MINIO_SECURE",
help="MinIO Secure param",
)
p.add(
"--minio-cert-reqs",
default="CERT_REQUIRED",
env_var="MINIO_CERT_REQS",
help="cert_reqs for urlib3.PoolManager used by MinIO",
)
p.add(
"--minio-ca-certs",
default="/etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt",
env_var="MINIO_CA_CERTS",
help="ca_certs for urlib3.PoolManager used by MinIO",
)
p.add(
"--minio-bucket",
default="acrcloud.raw",
env_var="MINIO_BUCKET",
help="MinIO Bucket Name",
)
p.add(
"--minio-access-key",
default=None,
env_var="MINIO_ACCESS_KEY",
help="MinIO Access Key",
)
p.add(
"--minio-secret-key",
default=None,
env_var="MINIO_SECRET_KEY",
help="MinIO Secret Key",
)
options = p.parse_args()
acr_client = ACRClient(
bearer_token=options.acr_bearer_token,
)
if options.oc:
# figure out what we are missing on ownCloud
oc = OwnCloudClient(options.oc_url)
oc.login(options.oc_user, options.oc_pass)
missing = oc_check(oc=oc, oc_path=options.oc_path)
if missing:
# fetch and store missing data
oc_fetch(
missing,
acr=acr_client,
oc=oc,
acr_project_id=options.acr_project_id,
acr_stream_id=options.acr_stream_id,
oc_path=options.oc_path,
)
if options.minio:
mc = Minio(
options.minio_url,
options.minio_access_key,
options.minio_secret_key,
secure=options.minio_secure,
http_client=urllib3.PoolManager(
cert_reqs=options.minio_cert_reqs,
ca_certs=options.minio_ca_certs,
),
)
if not mc.bucket_exists(options.minio_bucket):
mc.make_bucket(options.minio_bucket)
missing = mc_check(mc=mc, bucket=options.minio_bucket)
if missing:
# fetch and store missing data
mc_fetch(
missing,
acr=acr_client,
mc=mc,
acr_project_id=options.acr_project_id,
acr_stream_id=options.acr_stream_id,
bucket=options.minio_bucket,
)
if __name__ == "__main__": # pragma: no cover
main()