Do not send errors as part of the JSON response anymore.
[armadillo.git] / server / server.go
1 //
2 // Armadillo File Manager
3 // Copyright (c) 2010-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 "encoding/json"
14 "fmt"
15 "github.com/rsesek/armadillo/config"
16 "io"
17 "net/http"
18 "os"
19 "path"
20 "runtime"
21 "strings"
22 )
23
24 var (
25 kFrontEndFiles string
26 gConfig *config.Configuration
27 )
28
29 func init() {
30 _, thisFile, _, ok := runtime.Caller(0)
31 if !ok {
32 panic("unable to get file information from runtime.Caller so the frontend files cannot be found")
33 }
34 // thisFile = /armadillo/server/server.go, so compute /armadillo/frontend/
35 kFrontEndFiles = path.Join(path.Dir(path.Dir(thisFile)), "frontend")
36 }
37
38 func indexHandler(rw http.ResponseWriter, request *http.Request) {
39 fd, err := os.Open(path.Join(kFrontEndFiles, "index.html"))
40 if err != nil {
41 fmt.Print("Error opening file ", err.Error(), "\n")
42 return
43 }
44 defer fd.Close()
45
46 rw.Header().Set("Content-Type", "text/html")
47 io.Copy(rw, fd)
48 }
49
50 type pathReseponse struct {
51 Path string `json:"path"`
52 }
53
54 func listService(rw http.ResponseWriter, req *http.Request) {
55 if !requestIsPOST(rw, req) {
56 return
57 }
58
59 files, err := ListPath(req.FormValue("path"))
60 if err != nil {
61 httpError(rw, err.Error(), http.StatusNotFound)
62 } else {
63 okResponse(rw, files)
64 }
65 }
66
67 func removeService(rw http.ResponseWriter, req *http.Request) {
68 if !requestIsPOST(rw, req) {
69 return
70 }
71
72 err := RemovePath(req.FormValue("path"))
73 if err != nil {
74 httpError(rw, err.Error(), http.StatusNotFound)
75 } else {
76 okResponse(rw, nil)
77 }
78 }
79
80 func moveService(rw http.ResponseWriter, req *http.Request) {
81 if !requestIsPOST(rw, req) {
82 return
83 }
84
85 source := req.FormValue("source")
86 target := req.FormValue("target")
87 err := MovePath(source, target)
88 if err != nil {
89 httpError(rw, err.Error(), http.StatusNotFound)
90 } else {
91 okResponse(rw, pathReseponse{target})
92 }
93 }
94
95 func mkdirService(rw http.ResponseWriter, req *http.Request) {
96 if !requestIsPOST(rw, req) {
97 return
98 }
99
100 path := req.FormValue("path")
101 err := MakeDir(path)
102 if err != nil {
103 httpError(rw, err.Error(), http.StatusUnauthorized)
104 } else {
105 okResponse(rw, pathReseponse{path})
106 }
107 }
108
109 func tvRenameService(rw http.ResponseWriter, req *http.Request) {
110 if !requestIsPOST(rw, req) {
111 return
112 }
113
114 newPath, err := RenameTVEpisode(req.FormValue("path"))
115 if err != nil {
116 httpError(rw, err.Error(), http.StatusBadRequest)
117 } else {
118 okResponse(rw, pathReseponse{newPath})
119 }
120 }
121
122 func downloadHandler(response http.ResponseWriter, request *http.Request) {
123 valid, fullPath := IsValidPath(request.FormValue("path"))
124 if valid {
125 info, _ := os.Lstat(fullPath) // Error is already checked by |valid|.
126 if info.IsDir() {
127 http.Error(response, "Path is a directory", http.StatusBadRequest)
128 } else {
129 http.ServeFile(response, request, fullPath)
130 }
131 } else {
132 http.NotFound(response, request)
133 }
134 }
135
136 func httpError(rw http.ResponseWriter, message string, code int) {
137 message = strings.Replace(message, gConfig.JailRoot, "/", -1)
138 rw.WriteHeader(code)
139 rw.Header().Set("Content-Type", "text/plain")
140 fmt.Fprint(rw, message)
141 }
142
143 func okResponse(rw http.ResponseWriter, data interface{}) {
144 rw.Header().Set("Content-Type", "application/json")
145 jsonData, err := json.Marshal(data)
146 if err != nil {
147 httpError(rw, "Internal error: " + err.Error(), 500)
148 } else {
149 rw.Write(jsonData)
150 }
151 }
152
153 func requestIsPOST(rw http.ResponseWriter, req *http.Request) bool {
154 if req.Method != "POST" {
155 httpError(rw, "Service requests must be sent via POST", http.StatusMethodNotAllowed)
156 return false
157 }
158 return true
159 }
160
161 func RunBackEnd(c *config.Configuration) {
162 gConfig = c
163
164 mux := http.NewServeMux()
165 mux.HandleFunc("/", indexHandler)
166 mux.Handle("/fe/", http.StripPrefix("/fe/", http.FileServer(http.Dir(kFrontEndFiles))))
167 mux.HandleFunc("/service/list", listService)
168 mux.HandleFunc("/service/move", moveService)
169 mux.HandleFunc("/service/remove", removeService)
170 mux.HandleFunc("/service/mkdir", mkdirService)
171 mux.HandleFunc("/service/tv_rename", tvRenameService)
172 mux.HandleFunc("/download", downloadHandler)
173
174 error := http.ListenAndServe(fmt.Sprintf(":%d", gConfig.Port), mux)
175 fmt.Printf("error %v", error)
176 }