deleteFiles deletes a list of record files by their names. Returns the failed/remaining files.
(ctx context.Context, app App, record *Record, filenames []string)
| 575 | // deleteFiles deletes a list of record files by their names. |
| 576 | // Returns the failed/remaining files. |
| 577 | func (f *FileField) deleteFilesByNamesList(ctx context.Context, app App, record *Record, filenames []string) ([]string, error) { |
| 578 | if len(filenames) == 0 { |
| 579 | return nil, nil // nothing to delete |
| 580 | } |
| 581 | |
| 582 | if record.Id == "" { |
| 583 | return filenames, errors.New("the record doesn't have an id") |
| 584 | } |
| 585 | |
| 586 | fsys, err := app.NewFilesystem() |
| 587 | if err != nil { |
| 588 | return filenames, err |
| 589 | } |
| 590 | defer fsys.Close() |
| 591 | fsys.SetContext(ctx) |
| 592 | |
| 593 | var failures []error |
| 594 | |
| 595 | for i := len(filenames) - 1; i >= 0; i-- { |
| 596 | filename := filenames[i] |
| 597 | if filename == "" || strings.ContainsAny(filename, "/\\") { |
| 598 | continue // empty or not a plain filename |
| 599 | } |
| 600 | |
| 601 | path := record.BaseFilesPath() + "/" + filename |
| 602 | |
| 603 | err := fsys.Delete(path) |
| 604 | if err != nil && !errors.Is(err, filesystem.ErrNotFound) { |
| 605 | // store the delete error |
| 606 | failures = append(failures, fmt.Errorf("file %d (%q): %w", i, filename, err)) |
| 607 | } else { |
| 608 | // remove the deleted file from the list |
| 609 | filenames = append(filenames[:i], filenames[i+1:]...) |
| 610 | |
| 611 | // try to delete the related file thumbs (if any) |
| 612 | thumbsErr := fsys.DeletePrefix(record.BaseFilesPath() + "/thumbs_" + filename + "/") |
| 613 | if len(thumbsErr) > 0 { |
| 614 | app.Logger().Warn("Failed to delete file thumbs", "error", errors.Join(thumbsErr...)) |
| 615 | } |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | if len(failures) > 0 { |
| 620 | return filenames, fmt.Errorf("failed to delete all files: %w", errors.Join(failures...)) |
| 621 | } |
| 622 | |
| 623 | return nil, nil |
| 624 | } |
| 625 | |
| 626 | // newContextIfInvalid returns a new Background context if the provided one was cancelled. |
| 627 | func newContextIfInvalid(ctx context.Context) context.Context { |
no test coverage detected