Get file name parsing to work
[armadillo.git] / src / tv_rename.go
1 //
2 // Armadillo File Manager
3 // Copyright (c) 2011, Robert Sesek <http://www.bluestatic.org>
4 //
5 // This program is free software: you can redistribute it and/or modify it under
6 // the terms of the GNU General Public License as published by the Free Software
7 // Foundation, either version 3 of the License, or any later version.
8 //
9
10 package tv_rename
11
12 import (
13 "fmt"
14 "os"
15 "path"
16 "regexp"
17 "strconv"
18 "strings"
19 "./paths"
20 )
21
22 // Takes a full file path and renames the last path component as if it were a
23 // TV episode. This performs the actual rename as well.
24 func RenameEpisode(inPath string) (*string, os.Error) {
25 // Make sure a path was given.
26 if len(inPath) < 1 {
27 return nil, os.NewError("Invalid path")
28 }
29 // Check that it's inside the jail.
30 var safePath *string = paths.Verify(inPath)
31 if safePath == nil {
32 return nil, os.NewError("Path is invalid or outside of jail")
33 }
34 // Make sure that the file exists.
35 _, err := os.Stat(*safePath)
36 if err != nil {
37 return nil, err
38 }
39
40 // Parse the filename into its components.
41 _, fileName := path.Split(*safePath)
42 info := parseEpisodeName(fileName)
43 if info == nil {
44 return nil, os.NewError("Could not parse file name")
45 }
46 fmt.Print("info = ", *info)
47
48 return safePath, nil
49 }
50
51 type episodeInfo struct {
52 showName string
53 season int
54 episode int
55 }
56
57 // Parses the last path component into a the component structure.
58 func parseEpisodeName(name string) *episodeInfo {
59 regex := regexp.MustCompile("(.+)( |\\.)[sS]?([0-9]+)[xeXE]([0-9]+)")
60 matches := regex.FindAllStringSubmatch(name, -1)
61 if len(matches) < 1 || len(matches[0]) < 4 {
62 return nil
63 }
64
65 // Convert the season and episode numbers to integers.
66 season, err := strconv.Atoi(matches[0][3])
67 if err != nil {
68 return nil
69 }
70 episode, err := strconv.Atoi(matches[0][4])
71 if err != nil {
72 return nil
73 }
74
75 // If the separator between the show title and episode is a period, then
76 // it's likely of the form "some.show.name.s03e06.720p.blah.mkv", so strip the
77 // periods in the title.
78 var showName string = matches[0][1]
79 if matches[0][2] == "." {
80 showName = strings.Replace(matches[0][1], ".", " ", -1)
81 }
82
83 return &episodeInfo {
84 showName,
85 season,
86 episode,
87 }
88 }