~poptart/x

197bcbf285bb2a64f7e524b8ea051918f0253ec8 — terrorbyte 8 months ago 453a7c7
Added UA basics.
2 files changed, 97 insertions(+), 0 deletions(-)

A cmd/uacmd.go
A ua/ua.go
A cmd/uacmd.go => cmd/uacmd.go +19 -0
@@ 0,0 1,19 @@
package main

import (
	"fmt"
	"git.sr.ht/~poptart/x/ua"
	"os"
)

func main() {
	if _, err := os.Stat("/home/poptart/.config/hosaka_uacache"); err == nil {
		b, _ := useragent.GetUACache("/home/poptart/.config/hosaka_uacache")
		fmt.Println(b.UserAgent)
	} else if os.IsNotExist(err) {
		e := useragent.SaveUACache("/home/poptart/.config/hosaka_uacache")
		if e != nil {
			fmt.Println(e)
		}
	}
}

A ua/ua.go => ua/ua.go +78 -0
@@ 0,0 1,78 @@
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
}