aboutsummaryrefslogtreecommitdiff
path: root/util/proxy.go
blob: daa90b5ebc99ff9e764acf89b144cf6df959b144 (plain)
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
package util

import (
	"net/http"
	"net/url"
	"regexp"
	"time"

	"github.com/FChannel0/FChannel-Server/config"
)

func GetPathProxyType(path string) string {
	if config.TorProxy != "" {
		re := regexp.MustCompile(`(http://|http://)?(www.)?\w+\.onion`)
		onion := re.MatchString(path)

		if onion {
			return "tor"
		}
	}

	return "clearnet"
}

func MediaProxy(url string) string {
	re := regexp.MustCompile("(.+)?" + config.Domain + "(.+)?")
	if re.MatchString(url) {
		return url
	}

	re = regexp.MustCompile("(.+)?\\.onion(.+)?")
	if re.MatchString(url) {
		return url
	}

	config.MediaHashs[HashMedia(url)] = url

	return "/api/media?hash=" + HashMedia(url)
}

func RouteProxy(req *http.Request) (*http.Response, error) {
	var proxyType = GetPathProxyType(req.URL.Host)

	if proxyType == "tor" {
		proxyUrl, err := url.Parse("socks5://" + config.TorProxy)

		if err != nil {
			return nil, MakeError(err, "RouteProxy")
		}

		proxyTransport := &http.Transport{Proxy: http.ProxyURL(proxyUrl)}
		client := &http.Client{Transport: proxyTransport, Timeout: time.Second * 15}

		return client.Do(req)
	}

	return http.DefaultClient.Do(req)
}