Compare commits
15
Commits
4679b77d1a
..
v1.0.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
76714eb0c6 | ||
|
|
f48aa86256 | ||
|
|
5a908cbe4d | ||
|
|
d890c11a9b | ||
|
|
c54221fba2 | ||
|
|
221a3f634d | ||
|
|
9ac32e11b5 | ||
|
|
bc24b40bf2 | ||
|
|
4537613ed7 | ||
|
|
003a8754a6 | ||
|
|
b4275837bc | ||
|
|
c1f7981ed7 | ||
|
|
ba497924e9 | ||
|
|
945c550901 | ||
|
|
2bcc7733b6 |
@@ -0,0 +1,61 @@
|
||||
name: '🏗️ Build Plugin'
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
pull_request:
|
||||
branches:
|
||||
- master
|
||||
paths-ignore:
|
||||
- '**/*.md'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build:
|
||||
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 Release --no-restore --no-self-contained
|
||||
|
||||
- name: Run tests
|
||||
run: dotnet test Jellyfin.Plugin.Jellypod.sln --no-build --configuration Release --verbosity normal
|
||||
|
||||
- name: Install JPRM
|
||||
run: |
|
||||
python3 -m venv /tmp/jprm-venv
|
||||
/tmp/jprm-venv/bin/pip install jprm
|
||||
|
||||
- name: Build Jellyfin Plugin
|
||||
id: jprm
|
||||
run: |
|
||||
# Create artifacts directory for JPRM output
|
||||
mkdir -p artifacts
|
||||
|
||||
# Build plugin using JPRM
|
||||
/tmp/jprm-venv/bin/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,181 @@
|
||||
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-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Verify .NET installation
|
||||
run: dotnet --version
|
||||
|
||||
- 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: Install JPRM
|
||||
run: |
|
||||
python3 -m venv /tmp/jprm-venv
|
||||
/tmp/jprm-venv/bin/pip install jprm
|
||||
|
||||
- name: Build Jellyfin Plugin
|
||||
id: jprm
|
||||
run: |
|
||||
# Create artifacts directory for JPRM output
|
||||
mkdir -p artifacts
|
||||
|
||||
# Build plugin using JPRM
|
||||
/tmp/jprm-venv/bin/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 }}"
|
||||
|
||||
# Prepare release body
|
||||
RELEASE_BODY="Jellypod Jellyfin Plugin ${{ steps.get_version.outputs.version }}\n\nSee attached files for plugin installation.\n\nTo install, add this repository URL to Jellyfin:\n\`${GITEA_URL}/${REPO_OWNER}/${REPO_NAME}/raw/branch/master/manifest.json\`"
|
||||
RELEASE_BODY_JSON=$(echo -n "${RELEASE_BODY}" | jq -Rs .)
|
||||
|
||||
# Create release using Gitea API
|
||||
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 "{
|
||||
\"tag_name\": \"${{ steps.get_version.outputs.version }}\",
|
||||
\"name\": \"Release ${{ steps.get_version.outputs.version }}\",
|
||||
\"body\": ${RELEASE_BODY_JSON},
|
||||
\"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
|
||||
|
||||
# Create new version entry
|
||||
NEW_VERSION=$(cat <<EOF
|
||||
{
|
||||
"version": "${VERSION}",
|
||||
"changelog": "Release ${VERSION}",
|
||||
"targetAbi": "10.9.0.0",
|
||||
"sourceUrl": "${DOWNLOAD_URL}",
|
||||
"checksum": "${CHECKSUM}",
|
||||
"timestamp": "${TIMESTAMP}"
|
||||
}
|
||||
EOF
|
||||
)
|
||||
|
||||
# Update manifest.json - prepend new version to versions array
|
||||
jq --argjson newver "${NEW_VERSION}" '.[0].versions = [$newver] + .[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
|
||||
@@ -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('.');
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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;
|
||||
@@ -26,6 +27,8 @@ public class JellypodController : ControllerBase
|
||||
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.
|
||||
@@ -34,16 +37,22 @@ public class JellypodController : ControllerBase
|
||||
/// <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)
|
||||
IPodcastDownloadService downloadService,
|
||||
IOpmlService opmlService,
|
||||
IHttpClientFactory httpClientFactory)
|
||||
{
|
||||
_logger = logger;
|
||||
_rssFeedService = rssFeedService;
|
||||
_storageService = storageService;
|
||||
_downloadService = downloadService;
|
||||
_opmlService = opmlService;
|
||||
_httpClientFactory = httpClientFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -110,6 +119,12 @@ public class JellypodController : ControllerBase
|
||||
// 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);
|
||||
@@ -171,6 +186,11 @@ public class JellypodController : ControllerBase
|
||||
podcast.MaxEpisodesToKeep = request.MaxEpisodesToKeep.Value;
|
||||
}
|
||||
|
||||
if (request.MaxEpisodeAgeDays.HasValue)
|
||||
{
|
||||
podcast.MaxEpisodeAgeDays = request.MaxEpisodeAgeDays.Value;
|
||||
}
|
||||
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
return Ok(podcast);
|
||||
}
|
||||
@@ -216,6 +236,12 @@ public class JellypodController : ControllerBase
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -362,4 +388,214 @@ public class JellypodController : ControllerBase
|
||||
|
||||
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,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; }
|
||||
}
|
||||
@@ -14,4 +14,9 @@ public class UpdatePodcastRequest
|
||||
/// 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; }
|
||||
}
|
||||
|
||||
@@ -137,11 +137,11 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
/// <inheritdoc />
|
||||
public async Task<ChannelItemResult> GetChannelItems(InternalChannelItemQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
_logger.LogDebug("GetChannelItems called for folder {FolderId}", query.FolderId);
|
||||
_logger.LogDebug("GetChannelItems called for folder {FolderId}, SortBy: {SortBy}, SortDescending: {SortDescending}", query.FolderId, query.SortBy, query.SortDescending);
|
||||
|
||||
try
|
||||
{
|
||||
var items = await GetFolderItemsAsync(query.FolderId, cancellationToken).ConfigureAwait(false);
|
||||
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
|
||||
@@ -157,7 +157,7 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<List<ChannelItemInfo>> GetFolderItemsAsync(string? folderId, CancellationToken cancellationToken)
|
||||
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))
|
||||
@@ -168,7 +168,7 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
// Podcast folder - show episodes
|
||||
if (Guid.TryParse(folderId, out var podcastId))
|
||||
{
|
||||
return await GetPodcastEpisodesAsync(podcastId, cancellationToken).ConfigureAwait(false);
|
||||
return await GetPodcastEpisodesAsync(podcastId, sortBy, sortDescending, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new List<ChannelItemInfo>();
|
||||
@@ -189,7 +189,7 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
Id = podcast.Id.ToString("N"),
|
||||
Name = podcast.Title,
|
||||
Overview = podcast.Description,
|
||||
ImageUrl = podcast.ImageUrl,
|
||||
ImageUrl = GetPodcastImageUrl(podcast.Id),
|
||||
Type = ChannelItemType.Folder,
|
||||
FolderType = ChannelFolderType.Container,
|
||||
DateCreated = podcast.DateAdded,
|
||||
@@ -203,7 +203,7 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
return items;
|
||||
}
|
||||
|
||||
private async Task<List<ChannelItemInfo>> GetPodcastEpisodesAsync(Guid podcastId, CancellationToken cancellationToken)
|
||||
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);
|
||||
@@ -214,21 +214,50 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
return items;
|
||||
}
|
||||
|
||||
// Sort episodes by published date, newest first
|
||||
var episodes = podcast.Episodes
|
||||
.OrderByDescending(e => e.PublishedDate)
|
||||
.ToList();
|
||||
// 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 = episode.Title,
|
||||
Overview = episode.Description,
|
||||
ImageUrl = episode.ImageUrl ?? podcast.ImageUrl,
|
||||
Name = episodeName,
|
||||
Overview = overview,
|
||||
ImageUrl = GetEpisodeImageUrl(podcast.Id, episode.Id),
|
||||
Type = ChannelItemType.Media,
|
||||
ContentType = ChannelMediaContentType.Podcast,
|
||||
MediaType = ChannelMediaType.Audio,
|
||||
@@ -358,10 +387,9 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
/// <inheritdoc />
|
||||
public string? GetCacheKey(string? userId)
|
||||
{
|
||||
// Use 5-minute time buckets for cache key
|
||||
var now = DateTime.Now;
|
||||
var timeBucket = new DateTime(now.Year, now.Month, now.Day, now.Hour, (now.Minute / 5) * 5, 0);
|
||||
return timeBucket.ToString("yyyy-MM-dd-HH-mm", CultureInfo.InvariantCulture);
|
||||
// Include database modification time so cache invalidates when podcasts/episodes change
|
||||
var lastModified = _storageService.LastModified;
|
||||
return lastModified.ToString("O", CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -469,4 +497,16 @@ public class JellypodChannel : IChannel, IHasCacheKey, IRequiresMediaInfoCallbac
|
||||
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}";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,8 +17,11 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
GlobalAutoDownloadEnabled = true;
|
||||
MaxConcurrentDownloads = 2;
|
||||
MaxEpisodesPerPodcast = 50;
|
||||
MaxEpisodeAgeDays = 0;
|
||||
CreatePodcastFolders = true;
|
||||
DownloadNewEpisodesOnly = true;
|
||||
PostDownloadScriptPath = string.Empty;
|
||||
PostDownloadScriptTimeout = 60;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -47,6 +50,12 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
/// </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>
|
||||
@@ -56,4 +65,15 @@ public class PluginConfiguration : BasePluginConfiguration
|
||||
/// 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; }
|
||||
}
|
||||
|
||||
@@ -4,42 +4,64 @@
|
||||
<meta charset="utf-8">
|
||||
<title>Jellypod</title>
|
||||
<style>
|
||||
.podcast-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
.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-item:last-child {
|
||||
.podcast-table tr:last-child td {
|
||||
border-bottom: none;
|
||||
}
|
||||
.podcast-image {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
max-width: 50px;
|
||||
max-height: 50px;
|
||||
min-width: 50px;
|
||||
min-height: 50px;
|
||||
object-fit: cover;
|
||||
border-radius: 4px;
|
||||
margin-right: 1em;
|
||||
background: #333;
|
||||
flex-shrink: 0;
|
||||
.podcast-table tr:hover {
|
||||
background: rgba(255,255,255,0.05);
|
||||
}
|
||||
.podcast-info {
|
||||
flex: 1;
|
||||
.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;
|
||||
margin-bottom: 0.25em;
|
||||
}
|
||||
.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;
|
||||
@@ -142,6 +164,38 @@
|
||||
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>
|
||||
@@ -157,6 +211,19 @@
|
||||
<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">
|
||||
@@ -193,7 +260,10 @@
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -224,7 +294,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
var html = podcasts.map(function(podcast) {
|
||||
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;
|
||||
@@ -235,14 +305,15 @@
|
||||
|
||||
console.log('Jellypod: Rendering podcast:', podcastTitle, 'ID:', podcastId);
|
||||
|
||||
return '<div class="podcast-item" data-id="' + podcastId + '">' +
|
||||
'<img class="podcast-image" src="' + podcastImage + '" alt="" onerror="this.style.display=\'none\'">' +
|
||||
'<div class="podcast-info">' +
|
||||
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>' +
|
||||
'</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>' +
|
||||
@@ -251,9 +322,19 @@
|
||||
'<span class="material-icons">delete</span>' +
|
||||
'</button>' +
|
||||
'</div>' +
|
||||
'</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);
|
||||
}
|
||||
@@ -361,7 +442,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);
|
||||
});
|
||||
@@ -377,6 +461,102 @@
|
||||
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>
|
||||
|
||||
@@ -81,4 +81,24 @@ public class Episode
|
||||
/// 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,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";
|
||||
}
|
||||
@@ -69,6 +69,12 @@ public class Podcast
|
||||
/// </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>
|
||||
|
||||
@@ -26,8 +26,12 @@ public class PluginServiceRegistrator : IPluginServiceRegistrator
|
||||
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>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ 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;
|
||||
@@ -117,7 +118,22 @@ public class PodcastUpdateTask : IScheduledTask
|
||||
}
|
||||
|
||||
processedCount++;
|
||||
progress.Report((double)processedCount / totalPodcasts * 100);
|
||||
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);
|
||||
@@ -139,4 +155,78 @@ public class PodcastUpdateTask : IScheduledTask
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// <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();
|
||||
}
|
||||
@@ -46,4 +46,13 @@ public interface IPodcastDownloadService
|
||||
/// <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);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,12 @@ namespace Jellyfin.Plugin.Jellypod.Services;
|
||||
/// </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>
|
||||
@@ -57,4 +63,10 @@ public interface IPodcastStorageService
|
||||
/// </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,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);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
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;
|
||||
@@ -63,15 +65,27 @@ public sealed class PodcastDownloadService : IPodcastDownloadService, IDisposabl
|
||||
IProgress<double>? progress = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var filePath = _storageService.GetEpisodeFilePath(podcast, episode);
|
||||
var directory = Path.GetDirectoryName(filePath);
|
||||
var finalPath = _storageService.GetEpisodeFilePath(podcast, episode);
|
||||
var finalDirectory = Path.GetDirectoryName(finalPath);
|
||||
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
if (!string.IsNullOrEmpty(finalDirectory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
Directory.CreateDirectory(finalDirectory);
|
||||
}
|
||||
|
||||
_logger.LogInformation("Downloading episode: {Title} to {Path}", episode.Title, filePath);
|
||||
// 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
|
||||
{
|
||||
@@ -91,7 +105,7 @@ public sealed class PodcastDownloadService : IPodcastDownloadService, IDisposabl
|
||||
long totalRead;
|
||||
try
|
||||
{
|
||||
var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, true);
|
||||
var fileStream = new FileStream(downloadPath, FileMode.Create, FileAccess.Write, FileShare.None, 81920, true);
|
||||
try
|
||||
{
|
||||
var buffer = new byte[81920];
|
||||
@@ -119,17 +133,51 @@ public sealed class PodcastDownloadService : IPodcastDownloadService, IDisposabl
|
||||
await contentStream.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
episode.LocalFilePath = filePath;
|
||||
_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 = totalRead;
|
||||
|
||||
_logger.LogInformation("Downloaded episode: {Title} ({Size} bytes)", episode.Title, totalRead);
|
||||
episode.FileSizeBytes = finalFileInfo.Length;
|
||||
|
||||
// Update the podcast in storage
|
||||
await _storageService.UpdatePodcastAsync(podcast).ConfigureAwait(false);
|
||||
|
||||
return filePath;
|
||||
return finalPath;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -137,6 +185,35 @@ public sealed class PodcastDownloadService : IPodcastDownloadService, IDisposabl
|
||||
_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 />
|
||||
@@ -206,6 +283,46 @@ public sealed class PodcastDownloadService : IPodcastDownloadService, IDisposabl
|
||||
}
|
||||
}
|
||||
|
||||
/// <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
|
||||
@@ -240,6 +357,136 @@ public sealed class PodcastDownloadService : IPodcastDownloadService, IDisposabl
|
||||
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()
|
||||
{
|
||||
|
||||
@@ -28,6 +28,7 @@ public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
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.
|
||||
@@ -47,6 +48,9 @@ public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
"Jellypod",
|
||||
"podcasts.json");
|
||||
|
||||
/// <inheritdoc />
|
||||
public DateTime LastModified => _lastModified;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<Podcast>> GetAllPodcastsAsync()
|
||||
{
|
||||
@@ -180,6 +184,7 @@ public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
{
|
||||
_logger.LogWarning("Database file does not exist at {Path}", DatabasePath);
|
||||
_cache = new PodcastDatabase();
|
||||
_lastModified = DateTime.UtcNow;
|
||||
return _cache;
|
||||
}
|
||||
|
||||
@@ -189,6 +194,7 @@ public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
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;
|
||||
}
|
||||
@@ -196,6 +202,7 @@ public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
{
|
||||
_logger.LogError(ex, "Failed to load podcast database, starting fresh");
|
||||
_cache = new PodcastDatabase();
|
||||
_lastModified = DateTime.UtcNow;
|
||||
return _cache;
|
||||
}
|
||||
}
|
||||
@@ -211,6 +218,7 @@ public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
}
|
||||
|
||||
db.LastSaved = DateTime.UtcNow;
|
||||
_lastModified = db.LastSaved;
|
||||
var json = JsonSerializer.Serialize(db, JsonOptions);
|
||||
await File.WriteAllTextAsync(DatabasePath, json).ConfigureAwait(false);
|
||||
_cache = db;
|
||||
@@ -261,6 +269,13 @@ public sealed class PodcastStorageService : IPodcastStorageService, IDisposable
|
||||
return ".mp3";
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<DateTime?> GetLastModifiedAsync()
|
||||
{
|
||||
var db = await LoadDatabaseAsync().ConfigureAwait(false);
|
||||
return db.LastSaved;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
|
||||
@@ -1,415 +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 net8.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 9.0](https://dotnet.microsoft.com/en-us/download/dotnet)
|
||||
|
||||
- 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 net9.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
|
||||
|
||||
Navigate to the csproj that was generated, and ensure that you modify the package references to exclude assets, so that unnecessary files aren't copied over.
|
||||
Skipping this step will prevent your plugin from registering correctly.
|
||||
```
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Jellyfin.Controller" Version="10.11.3">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Jellyfin.Model" Version="10.11.3">
|
||||
<ExcludeAssets>runtime</ExcludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
```
|
||||
Note: Ensure the package reference version matches the install version of jellyfin server, otherwise the plugin will show as NotSupported.
|
||||
### Example Scripts
|
||||
|
||||
## 2. Set Up the Basics
|
||||
|
||||
There are a few mandatory classes you'll need for a plugin so we need to make them.
|
||||
|
||||
### PluginConfiguration
|
||||
|
||||
Create a folder named "Configuration", and a PluginConfiguration.cs file inside.
|
||||
|
||||
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`
|
||||
|
||||
It should look something like the following:
|
||||
```c#
|
||||
using MediaBrowser.Model.Plugins;
|
||||
|
||||
namespace MyJellyfinPlugin.Configuration;
|
||||
class PluginConfiguration : BasePluginConfiguration
|
||||
{
|
||||
|
||||
}
|
||||
**Audio normalization (bash + ffmpeg):**
|
||||
```bash
|
||||
#!/bin/bash
|
||||
INPUT="$1"
|
||||
OUTPUT="$2"
|
||||
ffmpeg-normalize "$INPUT" -o "$OUTPUT" -c:a libmp3lame -b:a 128k
|
||||
```
|
||||
|
||||
### Plugin
|
||||
|
||||
This is the main class for your plugin and will reside in the root of your project. It will define your name, version and Id. It should inherit from `MediaBrowser.Common.Plugins.BasePlugin<PluginConfiguration>`
|
||||
|
||||
It should look something like the following:
|
||||
```c#
|
||||
using MediaBrowser.Common.Plugins;
|
||||
using MyJellyfinPlugin.Configuration;
|
||||
|
||||
namespace MyJellyfinPlugin;
|
||||
|
||||
class Plugin : BasePlugin<PluginConfiguration>
|
||||
{
|
||||
|
||||
}
|
||||
**Format conversion (bash + ffmpeg):**
|
||||
```bash
|
||||
#!/bin/bash
|
||||
INPUT="$1"
|
||||
OUTPUT="$2"
|
||||
ffmpeg -i "$INPUT" -c:a aac -b:a 128k "$OUTPUT"
|
||||
```
|
||||
|
||||
Note: If you called your PluginConfiguration class something different, you need to put that between the <>
|
||||
### Behavior
|
||||
|
||||
### Implement Required Properties
|
||||
- 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
|
||||
|
||||
The Plugin class needs a few properties implemented before it can work correctly.
|
||||
## Screenshots
|
||||
|
||||
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.
|
||||
### Podcast Library
|
||||

|
||||
|
||||
```c#
|
||||
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) : base(applicationPaths, xmlSerializer){}
|
||||
public override string Name => throw new System.NotImplementedException();
|
||||
public override Guid Id => Guid.Parse("");
|
||||
### Plugin Settings
|
||||

