# All files / src/components/admin TaskControl.tsx

0% Statements 0/73
0% Branches 0/45
0% Functions 0/15
0% Lines 0/70

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255

     'use client';

    import React, { useEffect, useState } from 'react';
    import { mediaScannerService, ScanTask } from '@/services/mediaScanner';
    import { Button } from '@/components/ui/button';
    import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
    import { Badge } from '@/components/ui/badge';
    import { Trash2, Clock, CheckCircle, XCircle, AlertCircle } from 'lucide-react';
    import { useTranslation } from 'react-i18next';
    import useLoadNamespace from '@/hooks/useLoadNamespace';

    interface TaskControlProps {
      onTaskUpdate?: () => void;
    }

    export default function TaskControl({ onTaskUpdate }: TaskControlProps) {
      useLoadNamespace('admin/mediaScanner');
      const { t } = useTranslation(['admin/mediaScanner', 'admin', 'translation']);

      const [tasks, setTasks] = useState<ScanTask[]>([]);
      const [loading, setLoading] = useState(true);
      const [cancelling, setCancelling] = useState<string | null>(null);
      const [deleting, setDeleting] = useState<string | null>(null);

      const fetchTasks = async () => {
        try {
          const response = await mediaScannerService.getScanTasks();
          if (response.success && Array.isArray(response.data)) {
            setTasks(response.data);
          } else {
            console.error('Invalid response format:', response);
            setTasks([]); // Ensure tasks is always an array
          }
        } catch (error) {
          console.error('Error fetching tasks:', error);
          setTasks([]); // Ensure tasks is always an array on error
        } finally {
          setLoading(false);
        }
      };

      const handleCancelTask = async (taskId: string) => {
        setCancelling(taskId);
        try {
          const response = await mediaScannerService.cancelScanTask(taskId);
          if (response.success) {
            await fetchTasks();
            onTaskUpdate?.();
          }
        } catch (error) {
          console.error('Error cancelling task:', error);
        } finally {
          setCancelling(null);
        }
      };

      const handleDeleteTask = async (taskId: string) => {
        if (!confirm(t('mediaScanner.scanProgress.cancelConfirm'))) {
          return;
        }

        setDeleting(taskId);
        try {
          const response = await mediaScannerService.deleteTask(taskId);
          if (response.success) {
            // Remove task from local state immediately for better UX
            setTasks(prev => prev.filter(task => task.id !== taskId));
            onTaskUpdate?.();
          }
        } catch (error) {
          console.error('Error deleting task:', error);
        } finally {
          setDeleting(null);
        }
      };

      const formatDuration = (startTime: number, endTime?: number) => {
        const end = endTime || Math.floor(Date.now() / 1000);
        const duration = end - startTime;
        const hours = Math.floor(duration / 3600);
        const minutes = Math.floor((duration % 3600) / 60);
        const seconds = duration % 60;

        if (hours > 0) {
          return `${hours}h ${minutes}m ${seconds}s`;
        } else if (minutes > 0) {
          return `${minutes}m ${seconds}s`;
        } else {
          return `${seconds}s`;
        }
      };

      const formatTime = (timestamp: number) => {
        return new Date(timestamp * 1000).toLocaleString();
      };

      const getStatusIcon = (status: string) => {
        switch (status) {
          case 'running':
            return <Clock className="h-4 w-4 text-blue-500" />;
          case 'completed':
            return <CheckCircle className="h-4 w-4 text-green-500" />;
          case 'failed':
            return <XCircle className="h-4 w-4 text-red-500" />;
          case 'cancelled':
            return <AlertCircle className="h-4 w-4 text-yellow-500" />;
          default:
            return <Clock className="h-4 w-4 text-gray-500" />;
        }
      };

      const getStatusBadge = (status: string) => {
        const variants = {
          running: 'bg-blue-100 text-blue-800',
          completed: 'bg-green-100 text-green-800',
          failed: 'bg-red-100 text-red-800',
          cancelled: 'bg-yellow-100 text-yellow-800'
        };

        return (
          <Badge className={variants[status as keyof typeof variants] || 'bg-gray-100 text-gray-800'}>
            {getStatusIcon(status)}
            <span className="ml-1 capitalize">{status}</span>
          </Badge>
        );
      };

      useEffect(() => {
        fetchTasks();

        // Poll for updates every 5 seconds
        const interval = setInterval(fetchTasks, 5000);
        return () => clearInterval(interval);
      }, []);

      if (loading) {
        return (
          <Card>
            <CardHeader>
              <CardTitle>{t('mediaScanner.taskControl.title')}</CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-center py-4">{t('mediaScanner.folderExplorer.loading')}</div>
            </CardContent>
          </Card>
        );
      }

      return (
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between">
              {t('mediaScanner.taskControl.title')}
              <Badge variant="outline">{tasks?.length || 0} {t('mediaScanner.taskControl.tasks')}</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            {!tasks || tasks.length === 0 ? (
              <div className="text-center py-8 text-gray-500">
                {t('mediaScanner.taskControl.idle')}
              </div>
            ) : (
              tasks.map((task) => (
                <div key={task.id} className="border rounded-lg p-4 space-y-3">
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      {getStatusBadge(task.status)}
                      <span className="font-medium capitalize">{task.category}</span>
                    </div>
                    <div className="flex gap-2">
                      {task.status === 'running' && (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleCancelTask(task.id)}
                          disabled={cancelling === task.id}
                          className="text-red-600 hover:text-red-700"
                        >
                          <Trash2 className="h-4 w-4 mr-1" />
                          {cancelling === task.id ? t('mediaScanner.taskControl.cancelling') : t('mediaScanner.taskControl.cancel')}
                        </Button>
                      )}
                      {(task.status === 'cancelled' || task.status === 'completed' || task.status === 'failed') && (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDeleteTask(task.id)}
                          disabled={deleting === task.id}
                          className="text-gray-600 hover:text-gray-700"
                        >
                          <Trash2 className="h-4 w-4 mr-1" />
                          {deleting === task.id ? t('mediaScanner.taskControl.deleting') : t('mediaScanner.taskControl.delete')}
                        </Button>
                      )}
                    </div>
                  </div>

                  <div className="text-sm text-gray-600">
                    <div><strong>{t('mediaScanner.taskControl.path')}:</strong> {task.path}</div>
                    <div><strong>{t('mediaScanner.taskControl.started')}:</strong> {formatTime(task.start_time)}</div>
                    <div><strong>{t('mediaScanner.taskControl.duration')}:</strong> {formatDuration(task.start_time, task.end_time)}</div>
                    {task.current_file && (
                      <div><strong>{t('mediaScanner.taskControl.currentFile')}:</strong> {task.current_file}</div>
                    )}
                  </div>

                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      {/* Show movies counter for movie-like categories, or series counter for series-like */}
                      {['movies', 'kids'].includes(task.category?.toLowerCase() || '') ? (
                        <div className="text-green-600">✓ {t('mediaScanner.taskControl.stats.movies')}: {task.movies_created}</div>
                      ) : (
                        <>
                          {task.movies_created > 0 && (
                            <div className="text-green-600">✓ {t('mediaScanner.taskControl.stats.movies')}: {task.movies_created}</div>
                          )}
                        </>
                      )}
                      {/* Show series/anime counter based on category type */}
                      {['anime', 'series'].includes(task.category?.toLowerCase() || '') ? (
                        <>
                          <div className="text-blue-600">✓ {task.category}: {task.series_created}</div>
                          <div className="text-purple-600">✓ {t('mediaScanner.taskControl.stats.episodes')}: {task.episodes_created}</div>
                        </>
                      ) : (
                        <>
                          {task.series_created > 0 && (
                            <div className="text-blue-600">✓ {t('mediaScanner.taskControl.stats.series')}: {task.series_created}</div>
                          )}
                          {task.episodes_created > 0 && (
                            <div className="text-purple-600">✓ {t('mediaScanner.taskControl.stats.episodes')}: {task.episodes_created}</div>
                          )}
                        </>
                      )}
                    </div>
                    <div>
                      <div className="text-orange-600">✓ {t('mediaScanner.taskControl.stats.subtitles')}: {task.subtitles_added}</div>
                      <div className="text-gray-600">⊘ {t('mediaScanner.taskControl.stats.skipped')}: {task.skipped}</div>
                      <div className="text-yellow-600">↻ {t('mediaScanner.taskControl.stats.replaced')}: {task.replaced}</div>
                    </div>
                  </div>

                  {task.error_message && (
                    <div className="bg-red-50 border border-red-200 rounded p-2 text-sm text-red-700">
                      <strong>{t('mediaScanner.taskControl.error')}:</strong> {task.error_message}
                    </div>
                  )}
                </div>
              ))
            )}
          </CardContent>
        </Card>
      );
    }