-
Notifications
You must be signed in to change notification settings - Fork 0
/
emby.py
80 lines (69 loc) · 2.5 KB
/
emby.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
#! /usr/bin/env python3
import json
from time import sleep
from typing import Dict, List, Optional, Sequence, Union
import requests
from log import logger
from settings import EMBY_API_TOKEN, EMBY_BASE_URL
class Emby:
"Emby Class"
def __init__(
self, base_url: str = EMBY_BASE_URL, token: str = EMBY_API_TOKEN
) -> None:
self.token = token
self.base_url = base_url
@property
def libraries(self) -> List[Dict[str, str]]:
res = requests.get(
f"{self.base_url}/Library/SelectableMediaFolders?api_key={self.token}"
)
if res.status_code != requests.codes.ok:
logger.error(f"Error: fail to get libraries: {res.text}")
res.raise_for_status()
_libraries = []
for lib in res.json():
name = lib.get("Name")
subfolders = lib.get("SubFolders")
for _ in subfolders:
path = _.get("Path")
_libraries.append({"library": name, "path": path})
return _libraries
def get_library_by_location(self, path: str) -> Optional[str]:
"""通过路径获取库"""
for lib in self.libraries:
if path.startswith(lib.get("path")):
return lib.get("library")
return None
def scan(self, path: Union[str, Sequence]) -> None:
"""发送扫描请求"""
if isinstance(path, str):
path = [path]
_path = set(path)
for p in set(path):
lib = self.get_library_by_location(p)
if not lib:
logger.warning(f"Warning: library not found for {p}")
_path.remove(p)
if not _path:
return
payload = {"Updates": [{"Path": p} for p in _path]}
headers = {"Content-Type": "application/json"}
while True:
try:
res = requests.post(
url=f"{self.base_url}/Library/Media/Updated?api_key={self.token}",
data=json.dumps(payload),
headers=headers,
)
res.raise_for_status()
except (requests.Timeout, requests.ConnectionError) as e:
logger.error(e)
sleep(10)
continue
except requests.HTTPError:
logger.error(f"Error: {res.status_code}, {res.text}")
sleep(10)
continue
else:
logger.info(f"Sent scan request successfully: {_path}")
break