package useragent
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"time"
)
var DEFAULT_INTERVAL = int(time.Hour * 24 * 30)
var UA_URL = "https://raw.githubusercontent.com/chromium/chromium/master/content/public/common/user_agent.h"
var REG1 = `Mozilla\/5.0 \(Windows[^"]*`
var REG2 = `like Gecko\) Chrome[^"]*`
type UserAgentCache struct {
LastUpdate string
Interval int
UserAgent string
}
func GetCurrentUA() (string, error) {
re1 := regexp.MustCompile(REG1)
re2 := regexp.MustCompile(REG2)
resp, err := http.Get(UA_URL)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
m1 := re1.Find(body)
m2 := re2.Find(body)
return fmt.Sprintf("%s%s", string(m1), string(m2)), nil
}
func SaveUACache(file string) error {
t := time.Now().Unix()
ua, err := GetCurrentUA()
if err != nil {
return err
}
uac := UserAgentCache{
Interval: DEFAULT_INTERVAL,
LastUpdate: strconv.FormatInt(t, 10),
UserAgent: ua,
}
uaf, err := json.Marshal(uac)
if err != nil {
return err
}
err = ioutil.WriteFile(file, []byte(uaf), 0644)
if err != nil {
return err
}
return nil
}
//func GetUA() (string, error) {
//
//}
func GetUACache(file string) (UserAgentCache, error) {
var uac UserAgentCache
uaf, err := ioutil.ReadFile(file)
if err != nil {
return UserAgentCache{}, err
}
err = json.Unmarshal(uaf, &uac)
if err != nil {
return UserAgentCache{}, err
}
return uac, nil
}