namecheck/twitter/twitter.go

93 lines
1.8 KiB
Go

package twitter
import (
"fmt"
"net/http"
"regexp"
"strings"
"unicode/utf8"
"forge.cadoles.com/pcaseiro/namecheck"
)
const (
sizeMin = 1
sizeMax = 15
legalChars = "^[a-zA-Z0-9_]+$"
illegalPattern = "twitter"
twitterUrl = "https://twitter.com"
)
type Twitter struct {
HttpClient http.Client
Responds bool
}
var (
legal = regexp.MustCompile(legalChars)
illegal = regexp.MustCompile(illegalPattern)
)
func containsOnlyLegalChars(username string) bool {
return legal.MatchString(username)
}
func containsNoIllegalPattern(username string) bool {
if strings.Contains(strings.ToLower(username), illegalPattern) {
return false
}
return true
}
func isLongEnough(username string) bool {
return utf8.RuneCountInString(username) > sizeMin
}
func isShortEnough(username string) bool {
return utf8.RuneCountInString(username) <= sizeMax
}
func (t *Twitter) IsValid(username string) bool {
if !containsNoIllegalPattern(username) {
return false
}
if !containsOnlyLegalChars(username) {
return false
}
if !isLongEnough(username) {
return false
}
if !isShortEnough(username) {
return false
}
return true
}
// Name return a string with the name of the "Social Media"
func (t *Twitter) String() string {
return "Twitter"
}
// IsAvailable check if a user name is valid and available on twitter
func (t *Twitter) IsAvailable(username string) (bool, error) {
resp := t.IsValid(username)
if resp {
url := fmt.Sprintf("%s/%s", twitterUrl, username)
resp, err := t.HttpClient.Get(url)
if err != nil {
t.Responds = false
nerr := &namecheck.ErrUnknownAvailability{Username: username, Cause: err}
return false, nerr
}
t.Responds = true
defer resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
return false, nil
}
return true, nil
}
return false, fmt.Errorf("Username is not valid")
}