summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/components/modals/SubtitleToolModal.tsx
blob: f8891ecff40e7bee6909c32c23a9e2352686deb9 (plain)
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import {
  faClock,
  faCode,
  faDeaf,
  faExchangeAlt,
  faFilm,
  faImage,
  faLanguage,
  faMagic,
  faMinus,
  faPaintBrush,
  faPlay,
  faPlus,
  faTextHeight,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { dispatchTask } from "@modules/task";
import { createTask } from "@modules/task/utilities";
import { useSubtitleAction } from "apis/hooks";
import React, {
  FunctionComponent,
  useCallback,
  useMemo,
  useState,
} from "react";
import {
  Badge,
  Button,
  ButtonGroup,
  Dropdown,
  Form,
  InputGroup,
} from "react-bootstrap";
import { Column, useRowSelect } from "react-table";
import { isMovie, submodProcessColor } from "utilities";
import { useEnabledLanguages } from "utilities/languages";
import { log } from "utilities/logger";
import {
  ActionButton,
  ActionButtonItem,
  LanguageSelector,
  LanguageText,
  Selector,
  SimpleTable,
  useModalPayload,
  useShowModal,
} from "..";
import { useCustomSelection } from "../tables/plugins";
import BaseModal, { BaseModalProps } from "./BaseModal";
import { useCloseModal } from "./hooks";
import { availableTranslation, colorOptions } from "./toolOptions";

type SupportType = Item.Episode | Item.Movie;

type TableColumnType = FormType.ModifySubtitle & {
  _language: Language.Info;
};

function getIdAndType(item: SupportType): [number, "episode" | "movie"] {
  if (isMovie(item)) {
    return [item.radarrId, "movie"];
  } else {
    return [item.sonarrEpisodeId, "episode"];
  }
}

function submodProcessFrameRate(from: number, to: number) {
  return `change_FPS(from=${from},to=${to})`;
}

function submodProcessOffset(h: number, m: number, s: number, ms: number) {
  return `shift_offset(h=${h},m=${m},s=${s},ms=${ms})`;
}

interface ToolModalProps {
  process: (
    action: string,
    override?: Partial<FormType.ModifySubtitle>
  ) => void;
}

const AddColorModal: FunctionComponent<BaseModalProps & ToolModalProps> = (
  props
) => {
  const { process, ...modal } = props;
  const [selection, setSelection] = useState<Nullable<string>>(null);

  const submit = useCallback(() => {
    if (selection) {
      const action = submodProcessColor(selection);
      process(action);
    }
  }, [selection, process]);

  const footer = useMemo(
    () => (
      <Button disabled={selection === null} onClick={submit}>
        Save
      </Button>
    ),
    [selection, submit]
  );
  return (
    <BaseModal title="Choose Color" footer={footer} {...modal}>
      <Selector options={colorOptions} onChange={setSelection}></Selector>
    </BaseModal>
  );
};

const FrameRateModal: FunctionComponent<BaseModalProps & ToolModalProps> = (
  props
) => {
  const { process, ...modal } = props;

  const [from, setFrom] = useState<Nullable<number>>(null);
  const [to, setTo] = useState<Nullable<number>>(null);

  const canSave = from !== null && to !== null && from !== to;

  const submit = useCallback(() => {
    if (canSave) {
      const action = submodProcessFrameRate(from!, to!);
      process(action);
    }
  }, [canSave, from, to, process]);

  const footer = useMemo(
    () => (
      <Button disabled={!canSave} onClick={submit}>
        Save
      </Button>
    ),
    [submit, canSave]
  );

  return (
    <BaseModal title="Change Frame Rate" footer={footer} {...modal}>
      <InputGroup className="px-2">
        <Form.Control
          placeholder="From"
          type="number"
          onChange={(e) => {
            const value = parseFloat(e.currentTarget.value);
            if (isNaN(value)) {
              setFrom(null);
            } else {
              setFrom(value);
            }
          }}
        ></Form.Control>
        <Form.Control
          placeholder="To"
          type="number"
          onChange={(e) => {
            const value = parseFloat(e.currentTarget.value);
            if (isNaN(value)) {
              setTo(null);
            } else {
              setTo(value);
            }
          }}
        ></Form.Control>
      </InputGroup>
    </BaseModal>
  );
};

const AdjustTimesModal: FunctionComponent<BaseModalProps & ToolModalProps> = (
  props
) => {
  const { process, ...modal } = props;

  const [isPlus, setPlus] = useState(true);
  const [offset, setOffset] = useState<[number, number, number, number]>([
    0, 0, 0, 0,
  ]);

  const updateOffset = useCallback(
    (idx: number) => {
      return (e: any) => {
        let value = parseFloat(e.currentTarget.value);
        if (isNaN(value)) {
          value = 0;
        }
        const newOffset = [...offset] as [number, number, number, number];
        newOffset[idx] = value;
        setOffset(newOffset);
      };
    },
    [offset]
  );

  const canSave = offset.some((v) => v !== 0);

  const submit = useCallback(() => {
    if (canSave) {
      const newOffset = offset.map((v) => (isPlus ? v : -v));
      const action = submodProcessOffset(
        newOffset[0],
        newOffset[1],
        newOffset[2],
        newOffset[3]
      );
      process(action);
    }
  }, [process, canSave, offset, isPlus]);

  const footer = useMemo(
    () => (
      <Button disabled={!canSave} onClick={submit}>
        Save
      </Button>
    ),
    [submit, canSave]
  );

  return (
    <BaseModal title="Adjust Times" footer={footer} {...modal}>
      <InputGroup>
        <InputGroup.Prepend>
          <Button
            variant="secondary"
            title={isPlus ? "Later" : "Earlier"}
            onClick={() => setPlus(!isPlus)}
          >
            <FontAwesomeIcon icon={isPlus ? faPlus : faMinus}></FontAwesomeIcon>
          </Button>
        </InputGroup.Prepend>
        <Form.Control
          type="number"
          placeholder="hour"
          onChange={updateOffset(0)}
        ></Form.Control>
        <Form.Control
          type="number"
          placeholder="min"
          onChange={updateOffset(1)}
        ></Form.Control>
        <Form.Control
          type="number"
          placeholder="sec"
          onChange={updateOffset(2)}
        ></Form.Control>
        <Form.Control
          type="number"
          placeholder="ms"
          onChange={updateOffset(3)}
        ></Form.Control>
      </InputGroup>
    </BaseModal>
  );
};

const TranslateModal: FunctionComponent<BaseModalProps & ToolModalProps> = ({
  process,
  ...modal
}) => {
  const { data: languages } = useEnabledLanguages();

  const available = useMemo(
    () => languages.filter((v) => v.code2 in availableTranslation),
    [languages]
  );

  const [selectedLanguage, setLanguage] =
    useState<Nullable<Language.Info>>(null);

  const submit = useCallback(() => {
    if (selectedLanguage) {
      process("translate", { language: selectedLanguage.code2 });
    }
  }, [selectedLanguage, process]);

  const footer = useMemo(
    () => (
      <Button disabled={!selectedLanguage} onClick={submit}>
        Translate
      </Button>
    ),
    [submit, selectedLanguage]
  );

  return (
    <BaseModal title="Translate to" footer={footer} {...modal}>
      <Form.Label>
        Enabled languages not listed here are unsupported by Google Translate.
      </Form.Label>
      <LanguageSelector
        options={available}
        onChange={setLanguage}
      ></LanguageSelector>
    </BaseModal>
  );
};

const TaskGroupName = "Modifying Subtitles";

const CanSelectSubtitle = (item: TableColumnType) => {
  return item.path.endsWith(".srt");
};

const STM: FunctionComponent<BaseModalProps> = ({ ...props }) => {
  const payload = useModalPayload<SupportType[]>(props.modalKey);
  const [selections, setSelections] = useState<TableColumnType[]>([]);

  const closeModal = useCloseModal();

  const { mutateAsync } = useSubtitleAction();

  const process = useCallback(
    (action: string, override?: Partial<FormType.ModifySubtitle>) => {
      log("info", "executing action", action);
      closeModal(props.modalKey);

      const tasks = selections.map((s) => {
        const form: FormType.ModifySubtitle = {
          id: s.id,
          type: s.type,
          language: s.language,
          path: s.path,
          ...override,
        };
        return createTask(s.path, s.id, mutateAsync, { action, form });
      });

      dispatchTask(TaskGroupName, tasks, "Modifying subtitles...");
    },
    [closeModal, props.modalKey, selections, mutateAsync]
  );

  const showModal = useShowModal();

  const columns: Column<TableColumnType>[] = useMemo<Column<TableColumnType>[]>(
    () => [
      {
        Header: "Language",
        accessor: "_language",
        Cell: ({ value }) => (
          <Badge variant="secondary">
            <LanguageText text={value} long></LanguageText>
          </Badge>
        ),
      },
      {
        id: "file",
        Header: "File",
        accessor: "path",
        Cell: (row) => {
          const path = row.value!;

          let idx = path.lastIndexOf("/");

          if (idx === -1) {
            idx = path.lastIndexOf("\\");
          }

          if (idx !== -1) {
            return path.slice(idx + 1);
          } else {
            return path;
          }
        },
      },
    ],
    []
  );

  const data = useMemo<TableColumnType[]>(
    () =>
      payload?.flatMap((item) => {
        const [id, type] = getIdAndType(item);
        return item.subtitles.flatMap((v) => {
          if (v.path !== null) {
            return [
              {
                id,
                type,
                language: v.code2,
                path: v.path,
                _language: v,
              },
            ];
          } else {
            return [];
          }
        });
      }) ?? [],
    [payload]
  );

  const plugins = [useRowSelect, useCustomSelection];

  const footer = useMemo(
    () => (
      <Dropdown as={ButtonGroup} onSelect={(k) => k && process(k)}>
        <ActionButton
          size="sm"
          disabled={selections.length === 0}
          icon={faPlay}
          onClick={() => process("sync")}
        >
          Sync
        </ActionButton>
        <Dropdown.Toggle
          disabled={selections.length === 0}
          split
          variant="light"
          size="sm"
          className="px-2"
        ></Dropdown.Toggle>
        <Dropdown.Menu>
          <Dropdown.Item eventKey="remove_HI">
            <ActionButtonItem icon={faDeaf}>Remove HI Tags</ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item eventKey="remove_tags">
            <ActionButtonItem icon={faCode}>Remove Style Tags</ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item eventKey="OCR_fixes">
            <ActionButtonItem icon={faImage}>OCR Fixes</ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item eventKey="common">
            <ActionButtonItem icon={faMagic}>Common Fixes</ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item eventKey="fix_uppercase">
            <ActionButtonItem icon={faTextHeight}>
              Fix Uppercase
            </ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item eventKey="reverse_rtl">
            <ActionButtonItem icon={faExchangeAlt}>
              Reverse RTL
            </ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item onSelect={() => showModal("add-color")}>
            <ActionButtonItem icon={faPaintBrush}>Add Color</ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item onSelect={() => showModal("change-frame-rate")}>
            <ActionButtonItem icon={faFilm}>Change Frame Rate</ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item onSelect={() => showModal("adjust-times")}>
            <ActionButtonItem icon={faClock}>Adjust Times</ActionButtonItem>
          </Dropdown.Item>
          <Dropdown.Item onSelect={() => showModal("translate-sub")}>
            <ActionButtonItem icon={faLanguage}>Translate</ActionButtonItem>
          </Dropdown.Item>
        </Dropdown.Menu>
      </Dropdown>
    ),
    [showModal, selections.length, process]
  );

  return (
    <React.Fragment>
      <BaseModal title={"Subtitle Tools"} footer={footer} {...props}>
        <SimpleTable
          isSelecting={data.length !== 0}
          emptyText="No External Subtitles Found"
          plugins={plugins}
          columns={columns}
          onSelect={setSelections}
          canSelect={CanSelectSubtitle}
          data={data}
        ></SimpleTable>
      </BaseModal>
      <AddColorModal process={process} modalKey="add-color"></AddColorModal>
      <FrameRateModal
        process={process}
        modalKey="change-frame-rate"
      ></FrameRateModal>
      <AdjustTimesModal
        process={process}
        modalKey="adjust-times"
      ></AdjustTimesModal>
      <TranslateModal
        process={process}
        modalKey="translate-sub"
      ></TranslateModal>
    </React.Fragment>
  );
};

export default STM;