2024-08-16, 09:27 PM
import requests
import logging
import os
from flask import current_app as app
from dotenv import load_dotenv
load_dotenv() # Essa chamada deve estar antes de acessar variáveis de ambiente
JELLYFIN_URL = os.getenv("JELLYFIN_URL")
REQUIRESELEVATION_API_KEY = os.getenv("REQUIRESELEVATION_API_KEY")
DEFAULTAUTHORIZATION_API_KEY = os.getenv("DEFAULTAUTHORIZATION_API_KEY")
PRODUCT_ID_BASICO = os.getenv("PRODUCT_ID_BASICO")
PRODUCT_ID_ESTANDAR = os.getenv("PRODUCT_ID_ESTANDAR")
PRODUCT_ID_PREMIUM = os.getenv("PRODUCT_ID_PREMIUM")
def create_jellyfin_user(username, password):
url = f"{JELLYFIN_URL}/Users/New"
headers = {"X-Emby-Token": REQUIRESELEVATION_API_KEY}
payload = {"Name": username, "Password": password}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"Jellyfin user created successfully for {username}") # Log de sucesso
if response.status_code == 200:
return response.json() # Retorna as informações do novo usuário se houver retorno
return None # Retorna None para status 204, pois geralmente não há corpo de resposta
else:
app.logger.error(f"Failed to create Jellyfin user with status code {response.status_code}")
return None
def update_user_configuration(jellyfin_user_id):
url = f"{JELLYFIN_URL}/Users/{jellyfin_user_id}/Configuration"
payload = {
"AudioLanguagePreference": "spa",
"PlayDefaultAudioTrack": False,
"SubtitleLanguagePreference": "spa",
"DisplayMissingEpisodes": False,
"SubtitleMode": "None"
}
headers = {"X-Emby-Token": DEFAULTAUTHORIZATION_API_KEY}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"User configuration updated successfully.")
return response.status_code # Retorna o status code para indicar sucesso
else:
app.logger.error(f"Failed to update user configuration with status code {response.status_code}")
return response.status_code # Continua retornando o status code para indicar o tipo de erro
def update_user_policy(jellyfin_user_id, product_id):
# Mapeamento de product_id para max_sessions usando variáveis carregadas
session_limits = {
PRODUCT_ID_BASICO: 1, # Assinatura básica permite 1 sessão
PRODUCT_ID_ESTANDAR: 2, # Assinatura padrão permite 2 sessões
PRODUCT_ID_PREMIUM: 4 # Assinatura premium permite 4 sessões
}
# Recupera o limite de sessões baseado no product_id, padrão para 1 se não mapeado
max_sessions = session_limits.get(product_id, 1)
url = f"{JELLYFIN_URL}/Users/{jellyfin_user_id}/Policy"
payload = {
'IsAdministrator': False,
'IsHidden': True,
'EnableCollectionManagement': False,
'EnableSubtitleManagement': False,
'EnableLyricManagement': False,
'EnableLiveTvManagement': False,
'EnableLiveTvAccess': False,
'EnableContentDownloading': False,
'InvalidLoginAttemptCount': 6,
'LoginAttemptsBeforeLockout': 6,
'MaxActiveSessions': max_sessions,
'EnableAllChannels': False,
'AuthenticationProviderId': "Jellyfin.Server.Implementations.Users.DefaultAuthenticationProvider",
'PasswordResetProviderId': "Jellyfin.Server.Implementations.Users.DefaultPasswordResetProvider",
'SyncPlayAccess': "None"
}
headers = {"X-Emby-Token": REQUIRESELEVATION_API_KEY}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"User policy updated successfully with product ID: {product_id}")
return response.status_code
else:
app.logger.error(f"Failed to update user policy for user: status code {response.status_code}")
return response.status_code
def disable_user(jellyfin_user_id):
url = f"{JELLYFIN_URL}/Users/{jellyfin_user_id}/Policy"
payload = {
'IsAdministrator': False,
'EnableContentDownloading': False,
'IsHidden': True,
'IsDisabled': True,
'AuthenticationProviderId': "Jellyfin.Server.Implementations.Users.DefaultAuthenticationProvider",
'PasswordResetProviderId': "Jellyfin.Server.Implementations.Users.DefaultPasswordResetProvider"
}
headers = {"X-Emby-Token": REQUIRESELEVATION_API_KEY}
try:
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"User disabled successfully for user ID: {jellyfin_user_id}")
return response.status_code # Retorna o status code para indicar sucesso
else:
app.logger.error(f"Failed to disable user with user ID: {jellyfin_user_id}, status code {response.status_code}")
return response.status_code # Retorna o status code mesmo em caso de falha
except requests.exceptions.RequestException as e:
app.logger.error(f"Failed to disable user with user ID: {jellyfin_user_id} due to network error: {e}")
return None # Retorna None para indicar uma falha na chamada da API
def check_server_connectivity():
url = f"{JELLYFIN_URL}/System/Ping"
try:
response = requests.get(url)
if response.status_code == 200:
app.logger.info("Jellyfin server is online.")
return True
else:
app.logger.warning(f"Failed to ping Jellyfin server with status code {response.status_code}")
return False
except requests.exceptions.RequestException as e:
app.logger.error(f"Failed to ping Jellyfin server due to network error: {e}")
return False
.
Don't worry about the comments in the script, they're in Portuguese. Just to provide more information, the API keys I'm using were created within the server for both REQUIRESELEVATION and DEFAULTAUTHORIZATION. I've also tested using the administrator's access token for REQUIRESELEVATION_API_KEY, but I encountered the same issue with the "first two users."
import logging
import os
from flask import current_app as app
from dotenv import load_dotenv
load_dotenv() # Essa chamada deve estar antes de acessar variáveis de ambiente
JELLYFIN_URL = os.getenv("JELLYFIN_URL")
REQUIRESELEVATION_API_KEY = os.getenv("REQUIRESELEVATION_API_KEY")
DEFAULTAUTHORIZATION_API_KEY = os.getenv("DEFAULTAUTHORIZATION_API_KEY")
PRODUCT_ID_BASICO = os.getenv("PRODUCT_ID_BASICO")
PRODUCT_ID_ESTANDAR = os.getenv("PRODUCT_ID_ESTANDAR")
PRODUCT_ID_PREMIUM = os.getenv("PRODUCT_ID_PREMIUM")
def create_jellyfin_user(username, password):
url = f"{JELLYFIN_URL}/Users/New"
headers = {"X-Emby-Token": REQUIRESELEVATION_API_KEY}
payload = {"Name": username, "Password": password}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"Jellyfin user created successfully for {username}") # Log de sucesso
if response.status_code == 200:
return response.json() # Retorna as informações do novo usuário se houver retorno
return None # Retorna None para status 204, pois geralmente não há corpo de resposta
else:
app.logger.error(f"Failed to create Jellyfin user with status code {response.status_code}")
return None
def update_user_configuration(jellyfin_user_id):
url = f"{JELLYFIN_URL}/Users/{jellyfin_user_id}/Configuration"
payload = {
"AudioLanguagePreference": "spa",
"PlayDefaultAudioTrack": False,
"SubtitleLanguagePreference": "spa",
"DisplayMissingEpisodes": False,
"SubtitleMode": "None"
}
headers = {"X-Emby-Token": DEFAULTAUTHORIZATION_API_KEY}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"User configuration updated successfully.")
return response.status_code # Retorna o status code para indicar sucesso
else:
app.logger.error(f"Failed to update user configuration with status code {response.status_code}")
return response.status_code # Continua retornando o status code para indicar o tipo de erro
def update_user_policy(jellyfin_user_id, product_id):
# Mapeamento de product_id para max_sessions usando variáveis carregadas
session_limits = {
PRODUCT_ID_BASICO: 1, # Assinatura básica permite 1 sessão
PRODUCT_ID_ESTANDAR: 2, # Assinatura padrão permite 2 sessões
PRODUCT_ID_PREMIUM: 4 # Assinatura premium permite 4 sessões
}
# Recupera o limite de sessões baseado no product_id, padrão para 1 se não mapeado
max_sessions = session_limits.get(product_id, 1)
url = f"{JELLYFIN_URL}/Users/{jellyfin_user_id}/Policy"
payload = {
'IsAdministrator': False,
'IsHidden': True,
'EnableCollectionManagement': False,
'EnableSubtitleManagement': False,
'EnableLyricManagement': False,
'EnableLiveTvManagement': False,
'EnableLiveTvAccess': False,
'EnableContentDownloading': False,
'InvalidLoginAttemptCount': 6,
'LoginAttemptsBeforeLockout': 6,
'MaxActiveSessions': max_sessions,
'EnableAllChannels': False,
'AuthenticationProviderId': "Jellyfin.Server.Implementations.Users.DefaultAuthenticationProvider",
'PasswordResetProviderId': "Jellyfin.Server.Implementations.Users.DefaultPasswordResetProvider",
'SyncPlayAccess': "None"
}
headers = {"X-Emby-Token": REQUIRESELEVATION_API_KEY}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"User policy updated successfully with product ID: {product_id}")
return response.status_code
else:
app.logger.error(f"Failed to update user policy for user: status code {response.status_code}")
return response.status_code
def disable_user(jellyfin_user_id):
url = f"{JELLYFIN_URL}/Users/{jellyfin_user_id}/Policy"
payload = {
'IsAdministrator': False,
'EnableContentDownloading': False,
'IsHidden': True,
'IsDisabled': True,
'AuthenticationProviderId': "Jellyfin.Server.Implementations.Users.DefaultAuthenticationProvider",
'PasswordResetProviderId': "Jellyfin.Server.Implementations.Users.DefaultPasswordResetProvider"
}
headers = {"X-Emby-Token": REQUIRESELEVATION_API_KEY}
try:
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200 or response.status_code == 204:
app.logger.info(f"User disabled successfully for user ID: {jellyfin_user_id}")
return response.status_code # Retorna o status code para indicar sucesso
else:
app.logger.error(f"Failed to disable user with user ID: {jellyfin_user_id}, status code {response.status_code}")
return response.status_code # Retorna o status code mesmo em caso de falha
except requests.exceptions.RequestException as e:
app.logger.error(f"Failed to disable user with user ID: {jellyfin_user_id} due to network error: {e}")
return None # Retorna None para indicar uma falha na chamada da API
def check_server_connectivity():
url = f"{JELLYFIN_URL}/System/Ping"
try:
response = requests.get(url)
if response.status_code == 200:
app.logger.info("Jellyfin server is online.")
return True
else:
app.logger.warning(f"Failed to ping Jellyfin server with status code {response.status_code}")
return False
except requests.exceptions.RequestException as e:
app.logger.error(f"Failed to ping Jellyfin server due to network error: {e}")
return False
.
Don't worry about the comments in the script, they're in Portuguese. Just to provide more information, the API keys I'm using were created within the server for both REQUIRESELEVATION and DEFAULTAUTHORIZATION. I've also tested using the administrator's access token for REQUIRESELEVATION_API_KEY, but I encountered the same issue with the "first two users."