Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ef1b43ac62 | ||
|
|
39e5821760 | ||
|
|
cb68cb004e | ||
|
|
eb6bb93500 | ||
|
|
d0df93ebac | ||
|
|
8c41d8ccd9 | ||
|
|
e9753ffdc7 |
No files matched your search
+1
-1
@@ -2,7 +2,7 @@ os: linux
|
||||
dist: xenial
|
||||
language: go
|
||||
go:
|
||||
- 1.11.x
|
||||
- 1.15.x
|
||||
|
||||
env:
|
||||
global:
|
||||
|
||||
@@ -46,6 +46,15 @@ type APIResponse struct {
|
||||
Data *ResponseData `json:"data"`
|
||||
}
|
||||
|
||||
// APIError wraps errors returned by LBRY API server to discern them from other kinds (like http errors).
|
||||
type APIError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e APIError) Error() string {
|
||||
return fmt.Sprintf("api error: %v", e.Err)
|
||||
}
|
||||
|
||||
// ResponseData is a map containing parsed json response.
|
||||
type ResponseData map[string]interface{}
|
||||
|
||||
@@ -110,6 +119,9 @@ func (c Client) doCall(url string, payload string) ([]byte, error) {
|
||||
if err != nil {
|
||||
return body, err
|
||||
}
|
||||
if r.StatusCode >= 500 {
|
||||
return body, fmt.Errorf("server returned non-OK status: %v", r.StatusCode)
|
||||
}
|
||||
defer r.Body.Close()
|
||||
return ioutil.ReadAll(r.Body)
|
||||
}
|
||||
@@ -133,16 +145,17 @@ func (c Client) Call(object, method string, params map[string]interface{}) (Resp
|
||||
return rd, err
|
||||
}
|
||||
if !ar.Success {
|
||||
return rd, errors.New(*ar.Error)
|
||||
return rd, APIError{errors.New(*ar.Error)}
|
||||
}
|
||||
return *ar.Data, err
|
||||
}
|
||||
|
||||
// UserMe returns user details for the user associated with the current auth_token
|
||||
// UserMe returns user details for the user associated with the current auth_token.
|
||||
func (c Client) UserMe() (ResponseData, error) {
|
||||
return c.Call(userObjectPath, userMeMethod, map[string]interface{}{})
|
||||
}
|
||||
|
||||
// UserHasVerifiedEmail calls has_verified_email method.
|
||||
func (c Client) UserHasVerifiedEmail() (ResponseData, error) {
|
||||
return c.Call(userObjectPath, userHasVerifiedEmailMethod, map[string]interface{}{})
|
||||
}
|
||||
@@ -7,42 +7,26 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestUserMeWrongToken(t *testing.T) {
|
||||
c := NewClient("abc", nil)
|
||||
r, err := c.UserMe()
|
||||
require.NotNil(t, err)
|
||||
assert.Equal(t, "could not authenticate user", err.Error())
|
||||
assert.Nil(t, r)
|
||||
}
|
||||
|
||||
func TestUserHasVerifiedEmailWrongToken(t *testing.T) {
|
||||
c := NewClient("abc", nil)
|
||||
r, err := c.UserHasVerifiedEmail()
|
||||
require.NotNil(t, err)
|
||||
assert.Equal(t, "could not authenticate user", err.Error())
|
||||
assert.Nil(t, r)
|
||||
}
|
||||
|
||||
func launchDummyServer(lastReq **http.Request, path, response string) *httptest.Server {
|
||||
func launchDummyServer(lastReq **http.Request, path, response string, status int) *httptest.Server {
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
*lastReq = &*r
|
||||
if lastReq != nil {
|
||||
*lastReq = &*r
|
||||
}
|
||||
if r.URL.Path != path {
|
||||
fmt.Printf("path doesn't match: %v != %v", r.URL.Path, path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.WriteHeader(status)
|
||||
w.Write([]byte(response))
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
func TestUserMe(t *testing.T) {
|
||||
var req *http.Request
|
||||
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse)
|
||||
ts := launchDummyServer(nil, makeMethodPath(userObjectPath, userMeMethod), userMeResponse, http.StatusOK)
|
||||
defer ts.Close()
|
||||
|
||||
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
|
||||
@@ -52,8 +36,7 @@ func TestUserMe(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUserHasVerifiedEmail(t *testing.T) {
|
||||
var req *http.Request
|
||||
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userHasVerifiedEmailMethod), userHasVerifiedEmailResponse)
|
||||
ts := launchDummyServer(nil, makeMethodPath(userObjectPath, userHasVerifiedEmailMethod), userHasVerifiedEmailResponse, http.StatusOK)
|
||||
defer ts.Close()
|
||||
|
||||
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL})
|
||||
@@ -65,7 +48,7 @@ func TestUserHasVerifiedEmail(t *testing.T) {
|
||||
|
||||
func TestRemoteIP(t *testing.T) {
|
||||
var req *http.Request
|
||||
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse)
|
||||
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userMeMethod), userMeResponse, http.StatusOK)
|
||||
defer ts.Close()
|
||||
|
||||
c := NewClient("realToken", &ClientOpts{ServerAddress: ts.URL, RemoteIP: "8.8.8.8"})
|
||||
@@ -74,6 +57,34 @@ func TestRemoteIP(t *testing.T) {
|
||||
assert.Equal(t, []string{"8.8.8.8"}, req.Header["X-Forwarded-For"])
|
||||
}
|
||||
|
||||
func TestWrongToken(t *testing.T) {
|
||||
c := NewClient("zcasdasc", nil)
|
||||
|
||||
r, err := c.UserHasVerifiedEmail()
|
||||
assert.Nil(t, r)
|
||||
assert.EqualError(t, err, "api error: could not authenticate user")
|
||||
assert.ErrorAs(t, err, &APIError{})
|
||||
}
|
||||
|
||||
func TestHTTPError(t *testing.T) {
|
||||
c := NewClient("zcasdasc", &ClientOpts{ServerAddress: "http://lolcathost"})
|
||||
|
||||
r, err := c.UserHasVerifiedEmail()
|
||||
assert.Nil(t, r)
|
||||
assert.EqualError(t, err, `Post "http://lolcathost/user/has_verified_email": dial tcp: lookup lolcathost: no such host`)
|
||||
}
|
||||
|
||||
func TestGatewayError(t *testing.T) {
|
||||
var req *http.Request
|
||||
ts := launchDummyServer(&req, makeMethodPath(userObjectPath, userHasVerifiedEmailMethod), "", http.StatusBadGateway)
|
||||
defer ts.Close()
|
||||
c := NewClient("zcasdasc", &ClientOpts{ServerAddress: ts.URL})
|
||||
|
||||
r, err := c.UserHasVerifiedEmail()
|
||||
assert.Nil(t, r)
|
||||
assert.EqualError(t, err, `server returned non-OK status: 502`)
|
||||
}
|
||||
|
||||
const userMeResponse = `{
|
||||
"success": true,
|
||||
"error": null,
|
||||
|
||||
@@ -34,7 +34,7 @@ require (
|
||||
github.com/smartystreets/assertions v1.0.1 // indirect
|
||||
github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337 // indirect
|
||||
github.com/spf13/cast v1.3.0
|
||||
github.com/stretchr/testify v1.4.0
|
||||
github.com/stretchr/testify v1.7.0
|
||||
github.com/ybbus/jsonrpc v0.0.0-20180411222309-2a548b7d822d
|
||||
go.uber.org/atomic v1.4.0
|
||||
golang.org/x/crypto v0.0.0-20191002192127-34f69633bfdc
|
||||
@@ -51,4 +51,4 @@ require (
|
||||
gotest.tools v2.2.0+incompatible
|
||||
)
|
||||
|
||||
go 1.13
|
||||
go 1.15
|
||||
@@ -63,13 +63,10 @@ github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORN
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/lbryio/lbry.go v1.1.2 h1:Dyxc+glT/rVWJwHfIf7vjlPYYbjzrQz5ARmJd5Hp69c=
|
||||
github.com/lbryio/lbrycrd.go v0.0.0-20200203050410-e1076f12bf19 h1:/zWD8dVIl7bV1TdJWqPqy9tpqixzX2Qxgit48h3hQcY=
|
||||
github.com/lbryio/lbrycrd.go v0.0.0-20200203050410-e1076f12bf19/go.mod h1:wVuoA8VJLEcwgqHBwHmzLRazpKxTv13Px/pDuV7OomQ=
|
||||
github.com/lbryio/ozzo-validation v0.0.0-20170323141101-d1008ad1fd04 h1:Nze+C2HbeKvhjI/kVn+9Poj/UuEW5sOQxcsxqO7L3GI=
|
||||
github.com/lbryio/ozzo-validation v0.0.0-20170323141101-d1008ad1fd04/go.mod h1:fbG/dzobG8r95KzMwckXiLMHfFjZaBRQqC9hPs2XAQ4=
|
||||
github.com/lbryio/types v0.0.0-20191009145016-1bb8107e04f8 h1:jSNW/rK6DQsz7Zh+iv1zR384PeQdHt0gS4hKY17tkuM=
|
||||
github.com/lbryio/types v0.0.0-20191009145016-1bb8107e04f8/go.mod h1:CG3wsDv5BiVYQd5i1Jp7wGsaVyjZTJshqXeWMVKsISE=
|
||||
github.com/lbryio/types v0.0.0-20201019032447-f0b4476ef386 h1:JOQkGpeCM9FWkEHRx+kRPqySPCXElNW1em1++7tVS4M=
|
||||
github.com/lbryio/types v0.0.0-20201019032447-f0b4476ef386/go.mod h1:CG3wsDv5BiVYQd5i1Jp7wGsaVyjZTJshqXeWMVKsISE=
|
||||
github.com/lyoshenka/bencode v0.0.0-20180323155644-b7abd7672df5 h1:mG83tLXWSRdcXMWfkoumVwhcCbf3jHF9QKv/m37BkM0=
|
||||
@@ -109,8 +106,8 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/ybbus/jsonrpc v0.0.0-20180411222309-2a548b7d822d h1:tQo6hjclyv3RHUgZOl6iWb2Y44A/sN9bf9LAYfuioEg=
|
||||
github.com/ybbus/jsonrpc v0.0.0-20180411222309-2a548b7d822d/go.mod h1:XJrh1eMSzdIYFbM08flv0wp5G35eRniyeGut1z+LSiE=
|
||||
go.uber.org/atomic v1.4.0 h1:cxzIVoETapQEqDhQu3QfnvXAV4AlzcvUCxkVUFw3+EU=
|
||||
@@ -173,9 +170,10 @@ gopkg.in/nullbio/null.v6 v6.0.0-20161116030900-40264a2e6b79/go.mod h1:gWkaRU7CoX
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo=
|
||||
gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ dist: trusty
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.10.3
|
||||
- 1.15.x
|
||||
|
||||
script:
|
||||
- ./build_and_test.sh
|
||||
@@ -24,9 +24,9 @@ const lbrycrdTestnet = "lbrycrd_testnet"
|
||||
const lbrycrdRegtest = "lbrycrd_regtest"
|
||||
|
||||
var addressPrefixes = map[string][2]byte{
|
||||
lbrycrdMain: [2]byte{lbrycrdMainPubkeyPrefix, lbrycrdMainScriptPrefix},
|
||||
lbrycrdTestnet: [2]byte{lbrycrdTestnetPubkeyPrefix, lbrycrdTestnetScriptPrefix},
|
||||
lbrycrdRegtest: [2]byte{lbrycrdRegtestPubkeyPrefix, lbrycrdRegtestScriptPrefix},
|
||||
lbrycrdMain: {lbrycrdMainPubkeyPrefix, lbrycrdMainScriptPrefix},
|
||||
lbrycrdTestnet: {lbrycrdTestnetPubkeyPrefix, lbrycrdTestnetScriptPrefix},
|
||||
lbrycrdRegtest: {lbrycrdRegtestPubkeyPrefix, lbrycrdRegtestScriptPrefix},
|
||||
}
|
||||
|
||||
func PrefixIsValid(address [addressLength]byte, blockchainName string) bool {
|
||||
|
||||
+347
@@ -0,0 +1,347 @@
|
||||
package url
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const regexPartProtocol = "^((?:lbry://|https://)?)"
|
||||
const regexPartHost = "((?:open.lbry.com/|lbry.tv/|lbry.lat/|lbry.fr/|lbry.in/)?)"
|
||||
const regexPartStreamOrChannelName = "([^:$#/]*)"
|
||||
const regexPartModifierSeparator = "([:$#]?)([^/]*)"
|
||||
const regexQueryStringBreaker = "^([\\S]+)([?][\\S]*)"
|
||||
const urlComponentsSize = 9
|
||||
|
||||
const ChannelNameMinLength = 1
|
||||
const ClaimIdMaxLength = 40
|
||||
const ProtoDefault = "lbry://"
|
||||
const RegexClaimId = "(?i)^[0-9a-f]+$"
|
||||
const RegexInvalidUri = "(?i)[ =&#:$@%?;/\\\\\\\\\\\"<>%\\\\{\\\\}|^~\\\\[\\\\]`\\u0000-\\u0008\\u000b-\\u000c\\u000e-\\u001F\\uD800-\\uDFFF\\uFFFE-\\uFFFF]"
|
||||
|
||||
type LbryUri struct {
|
||||
Path string
|
||||
IsChannel bool
|
||||
StreamName string
|
||||
StreamClaimId string
|
||||
ChannelName string
|
||||
ChannelClaimId string
|
||||
PrimaryClaimSequence int
|
||||
SecondaryClaimSequence int
|
||||
PrimaryBidPosition int
|
||||
SecondaryBidPosition int
|
||||
ClaimName string
|
||||
ClaimId string
|
||||
ContentName string
|
||||
QueryString string
|
||||
}
|
||||
|
||||
type UriModifier struct {
|
||||
ClaimId string
|
||||
ClaimSequence int
|
||||
BidPosition int
|
||||
}
|
||||
|
||||
func (uri LbryUri) IsChannelUrl() bool {
|
||||
return (!isEmpty(uri.ChannelName) && isEmpty(uri.StreamName)) || (!isEmpty(uri.ClaimName) && strings.HasPrefix(uri.ClaimName, "@"))
|
||||
}
|
||||
|
||||
func (uri LbryUri) IsNameValid(name string) bool {
|
||||
return !regexp.MustCompile(RegexInvalidUri).MatchString(name)
|
||||
}
|
||||
|
||||
func (uri LbryUri) String() string {
|
||||
return uri.Build(true, ProtoDefault, false)
|
||||
}
|
||||
|
||||
func (uri LbryUri) VanityString() string {
|
||||
return uri.Build(true, ProtoDefault, true)
|
||||
}
|
||||
|
||||
func (uri LbryUri) TvString() string {
|
||||
return uri.Build(true, "https://lbry.tv/", false)
|
||||
}
|
||||
|
||||
func (uri LbryUri) Build(includeProto bool, protocol string, vanity bool) string {
|
||||
formattedChannelName := ""
|
||||
if !isEmpty(uri.ChannelName) {
|
||||
formattedChannelName = uri.ChannelName
|
||||
if !strings.HasPrefix(formattedChannelName, "@") {
|
||||
formattedChannelName = fmt.Sprintf("@%s", formattedChannelName)
|
||||
}
|
||||
}
|
||||
primaryClaimName := uri.ClaimName
|
||||
if isEmpty(primaryClaimName) {
|
||||
primaryClaimName = uri.ContentName
|
||||
}
|
||||
if isEmpty(primaryClaimName) {
|
||||
primaryClaimName = formattedChannelName
|
||||
}
|
||||
if isEmpty(primaryClaimName) {
|
||||
primaryClaimName = uri.StreamName
|
||||
}
|
||||
|
||||
primaryClaimId := uri.ClaimId
|
||||
if isEmpty(primaryClaimId) {
|
||||
if !isEmpty(formattedChannelName) {
|
||||
primaryClaimId = uri.ChannelClaimId
|
||||
} else {
|
||||
primaryClaimId = uri.StreamClaimId
|
||||
}
|
||||
}
|
||||
|
||||
var sb strings.Builder
|
||||
if includeProto {
|
||||
sb.WriteString(protocol)
|
||||
}
|
||||
sb.WriteString(primaryClaimName)
|
||||
if vanity {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
secondaryClaimName := ""
|
||||
if isEmpty(uri.ClaimName) && !isEmpty(uri.ContentName) {
|
||||
secondaryClaimName = uri.ContentName
|
||||
}
|
||||
if isEmpty(secondaryClaimName) {
|
||||
if !isEmpty(formattedChannelName) {
|
||||
secondaryClaimName = uri.StreamName
|
||||
}
|
||||
}
|
||||
secondaryClaimId := ""
|
||||
if !isEmpty(secondaryClaimName) {
|
||||
secondaryClaimId = uri.StreamClaimId
|
||||
}
|
||||
|
||||
if !isEmpty(primaryClaimId) {
|
||||
sb.WriteString("#")
|
||||
sb.WriteString(primaryClaimId)
|
||||
} else if uri.PrimaryClaimSequence > 0 {
|
||||
sb.WriteString(":")
|
||||
sb.WriteString(strconv.Itoa(uri.PrimaryClaimSequence))
|
||||
} else if uri.PrimaryBidPosition > 0 {
|
||||
sb.WriteString("$")
|
||||
sb.WriteString(strconv.Itoa(uri.PrimaryBidPosition))
|
||||
}
|
||||
|
||||
if !isEmpty(secondaryClaimName) {
|
||||
sb.WriteString("/")
|
||||
sb.WriteString(secondaryClaimName)
|
||||
}
|
||||
|
||||
if !isEmpty(secondaryClaimId) {
|
||||
sb.WriteString("#")
|
||||
sb.WriteString(secondaryClaimId)
|
||||
} else if uri.SecondaryClaimSequence > 0 {
|
||||
sb.WriteString(":")
|
||||
sb.WriteString(strconv.Itoa(uri.SecondaryClaimSequence))
|
||||
} else if uri.SecondaryBidPosition > 0 {
|
||||
sb.WriteString("$")
|
||||
sb.WriteString(strconv.Itoa(uri.SecondaryBidPosition))
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
func Parse(url string, requireProto bool) (*LbryUri, error) {
|
||||
if isEmpty(url) {
|
||||
return nil, errors.New("invalid url parameter")
|
||||
}
|
||||
|
||||
reComponents := regexp.MustCompile(
|
||||
fmt.Sprintf("(?i)%s%s%s%s(/?)%s%s",
|
||||
regexPartProtocol,
|
||||
regexPartHost,
|
||||
regexPartStreamOrChannelName,
|
||||
regexPartModifierSeparator,
|
||||
regexPartStreamOrChannelName,
|
||||
regexPartModifierSeparator))
|
||||
reSeparateQueryString := regexp.MustCompile(regexQueryStringBreaker)
|
||||
|
||||
cleanUrl := url
|
||||
queryString := ""
|
||||
|
||||
qsMatches := reSeparateQueryString.FindStringSubmatch(url)
|
||||
if len(qsMatches) == 3 {
|
||||
cleanUrl = qsMatches[1]
|
||||
queryString = qsMatches[2][1:]
|
||||
}
|
||||
|
||||
var components []string
|
||||
componentMatches := reComponents.FindStringSubmatch(cleanUrl)
|
||||
for _, component := range componentMatches[1:] {
|
||||
components = append(components, component)
|
||||
}
|
||||
if len(components) != urlComponentsSize {
|
||||
return nil, errors.New("regular expression error occurred while trying to Parse the value")
|
||||
}
|
||||
|
||||
/*
|
||||
* components[0] = proto
|
||||
* components[1] = host
|
||||
* components[2] = streamName or channelName
|
||||
* components[3] = primaryModSeparator
|
||||
* components[4] = primaryModValue
|
||||
* components[5] = path separator
|
||||
* components[6] = possibleStreamName
|
||||
* components[7] = secondaryModSeparator
|
||||
* components[8] = secondaryModValue
|
||||
*/
|
||||
if requireProto && isEmpty(components[0]) {
|
||||
return nil, errors.New("url must include a protocol prefix (lbry://)")
|
||||
}
|
||||
if isEmpty(components[2]) {
|
||||
return nil, errors.New("url does not include a name")
|
||||
}
|
||||
for _, component := range components[2:] {
|
||||
if strings.Index(component, " ") > -1 {
|
||||
return nil, errors.New("url cannot include a space")
|
||||
}
|
||||
}
|
||||
|
||||
streamOrChannelName := components[2]
|
||||
primaryModSeparator := components[3]
|
||||
primaryModValue := components[4]
|
||||
possibleStreamName := components[6]
|
||||
secondaryModSeparator := components[7]
|
||||
secondaryModValue := components[8]
|
||||
primaryClaimId := ""
|
||||
primaryClaimSequence := -1
|
||||
primaryBidPosition := -1
|
||||
secondaryClaimSequence := -1
|
||||
secondaryBidPosition := -1
|
||||
|
||||
includesChannel := strings.HasPrefix(streamOrChannelName, "@")
|
||||
isChannel := includesChannel && isEmpty(possibleStreamName)
|
||||
channelName := ""
|
||||
if includesChannel && len(streamOrChannelName) > 1 {
|
||||
channelName = streamOrChannelName[1:]
|
||||
}
|
||||
|
||||
// Convert the mod separators when parsing with protocol https://lbry.tv/ or similar
|
||||
// [https://] uses ':', [lbry://] expects #
|
||||
if !isEmpty(components[1]) {
|
||||
if primaryModSeparator == ":" {
|
||||
primaryModSeparator = "#"
|
||||
}
|
||||
if secondaryModSeparator == ":" {
|
||||
secondaryModSeparator = "#"
|
||||
}
|
||||
}
|
||||
|
||||
if includesChannel {
|
||||
if isEmpty(channelName) {
|
||||
// I wonder if this check is really necessary, considering the subsequent min length check
|
||||
return nil, errors.New("no channel name after @")
|
||||
}
|
||||
if len(channelName) < ChannelNameMinLength {
|
||||
return nil, errors.New(fmt.Sprintf("Channel names must be at least %d character long.", ChannelNameMinLength))
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
var primaryMod *UriModifier
|
||||
var secondaryMod *UriModifier
|
||||
if !isEmpty(primaryModSeparator) && !isEmpty(primaryModValue) {
|
||||
primaryMod, err = parseModifier(primaryModSeparator, primaryModValue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
primaryClaimId = primaryMod.ClaimId
|
||||
primaryClaimSequence = primaryMod.ClaimSequence
|
||||
primaryBidPosition = primaryMod.BidPosition
|
||||
}
|
||||
if !isEmpty(secondaryModSeparator) && !isEmpty(secondaryModValue) {
|
||||
secondaryMod, err = parseModifier(secondaryModSeparator, secondaryModValue)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
secondaryClaimSequence = secondaryMod.ClaimSequence
|
||||
secondaryBidPosition = secondaryMod.BidPosition
|
||||
}
|
||||
|
||||
streamName := streamOrChannelName
|
||||
if includesChannel {
|
||||
streamName = possibleStreamName
|
||||
}
|
||||
|
||||
streamClaimId := ""
|
||||
if includesChannel && secondaryMod != nil {
|
||||
streamClaimId = secondaryMod.ClaimId
|
||||
} else if primaryMod != nil {
|
||||
streamClaimId = primaryMod.ClaimId
|
||||
}
|
||||
channelClaimId := ""
|
||||
if includesChannel && primaryMod != nil {
|
||||
channelClaimId = primaryMod.ClaimId
|
||||
}
|
||||
|
||||
return &LbryUri{
|
||||
Path: strings.Join(components[2:], ""),
|
||||
IsChannel: isChannel,
|
||||
StreamName: streamName,
|
||||
StreamClaimId: streamClaimId,
|
||||
ChannelName: channelName,
|
||||
ChannelClaimId: channelClaimId,
|
||||
PrimaryClaimSequence: primaryClaimSequence,
|
||||
SecondaryClaimSequence: secondaryClaimSequence,
|
||||
PrimaryBidPosition: primaryBidPosition,
|
||||
SecondaryBidPosition: secondaryBidPosition,
|
||||
ClaimName: streamOrChannelName,
|
||||
ClaimId: primaryClaimId,
|
||||
ContentName: streamName,
|
||||
QueryString: queryString,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseModifier(modSeparator string, modValue string) (*UriModifier, error) {
|
||||
claimId := ""
|
||||
claimSequence := 0
|
||||
bidPosition := 0
|
||||
|
||||
if !isEmpty(modSeparator) {
|
||||
if isEmpty(modValue) {
|
||||
return nil, errors.New(fmt.Sprintf("No modifier provided after separator %s", modSeparator))
|
||||
}
|
||||
|
||||
if modSeparator == "#" {
|
||||
claimId = modValue
|
||||
} else if modSeparator == ":" {
|
||||
claimSequence = parseInt(modValue, -1)
|
||||
} else if modSeparator == "$" {
|
||||
bidPosition = parseInt(modValue, -1)
|
||||
}
|
||||
}
|
||||
|
||||
if !isEmpty(claimId) && (len(claimId) > ClaimIdMaxLength || !regexp.MustCompile(RegexClaimId).MatchString(claimId)) {
|
||||
return nil, errors.New(fmt.Sprintf("Invalid claim ID %s", claimId))
|
||||
}
|
||||
if claimSequence == -1 {
|
||||
return nil, errors.New("claim sequence must be a number")
|
||||
}
|
||||
if bidPosition == -1 {
|
||||
return nil, errors.New("bid position must be a number")
|
||||
}
|
||||
|
||||
return &UriModifier{
|
||||
ClaimId: claimId,
|
||||
ClaimSequence: claimSequence,
|
||||
BidPosition: bidPosition,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func parseInt(value string, defaultValue int) int {
|
||||
v, err := strconv.ParseInt(value, 10, 32)
|
||||
if err != nil {
|
||||
return defaultValue
|
||||
}
|
||||
return int(v)
|
||||
}
|
||||
|
||||
func isEmpty(s string) bool {
|
||||
return len(strings.TrimSpace(s)) == 0
|
||||
}
|
||||
Reference in new issue
Block a user