Compare commits

..

3 Commits

14 changed files with 149 additions and 108 deletions

View File

@ -116,6 +116,7 @@ Flags:
--fallback serve files as application/octet-stream if no matching format is registered
-f, --filter enable filtering
--flash enable support for shockwave flash files (via ruffle.rs)
--fun adds a bit of excitement to your day
--handlers display registered handlers (for debugging)
-h, --help help for roulette
--images enable support for image files
@ -123,7 +124,7 @@ Flags:
--index-file string path to optional persistent index file
-i, --info expose informational endpoints
--max-file-count int skip directories with file counts above this value (default 2147483647)
--min-file-count int skip directories with file counts below this value (default 1)
--min-file-count int skip directories with file counts below this value
--page-length int pagination length for info pages
-p, --port int port to listen on (default 8080)
--prefix string root path for http handlers (for reverse proxying) (default "/")

View File

@ -72,21 +72,21 @@ func kill(path string, index *fileIndex) error {
return nil
}
func newFile(list []string, sortOrder string, regexes *regexes, formats *types.Types) (string, error) {
func newFile(list []string, sortOrder string, regexes *regexes, formats types.Types) (string, error) {
path, err := pickFile(list)
if err != nil {
return "", err
}
if sortOrder == "asc" || sortOrder == "desc" {
splitPath, length, err := split(path, regexes)
splitPath, err := split(path, regexes)
if err != nil {
return "", err
}
switch {
case sortOrder == "asc":
splitPath.number = fmt.Sprintf("%0*d", length, 1)
splitPath.number = fmt.Sprintf("%0*d", len(splitPath.number), 1)
path, err = tryExtensions(splitPath, formats)
if err != nil {
@ -118,8 +118,8 @@ func newFile(list []string, sortOrder string, regexes *regexes, formats *types.T
return path, nil
}
func nextFile(filePath, sortOrder string, regexes *regexes, formats *types.Types) (string, error) {
splitPath, _, err := split(filePath, regexes)
func nextFile(filePath, sortOrder string, regexes *regexes, formats types.Types) (string, error) {
splitPath, err := split(filePath, regexes)
if err != nil {
return "", err
}
@ -141,10 +141,10 @@ func nextFile(filePath, sortOrder string, regexes *regexes, formats *types.Types
return path, err
}
func tryExtensions(splitPath *splitPath, formats *types.Types) (string, error) {
func tryExtensions(splitPath *splitPath, formats types.Types) (string, error) {
var path string
for extension := range formats.Extensions {
for extension := range formats {
path = fmt.Sprintf("%s%s%s", splitPath.base, splitPath.number, extension)
exists, err := fileExists(path)
@ -198,7 +198,7 @@ func pathIsValid(path string, paths []string) bool {
}
}
func hasSupportedFiles(path string, formats *types.Types) (bool, error) {
func hasSupportedFiles(path string, formats types.Types) (bool, error) {
hasRegisteredFiles := make(chan bool, 1)
err := filepath.WalkDir(path, func(p string, info os.DirEntry, err error) error {
@ -229,7 +229,7 @@ func hasSupportedFiles(path string, formats *types.Types) (bool, error) {
}
}
func walkPath(path string, fileChannel chan<- string, stats *scanStatsChannels, formats *types.Types) error {
func walkPath(path string, fileChannel chan<- string, stats *scanStatsChannels, formats types.Types) error {
errorChannel := make(chan error)
done := make(chan bool, 1)
@ -321,7 +321,7 @@ Poll:
return nil
}
func scanPaths(paths []string, sort string, index *fileIndex, formats *types.Types) ([]string, error) {
func scanPaths(paths []string, sort string, index *fileIndex, formats types.Types) ([]string, error) {
var list []string
fileChannel := make(chan string)
@ -375,13 +375,13 @@ Poll:
case path := <-fileChannel:
list = append(list, path)
case stat := <-statsChannels.filesMatched:
stats.filesMatched = stats.filesMatched + stat
stats.filesMatched += stat
case stat := <-statsChannels.filesSkipped:
stats.filesSkipped = stats.filesSkipped + stat
stats.filesSkipped += stat
case stat := <-statsChannels.directoriesMatched:
stats.directoriesMatched = stats.directoriesMatched + stat
stats.directoriesMatched += stat
case stat := <-statsChannels.directoriesSkipped:
stats.directoriesSkipped = stats.directoriesSkipped + stat
stats.directoriesSkipped += stat
case err := <-errorChannel:
return []string{}, err
case <-done:
@ -409,7 +409,7 @@ Poll:
return list, nil
}
func fileList(paths []string, filters *filters, sort string, index *fileIndex, formats *types.Types) ([]string, error) {
func fileList(paths []string, filters *filters, sort string, index *fileIndex, formats types.Types) ([]string, error) {
switch {
case Index && !index.isEmpty() && filters.isEmpty():
return index.List(), nil
@ -493,7 +493,7 @@ func normalizePath(path string) (string, error) {
return absolutePath, nil
}
func validatePaths(args []string, formats *types.Types) ([]string, error) {
func validatePaths(args []string, formats types.Types) ([]string, error) {
var paths []string
for i := 0; i < len(args); i++ {

View File

@ -104,7 +104,10 @@ func (index *fileIndex) Export(path string) error {
enc := gob.NewEncoder(z)
index.mutex.RLock()
enc.Encode(&index.list)
err = enc.Encode(&index.list)
if err != nil {
return err
}
length := len(index.list)
index.mutex.RUnlock()
@ -139,12 +142,11 @@ func (index *fileIndex) Import(path string) error {
index.mutex.Lock()
err = dec.Decode(&index.list)
length := len(index.list)
index.mutex.Unlock()
if err != nil {
return err
}
length := len(index.list)
index.mutex.Unlock()
if Verbose {
fmt.Printf("%s | INDEX: Imported %d entries from %s in %s\n",
@ -158,7 +160,7 @@ func (index *fileIndex) Import(path string) error {
return nil
}
func serveIndexRebuild(args []string, index *fileIndex, formats *types.Types, errorChannel chan<- error) httprouter.Handle {
func serveIndexRebuild(args []string, index *fileIndex, formats types.Types, errorChannel chan<- error) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
index.clear()
@ -175,13 +177,13 @@ func serveIndexRebuild(args []string, index *fileIndex, formats *types.Types, er
}
}
func registerIndexHandlers(mux *httprouter.Router, args []string, index *fileIndex, formats *types.Types, errorChannel chan<- error) error {
func registerIndexHandlers(mux *httprouter.Router, args []string, index *fileIndex, formats types.Types, errorChannel chan<- error) error {
registerHandler(mux, Prefix+"/rebuild_index", serveIndexRebuild(args, index, formats, errorChannel))
return nil
}
func importIndex(args []string, index *fileIndex, formats *types.Types) error {
func importIndex(args []string, index *fileIndex, formats types.Types) error {
skipIndex := false
if IndexFile != "" {

View File

@ -137,7 +137,7 @@ func serveIndexHtml(args []string, index *fileIndex, shouldPaginate bool) httpro
htmlBody.WriteString(`</table></body></html>`)
b, err := io.WriteString(w, gohtml.Format(htmlBody.String()))
length, err := io.WriteString(w, gohtml.Format(htmlBody.String()))
if err != nil {
return
}
@ -145,7 +145,7 @@ func serveIndexHtml(args []string, index *fileIndex, shouldPaginate bool) httpro
if Verbose {
fmt.Printf("%s | SERVE: HTML index page (%s) to %s in %s\n",
startTime.Format(logDate),
humanReadableSize(b),
humanReadableSize(length),
realIP(r),
time.Since(startTime).Round(time.Microsecond),
)
@ -195,12 +195,15 @@ func serveIndexJson(args []string, index *fileIndex, errorChannel chan<- error)
return
}
w.Write(response)
written, err := w.Write(response)
if err != nil {
errorChannel <- err
}
if Verbose {
fmt.Printf("%s | SERVE: JSON index page (%s) to %s in %s\n",
startTime.Format(logDate),
humanReadableSize(len(response)),
humanReadableSize(written),
realIP(r),
time.Since(startTime).Round(time.Microsecond),
)
@ -208,20 +211,21 @@ func serveIndexJson(args []string, index *fileIndex, errorChannel chan<- error)
}
}
func serveAvailableExtensions() httprouter.Handle {
func serveAvailableExtensions(errorChannel chan<- error) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "text/plain")
startTime := time.Now()
response := []byte(types.SupportedFormats.GetExtensions())
w.Write(response)
written, err := w.Write([]byte(types.SupportedFormats.GetExtensions()))
if err != nil {
errorChannel <- err
}
if Verbose {
fmt.Printf("%s | SERVE: Available extension list (%s) to %s in %s\n",
startTime.Format(logDate),
humanReadableSize(len(response)),
humanReadableSize(written),
realIP(r),
time.Since(startTime).Round(time.Microsecond),
)
@ -229,20 +233,21 @@ func serveAvailableExtensions() httprouter.Handle {
}
}
func serveEnabledExtensions(formats *types.Types) httprouter.Handle {
func serveEnabledExtensions(formats types.Types, errorChannel chan<- error) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "text/plain")
startTime := time.Now()
response := []byte(formats.GetExtensions())
w.Write(response)
written, err := w.Write([]byte(formats.GetExtensions()))
if err != nil {
errorChannel <- err
}
if Verbose {
fmt.Printf("%s | SERVE: Registered extension list (%s) to %s in %s\n",
startTime.Format(logDate),
humanReadableSize(len(response)),
humanReadableSize(written),
realIP(r),
time.Since(startTime).Round(time.Microsecond),
)
@ -250,20 +255,21 @@ func serveEnabledExtensions(formats *types.Types) httprouter.Handle {
}
}
func serveAvailableMimeTypes() httprouter.Handle {
func serveAvailableMimeTypes(errorChannel chan<- error) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "text/plain")
startTime := time.Now()
response := []byte(types.SupportedFormats.GetMimeTypes())
w.Write(response)
written, err := w.Write([]byte(types.SupportedFormats.GetMimeTypes()))
if err != nil {
errorChannel <- err
}
if Verbose {
fmt.Printf("%s | SERVE: Available MIME type list (%s) to %s in %s\n",
startTime.Format(logDate),
humanReadableSize(len(response)),
humanReadableSize(written),
realIP(r),
time.Since(startTime).Round(time.Microsecond),
)
@ -271,20 +277,21 @@ func serveAvailableMimeTypes() httprouter.Handle {
}
}
func serveEnabledMimeTypes(formats *types.Types) httprouter.Handle {
func serveEnabledMimeTypes(formats types.Types, errorChannel chan<- error) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "text/plain")
startTime := time.Now()
response := []byte(formats.GetMimeTypes())
w.Write(response)
written, err := w.Write([]byte(formats.GetMimeTypes()))
if err != nil {
errorChannel <- err
}
if Verbose {
fmt.Printf("%s | SERVE: Registered MIME type list (%s) to %s in %s\n",
startTime.Format(logDate),
humanReadableSize(len(response)),
humanReadableSize(written),
realIP(r),
time.Since(startTime).Round(time.Microsecond),
)
@ -292,7 +299,7 @@ func serveEnabledMimeTypes(formats *types.Types) httprouter.Handle {
}
}
func registerInfoHandlers(mux *httprouter.Router, args []string, index *fileIndex, formats *types.Types, errorChannel chan<- error) {
func registerInfoHandlers(mux *httprouter.Router, args []string, index *fileIndex, formats types.Types, errorChannel chan<- error) {
if Index {
registerHandler(mux, Prefix+"/html", serveIndexHtml(args, index, false))
if PageLength != 0 {
@ -305,8 +312,8 @@ func registerInfoHandlers(mux *httprouter.Router, args []string, index *fileInde
}
}
registerHandler(mux, Prefix+"/available_extensions", serveAvailableExtensions())
registerHandler(mux, Prefix+"/enabled_extensions", serveEnabledExtensions(formats))
registerHandler(mux, Prefix+"/available_mime_types", serveAvailableMimeTypes())
registerHandler(mux, Prefix+"/enabled_mime_types", serveEnabledMimeTypes(formats))
registerHandler(mux, Prefix+"/available_extensions", serveAvailableExtensions(errorChannel))
registerHandler(mux, Prefix+"/enabled_extensions", serveEnabledExtensions(formats, errorChannel))
registerHandler(mux, Prefix+"/available_mime_types", serveAvailableMimeTypes(errorChannel))
registerHandler(mux, Prefix+"/enabled_mime_types", serveEnabledMimeTypes(formats, errorChannel))
}

View File

@ -12,7 +12,7 @@ import (
)
const (
ReleaseVersion string = "2.4.0"
ReleaseVersion string = "2.6.0"
)
var (
@ -26,6 +26,7 @@ var (
Fallback bool
Filtering bool
Flash bool
Fun bool
Handlers bool
Images bool
Index bool
@ -91,6 +92,7 @@ func init() {
rootCmd.Flags().BoolVar(&Fallback, "fallback", false, "serve files as application/octet-stream if no matching format is registered")
rootCmd.Flags().BoolVarP(&Filtering, "filter", "f", false, "enable filtering")
rootCmd.Flags().BoolVar(&Flash, "flash", false, "enable support for shockwave flash files (via ruffle.rs)")
rootCmd.Flags().BoolVar(&Fun, "fun", false, "adds a bit of excitement to your day")
rootCmd.Flags().BoolVar(&Handlers, "handlers", false, "display registered handlers (for debugging)")
rootCmd.Flags().BoolVar(&Images, "images", false, "enable support for image files")
rootCmd.Flags().BoolVar(&Index, "index", false, "generate index of supported file paths at startup")

View File

@ -17,41 +17,35 @@ type splitPath struct {
}
func (splitPath *splitPath) increment() {
length := len(splitPath.number)
asInt, err := strconv.Atoi(splitPath.number)
if err != nil {
return
}
splitPath.number = fmt.Sprintf("%0*d", length, asInt+1)
splitPath.number = fmt.Sprintf("%0*d", len(splitPath.number), asInt+1)
}
func (splitPath *splitPath) decrement() {
length := len(splitPath.number)
asInt, err := strconv.Atoi(splitPath.number)
if err != nil {
return
}
splitPath.number = fmt.Sprintf("%0*d", length, asInt-1)
splitPath.number = fmt.Sprintf("%0*d", len(splitPath.number), asInt-1)
}
func split(path string, regexes *regexes) (*splitPath, int, error) {
p := splitPath{}
func split(path string, regexes *regexes) (*splitPath, error) {
split := regexes.filename.FindAllStringSubmatch(path, -1)
if len(split) < 1 || len(split[0]) < 3 {
return &splitPath{}, 0, nil
return &splitPath{}, nil
}
p.base = split[0][1]
p := &splitPath{
base: split[0][1],
number: split[0][2],
extension: split[0][3],
}
p.number = split[0][2]
p.extension = split[0][3]
return &p, len(p.number), nil
return p, nil
}

View File

@ -153,7 +153,7 @@ func serveStaticFile(paths []string, index *fileIndex, errorChannel chan<- error
}
}
func serveRoot(paths []string, regexes *regexes, index *fileIndex, formats *types.Types, errorChannel chan<- error) httprouter.Handle {
func serveRoot(paths []string, regexes *regexes, index *fileIndex, formats types.Types, errorChannel chan<- error) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
refererUri, err := stripQueryParams(refererToUri(r.Referer()))
if err != nil {
@ -236,7 +236,7 @@ func serveRoot(paths []string, regexes *regexes, index *fileIndex, formats *type
}
}
func serveMedia(paths []string, regexes *regexes, index *fileIndex, formats *types.Types, errorChannel chan<- error) httprouter.Handle {
func serveMedia(paths []string, regexes *regexes, index *fileIndex, formats types.Types, errorChannel chan<- error) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
filters := &filters{
included: splitQueryParams(r.URL.Query().Get("include"), regexes),
@ -433,34 +433,32 @@ func ServePage(args []string) error {
return errors.New("invalid bind address provided")
}
formats := &types.Types{
Extensions: make(map[string]types.Type),
}
formats := make(types.Types)
if Audio || All {
formats.Add(audio.Format{})
formats.Add(audio.Format{Fun: Fun})
}
if Code || All {
formats.Add(code.Format{Theme: CodeTheme})
formats.Add(code.Format{Fun: Fun, Theme: CodeTheme})
}
if Flash || All {
formats.Add(flash.Format{})
formats.Add(flash.Format{Fun: Fun})
}
if Text || All {
formats.Add(text.Format{})
formats.Add(text.Format{Fun: Fun})
}
if Videos || All {
formats.Add(video.Format{})
formats.Add(video.Format{Fun: Fun})
}
// enable image support if no other flags are passed, to retain backwards compatibility
// to be replaced with rootCmd.MarkFlagsOneRequired on next spf13/cobra update
if Images || All || len(formats.Extensions) == 0 {
formats.Add(images.Format{})
if Images || All || len(formats) == 0 {
formats.Add(images.Format{Fun: Fun})
}
paths, err := validatePaths(args, formats)

View File

@ -11,7 +11,9 @@ import (
"seedno.de/seednode/roulette/types"
)
type Format struct{}
type Format struct {
Fun bool
}
func (t Format) Css() string {
var css strings.Builder

View File

@ -20,6 +20,7 @@ import (
)
type Format struct {
Fun bool
Theme string
}
@ -56,6 +57,9 @@ func (t Format) Css() string {
css.WriteString("html{height:100%;width:100%;}\n")
css.WriteString("a{bottom:0;left:0;position:absolute;right:0;top:0;margin:1rem;padding:0;height:99%;width:99%;color:inherit;text-decoration:none;}\n")
if t.Fun {
css.WriteString("body{font-family: \"Comic Sans MS\", cursive, \"Brush Script MT\", sans-serif;}\n")
}
return css.String()
}

View File

@ -11,7 +11,9 @@ import (
"seedno.de/seednode/roulette/types"
)
type Format struct{}
type Format struct {
Fun bool
}
func (t Format) Css() string {
var css strings.Builder

View File

@ -11,6 +11,7 @@ import (
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"math/rand"
"os"
"strings"
@ -24,7 +25,9 @@ type dimensions struct {
height int
}
type Format struct{}
type Format struct {
Fun bool
}
func (t Format) Css() string {
var css strings.Builder
@ -32,7 +35,17 @@ func (t Format) Css() string {
css.WriteString(`html,body{margin:0;padding:0;height:100%;}`)
css.WriteString(`a{color:inherit;display:block;height:100%;width:100%;text-decoration:none;}`)
css.WriteString(`img{margin:auto;display:block;max-width:97%;max-height:97%;`)
css.WriteString(`object-fit:scale-down;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);}`)
css.WriteString(`object-fit:scale-down;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)`)
if t.Fun {
rotate := rand.Intn(360)
css.WriteString(fmt.Sprintf(" rotate(%ddeg);", rotate))
css.WriteString(fmt.Sprintf("-ms-transform:rotate(%ddeg);", rotate))
css.WriteString(fmt.Sprintf("-webkit-transform:rotate(%ddeg);", rotate))
css.WriteString(fmt.Sprintf("-moz-transform:rotate(%ddeg);", rotate))
css.WriteString(fmt.Sprintf("-o-transform:rotate(%ddeg)", rotate))
}
css.WriteString(`;}`)
return css.String()
}

View File

@ -14,7 +14,9 @@ import (
"seedno.de/seednode/roulette/types"
)
type Format struct{}
type Format struct {
Fun bool
}
func (t Format) Css() string {
var css strings.Builder

View File

@ -10,35 +10,47 @@ import (
"strings"
)
var SupportedFormats = &Types{
Extensions: make(map[string]Type),
}
var SupportedFormats = make(Types)
type Type interface {
// Returns either "inline" or "embed", depending on whether the file
// should be displayed inline (e.g. code) or embedded (e.g. images)
Type() string
// Returns a CSS string used to format the corresponding page
Css() string
// Returns an HTML <title> element for the specified file
Title(rootUrl, fileUri, filePath, fileName, prefix, mime string) (string, error)
// Returns an HTML <body> element used to display the specified file
Body(rootUrl, fileUri, filePath, fileName, prefix, mime string) (string, error)
// Returns a map of file extensions to MIME type strings.
Extensions() map[string]string
MimeType(string) string
// Given a file extension, returns the corresponding MIME type,
// if one exists. Otherwise, returns an empty string.
MimeType(extension string) string
// Optional function used to validate whether a given file matches this format.
// If no validation checks are needed, this function should always return true.
Validate(filePath string) bool
}
type Types struct {
Extensions map[string]Type
}
type Types map[string]Type
func (t *Types) Add(format Type) {
func (t Types) Add(format Type) {
for k := range format.Extensions() {
_, exists := t.Extensions[k]
_, exists := t[k]
if !exists {
t.Extensions[k] = format
t[k] = format
}
}
}
func (t *Types) FileType(path string) Type {
fileType, exists := t.Extensions[filepath.Ext(path)]
func (t Types) FileType(path string) Type {
fileType, exists := t[filepath.Ext(path)]
if exists {
return fileType
}
@ -46,12 +58,12 @@ func (t *Types) FileType(path string) Type {
return nil
}
func (t *Types) Register(format Type) {
func (t Types) Register(format Type) {
t.Add(format)
}
func (t *Types) Validate(path string) bool {
format, exists := t.Extensions[filepath.Ext(path)]
func (t Types) Validate(path string) bool {
format, exists := t[filepath.Ext(path)]
if !exists {
return false
}
@ -59,14 +71,14 @@ func (t *Types) Validate(path string) bool {
return format.Validate(path)
}
func (t *Types) GetExtensions() string {
func (t Types) GetExtensions() string {
var output strings.Builder
extensions := make([]string, len(t.Extensions))
extensions := make([]string, len(t))
i := 0
for k := range t.Extensions {
for k := range t {
extensions[i] = k
i++
}
@ -80,12 +92,12 @@ func (t *Types) GetExtensions() string {
return output.String()
}
func (t *Types) GetMimeTypes() string {
func (t Types) GetMimeTypes() string {
var output strings.Builder
var mimeTypes []string
for _, j := range t.Extensions {
for _, j := range t {
extensions := j.Extensions()
for _, v := range extensions {
mimeTypes = append(mimeTypes, v)

View File

@ -12,7 +12,9 @@ import (
"seedno.de/seednode/roulette/types"
)
type Format struct{}
type Format struct {
Fun bool
}
func (t Format) Css() string {
var css strings.Builder