# Notification System

## Overview

The Media Downloader uses a custom in-app notification system to provide real-time feedback for downloads, errors, and system events. This replaced the browser-based Notification API in v6.3.5 for better reliability and cross-platform compatibility.

## Architecture

### Frontend Components

#### NotificationToast Component
**Location**: `/opt/media-downloader/web/frontend/src/components/NotificationToast.tsx`

- Renders notification toasts that slide in from the right side of the screen
- Auto-dismisses after 5 seconds
- Manual close button available
- Color-coded by notification type (success, error, warning, info)
- Smooth CSS animations with opacity and transform transitions

#### Notification Manager
**Location**: `/opt/media-downloader/web/frontend/src/lib/notificationManager.ts`

- Manages notification state using observer pattern
- Maintains a queue of active notifications
- Provides convenience methods for common notification types
- Platform-specific icons and formatting

### Integration

The notification system is integrated in `App.tsx`:

```typescript
const [notifications, setNotifications] = useState<ToastNotification[]>([])

useEffect(() => {
  const unsubscribe = notificationManager.subscribe((newNotifications) => {
    setNotifications(newNotifications)
  })
  return unsubscribe
}, [])
```

WebSocket events automatically trigger notifications:

```typescript
wsClient.on('download_completed', (data) => {
  notificationManager.downloadCompleted(
    data.platform,
    data.filename,
    data.username
  )
})
```

## Notification Types

### Success Notifications
- **Icon**: ✅
- **Color**: Green
- **Usage**: Download completions, successful operations

### Error Notifications
- **Icon**: ❌
- **Color**: Red
- **Usage**: Download errors, failed operations

### Info Notifications
- **Icon**: 📋
- **Color**: Blue
- **Usage**: Download started, scheduler updates

### Warning Notifications
- **Icon**: ⚠️
- **Color**: Yellow
- **Usage**: Important alerts, non-critical issues

## Platform-Specific Notifications

The notification manager includes platform-specific icons:

- **Instagram** (fastdl, imginn, toolzu): 📸
- **TikTok**: 🎵
- **Snapchat**: 👻
- **Forums**: 💬
- **Default**: 📥

## Usage Examples

### Basic Notifications

```typescript
// Success
notificationManager.success('Operation Complete', 'File saved successfully')

// Error
notificationManager.error('Operation Failed', 'Unable to save file')

// Info
notificationManager.info('Processing', 'File is being processed...')

// Warning
notificationManager.warning('Low Space', 'Disk space is running low')
```

### Platform-Specific Notifications

```typescript
// Download started
notificationManager.downloadStarted('instagram', 'username')

// Download completed
notificationManager.downloadCompleted('instagram', 'photo.jpg', 'username')

// Download error
notificationManager.downloadError('instagram', 'Rate limit exceeded')
```

### Custom Notifications

```typescript
notificationManager.show(
  'Custom Title',
  'Custom message',
  '🎉',  // Custom icon
  'success'  // Type
)
```

## Backend Integration

### Pushover Notifications

The backend includes Pushover push notification support for mobile devices:

**Location**: `/opt/media-downloader/modules/pushover_notifier.py`

- Sends push notifications to Pushover app
- Records all notifications to database
- Supports priority levels (-2 to 2)
- Configurable per-event notification settings

### Notification History

All Pushover notifications are stored in the `notifications` table:

```sql
CREATE TABLE notifications (
  id INTEGER PRIMARY KEY,
  platform TEXT,
  source TEXT,
  content_type TEXT,
  message TEXT,
  title TEXT,
  priority INTEGER,
  download_count INTEGER,
  sent_at TIMESTAMP,
  status TEXT,
  response_data TEXT,
  metadata TEXT
)
```

View notification history in the UI: **Configuration → Notifications**

## Migration from Browser Notifications (v6.3.5)

### What Changed

1. **Removed**: Browser Notification API (incompatible with HTTP access)
2. **Removed**: Notification toggle button from menus
3. **Removed**: `/opt/media-downloader/web/frontend/src/lib/notifications.ts`
4. **Added**: Custom in-app notification system
5. **Added**: `NotificationToast.tsx` component
6. **Added**: `notificationManager.ts` state manager

### Benefits

- **No Browser Permissions**: Works immediately without user consent dialogs
- **HTTP Compatible**: Works on non-HTTPS connections
- **Consistent UX**: Same appearance across all browsers
- **Always Available**: No browser settings can disable notifications
- **Better Control**: Custom styling, animations, and positioning

### Breaking Changes

None - Notifications now work automatically for all users without configuration.

## CSS Animations

**Location**: `/opt/media-downloader/web/frontend/src/index.css`

```css
@keyframes slideInFromRight {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
```

Notifications use:
- Slide-in animation on appearance (300ms)
- Fade-out and slide-out on dismissal (300ms)
- Automatic stacking for multiple notifications

## Configuration

### Auto-Dismiss Timing

Default: 5 seconds

Modify in `NotificationToast.tsx`:

```typescript
const timer = setTimeout(() => {
  setIsExiting(true)
  setTimeout(() => onDismiss(notification.id), 300)
}, 5000)  // Change this value
```

### Position

Default: Top-right corner (20px from top, 16px from right)

Modify in `NotificationToast.tsx`:

```tsx
<div className="fixed top-20 right-4 z-50 space-y-2 pointer-events-none">
```

### Max Width

Default: 320px minimum, 28rem (448px) maximum

Modify in `NotificationToast.tsx`:

```tsx
<div className="min-w-[320px] max-w-md">
```

## Troubleshooting

### Notifications Not Appearing

1. Check browser console for errors
2. Verify WebSocket connection is active
3. Ensure `NotificationToast` component is rendered in `App.tsx`
4. Check that events are being emitted from backend

### Notifications Stack Up

- Old notifications should auto-dismiss after 5 seconds
- User can manually close with X button
- Check for memory leaks if notifications accumulate indefinitely

### Styling Issues

- Verify Tailwind CSS is properly compiled
- Check `index.css` includes the `slideInFromRight` animation
- Ensure dark mode classes are applied correctly

## Future Enhancements

Potential improvements for future versions:

1. **Notification Persistence**: Save dismissed notifications to localStorage
2. **Notification Center**: Add a panel to view recent notifications
3. **Custom Sounds**: Add audio alerts for certain event types
4. **Notification Grouping**: Collapse multiple similar notifications
5. **Action Buttons**: Add quick actions to notifications (e.g., "View File")
6. **Desktop Notifications**: Optionally enable browser notifications for users on HTTPS
7. **Notification Preferences**: Let users configure which events trigger notifications

## Version History

- **v6.3.5** (2025-10-31): Custom in-app notification system implemented
- **v6.3.4** (2025-10-31): Browser notification system (deprecated)
- **v6.3.0** (2025-10-30): Initial notification support with WebSocket events
