package worker import ( "fmt" "code.nonshy.com/nonshy/website/pkg/log" "code.nonshy.com/nonshy/website/pkg/models" "code.nonshy.com/nonshy/website/pkg/photo" ) // Vacuum runs database cleanup tasks for data consistency. Run it like `nonshy vacuum` from the CLI. func Vacuum(dryrun bool) error { log.Warn("Vacuum: Orphaned Comment Photos") if total, err := VacuumOrphanedCommentPhotos(dryrun); err != nil { log.Error("Orphaned Comment Photos: %s", err) } else { log.Info("Removed %d photo(s)", total) } log.Warn("Vacuum: Orphaned Gallery Photos") if total, err := VacuumOrphanedPhotos(dryrun); err != nil { log.Error("Orphaned Gallery Photos: %s", err) } else { log.Info("Removed %d photo(s)", total) } return nil } // VacuumOrphanedPhotos removes any lingering photo from failed account deletion. func VacuumOrphanedPhotos(dryrun bool) (int64, error) { photos, count, err := models.GetOrphanedPhotos() if err != nil { return count, err } if dryrun { return count, nil } for _, row := range photos { log.Info(" #%d: %s", row.ID, row.Filename) if err := photo.Delete(row.Filename); err != nil { return count, fmt.Errorf("photo ID %d: removing file %s: %s", row.ID, row.Filename, err) } if row.CroppedFilename != "" { if err := photo.Delete(row.CroppedFilename); err != nil { return count, fmt.Errorf("photo ID %d: removing file %s: %s", row.ID, row.Filename, err) } } if err := row.Delete(); err != nil { return count, fmt.Errorf("deleting orphaned photo (%d): %s", row.ID, err) } } return count, nil } // VacuumOrphanedCommentPhotos cleans up comment photos that weren't associated to a post, returning the count removed. func VacuumOrphanedCommentPhotos(dryrun bool) (int64, error) { // Do the needful. photos, total, err := models.GetOrphanedCommentPhotos() if err != nil { return total, err } if dryrun { return total, nil } for _, row := range photos { if err := photo.Delete(row.Filename); err != nil { return total, fmt.Errorf("photo ID %d: removing file %s: %s", row.ID, row.Filename, err) } if err := row.Delete(); err != nil { return total, fmt.Errorf("deleting orphaned comment photo (%d): %s", row.ID, err) } } return total, nil }