Fix most compile errors
[armadillo.git] / server / tv_rename.go
1 //
2 // Armadillo File Manager
3 // Copyright (c) 2011-2012, 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 server
11
12 import (
13 "bufio"
14 "errors"
15 "fmt"
16 "io"
17 "net"
18 "net/http"
19 "net/http/httputil"
20 "net/url"
21 "path"
22 "regexp"
23 "strconv"
24 "strings"
25 )
26
27 // Takes a full file path and renames the last path component as if it were a
28 // TV episode. This performs the actual rename as well.
29 func RenameTVEpisode(inPath string) (*string, error) {
30 // Parse the filename into its components.
31 dirName, fileName := path.Split(inPath)
32 info := parseEpisodeName(fileName)
33 if info == nil {
34 return nil, errors.New("Could not parse file name")
35 }
36
37 // Create the URL and perform the lookup.
38 queryURL := buildURL(info)
39 response, err := performLookup(queryURL)
40 if err != nil {
41 return nil, err
42 }
43
44 // Parse the response into the fullEpisodeInfo struct.
45 fullInfo := parseResponse(response)
46
47 // Create the new path.
48 newName := fmt.Sprintf("%s - %dx%02d - %s", fullInfo.episode.showName,
49 fullInfo.episode.season, fullInfo.episode.episode, fullInfo.episodeName)
50 newName = strings.Replace(newName, "/", "_", -1)
51 newName += path.Ext(fileName)
52 newPath := path.Join(dirName, newName)
53
54 return &newPath, nil
55 }
56
57 type episodeInfo struct {
58 showName string
59 season int
60 episode int
61 }
62
63 type fullEpisodeInfo struct {
64 episode episodeInfo
65 episodeName string
66 }
67
68 // Parses the last path component into a the component structure.
69 func parseEpisodeName(name string) *episodeInfo {
70 regex := regexp.MustCompile("(.+)( |\\.)[sS]?([0-9]+)[xeXE]([0-9]+)")
71 matches := regex.FindAllStringSubmatch(name, -1)
72 if len(matches) < 1 || len(matches[0]) < 4 {
73 return nil
74 }
75
76 // Convert the season and episode numbers to integers.
77 season, episode := convertEpisode(matches[0][3], matches[0][4])
78 if season == 0 && season == episode {
79 return nil
80 }
81
82 // If the separator between the show title and episode is a period, then
83 // it's likely of the form "some.show.name.s03e06.720p.blah.mkv", so strip the
84 // periods in the title.
85 var showName string = matches[0][1]
86 if matches[0][2] == "." {
87 showName = strings.Replace(matches[0][1], ".", " ", -1)
88 }
89
90 return &episodeInfo{
91 showName,
92 season,
93 episode,
94 }
95 }
96
97 // Builds the URL to which we send a HTTP request to get the episode name.
98 func buildURL(info *episodeInfo) string {
99 return fmt.Sprintf("http://services.tvrage.com/tools/quickinfo.php?show=%s&ep=%dx%d",
100 url.QueryEscape(info.showName), info.season, info.episode)
101 }
102
103 // Converts a season and episode to integers. If the return values are both 0,
104 // an error occurred.
105 func convertEpisode(season string, episode string) (int, int) {
106 seasonInt, err := strconv.Atoi(season)
107 if err != nil {
108 return 0, 0
109 }
110 episodeInt, err := strconv.Atoi(episode)
111 if err != nil {
112 return 0, 0
113 }
114 return seasonInt, episodeInt
115 }
116
117 // Performs the actual lookup and returns the HTTP response.
118 func performLookup(urlString string) (*http.Response, error) {
119 url_, err := url.Parse(urlString)
120 if err != nil {
121 return nil, err
122 }
123
124 // Open a TCP connection.
125 conn, err := net.Dial("tcp", url_.Host+":"+url_.Scheme)
126 if err != nil {
127 return nil, err
128 }
129
130 // Perform the HTTP request.
131 client := httputil.NewClientConn(conn, nil)
132 request, err := http.NewRequest("GET", urlString, nil)
133 if err != nil {
134 return nil, err
135 }
136 request.Header.Set("User-Agent", "Armadillo File Manager")
137 err = client.Write(request)
138 if err != nil {
139 return nil, err
140 }
141 return client.Read(request)
142 }
143
144 // Parses the HTTP response from performLookup().
145 func parseResponse(response *http.Response) *fullEpisodeInfo {
146 var err error
147 var line string
148 var info fullEpisodeInfo
149
150 buf := bufio.NewReader(response.Body)
151 for ; err != io.EOF; line, err = buf.ReadString('\n') {
152 // An error ocurred while reading.
153 if err != nil {
154 return nil
155 }
156 var parts []string = strings.SplitN(line, "@", 2)
157 if len(parts) != 2 {
158 continue
159 }
160 switch parts[0] {
161 case "Show Name":
162 info.episode.showName = strings.TrimSpace(parts[1])
163 case "Episode Info":
164 // Split the line, which is of the form: |SxE^Name^AirDate|.
165 parts = strings.SplitN(parts[1], "^", 3)
166 info.episodeName = parts[1]
167 // Split the episode string.
168 episode := strings.SplitN(parts[0], "x", 2)
169 info.episode.season, info.episode.episode = convertEpisode(episode[0], episode[1])
170 if info.episode.season == 0 && info.episode.season == info.episode.episode {
171 return nil
172 }
173 }
174 }
175 return &info
176 }