git.alexw.nyc home about git garden
    1
    2
    3
    4
    5
    6
    7
    8
    9
   10
   11
   12
   13
   14
   15
   16
   17
   18
   19
   20
   21
   22
   23
   24
   25
   26
   27
   28
   29
   30
   31
   32
   33
   34
   35
   36
   37
   38
   39
   40
   41
   42
   43
   44
   45
   46
   47
   48
   49
   50
   51
   52
   53
   54
   55
   56
   57
   58
   59
   60
   61
   62
   63
   64
   65
   66
   67
   68
   69
   70
   71
   72
   73
   74
   75
   76
   77
   78
   79
   80
   81
   82
   83
   84
   85
   86
   87
   88
   89
   90
   91
   92
   93
   94
   95
   96
   97
   98
   99
  100
  101
  102
  103
  104
  105
  106
  107
  108
  109
  110
  111
  112
  113
  114
  115
  116
  117
  118
  119
  120
  121
  122
  123
  124
  125
  126
  127
  128
  129
  130
  131
  132
  133
  134
  135
  136
  137
  138
  139
  140
  141
  142
  143
  144
  145
  146
  147
  148
  149
  150
  151
  152
  153
  154
  155
  156
  157
  158
  159
  160
  161
  162
  163
  164
  165
  166
  167
  168
  169
  170
  171
  172
  173
  174
  175
  176
  177
  178
  179
  180
  181
  182
  183
  184
  185
  186
  187
  188
  189
  190
  191
  192
  193
  194
  195
  196
  197
  198
  199
  200
  201
  202
  203
  204
  205
  206
  207
  208
  209
  210
  211
  212
  213
  214
  215
  216
  217
  218
  219
  220
  221
  222
  223
  224
  225
  226
  227
  228
  229
  230
  231
  232
  233
  234
  235
  236
  237
  238
  239
  240
  241
  242
  243
  244
  245
  246
  247
  248
  249
  250
  251
  252
  253
  254
  255
  256
  257
  258
  259
  260
  261
  262
  263
  264
  265
package main

import (
	"archive/zip"
	"bufio"
	"fmt"
	"io"
	"mime"
	"net"
	"os"
	"path"
	"path/filepath"
	"strings"
	"time"
	"unicode/utf8"
)

func getSchemedFlounderLinkLines(r io.Reader) []string {
	scanner := bufio.NewScanner(r)
	result := []string{}
	for scanner.Scan() {
		text := scanner.Text()
		// TODO use actual parser
		if strings.HasPrefix(text, "=>") && strings.Contains(text, "."+c.Host) && (strings.Contains(text, "gemini://") || strings.Contains(text, "https://")) {
			result = append(result, text)
		}
	}
	return result
}

func isOkUsername(s string) error {
	if len(s) < 1 {
		return fmt.Errorf("Username is too short")
	}
	if len(s) > 32 {
		return fmt.Errorf("Username is too long. 32 char max.")
	}
	for _, char := range s {
		if !strings.Contains(ok, strings.ToLower(string(char))) {
			return fmt.Errorf("Username contains invalid characters. Valid characters include lowercase letters, numbers, and hyphens.")
		}
	}
	for _, username := range bannedUsernames {
		if username == s {
			return fmt.Errorf("Username is not allowed.")
		}
	}
	return nil
}

// Check if it is a text file, first by checking mimetype, then by reading bytes
// Stolen from https://github.com/golang/tools/blob/master/godoc/util/util.go
func isTextFile(fullPath string) bool {
	isText := strings.HasPrefix(mime.TypeByExtension(path.Ext(fullPath)), "text")
	if isText {
		return true
	}
	const max = 1024 // at least utf8.UTFMax
	s := make([]byte, 1024)
	f, err := os.Open(fullPath)
	if os.IsNotExist(err) {
		return true // for the purposes of editing, we return true
	}
	n, err := f.Read(s)
	s = s[0:n]
	if err != nil {
		return false
	}
	f.Close()

	for i, c := range string(s) {
		if i+utf8.UTFMax > len(s) {
			// last char may be incomplete - ignore
			break
		}
		if c == 0xFFFD || c < ' ' && c != '\n' && c != '\t' && c != '\f' {
			// decoding error or control character - not a text file
			return false
		}
	}
	return true
}

