Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NotifyEmbyJellyfin extension #1

Merged
merged 4 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
name: release

on:
push:
tags:
- "v*"

jobs:
release:
uses: nzbgetcom/nzbget-extensions/.github/workflows/extension-release.yml@main
with:
release-file-list: main.py manifest.json
release-file-name: notifyembyjellyfin
release-dir: NotifyEmbyJellyfin
19 changes: 19 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: tests

on:
push:
branches:
- feature/*
- main
pull_request:
branches:
- main

jobs:
tests:
uses: nzbgetcom/nzbget-extensions/.github/workflows/python-tests.yml@main
with:
python-versions: "3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12"
supported-python-versions: "3.8 3.9 3.10 3.11 3.12"
test-script: tests.py
debug: true
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
>This extension is compatible to Python 3.8 and above.

## NZBGet Versions

- stable v23 [v1.0](https://github.com/nzbgetcom/Extension-NotifyEmbyJellyfin/releases/tag/v1.0)

# Notify Emby or Jellyfin

NZBGet [Post-Processing](https://github.com/nzbgetcom/nzbget/blob/develop/docs/extensions/POST-PROCESSING.md) extension to trigger Emby or Jellyfin after downloads.
118 changes: 118 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
#
# This file is part of nzbget. See <https://nzbget.com>.
#
# Copyright (C) 2024 Denis <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#


import os
import sys
import urllib.parse
import urllib.request

SUCCESS = 93
ERROR = 94
NONE = 95


REQUIRED_OPTIONS = [
"NZBPO_APIKEY",
"NZBPO_HOST",
"NZBPO_PORT",
]


def validate_options(options: list) -> None:
for optname in options:
if optname not in os.environ:
print(
f"[ERROR] Option {optname[6:]} is missing in configuration file. Please check extension settings."
)
sys.exit(ERROR)


validate_options(REQUIRED_OPTIONS)


API_KEY = os.environ["NZBPO_APIKEY"]
HOST = os.environ["NZBPO_HOST"]
PORT = os.environ["NZBPO_PORT"]


VERBOSE = os.environ["NZBPO_VERBOSE"] == "yes"
COMMAND = os.environ.get("NZBCP_COMMAND") == "ping"

URL = f"http://{HOST}:{PORT}"


if VERBOSE:
print("[INFO] URL:", URL)


def ping_server(url: str) -> int:
req_url = f"{url}/System/Ping"

if VERBOSE:
print(f"[INFO] REQUEST URL: {req_url}")

try:
req = urllib.request.Request(req_url)
with urllib.request.urlopen(req) as response:
data = response.read().decode("utf-8")

print(
f"[INFO] Server pinged successfully: {data}",
)
return SUCCESS

except Exception as ex:
print(f"[ERROR] Unexpected exception: {ex}. Wrong API key?")
return ERROR


def refresh_library(url) -> int:
req_url = f"{url}/Library/Refresh"
headers = {"Authorization": f'MediaBrowser Client="NZBGet", Token="{API_KEY}"'}

if VERBOSE:
print(f"[INFO] REQUEST URL: {req_url}")
print(f"[INFO] HEADERS: {headers}")

try:
req = urllib.request.Request(req_url, headers=headers, method="POST")
with urllib.request.urlopen(req) as response:
data = response.read().decode("utf-8")

print(f"[INFO] The library refreshed successfully: {data}")
return SUCCESS

except Exception as ex:
print(f"[ERROR] Unexpected exception: {ex}")
return ERROR


if COMMAND:
sys.exit(ping_server(URL))


PATH = os.environ.get("NZBPP_FINALDIR") or os.environ["NZBPP_DIRECTORY"]


if VERBOSE:
print(f"[INFO] PATH: {PATH}")


sys.exit(refresh_library(URL))
70 changes: 70 additions & 0 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"main": "main.py",
"name": "NotifyEmbyJellyfin",
"homepage": "https://github.com/nzbgetcom/Extension-NotifyEmbyJellyfin/",
"kind": "POST-PROCESSING",
"displayName": "Notify Emby/Jellyfin",
"version": "1.0",
"nzbgetMinVersion": "23.0",
"author": "Denis",
"license": "GNU",
"about": "Post-Processing extension to trigger Emby/Jellyfin after downloads.",
"queueEvents": "",
"description": [],
"requirements": [
"This extension supports Python 3.8 and above."
],
"options": [
{
"name": "host",
"displayName": "Host",
"value": "127.0.0.1",
"description": [
"Emby/Jellyfin server host."
],
"select": []
},
{
"name": "port",
"displayName": "Port",
"value": 8096,
"description": [
"Default port is: 8096"
],
"select": [1, 65535]
},
{
"name": "apiKey",
"displayName": "API Key",
"value": "<API KEY>",
"description": [
"Used to authenticate and authorize access to an Emby/Jellyfin API.",
"",
"Can be created in the settings of the web interface of Emby/Jellyfin."
],
"select": []
},
{
"name": "Verbose",
"displayName": "Verbose",
"value": "no",
"description": [
"Print more logging messages.",
"",
"For debugging."
],
"select": ["no", "yes"]
}
],
"commands": [
{
"name": "ping",
"displayName": "Ping",
"action": "Ping Emby/Jellyfin",
"description": [
"Ping Emby/Jellyfin to check if it is running."
]
}
],
"taskTime": ""
}
138 changes: 138 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
#
# This file is part of nzbget. See <https://nzbget.com>.
#
# Copyright (C) 2024 Denis <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#


import sys
from os.path import dirname
import os
import subprocess
import http.server
import threading
import unittest
import json
from urllib.parse import urlparse

SUCCESS = 93
NONE = 95
ERROR = 94

ROOT_DIR = dirname(__file__)
HOST = "127.0.0.1"
PORT = "8096"


class HttpServerGetMock(http.server.BaseHTTPRequestHandler):
def do_GET(self):
parsed_url = urlparse(self.path)

data = ""
if parsed_url.path == "/System/Ping":
data = "success"
self.send_response(200)
else:
data = "failure"
self.send_response(400)

self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()

data = "success"
self.wfile.write(data.encode("utf-8"))


class HttpPostMock(http.server.BaseHTTPRequestHandler):
def do_POST(self):
parsed_url = urlparse(self.path)

data = ""
if parsed_url.path == "/Library/Refresh":
data = "success"
self.send_response(200)
else:
data = "failure"
self.send_response(400)

self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(data.encode("utf-8"))


def get_python():
if os.name == "nt":
return "python"
return "python3"


def run_script():
sys.stdout.flush()
proc = subprocess.Popen(
[get_python(), ROOT_DIR + "/main.py"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=os.environ.copy(),
)
out, err = proc.communicate()
ret_code = proc.returncode
return (out.decode(), int(ret_code), err.decode())


def set_default_env():
os.environ["NZBPO_APIKEY"] = "API_KEY"
os.environ["NZBPP_DIRECTORY"] = ROOT_DIR
os.environ["NZBPO_HOST"] = HOST
os.environ["NZBPO_PORT"] = PORT
os.environ["NZBPO_VERBOSE"] = "yes"


class Tests(unittest.TestCase):
def test_command(self):
set_default_env()
os.environ["NZBCP_COMMAND"] = "ping"
server = http.server.HTTPServer((HOST, int(PORT)), HttpServerGetMock)
thread = threading.Thread(target=server.serve_forever)
thread.start()
[_, code, _] = run_script()
server.shutdown()
server.server_close()
thread.join()
self.assertEqual(code, SUCCESS)

def test_refresh_lib(self):
set_default_env()
os.environ.pop("NZBCP_COMMAND", None)
server = http.server.HTTPServer((HOST, int(PORT)), HttpPostMock)
thread = threading.Thread(target=server.serve_forever)
thread.start()
[_, code, _] = run_script()
server.shutdown()
server.server_close()
thread.join()
self.assertEqual(code, SUCCESS)

def test_manifest(self):
with open(ROOT_DIR + "/manifest.json", encoding="utf-8") as file:
try:
json.loads(file.read())
except ValueError as e:
self.fail(f"manifest.json is not valid: {e}")


if __name__ == "__main__":
unittest.main()