### Install Dependencies Source: https://github.com/codelitdev/medialit/blob/main/README.md Installs the project dependencies using pnpm package manager. ```shell pnpm install ``` -------------------------------- ### Install Utilities (Ubuntu/Debian) Source: https://github.com/codelitdev/medialit/blob/main/README.md Installs essential utilities (ffmpeg, webp) required for media processing on Linux-based systems. These are used for media conversion and optimization tasks. ```shell sudo apt install ffmpeg webp ``` -------------------------------- ### Install MediaLit SDK using npm, yarn, or pnpm Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md This section shows how to install the MediaLit Node.js SDK using different package managers. It's a prerequisite for using the SDK in your project. ```bash npm install medialit # or yarn add medialit # or pnpm add medialit ``` -------------------------------- ### Run the Service Source: https://github.com/codelitdev/medialit/blob/main/README.md Starts the MediaLit API service in development mode using the pnpm dev command. ```shell pnpm --filter=@medialit/api dev ``` -------------------------------- ### Initialize MediaLit Client and Upload File Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md Demonstrates how to initialize the MediaLit client with API keys and endpoint, and then upload a file from a request object. This is a core example for handling media uploads in a server-side application. ```typescript import { MediaLit } from "medialit"; // Initialize the client (Keep API keys on server) const medialit = new MediaLit({ apiKey: process.env.MEDIALIT_API_KEY, endpoint: process.env.MEDIALIT_ENDPOINT, }); // Example usage app.post("/api/upload", async (req, res) => { try { const file = req.files.file; const media = await medialit.upload(file.path, { access: "public", caption: req.body.caption, group: req.body.group, }); res.json(media); } catch (error) { res.status(500).json({ error: error.message }); } }); ``` -------------------------------- ### Install MediaLit Thumbnail Package (npm) Source: https://github.com/codelitdev/medialit/blob/main/packages/thumbnail/README.md Installs the MediaLit thumbnail package using npm. This is the first step before integrating thumbnail generation into your Node.js application. ```bash npm install @medialit/thumbnail ``` -------------------------------- ### Install ffmpeg for Ubuntu Source: https://github.com/codelitdev/medialit/blob/main/packages/thumbnail/README.md Installs the ffmpeg utility, which is a required dependency for processing video files when generating thumbnails with the MediaLit package. This command is specific to Ubuntu systems. ```bash apt install ffmpeg ``` -------------------------------- ### Get Media Settings Source: https://context7.com/codelitdev/medialit/llms.txt This endpoint retrieves the current media processing configuration. Requires an API key for authentication. ```APIDOC ## POST /settings/media/get ### Description Retrieve current media processing configuration. ### Method POST ### Endpoint /settings/media/get ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ### Response #### Success Response (200) - **userId** (string) - User ID. - **apikey** (string) - API Key. - **useWebP** (boolean) - WebP conversion setting. - **webpOutputQuality** (integer) - WebP output quality. - **thumbnailWidth** (integer) - Thumbnail width. - **thumbnailHeight** (integer) - Thumbnail height. #### Response Example { "userId": "507f1f77bcf86cd799439011", "apikey": "your-api-key", "useWebP": true, "webpOutputQuality": 85, "thumbnailWidth": 640, "thumbnailHeight": 360 } #### Default Response Example { "useWebP": false, "webpOutputQuality": 75, "thumbnailWidth": 1280, "thumbnailHeight": 720 } ``` -------------------------------- ### Configure Environment Variables Source: https://context7.com/codelitdev/medialit/llms.txt Defines required and optional environment variables for MediaLit deployment. Includes database, storage, user setup, server, CDN, file size limit, storage quota, and signature validity configurations. Supports MongoDB and AWS S3 integration. ```bash # Database (Required) DB_CONNECTION_STRING=mongodb://localhost:27017/medialit # S3 Storage (Required) CLOUD_ENDPOINT=https://s3.amazonaws.com CLOUD_REGION=us-east-1 CLOUD_KEY=AKIAIOSFODNN7EXAMPLE CLOUD_SECRET=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY CLOUD_BUCKET_NAME=my-medialit-bucket S3_ENDPOINT=https://my-medialit-bucket.s3.amazonaws.com CLOUD_PREFIX=media # Optional: prefix for all S3 keys # File Storage (Required) TEMP_FILE_DIR_FOR_UPLOADS=/tmp/medialit-uploads # Initial User Setup (Required on first run) EMAIL=admin@example.com # Server Configuration (Optional) PORT=80 ENABLE_TRUST_PROXY=true HOSTNAME_OVERRIDE=https://media.mydomain.com # CloudFront CDN (Optional) USE_CLOUDFRONT=true CLOUDFRONT_ENDPOINT=https://d1234567890abc.cloudfront.net CLOUDFRONT_KEY_PAIR_ID=APKAEIBAERJR2EXAMPLE CLOUDFRONT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEA... -----END RSA PRIVATE KEY-----" CDN_MAX_AGE=3600000 # 1 hour in milliseconds # File Size Limits (Optional, in bytes) MAX_UPLOAD_SIZE_SUBSCRIBED=2147483648 # 2GB default MAX_UPLOAD_SIZE_NOT_SUBSCRIBED=52428800 # 50MB default # Storage Quotas (Optional, in bytes) MAX_STORAGE_ALLOWED_SUBSCRIBED=107374182400 # 100GB default MAX_STORAGE_ALLOWED_NOT_SUBSCRIBED=1073741824 # 1GB default # Signature Validity (Optional, in minutes) SIGNATURE_VALIDITY_MINUTES=1440 # 24 hours default ``` -------------------------------- ### Update MediaLit Settings Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md This code example demonstrates how to update various media settings, such as enabling WebP conversion, setting WebP quality, and defining thumbnail dimensions. It takes a MediaSettings object as input. ```typescript interface MediaSettings { useWebP?: boolean; webpOutputQuality?: number; // 0-100 thumbnailWidth?: number; thumbnailHeight?: number; } // ... later in your code await medialit.updateSettings({ useWebP: true, webpOutputQuality: 80, thumbnailWidth: 200, thumbnailHeight: 200, }); ``` -------------------------------- ### Get Media Details Source: https://context7.com/codelitdev/medialit/llms.txt Fetch detailed information about a specific media file using its unique media ID. ```APIDOC ## GET /media/{mediaId} ### Description Fetch complete information about a specific media file. ### Method GET ### Endpoint /media/{mediaId} ### Parameters #### Path Parameters - **mediaId** (string) - Required - The unique identifier of the media file. ### Request Example ```javascript const mediaInfo = await client.get('abc123xyz789def456ghi012jkl345mno678'); ``` ### Response #### Success Response (200) - **mediaId** (string) - The unique identifier for the media. - **originalFileName** (string) - The original name of the file. - **fileName** (string) - The stored name of the file. - **mimeType** (string) - The MIME type of the file. - **size** (integer) - The size of the file in bytes. - **accessControl** (string) - The access level ('public' or 'private'). - **caption** (string) - Optional - The caption of the media. - **group** (string) - Optional - The group of the media. - **thumbnailGenerated** (boolean) - Indicates if a thumbnail was generated. - **file** (string) - The URL to the media file. - **thumbnail** (string) - The URL to the media thumbnail (if generated). #### Response Example ```json { "mediaId": "abc123xyz789def456ghi012jkl345mno678", "originalFileName": "image.jpg", "fileName": "stored_image_name.jpg", "mimeType": "image/jpeg", "size": 204800, "accessControl": "private", "caption": "A sample image", "group": "uploads", "thumbnailGenerated": true, "file": "https://cdn.example.com/private/signed_url_for_1_hour", "thumbnail": "https://cdn.example.com/thumbnails/stored_image_name.jpg" } ``` #### Error Response (404) - **message** (string) - Description of the error, e.g., "Media file not found." #### Error Response Example ```json { "message": "Media file not found." } ``` ``` -------------------------------- ### GET /media/get Source: https://context7.com/codelitdev/medialit/llms.txt Retrieves a paginated list of media files stored in MediaLit. Supports filtering by access level and group. ```APIDOC ## GET /media/get ### Description Retrieve a paginated list of media files. You can filter the results by access level and group. Requires API key authentication. ### Method GET ### Endpoint /media/get ### Parameters #### Headers - **x-medialit-apikey** (string) - Required - Your MediaLit API key for authentication. #### Query Parameters - **page** (integer) - Optional - The page number for pagination. Defaults to 1. - **limit** (integer) - Optional - The number of items per page. Defaults to 20. - **access** (string) - Optional - Filter by access level (e.g., 'public', 'private'). - **group** (string) - Optional - Filter by group name. ### Request Example (List all media files) ```bash curl -X GET "https://api.medialit.cloud/media/get?page=1&limit=20" \ -H "x-medialit-apikey: your-api-key" ``` ### Request Example (Filter by access level) ```bash curl -X GET "https://api.medialit.cloud/media/get?page=1&limit=10&access=public" \ -H "x-medialit-apikey: your-api-key" ``` ### Request Example (Filter by group) ```bash curl -X GET "https://api.medialit.cloud/media/get?page=2&limit=15&group=vacation-2024" \ -H "x-medialit-apikey: your-api-key" ``` ### Response #### Success Response (200) - An array of media objects, each containing: - **mediaId** (string) - Unique identifier for the media file. - **fileName** (string) - The processed filename. - **originalFileName** (string) - The original name of the uploaded file. - **mimeType** (string) - The MIME type of the file. - **size** (integer) - The size of the file in bytes. - **accessControl** (string) - The access level ('public' or 'private'). - **group** (string) - The group the file belongs to. - **thumbnail** (string) - URL to the generated thumbnail. ### Response Example ```json [ { "mediaId": "abc123xyz789def456ghi012jkl345mno678", "fileName": "main.webp", "originalFileName": "sunset.jpg", "mimeType": "image/webp", "size": 312456, "accessControl": "public", "group": "vacation-2024", "thumbnail": "https://s3.amazonaws.com/bucket/public/abc123xyz789def456ghi012jkl345mno678/thumb.webp" }, { "mediaId": "xyz789abc123def456ghi012jkl345mno678", "fileName": "main.mp4", "originalFileName": "beach-video.mp4", "mimeType": "video/mp4", "size": 5242880, "accessControl": "private", "group": "vacation-2024", "thumbnail": "https://s3.amazonaws.com/bucket/public/xyz789abc123def456ghi012jkl345mno678/thumb.webp" } ] ``` ``` -------------------------------- ### Get media settings with cURL Source: https://context7.com/codelitdev/medialit/llms.txt Retrieve current media processing configuration through POST request with API key authentication. Returns user-specific settings including WebP conversion preferences and thumbnail dimensions. Shows default values when no custom configuration exists. ```bash curl -X POST https://api.medialit.cloud/settings/media/get \ -H "x-medialit-apikey: your-api-key" # Response { "userId": "507f1f77bcf86cd799439011", "apikey": "your-api-key", "useWebP": true, "webpOutputQuality": 85, "thumbnailWidth": 640, "thumbnailHeight": 360 } # Default settings if not configured: { "useWebP": false, "webpOutputQuality": 75, "thumbnailWidth": 1280, "thumbnailHeight": 720 } ``` -------------------------------- ### Get Storage Statistics Source: https://context7.com/codelitdev/medialit/llms.txt This endpoint checks the current storage usage and maximum allowed storage quota. Requires an API key for authentication. ```APIDOC ## POST /media/get/size ### Description Check current storage usage and maximum allowed storage quota. ### Method POST ### Endpoint /media/get/size ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ### Response #### Success Response (200) - Subscribed User - **storage** (integer) - Storage used in bytes. - **maxStorage** (integer) - Maximum storage allowed in bytes. #### Response Example - Subscribed User { "storage": 45678901234, "maxStorage": 107374182400 } #### Success Response (200) - Free Tier User - **storage** (integer) - Storage used in bytes. - **maxStorage** (integer) - Maximum storage allowed in bytes. #### Response Example - Free Tier User { "storage": 512000000, "maxStorage": 1073741824 } ``` -------------------------------- ### SDK Error Handling Example - TypeScript Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md Demonstrates how to handle errors that may occur during MediaLit SDK operations. It includes checks for environment issues, API key validation, and file input validation, providing specific error messages for each case. ```typescript try { const media = await medialit.upload(file); } catch (error) { if (error.message.includes("server-side Node.js environment")) { console.error("SDK cannot be used in browser environment"); } else if (error.message === "API Key is required") { console.error("Missing API key configuration"); } else { console.error("Operation failed:", error.message); } } ``` -------------------------------- ### GET /media/get/{mediaId} Source: https://context7.com/codelitdev/medialit/llms.txt Retrieves detailed information for a specific media file using its unique ID. For private files, it provides time-limited signed URLs. ```APIDOC ## GET /media/get/{mediaId} ### Description Retrieve detailed information about a specific media file using its unique media identifier. For private files, this endpoint will generate time-limited signed URLs for accessing the file and its thumbnail. ### Method GET ### Endpoint /media/get/{mediaId} ### Parameters #### Headers - **x-medialit-apikey** (string) - Required - Your MediaLit API key for authentication. #### Path Parameters - **mediaId** (string) - Required - The unique identifier of the media file to retrieve. ### Request Example ```bash curl -X GET https://api.medialit.cloud/media/get/abc123xyz789def456ghi012jkl345mno678 \ -H "x-medialit-apikey: your-api-key" ``` ### Response #### Success Response (200) - **mediaId** (string) - Unique identifier for the media file. - **fileName** (string) - The processed filename. - **originalFileName** (string) - The original name of the uploaded file. - **mimeType** (string) - The MIME type of the file. - **size** (integer) - The size of the file in bytes. - **accessControl** (string) - The access level ('public' or 'private'). - **caption** (string) - The caption provided for the file. - **group** (string) - The group the file belongs to. - **thumbnailGenerated** (boolean) - Indicates if a thumbnail was generated. - **file** (string) - URL to access the media file. For private files, this will be a signed URL. - **thumbnail** (string) - URL to access the thumbnail. For private files, this will be a signed URL. ### Response Example (Public File) ```json { "mediaId": "abc123xyz789def456ghi012jkl345mno678", "fileName": "main.webp", "originalFileName": "landscape.jpg", "mimeType": "image/webp", "size": 412890, "accessControl": "public", "caption": "Mountain landscape", "group": "nature", "thumbnailGenerated": true, "file": "https://s3.amazonaws.com/bucket/public/abc123xyz789def456ghi012jkl345mno678/main.webp", "thumbnail": "https://s3.amazonaws.com/bucket/public/abc123xyz789def456ghi012jkl345mno678/thumb.webp" } ``` ``` -------------------------------- ### Get MediaLit Storage Statistics Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md This snippet shows how to retrieve the current storage usage and the maximum allowed storage for your MediaLit account. It returns a promise that resolves to a MediaStats object. ```typescript interface MediaStats { storage: number; // Current storage used in bytes maxStorage: number; // Maximum allowed storage in bytes } // ... later in your code const stats: MediaStats = await medialit.getStats(); console.log(`Storage used: ${stats.storage} bytes, Max storage: ${stats.maxStorage} bytes`); ``` -------------------------------- ### Get storage statistics with cURL Source: https://context7.com/codelitdev/medialit/llms.txt Check current storage usage and maximum allowed storage quota through POST request. Requires API key authentication. Returns storage bytes used and maximum storage limit in bytes. Response varies based on subscription tier (free vs paid). ```bash curl -X POST https://api.medialit.cloud/media/get/size \ -H "x-medialit-apikey: your-api-key" # Response (subscribed user) { "storage": 45678901234, "maxStorage": 107374182400 } # Response shows: # - storage: 42.5 GB used (45678901234 bytes) # - maxStorage: 100 GB limit (107374182400 bytes) # Response (free tier user) { "storage": 512000000, "maxStorage": 1073741824 } # Response shows: # - storage: 488 MB used # - maxStorage: 1 GB limit ``` -------------------------------- ### Get Storage Statistics - JavaScript Source: https://context7.com/codelitdev/medialit/llms.txt Retrieves and displays comprehensive storage statistics including used space, maximum capacity, remaining quota, and file count. Converts raw bytes to human-readable GB format and provides threshold warnings when storage approaches capacity. Includes quota validation to prevent overages. ```javascript const { MediaLit } = require('medialit'); const client = new MediaLit(); async function checkStorageStats() { try { const stats = await client.getStats(); const usedGB = (stats.storage / (1024 ** 3)).toFixed(2); const maxGB = (stats.maxStorage / (1024 ** 3)).toFixed(2); const usedPercent = ((stats.storage / stats.maxStorage) * 100).toFixed(1); const remainingBytes = stats.maxStorage - stats.storage; const remainingGB = (remainingGB / (1024 ** 3)).toFixed(2); console.log('Storage Statistics:'); console.log(` Used: ${usedGB} GB of ${maxGB} GB (${usedPercent}%)`); console.log(` Remaining: ${remainingGB} GB`); console.log(` Raw bytes used: ${stats.storage}`); console.log(` Raw bytes max: ${stats.maxStorage}`); // Check if storage is almost full if (stats.storage / stats.maxStorage > 0.9) { console.warn('WARNING: Storage is over 90% full!'); } // Check if storage is full if (stats.storage >= stats.maxStorage) { console.error('ERROR: Storage quota exceeded!'); return false; } return true; } catch (error) { console.error('Failed to get storage stats:', error.message); throw error; } } // Get file count async function getFileCount() { try { const count = await client.getCount(); console.log(`Total files: ${count}`); return count; } catch (error) { console.error('Failed to get file count:', error.message); throw error; } } checkStorageStats(); getFileCount(); ``` -------------------------------- ### Next.js Server-Side API Routes for Media Operations (TypeScript) Source: https://context7.com/codelitdev/medialit/llms.txt Implements server-side API routes for media operations within a Next.js App Router application. It supports GET requests for listing media or fetching details, POST requests for generating upload signatures, and DELETE requests for removing media files. Requires MEDIALIT_API_KEY and MEDIALIT_ENDPOINT environment variables. ```typescript // app/api/medialit/route.ts import { NextRequest } from 'next/server'; import { MediaLit } from 'medialit'; const client = new MediaLit({ apiKey: process.env.MEDIALIT_API_KEY, endpoint: process.env.MEDIALIT_ENDPOINT || 'https://api.medialit.cloud' }); // GET - List media or get single media details export async function GET(request: NextRequest) { const searchParams = request.nextUrl.searchParams; const mediaId = searchParams.get('mediaId'); const page = parseInt(searchParams.get('page') ?? '1'); const limit = parseInt(searchParams.get('limit') ?? '10'); const access = searchParams.get('access') as 'public' | 'private' | undefined; const group = searchParams.get('group') ?? undefined; try { if (mediaId) { const media = await client.get(mediaId); return Response.json(media); } const media = await client.list(page, limit, { access, group }); return Response.json(media); } catch (error) { return Response.json( { error: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } } // POST - Generate presigned upload signature export async function POST() { try { const signature = await client.getSignature(); return Response.json({ endpoint: client.endpoint, signature: signature }); } catch (error) { return Response.json( { error: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } } // DELETE - Delete media file export async function DELETE(request: NextRequest) { const searchParams = request.nextUrl.searchParams; const mediaId = searchParams.get('mediaId'); if (!mediaId) { return Response.json( { error: 'Media ID is required' }, { status: 400 } ); } try { await client.delete(mediaId); return Response.json({ success: true }); } catch (error) { return Response.json( { error: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } } ``` -------------------------------- ### Build Packages Source: https://github.com/codelitdev/medialit/blob/main/README.md Builds the image and thumbnail packages using the pnpm build command. ```shell pnpm --filter=@medialit/images build ``` ```shell pnpm --filter=@medialit/thumbnail build ``` -------------------------------- ### Publishing a New Version Source: https://github.com/codelitdev/medialit/blob/main/README.md Runs changeset to manage versioning and release notes for the project. ```shell pnpm exec changeset ``` -------------------------------- ### Initialize MediaLit Client with Constructor Options Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md Demonstrates how to initialize the MediaLit client directly within the code using a configuration object passed to the constructor. This includes setting both API key and endpoint, or just the API key. ```typescript const medialit = new MediaLit({ apiKey: "your-api-key", endpoint: "https://your-medialit-instance.com", // Optional, defaults to https://api.medialit.cloud }); // Or simply with just the API key const medialit = new MediaLit({ apiKey: "your-api-key", }); ``` -------------------------------- ### Configure Media Settings - JavaScript Source: https://context7.com/codelitdev/medialit/llms.txt Configures media processing settings including WebP conversion quality, thumbnail dimensions, and preset management. Demonstrates current settings retrieval, dynamic updates, and predefined configuration presets for different use cases (high quality, balanced, optimized, original). ```javascript const { MediaLit } = require('medialit'); const client = new MediaLit(); async function configureMediaProcessing() { try { // Get current settings const currentSettings = await client.getSettings(); console.log('Current settings:', currentSettings); // Update settings for high-quality output await client.updateSettings({ useWebP: true, webpOutputQuality: 90, thumbnailWidth: 1920, thumbnailHeight: 1080 }); console.log('Updated to high-quality settings'); // Update settings for smaller file sizes await client.updateSettings({ useWebP: true, webpOutputQuality: 75, thumbnailWidth: 640, thumbnailHeight: 360 }); console.log('Updated to optimized file size settings'); // Disable WebP conversion await client.updateSettings({ useWebP: false }); console.log('WebP conversion disabled'); // Verify new settings const newSettings = await client.getSettings(); console.log('New settings:', newSettings); return newSettings; } catch (error) { console.error('Failed to configure settings:', error.message); throw error; } } configureMediaProcessing(); // Recommended settings by use case: const presets = { highQuality: { useWebP: true, webpOutputQuality: 90, thumbnailWidth: 1920, thumbnailHeight: 1080 }, balanced: { useWebP: true, webpOutputQuality: 85, thumbnailWidth: 1280, thumbnailHeight: 720 }, optimized: { useWebP: true, webpOutputQuality: 75, thumbnailWidth: 640, thumbnailHeight: 360 }, original: { useWebP: false, thumbnailWidth: 1280, thumbnailHeight: 720 } }; async function applyPreset(presetName) { const settings = presets[presetName]; if (!settings) { throw new Error(`Unknown preset: ${presetName}`); } await client.updateSettings(settings); console.log(`Applied ${presetName} preset`); } ``` -------------------------------- ### Node.js SDK - Initialize MediaLit Client Source: https://context7.com/codelitdev/medialit/llms.txt Demonstrates how to initialize the MediaLit client in a Node.js server environment. ```APIDOC ## Initialize MediaLit Client ### Description Create and configure the MediaLit client for server-side Node.js applications. ### Code Example ```javascript const { MediaLit } = require('medialit'); // Using environment variables (recommended) // Set MEDIALIT_API_KEY and MEDIALIT_ENDPOINT in your .env file const client = new MediaLit(); // Or provide configuration explicitly const client = new MediaLit({ apiKey: 'your-api-key', endpoint: 'https://api.medialit.cloud' }); // Error handling for missing API key try { const client = new MediaLit(); } catch (error) { console.error(error.message); // "API Key is required" } // Note: SDK only works in Node.js server environments // Browser usage will throw: "MediaLit SDK is only meant to be used in a server-side Node.js environment" ``` ``` -------------------------------- ### Get Media Count Source: https://context7.com/codelitdev/medialit/llms.txt This endpoint retrieves the total number of media files for the authenticated user. Requires an API key for authentication. ```APIDOC ## POST /media/get/count ### Description Retrieve the total number of media files for the authenticated user. ### Method POST ### Endpoint /media/get/count ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ### Response #### Success Response (200) - **count** (integer) - The total number of media files. #### Response Example { "count": 247 } ``` -------------------------------- ### Create User & API Key Source: https://github.com/codelitdev/medialit/blob/main/README.md Defines the email to use for creating a user, for access with an API key. The API key will be generated and printed in the application logs. ```shell EMAIL=email@yourdomain.com ``` -------------------------------- ### Update media settings with cURL Source: https://context7.com/codelitdev/medialit/llms.txt Configure media processing settings including WebP conversion and thumbnail dimensions via POST request. Requires JSON content type and API key headers. Accepts configuration parameters for WebP quality and thumbnail size. Returns success message on completion. ```bash curl -X POST https://api.medialit.cloud/settings/media/create \ -H "Content-Type: application/json" \ -H "x-medialit-apikey: your-api-key" \ -d '{ "useWebP": true, "webpOutputQuality": 85, "thumbnailWidth": 640, "thumbnailHeight": 360 }' # Response { "message": "SUCCESS" } # Settings explanation: # - useWebP: Enable automatic WebP conversion for images # - webpOutputQuality: 0-100, higher = better quality but larger file # - thumbnailWidth/Height: Dimensions for generated thumbnails (16:9 aspect ratio) ``` -------------------------------- ### Health check API with cURL Source: https://context7.com/codelitdev/medialit/llms.txt Verify API availability and uptime status through simple GET request. No authentication required. Returns status indicator and uptime in seconds. Used for monitoring service availability and performance. ```bash curl -X GET https://api.medialit.cloud/health # Response { "status": "ok", "uptime": 345678.92 } # uptime is in seconds ``` -------------------------------- ### Manage Docker Deployment Commands Source: https://context7.com/codelitdev/medialit/llms.txt Provides shell commands for deploying MediaLit with Docker Compose and retrieving initial API key. Includes log parsing to extract generated API key. Verifies service health through HTTP request. ```bash # Deploy with Docker Compose docker-compose up -d # View logs to get API key docker-compose logs medialit | grep "API key" # Output will show: # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # @ API key: your-generated-api-key @ # @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ # Check service health curl http://localhost/health ``` -------------------------------- ### Get a Presigned URL for Direct MediaLit Upload Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md This function retrieves a presigned URL from the MediaLit API, which can be used for direct uploads from client-side applications. This enhances security and offloads server resources. ```typescript const presignedUrl = await medialit.getPresignedUploadUrl({ group: "user-uploads" }); console.log("Upload this file to:", presignedUrl); ``` -------------------------------- ### Node.js SDK - Upload File from Path Source: https://context7.com/codelitdev/medialit/llms.txt Demonstrates how to upload a file from the filesystem using the Node.js SDK. ```APIDOC ## Upload File from Path ### Description Upload a file from the filesystem with automatic processing. ### Code Example ```javascript const { MediaLit } = require('medialit'); const client = new MediaLit(); async function uploadFromPath() { try { const media = await client.upload('/path/to/image.jpg', { access: 'public', caption: 'Product photo for catalog', group: 'products' }); console.log('Upload successful!'); console.log('Media ID:', media.mediaId); console.log('File URL:', media.file); console.log('Thumbnail:', media.thumbnail); console.log('Size:', media.size, 'bytes'); console.log('Type:', media.mimeType); return media; } catch (error) { console.error('Upload failed:', error.message); throw error; } } uploadFromPath(); // Expected output: // Upload successful! // Media ID: abc123xyz789def456ghi012jkl345mno678 // File URL: https://s3.amazonaws.com/bucket/public/abc123xyz789def456ghi012jkl345mno678/main.webp // Thumbnail: https://s3.amazonaws.com/bucket/public/abc123xyz789def456ghi012jkl345mno678/thumb.webp // Size: 245678 bytes // Type: image/webp ``` ``` -------------------------------- ### Cloudfront Environment Variables Source: https://github.com/codelitdev/medialit/blob/main/README.md Specifies environment variables required for Cloudfront integration, including enabling Cloudfront, specifying the distribution name and providing private and public keys. Ensure that your bucket is locked down from public access. ```shell USE_CLOUDFRONT=true ``` ```shell CLOUDFRONT_ENDPOINT=CLOUDFRONT_DISTRIBUTION_NAME ``` ```shell CLOUDFRONT_PRIVATE_KEY="PRIVATE_KEY" ``` ```shell CLOUDFRONT_KEY_PAIR_ID=KEY_PAIR_ID ``` -------------------------------- ### Configure MediaLit SDK using Environment Variables Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md Shows how to configure the MediaLit SDK by setting environment variables for the API key and optionally the API endpoint. This is a common practice for managing sensitive credentials. ```bash MEDIALIT_API_KEY=your-api-key MEDIALIT_ENDPOINT=https://your-medialit-instance.com # Optional, defaults to https://api.medialit.cloud ``` -------------------------------- ### Update Media Settings Source: https://context7.com/codelitdev/medialit/llms.txt This endpoint configures media processing settings including WebP conversion and thumbnail dimensions. Requires an API key for authentication and a JSON payload. ```APIDOC ## POST /settings/media/create ### Description Configure media processing settings including WebP conversion and thumbnail dimensions. ### Method POST ### Endpoint /settings/media/create ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **useWebP** (boolean) - Optional - Enable automatic WebP conversion. - **webpOutputQuality** (integer) - Optional - WebP output quality (0-100). - **thumbnailWidth** (integer) - Optional - Thumbnail width. - **thumbnailHeight** (integer) - Optional - Thumbnail height. ### Request Example { "useWebP": true, "webpOutputQuality": 85, "thumbnailWidth": 640, "thumbnailHeight": 360 } ### Response #### Success Response (200) - **message** (string) - "SUCCESS" #### Response Example { "message": "SUCCESS" } ``` -------------------------------- ### Initialize MediaLit client in Node.js Source: https://context7.com/codelitdev/medialit/llms.txt Create and configure the MediaLit client for server-side Node.js applications. Supports environment variable configuration or explicit parameters. Includes error handling for missing API keys and environment validation. SDK restricted to server-side Node.js environments only. ```javascript const { MediaLit } = require('medialit'); // Using environment variables (recommended) // Set MEDIALIT_API_KEY and MEDIALIT_ENDPOINT in your .env file const client = new MediaLit(); // Or provide configuration explicitly const client = new MediaLit({ apiKey: 'your-api-key', endpoint: 'https://api.medialit.cloud' }); // Error handling for missing API key try { const client = new MediaLit(); } catch (error) { console.error(error.message); // "API Key is required" } // Note: SDK only works in Node.js server environments // Browser usage will throw: "MediaLit SDK is only meant to be used in a server-side Node.js environment" ``` -------------------------------- ### Get media count with cURL Source: https://context7.com/codelitdev/medialit/llms.txt Retrieve the total number of media files for the authenticated user via POST request. Requires API key authentication header. Returns JSON object with count property representing total media files. No additional parameters required. ```bash curl -X POST https://api.medialit.cloud/media/get/count \ -H "x-medialit-apikey: your-api-key" # Response { "count": 247 } ``` -------------------------------- ### Deploy with Docker Compose Source: https://context7.com/codelitdev/medialit/llms.txt Deploys MediaLit application stack using Docker Compose with MongoDB backend. Defines medialit and mongo services with necessary environment variables and volume mappings. Includes MongoDB data persistence and upload directory mounting. ```yaml # docker-compose.yml version: '3.8' services: medialit: image: ghcr.io/codelitdev/medialit:latest ports: - "80:80" environment: - DB_CONNECTION_STRING=mongodb://mongo:27017/medialit - CLOUD_ENDPOINT=https://s3.amazonaws.com - CLOUD_REGION=us-east-1 - CLOUD_KEY=${AWS_ACCESS_KEY_ID} - CLOUD_SECRET=${AWS_SECRET_ACCESS_KEY} - CLOUD_BUCKET_NAME=${S3_BUCKET_NAME} - S3_ENDPOINT=https://${S3_BUCKET_NAME}.s3.amazonaws.com - TEMP_FILE_DIR_FOR_UPLOADS=/tmp/uploads - EMAIL=admin@example.com - ENABLE_TRUST_PROXY=true volumes: - uploads:/tmp/uploads depends_on: - mongo mongo: image: mongo:7 volumes: - mongodb_data:/data/db ports: - "27017:27017" volumes: mongodb_data: uploads: ``` -------------------------------- ### Generate Presigned Upload Signature (JavaScript) Source: https://context7.com/codelitdev/medialit/llms.txt Generates temporary upload signatures for client-side uploads using the MediaLit SDK. It shows how to generate a signature without a group and with a specified group, returning the endpoint and signature for client use. Includes error handling and an example of integrating into an API endpoint. ```javascript const { MediaLit } = require('medialit'); const client = new MediaLit(); async function createUploadSignature() { try { // Generate signature without group const signature = await client.getSignature(); console.log('Signature (valid for 24 hours):', signature); // Generate signature with group const groupSignature = await client.getSignature({ group: 'user-uploads' }); console.log('Group signature:', groupSignature); // Return both endpoint and signature for client return { endpoint: client.endpoint, signature: signature }; } catch (error) { console.error('Failed to generate signature:', error.message); throw error; } } // Use in API endpoint for client-side uploads async function handleSignatureRequest(req, res) { try { const { group } = req.body; const signature = await client.getSignature({ group }); res.json({ endpoint: client.endpoint, signature: signature, expiresIn: 86400 // 24 hours in seconds }); } catch (error) { res.status(500).json({ error: error.message }); } } createUploadSignature(); ``` -------------------------------- ### Get Media Details by ID using MediaLit SDK Source: https://context7.com/codelitdev/medialit/llms.txt Explains how to fetch detailed information for a specific media file using its unique ID. It displays various properties including file name, size, access control, and URLs for the file and thumbnail. The function returns the media details object. ```javascript const { MediaLit } = require('medialit'); const client = new MediaLit(); async function getMediaInfo(mediaId) { try { const media = await client.get(mediaId); console.log('Media Details:'); console.log(' ID:', media.mediaId); console.log(' Original Name:', media.originalFileName); console.log(' Stored Name:', media.fileName); console.log(' Type:', media.mimeType); console.log(' Size:', Math.round(media.size / 1024), 'KB'); console.log(' Access:', media.accessControl); console.log(' Caption:', media.caption || 'No caption'); console.log(' Group:', media.group || 'No group'); console.log(' Thumbnail Generated:', media.thumbnailGenerated); console.log(' File URL:', media.file); console.log(' Thumbnail URL:', media.thumbnail); // For private files, the URL will be a signed URL valid for 1 hour if (media.accessControl === 'private') { console.log('Note: URL is a signed URL valid for 1 hour'); } return media; } catch (error) { if (error.message.includes('not found')) { console.error('Media file does not exist'); } else { console.error('Failed to get media details:', error.message); } throw error; } } getMediaInfo('abc123xyz789def456ghi012jkl345mno678'); ``` -------------------------------- ### POST /media/create Source: https://context7.com/codelitdev/medialit/llms.txt Upload a media file to MediaLit. The service automatically processes the file, including WebP conversion and thumbnail generation. Supports authentication via API key or a presigned signature. ```APIDOC ## POST /media/create ### Description Upload a media file with automatic processing including WebP conversion and thumbnail generation. Authentication can be done using an API key or a generated presigned signature. ### Method POST ### Endpoint /media/create ### Parameters #### Headers - **x-medialit-apikey** (string) - Required - Your MediaLit API key for authentication. - **x-medialit-signature** (string) - Required - A generated presigned signature token for temporary authentication. #### Request Body (Form Data) - **file** (file) - Required - The media file to upload. - **access** (string) - Optional - The access control for the file ('public' or 'private'). Defaults to 'public'. - **caption** (string) - Optional - A caption or description for the media file. - **group** (string) - Optional - A group identifier to categorize the media file. ### Request Example (API Key Authentication) ```bash curl -X POST https://api.medialit.cloud/media/create \ -H "x-medialit-apikey: your-api-key" \ -F "file=@/path/to/image.jpg" \ -F "access=public" \ -F "caption=My vacation photo" \ -F "group=vacation-2024" ``` ### Request Example (Presigned Signature Authentication) ```bash curl -X POST https://api.medialit.cloud/media/create \ -H "x-medialit-signature: generated-signature-token" \ -F "file=@/path/to/video.mp4" \ -F "access=private" \ -F "caption=Conference recording" ``` ### Response #### Success Response (200) - **mediaId** (string) - Unique identifier for the uploaded media. - **fileName** (string) - The processed filename (e.g., converted to WebP). - **originalFileName** (string) - The original name of the uploaded file. - **mimeType** (string) - The MIME type of the processed file. - **size** (integer) - The size of the processed file in bytes. - **accessControl** (string) - The access level ('public' or 'private'). - **caption** (string) - The caption provided for the file. - **group** (string) - The group assigned to the file. - **thumbnailGenerated** (boolean) - Indicates if a thumbnail was successfully generated. - **file** (string) - URL to access the uploaded media file. - **thumbnail** (string) - URL to access the generated thumbnail. ### Response Example ```json { "mediaId": "abc123xyz789def456ghi012jkl345mno678", "fileName": "main.webp", "originalFileName": "image.jpg", "mimeType": "image/webp", "size": 245678, "accessControl": "public", "caption": "My vacation photo", "group": "vacation-2024", "thumbnailGenerated": true, "file": "https://s3.amazonaws.com/bucket/public/abc123xyz789def456ghi012jkl345mno678/main.webp", "thumbnail": "https://s3.amazonaws.com/bucket/public/abc123xyz789def456ghi012jkl345mno678/thumb.webp" } ``` ``` -------------------------------- ### MediaLit Upload with Different File Input Types Source: https://github.com/codelitdev/medialit/blob/main/packages/medialit/README.md Illustrates the flexibility of the MediaLit SDK's `upload` method by showcasing how to upload files using a file path, a Buffer, or a Readable stream. ```typescript await medialit.upload("/path/to/file.jpg"); ``` ```typescript const buffer = Buffer.from("file content"); await medialit.upload(buffer); ``` ```typescript const stream = createReadStream("file.jpg"); await medialit.upload(stream); ``` -------------------------------- ### List and Filter Media with MediaLit SDK Source: https://context7.com/codelitdev/medialit/llms.txt Shows how to retrieve a list of media files with options for pagination and filtering by access level or group. It demonstrates fetching different pages and applying multiple filter criteria. The function returns the first page of media results. ```javascript const { MediaLit } = require('medialit'); const client = new MediaLit(); async function listAllMedia() { try { // Get first page (10 items per page by default) const page1 = await client.list(1, 10); console.log(`Retrieved ${page1.length} media files`); // Get second page with 20 items const page2 = await client.list(2, 20); // Filter by access level const publicFiles = await client.list(1, 50, { access: 'public' }); console.log(`Public files: ${publicFiles.length}`); const privateFiles = await client.list(1, 50, { access: 'private' }); console.log(`Private files: ${privateFiles.length}`); // Filter by group const productPhotos = await client.list(1, 100, { group: 'products' }); console.log(`Product photos: ${productPhotos.length}`); // Combine filters const publicProducts = await client.list(1, 100, { access: 'public', group: 'products' }); // Process results page1.forEach(media => { console.log(`${media.originalFileName} - ${media.mimeType} - ${media.size} bytes`); console.log(` Thumbnail: ${media.thumbnail}`); }); return page1; } catch (error) { console.error('Failed to list media:', error.message); throw error; } } listAllMedia(); ```