From 97e3d758edbb92fd8b8003846e8d9ea9bb57fc4c Mon Sep 17 00:00:00 2001 From: Robert Sesek Date: Sat, 7 May 2011 11:48:48 -0400 Subject: [PATCH] Run gofmt on all the code. Only whitespace changes. --- src/config.go | 44 ++++---- src/main.go | 78 ++++++------- src/paths.go | 116 +++++++++---------- src/server.go | 282 +++++++++++++++++++++++------------------------ src/tv_rename.go | 254 +++++++++++++++++++++--------------------- 5 files changed, 387 insertions(+), 387 deletions(-) diff --git a/src/config.go b/src/config.go index 93bf686..30c7193 100644 --- a/src/config.go +++ b/src/config.go @@ -10,36 +10,36 @@ package config import ( - "json" - "os" + "json" + "os" ) type Configuration struct { - // The path to which all file operations are restricted. - JailRoot string + // The path to which all file operations are restricted. + JailRoot string - // The port on which the server back end runs. - Port int + // The port on which the server back end runs. + Port int - // An array of URLs that the /proxy service will for which the back-end will - // forward GET requests and return the result. - ProxyURLs []string + // An array of URLs that the /proxy service will for which the back-end will + // forward GET requests and return the result. + ProxyURLs []string - // A map of usernames to MD5-encoded passwords that will be allowed to log in - // via a .htaccess style realm. - Users map [string] string + // A map of usernames to MD5-encoded passwords that will be allowed to log in + // via a .htaccess style realm. + Users map[string]string - // Whether to include dotfiles (files that begin with a '.'). Users will still - // be able to access directories that begin with a '.', but they will not be - // included in the list. - IncludeDotfiles bool + // Whether to include dotfiles (files that begin with a '.'). Users will still + // be able to access directories that begin with a '.', but they will not be + // included in the list. + IncludeDotfiles bool } func ReadFromFile(aPath string, config *Configuration) os.Error { - fd, error := os.Open(aPath, os.O_RDONLY, 0) - if error != nil { - return error - } - decoder := json.NewDecoder(fd) - return decoder.Decode(config) + fd, error := os.Open(aPath, os.O_RDONLY, 0) + if error != nil { + return error + } + decoder := json.NewDecoder(fd) + return decoder.Decode(config) } diff --git a/src/main.go b/src/main.go index 2a90f12..4ef72df 100644 --- a/src/main.go +++ b/src/main.go @@ -10,50 +10,50 @@ package main import ( - "flag" - "fmt" - "os" - "strings" - "./config" - "./paths" - "./server" + "flag" + "fmt" + "os" + "strings" + "./config" + "./paths" + "./server" ) func main() { - // Set up the basic flags. - var configPath *string = flag.String("config", "~/.armadillo", "Path to the configuration file") - var jailRoot *string = flag.String("jail", "", "Restrict file operations to this directory root") - var port *int = flag.Int("port", 0, "Port to run the server on") - flag.Parse() + // Set up the basic flags. + var configPath *string = flag.String("config", "~/.armadillo", "Path to the configuration file") + var jailRoot *string = flag.String("jail", "", "Restrict file operations to this directory root") + var port *int = flag.Int("port", 0, "Port to run the server on") + flag.Parse() - // Load the configuration file, if it is present. - var configuration = new(config.Configuration) - fmt.Printf("Reading configuration from %v\n", *configPath) - if len(*configPath) > 0 { - *configPath = strings.Replace(*configPath, "~", "$HOME", 1) - *configPath = os.ShellExpand(*configPath) - error := config.ReadFromFile(*configPath, configuration) - if error != nil { - fmt.Printf("Error while reading configuration: %v\n", error) - } - } + // Load the configuration file, if it is present. + var configuration = new(config.Configuration) + fmt.Printf("Reading configuration from %v\n", *configPath) + if len(*configPath) > 0 { + *configPath = strings.Replace(*configPath, "~", "$HOME", 1) + *configPath = os.ShellExpand(*configPath) + error := config.ReadFromFile(*configPath, configuration) + if error != nil { + fmt.Printf("Error while reading configuration: %v\n", error) + } + } - // Override configuration values with command line arguments. - if *jailRoot != "" { - configuration.JailRoot = *jailRoot - } - if *port != 0 { - configuration.Port = *port - } + // Override configuration values with command line arguments. + if *jailRoot != "" { + configuration.JailRoot = *jailRoot + } + if *port != 0 { + configuration.Port = *port + } - if configuration.Port == 0 { - fmt.Printf("Failed to start server (invalid port)\n") - os.Exit(1) - } + if configuration.Port == 0 { + fmt.Printf("Failed to start server (invalid port)\n") + os.Exit(1) + } - // Run the server. - fmt.Printf("Starting Armadillo on port %d with root:\n %v\n", - configuration.Port, configuration.JailRoot) - paths.SetConfig(configuration) - server.RunBackEnd(configuration) + // Run the server. + fmt.Printf("Starting Armadillo on port %d with root:\n %v\n", + configuration.Port, configuration.JailRoot) + paths.SetConfig(configuration) + server.RunBackEnd(configuration) } diff --git a/src/paths.go b/src/paths.go index 428c9b2..584910b 100644 --- a/src/paths.go +++ b/src/paths.go @@ -10,82 +10,82 @@ package paths import ( - "container/vector" - "os" - "path" - "strings" - "./config" + "container/vector" + "os" + "path" + "strings" + "./config" ) var gConfig *config.Configuration func SetConfig(aConfig *config.Configuration) { - gConfig = aConfig + gConfig = aConfig } func canonicalizePath(raw_path string) string { - raw_path = path.Join(gConfig.JailRoot, raw_path) - return path.Clean(raw_path) + raw_path = path.Join(gConfig.JailRoot, raw_path) + return path.Clean(raw_path) } func checkInJail(the_path string) bool { - if len(the_path) < len(gConfig.JailRoot) { - return false - } - if the_path[0:len(gConfig.JailRoot)] != gConfig.JailRoot { - return false - } - if strings.Index(the_path, "../") != -1 { - return false - } - return true + if len(the_path) < len(gConfig.JailRoot) { + return false + } + if the_path[0:len(gConfig.JailRoot)] != gConfig.JailRoot { + return false + } + if strings.Index(the_path, "../") != -1 { + return false + } + return true } func List(the_path string) (files vector.StringVector, err os.Error) { - full_path := canonicalizePath(the_path) - if !checkInJail(full_path) { - return nil, os.NewError("Path outside of jail") - } - - fd, file_error := os.Open(full_path, os.O_RDONLY, 0) - if file_error != nil { - return nil, file_error - } - - fileinfos, read_err := fd.Readdir(-1) - if read_err != nil { - return nil, read_err - } - - for _, info := range fileinfos { - name := info.Name - if info.IsDirectory() { - name += "/" - } - if !gConfig.IncludeDotfiles && name[0] == '.' { - continue - } - files.Push(name) - } - return files, nil + full_path := canonicalizePath(the_path) + if !checkInJail(full_path) { + return nil, os.NewError("Path outside of jail") + } + + fd, file_error := os.Open(full_path, os.O_RDONLY, 0) + if file_error != nil { + return nil, file_error + } + + fileinfos, read_err := fd.Readdir(-1) + if read_err != nil { + return nil, read_err + } + + for _, info := range fileinfos { + name := info.Name + if info.IsDirectory() { + name += "/" + } + if !gConfig.IncludeDotfiles && name[0] == '.' { + continue + } + files.Push(name) + } + return files, nil } func Remove(the_path string) os.Error { - full_path := canonicalizePath(the_path) - if !checkInJail(full_path) { - return os.NewError("Path outside of jail") - } - return os.RemoveAll(full_path) + full_path := canonicalizePath(the_path) + if !checkInJail(full_path) { + return os.NewError("Path outside of jail") + } + return os.RemoveAll(full_path) } func Move(source string, target string) os.Error { - source = canonicalizePath(source) - target = canonicalizePath(target) - if !checkInJail(source) { - return os.NewError("Source outside of jail") - } - if !checkInJail(target) { - return os.NewError("Target outside of jail") - } - return os.Rename(source, target) + source = canonicalizePath(source) + target = canonicalizePath(target) + if !checkInJail(source) { + return os.NewError("Source outside of jail") + } + if !checkInJail(target) { + return os.NewError("Target outside of jail") + } + return os.Rename(source, target) } diff --git a/src/server.go b/src/server.go index 8e0a7fb..6f26279 100644 --- a/src/server.go +++ b/src/server.go @@ -10,17 +10,17 @@ package server import ( - "fmt" - "http" - "io" - "json" - "net" - "os" - "path" - "strings" - "./config" - "./paths" - "./tv_rename" + "fmt" + "http" + "io" + "json" + "net" + "os" + "path" + "strings" + "./config" + "./paths" + "./tv_rename" ) var dir, file = path.Split(path.Clean(os.Getenv("_"))) @@ -28,154 +28,154 @@ var kFrontEndFiles string = path.Join(dir, "fe") var gConfig *config.Configuration = nil func indexHandler(response http.ResponseWriter, request *http.Request) { - fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"), os.O_RDONLY, 0) - if err != nil { - fmt.Print("Error opening file ", err.String(), "\n") - return - } - io.Copy(response, fd) + fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"), os.O_RDONLY, 0) + if err != nil { + fmt.Print("Error opening file ", err.String(), "\n") + return + } + io.Copy(response, fd) } func serviceHandler(response http.ResponseWriter, request *http.Request) { - if request.Method != "POST" { - io.WriteString(response, "Error: Not a POST request") - return - } - - switch request.FormValue("action") { - case "list": - files, err := paths.List(request.FormValue("path")) - if err != nil { - errorResponse(response, err.String()) - } else { - okResponse(response, files) - } - case "remove": - err := paths.Remove(request.FormValue("path")) - if err != nil { - errorResponse(response, err.String()) - } else { - data := map[string] int { - "error" : 0, - } - okResponse(response, data) - } - case "move": - source := request.FormValue("source") - target := request.FormValue("target") - err := paths.Move(source, target) - if err != nil { - errorResponse(response, err.String()) - } else { - data := map[string] interface{} { - "path" : target, - "error" : 0, - } - okResponse(response, data) - } - case "tv_rename": - newPath, err := tv_rename.RenameEpisode(request.FormValue("path")) - if err != nil { - errorResponse(response, err.String()) - } else { - data := map[string] interface{} { - "path" : *newPath, - "error" : 0, - } - okResponse(response, data) - } - default: - fmt.Printf("Invalid action: '%s'\n", request.FormValue("action")) - errorResponse(response, "Unhandled action") - } + if request.Method != "POST" { + io.WriteString(response, "Error: Not a POST request") + return + } + + switch request.FormValue("action") { + case "list": + files, err := paths.List(request.FormValue("path")) + if err != nil { + errorResponse(response, err.String()) + } else { + okResponse(response, files) + } + case "remove": + err := paths.Remove(request.FormValue("path")) + if err != nil { + errorResponse(response, err.String()) + } else { + data := map[string]int{ + "error": 0, + } + okResponse(response, data) + } + case "move": + source := request.FormValue("source") + target := request.FormValue("target") + err := paths.Move(source, target) + if err != nil { + errorResponse(response, err.String()) + } else { + data := map[string]interface{}{ + "path": target, + "error": 0, + } + okResponse(response, data) + } + case "tv_rename": + newPath, err := tv_rename.RenameEpisode(request.FormValue("path")) + if err != nil { + errorResponse(response, err.String()) + } else { + data := map[string]interface{}{ + "path": *newPath, + "error": 0, + } + okResponse(response, data) + } + default: + fmt.Printf("Invalid action: '%s'\n", request.FormValue("action")) + errorResponse(response, "Unhandled action") + } } func proxyHandler(response http.ResponseWriter, request *http.Request) { - rawURL := request.FormValue("url") - if len(rawURL) < 1 { - return - } - - var validURL bool = false - for i := range gConfig.ProxyURLs { - allowedURL := gConfig.ProxyURLs[i] - validURL = validURL || strings.HasPrefix(rawURL, allowedURL) - } - - if !validURL { - errorResponse(response, "URL is not in proxy whitelist") - return - } - - url, err := http.ParseURL(rawURL) - if err != nil { - errorResponse(response, err.String()) - return - } - err = performProxy(url, response, request) - if err != nil { - errorResponse(response, err.String()) - } + rawURL := request.FormValue("url") + if len(rawURL) < 1 { + return + } + + var validURL bool = false + for i := range gConfig.ProxyURLs { + allowedURL := gConfig.ProxyURLs[i] + validURL = validURL || strings.HasPrefix(rawURL, allowedURL) + } + + if !validURL { + errorResponse(response, "URL is not in proxy whitelist") + return + } + + url, err := http.ParseURL(rawURL) + if err != nil { + errorResponse(response, err.String()) + return + } + err = performProxy(url, response, request) + if err != nil { + errorResponse(response, err.String()) + } } func performProxy(url *http.URL, response http.ResponseWriter, origRequest *http.Request) os.Error { - conn, err := net.Dial("tcp", "", url.Host + ":http") - if err != nil { - return err - } - client := http.NewClientConn(conn, nil) - var request http.Request - request.URL = url - request.Method = "GET" - request.UserAgent = origRequest.UserAgent - err = client.Write(&request) - if err != nil { - return err - } - var proxyResponse *http.Response - proxyResponse, err = client.Read(&request) - if err != nil && err != http.ErrPersistEOF { - return err - } - _, err = io.Copy(response, proxyResponse.Body) - return err + conn, err := net.Dial("tcp", "", url.Host+":http") + if err != nil { + return err + } + client := http.NewClientConn(conn, nil) + var request http.Request + request.URL = url + request.Method = "GET" + request.UserAgent = origRequest.UserAgent + err = client.Write(&request) + if err != nil { + return err + } + var proxyResponse *http.Response + proxyResponse, err = client.Read(&request) + if err != nil && err != http.ErrPersistEOF { + return err + } + _, err = io.Copy(response, proxyResponse.Body) + return err } func errorResponse(response http.ResponseWriter, message string) { - message = strings.Replace(message, gConfig.JailRoot, "/", -1) - data := map[string] interface{} { - "error" : -1, - "message" : message, - } - json_data, err := json.Marshal(data) - - response.SetHeader("Content-Type", "text/json") - if err != nil { - io.WriteString(response, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}") - } else { - response.Write(json_data) - } + message = strings.Replace(message, gConfig.JailRoot, "/", -1) + data := map[string]interface{}{ + "error": -1, + "message": message, + } + json_data, err := json.Marshal(data) + + response.SetHeader("Content-Type", "text/json") + if err != nil { + io.WriteString(response, "{\"error\":\"-9\",\"message\":\"Internal encoding error\"}") + } else { + response.Write(json_data) + } } func okResponse(response http.ResponseWriter, data interface{}) { - response.SetHeader("Content-Type", "text/json") - json_data, err := json.Marshal(data) - if err != nil { - errorResponse(response, "Internal encoding error") - } else { - response.Write(json_data) - } + response.SetHeader("Content-Type", "text/json") + json_data, err := json.Marshal(data) + if err != nil { + errorResponse(response, "Internal encoding error") + } else { + response.Write(json_data) + } } func RunBackEnd(config *config.Configuration) { - mux := http.NewServeMux() - mux.HandleFunc("/", indexHandler) - mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/")) - mux.HandleFunc("/service", serviceHandler) - mux.HandleFunc("/proxy", proxyHandler) + mux := http.NewServeMux() + mux.HandleFunc("/", indexHandler) + mux.Handle("/fe/", http.FileServer(kFrontEndFiles, "/fe/")) + mux.HandleFunc("/service", serviceHandler) + mux.HandleFunc("/proxy", proxyHandler) - gConfig = config + gConfig = config - error := http.ListenAndServe(fmt.Sprintf(":%d", config.Port), mux) - fmt.Printf("error %v", error) + error := http.ListenAndServe(fmt.Sprintf(":%d", config.Port), mux) + fmt.Printf("error %v", error) } diff --git a/src/tv_rename.go b/src/tv_rename.go index 4b8b23c..10982e6 100644 --- a/src/tv_rename.go +++ b/src/tv_rename.go @@ -10,163 +10,163 @@ package tv_rename import ( - "bufio" - "fmt" - "http" - "net" - "os" - "path" - "regexp" - "strconv" - "strings" + "bufio" + "fmt" + "http" + "net" + "os" + "path" + "regexp" + "strconv" + "strings" ) // Takes a full file path and renames the last path component as if it were a // TV episode. This performs the actual rename as well. func RenameEpisode(inPath string) (*string, os.Error) { - // Parse the filename into its components. - dirName, fileName := path.Split(inPath) - info := parseEpisodeName(fileName) - if info == nil { - return nil, os.NewError("Could not parse file name") - } - - // Create the URL and perform the lookup. - queryURL := buildURL(info) - response, err := performLookup(queryURL) - if err != nil { - return nil, err - } - - // Parse the response into the fullEpisodeInfo struct. - fullInfo := parseResponse(response) - - // Create the new path. - newName := fmt.Sprintf("%s - %dx%02d - %s", fullInfo.episode.showName, - fullInfo.episode.season, fullInfo.episode.episode, fullInfo.episodeName) - newName = strings.Replace(newName, "/", "_", -1) - newName += path.Ext(fileName) - newPath := path.Join(dirName, newName) - - return &newPath, nil + // Parse the filename into its components. + dirName, fileName := path.Split(inPath) + info := parseEpisodeName(fileName) + if info == nil { + return nil, os.NewError("Could not parse file name") + } + + // Create the URL and perform the lookup. + queryURL := buildURL(info) + response, err := performLookup(queryURL) + if err != nil { + return nil, err + } + + // Parse the response into the fullEpisodeInfo struct. + fullInfo := parseResponse(response) + + // Create the new path. + newName := fmt.Sprintf("%s - %dx%02d - %s", fullInfo.episode.showName, + fullInfo.episode.season, fullInfo.episode.episode, fullInfo.episodeName) + newName = strings.Replace(newName, "/", "_", -1) + newName += path.Ext(fileName) + newPath := path.Join(dirName, newName) + + return &newPath, nil } type episodeInfo struct { - showName string - season int - episode int + showName string + season int + episode int } type fullEpisodeInfo struct { - episode episodeInfo - episodeName string + episode episodeInfo + episodeName string } // Parses the last path component into a the component structure. func parseEpisodeName(name string) *episodeInfo { - regex := regexp.MustCompile("(.+)( |\\.)[sS]?([0-9]+)[xeXE]([0-9]+)") - matches := regex.FindAllStringSubmatch(name, -1) - if len(matches) < 1 || len(matches[0]) < 4 { - return nil - } - - // Convert the season and episode numbers to integers. - season, episode := convertEpisode(matches[0][3], matches[0][4]) - if season == 0 && season == episode { - return nil - } - - // If the separator between the show title and episode is a period, then - // it's likely of the form "some.show.name.s03e06.720p.blah.mkv", so strip the - // periods in the title. - var showName string = matches[0][1] - if matches[0][2] == "." { - showName = strings.Replace(matches[0][1], ".", " ", -1) - } - - return &episodeInfo { - showName, - season, - episode, - } + regex := regexp.MustCompile("(.+)( |\\.)[sS]?([0-9]+)[xeXE]([0-9]+)") + matches := regex.FindAllStringSubmatch(name, -1) + if len(matches) < 1 || len(matches[0]) < 4 { + return nil + } + + // Convert the season and episode numbers to integers. + season, episode := convertEpisode(matches[0][3], matches[0][4]) + if season == 0 && season == episode { + return nil + } + + // If the separator between the show title and episode is a period, then + // it's likely of the form "some.show.name.s03e06.720p.blah.mkv", so strip the + // periods in the title. + var showName string = matches[0][1] + if matches[0][2] == "." { + showName = strings.Replace(matches[0][1], ".", " ", -1) + } + + return &episodeInfo{ + showName, + season, + episode, + } } // Builds the URL to which we send a HTTP request to get the episode name. func buildURL(info *episodeInfo) string { - return fmt.Sprintf("http://services.tvrage.com/tools/quickinfo.php?show=%s&ep=%dx%d", - http.URLEscape(info.showName), info.season, info.episode) + return fmt.Sprintf("http://services.tvrage.com/tools/quickinfo.php?show=%s&ep=%dx%d", + http.URLEscape(info.showName), info.season, info.episode) } // Converts a season and episode to integers. If the return values are both 0, // an error occurred. func convertEpisode(season string, episode string) (int, int) { - seasonInt, err := strconv.Atoi(season) - if err != nil { - return 0, 0 - } - episodeInt, err := strconv.Atoi(episode) - if err != nil { - return 0, 0 - } - return seasonInt, episodeInt + seasonInt, err := strconv.Atoi(season) + if err != nil { + return 0, 0 + } + episodeInt, err := strconv.Atoi(episode) + if err != nil { + return 0, 0 + } + return seasonInt, episodeInt } // Performs the actual lookup and returns the HTTP response. func performLookup(urlString string) (*http.Response, os.Error) { - url, err := http.ParseURL(urlString) - if err != nil { - return nil, err - } - - // Open a TCP connection. - conn, err := net.Dial("tcp", "", url.Host + ":" + url.Scheme) - if err != nil { - return nil, err - } - - // Perform the HTTP request. - client := http.NewClientConn(conn, nil) - var request http.Request - request.URL = url - request.Method = "GET" - request.UserAgent = "Armadillo File Manager" - err = client.Write(&request) - if err != nil { - return nil, err - } - return client.Read(&request) + url, err := http.ParseURL(urlString) + if err != nil { + return nil, err + } + + // Open a TCP connection. + conn, err := net.Dial("tcp", "", url.Host+":"+url.Scheme) + if err != nil { + return nil, err + } + + // Perform the HTTP request. + client := http.NewClientConn(conn, nil) + var request http.Request + request.URL = url + request.Method = "GET" + request.UserAgent = "Armadillo File Manager" + err = client.Write(&request) + if err != nil { + return nil, err + } + return client.Read(&request) } // Parses the HTTP response from performLookup(). func parseResponse(response *http.Response) *fullEpisodeInfo { - var err os.Error - var line string - var info fullEpisodeInfo - - buf := bufio.NewReader(response.Body) - for ; err != os.EOF; line, err = buf.ReadString('\n') { - // An error ocurred while reading. - if err != nil { - return nil - } - var parts []string = strings.Split(line, "@", 2) - if len(parts) != 2 { - continue - } - switch parts[0] { - case "Show Name": - info.episode.showName = strings.TrimSpace(parts[1]) - case "Episode Info": - // Split the line, which is of the form: |SxE^Name^AirDate|. - parts = strings.Split(parts[1], "^", 3) - info.episodeName = parts[1] - // Split the episode string. - episode := strings.Split(parts[0], "x", 2) - info.episode.season, info.episode.episode = convertEpisode(episode[0], episode[1]) - if info.episode.season == 0 && info.episode.season == info.episode.episode { - return nil - } - } - } - return &info + var err os.Error + var line string + var info fullEpisodeInfo + + buf := bufio.NewReader(response.Body) + for ; err != os.EOF; line, err = buf.ReadString('\n') { + // An error ocurred while reading. + if err != nil { + return nil + } + var parts []string = strings.Split(line, "@", 2) + if len(parts) != 2 { + continue + } + switch parts[0] { + case "Show Name": + info.episode.showName = strings.TrimSpace(parts[1]) + case "Episode Info": + // Split the line, which is of the form: |SxE^Name^AirDate|. + parts = strings.Split(parts[1], "^", 3) + info.episodeName = parts[1] + // Split the episode string. + episode := strings.Split(parts[0], "x", 2) + info.episode.season, info.episode.episode = convertEpisode(episode[0], episode[1]) + if info.episode.season == 0 && info.episode.season == info.episode.episode { + return nil + } + } + } + return &info } -- 2.22.5