Compare commits
33
Commits
74da0d2568
...
v1.0.9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3ba704882 | ||
|
|
77bbc87a1a | ||
|
|
d4842c2361 | ||
|
|
67619a4f56 | ||
|
|
cdf53c5288 | ||
|
|
6be05158d0 | ||
|
|
4f3af0db69 | ||
|
|
76714eb0c6 | ||
|
|
f48aa86256 | ||
|
|
5a908cbe4d | ||
|
|
d890c11a9b | ||
|
|
c54221fba2 | ||
|
|
221a3f634d | ||
|
|
9ac32e11b5 | ||
|
|
bc24b40bf2 | ||
|
|
4537613ed7 | ||
|
|
003a8754a6 | ||
|
|
b4275837bc | ||
|
|
c1f7981ed7 | ||
|
|
ba497924e9 | ||
|
|
945c550901 | ||
|
|
2bcc7733b6 | ||
|
|
4679b77d1a | ||
|
|
7a9dbdafcc | ||
|
|
6277846394 | ||
|
|
d544b71939 | ||
|
|
12988e127f | ||
|
|
e9312af2c2 | ||
|
|
4291891dfd | ||
|
|
e9c9f334cd | ||
|
|
3afa1fc407 | ||
|
|
2c1143b49f | ||
|
|
7fe332f29c |
@@ -0,0 +1,52 @@
|
||||
name: '🏗️ Build Plugin'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
container:
|
||||
image: gitea.tourolle.paris/dtourolle/jellypod-builder:latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore Jellyfin.Plugin.Jellypod.sln
|
||||
|
||||
- name: Build solution
|
||||
run: dotnet build Jellyfin.Plugin.Jellypod.sln --configuration Release --no-restore --no-self-contained
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test Jellyfin.Plugin.Jellypod.sln --no-build --configuration Release --verbosity normal
|
||||
|
||||
- name: Build Jellyfin Plugin
|
||||
id: jprm
|
||||
run: |
|
||||
mkdir -p artifacts
|
||||
jprm --verbosity=debug plugin build .
|
||||
|
||||
# Find the generated zip file
|
||||
ARTIFACT=$(find . -name "*.zip" -type f -print -quit)
|
||||
echo "artifact=${ARTIFACT}" >> $GITHUB_OUTPUT
|
||||
echo "Found artifact: ${ARTIFACT}"
|
||||
|
||||
- name: Upload build artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: jellypod-plugin
|
||||
path: ${{ steps.jprm.outputs.artifact }}
|
||||
retention-days: 30
|
||||
if-no-files-found: error
|
||||
@@ -0,0 +1,157 @@
|
||||
name: '🚀 Release Plugin'
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*.*.*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
description: 'Version to release (e.g., v1.0.0)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
build-and-release:
|
||||
runs-on: ubuntu-22.04
|
||||
container:
|
||||
image: gitea.tourolle.paris/dtourolle/jellypod-builder:latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Get version
|
||||
id: get_version
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
VERSION="${{ github.event.inputs.version }}"
|
||||
else
|
||||
VERSION="${GITHUB_REF#refs/tags/}"
|
||||
fi
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "version_number=${VERSION#v}" >> $GITHUB_OUTPUT
|
||||
echo "Building version: ${VERSION}"
|
||||
|
||||
- name: Update build.yaml with version
|
||||
run: |
|
||||
VERSION="${{ steps.get_version.outputs.version_number }}"
|
||||
sed -i "s/^version:.*/version: \"${VERSION}\"/" build.yaml
|
||||
cat build.yaml
|
||||
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore Jellyfin.Plugin.Jellypod.sln
|
||||
|
||||
- name: Build solution
|
||||
run: dotnet build Jellyfin.Plugin.Jellypod.sln --configuration Release --no-restore --no-self-contained
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test Jellyfin.Plugin.Jellypod.sln --no-build --configuration Release --verbosity normal
|
||||
|
||||
- name: Build Jellyfin Plugin
|
||||
id: jprm
|
||||
run: |
|
||||
mkdir -p artifacts
|
||||
jprm --verbosity=debug plugin build ./
|
||||
|
||||
# Find the generated zip file
|
||||
ARTIFACT=$(find . -name "*.zip" -type f -print -quit)
|
||||
ARTIFACT_NAME=$(basename "${ARTIFACT}")
|
||||
echo "artifact=${ARTIFACT}" >> $GITHUB_OUTPUT
|
||||
echo "artifact_name=${ARTIFACT_NAME}" >> $GITHUB_OUTPUT
|
||||
echo "Found artifact: ${ARTIFACT}"
|
||||
|
||||
- name: Calculate checksum
|
||||
id: checksum
|
||||
run: |
|
||||
CHECKSUM=$(md5sum "${{ steps.jprm.outputs.artifact }}" | awk '{print $1}')
|
||||
echo "checksum=${CHECKSUM}" >> $GITHUB_OUTPUT
|
||||
echo "MD5 Checksum: ${CHECKSUM}"
|
||||
|
||||
- name: Create Release
|
||||
id: create_release
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
# Get repository information
|
||||
REPO_OWNER="${{ github.repository_owner }}"
|
||||
REPO_NAME="${{ github.event.repository.name }}"
|
||||
GITEA_URL="${{ github.server_url }}"
|
||||
|
||||
# Create release using Gitea API
|
||||
VERSION="${{ steps.get_version.outputs.version }}"
|
||||
RESPONSE=$(curl -s -w "\n%{http_code}" -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/json" \
|
||||
"${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/releases" \
|
||||
-d "$(jq -n --arg tag "$VERSION" --arg name "Release $VERSION" --arg body "Jellypod Jellyfin Plugin. See attached files for plugin installation." '{tag_name: $tag, name: $name, body: $body, draft: false, prerelease: false}')")
|
||||
|
||||
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
|
||||
BODY=$(echo "$RESPONSE" | sed '$d')
|
||||
|
||||
if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
|
||||
RELEASE_ID=$(echo "$BODY" | jq -r '.id')
|
||||
echo "release_id=${RELEASE_ID}" >> $GITHUB_OUTPUT
|
||||
echo "Created release with ID: ${RELEASE_ID}"
|
||||
else
|
||||
echo "Failed to create release. HTTP ${HTTP_CODE}"
|
||||
echo "$BODY"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Upload plugin artifact
|
||||
echo "Uploading plugin artifact..."
|
||||
curl -f -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/zip" \
|
||||
--data-binary "@${{ steps.jprm.outputs.artifact }}" \
|
||||
"${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/releases/${RELEASE_ID}/assets?name=${{ steps.jprm.outputs.artifact_name }}"
|
||||
|
||||
# Upload build.yaml
|
||||
echo "Uploading build.yaml..."
|
||||
curl -f -X POST \
|
||||
-H "Authorization: token ${GITEA_TOKEN}" \
|
||||
-H "Content-Type: application/x-yaml" \
|
||||
--data-binary "@build.yaml" \
|
||||
"${GITEA_URL}/api/v1/repos/${REPO_OWNER}/${REPO_NAME}/releases/${RELEASE_ID}/assets?name=build.yaml"
|
||||
|
||||
echo "Release created successfully!"
|
||||
echo "View at: ${GITEA_URL}/${REPO_OWNER}/${REPO_NAME}/releases/tag/${{ steps.get_version.outputs.version }}"
|
||||
|
||||
- name: Update manifest.json
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
REPO_OWNER="${{ github.repository_owner }}"
|
||||
REPO_NAME="${{ github.event.repository.name }}"
|
||||
GITEA_URL="${{ github.server_url }}"
|
||||
VERSION="${{ steps.get_version.outputs.version_number }}"
|
||||
CHECKSUM="${{ steps.checksum.outputs.checksum }}"
|
||||
ARTIFACT_NAME="${{ steps.jprm.outputs.artifact_name }}"
|
||||
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
DOWNLOAD_URL="${GITEA_URL}/${REPO_OWNER}/${REPO_NAME}/releases/download/${{ steps.get_version.outputs.version }}/${ARTIFACT_NAME}"
|
||||
|
||||
# Configure git
|
||||
git config user.name "Gitea Actions"
|
||||
git config user.email "actions@gitea.tourolle.paris"
|
||||
|
||||
# Fetch and checkout master branch
|
||||
git fetch origin master
|
||||
git checkout master
|
||||
|
||||
# Update manifest.json - prepend new version to versions array
|
||||
jq --arg ver "${VERSION}" \
|
||||
--arg changelog "Release ${VERSION}" \
|
||||
--arg abi "10.9.0.0" \
|
||||
--arg url "${DOWNLOAD_URL}" \
|
||||
--arg checksum "${CHECKSUM}" \
|
||||
--arg ts "${TIMESTAMP}" \
|
||||
'.[0].versions = [{version: $ver, changelog: $changelog, targetAbi: $abi, sourceUrl: $url, checksum: $checksum, timestamp: $ts}] + .[0].versions' \
|
||||
manifest.json > manifest.tmp && mv manifest.tmp manifest.json
|
||||
|
||||
# Commit and push
|
||||
git add manifest.json
|
||||
git commit -m "Update manifest.json for version ${VERSION}"
|
||||
git push origin master
|
||||
|
||||
echo "Manifest updated successfully!"
|
||||
@@ -0,0 +1,44 @@
|
||||
name: '🧪 Test Plugin'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
- develop
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
- develop
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Verify .NET installation
|
||||
run: dotnet --version
|
||||
|
||||
- name: Restore dependencies
|
||||
run: dotnet restore Jellyfin.Plugin.Jellypod.sln
|
||||
|
||||
- name: Build solution
|
||||
run: dotnet build Jellyfin.Plugin.Jellypod.sln --configuration Debug --no-restore --no-self-contained
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test Jellyfin.Plugin.Jellypod.sln --no-build --configuration Debug --verbosity normal --logger "trx;LogFileName=test-results.trx"
|
||||
|
||||
- name: Upload test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: test-results
|
||||
path: '**/test-results.trx'
|
||||
retention-days: 7
|
||||
Vendored
+1
-1
@@ -7,7 +7,7 @@
|
||||
"name": "Launch",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build-and-copy",
|
||||
"program": "${config:jellyfinDir}/bin/Debug/net6.0/jellyfin.dll",
|
||||
"program": "${config:jellyfinDir}/bin/Debug/net9.0/jellyfin.dll",
|
||||
"args": [
|
||||
//"--nowebclient"
|
||||
"--webdir",
|
||||
|
||||
Vendored
+1
-1
@@ -15,5 +15,5 @@
|
||||
"jellyfinWindowsDataDir": "${env:LOCALAPPDATA}/jellyfin",
|
||||
"jellyfinLinuxDataDir": "$HOME/.local/share/jellyfin",
|
||||
// The name of the plugin
|
||||
"pluginName": "Jellyfin.Plugin.Template",
|
||||
"pluginName": "Jellyfin.Plugin.Jellypod",
|
||||
}
|
||||
Vendored
+4
-3
@@ -20,6 +20,7 @@
|
||||
"type": "shell",
|
||||
"args": [
|
||||
"publish",
|
||||
"--configuration=Debug",
|
||||
"${workspaceFolder}/${config:pluginName}.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
@@ -59,17 +60,17 @@
|
||||
"command": "cp",
|
||||
"windows": {
|
||||
"args": [
|
||||
"./${config:pluginName}/bin/Debug/net6.0/publish/*",
|
||||
"./${config:pluginName}/bin/Debug/net9.0/publish/*",
|
||||
"${config:jellyfinWindowsDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
},
|
||||
"linux": {
|
||||
"args": [
|
||||
"-r",
|
||||
"./${config:pluginName}/bin/Debug/net6.0/publish/*",
|
||||
"./${config:pluginName}/bin/Debug/net9.0/publish/*",
|
||||
"${config:jellyfinLinuxDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0
|
||||
|
||||
# Install Python, Node.js, and tools
|
||||
RUN apt-get update && apt-get install -y \
|
||||
python3 \
|
||||
python3-pip \
|
||||
jq \
|
||||
git \
|
||||
nodejs \
|
||||
npm \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Install JPRM
|
||||
RUN pip install --break-system-packages jprm
|
||||
|
||||
WORKDIR /src
|
||||
@@ -0,0 +1,28 @@
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
#
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.Jellypod", "Jellyfin.Plugin.Jellypod\Jellyfin.Plugin.Jellypod.csproj", "{D921B930-CF91-406F-ACBC-08914DCD0D34}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x64.Build.0 = Release|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,189 @@
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Controller for serving podcast and episode images.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("Jellypod/Image")]
|
||||
public class ImageController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<ImageController> _logger;
|
||||
private readonly IPodcastStorageService _storageService;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ImageController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="storageService">Storage service instance.</param>
|
||||
/// <param name="httpClientFactory">HTTP client factory.</param>
|
||||
public ImageController(
|
||||
ILogger<ImageController> logger,
|
||||
IPodcastStorageService storageService,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_logger = logger;
|
||||
_storageService = storageService;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the image for a podcast.
|
||||
/// </summary>
|
||||
/// <param name="podcastId">The podcast ID.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The image file.</returns>
|
||||
[HttpGet("podcast/{podcastId}")]
|
||||
[AllowAnonymous]
|
||||
[SuppressMessage("Microsoft.Security", "CA3003:ReviewCodeForFilePathInjectionVulnerabilities", Justification = "Path is constructed from validated GUID and sanitized podcast title")]
|
||||
public async Task<IActionResult> GetPodcastImage(
|
||||
[FromRoute] Guid podcastId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
if (podcast == null)
|
||||
{
|
||||
return NotFound("Podcast not found");
|
||||
}
|
||||
|
||||
// Try to serve local cached image first
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
if (config?.CreatePodcastFolders == true)
|
||||
{
|
||||
var basePath = _storageService.GetStoragePath();
|
||||
var podcastFolder = Path.Combine(basePath, SanitizeFileName(podcast.Title));
|
||||
var artworkPath = Path.Combine(podcastFolder, "folder.jpg");
|
||||
|
||||
if (System.IO.File.Exists(artworkPath))
|
||||
{
|
||||
var fileStream = System.IO.File.OpenRead(artworkPath);
|
||||
return File(fileStream, "image/jpeg");
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to proxying the external URL
|
||||
if (!string.IsNullOrEmpty(podcast.ImageUrl))
|
||||
{
|
||||
return await ProxyImageAsync(podcast.ImageUrl, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return NotFound("No image available");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error serving podcast image for {PodcastId}", podcastId);
|
||||
return StatusCode(500, "Failed to serve podcast image");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the image for an episode.
|
||||
/// </summary>
|
||||
/// <param name="podcastId">The podcast ID.</param>
|
||||
/// <param name="episodeId">The episode ID.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The image file.</returns>
|
||||
[HttpGet("episode/{podcastId}/{episodeId}")]
|
||||
[AllowAnonymous]
|
||||
[SuppressMessage("Microsoft.Security", "CA3003:ReviewCodeForFilePathInjectionVulnerabilities", Justification = "Path is constructed from validated GUIDs and sanitized podcast title")]
|
||||
public async Task<IActionResult> GetEpisodeImage(
|
||||
[FromRoute] Guid podcastId,
|
||||
[FromRoute] Guid episodeId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
if (podcast == null)
|
||||
{
|
||||
return NotFound("Podcast not found");
|
||||
}
|
||||
|
||||
var episode = podcast.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
if (episode == null)
|
||||
{
|
||||
return NotFound("Episode not found");
|
||||
}
|
||||
|
||||
// Try to serve local cached episode image first
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
if (config?.CreatePodcastFolders == true)
|
||||
{
|
||||
var basePath = _storageService.GetStoragePath();
|
||||
var podcastFolder = Path.Combine(basePath, SanitizeFileName(podcast.Title));
|
||||
var episodeFileName = $"{SanitizeFileName(episode.Id.ToString())}.jpg";
|
||||
var artworkPath = Path.Combine(podcastFolder, episodeFileName);
|
||||
|
||||
if (System.IO.File.Exists(artworkPath))
|
||||
{
|
||||
var fileStream = System.IO.File.OpenRead(artworkPath);
|
||||
return File(fileStream, "image/jpeg");
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to episode ImageUrl if available
|
||||
if (!string.IsNullOrEmpty(episode.ImageUrl))
|
||||
{
|
||||
return await ProxyImageAsync(episode.ImageUrl, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Final fallback to podcast image
|
||||
if (!string.IsNullOrEmpty(podcast.ImageUrl))
|
||||
{
|
||||
return await ProxyImageAsync(podcast.ImageUrl, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return NotFound("No image available");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error serving episode image for {EpisodeId}", episodeId);
|
||||
return StatusCode(500, "Failed to serve episode image");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<IActionResult> ProxyImageAsync(string imageUrl, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var client = _httpClientFactory.CreateClient("Jellypod");
|
||||
var response = await client.GetAsync(imageUrl, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("Failed to fetch image: {StatusCode} from {Url}", response.StatusCode, imageUrl);
|
||||
return StatusCode((int)response.StatusCode);
|
||||
}
|
||||
|
||||
var contentType = response.Content.Headers.ContentType?.MediaType ?? "image/jpeg";
|
||||
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
return File(stream, contentType);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error proxying image from {Url}", imageUrl);
|
||||
return StatusCode(500, "Failed to proxy image");
|
||||
}
|
||||
}
|
||||
|
||||
private static string SanitizeFileName(string name)
|
||||
{
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
return string.Join("_", name.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Mime;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using Jellyfin.Plugin.Jellypod.Services;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Controller for Jellypod podcast management.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Authorize]
|
||||
[Route("Jellypod")]
|
||||
[Produces(MediaTypeNames.Application.Json)]
|
||||
public class JellypodController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<JellypodController> _logger;
|
||||
private readonly IRssFeedService _rssFeedService;
|
||||
private readonly IPodcastStorageService _storageService;
|
||||
private readonly IPodcastDownloadService _downloadService;
|
||||
private readonly IOpmlService _opmlService;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JellypodController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="rssFeedService">RSS feed service.</param>
|
||||
/// <param name="storageService">Storage service.</param>
|
||||
/// <param name="downloadService">Download service.</param>
|
||||
/// <param name="opmlService">OPML service.</param>
|
||||
/// <param name="httpClientFactory">HTTP client factory.</param>
|
||||
public JellypodController(
|
||||
ILogger<JellypodController> logger,
|
||||
IRssFeedService rssFeedService,
|
||||
IPodcastStorageService storageService,
|
||||
IPodcastDownloadService downloadService,
|
||||
IOpmlService opmlService,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_logger = logger;
|
||||
_rssFeedService = rssFeedService;
|
||||
_storageService = storageService;
|
||||
_downloadService = downloadService;
|
||||
_opmlService = opmlService;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets all subscribed podcasts.
|
||||
/// </summary>
|
||||
/// <returns>List of podcasts.</returns>
|
||||
[HttpGet("podcasts")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<ActionResult<IEnumerable<Podcast>>> GetPodcasts()
|
||||
{
|
||||
var podcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
return Ok(podcasts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets a specific podcast by ID.
|
||||
/// </summary>
|
||||
/// <param name="id">Podcast ID.</param>
|
||||
/// <returns>The podcast.</returns>
|
||||
[HttpGet("podcasts/{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<Podcast>> GetPodcast([FromRoute] Guid id)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(id).ConfigureAwait(false);
|
||||
return podcast != null ? Ok(podcast) : NotFound();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new podcast subscription.
|
||||
/// </summary>
|
||||
/// <param name="request">Add podcast request.</param>
|
||||
/// <returns>The created podcast.</returns>
|
||||
[HttpPost("podcasts")]
|
||||
[ProducesResponseType(StatusCodes.Status201Created)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
[ProducesResponseType(StatusCodes.Status409Conflict)]
|
||||
public async Task<ActionResult<Podcast>> AddPodcast([FromBody] AddPodcastRequest request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.FeedUrl))
|
||||
{
|
||||
return BadRequest("Feed URL is required");
|
||||
}
|
||||
|
||||
// Check if already subscribed
|
||||
var existingPodcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
var existing = existingPodcasts.FirstOrDefault(p =>
|
||||
string.Equals(p.FeedUrl, request.FeedUrl, StringComparison.OrdinalIgnoreCase));
|
||||
if (existing != null)
|
||||
{
|
||||
return Conflict($"Already subscribed to this podcast: {existing.Title}");
|
||||
}
|
||||
|
||||
// Fetch and validate the feed
|
||||
var podcast = await _rssFeedService.FetchPodcastAsync(request.FeedUrl).ConfigureAwait(false);
|
||||
if (podcast == null)
|
||||
{
|
||||
return BadRequest("Invalid or inaccessible RSS feed");
|
||||
}
|
||||
|
||||
podcast.AutoDownloadEnabled = request.AutoDownload ?? true;
|
||||
await _storageService.AddPodcastAsync(podcast).ConfigureAwait(false);
|
||||
|
||||
// Download podcast artwork
|
||||
await _downloadService.DownloadPodcastArtworkAsync(podcast).ConfigureAwait(false);
|
||||
|
||||
// Download episode artwork for all initial episodes
|
||||
foreach (var episode in podcast.Episodes)
|
||||
{
|
||||
await _downloadService.DownloadEpisodeArtworkAsync(podcast, episode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Added podcast: {Title} ({Url})", podcast.Title, podcast.FeedUrl);
|
||||
|
||||
return CreatedAtAction(nameof(GetPodcast), new { id = podcast.Id }, podcast);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a podcast subscription.
|
||||
/// </summary>
|
||||
/// <param name="id">Podcast ID.</param>
|
||||
/// <param name="deleteFiles">Whether to delete downloaded files.</param>
|
||||
/// <returns>No content.</returns>
|
||||
[HttpDelete("podcasts/{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> DeletePodcast([FromRoute] Guid id, [FromQuery] bool deleteFiles = false)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(id).ConfigureAwait(false);
|
||||
if (podcast == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (deleteFiles)
|
||||
{
|
||||
foreach (var episode in podcast.Episodes.Where(e => e.Status == EpisodeStatus.Downloaded))
|
||||
{
|
||||
await _downloadService.DeleteEpisodeFileAsync(episode).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await _storageService.DeletePodcastAsync(id).ConfigureAwait(false);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates a podcast's settings.
|
||||
/// </summary>
|
||||
/// <param name="id">Podcast ID.</param>
|
||||
/// <param name="request">Update request.</param>
|
||||
/// <returns>The updated podcast.</returns>
|
||||
[HttpPut("podcasts/{id}")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<Podcast>> UpdatePodcast([FromRoute] Guid id, [FromBody] UpdatePodcastRequest request)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(id).ConfigureAwait(false);
|
||||
if (podcast == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (request.AutoDownload.HasValue)
|
||||
{
|
||||
podcast.AutoDownloadEnabled = request.AutoDownload.Value;
|
||||
}
|
||||
|
||||
if (request.MaxEpisodesToKeep.HasValue)
|
||||
{
|
||||
podcast.MaxEpisodesToKeep = request.MaxEpisodesToKeep.Value;
|
||||
}
|
||||
|
||||
if (request.MaxEpisodeAgeDays.HasValue)
|
||||
{
|
||||
podcast.MaxEpisodeAgeDays = request.MaxEpisodeAgeDays.Value;
|
||||
}
|
||||
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
return Ok(podcast);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes a podcast feed.
|
||||
/// </summary>
|
||||
/// <param name="id">Podcast ID.</param>
|
||||
/// <returns>The updated podcast.</returns>
|
||||
[HttpPost("podcasts/{id}/refresh")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<Podcast>> RefreshPodcast([FromRoute] Guid id)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(id).ConfigureAwait(false);
|
||||
if (podcast == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var updatedPodcast = await _rssFeedService.FetchPodcastAsync(podcast.FeedUrl).ConfigureAwait(false);
|
||||
if (updatedPodcast == null)
|
||||
{
|
||||
return BadRequest("Failed to fetch podcast feed");
|
||||
}
|
||||
|
||||
// Find new episodes
|
||||
var existingGuids = podcast.Episodes
|
||||
.Select(e => e.EpisodeGuid)
|
||||
.Where(g => !string.IsNullOrEmpty(g))
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var newEpisodes = updatedPodcast.Episodes
|
||||
.Where(e => !string.IsNullOrEmpty(e.EpisodeGuid) && !existingGuids.Contains(e.EpisodeGuid))
|
||||
.ToList();
|
||||
|
||||
foreach (var episode in newEpisodes)
|
||||
{
|
||||
episode.PodcastId = podcast.Id;
|
||||
podcast.Episodes.Insert(0, episode);
|
||||
}
|
||||
|
||||
podcast.LastUpdated = DateTime.UtcNow;
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
|
||||
// Download artwork for new episodes
|
||||
foreach (var episode in newEpisodes)
|
||||
{
|
||||
await _downloadService.DownloadEpisodeArtworkAsync(podcast, episode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return Ok(podcast);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads multiple episodes from a podcast.
|
||||
/// </summary>
|
||||
/// <param name="id">Podcast ID.</param>
|
||||
/// <param name="request">Download request with count.</param>
|
||||
/// <returns>Number of episodes queued.</returns>
|
||||
[HttpPost("podcasts/{id}/download")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<DownloadResult>> DownloadEpisodes([FromRoute] Guid id, [FromBody] DownloadEpisodesRequest request)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(id).ConfigureAwait(false);
|
||||
if (podcast == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var count = request.Count > 0 ? request.Count : 5;
|
||||
var episodesToDownload = podcast.Episodes
|
||||
.Where(e => e.Status == EpisodeStatus.Available)
|
||||
.OrderByDescending(e => e.PublishedDate)
|
||||
.Take(count)
|
||||
.ToList();
|
||||
|
||||
foreach (var episode in episodesToDownload)
|
||||
{
|
||||
await _downloadService.QueueDownloadAsync(podcast, episode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Queued {Count} episodes for download from {Podcast}", episodesToDownload.Count, podcast.Title);
|
||||
|
||||
return Ok(new DownloadResult { QueuedCount = episodesToDownload.Count });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Downloads a specific episode.
|
||||
/// </summary>
|
||||
/// <param name="podcastId">Podcast ID.</param>
|
||||
/// <param name="episodeId">Episode ID.</param>
|
||||
/// <returns>Accepted status.</returns>
|
||||
[HttpPost("podcasts/{podcastId}/episodes/{episodeId}/download")]
|
||||
[ProducesResponseType(StatusCodes.Status202Accepted)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> DownloadEpisode([FromRoute] Guid podcastId, [FromRoute] Guid episodeId)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
var episode = podcast?.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
|
||||
if (podcast == null || episode == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
await _downloadService.QueueDownloadAsync(podcast, episode).ConfigureAwait(false);
|
||||
return Accepted();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes an episode.
|
||||
/// </summary>
|
||||
/// <param name="podcastId">Podcast ID.</param>
|
||||
/// <param name="episodeId">Episode ID.</param>
|
||||
/// <param name="deleteFile">Whether to delete the downloaded file.</param>
|
||||
/// <returns>No content.</returns>
|
||||
[HttpDelete("podcasts/{podcastId}/episodes/{episodeId}")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> DeleteEpisode(
|
||||
[FromRoute] Guid podcastId,
|
||||
[FromRoute] Guid episodeId,
|
||||
[FromQuery] bool deleteFile = true)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
var episode = podcast?.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
|
||||
if (podcast == null || episode == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
if (deleteFile && episode.Status == EpisodeStatus.Downloaded)
|
||||
{
|
||||
await _downloadService.DeleteEpisodeFileAsync(episode).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
podcast.Episodes.Remove(episode);
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Previews a podcast feed without subscribing.
|
||||
/// </summary>
|
||||
/// <param name="request">Preview request.</param>
|
||||
/// <returns>The podcast info.</returns>
|
||||
[HttpPost("preview")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<ActionResult<Podcast>> PreviewFeed([FromBody] PreviewFeedRequest request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.FeedUrl))
|
||||
{
|
||||
return BadRequest("Feed URL is required");
|
||||
}
|
||||
|
||||
var podcast = await _rssFeedService.FetchPodcastAsync(request.FeedUrl).ConfigureAwait(false);
|
||||
return podcast != null ? Ok(podcast) : BadRequest("Invalid or inaccessible RSS feed");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes duplicate podcast subscriptions, keeping the first one.
|
||||
/// </summary>
|
||||
/// <returns>Number of duplicates removed.</returns>
|
||||
[HttpPost("cleanup")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<ActionResult<object>> CleanupDuplicates()
|
||||
{
|
||||
var podcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
var seenUrls = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
var duplicatesToRemove = new List<Guid>();
|
||||
|
||||
foreach (var podcast in podcasts)
|
||||
{
|
||||
if (seenUrls.Contains(podcast.FeedUrl))
|
||||
{
|
||||
duplicatesToRemove.Add(podcast.Id);
|
||||
}
|
||||
else
|
||||
{
|
||||
seenUrls.Add(podcast.FeedUrl);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var id in duplicatesToRemove)
|
||||
{
|
||||
await _storageService.DeletePodcastAsync(id).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Removed {Count} duplicate podcast subscriptions", duplicatesToRemove.Count);
|
||||
|
||||
return Ok(new { RemovedCount = duplicatesToRemove.Count });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates playback progress for an episode.
|
||||
/// </summary>
|
||||
/// <param name="podcastId">Podcast ID.</param>
|
||||
/// <param name="episodeId">Episode ID.</param>
|
||||
/// <param name="request">Progress update request.</param>
|
||||
/// <returns>No content.</returns>
|
||||
[HttpPost("podcasts/{podcastId}/episodes/{episodeId}/progress")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> UpdatePlaybackProgress(
|
||||
[FromRoute] Guid podcastId,
|
||||
[FromRoute] Guid episodeId,
|
||||
[FromBody] PlaybackProgressRequest request)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
var episode = podcast?.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
|
||||
if (podcast == null || episode == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
episode.PlaybackPositionTicks = request.PositionTicks;
|
||||
episode.LastPlayedDate = DateTime.UtcNow;
|
||||
|
||||
// Mark as played if we've reached near the end (within last 5%)
|
||||
if (episode.Duration.HasValue && request.PositionTicks > 0)
|
||||
{
|
||||
var durationTicks = episode.Duration.Value.Ticks;
|
||||
var percentComplete = (double)request.PositionTicks / durationTicks;
|
||||
if (percentComplete >= 0.95)
|
||||
{
|
||||
episode.IsPlayed = true;
|
||||
episode.PlayCount++;
|
||||
_logger.LogInformation("Episode marked as played: {Title} (played {Count} times)", episode.Title, episode.PlayCount);
|
||||
}
|
||||
}
|
||||
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Marks an episode as played or unplayed.
|
||||
/// </summary>
|
||||
/// <param name="podcastId">Podcast ID.</param>
|
||||
/// <param name="episodeId">Episode ID.</param>
|
||||
/// <param name="played">Whether the episode is played.</param>
|
||||
/// <returns>No content.</returns>
|
||||
[HttpPost("podcasts/{podcastId}/episodes/{episodeId}/played")]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult> SetPlayedStatus(
|
||||
[FromRoute] Guid podcastId,
|
||||
[FromRoute] Guid episodeId,
|
||||
[FromQuery] bool played = true)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
var episode = podcast?.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
|
||||
if (podcast == null || episode == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
episode.IsPlayed = played;
|
||||
if (played)
|
||||
{
|
||||
episode.LastPlayedDate = DateTime.UtcNow;
|
||||
episode.PlayCount++;
|
||||
}
|
||||
else
|
||||
{
|
||||
episode.PlaybackPositionTicks = 0;
|
||||
}
|
||||
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
_logger.LogInformation("Episode {Title} marked as {Status}", episode.Title, played ? "played" : "unplayed");
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets playback progress for an episode.
|
||||
/// </summary>
|
||||
/// <param name="podcastId">Podcast ID.</param>
|
||||
/// <param name="episodeId">Episode ID.</param>
|
||||
/// <returns>Playback progress info.</returns>
|
||||
[HttpGet("podcasts/{podcastId}/episodes/{episodeId}/progress")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status404NotFound)]
|
||||
public async Task<ActionResult<PlaybackProgressResponse>> GetPlaybackProgress(
|
||||
[FromRoute] Guid podcastId,
|
||||
[FromRoute] Guid episodeId)
|
||||
{
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
var episode = podcast?.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
|
||||
if (podcast == null || episode == null)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
return Ok(new PlaybackProgressResponse
|
||||
{
|
||||
PositionTicks = episode.PlaybackPositionTicks,
|
||||
IsPlayed = episode.IsPlayed,
|
||||
LastPlayedDate = episode.LastPlayedDate,
|
||||
PlayCount = episode.PlayCount
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exports all podcast subscriptions as OPML.
|
||||
/// </summary>
|
||||
/// <returns>OPML XML file.</returns>
|
||||
[HttpGet("opml/export")]
|
||||
[Produces("application/xml")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
public async Task<IActionResult> ExportOpml()
|
||||
{
|
||||
var opml = await _opmlService.ExportToOpmlAsync().ConfigureAwait(false);
|
||||
var bytes = System.Text.Encoding.UTF8.GetBytes(opml);
|
||||
|
||||
var fileName = $"jellypod-subscriptions-{DateTime.UtcNow:yyyy-MM-dd}.opml";
|
||||
return File(bytes, "application/xml", fileName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Imports podcasts from an uploaded OPML file.
|
||||
/// </summary>
|
||||
/// <param name="file">The OPML file to import.</param>
|
||||
/// <returns>Import results.</returns>
|
||||
[HttpPost("opml/import")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<ActionResult<OpmlImportResult>> ImportOpmlFile(IFormFile file)
|
||||
{
|
||||
if (file == null || file.Length == 0)
|
||||
{
|
||||
return BadRequest("No file uploaded");
|
||||
}
|
||||
|
||||
if (file.Length > 5 * 1024 * 1024) // 5MB limit
|
||||
{
|
||||
return BadRequest("File too large. Maximum size is 5MB.");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var stream = file.OpenReadStream();
|
||||
var outlines = _opmlService.ParseOpml(stream);
|
||||
|
||||
if (outlines.Count == 0)
|
||||
{
|
||||
return BadRequest("No podcast feeds found in OPML file");
|
||||
}
|
||||
|
||||
var result = await _opmlService.ImportPodcastsAsync(outlines).ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (System.Xml.XmlException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Invalid OPML XML");
|
||||
return BadRequest("Invalid OPML file format");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Imports podcasts from an OPML URL.
|
||||
/// </summary>
|
||||
/// <param name="request">Request containing the OPML URL.</param>
|
||||
/// <returns>Import results.</returns>
|
||||
[HttpPost("opml/import-url")]
|
||||
[ProducesResponseType(StatusCodes.Status200OK)]
|
||||
[ProducesResponseType(StatusCodes.Status400BadRequest)]
|
||||
public async Task<ActionResult<OpmlImportResult>> ImportOpmlUrl([FromBody] OpmlImportRequest request)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.Url))
|
||||
{
|
||||
return BadRequest("URL is required");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var httpClient = _httpClientFactory.CreateClient("Jellypod");
|
||||
var opmlContent = await httpClient.GetStringAsync(request.Url).ConfigureAwait(false);
|
||||
|
||||
var outlines = _opmlService.ParseOpml(opmlContent);
|
||||
|
||||
if (outlines.Count == 0)
|
||||
{
|
||||
return BadRequest("No podcast feeds found in OPML");
|
||||
}
|
||||
|
||||
var result = await _opmlService.ImportPodcastsAsync(outlines).ConfigureAwait(false);
|
||||
return Ok(result);
|
||||
}
|
||||
catch (HttpRequestException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to fetch OPML from URL");
|
||||
return BadRequest("Failed to fetch OPML from URL");
|
||||
}
|
||||
catch (System.Xml.XmlException ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Invalid OPML XML from URL");
|
||||
return BadRequest("Invalid OPML format");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Request to add a new podcast.
|
||||
/// </summary>
|
||||
public class AddPodcastRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the RSS feed URL.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string FeedUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether to enable auto-download.
|
||||
/// </summary>
|
||||
public bool? AutoDownload { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Request to download episodes from a podcast.
|
||||
/// </summary>
|
||||
public class DownloadEpisodesRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the number of episodes to download.
|
||||
/// </summary>
|
||||
public int Count { get; set; } = 5;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Result of a download request.
|
||||
/// </summary>
|
||||
public class DownloadResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the number of episodes queued for download.
|
||||
/// </summary>
|
||||
public int QueuedCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Details about a failed OPML feed import.
|
||||
/// </summary>
|
||||
public class OpmlImportError
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the feed URL that failed.
|
||||
/// </summary>
|
||||
public string FeedUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the feed title from OPML (if available).
|
||||
/// </summary>
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the error message.
|
||||
/// </summary>
|
||||
public string Error { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Request to import podcasts from an OPML URL.
|
||||
/// </summary>
|
||||
public class OpmlImportRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the URL to fetch OPML from.
|
||||
/// </summary>
|
||||
public string Url { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Result of an OPML import operation.
|
||||
/// </summary>
|
||||
public class OpmlImportResult
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of feeds found in the OPML.
|
||||
/// </summary>
|
||||
public int TotalFeeds { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of feeds successfully imported.
|
||||
/// </summary>
|
||||
public int ImportedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of feeds skipped (already subscribed).
|
||||
/// </summary>
|
||||
public int SkippedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of feeds that failed to import.
|
||||
/// </summary>
|
||||
public int FailedCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of imported podcast titles.
|
||||
/// </summary>
|
||||
public Collection<string> ImportedPodcasts { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of skipped feed URLs (already subscribed).
|
||||
/// </summary>
|
||||
public Collection<string> SkippedFeeds { get; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the list of failed imports with error details.
|
||||
/// </summary>
|
||||
public Collection<OpmlImportError> Errors { get; } = new();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Request to update playback progress.
|
||||
/// </summary>
|
||||
public class PlaybackProgressRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the playback position in ticks.
|
||||
/// </summary>
|
||||
public long PositionTicks { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Response containing playback progress info.
|
||||
/// </summary>
|
||||
public class PlaybackProgressResponse
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the playback position in ticks.
|
||||
/// </summary>
|
||||
public long PositionTicks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the episode has been played.
|
||||
/// </summary>
|
||||
public bool IsPlayed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date the episode was last played.
|
||||
/// </summary>
|
||||
public DateTime? LastPlayedDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of times the episode has been played.
|
||||
/// </summary>
|
||||
public int PlayCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Request to preview a feed.
|
||||
/// </summary>
|
||||
public class PreviewFeedRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the RSS feed URL.
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string FeedUrl { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
namespace Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Request to update a podcast.
|
||||
/// </summary>
|
||||
public class UpdatePodcastRequest
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets whether to enable auto-download.
|
||||
/// </summary>
|
||||
public bool? AutoDownload { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum episodes to keep.
|
||||
/// </summary>
|
||||
public int? MaxEpisodesToKeep { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum age in days for episodes (0 = use global, -1 = unlimited).
|
||||
/// </summary>
|
||||
public int? MaxEpisodeAgeDays { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Net.Http;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Api;
|
||||
|
||||
/// <summary>
|
||||
/// Controller for proxying podcast audio streams.
|
||||
/// </summary>
|
||||
[ApiController]
|
||||
[Route("Jellypod/Stream")]
|
||||
public class StreamProxyController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<StreamProxyController> _logger;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StreamProxyController"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="httpClientFactory">HTTP client factory.</param>
|
||||
public StreamProxyController(
|
||||
ILogger<StreamProxyController> logger,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_logger = logger;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Proxies an audio stream from a remote URL.
|
||||
/// </summary>
|
||||
/// <param name="url">Base64-encoded URL to stream.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The audio stream.</returns>
|
||||
[HttpGet("{url}")]
|
||||
[AllowAnonymous]
|
||||
public async Task<IActionResult> GetStream([FromRoute] string url, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Decode the URL from base64
|
||||
var decodedUrl = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(url));
|
||||
_logger.LogDebug("Proxying audio stream from: {Url}", decodedUrl);
|
||||
|
||||
var client = _httpClientFactory.CreateClient("Jellypod");
|
||||
|
||||
// Make a streaming request
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, decodedUrl);
|
||||
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
_logger.LogWarning("Failed to fetch audio stream: {StatusCode}", response.StatusCode);
|
||||
return StatusCode((int)response.StatusCode);
|
||||
}
|
||||
|
||||
// Get content type
|
||||
var contentType = response.Content.Headers.ContentType?.MediaType ?? "audio/mpeg";
|
||||
var contentLength = response.Content.Headers.ContentLength;
|
||||
|
||||
// Stream the response
|
||||
var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (contentLength.HasValue)
|
||||
{
|
||||
Response.Headers["Content-Length"] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
Response.Headers["Accept-Ranges"] = "bytes";
|
||||
|
||||
return File(stream, contentType, enableRangeProcessing: true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error proxying audio stream");
|
||||
return StatusCode(500, "Failed to proxy audio stream");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using Jellyfin.Plugin.Jellypod.Services;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Channels;
|
||||
using MediaBrowser.Controller.Providers;
|
||||
using MediaBrowser.Model.Channels;
|
||||
using MediaBrowser.Model.Dto;
|
||||
using MediaBrowser.Model.Entities;
|
||||
using MediaBrowser.Model.MediaInfo;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// Jellypod channel for browsing and playing podcast episodes.
|
||||
/// </summary>
|
||||
public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallback
|
||||
{
|
||||
private readonly ILogger<JellypodChannel> _logger;
|
||||
private readonly IPodcastStorageService _storageService;
|
||||
private readonly IRssFeedService _rssFeedService;
|
||||
private readonly IPodcastDownloadService _downloadService;
|
||||
private readonly IServerApplicationHost _appHost;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JellypodChannel"/> class.
|
||||
/// </summary>
|
||||
/// <param name="loggerFactory">The logger factory.</param>
|
||||
/// <param name="storageService">The podcast storage service.</param>
|
||||
/// <param name="rssFeedService">The RSS feed service.</param>
|
||||
/// <param name="downloadService">The download service.</param>
|
||||
/// <param name="appHost">The server application host.</param>
|
||||
public JellypodChannel(
|
||||
ILoggerFactory loggerFactory,
|
||||
IPodcastStorageService storageService,
|
||||
IRssFeedService rssFeedService,
|
||||
IPodcastDownloadService downloadService,
|
||||
IServerApplicationHost appHost)
|
||||
{
|
||||
_logger = loggerFactory.CreateLogger<JellypodChannel>();
|
||||
_storageService = storageService;
|
||||
_rssFeedService = rssFeedService;
|
||||
_downloadService = downloadService;
|
||||
_appHost = appHost;
|
||||
_logger.LogDebug("JellypodChannel initialized");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => "Podcasts";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description => "Browse and listen to your podcast subscriptions";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string DataVersion => "1.0";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string HomePageUrl => string.Empty;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ChannelParentalRating ParentalRating => ChannelParentalRating.GeneralAudience;
|
||||
|
||||
/// <inheritdoc />
|
||||
public InternalChannelFeatures GetChannelFeatures()
|
||||
{
|
||||
return new InternalChannelFeatures
|
||||
{
|
||||
ContentTypes = new List<ChannelMediaContentType>
|
||||
{
|
||||
ChannelMediaContentType.Podcast
|
||||
},
|
||||
MediaTypes = new List<ChannelMediaType>
|
||||
{
|
||||
ChannelMediaType.Audio
|
||||
},
|
||||
SupportsSortOrderToggle = true,
|
||||
DefaultSortFields = new List<ChannelItemSortField>
|
||||
{
|
||||
ChannelItemSortField.PremiereDate,
|
||||
ChannelItemSortField.DateCreated,
|
||||
ChannelItemSortField.Name
|
||||
},
|
||||
AutoRefreshLevels = 1,
|
||||
MaxPageSize = 100
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<DynamicImageResponse> GetChannelImage(ImageType type, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("GetChannelImage called with type: {Type}", type);
|
||||
|
||||
var assembly = GetType().Assembly;
|
||||
var resourceName = "Jellyfin.Plugin.Jellypod.Images.channel-icon.jpg";
|
||||
|
||||
// Log available resources for debugging
|
||||
var resourceNames = assembly.GetManifestResourceNames();
|
||||
_logger.LogInformation("Available embedded resources: {Resources}", string.Join(", ", resourceNames));
|
||||
|
||||
var stream = assembly.GetManifestResourceStream(resourceName);
|
||||
|
||||
if (stream != null)
|
||||
{
|
||||
_logger.LogInformation("Found channel icon, stream length: {Length}", stream.Length);
|
||||
return Task.FromResult(new DynamicImageResponse
|
||||
{
|
||||
HasImage = true,
|
||||
Stream = stream,
|
||||
Format = MediaBrowser.Model.Drawing.ImageFormat.Jpg
|
||||
});
|
||||
}
|
||||
|
||||
_logger.LogWarning("Channel icon resource not found: {ResourceName}", resourceName);
|
||||
return Task.FromResult(new DynamicImageResponse
|
||||
{
|
||||
HasImage = false
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<ImageType> GetSupportedChannelImages()
|
||||
{
|
||||
return new List<ImageType>
|
||||
{
|
||||
ImageType.Primary,
|
||||
ImageType.Thumb
|
||||
};
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<ChannelItemResult> GetChannelItems(InternalChannelItemQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogDebug("GetChannelItems called for folder {FolderId}, SortBy: {SortBy}, SortDescending: {SortDescending}", query.FolderId, query.SortBy, query.SortDescending);
|
||||
|
||||
try
|
||||
{
|
||||
var items = await GetFolderItemsAsync(query.FolderId, query.SortBy, query.SortDescending, cancellationToken).ConfigureAwait(false);
|
||||
_logger.LogDebug("Returning {Count} channel items for folder {FolderId}", items.Count, query.FolderId);
|
||||
|
||||
return new ChannelItemResult
|
||||
{
|
||||
Items = items,
|
||||
TotalRecordCount = items.Count
|
||||
};
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error getting channel items for folder {FolderId}", query.FolderId);
|
||||
return new ChannelItemResult { Items = new List<ChannelItemInfo>(), TotalRecordCount = 0 };
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<List<ChannelItemInfo>> GetFolderItemsAsync(string? folderId, ChannelItemSortField? sortBy, bool? sortDescending, CancellationToken cancellationToken)
|
||||
{
|
||||
// Root level - show all subscribed podcasts as folders
|
||||
if (string.IsNullOrEmpty(folderId))
|
||||
{
|
||||
return await GetPodcastFoldersAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Podcast folder - show episodes
|
||||
if (Guid.TryParse(folderId, out var podcastId))
|
||||
{
|
||||
return await GetPodcastEpisodesAsync(podcastId, sortBy, sortDescending, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new List<ChannelItemInfo>();
|
||||
}
|
||||
|
||||
private async Task<List<ChannelItemInfo>> GetPodcastFoldersAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var items = new List<ChannelItemInfo>();
|
||||
var podcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
|
||||
foreach (var podcast in podcasts)
|
||||
{
|
||||
var episodeCount = podcast.Episodes.Count;
|
||||
var downloadedCount = podcast.Episodes.Count(e => e.Status == EpisodeStatus.Downloaded);
|
||||
|
||||
items.Add(new ChannelItemInfo
|
||||
{
|
||||
Id = podcast.Id.ToString("N"),
|
||||
Name = podcast.Title,
|
||||
Overview = podcast.Description,
|
||||
ImageUrl = GetPodcastImageUrl(podcast.Id),
|
||||
Type = ChannelItemType.Folder,
|
||||
FolderType = ChannelFolderType.Container,
|
||||
DateCreated = podcast.DateAdded,
|
||||
DateModified = podcast.LastUpdated
|
||||
});
|
||||
|
||||
_logger.LogDebug("Added podcast folder: {Title} ({EpisodeCount} episodes, {DownloadedCount} downloaded)", podcast.Title, episodeCount, downloadedCount);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Returning {Count} podcast folders", items.Count);
|
||||
return items;
|
||||
}
|
||||
|
||||
private async Task<List<ChannelItemInfo>> GetPodcastEpisodesAsync(Guid podcastId, ChannelItemSortField? sortBy, bool? sortDescending, CancellationToken cancellationToken)
|
||||
{
|
||||
var items = new List<ChannelItemInfo>();
|
||||
var podcast = await _storageService.GetPodcastAsync(podcastId).ConfigureAwait(false);
|
||||
|
||||
if (podcast == null)
|
||||
{
|
||||
_logger.LogWarning("Podcast {PodcastId} not found", podcastId);
|
||||
return items;
|
||||
}
|
||||
|
||||
// Default to sorting by premiere date descending (newest first)
|
||||
var sortField = sortBy ?? ChannelItemSortField.PremiereDate;
|
||||
var descending = sortDescending ?? true;
|
||||
|
||||
_logger.LogDebug("Sorting episodes by {SortField}, descending: {Descending}", sortField, descending);
|
||||
|
||||
// Sort episodes based on query parameters
|
||||
IEnumerable<Episode> sortedEpisodes = sortField switch
|
||||
{
|
||||
ChannelItemSortField.Name => descending
|
||||
? podcast.Episodes.OrderByDescending(e => e.Title)
|
||||
: podcast.Episodes.OrderBy(e => e.Title),
|
||||
ChannelItemSortField.DateCreated or ChannelItemSortField.PremiereDate => descending
|
||||
? podcast.Episodes.OrderByDescending(e => e.PublishedDate)
|
||||
: podcast.Episodes.OrderBy(e => e.PublishedDate),
|
||||
_ => podcast.Episodes.OrderByDescending(e => e.PublishedDate)
|
||||
};
|
||||
|
||||
var episodes = sortedEpisodes.ToList();
|
||||
|
||||
foreach (var episode in episodes)
|
||||
{
|
||||
// Build episode name with played indicator
|
||||
var episodeName = episode.IsPlayed
|
||||
? $"[Played] {episode.Title}"
|
||||
: episode.Title;
|
||||
|
||||
// Build overview with progress info if partially played
|
||||
var overview = episode.Description ?? string.Empty;
|
||||
if (episode.PlaybackPositionTicks > 0 && !episode.IsPlayed && episode.Duration.HasValue)
|
||||
{
|
||||
var progressPercent = (int)((double)episode.PlaybackPositionTicks / episode.Duration.Value.Ticks * 100);
|
||||
var positionTime = TimeSpan.FromTicks(episode.PlaybackPositionTicks);
|
||||
overview = $"[{progressPercent}% - {positionTime:hh\\:mm\\:ss}] {overview}";
|
||||
}
|
||||
|
||||
// Don't provide MediaSources here - this forces Jellyfin to call GetChannelItemMediaInfo
|
||||
// which allows us to download-on-demand and return proper local file paths
|
||||
items.Add(new ChannelItemInfo
|
||||
{
|
||||
Id = episode.Id.ToString("N"),
|
||||
Name = episodeName,
|
||||
Overview = overview,
|
||||
ImageUrl = GetEpisodeImageUrl(podcast.Id, episode.Id),
|
||||
Type = ChannelItemType.Media,
|
||||
ContentType = ChannelMediaContentType.Podcast,
|
||||
MediaType = ChannelMediaType.Audio,
|
||||
DateCreated = episode.PublishedDate,
|
||||
PremiereDate = episode.PublishedDate,
|
||||
RunTimeTicks = episode.Duration?.Ticks,
|
||||
SeriesName = podcast.Title
|
||||
// MediaSources intentionally omitted - see GetChannelItemMediaInfo
|
||||
});
|
||||
}
|
||||
|
||||
_logger.LogInformation("Returning {Count} episodes for podcast {PodcastTitle}", items.Count, podcast.Title);
|
||||
return items;
|
||||
}
|
||||
|
||||
private MediaSourceInfo CreateMediaSource(Podcast podcast, Episode episode)
|
||||
{
|
||||
// If episode is downloaded, use local file; otherwise proxy through our endpoint
|
||||
var isLocal = episode.Status == EpisodeStatus.Downloaded && !string.IsNullOrEmpty(episode.LocalFilePath);
|
||||
|
||||
string path;
|
||||
MediaProtocol protocol;
|
||||
|
||||
if (isLocal)
|
||||
{
|
||||
path = episode.LocalFilePath!;
|
||||
protocol = MediaProtocol.File;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Use proxy URL to avoid ffprobe issues with remote URLs
|
||||
var encodedUrl = Convert.ToBase64String(Encoding.UTF8.GetBytes(episode.AudioUrl));
|
||||
var serverUrl = _appHost.GetSmartApiUrl(string.Empty);
|
||||
path = $"{serverUrl}/Jellypod/Stream/{encodedUrl}";
|
||||
protocol = MediaProtocol.Http;
|
||||
}
|
||||
|
||||
var container = GetContainerFromUrl(episode.AudioUrl);
|
||||
var codec = GetCodecFromContainer(container);
|
||||
|
||||
// Create audio stream info - required for Jellyfin to play without probing
|
||||
var audioStream = new MediaStream
|
||||
{
|
||||
Type = MediaStreamType.Audio,
|
||||
Index = 0,
|
||||
Codec = codec,
|
||||
Channels = 2,
|
||||
SampleRate = 44100,
|
||||
BitRate = 128000,
|
||||
IsDefault = true,
|
||||
Language = "und"
|
||||
};
|
||||
|
||||
return new MediaSourceInfo
|
||||
{
|
||||
Id = episode.Id.ToString("N"),
|
||||
Name = episode.Title,
|
||||
Path = path,
|
||||
Protocol = protocol,
|
||||
Container = container,
|
||||
Type = MediaSourceType.Default,
|
||||
IsRemote = !isLocal,
|
||||
SupportsDirectPlay = true,
|
||||
SupportsDirectStream = true,
|
||||
SupportsTranscoding = false,
|
||||
SupportsProbing = false,
|
||||
RequiresOpening = false,
|
||||
RequiresClosing = false,
|
||||
RunTimeTicks = episode.Duration?.Ticks,
|
||||
Size = episode.FileSizeBytes,
|
||||
Bitrate = 128000,
|
||||
MediaStreams = new List<MediaStream> { audioStream },
|
||||
DefaultAudioStreamIndex = 0,
|
||||
ReadAtNativeFramerate = false,
|
||||
AnalyzeDurationMs = 0,
|
||||
IsInfiniteStream = false
|
||||
};
|
||||
}
|
||||
|
||||
private static string GetCodecFromContainer(string container)
|
||||
{
|
||||
return container switch
|
||||
{
|
||||
"mp3" => "mp3",
|
||||
"m4a" => "aac",
|
||||
"ogg" => "vorbis",
|
||||
"opus" => "opus",
|
||||
_ => "mp3"
|
||||
};
|
||||
}
|
||||
|
||||
private static string GetContainerFromUrl(string url)
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri(url);
|
||||
var path = uri.AbsolutePath.ToLowerInvariant();
|
||||
|
||||
if (path.EndsWith(".mp3", StringComparison.Ordinal))
|
||||
{
|
||||
return "mp3";
|
||||
}
|
||||
|
||||
if (path.EndsWith(".m4a", StringComparison.Ordinal))
|
||||
{
|
||||
return "m4a";
|
||||
}
|
||||
|
||||
if (path.EndsWith(".ogg", StringComparison.Ordinal))
|
||||
{
|
||||
return "ogg";
|
||||
}
|
||||
|
||||
if (path.EndsWith(".opus", StringComparison.Ordinal))
|
||||
{
|
||||
return "opus";
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore URL parsing errors
|
||||
}
|
||||
|
||||
return "mp3"; // Default to mp3
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? GetCacheKey(string? userId)
|
||||
{
|
||||
// Include database modification time so cache invalidates when podcasts/episodes change
|
||||
var lastModified = _storageService.LastModified;
|
||||
return lastModified.ToString("O", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsEnabledFor(string userId)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IEnumerable<MediaSourceInfo>> GetChannelItemMediaInfo(string id, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogDebug("GetChannelItemMediaInfo called for id: {Id}", id);
|
||||
|
||||
// Parse the episode ID
|
||||
if (!Guid.TryParse(id, out var episodeId))
|
||||
{
|
||||
_logger.LogWarning("Invalid episode ID format: {Id}", id);
|
||||
return Enumerable.Empty<MediaSourceInfo>();
|
||||
}
|
||||
|
||||
// Find the episode across all podcasts
|
||||
var podcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
foreach (var podcast in podcasts)
|
||||
{
|
||||
var episode = podcast.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
if (episode != null)
|
||||
{
|
||||
var currentPodcast = podcast;
|
||||
var currentEpisode = episode;
|
||||
|
||||
// Download episode if not already downloaded
|
||||
if (currentEpisode.Status != EpisodeStatus.Downloaded || string.IsNullOrEmpty(currentEpisode.LocalFilePath))
|
||||
{
|
||||
_logger.LogInformation("Downloading episode on demand: {Title}", currentEpisode.Title);
|
||||
try
|
||||
{
|
||||
await _downloadService.DownloadEpisodeAsync(currentPodcast, currentEpisode, null, cancellationToken).ConfigureAwait(false);
|
||||
// Reload the episode to get updated status
|
||||
var reloadedPodcast = await _storageService.GetPodcastAsync(currentPodcast.Id).ConfigureAwait(false);
|
||||
var reloadedEpisode = reloadedPodcast?.Episodes.FirstOrDefault(e => e.Id == episodeId);
|
||||
if (reloadedEpisode == null)
|
||||
{
|
||||
_logger.LogError("Episode disappeared after download: {Id}", id);
|
||||
return Enumerable.Empty<MediaSourceInfo>();
|
||||
}
|
||||
|
||||
currentEpisode = reloadedEpisode;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to download episode: {Title}", currentEpisode.Title);
|
||||
return Enumerable.Empty<MediaSourceInfo>();
|
||||
}
|
||||
}
|
||||
|
||||
var mediaSource = CreateMediaSourceForLocalFile(currentEpisode);
|
||||
_logger.LogDebug("Returning media source for episode: {Title}, Path: {Path}", currentEpisode.Title, mediaSource.Path);
|
||||
return new[] { mediaSource };
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogWarning("Episode not found: {Id}", id);
|
||||
return Enumerable.Empty<MediaSourceInfo>();
|
||||
}
|
||||
|
||||
private MediaSourceInfo CreateMediaSourceForLocalFile(Episode episode)
|
||||
{
|
||||
// This is for downloaded local files
|
||||
var container = GetContainerFromUrl(episode.AudioUrl);
|
||||
var codec = GetCodecFromContainer(container);
|
||||
|
||||
// Jellyfin requires MediaStreams with audio info for StreamBuilder.GetOptimalAudioStream
|
||||
var audioStream = new MediaStream
|
||||
{
|
||||
Type = MediaStreamType.Audio,
|
||||
Index = 0,
|
||||
Codec = codec,
|
||||
Channels = 2,
|
||||
SampleRate = 44100,
|
||||
BitRate = 128000,
|
||||
IsDefault = true,
|
||||
Language = "und"
|
||||
};
|
||||
|
||||
return new MediaSourceInfo
|
||||
{
|
||||
Id = episode.Id.ToString("N"),
|
||||
Name = episode.Title,
|
||||
Path = episode.LocalFilePath!,
|
||||
Protocol = MediaProtocol.File,
|
||||
Container = container,
|
||||
Type = MediaSourceType.Default,
|
||||
IsRemote = false,
|
||||
SupportsDirectPlay = true,
|
||||
SupportsDirectStream = true,
|
||||
SupportsTranscoding = true,
|
||||
SupportsProbing = false, // Don't probe - we provide stream info
|
||||
RequiresOpening = false,
|
||||
RequiresClosing = false,
|
||||
RunTimeTicks = episode.Duration?.Ticks,
|
||||
Size = episode.FileSizeBytes,
|
||||
Bitrate = 128000,
|
||||
MediaStreams = new List<MediaStream> { audioStream },
|
||||
DefaultAudioStreamIndex = 0,
|
||||
ReadAtNativeFramerate = false
|
||||
};
|
||||
}
|
||||
|
||||
private string GetPodcastImageUrl(Guid podcastId)
|
||||
{
|
||||
var localAddress = _appHost.GetApiUrlForLocalAccess();
|
||||
return $"{localAddress}/Jellypod/Image/podcast/{podcastId:N}";
|
||||
}
|
||||
|
||||
private string GetEpisodeImageUrl(Guid podcastId, Guid episodeId)
|
||||
{
|
||||
var localAddress = _appHost.GetApiUrlForLocalAccess();
|
||||
return $"{localAddress}/Jellypod/Image/episode/{podcastId:N}/{episodeId:N}";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using MediaBrowser.Model.Plugins;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Plugin configuration for Jellypod.
|
||||
/// </summary>
|
||||
public class PluginConfiguration : BasePluginConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginConfiguration"/> class.
|
||||
/// </summary>
|
||||
public PluginConfiguration()
|
||||
{
|
||||
PodcastStoragePath = string.Empty;
|
||||
UpdateIntervalHours = 6;
|
||||
GlobalAutoDownloadEnabled = true;
|
||||
MaxConcurrentDownloads = 2;
|
||||
MaxEpisodesPerPodcast = 50;
|
||||
MaxEpisodeAgeDays = 0;
|
||||
CreatePodcastFolders = true;
|
||||
DownloadNewEpisodesOnly = true;
|
||||
PostDownloadScriptPath = string.Empty;
|
||||
PostDownloadScriptTimeout = 60;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path where podcasts will be stored.
|
||||
/// Leave empty to use the default Jellyfin data path.
|
||||
/// </summary>
|
||||
public string PodcastStoragePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the update interval in hours for checking new episodes.
|
||||
/// </summary>
|
||||
public int UpdateIntervalHours { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether auto-download is enabled globally.
|
||||
/// </summary>
|
||||
public bool GlobalAutoDownloadEnabled { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum number of concurrent downloads.
|
||||
/// </summary>
|
||||
public int MaxConcurrentDownloads { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum episodes to keep per podcast (0 = unlimited).
|
||||
/// </summary>
|
||||
public int MaxEpisodesPerPodcast { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum age in days for downloaded episodes (0 = unlimited).
|
||||
/// Episodes older than this will be automatically deleted.
|
||||
/// </summary>
|
||||
public int MaxEpisodeAgeDays { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether to create subfolders for each podcast.
|
||||
/// </summary>
|
||||
public bool CreatePodcastFolders { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether to only download new episodes after subscription.
|
||||
/// </summary>
|
||||
public bool DownloadNewEpisodesOnly { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the path to post-download processing script.
|
||||
/// Script is called with: script input_file output_file.
|
||||
/// </summary>
|
||||
public string PostDownloadScriptPath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the timeout in seconds for post-download script execution.
|
||||
/// </summary>
|
||||
public int PostDownloadScriptTimeout { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,563 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Jellypod</title>
|
||||
<style>
|
||||
.podcast-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
.podcast-table th {
|
||||
text-align: left;
|
||||
padding: 0.75em;
|
||||
border-bottom: 2px solid rgba(255,255,255,0.2);
|
||||
font-weight: 600;
|
||||
}
|
||||
.podcast-table td {
|
||||
padding: 0.75em;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.1);
|
||||
vertical-align: middle;
|
||||
}
|
||||
.podcast-table tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
.podcast-table tr:hover {
|
||||
background: rgba(255,255,255,0.05);
|
||||
}
|
||||
.podcast-image {
|
||||
width: 50px !important;
|
||||
height: 50px !important;
|
||||
max-width: 50px !important;
|
||||
max-height: 50px !important;
|
||||
min-width: 50px !important;
|
||||
min-height: 50px !important;
|
||||
object-fit: cover !important;
|
||||
border-radius: 4px !important;
|
||||
background: #333 !important;
|
||||
display: block !important;
|
||||
}
|
||||
.col-image img {
|
||||
width: 50px !important;
|
||||
height: 50px !important;
|
||||
max-width: 50px !important;
|
||||
max-height: 50px !important;
|
||||
}
|
||||
.podcast-title {
|
||||
font-weight: bold;
|
||||
}
|
||||
.podcast-meta {
|
||||
font-size: 0.85em;
|
||||
opacity: 0.7;
|
||||
margin-top: 0.25em;
|
||||
}
|
||||
.podcast-actions {
|
||||
display: flex;
|
||||
gap: 0.5em;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.col-image {
|
||||
width: 50px;
|
||||
}
|
||||
.col-actions {
|
||||
width: 100px;
|
||||
text-align: right;
|
||||
}
|
||||
.add-podcast-form {
|
||||
display: flex;
|
||||
gap: 0.5em;
|
||||
align-items: flex-end;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
.add-podcast-form .inputContainer {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
}
|
||||
.section-divider {
|
||||
margin: 2em 0;
|
||||
border-top: 1px solid rgba(255,255,255,0.2);
|
||||
}
|
||||
.empty-state {
|
||||
text-align: center;
|
||||
padding: 2em;
|
||||
opacity: 0.7;
|
||||
}
|
||||
.info-box {
|
||||
background: rgba(0,100,200,0.2);
|
||||
border: 1px solid rgba(0,100,200,0.4);
|
||||
border-radius: 4px;
|
||||
padding: 1em;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="JellypodConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
|
||||
<div data-role="content">
|
||||
<div class="content-primary">
|
||||
<h2 class="sectionTitle">Jellypod Settings</h2>
|
||||
|
||||
<div class="info-box">
|
||||
<strong>Browse Podcasts:</strong> Your subscribed podcasts appear in the <em>Channels</em> section of Jellyfin's main menu.
|
||||
Use this settings page to add/remove podcast subscriptions and configure download options.
|
||||
</div>
|
||||
|
||||
<form id="JellypodConfigForm">
|
||||
<!-- Storage Settings -->
|
||||
<div class="verticalSection">
|
||||
<h3 class="sectionTitle">Storage</h3>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="PodcastStoragePath">
|
||||
Download Storage Path
|
||||
</label>
|
||||
<input id="PodcastStoragePath" name="PodcastStoragePath" type="text" is="emby-input" />
|
||||
<div class="fieldDescription">
|
||||
Path where downloaded episodes are stored. Leave empty for default location.
|
||||
</div>
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="CreatePodcastFolders" name="CreatePodcastFolders" type="checkbox" is="emby-checkbox" />
|
||||
<span>Create subfolders for each podcast</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Update Settings -->
|
||||
<div class="verticalSection">
|
||||
<h3 class="sectionTitle">Feed Updates</h3>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="UpdateIntervalHours">
|
||||
Update Interval (hours)
|
||||
</label>
|
||||
<input id="UpdateIntervalHours" name="UpdateIntervalHours" type="number" is="emby-input" min="1" max="168" />
|
||||
<div class="fieldDescription">
|
||||
How often to check for new episodes (default: 6 hours)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Download Settings -->
|
||||
<div class="verticalSection">
|
||||
<h3 class="sectionTitle">Downloads</h3>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="GlobalAutoDownloadEnabled" name="GlobalAutoDownloadEnabled" type="checkbox" is="emby-checkbox" />
|
||||
<span>Automatically download new episodes</span>
|
||||
</label>
|
||||
<div class="fieldDescription">
|
||||
Episodes can always be streamed directly. Enable this to also download them locally.
|
||||
</div>
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="MaxConcurrentDownloads">
|
||||
Max Concurrent Downloads
|
||||
</label>
|
||||
<input id="MaxConcurrentDownloads" name="MaxConcurrentDownloads" type="number" is="emby-input" min="1" max="5" />
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="MaxEpisodesPerPodcast">
|
||||
Max Episodes Per Podcast
|
||||
</label>
|
||||
<input id="MaxEpisodesPerPodcast" name="MaxEpisodesPerPodcast" type="number" is="emby-input" min="0" />
|
||||
<div class="fieldDescription">
|
||||
Maximum episodes to keep downloaded per podcast (0 = unlimited)
|
||||
</div>
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="MaxEpisodeAgeDays">
|
||||
Max Episode Age (days)
|
||||
</label>
|
||||
<input id="MaxEpisodeAgeDays" name="MaxEpisodeAgeDays" type="number" is="emby-input" min="0" />
|
||||
<div class="fieldDescription">
|
||||
Automatically delete episodes downloaded more than this many days ago (0 = unlimited)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Post-Download Processing -->
|
||||
<div class="verticalSection">
|
||||
<h3 class="sectionTitle">Post-Download Processing</h3>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="PostDownloadScriptPath">
|
||||
Post-Download Script Path
|
||||
</label>
|
||||
<input id="PostDownloadScriptPath" name="PostDownloadScriptPath" type="text" is="emby-input" />
|
||||
<div class="fieldDescription">
|
||||
Optional script to process episodes after download. Called as: script input_file output_file
|
||||
</div>
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="PostDownloadScriptTimeout">
|
||||
Script Timeout (seconds)
|
||||
</label>
|
||||
<input id="PostDownloadScriptTimeout" name="PostDownloadScriptTimeout" type="number" is="emby-input" min="1" max="3600" />
|
||||
<div class="fieldDescription">
|
||||
Maximum time to wait for script completion (default: 60 seconds)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
|
||||
<span>Save Settings</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="section-divider"></div>
|
||||
|
||||
<!-- Podcast Subscription Management -->
|
||||
<div class="verticalSection">
|
||||
<h2 class="sectionTitle">Podcast Subscriptions</h2>
|
||||
|
||||
<!-- OPML Import/Export -->
|
||||
<div class="opml-actions" style="margin-bottom: 1em; display: flex; gap: 0.5em; align-items: center;">
|
||||
<button is="emby-button" type="button" id="btnExportOpml" class="raised emby-button">
|
||||
<span class="material-icons" style="margin-right: 0.25em;">download</span>
|
||||
<span>Export OPML</span>
|
||||
</button>
|
||||
<button is="emby-button" type="button" id="btnImportOpml" class="raised emby-button">
|
||||
<span class="material-icons" style="margin-right: 0.25em;">upload</span>
|
||||
<span>Import OPML</span>
|
||||
</button>
|
||||
<input type="file" id="opmlFileInput" accept=".opml,.xml" style="display: none;" />
|
||||
</div>
|
||||
|
||||
<!-- Add Podcast Form -->
|
||||
<div class="add-podcast-form">
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="NewFeedUrl">
|
||||
RSS Feed URL
|
||||
</label>
|
||||
<input id="NewFeedUrl" type="url" is="emby-input" placeholder="https://example.com/feed.xml" />
|
||||
</div>
|
||||
<button is="emby-button" type="button" id="btnAddPodcast" class="raised emby-button">
|
||||
<span>Subscribe</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Podcast List -->
|
||||
<div id="podcastList">
|
||||
<div class="empty-state" id="emptyState">
|
||||
No podcast subscriptions yet. Add one above, then browse in Channels.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="text/javascript">
|
||||
var JellypodConfig = {
|
||||
pluginUniqueId: 'c713faf4-4e50-4e87-941a-1200178ed605'
|
||||
};
|
||||
|
||||
function loadConfig() {
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.getPluginConfiguration(JellypodConfig.pluginUniqueId).then(function (config) {
|
||||
document.querySelector('#PodcastStoragePath').value = config.PodcastStoragePath || '';
|
||||
document.querySelector('#UpdateIntervalHours').value = config.UpdateIntervalHours;
|
||||
document.querySelector('#GlobalAutoDownloadEnabled').checked = config.GlobalAutoDownloadEnabled;
|
||||
document.querySelector('#MaxConcurrentDownloads').value = config.MaxConcurrentDownloads;
|
||||
document.querySelector('#MaxEpisodesPerPodcast').value = config.MaxEpisodesPerPodcast;
|
||||
document.querySelector('#MaxEpisodeAgeDays').value = config.MaxEpisodeAgeDays;
|
||||
document.querySelector('#CreatePodcastFolders').checked = config.CreatePodcastFolders;
|
||||
document.querySelector('#PostDownloadScriptPath').value = config.PostDownloadScriptPath || '';
|
||||
document.querySelector('#PostDownloadScriptTimeout').value = config.PostDownloadScriptTimeout || 60;
|
||||
Dashboard.hideLoadingMsg();
|
||||
});
|
||||
}
|
||||
|
||||
function loadPodcasts() {
|
||||
console.log('Jellypod: Loading podcasts...');
|
||||
ApiClient.fetch({
|
||||
url: ApiClient.getUrl('Jellypod/podcasts'),
|
||||
type: 'GET'
|
||||
}).then(function(response) {
|
||||
// ApiClient.fetch returns a Response object, need to parse JSON
|
||||
return response.json();
|
||||
}).then(function(podcasts) {
|
||||
console.log('Jellypod: Received podcasts:', podcasts);
|
||||
renderPodcasts(podcasts);
|
||||
}).catch(function(err) {
|
||||
console.error('Jellypod: Failed to load podcasts:', err);
|
||||
renderPodcasts([]);
|
||||
});
|
||||
}
|
||||
|
||||
function renderPodcasts(podcasts) {
|
||||
var container = document.querySelector('#podcastList');
|
||||
console.log('Jellypod: Rendering podcasts, count:', podcasts ? podcasts.length : 0);
|
||||
|
||||
if (!podcasts || podcasts.length === 0) {
|
||||
container.innerHTML = '<div class="empty-state">No podcast subscriptions yet. Add one above, then browse in Channels.</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
var rows = podcasts.map(function(podcast) {
|
||||
// Handle both PascalCase (C#) and camelCase (JSON) property names
|
||||
var episodeCount = (podcast.Episodes || podcast.episodes || []).length;
|
||||
var lastUpdated = podcast.LastUpdated || podcast.lastUpdated;
|
||||
var lastUpdatedStr = lastUpdated ? new Date(lastUpdated).toLocaleString() : 'Never';
|
||||
var podcastId = podcast.Id || podcast.id;
|
||||
var podcastTitle = podcast.Title || podcast.title || 'Unknown';
|
||||
var podcastImage = podcast.ImageUrl || podcast.imageUrl || '';
|
||||
|
||||
console.log('Jellypod: Rendering podcast:', podcastTitle, 'ID:', podcastId);
|
||||
|
||||
return '<tr data-id="' + podcastId + '">' +
|
||||
'<td class="col-image">' +
|
||||
'<img class="podcast-image" src="' + podcastImage + '" alt="" style="width:50px;height:50px;max-width:50px;max-height:50px;object-fit:cover;" onerror="this.style.display=\'none\'">' +
|
||||
'</td>' +
|
||||
'<td>' +
|
||||
'<div class="podcast-title">' + escapeHtml(podcastTitle) + '</div>' +
|
||||
'<div class="podcast-meta">' + episodeCount + ' episodes | Updated: ' + lastUpdatedStr + '</div>' +
|
||||
'</td>' +
|
||||
'<td class="col-actions">' +
|
||||
'<div class="podcast-actions">' +
|
||||
'<button is="emby-button" type="button" class="emby-button" onclick="refreshPodcast(\'' + podcastId + '\')" title="Refresh Feed">' +
|
||||
'<span class="material-icons">refresh</span>' +
|
||||
'</button>' +
|
||||
'<button is="emby-button" type="button" class="emby-button" onclick="deletePodcast(\'' + podcastId + '\')" title="Unsubscribe">' +
|
||||
'<span class="material-icons">delete</span>' +
|
||||
'</button>' +
|
||||
'</div>' +
|
||||
'</td>' +
|
||||
'</tr>';
|
||||
}).join('');
|
||||
|
||||
var html = '<table class="podcast-table">' +
|
||||
'<thead><tr>' +
|
||||
'<th class="col-image"></th>' +
|
||||
'<th>Podcast</th>' +
|
||||
'<th class="col-actions">Actions</th>' +
|
||||
'</tr></thead>' +
|
||||
'<tbody>' + rows + '</tbody>' +
|
||||
'</table>';
|
||||
|
||||
container.innerHTML = html;
|
||||
console.log('Jellypod: Rendered HTML length:', html.length);
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
var div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
function addPodcast() {
|
||||
var feedUrl = document.querySelector('#NewFeedUrl').value.trim();
|
||||
if (!feedUrl) {
|
||||
Dashboard.alert('Please enter a feed URL');
|
||||
return;
|
||||
}
|
||||
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.fetch({
|
||||
url: ApiClient.getUrl('Jellypod/podcasts'),
|
||||
type: 'POST',
|
||||
contentType: 'application/json',
|
||||
data: JSON.stringify({ feedUrl: feedUrl })
|
||||
}).then(function(podcast) {
|
||||
document.querySelector('#NewFeedUrl').value = '';
|
||||
Dashboard.hideLoadingMsg();
|
||||
loadPodcasts();
|
||||
Dashboard.alert('Subscribed to: ' + podcast.title + '\n\nBrowse episodes in Channels > Podcasts');
|
||||
}).catch(function(err) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
Dashboard.alert('Failed to subscribe. Please check the URL and try again.');
|
||||
});
|
||||
}
|
||||
|
||||
window.refreshPodcast = function(id) {
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.fetch({
|
||||
url: ApiClient.getUrl('Jellypod/podcasts/' + id + '/refresh'),
|
||||
type: 'POST'
|
||||
}).then(function() {
|
||||
Dashboard.hideLoadingMsg();
|
||||
loadPodcasts();
|
||||
Dashboard.alert('Feed refreshed');
|
||||
}).catch(function(err) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
Dashboard.alert('Failed to refresh feed');
|
||||
});
|
||||
};
|
||||
|
||||
window.deletePodcast = function(id) {
|
||||
console.log('Jellypod: deletePodcast called with id:', id);
|
||||
// Use simple confirm since require(['confirm']) may not work in newer Jellyfin
|
||||
if (confirm('Are you sure you want to unsubscribe from this podcast?')) {
|
||||
console.log('Jellypod: User confirmed deletion');
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.fetch({
|
||||
url: ApiClient.getUrl('Jellypod/podcasts/' + id + '?deleteFiles=true'),
|
||||
type: 'DELETE'
|
||||
}).then(function() {
|
||||
console.log('Jellypod: Delete successful');
|
||||
Dashboard.hideLoadingMsg();
|
||||
loadPodcasts();
|
||||
}).catch(function(err) {
|
||||
console.error('Jellypod: Delete failed:', err);
|
||||
Dashboard.hideLoadingMsg();
|
||||
Dashboard.alert('Failed to unsubscribe');
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Jellyfin uses 'viewshow' event for SPA navigation, not 'pageshow'
|
||||
document.querySelector('#JellypodConfigPage').addEventListener('viewshow', function() {
|
||||
console.log('Jellypod: viewshow event fired');
|
||||
loadConfig();
|
||||
loadPodcasts();
|
||||
});
|
||||
|
||||
// Also handle pageshow as fallback
|
||||
document.querySelector('#JellypodConfigPage').addEventListener('pageshow', function() {
|
||||
console.log('Jellypod: pageshow event fired');
|
||||
loadConfig();
|
||||
loadPodcasts();
|
||||
});
|
||||
|
||||
// Initialize immediately if the page is already visible (handles direct page load)
|
||||
(function() {
|
||||
console.log('Jellypod: Script loaded, checking if should initialize...');
|
||||
// Small delay to ensure Jellyfin's framework is ready
|
||||
setTimeout(function() {
|
||||
var page = document.querySelector('#JellypodConfigPage');
|
||||
if (page && page.offsetParent !== null) {
|
||||
console.log('Jellypod: Page visible, initializing...');
|
||||
loadConfig();
|
||||
loadPodcasts();
|
||||
}
|
||||
}, 100);
|
||||
})();
|
||||
|
||||
document.querySelector('#JellypodConfigForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.getPluginConfiguration(JellypodConfig.pluginUniqueId).then(function (config) {
|
||||
config.PodcastStoragePath = document.querySelector('#PodcastStoragePath').value;
|
||||
config.UpdateIntervalHours = parseInt(document.querySelector('#UpdateIntervalHours').value, 10);
|
||||
config.GlobalAutoDownloadEnabled = document.querySelector('#GlobalAutoDownloadEnabled').checked;
|
||||
config.MaxConcurrentDownloads = parseInt(document.querySelector('#MaxConcurrentDownloads').value, 10);
|
||||
config.MaxEpisodesPerPodcast = parseInt(document.querySelector('#MaxEpisodesPerPodcast').value, 10);
|
||||
config.MaxEpisodeAgeDays = parseInt(document.querySelector('#MaxEpisodeAgeDays').value, 10);
|
||||
config.CreatePodcastFolders = document.querySelector('#CreatePodcastFolders').checked;
|
||||
config.PostDownloadScriptPath = document.querySelector('#PostDownloadScriptPath').value;
|
||||
config.PostDownloadScriptTimeout = parseInt(document.querySelector('#PostDownloadScriptTimeout').value, 10);
|
||||
ApiClient.updatePluginConfiguration(JellypodConfig.pluginUniqueId, config).then(function (result) {
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
});
|
||||
});
|
||||
return false;
|
||||
});
|
||||
|
||||
document.querySelector('#btnAddPodcast').addEventListener('click', addPodcast);
|
||||
|
||||
document.querySelector('#NewFeedUrl').addEventListener('keypress', function(e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
addPodcast();
|
||||
}
|
||||
});
|
||||
|
||||
// Export OPML
|
||||
document.querySelector('#btnExportOpml').addEventListener('click', function() {
|
||||
Dashboard.showLoadingMsg();
|
||||
|
||||
fetch(ApiClient.getUrl('Jellypod/opml/export'), {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Authorization': ApiClient.accessToken() ? ('MediaBrowser Token="' + ApiClient.accessToken() + '"') : ''
|
||||
}
|
||||
})
|
||||
.then(function(response) {
|
||||
if (!response.ok) {
|
||||
throw new Error('Export failed');
|
||||
}
|
||||
return response.blob();
|
||||
})
|
||||
.then(function(blob) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
|
||||
// Create download link
|
||||
var url = window.URL.createObjectURL(blob);
|
||||
var a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'jellypod-subscriptions-' + new Date().toISOString().split('T')[0] + '.opml';
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
document.body.removeChild(a);
|
||||
})
|
||||
.catch(function(err) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
Dashboard.alert('Export failed: ' + err.message);
|
||||
});
|
||||
});
|
||||
|
||||
// Import OPML - trigger file picker
|
||||
document.querySelector('#btnImportOpml').addEventListener('click', function() {
|
||||
document.querySelector('#opmlFileInput').click();
|
||||
});
|
||||
|
||||
// Handle file selection
|
||||
document.querySelector('#opmlFileInput').addEventListener('change', function(e) {
|
||||
var file = e.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
// Reset input so same file can be selected again
|
||||
e.target.value = '';
|
||||
|
||||
Dashboard.showLoadingMsg();
|
||||
|
||||
var formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
// Use fetch for multipart/form-data upload
|
||||
fetch(ApiClient.getUrl('Jellypod/opml/import'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': ApiClient.accessToken() ? ('MediaBrowser Token="' + ApiClient.accessToken() + '"') : ''
|
||||
},
|
||||
body: formData
|
||||
})
|
||||
.then(function(response) {
|
||||
if (!response.ok) {
|
||||
return response.text().then(function(text) {
|
||||
throw new Error(text || 'Import failed');
|
||||
});
|
||||
}
|
||||
return response.json();
|
||||
})
|
||||
.then(function(result) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
loadPodcasts();
|
||||
|
||||
var message = 'Import complete!\n\n' +
|
||||
'Imported: ' + result.importedCount + '\n' +
|
||||
'Skipped (already subscribed): ' + result.skippedCount + '\n' +
|
||||
'Failed: ' + result.failedCount;
|
||||
|
||||
if (result.errors && result.errors.length > 0) {
|
||||
message += '\n\nFailed feeds:\n';
|
||||
result.errors.slice(0, 5).forEach(function(err) {
|
||||
message += '- ' + (err.title || err.feedUrl) + ': ' + err.error + '\n';
|
||||
});
|
||||
if (result.errors.length > 5) {
|
||||
message += '... and ' + (result.errors.length - 5) + ' more';
|
||||
}
|
||||
}
|
||||
|
||||
Dashboard.alert(message);
|
||||
})
|
||||
.catch(function(err) {
|
||||
Dashboard.hideLoadingMsg();
|
||||
Dashboard.alert('Import failed: ' + err.message);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
+14
-5
@@ -1,29 +1,38 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>Jellyfin.Plugin.Template</RootNamespace>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<RootNamespace>Jellyfin.Plugin.Jellypod</RootNamespace>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<Nullable>enable</Nullable>
|
||||
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
|
||||
<CodeAnalysisRuleSet>../jellyfin.ruleset</CodeAnalysisRuleSet>
|
||||
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Jellyfin.Controller" Version="10.8.13" />
|
||||
<PackageReference Include="Jellyfin.Model" Version="10.8.13" />
|
||||
<PackageReference Include="Jellyfin.Controller" Version="10.9.11">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Jellyfin.Model" Version="10.9.11">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.1" />
|
||||
<PackageReference Include="System.ServiceModel.Syndication" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="SerilogAnalyzer" Version="0.15.0" PrivateAssets="All" />
|
||||
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.507" PrivateAssets="All" />
|
||||
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556" PrivateAssets="All" />
|
||||
<PackageReference Include="SmartAnalyzers.MultithreadingAnalyzer" Version="1.1.31" PrivateAssets="All" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="Configuration\configPage.html" />
|
||||
<EmbeddedResource Include="Configuration\configPage.html" />
|
||||
<None Remove="Images\channel-icon.jpg" />
|
||||
<EmbeddedResource Include="Images\channel-icon.jpg" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,104 @@
|
||||
using System;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a podcast episode.
|
||||
/// </summary>
|
||||
public class Episode
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the unique identifier for this episode.
|
||||
/// </summary>
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the ID of the parent podcast.
|
||||
/// </summary>
|
||||
public Guid PodcastId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the episode title.
|
||||
/// </summary>
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the episode description.
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the URL to the audio file.
|
||||
/// </summary>
|
||||
public string AudioUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the local file path where the episode is stored.
|
||||
/// </summary>
|
||||
public string? LocalFilePath { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the file size in bytes.
|
||||
/// </summary>
|
||||
public long? FileSizeBytes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the episode duration.
|
||||
/// </summary>
|
||||
public TimeSpan? Duration { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the publish date.
|
||||
/// </summary>
|
||||
public DateTime PublishedDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date the episode was downloaded.
|
||||
/// </summary>
|
||||
public DateTime? DownloadedDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the download status.
|
||||
/// </summary>
|
||||
public EpisodeStatus Status { get; set; } = EpisodeStatus.Available;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the RSS GUID for deduplication.
|
||||
/// </summary>
|
||||
public string? EpisodeGuid { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the season number if applicable.
|
||||
/// </summary>
|
||||
public int? SeasonNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the episode number if applicable.
|
||||
/// </summary>
|
||||
public int? EpisodeNumber { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the episode-specific image URL.
|
||||
/// </summary>
|
||||
public string? ImageUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the playback position in ticks.
|
||||
/// </summary>
|
||||
public long PlaybackPositionTicks { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether the episode has been played/completed.
|
||||
/// </summary>
|
||||
public bool IsPlayed { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date the episode was last played.
|
||||
/// </summary>
|
||||
public DateTime? LastPlayedDate { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of times the episode has been played.
|
||||
/// </summary>
|
||||
public int PlayCount { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents the download status of a podcast episode.
|
||||
/// </summary>
|
||||
[JsonConverter(typeof(JsonStringEnumConverter))]
|
||||
public enum EpisodeStatus
|
||||
{
|
||||
/// <summary>
|
||||
/// Episode is known but not downloaded.
|
||||
/// </summary>
|
||||
Available,
|
||||
|
||||
/// <summary>
|
||||
/// Episode is currently being downloaded.
|
||||
/// </summary>
|
||||
Downloading,
|
||||
|
||||
/// <summary>
|
||||
/// Episode has been downloaded and is available locally.
|
||||
/// </summary>
|
||||
Downloaded,
|
||||
|
||||
/// <summary>
|
||||
/// Download failed.
|
||||
/// </summary>
|
||||
Error
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents an outline element from an OPML file.
|
||||
/// </summary>
|
||||
public class OpmlOutline
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the outline title (text attribute).
|
||||
/// </summary>
|
||||
public string? Text { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the outline title (title attribute).
|
||||
/// </summary>
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the RSS feed URL (xmlUrl attribute).
|
||||
/// </summary>
|
||||
public string? XmlUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the website URL (htmlUrl attribute).
|
||||
/// </summary>
|
||||
public string? HtmlUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the description.
|
||||
/// </summary>
|
||||
public string? Description { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the category.
|
||||
/// </summary>
|
||||
public string? Category { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the display title (prefers Title over Text).
|
||||
/// </summary>
|
||||
public string DisplayTitle => Title ?? Text ?? "Unknown";
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a podcast subscription.
|
||||
/// </summary>
|
||||
public class Podcast
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the unique identifier for this podcast.
|
||||
/// </summary>
|
||||
public Guid Id { get; set; } = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the podcast title.
|
||||
/// </summary>
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the podcast description.
|
||||
/// </summary>
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the RSS feed URL.
|
||||
/// </summary>
|
||||
public string FeedUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the podcast artwork URL.
|
||||
/// </summary>
|
||||
public string? ImageUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the podcast author/publisher.
|
||||
/// </summary>
|
||||
public string? Author { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the podcast language.
|
||||
/// </summary>
|
||||
public string? Language { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the podcast category.
|
||||
/// </summary>
|
||||
public string? Category { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the last time the feed was updated.
|
||||
/// </summary>
|
||||
public DateTime LastUpdated { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date this podcast was added.
|
||||
/// </summary>
|
||||
public DateTime DateAdded { get; set; } = DateTime.UtcNow;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether auto-download is enabled for this podcast.
|
||||
/// </summary>
|
||||
public bool AutoDownloadEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum episodes to keep (0 = unlimited).
|
||||
/// </summary>
|
||||
public int MaxEpisodesToKeep { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the maximum age in days for downloaded episodes.
|
||||
/// 0 = use global setting, -1 = unlimited, greater than 0 = specific days.
|
||||
/// </summary>
|
||||
public int MaxEpisodeAgeDays { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the list of episodes.
|
||||
/// </summary>
|
||||
[SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Required for JSON deserialization")]
|
||||
public Collection<Episode> Episodes { get; set; } = new();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Container for podcast data persistence.
|
||||
/// </summary>
|
||||
public class PodcastDatabase
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the list of subscribed podcasts.
|
||||
/// </summary>
|
||||
[SuppressMessage("Usage", "CA2227:Collection properties should be read only", Justification = "Required for JSON deserialization")]
|
||||
public Collection<Podcast> Podcasts { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the last time the database was saved.
|
||||
/// </summary>
|
||||
public DateTime LastSaved { get; set; }
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using Jellyfin.Plugin.Template.Configuration;
|
||||
using Jellyfin.Plugin.Jellypod.Configuration;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using MediaBrowser.Common.Plugins;
|
||||
using MediaBrowser.Model.Plugins;
|
||||
using MediaBrowser.Model.Serialization;
|
||||
|
||||
namespace Jellyfin.Plugin.Template;
|
||||
namespace Jellyfin.Plugin.Jellypod;
|
||||
|
||||
/// <summary>
|
||||
/// The main plugin.
|
||||
@@ -26,10 +26,10 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override string Name => "Template";
|
||||
public override string Name => "Jellypod";
|
||||
|
||||
/// <inheritdoc />
|
||||
public override Guid Id => Guid.Parse("eb5d7894-8eef-4b36-aa6f-5d124e828ce1");
|
||||
public override Guid Id => Guid.Parse("c713faf4-4e50-4e87-941a-1200178ed605");
|
||||
|
||||
/// <summary>
|
||||
/// Gets the current plugin instance.
|
||||
@@ -39,13 +39,13 @@ public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<PluginPageInfo> GetPages()
|
||||
{
|
||||
return new[]
|
||||
{
|
||||
return
|
||||
[
|
||||
new PluginPageInfo
|
||||
{
|
||||
Name = this.Name,
|
||||
Name = Name,
|
||||
EmbeddedResourcePath = string.Format(CultureInfo.InvariantCulture, "{0}.Configuration.configPage.html", GetType().Namespace)
|
||||
}
|
||||
};
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using Jellyfin.Plugin.Jellypod.Channels;
|
||||
using Jellyfin.Plugin.Jellypod.Services;
|
||||
using MediaBrowser.Controller;
|
||||
using MediaBrowser.Controller.Channels;
|
||||
using MediaBrowser.Controller.Plugins;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod;
|
||||
|
||||
/// <summary>
|
||||
/// Registers plugin services with the dependency injection container.
|
||||
/// </summary>
|
||||
public class PluginServiceRegistrator : IPluginServiceRegistrator
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public void RegisterServices(IServiceCollection serviceCollection, IServerApplicationHost applicationHost)
|
||||
{
|
||||
// Register HTTP client
|
||||
serviceCollection.AddHttpClient("Jellypod", client =>
|
||||
{
|
||||
client.DefaultRequestHeaders.Add("User-Agent", "Jellypod/1.0 (Jellyfin Podcast Plugin)");
|
||||
client.Timeout = System.TimeSpan.FromMinutes(10);
|
||||
});
|
||||
|
||||
// Register services
|
||||
serviceCollection.AddSingleton<IRssFeedService, RssFeedService>();
|
||||
serviceCollection.AddSingleton<IPodcastStorageService, PodcastStorageService>();
|
||||
serviceCollection.AddSingleton<IPodcastDownloadService, PodcastDownloadService>();
|
||||
serviceCollection.AddSingleton<IOpmlService, OpmlService>();
|
||||
|
||||
// Register channel
|
||||
serviceCollection.AddSingleton<IChannel, JellypodChannel>();
|
||||
|
||||
// Register playback reporting service
|
||||
serviceCollection.AddHostedService<PlaybackReportingService>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using Jellyfin.Plugin.Jellypod.Services;
|
||||
using MediaBrowser.Model.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.ScheduledTasks;
|
||||
|
||||
/// <summary>
|
||||
/// Scheduled task that updates all podcast feeds and downloads new episodes.
|
||||
/// </summary>
|
||||
public class PodcastUpdateTask : IScheduledTask
|
||||
{
|
||||
private readonly ILogger<PodcastUpdateTask> _logger;
|
||||
private readonly IRssFeedService _rssFeedService;
|
||||
private readonly IPodcastStorageService _storageService;
|
||||
private readonly IPodcastDownloadService _downloadService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PodcastUpdateTask"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="rssFeedService">RSS feed service.</param>
|
||||
/// <param name="storageService">Storage service.</param>
|
||||
/// <param name="downloadService">Download service.</param>
|
||||
public PodcastUpdateTask(
|
||||
ILogger<PodcastUpdateTask> logger,
|
||||
IRssFeedService rssFeedService,
|
||||
IPodcastStorageService storageService,
|
||||
IPodcastDownloadService downloadService)
|
||||
{
|
||||
_logger = logger;
|
||||
_rssFeedService = rssFeedService;
|
||||
_storageService = storageService;
|
||||
_downloadService = downloadService;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Name => "Update Podcast Feeds";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Key => "JellypodUpdateFeeds";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Description => "Checks all subscribed podcasts for new episodes and downloads them.";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Category => "Jellypod";
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ExecuteAsync(IProgress<double> progress, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogInformation("Starting podcast feed update task");
|
||||
|
||||
var podcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
var totalPodcasts = podcasts.Count;
|
||||
var processedCount = 0;
|
||||
|
||||
foreach (var podcast in podcasts)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogDebug("Updating podcast: {Title}", podcast.Title);
|
||||
|
||||
var updatedPodcast = await _rssFeedService.FetchPodcastAsync(podcast.FeedUrl, cancellationToken).ConfigureAwait(false);
|
||||
if (updatedPodcast != null)
|
||||
{
|
||||
// Find new episodes (by GUID)
|
||||
var existingGuids = podcast.Episodes
|
||||
.Select(e => e.EpisodeGuid)
|
||||
.Where(g => !string.IsNullOrEmpty(g))
|
||||
.ToHashSet(StringComparer.Ordinal);
|
||||
|
||||
var newEpisodes = updatedPodcast.Episodes
|
||||
.Where(e => !string.IsNullOrEmpty(e.EpisodeGuid) && !existingGuids.Contains(e.EpisodeGuid))
|
||||
.ToList();
|
||||
|
||||
if (newEpisodes.Count > 0)
|
||||
{
|
||||
_logger.LogInformation("Found {Count} new episodes for {Title}", newEpisodes.Count, podcast.Title);
|
||||
|
||||
// Add new episodes to podcast
|
||||
foreach (var episode in newEpisodes)
|
||||
{
|
||||
episode.PodcastId = podcast.Id;
|
||||
podcast.Episodes.Insert(0, episode);
|
||||
}
|
||||
|
||||
podcast.LastUpdated = DateTime.UtcNow;
|
||||
|
||||
// Auto-download if enabled
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
if (config?.GlobalAutoDownloadEnabled == true && podcast.AutoDownloadEnabled)
|
||||
{
|
||||
foreach (var episode in newEpisodes)
|
||||
{
|
||||
await _downloadService.QueueDownloadAsync(podcast, episode).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogDebug("No new episodes for {Title}", podcast.Title);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to update podcast: {Title}", podcast.Title);
|
||||
}
|
||||
|
||||
processedCount++;
|
||||
progress.Report((double)processedCount / totalPodcasts * 90 / 100);
|
||||
}
|
||||
|
||||
// Run cleanup for expired episodes
|
||||
_logger.LogInformation("Starting episode retention cleanup");
|
||||
foreach (var podcast in podcasts)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
try
|
||||
{
|
||||
await CleanupExpiredEpisodesAsync(podcast, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to cleanup expired episodes for: {Title}", podcast.Title);
|
||||
}
|
||||
}
|
||||
|
||||
progress.Report(100);
|
||||
_logger.LogInformation("Podcast feed update task completed");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IEnumerable<TaskTriggerInfo> GetDefaultTriggers()
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
var intervalHours = config?.UpdateIntervalHours ?? 6;
|
||||
|
||||
return new[]
|
||||
{
|
||||
new TaskTriggerInfo
|
||||
{
|
||||
Type = TaskTriggerInfo.TriggerInterval,
|
||||
IntervalTicks = TimeSpan.FromHours(intervalHours).Ticks
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Cleans up episodes that exceed the retention policy.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The podcast to clean up.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A task representing the asynchronous operation.</returns>
|
||||
private async Task CleanupExpiredEpisodesAsync(Podcast podcast, CancellationToken cancellationToken)
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
|
||||
// Determine effective max age for this podcast
|
||||
int effectiveMaxAgeDays;
|
||||
if (podcast.MaxEpisodeAgeDays == -1)
|
||||
{
|
||||
// Per-podcast override: unlimited
|
||||
return;
|
||||
}
|
||||
else if (podcast.MaxEpisodeAgeDays > 0)
|
||||
{
|
||||
// Per-podcast specific value
|
||||
effectiveMaxAgeDays = podcast.MaxEpisodeAgeDays;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Use global setting (podcast.MaxEpisodeAgeDays == 0)
|
||||
effectiveMaxAgeDays = config?.MaxEpisodeAgeDays ?? 0;
|
||||
}
|
||||
|
||||
// 0 means unlimited
|
||||
if (effectiveMaxAgeDays <= 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var cutoffDate = DateTime.UtcNow.AddDays(-effectiveMaxAgeDays);
|
||||
var expiredEpisodes = podcast.Episodes
|
||||
.Where(e => e.Status == EpisodeStatus.Downloaded
|
||||
&& e.DownloadedDate.HasValue
|
||||
&& e.DownloadedDate.Value < cutoffDate)
|
||||
.ToList();
|
||||
|
||||
if (expiredEpisodes.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"Found {Count} expired episodes for {Podcast} (older than {Days} days)",
|
||||
expiredEpisodes.Count,
|
||||
podcast.Title,
|
||||
effectiveMaxAgeDays);
|
||||
|
||||
foreach (var episode in expiredEpisodes)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
try
|
||||
{
|
||||
await _downloadService.DeleteEpisodeFileAsync(episode).ConfigureAwait(false);
|
||||
_logger.LogDebug(
|
||||
"Deleted expired episode: {Title} (downloaded {Date})",
|
||||
episode.Title,
|
||||
episode.DownloadedDate);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to delete expired episode: {Title}", episode.Title);
|
||||
}
|
||||
}
|
||||
|
||||
// Save changes to storage
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for handling OPML import and export.
|
||||
/// </summary>
|
||||
public interface IOpmlService
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses OPML content and extracts podcast outlines.
|
||||
/// </summary>
|
||||
/// <param name="opmlContent">The OPML XML content.</param>
|
||||
/// <returns>List of parsed outlines.</returns>
|
||||
IReadOnlyList<OpmlOutline> ParseOpml(string opmlContent);
|
||||
|
||||
/// <summary>
|
||||
/// Parses OPML from a stream.
|
||||
/// </summary>
|
||||
/// <param name="stream">The input stream containing OPML XML.</param>
|
||||
/// <returns>List of parsed outlines.</returns>
|
||||
IReadOnlyList<OpmlOutline> ParseOpml(Stream stream);
|
||||
|
||||
/// <summary>
|
||||
/// Imports podcasts from parsed OPML outlines.
|
||||
/// </summary>
|
||||
/// <param name="outlines">The parsed OPML outlines.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Import result with statistics.</returns>
|
||||
Task<OpmlImportResult> ImportPodcastsAsync(
|
||||
IReadOnlyList<OpmlOutline> outlines,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Exports all subscribed podcasts to OPML format.
|
||||
/// </summary>
|
||||
/// <returns>OPML XML string.</returns>
|
||||
Task<string> ExportToOpmlAsync();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for downloading podcast episodes.
|
||||
/// </summary>
|
||||
public interface IPodcastDownloadService
|
||||
{
|
||||
/// <summary>
|
||||
/// Queues an episode for download.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The podcast.</param>
|
||||
/// <param name="episode">The episode to download.</param>
|
||||
/// <returns>Task representing the queue operation.</returns>
|
||||
Task QueueDownloadAsync(Podcast podcast, Episode episode);
|
||||
|
||||
/// <summary>
|
||||
/// Downloads an episode immediately.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The podcast.</param>
|
||||
/// <param name="episode">The episode to download.</param>
|
||||
/// <param name="progress">Optional progress reporter.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The local file path of the downloaded episode.</returns>
|
||||
Task<string> DownloadEpisodeAsync(
|
||||
Podcast podcast,
|
||||
Episode episode,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a downloaded episode file.
|
||||
/// </summary>
|
||||
/// <param name="episode">The episode whose file to delete.</param>
|
||||
/// <returns>Task representing the delete operation.</returns>
|
||||
Task DeleteEpisodeFileAsync(Episode episode);
|
||||
|
||||
/// <summary>
|
||||
/// Downloads podcast artwork.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The podcast.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Task representing the download operation.</returns>
|
||||
Task DownloadPodcastArtworkAsync(Podcast podcast, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Downloads episode artwork.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The podcast.</param>
|
||||
/// <param name="episode">The episode.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>Task representing the download operation.</returns>
|
||||
Task DownloadEpisodeArtworkAsync(Podcast podcast, Episode episode, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for storing and retrieving podcast data.
|
||||
/// </summary>
|
||||
public interface IPodcastStorageService
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets the cached last modification time (synchronous, for cache key generation).
|
||||
/// Returns default if database hasn't been loaded yet.
|
||||
/// </summary>
|
||||
DateTime LastModified { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets all subscribed podcasts.
|
||||
/// </summary>
|
||||
/// <returns>List of all podcasts.</returns>
|
||||
Task<IReadOnlyList<Podcast>> GetAllPodcastsAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Gets a podcast by its ID.
|
||||
/// </summary>
|
||||
/// <param name="id">The podcast ID.</param>
|
||||
/// <returns>The podcast, or null if not found.</returns>
|
||||
Task<Podcast?> GetPodcastAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new podcast subscription.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The podcast to add.</param>
|
||||
/// <returns>Task representing the operation.</returns>
|
||||
Task AddPodcastAsync(Podcast podcast);
|
||||
|
||||
/// <summary>
|
||||
/// Updates an existing podcast.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The podcast to update.</param>
|
||||
/// <returns>Task representing the operation.</returns>
|
||||
Task UpdatePodcastAsync(Podcast podcast);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a podcast subscription.
|
||||
/// </summary>
|
||||
/// <param name="id">The podcast ID to delete.</param>
|
||||
/// <returns>Task representing the operation.</returns>
|
||||
Task DeletePodcastAsync(Guid id);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the local file path for an episode.
|
||||
/// </summary>
|
||||
/// <param name="podcast">The parent podcast.</param>
|
||||
/// <param name="episode">The episode.</param>
|
||||
/// <returns>The file path where the episode should be stored.</returns>
|
||||
string GetEpisodeFilePath(Podcast podcast, Episode episode);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the storage path for podcasts.
|
||||
/// </summary>
|
||||
/// <returns>The base path for podcast storage.</returns>
|
||||
string GetStoragePath();
|
||||
|
||||
/// <summary>
|
||||
/// Gets the last time the database was modified.
|
||||
/// </summary>
|
||||
/// <returns>The last modification time, or null if unknown.</returns>
|
||||
Task<DateTime?> GetLastModifiedAsync();
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for fetching and parsing podcast RSS feeds.
|
||||
/// </summary>
|
||||
public interface IRssFeedService
|
||||
{
|
||||
/// <summary>
|
||||
/// Fetches and parses a podcast from an RSS feed URL.
|
||||
/// </summary>
|
||||
/// <param name="feedUrl">The RSS feed URL.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The parsed podcast with episodes, or null if parsing failed.</returns>
|
||||
Task<Podcast?> FetchPodcastAsync(string feedUrl, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
using Jellyfin.Plugin.Jellypod.Api.Models;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for handling OPML import and export operations.
|
||||
/// </summary>
|
||||
public class OpmlService : IOpmlService
|
||||
{
|
||||
private readonly ILogger<OpmlService> _logger;
|
||||
private readonly IRssFeedService _rssFeedService;
|
||||
private readonly IPodcastStorageService _storageService;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="OpmlService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="rssFeedService">RSS feed service.</param>
|
||||
/// <param name="storageService">Storage service.</param>
|
||||
public OpmlService(
|
||||
ILogger<OpmlService> logger,
|
||||
IRssFeedService rssFeedService,
|
||||
IPodcastStorageService storageService)
|
||||
{
|
||||
_logger = logger;
|
||||
_rssFeedService = rssFeedService;
|
||||
_storageService = storageService;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<OpmlOutline> ParseOpml(string opmlContent)
|
||||
{
|
||||
using var reader = new StringReader(opmlContent);
|
||||
var doc = XDocument.Load(reader);
|
||||
return ParseOpmlDocument(doc);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<OpmlOutline> ParseOpml(Stream stream)
|
||||
{
|
||||
var doc = XDocument.Load(stream);
|
||||
return ParseOpmlDocument(doc);
|
||||
}
|
||||
|
||||
private List<OpmlOutline> ParseOpmlDocument(XDocument doc)
|
||||
{
|
||||
var outlines = new List<OpmlOutline>();
|
||||
var body = doc.Root?.Element("body");
|
||||
|
||||
if (body == null)
|
||||
{
|
||||
_logger.LogWarning("OPML document has no body element");
|
||||
return outlines;
|
||||
}
|
||||
|
||||
// Recursively find all outline elements with xmlUrl (podcast feeds)
|
||||
ParseOutlines(body.Elements("outline"), outlines, null);
|
||||
|
||||
_logger.LogInformation("Parsed {Count} podcast feeds from OPML", outlines.Count);
|
||||
return outlines;
|
||||
}
|
||||
|
||||
private void ParseOutlines(
|
||||
IEnumerable<XElement> elements,
|
||||
List<OpmlOutline> outlines,
|
||||
string? parentCategory)
|
||||
{
|
||||
foreach (var element in elements)
|
||||
{
|
||||
var xmlUrl = element.Attribute("xmlUrl")?.Value;
|
||||
var text = element.Attribute("text")?.Value;
|
||||
|
||||
if (!string.IsNullOrEmpty(xmlUrl))
|
||||
{
|
||||
// This is a feed outline
|
||||
outlines.Add(new OpmlOutline
|
||||
{
|
||||
Text = text,
|
||||
Title = element.Attribute("title")?.Value,
|
||||
XmlUrl = xmlUrl,
|
||||
HtmlUrl = element.Attribute("htmlUrl")?.Value,
|
||||
Description = element.Attribute("description")?.Value,
|
||||
Category = parentCategory ?? element.Attribute("category")?.Value
|
||||
});
|
||||
}
|
||||
else if (element.HasElements)
|
||||
{
|
||||
// This might be a category/folder - use text as category for children
|
||||
var category = parentCategory ?? text;
|
||||
ParseOutlines(element.Elements("outline"), outlines, category);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<OpmlImportResult> ImportPodcastsAsync(
|
||||
IReadOnlyList<OpmlOutline> outlines,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var result = new OpmlImportResult { TotalFeeds = outlines.Count };
|
||||
|
||||
// Get existing feeds to check for duplicates
|
||||
var existingPodcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
var existingUrls = existingPodcasts
|
||||
.Select(p => p.FeedUrl)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var outline in outlines)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(outline.XmlUrl))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if already subscribed
|
||||
if (existingUrls.Contains(outline.XmlUrl))
|
||||
{
|
||||
result.SkippedCount++;
|
||||
result.SkippedFeeds.Add(outline.XmlUrl);
|
||||
_logger.LogDebug("Skipping already subscribed feed: {Url}", outline.XmlUrl);
|
||||
continue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var podcast = await _rssFeedService.FetchPodcastAsync(
|
||||
outline.XmlUrl,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (podcast == null)
|
||||
{
|
||||
result.FailedCount++;
|
||||
result.Errors.Add(new OpmlImportError
|
||||
{
|
||||
FeedUrl = outline.XmlUrl,
|
||||
Title = outline.DisplayTitle,
|
||||
Error = "Failed to fetch or parse RSS feed"
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Preserve category from OPML if the feed doesn't have one
|
||||
if (string.IsNullOrEmpty(podcast.Category) && !string.IsNullOrEmpty(outline.Category))
|
||||
{
|
||||
podcast.Category = outline.Category;
|
||||
}
|
||||
|
||||
await _storageService.AddPodcastAsync(podcast).ConfigureAwait(false);
|
||||
|
||||
result.ImportedCount++;
|
||||
result.ImportedPodcasts.Add(podcast.Title);
|
||||
existingUrls.Add(outline.XmlUrl); // Prevent duplicate adds within same import
|
||||
|
||||
_logger.LogInformation("Imported podcast: {Title} ({Url})", podcast.Title, podcast.FeedUrl);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
result.FailedCount++;
|
||||
result.Errors.Add(new OpmlImportError
|
||||
{
|
||||
FeedUrl = outline.XmlUrl,
|
||||
Title = outline.DisplayTitle,
|
||||
Error = ex.Message
|
||||
});
|
||||
_logger.LogWarning(ex, "Failed to import feed: {Url}", outline.XmlUrl);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation(
|
||||
"OPML import complete: {Imported} imported, {Skipped} skipped, {Failed} failed out of {Total}",
|
||||
result.ImportedCount,
|
||||
result.SkippedCount,
|
||||
result.FailedCount,
|
||||
result.TotalFeeds);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string> ExportToOpmlAsync()
|
||||
{
|
||||
var podcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
|
||||
var doc = new XDocument(
|
||||
new XDeclaration("1.0", "utf-8", null),
|
||||
new XElement(
|
||||
"opml",
|
||||
new XAttribute("version", "2.0"),
|
||||
new XElement(
|
||||
"head",
|
||||
new XElement("title", "Jellypod Podcast Subscriptions"),
|
||||
new XElement("dateCreated", DateTime.UtcNow.ToString("r", CultureInfo.InvariantCulture)),
|
||||
new XElement("docs", "http://opml.org/spec2.opml")),
|
||||
new XElement(
|
||||
"body",
|
||||
podcasts.Select(p => CreateOutlineElement(p)))));
|
||||
|
||||
var settings = new XmlWriterSettings
|
||||
{
|
||||
Indent = true,
|
||||
Encoding = new UTF8Encoding(false),
|
||||
OmitXmlDeclaration = false
|
||||
};
|
||||
|
||||
using var stringWriter = new StringWriter();
|
||||
using (var xmlWriter = XmlWriter.Create(stringWriter, settings))
|
||||
{
|
||||
doc.Save(xmlWriter);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Exported {Count} podcasts to OPML", podcasts.Count);
|
||||
return stringWriter.ToString();
|
||||
}
|
||||
|
||||
private static XElement CreateOutlineElement(Podcast podcast)
|
||||
{
|
||||
var element = new XElement(
|
||||
"outline",
|
||||
new XAttribute("type", "rss"),
|
||||
new XAttribute("text", podcast.Title),
|
||||
new XAttribute("title", podcast.Title),
|
||||
new XAttribute("xmlUrl", podcast.FeedUrl));
|
||||
|
||||
if (!string.IsNullOrEmpty(podcast.Description))
|
||||
{
|
||||
element.Add(new XAttribute("description", TruncateDescription(podcast.Description)));
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(podcast.Category))
|
||||
{
|
||||
element.Add(new XAttribute("category", podcast.Category));
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
|
||||
private static string TruncateDescription(string description, int maxLength = 200)
|
||||
{
|
||||
if (string.IsNullOrEmpty(description) || description.Length <= maxLength)
|
||||
{
|
||||
return description;
|
||||
}
|
||||
|
||||
return string.Concat(description.AsSpan(0, maxLength), "...");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using MediaBrowser.Controller.Library;
|
||||
using MediaBrowser.Controller.Session;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service that listens to Jellyfin playback events and tracks podcast progress.
|
||||
/// </summary>
|
||||
public class PlaybackReportingService : IHostedService, IDisposable
|
||||
{
|
||||
private readonly ISessionManager _sessionManager;
|
||||
private readonly IPodcastStorageService _storageService;
|
||||
private readonly ILogger<PlaybackReportingService> _logger;
|
||||
private bool _disposed;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PlaybackReportingService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="sessionManager">Session manager.</param>
|
||||
/// <param name="storageService">Podcast storage service.</param>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
public PlaybackReportingService(
|
||||
ISessionManager sessionManager,
|
||||
IPodcastStorageService storageService,
|
||||
ILogger<PlaybackReportingService> logger)
|
||||
{
|
||||
_sessionManager = sessionManager;
|
||||
_storageService = storageService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_sessionManager.PlaybackStart += OnPlaybackStart;
|
||||
_sessionManager.PlaybackStopped += OnPlaybackStopped;
|
||||
_sessionManager.PlaybackProgress += OnPlaybackProgress;
|
||||
|
||||
_logger.LogInformation("Jellypod playback reporting service started");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_sessionManager.PlaybackStart -= OnPlaybackStart;
|
||||
_sessionManager.PlaybackStopped -= OnPlaybackStopped;
|
||||
_sessionManager.PlaybackProgress -= OnPlaybackProgress;
|
||||
|
||||
_logger.LogInformation("Jellypod playback reporting service stopped");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Dispose(true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases unmanaged and optionally managed resources.
|
||||
/// </summary>
|
||||
/// <param name="disposing">True to release both managed and unmanaged resources.</param>
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
_sessionManager.PlaybackStart -= OnPlaybackStart;
|
||||
_sessionManager.PlaybackStopped -= OnPlaybackStopped;
|
||||
_sessionManager.PlaybackProgress -= OnPlaybackProgress;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
}
|
||||
|
||||
private void OnPlaybackStart(object? sender, PlaybackProgressEventArgs e)
|
||||
{
|
||||
_ = HandlePlaybackEventAsync(e, "start");
|
||||
}
|
||||
|
||||
private void OnPlaybackProgress(object? sender, PlaybackProgressEventArgs e)
|
||||
{
|
||||
_ = HandlePlaybackEventAsync(e, "progress");
|
||||
}
|
||||
|
||||
private void OnPlaybackStopped(object? sender, PlaybackStopEventArgs e)
|
||||
{
|
||||
_ = HandlePlaybackStoppedAsync(e);
|
||||
}
|
||||
|
||||
private async Task HandlePlaybackEventAsync(PlaybackProgressEventArgs e, string eventType)
|
||||
{
|
||||
try
|
||||
{
|
||||
var item = e.Item;
|
||||
if (item == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this is a channel item (podcast episode)
|
||||
var channelId = item.ChannelId;
|
||||
if (channelId == Guid.Empty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to find the episode by its ID
|
||||
var episodeIdStr = item.Id.ToString("N");
|
||||
var episode = await FindEpisodeByIdAsync(episodeIdStr).ConfigureAwait(false);
|
||||
|
||||
if (episode == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogDebug(
|
||||
"Playback {EventType} for podcast episode: {Title}, Position: {Position}",
|
||||
eventType,
|
||||
episode.Episode.Title,
|
||||
e.PlaybackPositionTicks);
|
||||
|
||||
// Update progress
|
||||
episode.Episode.PlaybackPositionTicks = e.PlaybackPositionTicks ?? 0;
|
||||
episode.Episode.LastPlayedDate = DateTime.UtcNow;
|
||||
|
||||
await _storageService.UpdatePodcastAsync(episode.Podcast).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling playback {EventType} event", eventType);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandlePlaybackStoppedAsync(PlaybackStopEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
var item = e.Item;
|
||||
if (item == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if this is a channel item (podcast episode)
|
||||
var channelId = item.ChannelId;
|
||||
if (channelId == Guid.Empty)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to find the episode by its ID
|
||||
var episodeIdStr = item.Id.ToString("N");
|
||||
var episode = await FindEpisodeByIdAsync(episodeIdStr).ConfigureAwait(false);
|
||||
|
||||
if (episode == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var positionTicks = e.PlaybackPositionTicks ?? 0;
|
||||
episode.Episode.PlaybackPositionTicks = positionTicks;
|
||||
episode.Episode.LastPlayedDate = DateTime.UtcNow;
|
||||
|
||||
// Check if episode is complete (95% or more)
|
||||
if (episode.Episode.Duration.HasValue && positionTicks > 0)
|
||||
{
|
||||
var durationTicks = episode.Episode.Duration.Value.Ticks;
|
||||
var percentComplete = (double)positionTicks / durationTicks;
|
||||
|
||||
_logger.LogInformation(
|
||||
"Playback stopped for {Title} at {Percent:P1} complete",
|
||||
episode.Episode.Title,
|
||||
percentComplete);
|
||||
|
||||
if (percentComplete >= 0.95 && !episode.Episode.IsPlayed)
|
||||
{
|
||||
episode.Episode.IsPlayed = true;
|
||||
episode.Episode.PlayCount++;
|
||||
_logger.LogInformation(
|
||||
"Episode marked as played: {Title} (played {Count} times)",
|
||||
episode.Episode.Title,
|
||||
episode.Episode.PlayCount);
|
||||
}
|
||||
}
|
||||
|
||||
await _storageService.UpdatePodcastAsync(episode.Podcast).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error handling playback stopped event");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<EpisodeWithPodcast?> FindEpisodeByIdAsync(string episodeId)
|
||||
{
|
||||
if (!Guid.TryParse(episodeId, out var episodeGuid))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var podcasts = await _storageService.GetAllPodcastsAsync().ConfigureAwait(false);
|
||||
foreach (var podcast in podcasts)
|
||||
{
|
||||
var episode = podcast.Episodes.FirstOrDefault(e => e.Id == episodeGuid);
|
||||
if (episode != null)
|
||||
{
|
||||
return new EpisodeWithPodcast(podcast, episode);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private sealed record EpisodeWithPodcast(Podcast Podcast, Episode Episode);
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for downloading podcast episodes.
|
||||
/// </summary>
|
||||
public sealed class PodcastDownloadService : IPodcastDownloadService, IDisposable
|
||||
{
|
||||
private readonly ILogger<PodcastDownloadService> _logger;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
private readonly IPodcastStorageService _storageService;
|
||||
private readonly ConcurrentQueue<(Podcast Podcast, Episode Episode)> _downloadQueue = new();
|
||||
private readonly SemaphoreSlim _downloadSemaphore;
|
||||
private int _isProcessing;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PodcastDownloadService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="httpClientFactory">HTTP client factory.</param>
|
||||
/// <param name="storageService">Storage service.</param>
|
||||
public PodcastDownloadService(
|
||||
ILogger<PodcastDownloadService> logger,
|
||||
IHttpClientFactory httpClientFactory,
|
||||
IPodcastStorageService storageService)
|
||||
{
|
||||
_logger = logger;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
_storageService = storageService;
|
||||
|
||||
var maxConcurrent = Plugin.Instance?.Configuration?.MaxConcurrentDownloads ?? 2;
|
||||
_downloadSemaphore = new SemaphoreSlim(maxConcurrent, maxConcurrent);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task QueueDownloadAsync(Podcast podcast, Episode episode)
|
||||
{
|
||||
_downloadQueue.Enqueue((podcast, episode));
|
||||
_logger.LogDebug("Queued download: {PodcastTitle} - {EpisodeTitle}", podcast.Title, episode.Title);
|
||||
|
||||
// Start processing if not already running
|
||||
if (Interlocked.CompareExchange(ref _isProcessing, 1, 0) == 0)
|
||||
{
|
||||
_ = ProcessQueueAsync();
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<string> DownloadEpisodeAsync(
|
||||
Podcast podcast,
|
||||
Episode episode,
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var finalPath = _storageService.GetEpisodeFilePath(podcast, episode);
|
||||
var finalDirectory = Path.GetDirectoryName(finalPath);
|
||||
|
||||
if (!string.IsNullOrEmpty(finalDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(finalDirectory);
|
||||
}
|
||||
|
||||
// Determine if we should use temp directory for post-processing
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
var usePostProcessing = !string.IsNullOrWhiteSpace(config?.PostDownloadScriptPath);
|
||||
|
||||
// Use temp directory if post-processing is enabled, otherwise download directly to final location
|
||||
var downloadPath = usePostProcessing
|
||||
? Path.Combine(Path.GetTempPath(), "jellypod-" + Path.GetRandomFileName() + Path.GetExtension(finalPath))
|
||||
: finalPath;
|
||||
|
||||
_logger.LogInformation("Downloading episode: {Title} to {Path}", episode.Title, downloadPath);
|
||||
|
||||
string? tempInputFile = null;
|
||||
string? tempOutputFile = null;
|
||||
|
||||
try
|
||||
{
|
||||
episode.Status = EpisodeStatus.Downloading;
|
||||
|
||||
var httpClient = _httpClientFactory.CreateClient("Jellypod");
|
||||
using var response = await httpClient.GetAsync(
|
||||
episode.AudioUrl,
|
||||
HttpCompletionOption.ResponseHeadersRead,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
var totalBytes = response.Content.Headers.ContentLength ?? -1;
|
||||
|
||||
var contentStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
long totalRead;
|
||||
try
|
||||
{
|
||||
var fileStream = new FileStream(downloadPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, true);
|
||||
try
|
||||
{
|
||||
var buffer = new byte[81920];
|
||||
totalRead = 0L;
|
||||
int bytesRead;
|
||||
|
||||
while ((bytesRead = await contentStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
|
||||
{
|
||||
await fileStream.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false);
|
||||
totalRead += bytesRead;
|
||||
|
||||
if (totalBytes > 0)
|
||||
{
|
||||
progress?.Report((double)totalRead / totalBytes * 100);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await fileStream.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
await contentStream.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Downloaded episode: {Title} ({Size} bytes)", episode.Title, totalRead);
|
||||
|
||||
// Post-processing if configured
|
||||
string sourceFile = downloadPath;
|
||||
if (usePostProcessing)
|
||||
{
|
||||
tempInputFile = downloadPath;
|
||||
tempOutputFile = Path.Combine(
|
||||
Path.GetTempPath(),
|
||||
"jellypod-output-" + Path.GetRandomFileName() + Path.GetExtension(finalPath));
|
||||
|
||||
var scriptTimeout = config?.PostDownloadScriptTimeout ?? 60;
|
||||
var processedFile = await ExecutePostDownloadScriptAsync(
|
||||
tempInputFile,
|
||||
tempOutputFile,
|
||||
scriptTimeout,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
if (processedFile != null)
|
||||
{
|
||||
_logger.LogInformation("Using processed file from post-download script");
|
||||
sourceFile = processedFile;
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Using original file (script failed, timed out, or not configured)");
|
||||
sourceFile = tempInputFile;
|
||||
}
|
||||
|
||||
// Copy the selected file to final destination
|
||||
File.Copy(sourceFile, finalPath, overwrite: true);
|
||||
_logger.LogInformation("Copied episode to final location: {Path}", finalPath);
|
||||
}
|
||||
|
||||
// Get final file size
|
||||
var finalFileInfo = new FileInfo(finalPath);
|
||||
episode.LocalFilePath = finalPath;
|
||||
episode.Status = EpisodeStatus.Downloaded;
|
||||
episode.DownloadedDate = DateTime.UtcNow;
|
||||
episode.FileSizeBytes = finalFileInfo.Length;
|
||||
|
||||
// Update the podcast in storage
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
|
||||
return finalPath;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
episode.Status = EpisodeStatus.Error;
|
||||
_logger.LogError(ex, "Failed to download episode: {Title}", episode.Title);
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Clean up temp files
|
||||
if (tempInputFile != null && File.Exists(tempInputFile))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(tempInputFile);
|
||||
_logger.LogDebug("Cleaned up temp input file: {Path}", tempInputFile);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to delete temp input file: {Path}", tempInputFile);
|
||||
}
|
||||
}
|
||||
|
||||
if (tempOutputFile != null && File.Exists(tempOutputFile))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(tempOutputFile);
|
||||
_logger.LogDebug("Cleaned up temp output file: {Path}", tempOutputFile);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to delete temp output file: {Path}", tempOutputFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task DeleteEpisodeFileAsync(Episode episode)
|
||||
{
|
||||
if (string.IsNullOrEmpty(episode.LocalFilePath))
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (File.Exists(episode.LocalFilePath))
|
||||
{
|
||||
File.Delete(episode.LocalFilePath);
|
||||
_logger.LogInformation("Deleted episode file: {Path}", episode.LocalFilePath);
|
||||
}
|
||||
|
||||
episode.LocalFilePath = null;
|
||||
episode.Status = EpisodeStatus.Available;
|
||||
episode.DownloadedDate = null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to delete episode file: {Path}", episode.LocalFilePath);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DownloadPodcastArtworkAsync(Podcast podcast, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(podcast.ImageUrl))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
if (config?.CreatePodcastFolders != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var basePath = _storageService.GetStoragePath();
|
||||
var podcastFolder = Path.Combine(basePath, SanitizeFileName(podcast.Title));
|
||||
var artworkPath = Path.Combine(podcastFolder, "folder.jpg");
|
||||
|
||||
if (File.Exists(artworkPath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(podcastFolder);
|
||||
|
||||
var httpClient = _httpClientFactory.CreateClient("Jellypod");
|
||||
var imageBytes = await httpClient.GetByteArrayAsync(podcast.ImageUrl, cancellationToken).ConfigureAwait(false);
|
||||
await File.WriteAllBytesAsync(artworkPath, imageBytes, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_logger.LogInformation("Downloaded artwork for podcast: {Title}", podcast.Title);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Failed to download artwork for podcast: {Title}", podcast.Title);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DownloadEpisodeArtworkAsync(Podcast podcast, Episode episode, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(episode.ImageUrl))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
if (config?.CreatePodcastFolders != true)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var basePath = _storageService.GetStoragePath();
|
||||
var podcastFolder = Path.Combine(basePath, SanitizeFileName(podcast.Title));
|
||||
var episodeFileName = $"{SanitizeFileName(episode.Id.ToString())}.jpg";
|
||||
var artworkPath = Path.Combine(podcastFolder, episodeFileName);
|
||||
|
||||
if (File.Exists(artworkPath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(podcastFolder);
|
||||
|
||||
var httpClient = _httpClientFactory.CreateClient("Jellypod");
|
||||
var imageBytes = await httpClient.GetByteArrayAsync(episode.ImageUrl, cancellationToken).ConfigureAwait(false);
|
||||
await File.WriteAllBytesAsync(artworkPath, imageBytes, cancellationToken).ConfigureAwait(false);
|
||||
|
||||
_logger.LogDebug("Downloaded artwork for episode: {Title}", episode.Title);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Failed to download artwork for episode: {Title}", episode.Title);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ProcessQueueAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (_downloadQueue.TryDequeue(out var item))
|
||||
{
|
||||
await _downloadSemaphore.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await DownloadEpisodeAsync(item.Podcast, item.Episode).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to process queued download: {Title}", item.Episode.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_downloadSemaphore.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Exchange(ref _isProcessing, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private static string SanitizeFileName(string name)
|
||||
{
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
var result = new string(name.Where(c => !invalidChars.Contains(c)).ToArray());
|
||||
return result.Length > 100 ? result.Substring(0, 100).Trim() : result.Trim();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes the post-download script if configured.
|
||||
/// </summary>
|
||||
/// <param name="inputFilePath">Path to the downloaded file.</param>
|
||||
/// <param name="outputFilePath">Path where the script should write the processed file.</param>
|
||||
/// <param name="timeoutSeconds">Timeout in seconds.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The output file path if successful, null if failed/timeout.</returns>
|
||||
private async Task<string?> ExecutePostDownloadScriptAsync(
|
||||
string inputFilePath,
|
||||
string outputFilePath,
|
||||
int timeoutSeconds,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
var scriptPath = config?.PostDownloadScriptPath;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(scriptPath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!File.Exists(scriptPath))
|
||||
{
|
||||
_logger.LogError("Post-download script not found at path: {ScriptPath}", scriptPath);
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"Executing post-download script: {ScriptPath} {InputFile} {OutputFile}",
|
||||
scriptPath,
|
||||
inputFilePath,
|
||||
outputFilePath);
|
||||
|
||||
var processStartInfo = new ProcessStartInfo
|
||||
{
|
||||
FileName = scriptPath,
|
||||
Arguments = $"\"{inputFilePath}\" \"{outputFilePath}\"",
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
UseShellExecute = false,
|
||||
CreateNoWindow = true
|
||||
};
|
||||
|
||||
using var process = new Process { StartInfo = processStartInfo };
|
||||
var stdoutBuilder = new StringBuilder();
|
||||
var stderrBuilder = new StringBuilder();
|
||||
|
||||
process.OutputDataReceived += (sender, e) =>
|
||||
{
|
||||
if (e.Data != null)
|
||||
{
|
||||
stdoutBuilder.AppendLine(e.Data);
|
||||
}
|
||||
};
|
||||
|
||||
process.ErrorDataReceived += (sender, e) =>
|
||||
{
|
||||
if (e.Data != null)
|
||||
{
|
||||
stderrBuilder.AppendLine(e.Data);
|
||||
}
|
||||
};
|
||||
|
||||
process.Start();
|
||||
process.BeginOutputReadLine();
|
||||
process.BeginErrorReadLine();
|
||||
|
||||
// Create a timeout cancellation token
|
||||
using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
|
||||
timeoutCts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));
|
||||
|
||||
try
|
||||
{
|
||||
await process.WaitForExitAsync(timeoutCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
if (!process.HasExited)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Post-download script timed out after {Timeout} seconds, killing process",
|
||||
timeoutSeconds);
|
||||
process.Kill(entireProcessTree: true);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
var stdout = stdoutBuilder.ToString();
|
||||
var stderr = stderrBuilder.ToString();
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(stdout))
|
||||
{
|
||||
_logger.LogDebug("Script stdout: {Stdout}", stdout.Trim());
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(stderr))
|
||||
{
|
||||
_logger.LogDebug("Script stderr: {Stderr}", stderr.Trim());
|
||||
}
|
||||
|
||||
if (process.ExitCode != 0)
|
||||
{
|
||||
_logger.LogError(
|
||||
"Post-download script failed with exit code {ExitCode}",
|
||||
process.ExitCode);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!File.Exists(outputFilePath))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"Post-download script succeeded but output file was not created: {OutputFile}",
|
||||
outputFilePath);
|
||||
return null;
|
||||
}
|
||||
|
||||
_logger.LogInformation("Post-download script executed successfully");
|
||||
return outputFilePath;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to execute post-download script");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_downloadSemaphore.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using MediaBrowser.Common.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for storing and retrieving podcast data.
|
||||
/// </summary>
|
||||
public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
private readonly ILogger<PodcastStorageService> _logger;
|
||||
private readonly IApplicationPaths _applicationPaths;
|
||||
private readonly SemaphoreSlim _dbLock = new(1, 1);
|
||||
private PodcastDatabase? _cache;
|
||||
private DateTime _lastModified;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PodcastStorageService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="applicationPaths">Application paths.</param>
|
||||
public PodcastStorageService(ILogger<PodcastStorageService> logger, IApplicationPaths applicationPaths)
|
||||
{
|
||||
_logger = logger;
|
||||
_applicationPaths = applicationPaths;
|
||||
_logger.LogInformation("Jellypod database path: {Path}", DatabasePath);
|
||||
_logger.LogInformation("PluginConfigurationsPath: {Path}", applicationPaths.PluginConfigurationsPath);
|
||||
}
|
||||
|
||||
private string DatabasePath => Path.Combine(
|
||||
_applicationPaths.PluginConfigurationsPath,
|
||||
"Jellypod",
|
||||
"podcasts.json");
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateTime LastModified => _lastModified;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<Podcast>> GetAllPodcastsAsync()
|
||||
{
|
||||
var db = await LoadDatabaseAsync().ConfigureAwait(false);
|
||||
return db.Podcasts.ToList();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Podcast?> GetPodcastAsync(Guid id)
|
||||
{
|
||||
var db = await LoadDatabaseAsync().ConfigureAwait(false);
|
||||
return db.Podcasts.FirstOrDefault(p => p.Id == id);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task AddPodcastAsync(Podcast podcast)
|
||||
{
|
||||
await _dbLock.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var db = await LoadDatabaseInternalAsync().ConfigureAwait(false);
|
||||
db.Podcasts.Add(podcast);
|
||||
await SaveDatabaseInternalAsync(db).ConfigureAwait(false);
|
||||
_logger.LogInformation("Added podcast: {Title}", podcast.Title);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dbLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task UpdatePodcastAsync(Podcast podcast)
|
||||
{
|
||||
await _dbLock.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var db = await LoadDatabaseInternalAsync().ConfigureAwait(false);
|
||||
var existing = db.Podcasts.FirstOrDefault(p => p.Id == podcast.Id);
|
||||
if (existing != null)
|
||||
{
|
||||
var index = db.Podcasts.IndexOf(existing);
|
||||
db.Podcasts[index] = podcast;
|
||||
await SaveDatabaseInternalAsync(db).ConfigureAwait(false);
|
||||
_logger.LogDebug("Updated podcast: {Title}", podcast.Title);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dbLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task DeletePodcastAsync(Guid id)
|
||||
{
|
||||
await _dbLock.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
var db = await LoadDatabaseInternalAsync().ConfigureAwait(false);
|
||||
var podcast = db.Podcasts.FirstOrDefault(p => p.Id == id);
|
||||
if (podcast != null)
|
||||
{
|
||||
db.Podcasts.Remove(podcast);
|
||||
await SaveDatabaseInternalAsync(db).ConfigureAwait(false);
|
||||
_logger.LogInformation("Deleted podcast: {Title}", podcast.Title);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dbLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string GetEpisodeFilePath(Podcast podcast, Episode episode)
|
||||
{
|
||||
var basePath = GetStoragePath();
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
|
||||
var safePodcastTitle = SanitizeFileName(podcast.Title);
|
||||
var safeEpisodeTitle = SanitizeFileName(episode.Title);
|
||||
var extension = GetAudioExtension(episode.AudioUrl);
|
||||
|
||||
// Format: YYYY-MM-DD - Episode Title.mp3
|
||||
var datePrefix = episode.PublishedDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
|
||||
var fileName = $"{datePrefix} - {safeEpisodeTitle}{extension}";
|
||||
|
||||
if (config?.CreatePodcastFolders == true)
|
||||
{
|
||||
return Path.Combine(basePath, safePodcastTitle, fileName);
|
||||
}
|
||||
|
||||
return Path.Combine(basePath, $"{safePodcastTitle} - {fileName}");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public string GetStoragePath()
|
||||
{
|
||||
var config = Plugin.Instance?.Configuration;
|
||||
|
||||
if (!string.IsNullOrEmpty(config?.PodcastStoragePath))
|
||||
{
|
||||
return config.PodcastStoragePath;
|
||||
}
|
||||
|
||||
return Path.Combine(_applicationPaths.DataPath, "Podcasts");
|
||||
}
|
||||
|
||||
private async Task<PodcastDatabase> LoadDatabaseAsync()
|
||||
{
|
||||
await _dbLock.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return await LoadDatabaseInternalAsync().ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_dbLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<PodcastDatabase> LoadDatabaseInternalAsync()
|
||||
{
|
||||
if (_cache != null)
|
||||
{
|
||||
return _cache;
|
||||
}
|
||||
|
||||
if (!File.Exists(DatabasePath))
|
||||
{
|
||||
_logger.LogWarning("Database file does not exist at {Path}", DatabasePath);
|
||||
_cache = new PodcastDatabase();
|
||||
_lastModified = DateTime.UtcNow;
|
||||
return _cache;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_logger.LogInformation("Loading database from {Path}", DatabasePath);
|
||||
var json = await File.ReadAllTextAsync(DatabasePath).ConfigureAwait(false);
|
||||
_logger.LogInformation("Read {Length} characters from database file", json.Length);
|
||||
_cache = JsonSerializer.Deserialize<PodcastDatabase>(json, JsonOptions) ?? new PodcastDatabase();
|
||||
_lastModified = _cache.LastSaved;
|
||||
_logger.LogInformation("Loaded {Count} podcasts from database", _cache.Podcasts.Count);
|
||||
return _cache;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to load podcast database, starting fresh");
|
||||
_cache = new PodcastDatabase();
|
||||
_lastModified = DateTime.UtcNow;
|
||||
return _cache;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveDatabaseInternalAsync(PodcastDatabase db)
|
||||
{
|
||||
try
|
||||
{
|
||||
var directory = Path.GetDirectoryName(DatabasePath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
db.LastSaved = DateTime.UtcNow;
|
||||
_lastModified = db.LastSaved;
|
||||
var json = JsonSerializer.Serialize(db, JsonOptions);
|
||||
await File.WriteAllTextAsync(DatabasePath, json).ConfigureAwait(false);
|
||||
_cache = db;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to save podcast database");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static string SanitizeFileName(string name)
|
||||
{
|
||||
var invalidChars = Path.GetInvalidFileNameChars();
|
||||
var result = new string(name.Where(c => !invalidChars.Contains(c)).ToArray());
|
||||
|
||||
// Limit length
|
||||
if (result.Length > 100)
|
||||
{
|
||||
result = result.Substring(0, 100);
|
||||
}
|
||||
|
||||
return result.Trim();
|
||||
}
|
||||
|
||||
private static string GetAudioExtension(string url)
|
||||
{
|
||||
try
|
||||
{
|
||||
var uri = new Uri(url);
|
||||
var path = uri.AbsolutePath;
|
||||
var extension = Path.GetExtension(path);
|
||||
|
||||
if (!string.IsNullOrEmpty(extension) &&
|
||||
(extension.Equals(".mp3", StringComparison.OrdinalIgnoreCase) ||
|
||||
extension.Equals(".m4a", StringComparison.OrdinalIgnoreCase) ||
|
||||
extension.Equals(".ogg", StringComparison.OrdinalIgnoreCase) ||
|
||||
extension.Equals(".opus", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return extension.ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore URL parsing errors
|
||||
}
|
||||
|
||||
return ".mp3";
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DateTime?> GetLastModifiedAsync()
|
||||
{
|
||||
var db = await LoadDatabaseAsync().ConfigureAwait(false);
|
||||
return db.LastSaved;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_dbLock.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.ServiceModel.Syndication;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
using System.Xml.Linq;
|
||||
using Jellyfin.Plugin.Jellypod.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Service for fetching and parsing podcast RSS feeds.
|
||||
/// </summary>
|
||||
public class RssFeedService : IRssFeedService
|
||||
{
|
||||
private static readonly XNamespace ItunesNs = "http://www.itunes.com/dtds/podcast-1.0.dtd";
|
||||
private static readonly XNamespace ContentNs = "http://purl.org/rss/1.0/modules/content/";
|
||||
|
||||
private readonly ILogger<RssFeedService> _logger;
|
||||
private readonly IHttpClientFactory _httpClientFactory;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="RssFeedService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="logger">Logger instance.</param>
|
||||
/// <param name="httpClientFactory">HTTP client factory.</param>
|
||||
public RssFeedService(ILogger<RssFeedService> logger, IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_logger = logger;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<Podcast?> FetchPodcastAsync(string feedUrl, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var httpClient = _httpClientFactory.CreateClient("Jellypod");
|
||||
using var response = await httpClient.GetAsync(feedUrl, cancellationToken).ConfigureAwait(false);
|
||||
response.EnsureSuccessStatusCode();
|
||||
|
||||
using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
|
||||
using var reader = XmlReader.Create(stream);
|
||||
var feed = SyndicationFeed.Load(reader);
|
||||
|
||||
var podcast = new Podcast
|
||||
{
|
||||
FeedUrl = feedUrl,
|
||||
Title = feed.Title?.Text ?? "Unknown Podcast",
|
||||
Description = StripHtml(feed.Description?.Text ?? string.Empty),
|
||||
ImageUrl = GetItunesImage(feed) ?? feed.ImageUrl?.ToString(),
|
||||
Author = GetItunesAuthor(feed),
|
||||
Language = feed.Language,
|
||||
LastUpdated = DateTime.UtcNow
|
||||
};
|
||||
|
||||
// Parse episodes
|
||||
foreach (var item in feed.Items)
|
||||
{
|
||||
var episode = ParseEpisode(item, podcast.Id);
|
||||
if (episode != null)
|
||||
{
|
||||
podcast.Episodes.Add(episode);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.LogInformation("Fetched podcast '{Title}' with {Count} episodes", podcast.Title, podcast.Episodes.Count);
|
||||
return podcast;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to fetch podcast from {FeedUrl}", feedUrl);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private Episode? ParseEpisode(SyndicationItem item, Guid podcastId)
|
||||
{
|
||||
// Find audio enclosure
|
||||
var enclosure = item.Links.FirstOrDefault(l =>
|
||||
string.Equals(l.RelationshipType, "enclosure", StringComparison.OrdinalIgnoreCase) &&
|
||||
(l.MediaType?.StartsWith("audio/", StringComparison.OrdinalIgnoreCase) == true ||
|
||||
l.Uri?.ToString().EndsWith(".mp3", StringComparison.OrdinalIgnoreCase) == true ||
|
||||
l.Uri?.ToString().EndsWith(".m4a", StringComparison.OrdinalIgnoreCase) == true));
|
||||
|
||||
if (enclosure == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Episode
|
||||
{
|
||||
PodcastId = podcastId,
|
||||
Title = item.Title?.Text ?? "Untitled Episode",
|
||||
Description = StripHtml(item.Summary?.Text ?? GetContentEncoded(item) ?? string.Empty),
|
||||
AudioUrl = enclosure.Uri.ToString(),
|
||||
FileSizeBytes = enclosure.Length > 0 ? enclosure.Length : null,
|
||||
PublishedDate = item.PublishDate.UtcDateTime,
|
||||
EpisodeGuid = item.Id ?? enclosure.Uri.ToString(),
|
||||
Duration = GetItunesDuration(item),
|
||||
SeasonNumber = GetItunesSeason(item),
|
||||
EpisodeNumber = GetItunesEpisode(item),
|
||||
ImageUrl = GetItunesEpisodeImage(item)
|
||||
};
|
||||
}
|
||||
|
||||
private static string? GetItunesImage(SyndicationFeed feed)
|
||||
{
|
||||
var imageElement = feed.ElementExtensions
|
||||
.FirstOrDefault(e => e.OuterName == "image" && e.OuterNamespace == ItunesNs.NamespaceName);
|
||||
|
||||
if (imageElement != null)
|
||||
{
|
||||
var element = imageElement.GetObject<XElement>();
|
||||
return element.Attribute("href")?.Value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetItunesAuthor(SyndicationFeed feed)
|
||||
{
|
||||
var authorElement = feed.ElementExtensions
|
||||
.FirstOrDefault(e => e.OuterName == "author" && e.OuterNamespace == ItunesNs.NamespaceName);
|
||||
|
||||
return authorElement?.GetObject<XElement>()?.Value;
|
||||
}
|
||||
|
||||
private static TimeSpan? GetItunesDuration(SyndicationItem item)
|
||||
{
|
||||
var durationElement = item.ElementExtensions
|
||||
.FirstOrDefault(e => e.OuterName == "duration" && e.OuterNamespace == ItunesNs.NamespaceName);
|
||||
|
||||
if (durationElement == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var durationStr = durationElement.GetObject<XElement>()?.Value;
|
||||
if (string.IsNullOrEmpty(durationStr))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Duration can be in formats: HH:MM:SS, MM:SS, or just seconds
|
||||
var parts = durationStr.Split(':');
|
||||
return parts.Length switch
|
||||
{
|
||||
3 when int.TryParse(parts[0], out var h) && int.TryParse(parts[1], out var m) && int.TryParse(parts[2], out var s)
|
||||
=> new TimeSpan(h, m, s),
|
||||
2 when int.TryParse(parts[0], out var m) && int.TryParse(parts[1], out var s)
|
||||
=> new TimeSpan(0, m, s),
|
||||
1 when int.TryParse(parts[0], out var s)
|
||||
=> TimeSpan.FromSeconds(s),
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
private static int? GetItunesSeason(SyndicationItem item)
|
||||
{
|
||||
var seasonElement = item.ElementExtensions
|
||||
.FirstOrDefault(e => e.OuterName == "season" && e.OuterNamespace == ItunesNs.NamespaceName);
|
||||
|
||||
var value = seasonElement?.GetObject<XElement>()?.Value;
|
||||
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var season) ? season : null;
|
||||
}
|
||||
|
||||
private static int? GetItunesEpisode(SyndicationItem item)
|
||||
{
|
||||
var episodeElement = item.ElementExtensions
|
||||
.FirstOrDefault(e => e.OuterName == "episode" && e.OuterNamespace == ItunesNs.NamespaceName);
|
||||
|
||||
var value = episodeElement?.GetObject<XElement>()?.Value;
|
||||
return int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var episode) ? episode : null;
|
||||
}
|
||||
|
||||
private static string? GetItunesEpisodeImage(SyndicationItem item)
|
||||
{
|
||||
var imageElement = item.ElementExtensions
|
||||
.FirstOrDefault(e => e.OuterName == "image" && e.OuterNamespace == ItunesNs.NamespaceName);
|
||||
|
||||
if (imageElement != null)
|
||||
{
|
||||
var element = imageElement.GetObject<XElement>();
|
||||
return element.Attribute("href")?.Value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string? GetContentEncoded(SyndicationItem item)
|
||||
{
|
||||
var contentElement = item.ElementExtensions
|
||||
.FirstOrDefault(e => e.OuterName == "encoded" && e.OuterNamespace == ContentNs.NamespaceName);
|
||||
|
||||
return contentElement?.GetObject<XElement>()?.Value;
|
||||
}
|
||||
|
||||
private static string StripHtml(string html)
|
||||
{
|
||||
if (string.IsNullOrEmpty(html))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
// Simple HTML stripping - remove tags
|
||||
var result = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", string.Empty);
|
||||
// Decode common HTML entities
|
||||
result = result.Replace(" ", " ", StringComparison.Ordinal)
|
||||
.Replace("&", "&", StringComparison.Ordinal)
|
||||
.Replace("<", "<", StringComparison.Ordinal)
|
||||
.Replace(">", ">", StringComparison.Ordinal)
|
||||
.Replace(""", "\"", StringComparison.Ordinal);
|
||||
return result.Trim();
|
||||
}
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Jellyfin.Plugin.Template", "Jellyfin.Plugin.Template\Jellyfin.Plugin.Template.csproj", "{D921B930-CF91-406F-ACBC-08914DCD0D34}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{D921B930-CF91-406F-ACBC-08914DCD0D34}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,57 +0,0 @@
|
||||
using MediaBrowser.Model.Plugins;
|
||||
|
||||
namespace Jellyfin.Plugin.Template.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// The configuration options.
|
||||
/// </summary>
|
||||
public enum SomeOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Option one.
|
||||
/// </summary>
|
||||
OneOption,
|
||||
|
||||
/// <summary>
|
||||
/// Second option.
|
||||
/// </summary>
|
||||
AnotherOption
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Plugin configuration.
|
||||
/// </summary>
|
||||
public class PluginConfiguration : BasePluginConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="PluginConfiguration"/> class.
|
||||
/// </summary>
|
||||
public PluginConfiguration()
|
||||
{
|
||||
// set default options here
|
||||
Options = SomeOptions.AnotherOption;
|
||||
TrueFalseSetting = true;
|
||||
AnInteger = 2;
|
||||
AString = "string";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a value indicating whether some true or false setting is enabled..
|
||||
/// </summary>
|
||||
public bool TrueFalseSetting { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets an integer setting.
|
||||
/// </summary>
|
||||
public int AnInteger { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets a string setting.
|
||||
/// </summary>
|
||||
public string AString { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets an enum option.
|
||||
/// </summary>
|
||||
public SomeOptions Options { get; set; }
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Template</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="TemplateConfigPage" data-role="page" class="page type-interior pluginConfigurationPage" data-require="emby-input,emby-button,emby-select,emby-checkbox">
|
||||
<div data-role="content">
|
||||
<div class="content-primary">
|
||||
<form id="TemplateConfigForm">
|
||||
<div class="selectContainer">
|
||||
<label class="selectLabel" for="Options">Several Options</label>
|
||||
<select is="emby-select" id="Options" name="Options" class="emby-select-withcolor emby-select">
|
||||
<option id="optOneOption" value="OneOption">One Option</option>
|
||||
<option id="optAnotherOption" value="AnotherOption">Another Option</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="AnInteger">An Integer</label>
|
||||
<input id="AnInteger" name="AnInteger" type="number" is="emby-input" min="0" />
|
||||
<div class="fieldDescription">A Description</div>
|
||||
</div>
|
||||
<div class="checkboxContainer checkboxContainer-withDescription">
|
||||
<label class="emby-checkbox-label">
|
||||
<input id="TrueFalseSetting" name="TrueFalseCheckBox" type="checkbox" is="emby-checkbox" />
|
||||
<span>A Checkbox</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="inputContainer">
|
||||
<label class="inputLabel inputLabelUnfocused" for="AString">A String</label>
|
||||
<input id="AString" name="AString" type="text" is="emby-input" />
|
||||
<div class="fieldDescription">Another Description</div>
|
||||
</div>
|
||||
<div>
|
||||
<button is="emby-button" type="submit" class="raised button-submit block emby-button">
|
||||
<span>Save</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
var TemplateConfig = {
|
||||
pluginUniqueId: 'eb5d7894-8eef-4b36-aa6f-5d124e828ce1'
|
||||
};
|
||||
|
||||
document.querySelector('#TemplateConfigPage')
|
||||
.addEventListener('pageshow', function() {
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.getPluginConfiguration(TemplateConfig.pluginUniqueId).then(function (config) {
|
||||
document.querySelector('#Options').value = config.Options;
|
||||
document.querySelector('#AnInteger').value = config.AnInteger;
|
||||
document.querySelector('#TrueFalseSetting').checked = config.TrueFalseSetting;
|
||||
document.querySelector('#AString').value = config.AString;
|
||||
Dashboard.hideLoadingMsg();
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelector('#TemplateConfigForm')
|
||||
.addEventListener('submit', function(e) {
|
||||
Dashboard.showLoadingMsg();
|
||||
ApiClient.getPluginConfiguration(TemplateConfig.pluginUniqueId).then(function (config) {
|
||||
config.Options = document.querySelector('#Options').value;
|
||||
config.AnInteger = document.querySelector('#AnInteger').value;
|
||||
config.TrueFalseSetting = document.querySelector('#TrueFalseSetting').checked;
|
||||
config.AString = document.querySelector('#AString').value;
|
||||
ApiClient.updatePluginConfiguration(TemplateConfig.pluginUniqueId, config).then(function (result) {
|
||||
Dashboard.processPluginConfigurationUpdateResult(result);
|
||||
});
|
||||
});
|
||||
|
||||
e.preventDefault();
|
||||
return false;
|
||||
});
|
||||
</script>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
+282
File diff suppressed because one or more lines are too long
@@ -1,373 +1,128 @@
|
||||
# So you want to make a Jellyfin plugin
|
||||
# Jellypod
|
||||
|
||||
Awesome! This guide is for you. Jellyfin plugins are written using the dotnet standard framework. What that means is you can write them in any language that implements the CLI or the DLI and can compile to net6.0. The examples on this page are in C# because that is what most of Jellyfin is written in, but F#, Visual Basic, and IronPython should all be compatible once compiled.
|
||||
A Jellyfin plugin that adds podcast support to your media server.
|
||||
|
||||
## 0. Things you need to get started
|
||||
## Quick Install
|
||||
|
||||
- [Dotnet SDK 6.0](https://dotnet.microsoft.com/download)
|
||||
|
||||
- An editor of your choice. Some free choices are:
|
||||
|
||||
[Visual Studio Code](https://code.visualstudio.com)
|
||||
|
||||
[Visual Studio Community Edition](https://visualstudio.microsoft.com/downloads)
|
||||
|
||||
[Mono Develop](https://www.monodevelop.com)
|
||||
|
||||
## 0.5. Quickstarts
|
||||
|
||||
We have a number of quickstart options available to speed you along the way.
|
||||
|
||||
- [Download the Example Plugin Project](https://github.com/jellyfin/jellyfin-plugin-template/tree/master/Jellyfin.Plugin.Template) from this repository, open it in your IDE and go to [step 3](https://github.com/jellyfin/jellyfin-plugin-template#3-customize-plugin-information)
|
||||
|
||||
- Install our dotnet template by [downloading the dotnet-template/content folder from this repo](https://github.com/jellyfin/jellyfin-plugin-template/tree/master/dotnet-template/content) or off of Nuget (Coming soon)
|
||||
|
||||
```
|
||||
dotnet new -i /path/to/templatefolder
|
||||
```
|
||||
|
||||
- Run this command then skip to step 4
|
||||
|
||||
```
|
||||
dotnet new Jellyfin-plugin -name MyPlugin
|
||||
```
|
||||
|
||||
If you'd rather start from scratch keep going on to step one. This assumes no specific editor or IDE and requires only the command line with dotnet in the path.
|
||||
|
||||
## 1. Initialize Your Project
|
||||
|
||||
Make a new dotnet standard project with the following command, it will make a directory for itself.
|
||||
Add this repository URL in Jellyfin (Dashboard → Plugins → Repositories):
|
||||
|
||||
```
|
||||
dotnet new classlib -f net6.0 -n MyJellyfinPlugin
|
||||
https://gitea.tourolle.paris/dtourolle/jellypod/raw/branch/master/manifest.json
|
||||
```
|
||||
|
||||
Now add the Jellyfin shared libraries.
|
||||
## Features
|
||||
|
||||
```
|
||||
dotnet add package Jellyfin.Model
|
||||
dotnet add package Jellyfin.Controller
|
||||
- Browse and subscribe to podcasts
|
||||
- Automatic episode downloads
|
||||
- Integration with Jellyfin's library system
|
||||
- Post-download script hook for audio processing
|
||||
|
||||
## Post-Download Script Hook
|
||||
|
||||
Jellypod supports running a custom script on each downloaded episode before it's added to your library. This is useful for:
|
||||
|
||||
- Audio normalization (e.g., using ffmpeg-normalize)
|
||||
- Format conversion
|
||||
- Metadata enhancement
|
||||
- Custom processing workflows
|
||||
|
||||
### Configuration
|
||||
|
||||
In the plugin settings (Dashboard → Plugins → Jellypod):
|
||||
|
||||
1. **Post-Download Script Path**: Full path to your script or executable
|
||||
2. **Script Timeout**: Maximum execution time in seconds (default: 60)
|
||||
|
||||
### Script API
|
||||
|
||||
Your script will be called with two arguments:
|
||||
|
||||
```bash
|
||||
script <input_file> <output_file>
|
||||
```
|
||||
|
||||
You have an autogenerated Class1.cs file. You won't be needing this, so go ahead and delete it.
|
||||
- `input_file`: Path to the downloaded episode (read-only)
|
||||
- `output_file`: Path where your script should write the processed file
|
||||
|
||||
## 2. Set Up the Basics
|
||||
### Example Scripts
|
||||
|
||||
There are a few mandatory classes you'll need for a plugin so we need to make them.
|
||||
|
||||
### PluginConfiguration
|
||||
|
||||
You can call it whatever you'd like really. This class is used to hold settings your plugin might need. We can leave it empty for now. This class should inherit from `MediaBrowser.Model.Plugins.BasePluginConfiguration`
|
||||
|
||||
### Plugin
|
||||
|
||||
This is the main class for your plugin. It will define your name, version and Id. It should inherit from `MediaBrowser.Common.Plugins.BasePlugin<PluginConfiguration>`
|
||||
|
||||
Note: If you called your PluginConfiguration class something different, you need to put that between the <>
|
||||
|
||||
### Implement Required Properties
|
||||
|
||||
The Plugin class needs a few properties implemented before it can work correctly.
|
||||
|
||||
It needs an override on ID, an override on Name, and a constructor that follows a specific model. To get started you can use the following section.
|
||||
|
||||
```c#
|
||||
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer){}
|
||||
public override string Name => throw new System.NotImplementedException();
|
||||
public override Guid Id => Guid.Parse("");
|
||||
**Audio normalization (bash + ffmpeg):**
|
||||
```bash
|
||||
#!/bin/bash
|
||||
INPUT="$1"
|
||||
OUTPUT="$2"
|
||||
ffmpeg-normalize "$INPUT" -o "$OUTPUT" -c:a libmp3lame -b:a 128k
|
||||
```
|
||||
|
||||
## 3. Customize Plugin Information
|
||||
|
||||
You need to populate some of your plugin's information. Go ahead a put in a string of the Name you've overridden name, and generate a GUID
|
||||
|
||||
- **Windows Users**: you can use the Powershell command `New-Guid`, `[guid]::NewGuid()` or the Visual Studio GUID generator
|
||||
|
||||
- **Linux and OS X Users**: you can use the Powershell Core command `New-Guid` or this command from your shell of choice:
|
||||
|
||||
```bash
|
||||
od -x /dev/urandom | head -1 | awk '{OFS="-"; srand($6); sub(/./,"4",$5); sub(/./,substr("89ab",rand()*4,1),$6); print $2$3,$4,$5,$6,$7$8$9}'
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
uuidgen
|
||||
```
|
||||
|
||||
- Place that guid inside the `Guid.Parse("")` quotes to define your plugin's ID.
|
||||
|
||||
## 4. Adding Functionality
|
||||
|
||||
Congratulations, you now have everything you need for a perfectly functional functionless Jellyfin plugin! You can try it out right now if you'd like by compiling it, then placing the dll you generate in a subfolder (named after your plugin for example) within the plugins folder under your Jellyfin config directory. If you want to try and hook it up to a debugger make sure you copy the generated PDB file alongside it.
|
||||
|
||||
Most people aren't satisfied with just having an entry in a menu for their plugin, most people want to have some functionality, so lets look at how to add it.
|
||||
|
||||
### 4a. Implement Interfaces
|
||||
|
||||
If the functionality you are trying to add is functionality related to something that Jellyfin has an interface for you're in luck. Jellyfin uses some automatic discovery and injection to allow any interfaces you implement in your plugin to be available in Jellyfin.
|
||||
|
||||
Here's some interfaces you could implement for common use cases:
|
||||
|
||||
- **IAuthenticationProvider** - Allows you to add an authentication provider that can authenticate a user based on a name and a password, but that doesn't expect to deal with local users.
|
||||
- **IBaseItemComparer** - Allows you to add sorting rules for dealing with media that will show up in sort menus
|
||||
- **IIntroProvider** - Allows you to play a piece of media before another piece of media (i.e. a trailer before a movie, or a network bumper before an episode of a show)
|
||||
- **IItemResolver** - Allows you to define custom media types
|
||||
- **ILibraryPostScanTask** - Allows you to define a task that fires after scanning a library
|
||||
- **IMetadataSaver** - Allows you to define a metadata standard that Jellyfin can use to write metadata
|
||||
- **IResolverIgnoreRule** - Allows you to define subpaths that are ignored by media resolvers for use with another function (i.e. you wanted to have a theme song for each tv series stored in a subfolder that could be accessed by your plugin for playback in a menu).
|
||||
- **IScheduledTask** - Allows you to create a scheduled task that will appear in the scheduled task lists on the dashboard.
|
||||
|
||||
There are loads of other interfaces that can be used, but you'll need to poke around the API to get some info. If you're an expert on a particular interface, you should help [contribute some documentation](https://docs.jellyfin.org/general/contributing/index.html)!
|
||||
|
||||
### 4b. Use plugin aimed interfaces to add custom functionality
|
||||
|
||||
If your plugin doesn't fit perfectly neatly into a predefined interface, never fear, there are a set of interfaces and classes that allow your plugin to extend Jellyfin any which way you please. Here's a quick overview on how to use them
|
||||
|
||||
- **IPluginConfigurationPage** - Allows you to have a plugin config page on the dashboard. If you used one of the quickstart example projects, a premade page with some useful components to work with has been created for you! If not you can check out this guide here for how to whip one up.
|
||||
|
||||
- **IServerEntryPoint** - Allows you to run code at server startup that will stay in memory. You can make as many of these as you need and it is wildly useful for loading configs or persisting state. **Be aware that your main plugin class (IBasePlugin) cannot also be a IServerEntryPoint.**
|
||||
|
||||
- **ControllerBase** - Allows you to define custom REST-API endpoints. This is the default ASP.NET Web-API controller. You can use it exactly as you would in a normal Web-API project. Learn more about it [here](https://docs.microsoft.com/aspnet/core/web-api/?view=aspnetcore-5.0).
|
||||
|
||||
Likewise you might need to get data and services from the Jellyfin core, Jellyfin provides a number of interfaces you can add as parameters to your plugin constructor which are then made available in your project (you can see the 2 mandatory ones that are needed by the plugin system in the constructor as is).
|
||||
|
||||
- **IBlurayExaminer** - Allows you to examine blu-ray folders
|
||||
- **IDtoService** - Allows you to create data transport objects, presumably to send to other plugins or to the core
|
||||
- **ILibraryManager** - Allows you to directly access the media libraries without hopping through the API
|
||||
- **ILocalizationManager** - Allows you tap into the main localization engine which governs translations, rating systems, units etc...
|
||||
- **INetworkManager** - Allows you to get information about the server's networking status
|
||||
- **IServerApplicationPaths** - Allows you to get the running server's paths
|
||||
- **IServerConfigurationManager** - Allows you to write or read server configuration data into the application paths
|
||||
- **ITaskManager** - Allows you to execute and manipulate scheduled tasks
|
||||
- **IUserManager** - Allows you to retrieve user info and user library related info
|
||||
- **IXmlSerializer** - Allows you to use the main xml serializer
|
||||
- **IZipClient** - Allows you to use the core zip client for compressing and decompressing data
|
||||
|
||||
## 5. Create a Repository
|
||||
|
||||
- [See blog post](https://jellyfin.org/posts/plugin-updates/)
|
||||
|
||||
## 6. Set Up Debugging
|
||||
|
||||
Debugging can be set up by creating tasks which will be executed when running the plugin project. The specifics on setting up these tasks are not included as they may differ from IDE to IDE. The following list describes the general process:
|
||||
|
||||
- Compile the plugin in debug mode.
|
||||
- Create the plugin directory if it doesn't exist.
|
||||
- Copy the plugin into your server's plugin directory. The server will then execute it.
|
||||
- Make sure to set the working directory of the program being debugged to the working directory of the Jellyfin Server.
|
||||
- Start the server.
|
||||
|
||||
Some IDEs like Visual Studio Code may need the following compile flags to compile the plugin:
|
||||
|
||||
```shell
|
||||
dotnet build Your-Plugin.sln /property:GenerateFullPaths=true /consoleloggerparameters:NoSummary
|
||||
**Format conversion (bash + ffmpeg):**
|
||||
```bash
|
||||
#!/bin/bash
|
||||
INPUT="$1"
|
||||
OUTPUT="$2"
|
||||
ffmpeg -i "$INPUT" -c:a aac -b:a 128k "$OUTPUT"
|
||||
```
|
||||
|
||||
These flags generate the full paths for file names and **do not** generate a summary during the build process as this may lead to duplicate errors in the problem panel of your IDE.
|
||||
### Behavior
|
||||
|
||||
### 6.a Set Up Debugging on Visual Studio
|
||||
- If the script succeeds (exit code 0) and creates the output file, the processed file is added to your library
|
||||
- If the script fails, times out, or doesn't create an output file, the original downloaded file is used instead
|
||||
- All script output (stdout/stderr) is logged for debugging
|
||||
- Leave the script path empty to disable post-processing
|
||||
|
||||
Visual Studio allows developers to connect to other processes and debug them, setting breakpoints and inspecting the variables of the program. We can set this up following this steps:
|
||||
On this section we will explain how to set up our solution to enable debugging before the server starts.
|
||||
## Screenshots
|
||||
|
||||
1. Right-click on the solution, And click on Add -> Existing Project...
|
||||
2. Locate Jellyfin executable in your installation folder and click on 'Open'. It is called `Jellyfin.exe`. Now The solution will have a new "Project" called Jellyfin. This is the executable, not the source code of Jellyfin.
|
||||
3. Right-click on this new project and click on 'Set up as Startup Project'
|
||||
4. Right-click on this new project and click on 'Properties'
|
||||
5. Make sure that the 'Attach' parameter is set to 'No'
|
||||
### Podcast Library
|
||||

|
||||
|
||||
From now on, everytime you click on start from Visual Studio, it will start Jellyfin attached to the debugger!
|
||||
### Plugin Settings
|
||||

|
||||
|
||||
The only thing left to do is to compile the project as it is specified a few lines above and you are done.
|
||||
## Installation
|
||||
|
||||
### 6.b Automate the Setup on Visual Studio Code
|
||||
### From Plugin Repository (Recommended)
|
||||
|
||||
Visual Studio Code allows developers to automate the process of starting all necessary dependencies to start debugging the plugin. This guide assumes the reader is familiar with the [documentation on debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging) and has read the documentation in this file. It is assumed that the Jellyfin Server has already been compiled once. However, should one desire to automatically compile the server before the start of the debugging session, this can be easily implemented, but is not further discussed here.
|
||||
1. In Jellyfin, go to **Dashboard** → **Plugins** → **Repositories**
|
||||
2. Click the **+** button to add a new repository
|
||||
3. Enter:
|
||||
- **Repository Name**: `Jellypod`
|
||||
- **Repository URL**: `https://gitea.tourolle.paris/dtourolle/jellypod/raw/branch/master/manifest.json`
|
||||
4. Click **Save**
|
||||
5. Go to **Catalog** tab and find **Jellypod**
|
||||
6. Click **Install** and restart Jellyfin
|
||||
|
||||
A full example, which aims to be portable may be found in this repo's `.vscode` folder.
|
||||
### Manual Installation
|
||||
|
||||
This example expects you to clone `jellyfin`, `jellyfin-web` and `jellyfin-plugin-template` under the same parent directory, though you can customize this in `settings.json`
|
||||
1. Download the latest release from [Releases](https://gitea.tourolle.paris/dtourolle/jellypod/releases)
|
||||
2. Extract the contents to your Jellyfin plugins directory:
|
||||
- **Linux**: `~/.local/share/jellyfin/plugins/Jellypod/`
|
||||
- **Windows**: `%LOCALAPPDATA%\jellyfin\plugins\Jellypod\`
|
||||
- **Docker**: `/config/plugins/Jellypod/`
|
||||
3. Restart Jellyfin
|
||||
|
||||
1. Create a `settings.json` file inside your `.vscode` folder, to specify common options specific to your local setup.
|
||||
```jsonc
|
||||
{
|
||||
// jellyfinDir : The directory of the cloned jellyfin server project
|
||||
// This needs to be built once before it can be used
|
||||
"jellyfinDir" : "${workspaceFolder}/../jellyfin/Jellyfin.Server",
|
||||
// jellyfinWebDir : The directory of the cloned jellyfin-web project
|
||||
// This needs to be built once before it can be used
|
||||
"jellyfinWebDir" : "${workspaceFolder}/../jellyfin-web",
|
||||
// jellyfinDataDir : the root data directory for a running jellyfin instance
|
||||
// This is where jellyfin stores its configs, plugins, metadata etc
|
||||
// This is platform specific by default, but on Windows defaults to
|
||||
// ${env:LOCALAPPDATA}/jellyfin
|
||||
"jellyfinDataDir" : "${env:LOCALAPPDATA}/jellyfin",
|
||||
// The name of the plugin
|
||||
"pluginName" : "Jellyfin.Plugin.Template",
|
||||
}
|
||||
```
|
||||
### Building from Source
|
||||
|
||||
1. To automate the launch process, create a new `launch.json` file for C# projects inside the `.vscode` folder. The example below shows only the relevant parts of the file. Adjustments to your specific setup and operating system may be required.
|
||||
#### Requirements
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Paths and plugin names are configured in settings.json
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "coreclr",
|
||||
"name": "Launch",
|
||||
"request": "launch",
|
||||
"preLaunchTask": "build-and-copy",
|
||||
"program": "${config:jellyfinDir}/bin/Debug/net6.0/jellyfin.dll",
|
||||
"args": [
|
||||
//"--nowebclient"
|
||||
"--webdir",
|
||||
"${config:jellyfinWebDir}/dist/"
|
||||
],
|
||||
"cwd": "${config:jellyfinDir}",
|
||||
}
|
||||
]
|
||||
}
|
||||
- [.NET SDK 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0)
|
||||
|
||||
```
|
||||
#### Build
|
||||
|
||||
The `request` type is specified as `launch`, as this `launch.json` file will start the Jellyfin Server process. The `preLaunchTask` defines a task that will run before the Jellyfin Server starts. More on this later. It is important to set the `program` path to the Jellyin Server program and set the current working directory (`cwd`) to the working directory of the Jellyfin Server.
|
||||
The `args` option allows to specify arguments to be passed to the server, e.g. whether Jellyfin should start with the web-client or without it.
|
||||
```bash
|
||||
dotnet build
|
||||
```
|
||||
|
||||
2. Create a `tasks.json` file inside your `.vscode` folder and specify a `build-and-copy` task that will run in `sequence` order. This tasks depends on multiple other tasks and all of those other tasks can be defined as simple `shell` tasks that run commands like the `cp` command to copy a file. The sequence to run those tasks in is given below. Please note that it might be necessary to adjust the examples for your specific setup and operating system.
|
||||
The plugin DLL will be in `Jellyfin.Plugin.Jellypod/bin/Debug/net8.0/`.
|
||||
|
||||
The full file is shown here - Specific sections will be discussed in depth
|
||||
```jsonc
|
||||
{
|
||||
// Paths and plugin name are configured in settings.json
|
||||
"version": "2.0.0",
|
||||
"tasks": [
|
||||
{
|
||||
// A chain task - build the plugin, then copy it to your
|
||||
// jellyfin server's plugin directory
|
||||
"label": "build-and-copy",
|
||||
"dependsOrder": "sequence",
|
||||
"dependsOn": ["build", "make-plugin-dir", "copy-dll"]
|
||||
},
|
||||
{
|
||||
// Build the plugin
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "shell",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/${config:pluginName}.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
{
|
||||
// Ensure the plugin directory exists before trying to use it
|
||||
"label": "make-plugin-dir",
|
||||
"type": "shell",
|
||||
"command": "mkdir",
|
||||
"args": [
|
||||
"-Force",
|
||||
"-Path",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
},
|
||||
{
|
||||
// Copy the plugin dll to the jellyfin plugin install path
|
||||
// This command copies every .dll from the build directory to the plugin dir
|
||||
// Usually, you probablly only need ${config:pluginName}.dll
|
||||
// But some plugins may bundle extra requirements
|
||||
"label": "copy-dll",
|
||||
"type": "shell",
|
||||
"command": "cp",
|
||||
"args": [
|
||||
"./${config:pluginName}/bin/Debug/net6.0/publish/*",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
## Development
|
||||
|
||||
},
|
||||
]
|
||||
}
|
||||
This plugin is based on the [Jellyfin Plugin Template](https://github.com/jellyfin/jellyfin-plugin-template).
|
||||
|
||||
```
|
||||
1. The "build-and-copy" task which triggers all of the other tasks
|
||||
```jsonc
|
||||
{
|
||||
// A chain task - build the plugin, then copy it to your
|
||||
// jellyfin server's plugin directory
|
||||
"label": "build-and-copy",
|
||||
"dependsOrder": "sequence",
|
||||
"dependsOn": ["build", "make-plugin-dir", "copy-dll"]
|
||||
},
|
||||
```
|
||||
2. A build task. This task builds the plugin without generating summary, but with full paths for file names enabled.
|
||||
See the `.vscode` folder for VS Code debugging configuration.
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Build the plugin
|
||||
"label": "build",
|
||||
"command": "dotnet",
|
||||
"type": "shell",
|
||||
"args": [
|
||||
"publish",
|
||||
"${workspaceFolder}/${config:pluginName}.sln",
|
||||
"/property:GenerateFullPaths=true",
|
||||
"/consoleloggerparameters:NoSummary"
|
||||
],
|
||||
"group": "build",
|
||||
"presentation": {
|
||||
"reveal": "silent"
|
||||
},
|
||||
"problemMatcher": "$msCompile"
|
||||
},
|
||||
```
|
||||
## License
|
||||
|
||||
3. A tasks which creates the necessary plugin directory and a sub-folder for the specific plugin. The plugin directory is located below the [data directory](https://jellyfin.org/docs/general/administration/configuration.html) of the Jellyfin Server. As an example, the following path can be used for the bookshelf plugin: `$HOME/.local/share/jellyfin/plugins/Bookshelf/`
|
||||
```jsonc
|
||||
{
|
||||
// Ensure the plugin directory exists before trying to use it
|
||||
"label": "make-plugin-dir",
|
||||
"type": "shell",
|
||||
"command": "mkdir",
|
||||
"args": [
|
||||
"-Force",
|
||||
"-Path",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
},
|
||||
```
|
||||
This project is licensed under the GPLv3 - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
4. A tasks which copies the plugin dll which has been built in step 2.1. The file is copied into it's specific plugin directory within the server's plugin directory.
|
||||
## Links
|
||||
|
||||
```jsonc
|
||||
{
|
||||
// Copy the plugin dll to the jellyfin plugin install path
|
||||
// This command copies every .dll from the build directory to the plugin dir
|
||||
// Usually, you probablly only need ${config:pluginName}.dll
|
||||
// But some plugins may bundle extra requirements
|
||||
"label": "copy-dll",
|
||||
"type": "shell",
|
||||
"command": "cp",
|
||||
"args": [
|
||||
"./${config:pluginName}/bin/Debug/net6.0/publish/*",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
},
|
||||
```
|
||||
|
||||
## Licensing
|
||||
|
||||
Licensing is a complex topic. This repository features a GPLv3 license template that can be used to provide a good default license for your plugin. You may alter this if you like, but if you do a permissive license must be chosen.
|
||||
|
||||
Due to how plugins in Jellyfin work, when your plugin is compiled into a binary, it will link against the various Jellyfin binary NuGet packages. These packages are licensed under the GPLv3. Thus, due to the nature and restrictions of the GPL, the binary plugin you get will also be licensed under the GPLv3.
|
||||
|
||||
If you accept the default GPLv3 license from this template, all will be good. However if you choose a different license, please keep this fact in mind, as it might not always be obvious that an, e.g. MIT-licensed plugin would become GPLv3 when compiled.
|
||||
|
||||
Please note that this also means making "proprietary", source-unavailable, or otherwise "hidden" plugins for public consumption is not permitted. To build a Jellyfin plugin for distribution to others, it must be under the GPLv3 or a permissive open-source license that can be linked against the GPLv3.
|
||||
- **Repository**: https://gitea.tourolle.paris/dtourolle/jellypod
|
||||
|
||||
+15
-9
@@ -1,16 +1,22 @@
|
||||
---
|
||||
name: "Template"
|
||||
guid: "eb5d7894-8eef-4b36-aa6f-5d124e828ce1"
|
||||
name: "Jellypod"
|
||||
guid: "c713faf4-4e50-4e87-941a-1200178ed605"
|
||||
version: "1.0.0.0"
|
||||
targetAbi: "10.8.0.0"
|
||||
framework: "net6.0"
|
||||
overview: "Short description about your plugin"
|
||||
targetAbi: "10.9.0.0"
|
||||
framework: "net8.0"
|
||||
overview: "Podcast management plugin for Jellyfin"
|
||||
description: >
|
||||
This is a longer description that can span more than one
|
||||
line and include details about your plugin.
|
||||
Jellypod allows you to subscribe to podcast RSS feeds, automatically download
|
||||
episodes, and manage your podcast library within Jellyfin. Episodes are stored
|
||||
as standard audio files and integrate with Jellyfin's built-in audio player.
|
||||
category: "General"
|
||||
owner: "jellyfin"
|
||||
artifacts:
|
||||
- "Jellyfin.Plugin.Template.dll"
|
||||
- "Jellyfin.Plugin.Jellypod.dll"
|
||||
- "System.ServiceModel.Syndication.dll"
|
||||
build_type: "dotnet"
|
||||
dotnet_configuration: "Release"
|
||||
dotnet_framework: "net8.0"
|
||||
project: "Jellyfin.Plugin.Jellypod/Jellyfin.Plugin.Jellypod.csproj"
|
||||
changelog: >
|
||||
changelog
|
||||
Initial release
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 192 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 122 KiB |
@@ -0,0 +1,45 @@
|
||||
[
|
||||
{
|
||||
"guid": "c713faf4-4e50-4e87-941a-1200178ed605",
|
||||
"name": "Jellypod",
|
||||
"description": "Jellypod allows you to subscribe to podcast RSS feeds, automatically download episodes, and manage your podcast library within Jellyfin. Episodes are stored as standard audio files and integrate with Jellyfin's built-in audio player.",
|
||||
"overview": "Podcast management plugin for Jellyfin",
|
||||
"owner": "dtourolle",
|
||||
"category": "General",
|
||||
"imageUrl": "https://gitea.tourolle.paris/dtourolle/jellypod/raw/branch/master/Jellyfin.Plugin.Jellypod/Images/channel-icon.jpg",
|
||||
"versions": [
|
||||
{
|
||||
"version": "1.0.4",
|
||||
"changelog": "Release 1.0.4",
|
||||
"targetAbi": "10.9.0.0",
|
||||
"sourceUrl": "https://gitea.tourolle.paris/dtourolle/jellypod/releases/download/v1.0.4/jellypod_1.0.4.0.zip",
|
||||
"checksum": "0e0c134e6584581a8498cb17dfda334b",
|
||||
"timestamp": "2026-01-10T18:48:08Z"
|
||||
},
|
||||
{
|
||||
"version": "1.0.2",
|
||||
"changelog": "Release 1.0.2",
|
||||
"targetAbi": "10.9.0.0",
|
||||
"sourceUrl": "https://gitea.tourolle.paris/dtourolle/jellypod/releases/download/v1.0.2/jellypod_1.0.2.0.zip",
|
||||
"checksum": "874f6b76c8cf4bac6495fe946224096a",
|
||||
"timestamp": "2025-12-30T15:25:33Z"
|
||||
},
|
||||
{
|
||||
"version": "1.0.1",
|
||||
"changelog": "Release 1.0.1",
|
||||
"targetAbi": "10.9.0.0",
|
||||
"sourceUrl": "https://gitea.tourolle.paris/dtourolle/jellypod/releases/download/v1.0.1/jellypod_1.0.1.0.zip",
|
||||
"checksum": "8b8cddefe4e6b5c7128e1626a424519b",
|
||||
"timestamp": "2025-12-21T13:07:42Z"
|
||||
},
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"changelog": "Release 1.0.0",
|
||||
"targetAbi": "10.9.0.0",
|
||||
"sourceUrl": "https://gitea.tourolle.paris/dtourolle/jellypod/releases/download/v1.0.0/jellypod_1.0.0.0.zip",
|
||||
"checksum": "3267fa2bee3661f9a85c959497fe20dd",
|
||||
"timestamp": "2025-12-20T13:00:27Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
Reference in New Issue
Block a user