|
||||
|
||||
## Installation
|
||||
|
||||
### From Plugin Repository (Recommended)
|
||||
|
||||
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
|
||||
|
||||
### Manual Installation
|
||||
|
||||
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
|
||||
|
||||
### Building from Source
|
||||
|
||||
#### Requirements
|
||||
|
||||
- [.NET SDK 8.0](https://dotnet.microsoft.com/en-us/download/dotnet/8.0)
|
||||
|
||||
#### Build
|
||||
|
||||
```bash
|
||||
dotnet build
|
||||
```
|
||||
|
||||
## 3. Customize Plugin Information
|
||||
The plugin DLL will be in `Jellyfin.Plugin.Jellypod/bin/Debug/net8.0/`.
|
||||
|
||||
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
|
||||
## Development
|
||||
|
||||
- **Windows Users**: you can use the Powershell command `New-Guid`, `[guid]::NewGuid()` or the Visual Studio GUID generator
|
||||
This plugin is based on the [Jellyfin Plugin Template](https://github.com/jellyfin/jellyfin-plugin-template).
|
||||
|
||||
- **Linux and OS X Users**: you can use the Powershell Core command `New-Guid` or this command from your shell of choice:
|
||||
See the `.vscode` folder for VS Code debugging configuration.
|
||||
|
||||
```bash
|
||||
od -x /dev/urandom | head -n1 | awk '{OFS="-"; srand($6); sub(/./,"4",$5); sub(/./,substr("89ab",1+rand()*4,1),$6); print $2$3,$4,$5,$6,$7$8$9}'
|
||||
```
|
||||
## License
|
||||
|
||||
or
|
||||
This project is licensed under the GPLv3 - see the [LICENSE](LICENSE) file for details.
|
||||
|
||||
```bash
|
||||
uuidgen
|
||||
```
|
||||
## Links
|
||||
|
||||
- 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 directory (Normally C:\Users\{YourUserName}\AppData\Local\jellyfin\plugins). 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.
|
||||
|
||||
**IPluginServiceRegistrator** - Will be located by Jellyfin at server startup and allows you to add services to the DI container to allow for injection in your plugin's classes later.
|
||||
|
||||
- **IHostedService** - Allows you to run code as a background task that will be started at program startup and will remain in memory. See [Microsoft's documentation](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-8.0&tabs=visual-studio#ihostedservice-interface) for more information. You can make as many of these as you need; make Jellyfin aware of them with an `IPluginServiceRegistrator`. It is wildly useful for loading configs or persisting state. **Be aware that your main plugin class (IBasePlugin) cannot also be a IHostedService.**
|
||||
|
||||
- **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
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
### 6.a Set Up Debugging on Visual Studio
|
||||
|
||||
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.
|
||||
|
||||
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'
|
||||
|
||||
From now on, everytime you click on start from Visual Studio, it will start Jellyfin attached to the debugger!
|
||||
|
||||
The only thing left to do is to compile the project as it is specified a few lines above and you are done.
|
||||
|
||||
### 6.b Automate the Setup on Visual Studio Code
|
||||
|
||||
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.
|
||||
|
||||
A full example, which aims to be portable may be found in this repo's `.vscode` folder.
|
||||
|
||||
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. 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",
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```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/net8.0/jellyfin.dll",
|
||||
"args": [
|
||||
//"--nowebclient"
|
||||
"--webdir",
|
||||
"${config:jellyfinWebDir}/dist/"
|
||||
],
|
||||
"cwd": "${config:jellyfinDir}",
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
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 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/net8.0/publish/*",
|
||||
"${config:jellyfinDataDir}/plugins/${config:pluginName}/"
|
||||
]
|
||||
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
```
|
||||
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.
|
||||
|
||||
```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"
|
||||
},
|
||||
```
|
||||
|
||||
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}/"
|
||||
]
|
||||
},
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
```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/net8.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
|
||||
|
||||
@@ -14,5 +14,9 @@ owner: "jellyfin"
|
||||
artifacts:
|
||||
- "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: >
|
||||
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,37 @@
|
||||
[
|
||||
{
|
||||
"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.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