// get the user-reltaive local path from the filespath
// NOTE -- dont use on unsafe input ( I think )
func getLocalPath(filesPath string) string {
	l := len(strings.Split(c.FilesDirectory, "/"))
	return strings.Join(strings.Split(filesPath, "/")[l+1:], "/")
}

func getCreator(filePath string) string {
	l := len(strings.Split(c.FilesDirectory, "/"))
	r := strings.Split(filePath, "/")[l]
	return r
}

func isGemini(filename string) bool {
	extension := path.Ext(filename)
	return extension == ".gmi" || extension == ".gemini"
}

const solarYearSecs = 31556926

func timeago(t *time.Time) string {
	d := time.Since(*t)
	var metric string
	var amount int
	if d.Seconds() < 60 {
		amount = int(d.Seconds())
		metric = "second"
	} else if d.Minutes() < 60 {
		amount = int(d.Minutes())
		metric = "minute"
	} else if d.Hours() < 24 {
		amount = int(d.Hours())
		metric = "hour"
	} else if d.Seconds() < solarYearSecs {
		amount = int(d.Hours()) / 24
		metric = "day"
	} else {
		amount = int(d.Seconds()) / solarYearSecs
		metric = "year"
	}
	if amount == 1 {
		return fmt.Sprintf("%d %s ago", amount, metric)
	} else {
		return fmt.Sprintf("%d %ss ago", amount, metric)
	}
}
func GetIPFromRemoteAddress(remoteAddress string) string {
	ip, _, err := net.SplitHostPort(remoteAddress)
	if err == nil {
		return ip
	}
	return remoteAddress
}

// safe
func getUserDirectory(username string) string {
	// extra filepath.clean just to be safe
	userFolder := path.Join(c.FilesDirectory, cleanPath(username))
	return userFolder
}

func safeGetFilePath(username string, filename string) string {
	return path.Join(getUserDirectory(username), cleanPath(filename))
}

// Safe
func cleanPath(thepath string) string {
	res := filepath.FromSlash(path.Clean("/" + strings.Trim(thepath, "/")))
	if strings.Contains(res, "..") { // sanity check
		return ""
	}
	return res
}

func dirSize(path string) (int64, error) {
	var size int64
	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			size += info.Size()
		}
		return err
	})
	return size, err
}

/// Perform some checks to make sure the file is OK to upload
func checkIfValidFile(username string, filename string, fileBytes []byte) error {
	if len(filename) == 0 {
		return fmt.Errorf("Please enter a filename")
	}
	if len(filename) > 256 { // arbitrarily chosen
		return fmt.Errorf("Filename is too long")
	}
	ext := strings.ToLower(path.Ext(filename))
	found := false
	for _, mimetype := range c.OkExtensions {
		if ext == mimetype {
			found = true
		}
	}
	if username == "alex" && ext == ".html" { // obviously a hack TODO
		found = true
	}
	if !found {
		return fmt.Errorf("Invalid file extension: %s", ext)
	}
	if len(fileBytes) > c.MaxFileBytes {
		return fmt.Errorf("File too large. File was %d bytes, Max file size is %d", len(fileBytes), c.MaxFileBytes)
	}
	userFolder := getUserDirectory(username)
	myFiles, err := getMyFilesRecursive(userFolder, username)
	if err != nil {
		return err
	}
	if len(myFiles) >= c.MaxFilesPerUser {
		return fmt.Errorf("You have reached the max number of files. Delete some before uploading")
	}
	size, err := dirSize(userFolder)
	if err != nil || size+int64(len(fileBytes)) > c.MaxUserBytes {
		return fmt.Errorf("You are out of storage space. Delete some files before continuing.")
	}
	return nil
}

func zipit(source string, target io.Writer) error {
	archive := zip.NewWriter(target)

	info, err := os.Stat(source)
	if err != nil {
		return nil
	}

	var baseDir string
	if info.IsDir() {
		baseDir = filepath.Base(source)
	}

	filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}

		if baseDir != "" {
			header.Name = filepath.Join(baseDir, strings.TrimPrefix(path, source))
		}

		if info.IsDir() {
			header.Name += "/"
		} else {
			header.Method = zip.Deflate
		}

		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}

		if info.IsDir() {
			return nil
		}

		file, err := os.Open(path)
		if err != nil {
			return err
		}
		defer file.Close()
		_, err = io.Copy(writer, file)
		return err
	})

	archive.Close()

	return err
}