From 29336d1ee0c7a83c896f1e78efa2618c777d16ec Mon Sep 17 00:00:00 2001 From: bnkai <48220860+bnkai@users.noreply.github.com> Date: Fri, 24 Apr 2020 05:53:18 +0300 Subject: [PATCH] Move image with cover.jpg in name to first place in Galleries (#477) --- pkg/models/model_gallery.go | 38 ++++++++++++++++++++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/pkg/models/model_gallery.go b/pkg/models/model_gallery.go index 53ab2b406..932164db3 100644 --- a/pkg/models/model_gallery.go +++ b/pkg/models/model_gallery.go @@ -88,7 +88,7 @@ func (g *Gallery) readZipFile(index int) ([]byte, error) { func (g *Gallery) listZipContents() ([]*zip.File, *zip.ReadCloser, error) { readCloser, err := zip.OpenReader(g.Path) if err != nil { - logger.Warn("failed to read zip file") + logger.Warnf("failed to read zip file %s", g.Path) return nil, nil, err } @@ -112,5 +112,41 @@ func (g *Gallery) listZipContents() ([]*zip.File, *zip.ReadCloser, error) { return utils.NaturalCompare(a.Name, b.Name) }) + cover := contains(filteredFiles, "cover.jpg") // first image with cover.jpg in the name + if cover >= 0 { // will be moved to the start + reorderedFiles := reorder(filteredFiles, cover) + if reorderedFiles != nil { + return reorderedFiles, readCloser, nil + } + } + return filteredFiles, readCloser, nil } + +// return index of first occurenece of string x in name of zip contents, -1 otherwise +func contains(a []*zip.File, x string) int { + for i, n := range a { + if strings.Contains(n.Name, x) { + return i + } + } + return -1 +} + +// reorder slice so that element with position toFirst gets at the start +func reorder(a []*zip.File, toFirst int) []*zip.File { + var first *zip.File + switch { + case toFirst < 0 || toFirst >= len(a): + return nil + case toFirst == 0: + return a + default: + first = a[toFirst] + copy(a[toFirst:], a[toFirst+1:]) // Shift a[toFirst+1:] left one index removing a[toFirst] element + a[len(a)-1] = nil // Nil now unused element for garbage collection + a = a[:len(a)-1] // Truncate slice + a = append([]*zip.File{first}, a...) // Push first to the start of the slice + } + return a +}