-
Notifications
You must be signed in to change notification settings - Fork 3
/
app_rename.go
297 lines (258 loc) · 7.04 KB
/
app_rename.go
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
package app
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/apex/log"
"github.com/tympanix/supper/media"
"github.com/tympanix/supper/provider"
"github.com/tympanix/supper/types"
)
type renamer func(types.Local, string) error
// Rename is a wrapper function around a renamer which performs some sanity checks
func (r renamer) Rename(local types.Local, dest string, force bool) error {
if err := ensurePath(dest, force); err != nil {
return err
}
return r(local, dest)
}
func ensurePath(dest string, force bool) error {
_, err := os.Stat(dest)
if !force && err == nil {
return media.NewExistsErr()
}
if err == nil {
if err := os.Remove(dest); err != nil {
return err
}
log.WithField("path", dest).Debug("Removed existing media")
}
if err := os.MkdirAll(filepath.Dir(dest), os.ModePerm); err != nil {
return err
}
return nil
}
func copyMedia(file io.Reader, dest string) error {
out, err := os.Create(dest)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
return err
}
log.WithField("path", dest).Debug("Media copied")
return nil
}
func copyRenamer(local types.Local, dest string) error {
file, err := os.Open(local.Path())
if err != nil {
return err
}
defer file.Close()
if err := copyMedia(file, dest); err != nil {
return err
}
return nil
}
func moveRenamer(local types.Local, dest string) error {
if err := os.Rename(local.Path(), dest); err != nil {
return err
}
log.WithField("path", dest).Debug("Media moved")
return nil
}
func symlinkRenamer(local types.Local, dest string) error {
abs, err := filepath.Abs(local.Path())
if err != nil {
return err
}
if err := os.Symlink(abs, dest); err != nil {
return err
}
log.WithField("path", dest).Debug("Media symlinked")
return nil
}
func hardlinkRenamer(local types.Local, dest string) error {
if err := os.Link(local.Path(), dest); err != nil {
return err
}
log.WithField("path", dest).Debug("Media hardlinked")
return nil
}
// Renamers holds the available renaming actions of the application
var Renamers = map[string]renamer{
"copy": renamer(copyRenamer),
"move": renamer(moveRenamer),
"symlink": renamer(symlinkRenamer),
"hardlink": renamer(hardlinkRenamer),
}
var pathRegex = regexp.MustCompile(`[%/\?\\\*:\|"<>\n\r]`)
// cleanString cleans the string for unwanted characters such that it can
// be used safely as a name in a file hierarchy. All path seperators are
// removed from the string.
func cleanString(str string) string {
return pathRegex.ReplaceAllString(str, "")
}
var multispaceRegex = regexp.MustCompile(`\s\s+`)
var illegalPostfixRegex = regexp.MustCompile(`[^\p{L}\)0-9]+$`)
// truncateSpaces replaces all consecutive space characters with a single space.
// Trailing non-characters (i.e. spaces, symbols ect.) are removed
func truncateSpaces(str string) string {
str = multispaceRegex.ReplaceAllString(str, " ")
str = illegalPostfixRegex.ReplaceAllString(str, "")
return str
}
// RenameMedia traverses the local media list and renames the media
func (a *Application) RenameMedia(list types.LocalMediaList) error {
renamer, ok := Renamers[a.Config().RenameAction()]
if !ok {
return fmt.Errorf("%s: unknown action", a.Config().RenameAction())
}
for _, m := range list.List() {
ctx := log.WithField("media", m).WithField("action", a.Config().RenameAction())
dest, err := a.scrapeAndRenameMedia(m, m)
if err != nil {
return err
}
if !a.Config().Dry() {
err = renamer.Rename(m, dest, a.Config().Force())
} else {
ctx.WithField("reason", "dry-run").Info("Skip rename")
continue
}
if err != nil {
if media.IsExistsErr(err) {
ctx.WithField("reason", "media already exists").Warn("Rename skipped")
} else {
ctx.WithError(err).Error("Rename failed")
}
if a.Config().Strict() {
return err
}
} else {
ctx.Info("Media renamed")
}
}
return nil
}
func (a *Application) scrapeAndRenameMedia(info os.FileInfo, m types.Media) (string, error) {
scraped, err := a.scrapeMedia(m)
if err != nil {
return "", err
}
if err = m.Merge(scraped); err != nil {
return "", err
}
dest, err := a.renameMedia(info, m)
if media.IsUnknown(err) && a.Config().Strict() {
return "", err
}
if err != nil && !media.IsUnknown(err) {
return "", err
}
return dest, nil
}
func (a *Application) renameMedia(info os.FileInfo, m types.Media) (dest string, err error) {
if movie, ok := m.TypeMovie(); ok {
return a.renameMovie(info, movie)
} else if episode, ok := m.TypeEpisode(); ok {
return a.renameEpisode(info, episode)
} else if sub, ok := m.TypeSubtitle(); ok {
return a.renameSubtitle(info, sub)
}
return "", media.NewUnknownErr()
}
func (a *Application) scrapeMedia(m types.Media) (types.Media, error) {
for _, s := range a.Scrapers() {
scraped, err := s.Scrape(m)
if err != nil {
if provider.IsErrMediaNotSupported(err) {
continue
}
return nil, err
}
return scraped, nil
}
return nil, errors.New("no scrapers to use for media")
}
func (a *Application) renameMovie(info os.FileInfo, m types.Movie) (string, error) {
var buf bytes.Buffer
template := a.Config().Movies().Template()
if template == nil {
return "", errors.New("missing template for movies")
}
data := struct {
Movie string
Year int
Quality string
Codec string
Source string
Group string
}{
Movie: cleanString(m.MovieName()),
Year: m.Year(),
Quality: m.Quality().String(),
Codec: m.Codec().String(),
Source: m.Source().String(),
Group: cleanString(m.Group()),
}
if err := template.Execute(&buf, &data); err != nil {
return "", err
}
if buf.String() == "" {
return "", errors.New("empty movie template")
}
filename := truncateSpaces(buf.String()) + filepath.Ext(info.Name())
return filepath.Join(a.Config().Movies().Directory(), filename), nil
}
func (a *Application) renameEpisode(info os.FileInfo, e types.Episode) (string, error) {
var buf bytes.Buffer
template := a.Config().TVShows().Template()
if template == nil {
return "", errors.New("missing template for tvshows")
}
data := struct {
TVShow string
Name string
Episode int
Season int
Quality string
Codec string
Source string
Group string
}{
TVShow: cleanString(e.TVShow()),
Name: cleanString(e.EpisodeName()),
Episode: e.Episode(),
Season: e.Season(),
Quality: e.Quality().String(),
Codec: e.Codec().String(),
Source: e.Source().String(),
Group: cleanString(e.Group()),
}
if err := template.Execute(&buf, &data); err != nil {
return "", err
}
if buf.String() == "" {
return "", errors.New("empty episode template")
}
filename := truncateSpaces(buf.String()) + filepath.Ext(info.Name())
return filepath.Join(a.Config().TVShows().Directory(), filename), nil
}
func (a *Application) renameSubtitle(info os.FileInfo, s types.Subtitle) (string, error) {
dest, err := a.renameMedia(info, s.ForMedia())
if err != nil {
return "", err
}
ext := filepath.Ext(dest)
base := strings.TrimSuffix(dest, ext)
dest = base + "." + fmt.Sprintf("%v", s.Language()) + ext
return dest, err
}