### Playback Tracking Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/11-examples.md Demonstrates how to track media playback using the Jellyfin SDK. This includes reporting playback start, progress updates, and playback stopped events. Ensure you have the SDK installed and a running Jellyfin instance to test. ```typescript import { Jellyfin, getUserApi, getPlaystateApi, getItemsApi } from '@jellyfin/sdk'; async function trackPlayback() { const jellyfin = new Jellyfin({ clientInfo: { name: 'PlaybackClient', version: '1.0.0' }, deviceInfo: { id: 'playback-device', name: 'Media Player' } }); const api = jellyfin.createApi('https://jellyfin.example.com'); // Authenticate const auth = await getUserApi(api).authenticateUserByName({ authenticateUserByName: { Username: 'demo', Pw: '' } }); api.update({ accessToken: auth.data.AccessToken || '' }); const userId = auth.data.User?.Id || ''; // Get a movie to play const itemsApi = getItemsApi(api); const movies = await itemsApi.getItems({ includeItemTypes: ['Movie'], limit: 1 }); const movieId = movies.data.Items?.[0]?.Id; if (!movieId) { console.error('No movies found'); return; } const movie = movies.data.Items![0]; console.log(`Playing: ${movie.Name}`); const playstateApi = getPlaystateApi(api); // Report playback start console.log('Reporting playback start...'); await playstateApi.reportPlaybackStart({ playbackStartInfo: { ItemId: movieId, CanSeek: true, IsPaused: false, PlaySessionId: 'session-123' } }); // Simulate playback progress updates const durationTicks = movie.RunTimeTicks || 0; let positionTicks = 0; for (let i = 0; i < 10; i++) { await new Promise(resolve => setTimeout(resolve, 1000)); positionTicks += 10_000_000; // 1 second in 100-ns ticks const percentComplete = (positionTicks / durationTicks) * 100; console.log(`Progress: ${percentComplete.toFixed(1)}%`); await playstateApi.reportPlaybackProgress({ playbackProgressInfo: { ItemId: movieId, PositionTicks: positionTicks, IsPaused: false, PlaySessionId: 'session-123' } }); } // Report playback stopped console.log('Reporting playback stopped...'); await playstateApi.reportPlaybackStopped({ playbackStopInfo: { ItemId: movieId, PositionTicks: positionTicks, PlaySessionId: 'session-123' } }); console.log('Playback tracking complete'); } trackPlayback().catch(console.error); ``` -------------------------------- ### Complete Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/05-api-utilities.md A comprehensive example demonstrating how to initialize the Jellyfin SDK, create an API instance, fetch public server information, authenticate a user, retrieve media libraries, and fetch recent movies. ```APIDOC ## Complete Example ```typescript import { Jellyfin, getUserApi, getSystemApi, getLibraryApi, getItemsApi } from '@jellyfin/sdk'; const jellyfin = new Jellyfin({ clientInfo: { name: 'MyApp', version: '1.0.0' }, deviceInfo: { id: 'device-1', name: 'Web Client' } }); // Create API instance const api = jellyfin.createApi('https://jellyfin.example.com'); // Get public server info const systemApi = getSystemApi(api); const info = await systemApi.getPublicSystemInfo(); console.log(`Connected to: ${info.data.ServerName}`); // Login const userApi = getUserApi(api); const auth = await userApi.authenticateUserByName({ authenticateUserByName: { Username: 'admin', Pw: 'password' } }); api.update({ accessToken: auth.data.AccessToken || '' }); // Get libraries const libraryApi = getLibraryApi(api); const libraries = await libraryApi.getMediaFolders(); console.log('Libraries:', libraries.data); // Get recent movies const itemsApi = getItemsApi(api); const movies = await itemsApi.getItems({ includeItemTypes: ['Movie'], limit: 10 }); console.log('Recent movies:', movies.data.Items); ``` ``` -------------------------------- ### Install Jellyfin SDK Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Install the SDK and axios using npm. This command ensures you have the necessary packages for SDK functionality. ```bash npm install @jellyfin/sdk axios ``` -------------------------------- ### Complete Jellyfin SDK Configuration Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/08-configuration.md This example demonstrates initializing the Jellyfin SDK with client and device information, creating a custom Axios instance with logging, and setting up the API. It also shows how to update the access token, switch servers, and log out. ```typescript import axios from 'axios'; import { Jellyfin } from '@jellyfin/sdk'; // Initialize SDK with client/device info const jellyfin = new Jellyfin({ clientInfo: { name: 'MyMediaApp', version: '2.0.0' }, deviceInfo: { id: 'device-uuid-1234-5678', name: 'Samsung Smart TV' } }); // Create custom Axios instance const customAxios = axios.create({ timeout: 30000, headers: { 'User-Agent': 'MyMediaApp/2.0.0' } }); // Add request logging customAxios.interceptors.request.use((config) => { console.log(`${config.method?.toUpperCase()} ${config.url}`); return config; }); // Create API instance const api = jellyfin.createApi( 'https://jellyfin.example.com:8920', '', // no token initially customAxios ); // Later: update token after authentication api.update({ accessToken: 'my-auth-token' }); // Switch servers if needed api.update({ basePath: 'https://new-server.example.com' }); // Logout api.update({ accessToken: '' }); ``` -------------------------------- ### Complete Utility Function Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/07-utility-functions.md This snippet shows how to use multiple utility functions including getting address candidates, parsing URLs, checking version compatibility, and generating authorization headers. Ensure you have imported the necessary functions from '@jellyfin/sdk'. ```typescript import { getAddressCandidates, getAuthorizationHeader, isVersionLess, parseUrl } from '@jellyfin/sdk'; // Generate address candidates const candidates = getAddressCandidates('jellyfin.local'); // Parse a URL const url = parseUrl('https://jellyfin.example.com:8920'); console.log(`${url.hostname}:${url.port}`); // "jellyfin.example.com:8920" // Check version compatibility if (isVersionLess('10.9.0', '10.10.0')) { console.log('Server version not supported'); } // Generate auth header const header = getAuthorizationHeader( { name: 'MyApp', version: '1.0.0' }, { name: 'WebClient', id: 'device-id' }, 'access-token' ); console.log(header); // "MediaBrowser Client=\"MyApp\", Device=\"WebClient\", DeviceId=\"device-id\", Version=\"1.0.0\", Token=\"access-token\"" ``` -------------------------------- ### Manage Jellyfin Libraries with TypeScript Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/11-examples.md This example demonstrates how to authenticate with the Jellyfin API, retrieve media libraries, refresh a library, and get library statistics using the TypeScript SDK. Ensure you have the SDK installed and replace placeholder credentials and URLs with your actual values. ```typescript import { Jellyfin, getUserApi, getLibraryApi, getItemRefreshApi } from '@jellyfin/sdk'; async function manageLibraries() { const jellyfin = new Jellyfin({ clientInfo: { name: 'LibraryClient', version: '1.0.0' }, deviceInfo: { id: 'library-device', name: 'Admin Tool' } }); const api = jellyfin.createApi('https://jellyfin.example.com'); // Authenticate as admin const auth = await getUserApi(api).authenticateUserByName({ authenticateUserByName: { Username: 'admin', Pw: 'password' } }); api.update({ accessToken: auth.data.AccessToken || '' }); // Get media libraries console.log('=== Media Libraries ==='); const libraryApi = getLibraryApi(api); const folders = await libraryApi.getMediaFolders(); folders.data.Items?.forEach(lib => { console.log(`Library: ${lib.Name}`); console.log(` Type: ${lib.CollectionType}`); console.log(` Path: ${lib.Path}`); }); // Refresh libraries if (folders.data.Items && folders.data.Items.length > 0) { const firstLibrary = folders.data.Items[0]; if (firstLibrary.Id) { console.log(`\nRefreshing: ${firstLibrary.Name}`); await libraryApi.refreshLibrary(firstLibrary.Id); console.log('Refresh started'); } } // Get library statistics console.log('\n=== Library Statistics ==='); const libraries = await libraryApi.getLibraries(); libraries.data.Items?.forEach(lib => { const itemCount = lib.CollectionFolders?.length || 0; console.log(`${lib.Name}: ${itemCount} folders`); }); } manageLibraries().catch(console.error); ``` -------------------------------- ### Install Jellyfin SDK Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/README.md Commands to install the Jellyfin SDK package using npm or yarn. ```sh npm i --save @jellyfin/sdk ``` ```sh yarn add @jellyfin/sdk ``` -------------------------------- ### Complete WebSocket Subscription Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/04-websocket-service.md Demonstrates how to establish a WebSocket connection, subscribe to session and activity log updates, listen for connection status changes, and clean up subscriptions. ```typescript import { Jellyfin, OutboundWebSocketMessageType, PeriodicListenerInterval } from '@jellyfin/sdk'; const jellyfin = new Jellyfin({ clientInfo: { name: 'MyApp', version: '1.0.0' }, deviceInfo: { id: 'device-123', name: 'MyDevice' } }); const api = jellyfin.createApi('https://jellyfin.example.com', 'my-token'); // Subscribe to session updates const unsubscribeSessions = api.subscribe( [OutboundWebSocketMessageType.Sessions], (message) => { console.log('Session count:', message.Data?.length); } ); // Subscribe to activity log updates const unsubscribeActivity = api.subscribe( [OutboundWebSocketMessageType.ActivityLogEntry], (message) => { console.log('Activity:', message.Data); } ); // Listen to connection status changes const unsubscribeStatus = api.webSocket?.onStatusChange((status) => { console.log('WebSocket status:', status); }) ?? (() => {}); // Later, cleanup unsubscribeSessions(); unsubscribeActivity(); unsubscribeStatus(); ``` -------------------------------- ### Install Jellyfin SDK and Axios Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/00-index.md Install the Jellyfin SDK and Axios using npm or yarn. Axios is a peer dependency required for making HTTP requests. ```bash npm install @jellyfin/sdk axios # or yarn add @jellyfin/sdk axios ``` -------------------------------- ### Complete Jellyfin SDK Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/05-api-utilities.md Demonstrates initializing the Jellyfin client, creating an API instance, fetching public system information, authenticating a user, retrieving media libraries, and fetching recent movies. Ensure you replace 'https://jellyfin.example.com', 'admin', and 'password' with your actual server URL and credentials. ```typescript import { Jellyfin, getUserApi, getSystemApi, getLibraryApi, getItemsApi } from '@jellyfin/sdk'; const jellyfin = new Jellyfin({ clientInfo: { name: 'MyApp', version: '1.0.0' }, deviceInfo: { id: 'device-1', name: 'Web Client' } }); // Create API instance const api = jellyfin.createApi('https://jellyfin.example.com'); // Get public server info const systemApi = getSystemApi(api); const info = await systemApi.getPublicSystemInfo(); console.log(`Connected to: ${info.data.ServerName}`); // Login const userApi = getUserApi(api); const auth = await userApi.authenticateUserByName({ authenticateUserByName: { Username: 'admin', Pw: 'password' } }); api.update({ accessToken: auth.data.AccessToken || '' }); // Get libraries const libraryApi = getLibraryApi(api); const libraries = await libraryApi.getMediaFolders(); console.log('Libraries:', libraries.data); // Get recent movies const itemsApi = getItemsApi(api); const movies = await itemsApi.getItems({ includeItemTypes: ['Movie'], limit: 10 }); console.log('Recent movies:', movies.data.Items); ``` -------------------------------- ### API Model Usage Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/06-types-models.md Demonstrates how to use SDK models for fetching items, reporting playback progress, and creating users. Ensure the API instance is correctly initialized before use. ```typescript import type { ItemDto, PlaystateRequest, CreateUserByName } from '@jellyfin/sdk'; import { getItemsApi, getPlaystateApi, getUserApi } from '@jellyfin/sdk'; // Get items (returns Promise>) const response = await getItemsApi(api).getItems({ includeItemTypes: ['Movie'], limit: 20 }); const items: ItemDto[] = response.data.Items || []; // Track playback const playstateRequest: PlaystateRequest = { ItemId: 'item-123', PositionTicks: 540000000, // 54 seconds in 100-ns units IsPaused: false }; await getPlaystateApi(api).reportPlaybackProgress({ playbackProgressInfo: playstateRequest }); // Create user const createRequest: CreateUserByName = { Name: 'newuser', Password: 'secure-password' }; await getUserApi(api).createUserByName({ createUserByName: createRequest }); ``` -------------------------------- ### React Example: Fetch and Display Movies Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md A React component demonstrating how to initialize the Jellyfin SDK, authenticate a user, fetch a list of movies, and display them. Handles loading and error states. ```typescript import { useState, useEffect } from 'react'; import { Jellyfin, getUserApi, getItemsApi } from '@jellyfin/sdk'; function JellyfinClient() { const [items, setItems] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { async function loadItems() { try { const jellyfin = new Jellyfin({ clientInfo: { name: 'ReactClient', version: '1.0.0' }, deviceInfo: { id: 'react-device', name: 'React App' } }); const api = jellyfin.createApi('https://jellyfin.example.com'); // Authenticate const auth = await getUserApi(api).authenticateUserByName({ authenticateUserByName: { Username: 'demo', Pw: '' } }); api.update({ accessToken: auth.data.AccessToken || '' }); // Get items const response = await getItemsApi(api).getItems({ limit: 20, includeItemTypes: ['Movie'] }); setItems(response.data.Items || []); } catch (err) { setError(err instanceof Error ? err.message : 'Unknown error'); } finally { setLoading(false); } } loadItems(); }, []); if (loading) return
Loading...
; if (error) return
Error: {error}
; return (

Movies

); } export default JellyfinClient; ``` -------------------------------- ### Server Discovery and Connection (TypeScript) Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/11-examples.md Discover available Jellyfin servers on the network and connect to the best-rated one. This example uses the discovery module to find servers and evaluate their suitability. ```typescript import { Jellyfin, getSystemApi } from '@jellyfin/sdk'; import type { RecommendedServerInfoScore } from '@jellyfin/sdk'; async function discoverAndConnect(serverAddress: string) { const jellyfin = new Jellyfin({ clientInfo: { name: 'DiscoveryClient', version: '1.0.0' }, deviceInfo: { id: 'discovery-device', name: 'Discovery App' } }); console.log(`Discovering servers for: ${serverAddress}`); // Get address candidates const candidates = jellyfin.discovery.getAddressCandidates(serverAddress); console.log(`Candidates: ${candidates.join(', ')}`); // Evaluate servers const servers = await jellyfin.discovery.getRecommendedServers(candidates); // Display results console.log(' Server Discovery Results:'); servers.forEach(server => { const scoreNames: Record = { 2: 'GREAT', 1: 'GOOD', 0: 'OK', '-1': 'BAD' }; console.log(` ${server.address}`); console.log(` Score: ${scoreNames[server.score]}`); console.log(` Response Time: ${server.responseTime}ms`); console.log(` Version: ${server.systemInfo?.Version}`); server.issues.forEach(issue => { console.log(` Issue: ${issue.constructor.name}`); }); }); // Find and connect to best server const best = jellyfin.discovery.findBestServer(servers); if (best) { console.log(` Best server: ${best.address}`); const api = jellyfin.createApi(best.address); const info = await getSystemApi(api).getPublicSystemInfo(); console.log(`Server Name: ${info.data.ServerName}`); return api; } else { console.log('No suitable servers found'); return null; } } discoverAndConnect('jellyfin.example.com').catch(console.error); ``` -------------------------------- ### Make API Calls Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Make API calls to retrieve server information and items. This example demonstrates fetching public system info and a list of movies. ```typescript import { getSystemApi, getItemsApi } from '@jellyfin/sdk'; // Get server info const systemApi = getSystemApi(api); const systemInfo = await systemApi.getPublicSystemInfo(); console.log(`Server: ${systemInfo.data.ServerName}`); // Get items const itemsApi = getItemsApi(api); const items = await itemsApi.getItems({ limit: 20, includeItemTypes: ['Movie'] }); console.log(`Found ${items.data.Items?.length} movies`); items.data.Items?.forEach(item => { console.log(`- ${item.Name} (${item.ProductionYear})`); }); ``` -------------------------------- ### Get Media Libraries Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Retrieve a list of all media folders (libraries) configured in Jellyfin. Requires an initialized 'api' object. ```typescript import { getLibraryApi } from '@jellyfin/sdk'; const libraryApi = getLibraryApi(api); const libraries = await libraryApi.getMediaFolders(); libraries.data.Items?.forEach(lib => { console.log(`${lib.Name}: ${lib.CollectionType}`); }); ``` -------------------------------- ### Get Recommended Server Candidates Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/03-discovery-service.md A convenience method that combines generating address candidates and evaluating server health. Use this for a quick assessment of a given server input. ```typescript const servers = await jellyfin.discovery.getRecommendedServerCandidates('demo.jellyfin.org'); ``` -------------------------------- ### Get Libraries Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Retrieve a list of all media libraries available on the server. ```APIDOC ## Get Libraries ### Description Retrieve a list of all media folders (libraries) configured on the server. ### Method ```typescript getLibraryApi(api).getMediaFolders() ``` ### Response - `libraries.data.Items`: An array of library objects, each with `Name` and `CollectionType` properties. ``` -------------------------------- ### WebSocket Connection Setup Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Ensure the access token is set on the API instance before subscribing to WebSocket messages. This is crucial for establishing a connection. ```typescript // Must have access token for WebSocket to connect api.update({ accessToken: 'valid-token' }); // Then subscribe api.subscribe([OutboundWebSocketMessageType.Sessions], (msg) => { console.log(msg); }); ``` -------------------------------- ### Robust Error Handling Example Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/11-examples.md This example shows how to handle authentication and API request errors, including specific checks for common HTTP status codes and network issues. It demonstrates nested try-catch blocks for granular error management. ```typescript import { Jellyfin, getUserApi, getItemsApi } from '@jellyfin/sdk'; import type { AxiosError } from 'axios'; async function robustExample() { const jellyfin = new Jellyfin({ clientInfo: { name: 'RobustClient', version: '1.0.0' }, deviceInfo: { id: 'robust-device', name: 'Error Handler' } }); const api = jellyfin.createApi('https://jellyfin.example.com'); try { // Try to authenticate try { const auth = await getUserApi(api).authenticateUserByName({ authenticateUserByName: { Username: 'admin', Pw: 'password' } }); api.update({ accessToken: auth.data.AccessToken || '' }); } catch (error) { const axiosError = error as AxiosError; if (axiosError.response?.status === 401) { console.log('Invalid credentials, trying as guest...'); } else if (axiosError.code === 'ECONNREFUSED') { throw new Error('Server is not running'); } else { throw error; } } // Try to get items try { const items = await getItemsApi(api).getItems({ limit: 10 }); console.log(`Found ${items.data.Items?.length || 0} items`); } catch (error) { const axiosError = error as AxiosError; if (axiosError.response?.status === 403) { console.error('Access denied'); } else if (axiosError.response?.status === 404) { console.error('Items endpoint not found'); } else { throw error; } } } catch (error) { console.error('Fatal error:', error instanceof Error ? error.message : error); } } robustExample(); ``` -------------------------------- ### Get Detailed System Information Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/05-api-utilities.md Retrieves detailed system information, which requires authentication. Useful for monitoring server status and processes. ```typescript // Get detailed system info (requires auth) const detailed = await systemApi.getSystemInfo(); console.log(`Uptime: ${detailed.data.RunningProcessName}`); ``` -------------------------------- ### Get Public System Information Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/05-api-utilities.md Retrieves basic server information without requiring authentication. Useful for displaying server name and version. ```typescript const systemApi = getSystemApi(api); // Get public server info const info = await systemApi.getPublicSystemInfo(); console.log(`Server: ${info.data.ServerName} v${info.data.Version}`); ``` -------------------------------- ### URL Normalization Examples Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/07-utility-functions.md Demonstrates how `parseUrl()` normalizes URLs by removing fragments, query strings, decoding octets, and handling trailing dots and slashes. Use this to ensure consistent URL parsing. ```typescript parseUrl('http://example.com/path/?query=1#section').pathname // → "/path" (query and fragment removed) ``` ```typescript parseUrl('http://example.com./path').hostname // → "example.com" (trailing dot removed) ``` ```typescript parseUrl('http://example.com/path//double').pathname // → "/path/double" (duplicate slash collapsed) ``` -------------------------------- ### Handle URL Parsing Errors Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/10-errors-exceptions.md Demonstrates how to catch and handle errors when parsing unsupported or invalid URLs using the SDK's parsing functions. Includes examples for unsupported data URLs and empty input. ```typescript import { getAddressCandidates, parseUrl } from '@jellyfin/sdk'; try { getAddressCandidates('data:text/html,test'); // throws } catch (error) { console.error('Invalid URL:', error instanceof Error ? error.message : error); // Result: "data URLs are not supported" } try { parseUrl(''); // throws } catch (error) { console.error('Invalid URL:', error instanceof Error ? error.message : error); // Result: "Input is required" } ``` -------------------------------- ### Handle Server Not Found Errors Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/10-errors-exceptions.md Detect server connection issues by checking specific Axios error codes like ECONNREFUSED, ENOTFOUND, and ETIMEDOUT. This example shows how to attempt to get public system information and handle connection-related errors. ```typescript import { getSystemApi } from '@jellyfin/sdk'; import type { AxiosError } from 'axios'; try { const api = jellyfin.createApi('https://jellyfin.local:9999'); const info = await getSystemApi(api).getPublicSystemInfo(); } catch (error) { const axiosError = error as AxiosError; if (axiosError.code === 'ECONNREFUSED') { console.error('Server is not running or port is incorrect'); } else if (axiosError.code === 'ENOTFOUND') { console.error('Server hostname could not be resolved'); } else if (axiosError.code === 'ETIMEDOUT') { console.error('Server is not responding (timeout)'); } else { console.error('Connection error:', axiosError.message); } } ``` -------------------------------- ### Initialize SDK, Discover Server, and Fetch Data Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/README.md Demonstrates initializing the Jellyfin SDK, discovering available servers, connecting to the best server, and fetching public system information and user data. Ensure the SDK is imported and the necessary utility functions are available. ```js const jellyfin = new Jellyfin({ clientInfo: { name: 'My Client Application', version: '1.0.0' }, deviceInfo: { name: 'Device Name', id: 'unique-device-id' } }); const servers = await jellyfin.discovery.getRecommendedServerCandidates('demo.jellyfin.org/stable'); const best = jellyfin.discovery.findBestServer(servers); const api = jellyfin.createApi(best.address); const info = await getSystemApi(api).getPublicSystemInfo(); console.log('Info =>', info.data); const users = await getUserApi(api).getPublicUsers(); console.log('Users =>', users.data); ``` -------------------------------- ### Initialize Jellyfin SDK Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Initialize the Jellyfin SDK with client and device information. This is the first step before creating API instances. ```typescript import { Jellyfin } from '@jellyfin/sdk'; const jellyfin = new Jellyfin({ clientInfo: { name: 'My Jellyfin Client', version: '1.0.0' }, deviceInfo: { id: 'unique-device-id-123', name: 'Web Browser' } }); ``` -------------------------------- ### Server Discovery and Connection Flow Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/03-discovery-service.md Illustrates the standard process for discovering Jellyfin servers from user input, selecting the best available server, and establishing an API connection. Requires initialization of the Jellyfin client with client and device information. ```typescript const jellyfin = new Jellyfin({ clientInfo: { name: 'MyApp', version: '1.0.0' }, deviceInfo: { id: 'device-123', name: 'MyDevice' } }); // Discover servers from user input const servers = await jellyfin.discovery.getRecommendedServerCandidates('jellyfin.example.com'); // Find the best one const best = jellyfin.discovery.findBestServer(servers); // Create API instance if (best) { const api = jellyfin.createApi(best.address); console.log(`Connecting to ${best.address}`); } else { console.error('No servers found'); } ``` -------------------------------- ### Handle Errors Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Example of how to handle potential errors when making API calls. ```APIDOC ## Handle Errors ### Description Demonstrates how to catch and handle errors, such as `AxiosError`, that may occur during API requests. ### Method ```typescript try { await itemsApi.getItem('invalid-id'); } catch (error) { const axiosError = error as AxiosError; console.error(`Error ${axiosError.response?.status}: ${axiosError.message}`); } ``` ``` -------------------------------- ### Get Item Details Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Retrieve detailed information about a specific media item. ```APIDOC ## Get Item Details ### Description Retrieve detailed information for a specific item using its ID. ### Method ```typescript getItemsApi(api).getItem(itemId) ``` ### Parameters #### Path Parameters - **itemId** (string) - Required - The ID of the item to retrieve. ### Response - `item.data`: The detailed object for the requested item. ``` -------------------------------- ### Get User Information Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Retrieve public users without authentication or all users with authentication. ```APIDOC ## Get User Information ### Description Retrieve public users (no authentication required) or all users (requires authentication). ### Method ```typescript getUserApi(api).getPublicUsers() getUserApi(api).getUsers() ``` ### Parameters None for `getPublicUsers`. Requires authentication for `getUsers`. ### Response - `users.data`: Array of user objects. - `allUsers.data`: Array of all user objects. ``` -------------------------------- ### Get Item Details Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Fetch details for a specific media item using its ID. Requires an initialized 'api' object. ```typescript import { getItemsApi } from '@jellyfin/sdk'; const itemsApi = getItemsApi(api); const item = await itemsApi.getItem('item-id-123'); console.log(item.data); ``` -------------------------------- ### Jellyfin Constructor Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/01-jellyfin-class.md Initializes a new instance of the Jellyfin SDK with provided client and device configurations. ```APIDOC ## Constructor Jellyfin ### Description Creates a new instance of the Jellyfin SDK. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **parameters** (JellyfinParameters) - Required - Configuration object containing client and device information ### Request Example ```typescript const jellyfin = new Jellyfin({ clientInfo: { name: 'My Client', version: '1.0.0' }, deviceInfo: { id: 'device-123', name: 'My Device' } }); ``` ### Response #### Success Response (void) Returns void. #### Response Example None ``` -------------------------------- ### Get User Information Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Retrieve public users without authentication or all users with authentication. Ensure the 'api' object is initialized. ```typescript import { getUserApi } from '@jellyfin/sdk'; const userApi = getUserApi(api); // Get public users (no auth required) const users = await userApi.getPublicUsers(); console.log(users.data); // Get all users (requires auth) const allUsers = await userApi.getUsers(); ``` -------------------------------- ### Basic Server Connection and Item Browsing (TypeScript) Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/11-examples.md Connect to a Jellyfin server, authenticate, and retrieve a list of recent movies. Requires client and device information for initialization. ```typescript import { Jellyfin, getUserApi, getSystemApi, getItemsApi } from '@jellyfin/sdk'; async function main() { // Initialize SDK const jellyfin = new Jellyfin({ clientInfo: { name: 'BasicClient', version: '1.0.0' }, deviceInfo: { id: 'basic-device-001', name: 'Console App' } }); // Create API instance const api = jellyfin.createApi('https://jellyfin.example.com'); // Get public server info const systemApi = getSystemApi(api); const systemInfo = await systemApi.getPublicSystemInfo(); console.log(`Connected to: ${systemInfo.data.ServerName}`); // Authenticate const userApi = getUserApi(api); const auth = await userApi.authenticateUserByName({ authenticateUserByName: { Username: 'admin', Pw: 'password' } }); if (!auth.data.AccessToken) { console.error('Authentication failed'); return; } api.update({ accessToken: auth.data.AccessToken }); console.log(`Logged in as: ${auth.data.User?.Name}`); // Get movies const itemsApi = getItemsApi(api); const movies = await itemsApi.getItems({ includeItemTypes: ['Movie'], limit: 10 }); console.log(' Recent Movies:'); movies.data.Items?.forEach(movie => { console.log(` - ${movie.Name} (${movie.ProductionYear})`); }); } main().catch(console.error); ``` -------------------------------- ### Live TV APIs Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/05-api-utilities.md APIs for accessing Live TV channel information, guide data, and managing scheduled tasks. ```APIDOC ## getLiveTvApi ### Description Provides access to Live TV channel and program guide information. ### Method Signature ```typescript function getLiveTvApi(api: Api): LiveTvApi ``` ### Key Methods - `getChannels()`: Retrieves a list of available TV channels. - `getGuideInfo()`: Fetches program guide information. ``` ```APIDOC ## getScheduledTasksApi ### Description Manages server scheduled tasks. ### Method Signature ```typescript function getScheduledTasksApi(api: Api): ScheduledTasksApi ``` ### Key Methods - `getTasks()`: Lists all scheduled tasks. - `startTask(taskId)`: Initiates the execution of a specific task. - `getTask(taskId)`: Retrieves details for a specific task. ``` -------------------------------- ### Api Constructor Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/02-api-class.md Initializes a new Api instance to connect to a Jellyfin server. It requires server details and client/device information, with optional authentication token and custom Axios instance. ```APIDOC ## Constructor Api ### Description Creates a new API instance. Typically created via `Jellyfin.createApi()` rather than directly. ### Parameters #### Path Parameters - **basePath** (`string`) - Required - Server base URL (trailing slash automatically removed) - **clientInfo** (`ClientInfo`) - Required - Client application information - **deviceInfo** (`DeviceInfo`) - Required - Device information - **accessToken** (`string`) - Optional - Initial access token for authenticated requests - **axiosInstance** (`AxiosInstance`) - Optional - Custom Axios instance for HTTP communication ### Returns - `void` ``` -------------------------------- ### Jellyfin SDK Initialization Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/08-configuration.md Instantiate the Jellyfin SDK with essential client and device information. Ensure ClientInfo and DeviceInfo structures are correctly populated. ```typescript interface JellyfinParameters { clientInfo: ClientInfo; deviceInfo: DeviceInfo; } interface ClientInfo { name: string; // Application name (e.g., "MyMediaClient") version: string; // Application version (e.g., "1.0.0") } interface DeviceInfo { id: string; // Unique device identifier (UUID recommended) name: string; // Human-readable device name (e.g., "Living Room TV") } ``` ```typescript import { Jellyfin } from '@jellyfin/sdk'; const jellyfin = new Jellyfin({ clientInfo: { name: 'MyMediaClient', version: '2.1.0' }, deviceInfo: { id: 'a1b2c3d4-e5f6-7g8h-9i0j-k1l2m3n4o5p6', name: 'Web Browser' } }); ``` -------------------------------- ### Create a Playlist Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Create a new playlist and add items to it. ```APIDOC ## Create a Playlist ### Description Create a new playlist and subsequently add items to it. ### Methods - `createPlaylist(createPlaylistDto)` - `addPlaylistItem(itemId, playlistId)` ### Parameters #### `createPlaylistDto` (object) - Required - **Name** (string) - Required - The name of the new playlist. - **UserId** (string) - Required - The ID of the user for whom the playlist is created. #### `itemId` (string) - Required - The ID of the item to add to the playlist. #### `playlistId` (string) - Required - The ID of the playlist to which the item will be added. ### Request Example ```typescript const playlist = await playlistsApi.createPlaylist({ createPlaylistDto: { Name: 'My Playlist', UserId: 'user-id' } }); const playlistId = playlist.data.Id; // Add items to playlist await playlistsApi.addPlaylistItem('my-item-id', playlistId); ``` ``` -------------------------------- ### Convenience Method for Server Discovery Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md A simplified method to discover recommended Jellyfin servers and find the best one using a hostname. ```typescript const servers = await jellyfin.discovery.getRecommendedServerCandidates('jellyfin.example.com'); const best = jellyfin.discovery.findBestServer(servers); ``` -------------------------------- ### Import Generated Client Types Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/06-types-models.md Import frequently used TypeScript types from the generated Jellyfin SDK client. Ensure the SDK is installed and configured correctly. ```typescript import type { UserDto, ItemDto, AuthenticationResult, PublicSystemInfo, PlaystateRequest, CreateUserByName } from '@jellyfin/sdk'; ``` -------------------------------- ### Access API Endpoints Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/00-index.md Utilize API utilities to get type-safe access to generated OpenAPI client endpoints. Imports are required for specific API modules. ```typescript import { getUserApi, getItemsApi, getSystemApi } from '@jellyfin/sdk'; const userApi = getUserApi(api); const items = await getItemsApi(api).getItems({ limit: 20 }); ``` -------------------------------- ### RecommendedServerDiscovery Methods Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/03-discovery-service.md Provides methods for fetching server information and discovering servers. These are low-level methods typically used internally. ```typescript async fetchRecommendedServerInfo(address: string): Promise async discover(servers: Array, minimumScore?: RecommendedServerInfoScore): Promise> ``` -------------------------------- ### Track Playback Progress Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Report playback start, progress updates, and playback stop for media items. Requires an initialized 'api' object and valid ItemIds. ```typescript import { getPlaystateApi } from '@jellyfin/sdk'; const playstateApi = getPlaystateApi(api); // Report playback start await playstateApi.reportPlaybackStart({ playbackStartInfo: { ItemId: 'item-123', CanSeek: true, IsPaused: false } }); // Update progress await playstateApi.reportPlaybackProgress({ playbackProgressInfo: { ItemId: 'item-123', PositionTicks: 540000000, // 54 seconds IsPaused: false } }); // Report playback end await playstateApi.reportPlaybackStopped({ playbackStopInfo: { ItemId: 'item-123', PositionTicks: 5400000000 // total time watched } }); ``` -------------------------------- ### Create Jellyfin API Instance Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/01-jellyfin-class.md Instantiates the Jellyfin SDK with client and device details, then creates an API client for a specific Jellyfin server using its base path and an optional access token. ```typescript const jellyfin = new Jellyfin({ clientInfo: { name: 'My Client', version: '1.0.0' }, deviceInfo: { id: 'device-123', name: 'My Device' } }); const api = jellyfin.createApi('https://jellyfin.example.com', 'my-access-token'); ``` -------------------------------- ### Build Jellyfin SDK Locally Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/README.md Commands to build the SDK locally after replacing the openapi.json file. This generates compiled output in the 'lib' folder. ```sh npm run fix-schema npm run build ``` -------------------------------- ### Get Default Port for Protocol Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/07-utility-functions.md Retrieves the standard port number associated with a given protocol string (e.g., 'http:' or 'https:'). Throws an error if the protocol is not supported. ```typescript function getDefaultPort(protocol: string): number ``` -------------------------------- ### Create API Instance Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Create an API instance by providing the base URL of your Jellyfin server. This instance will be used for all subsequent API calls. ```typescript const api = jellyfin.createApi('https://jellyfin.example.com'); ``` -------------------------------- ### Get Current WebSocket Status Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/04-websocket-service.md Access the `socketStatus` getter to retrieve the current connection status of the WebSocket. This returns the current `WebSocketStatus` or `undefined` if the status is not yet available. ```typescript get socketStatus(): WebSocketStatus | undefined ``` -------------------------------- ### Minimal vs. Full Model Creation Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/06-types-models.md Illustrates how to construct models with only required fields for minimal creation, and how to include all fields for full creation. This is useful for understanding optional properties marked with '?'. ```typescript // Minimal user creation const minimalCreate: CreateUserByName = { Name: 'newuser' // Password is optional }; // Full user creation const fullCreate: CreateUserByName = { Name: 'newuser', Password: 'secure-password' }; ``` -------------------------------- ### Import and Initialize API Utilities Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/05-api-utilities.md Import and initialize various API utilities by passing an Api instance. This sets up type-safe access to different functional areas of the Jellyfin API. ```typescript import { getUserApi, getItemsApi, getSystemApi } from '@jellyfin/sdk'; const userApi = getUserApi(api); const itemsApi = getItemsApi(api); const systemApi = getSystemApi(api); ``` -------------------------------- ### Configuration APIs Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/05-api-utilities.md APIs for managing server configuration and user display preferences. ```APIDOC ## getConfigurationApi ### Description Handles server configuration management. ### Method Signature ```typescript function getConfigurationApi(api: Api): ConfigurationApi ``` ### Key Methods - `getConfiguration()`: Retrieves the current server configuration. - `updateConfiguration(config)`: Updates the server configuration with the provided settings. ``` ```APIDOC ## getDisplayPreferencesApi ### Description Manages user-specific display preferences, including view settings, sorting, and filtering. ### Method Signature ```typescript function getDisplayPreferencesApi(api: Api): DisplayPreferencesApi ``` ``` ```APIDOC ## getDevicesApi ### Description Provides functionality for managing registered devices. ### Method Signature ```typescript function getDevicesApi(api: Api): DevicesApi ``` ### Key Methods - `getDevices()`: Retrieves a list of all registered devices. - `deleteDevice(deviceId)`: Removes a specific device using its ID. ``` -------------------------------- ### Handle Insufficient Permissions Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/10-errors-exceptions.md Identify insufficient permissions by checking for a 403 status code in the Axios error response. This example attempts to retrieve a list of movies and handles the permission error. ```typescript try { // Operation requires higher permissions const items = await getItemsApi(api).getItems({ includeItemTypes: ['Movie'] }); } catch (error) { const axiosError = error as AxiosError; if (axiosError.response?.status === 403) { console.error('You do not have permission to access this'); } else { console.error('Error:', axiosError.message); } } ``` -------------------------------- ### Create API Instance Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/00-index.md Create an Api instance for a specific Jellyfin server. Supports providing an access token and an Axios instance for custom configurations. ```typescript const api = jellyfin.createApi('https://jellyfin.example.com', accessToken?, axiosInstance?); ``` -------------------------------- ### Api Class Constructor Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/02-api-class.md Creates a new Api instance. This is usually done through Jellyfin.createApi(). It requires server base path, client info, and device info, with optional access token and Axios instance. ```typescript constructor( basePath: string, clientInfo: ClientInfo, deviceInfo: DeviceInfo, accessToken?: string, axiosInstance?: AxiosInstance ): void ``` -------------------------------- ### RecommendedServerInfo Interface Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/03-discovery-service.md Represents the information gathered about a discovered Jellyfin server, including its address, performance metrics, and any detected issues. ```typescript interface RecommendedServerInfo { address: string; responseTime: number; score: RecommendedServerInfoScore; issues: Array; systemInfo?: PublicSystemInfo; } ``` -------------------------------- ### Get Server Address Candidates Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/09-quick-start.md Use getAddressCandidates to find potential server addresses. This function supports various address formats, including hostnames, IP addresses, and URLs with or without ports. ```typescript // These all work getAddressCandidates('jellyfin.example.com') getAddressCandidates('192.168.1.100:8096') getAddressCandidates('http://jellyfin.local') getAddressCandidates('https://jellyfin.example.com:8920') ``` -------------------------------- ### Batch Operations with Jellyfin SDK Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/11-examples.md Demonstrates how to perform batch operations, such as marking multiple movies as watched, using the Jellyfin SDK. Ensure you have authenticated and updated the API with an access token before executing. ```typescript import { Jellyfin, getUserApi, getItemsApi, getPlaystateApi } from '@jellyfin/sdk'; async function batchOperations() { const jellyfin = new Jellyfin({ clientInfo: { name: 'BatchClient', version: '1.0.0' }, deviceInfo: { id: 'batch-device', name: 'Batch Processor' } }); const api = jellyfin.createApi('https://jellyfin.example.com'); // Authenticate const auth = await getUserApi(api).authenticateUserByName({ authenticateUserByName: { Username: 'demo', Pw: '' } }); api.update({ accessToken: auth.data.AccessToken || '' }); const itemsApi = getItemsApi(api); const playstateApi = getPlaystateApi(api); // Get movies const movies = await itemsApi.getItems({ includeItemTypes: ['Movie'], limit: 50 }); const movieIds = movies.data.Items?.map(m => m.Id).filter(id => id) || []; console.log(`Processing ${movieIds.length} movies...`); // Mark all as watched (batch operation) for (const movieId of movieIds) { try { await playstateApi.markPlayedItem(movieId); console.log(`Marked ${movieId} as watched`); } catch (error) { console.error(`Failed to mark ${movieId}:`, error); } } console.log('Batch operation complete'); } batchOperations().catch(console.error); ``` -------------------------------- ### Create Jellyfin API Instance Source: https://github.com/jellyfin/jellyfin-sdk-typescript/blob/master/_autodocs/08-configuration.md Create an API instance for a specific server connection. Provide the server's base path and optionally an access token or a custom Axios instance for advanced configurations like setting timeouts. ```typescript createApi( basePath: string, accessToken?: string, axiosInstance?: AxiosInstance ): Api ``` ```typescript // Minimal configuration const api = jellyfin.createApi('https://jellyfin.example.com'); ``` ```typescript // With access token const api = jellyfin.createApi( 'https://jellyfin.example.com', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' ); ``` ```typescript // Custom Axios instance with timeout import axios from 'axios'; const customAxios = axios.create({ timeout: 30000 }); const api = jellyfin.createApi( 'https://jellyfin.example.com', 'access-token', customAxios ); ```