lanonna/jellyfin-fml/main.py

89 lines
2.4 KiB
Python
Raw Normal View History

2024-03-25 15:01:17 +01:00
import os
import time
def read_conf():
import tomllib
with open('/etc/jellyfin-fml.toml', 'rb') as fp:
conf = tomllib.load(fp)
return (conf['configuration']['mq_host'],
conf['configuration']['mq_user'],
2024-03-25 15:13:36 +01:00
conf['configuration']['mq_password'],
conf['configuration']['matrix_room'])
2024-03-25 15:01:17 +01:00
2024-03-25 15:09:32 +01:00
2024-03-25 15:01:17 +01:00
def remaining_space_gb():
from shutil import disk_usage
total, used, free = disk_usage("/")
return free / 1024**3
2024-03-25 15:09:32 +01:00
def all_transcodes():
2024-03-25 15:01:17 +01:00
folder_path = '/var/lib/jellyfin/transcodes'
files = os.listdir(folder_path)
a = []
for file in files:
file_path = os.path.join(folder_path, file)
creation_time = os.path.getctime(file_path)
2024-03-25 15:09:32 +01:00
space = os.path.getsize(file_path)
a.append((file, creation_time, space))
return a
def pop(files):
2024-03-25 15:09:58 +01:00
if files:
files.sort(key=lambda t: t[1])
return files[0]
2024-03-25 15:01:17 +01:00
else:
return None
2024-03-25 15:13:36 +01:00
def send_to_mq(mq_host, mq_user, mq_pass, matrix_room, space_rem, transcode_space):
2024-03-25 15:01:17 +01:00
import pika
import json
creds = pika.PlainCredentials(mq_user, mq_pass)
params = pika.ConnectionParameters(mq_host, 5672, "/", creds)
conn = pika.BlockingConnection(params)
channel = conn.channel()
space_rem = round(space_rem, 2)
2024-03-25 15:09:32 +01:00
msg = f'Paperino, manca spazio su disco: {space_rem}|{transcode_space}'
2024-03-25 15:01:17 +01:00
response = {
'content': msg,
'source_message_id': None,
2024-03-25 15:13:36 +01:00
'room_id': matrix_room,
2024-03-25 15:01:17 +01:00
'as_reply': False,
'as_markdown': False,
}
mq_msg = json.dumps(response).encode()
# channel.queue_declare(queue='jellyfin-fml')
channel.basic_publish(exchange='', routing_key='lanonna', body=mq_msg)
conn.close()
2024-03-25 15:13:36 +01:00
def main(mq_host, mq_user, mq_pass, matrix_room):
2024-03-25 15:01:17 +01:00
while True:
space_rem = remaining_space_gb()
2024-03-25 15:09:32 +01:00
if space_rem >= 1.0:
time.sleep(60)
else:
files = all_transcodes()
total_space = sum(map(lambda t: t[2], files))
2024-03-25 15:13:36 +01:00
send_to_mq(mq_host, mq_user, mq_pass, matrix_room, space_rem, total_space)
2024-03-25 15:01:17 +01:00
while remaining_space_gb() < 2.0:
2024-03-25 15:09:32 +01:00
file = pop(files)
if not file:
break
else:
os.remove(file)
files = all_transcodes()
2024-03-25 15:01:17 +01:00
if __name__ == '__main__':
2024-03-25 15:13:36 +01:00
mq_host, mq_user, mq_pass, matrix_room = read_conf()
main(mq_host, mq_user, mq_pass, matrix_room)