Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0ab534624a | ||
|
|
b3ce49788b | ||
|
|
bbe839bb88 | ||
|
|
60f19968e3 | ||
|
|
c62d84b40a | ||
|
|
1a072fee59 | ||
|
|
c4213e697d | ||
|
|
934a306bc9 | ||
|
|
82bdbb1f3b | ||
|
|
b090cb86a5 | ||
|
|
e42df54632 | ||
|
|
0120fdd0e2 | ||
|
|
eab73aec04 | ||
|
|
bd9dca9766 | ||
|
|
56f7d093ef | ||
|
|
62b413c033 | ||
|
|
3adcee2fbe | ||
|
|
e916b5abfc | ||
|
|
211ef64261 | ||
|
|
bb8e2a18ef | ||
|
|
d2cf8c74a2 | ||
|
|
db289cb5c8 | ||
|
|
128c98dfbd | ||
|
|
a41ea7d501 | ||
|
|
d38555a555 | ||
|
|
d7d523b0a7 | ||
|
|
649bae91f2 | ||
|
|
5406250af3 | ||
|
|
e19cd7095d | ||
|
|
0013db850c | ||
|
|
d978a398b1 | ||
|
|
e7782d4ff5 |
@@ -20,7 +20,8 @@ var authlimiter = rate.NewLimiter(rate.Limit(1.0/60.0), 1)
|
|||||||
var limiter = rate.NewLimiter(rate.Limit(1.0/20.0), 1)
|
var limiter = rate.NewLimiter(rate.Limit(1.0/20.0), 1)
|
||||||
|
|
||||||
type Broker interface {
|
type Broker interface {
|
||||||
Search([]config.State) ([]Job, error)
|
SearchStates([]config.State) ([]Job, error)
|
||||||
|
SearchZips([]string) ([]Job, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func do(r *http.Request) (*http.Response, error) {
|
func do(r *http.Request) (*http.Response, error) {
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import (
|
|||||||
"local/truckstop/config"
|
"local/truckstop/config"
|
||||||
"local/truckstop/logtr"
|
"local/truckstop/logtr"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"sort"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -38,13 +39,24 @@ func (fe FastExact) WithMock() FastExact {
|
|||||||
return fe
|
return fe
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fe FastExact) Search(states []config.State) ([]Job, error) {
|
func (fe FastExact) SearchZips(zips []string) ([]Job, error) {
|
||||||
jobs, err := fe.search(states)
|
jobs, err := fe.searchZips(zips)
|
||||||
if err == ErrNoAuth {
|
if err == ErrNoAuth {
|
||||||
if err := fe.login(); err != nil {
|
if err := fe.login(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
jobs, err = fe.search(states)
|
jobs, err = fe.searchZips(zips)
|
||||||
|
}
|
||||||
|
return jobs, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fe FastExact) SearchStates(states []config.State) ([]Job, error) {
|
||||||
|
jobs, err := fe.searchStates(states)
|
||||||
|
if err == ErrNoAuth {
|
||||||
|
if err := fe.login(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
jobs, err = fe.searchStates(states)
|
||||||
}
|
}
|
||||||
return jobs, err
|
return jobs, err
|
||||||
}
|
}
|
||||||
@@ -91,28 +103,47 @@ func (fe FastExact) setHeaders(req *http.Request) {
|
|||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fe FastExact) search(states []config.State) ([]Job, error) {
|
func (fe FastExact) searchZips(zips []string) ([]Job, error) {
|
||||||
var jobs []Job
|
var jobs []Job
|
||||||
for _, state := range states {
|
for _, zip := range zips {
|
||||||
subjobs, err := fe.searchOne(state)
|
subjobs, err := fe.searchOneZip(zip)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
jobs = append(jobs, subjobs...)
|
jobs = append(jobs, subjobs...)
|
||||||
}
|
}
|
||||||
|
return fe.dedupeJobs(jobs), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fe FastExact) searchStates(states []config.State) ([]Job, error) {
|
||||||
|
var jobs []Job
|
||||||
|
for _, state := range states {
|
||||||
|
subjobs, err := fe.searchOneState(state)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
jobs = append(jobs, subjobs...)
|
||||||
|
}
|
||||||
|
return fe.dedupeJobs(jobs), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fe FastExact) dedupeJobs(jobs []Job) []Job {
|
||||||
|
sort.Slice(jobs, func(i, j int) bool {
|
||||||
|
return jobs[i].UID() < jobs[j].UID()
|
||||||
|
})
|
||||||
dedupeJobs := map[string]Job{}
|
dedupeJobs := map[string]Job{}
|
||||||
for _, job := range jobs {
|
for _, job := range jobs {
|
||||||
dedupeJobs[job.UID()] = job
|
dedupeJobs[strings.ReplaceAll(job.UID(), job.ID, "")] = job
|
||||||
}
|
}
|
||||||
result := []Job{}
|
result := []Job{}
|
||||||
for _, job := range dedupeJobs {
|
for _, job := range dedupeJobs {
|
||||||
result = append(result, job)
|
result = append(result, job)
|
||||||
}
|
}
|
||||||
return result, nil
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fe FastExact) searchOne(state config.State) ([]Job, error) {
|
func (fe FastExact) searchOneZip(zip string) ([]Job, error) {
|
||||||
req, err := fe.newRequest(state)
|
req, err := fe.newRequest(zip)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -124,14 +155,31 @@ func (fe FastExact) searchOne(state config.State) ([]Job, error) {
|
|||||||
return fe.parse(resp)
|
return fe.parse(resp)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fe FastExact) newRequest(state config.State) (*http.Request, error) {
|
func (fe FastExact) searchOneState(state config.State) ([]Job, error) {
|
||||||
|
req, err := fe.newRequestWithState(state)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
resp, err := fe.doer.doRequest(req)
|
||||||
|
logtr.Verbosef("req: %+v => resp: %+v", req, resp)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return fe.parse(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fe FastExact) newRequestWithState(state config.State) (*http.Request, error) {
|
||||||
zip, ok := config.States[state]
|
zip, ok := config.States[state]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil, fmt.Errorf("no configured zip for %s", state)
|
return nil, fmt.Errorf("no configured zip for %s", state)
|
||||||
}
|
}
|
||||||
|
return fe.newRequest(zip)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (fe FastExact) newRequest(zip string) (*http.Request, error) {
|
||||||
req, err := http.NewRequest(
|
req, err := http.NewRequest(
|
||||||
http.MethodGet,
|
http.MethodGet,
|
||||||
"https://www.fastexact.com/secure/index.php?page=ajaxListJobs&action=ajax&zipcode="+zip+"&records_per_page=50&distance="+strconv.Itoa(config.Get().Brokers.FastExact.RadiusMiles)+"&st_loc_zip=8",
|
"https://www.fastexact.com/secure/index.php?page=ajaxListJobs&action=ajax&zipcode="+zip+"&records_per_page=50&distance="+strconv.Itoa(config.Get().Brokers.RadiusMiles)+"&st_loc_zip=8",
|
||||||
nil,
|
nil,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -244,7 +292,7 @@ func (mock mockFastExactDoer) doRequest(req *http.Request) (*http.Response, erro
|
|||||||
if req.URL.Query().Get("records_per_page") != "50" {
|
if req.URL.Query().Get("records_per_page") != "50" {
|
||||||
return nil, errors.New("bad query: records_per_page should be 50")
|
return nil, errors.New("bad query: records_per_page should be 50")
|
||||||
}
|
}
|
||||||
if req.URL.Query().Get("distance") != strconv.Itoa(config.Get().Brokers.FastExact.RadiusMiles) {
|
if req.URL.Query().Get("distance") != strconv.Itoa(config.Get().Brokers.RadiusMiles) {
|
||||||
return nil, errors.New("bad query: distance should be as configured")
|
return nil, errors.New("bad query: distance should be as configured")
|
||||||
}
|
}
|
||||||
if req.URL.Query().Get("zipcode") == "" {
|
if req.URL.Query().Get("zipcode") == "" {
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ func TestFastExactReal(t *testing.T) {
|
|||||||
if err := fe.login(); err != nil {
|
if err := fe.login(); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
jobs, err := fe.search(states)
|
jobs, err := fe.searchStates(states)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -56,16 +56,16 @@ func TestFastExactLogin(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFastExactSearch(t *testing.T) {
|
func TestFastExactSearchStates(t *testing.T) {
|
||||||
logtr.SetLevel(logtr.SOS)
|
logtr.SetLevel(logtr.SOS)
|
||||||
limiter = rate.NewLimiter(rate.Limit(60.0), 1)
|
limiter = rate.NewLimiter(rate.Limit(60.0), 1)
|
||||||
fe := NewFastExact().WithMock()
|
fe := NewFastExact().WithMock()
|
||||||
_ = fe
|
_ = fe
|
||||||
db := storage.NewMap()
|
db := storage.NewMap()
|
||||||
_ = db
|
_ = db
|
||||||
if jobs, err := fe.search([]config.State{config.State("NC"), config.State("SC")}); err != nil {
|
if jobs, err := fe.searchStates([]config.State{config.State("NC"), config.State("SC")}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
} else if len(jobs) != 10 {
|
} else if len(jobs) != 9 {
|
||||||
t.Fatal(len(jobs))
|
t.Fatal(len(jobs))
|
||||||
} else {
|
} else {
|
||||||
for _, job := range jobs {
|
for _, job := range jobs {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"local/truckstop/config"
|
"local/truckstop/config"
|
||||||
"local/truckstop/logtr"
|
"local/truckstop/zip"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -86,9 +86,17 @@ func (j Job) FormatMultilineText() string {
|
|||||||
}
|
}
|
||||||
out := ""
|
out := ""
|
||||||
clients := config.Clients(j.Pickup.Date)
|
clients := config.Clients(j.Pickup.Date)
|
||||||
|
useZip := config.Get().Brokers.UseZips
|
||||||
|
zipRadius := config.Get().Brokers.RadiusMiles
|
||||||
|
jobZip := zip.FromCityState(j.Pickup.City, j.Pickup.State)
|
||||||
for k := range clients {
|
for k := range clients {
|
||||||
logtr.Debugf("job multiline: %+v contains %s then use %v", clients[k].States, j.Pickup.State, k)
|
should := strings.Contains(fmt.Sprint(clients[k].States), j.Pickup.State)
|
||||||
if strings.Contains(fmt.Sprint(clients[k].States), j.Pickup.State) {
|
if useZip {
|
||||||
|
for _, z := range clients[k].Zips {
|
||||||
|
should = should || zip.Get(z).MilesTo(jobZip) <= zipRadius
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if should {
|
||||||
if len(out) > 0 {
|
if len(out) > 0 {
|
||||||
out += "\n"
|
out += "\n"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,13 +9,14 @@ import (
|
|||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"local/truckstop/config"
|
"local/truckstop/config"
|
||||||
"local/truckstop/logtr"
|
"local/truckstop/logtr"
|
||||||
|
"local/truckstop/zip"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type NTGVision struct {
|
type NTGVision struct {
|
||||||
searcher interface {
|
searcher interface {
|
||||||
search(states []config.State) (io.ReadCloser, error)
|
searchStates(states []config.State) (io.ReadCloser, error)
|
||||||
searchJobReadCloser(id int64) (io.ReadCloser, error)
|
searchJobReadCloser(id int64) (io.ReadCloser, error)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -187,8 +188,77 @@ func (ntg NTGVision) searchJob(id int64) (ntgVisionJobInfo, error) {
|
|||||||
return result, err
|
return result, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ntg NTGVision) Search(states []config.State) ([]Job, error) {
|
func (ntg NTGVision) SearchZips(zips []string) ([]Job, error) {
|
||||||
rc, err := ntg.searcher.search(states)
|
radius := config.Get().Brokers.RadiusMiles
|
||||||
|
statesm := map[string]struct{}{}
|
||||||
|
for _, z := range zips {
|
||||||
|
somestates := zip.GetStatesWithin(zip.Get(z), radius)
|
||||||
|
for _, state := range somestates {
|
||||||
|
statesm[state] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
states := make([]config.State, 0, len(statesm))
|
||||||
|
for state := range statesm {
|
||||||
|
states = append(states, config.State(state))
|
||||||
|
}
|
||||||
|
if len(states) == 0 {
|
||||||
|
return nil, fmt.Errorf("failed to map zipcodes %+v to any states", zips)
|
||||||
|
}
|
||||||
|
jobs, err := ntg.SearchStates(states)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
for i := len(jobs) - 1; i >= 0; i-- {
|
||||||
|
ok := false
|
||||||
|
for _, z := range zips {
|
||||||
|
ok = ok || zip.Get(z).MilesTo(zip.FromCityState(jobs[i].Pickup.City, jobs[i].Pickup.State)) <= radius
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
jobs[i], jobs[len(jobs)-1] = jobs[len(jobs)-1], jobs[i]
|
||||||
|
jobs = jobs[:len(jobs)-1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return jobs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ntg NTGVision) workingHours(now time.Time) bool {
|
||||||
|
// TODO assert M-F 9-4 EST
|
||||||
|
now = now.In(time.FixedZone("EST", -5*60*60))
|
||||||
|
working := config.Get().Brokers.NTG.Working
|
||||||
|
logtr.Debugf("ntg.workingHours: now=%s, weekday=%v, hour=%v (ok=%+v)", now.String(), now.Weekday(), now.Hour(), working)
|
||||||
|
if ok := func() bool {
|
||||||
|
for _, hr := range working.Hours {
|
||||||
|
if now.Hour() == hr {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}(); !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if ok := func() bool {
|
||||||
|
for _, weekday := range working.Weekdays {
|
||||||
|
if now.Weekday() == time.Weekday(weekday) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}(); !ok {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ntg NTGVision) SearchStates(states []config.State) ([]Job, error) {
|
||||||
|
if !ntg.workingHours(time.Now()) {
|
||||||
|
lastNtgB, _ := config.Get().DB().Get("ntg_last_search_states")
|
||||||
|
var jobs []Job
|
||||||
|
json.Unmarshal(lastNtgB, &jobs)
|
||||||
|
logtr.Verbosef("ntg.SearchStates: outside of working hours so returning ntg_last_search_states: %+v", jobs)
|
||||||
|
return jobs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rc, err := ntg.searcher.searchStates(states)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -203,12 +273,22 @@ func (ntg NTGVision) Search(states []config.State) ([]Job, error) {
|
|||||||
|
|
||||||
var ntgjobs []ntgVisionJob
|
var ntgjobs []ntgVisionJob
|
||||||
err = json.Unmarshal(b, &ntgjobs)
|
err = json.Unmarshal(b, &ntgjobs)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
jobs := make([]Job, len(ntgjobs))
|
jobs := make([]Job, len(ntgjobs))
|
||||||
for i := range jobs {
|
for i := range jobs {
|
||||||
jobs[i] = ntgjobs[i].Job()
|
jobs[i] = ntgjobs[i].Job()
|
||||||
}
|
}
|
||||||
return jobs, err
|
|
||||||
|
jobsB, err := json.Marshal(jobs)
|
||||||
|
if err == nil {
|
||||||
|
config.Get().DB().Set("ntg_last_search_states", jobsB)
|
||||||
|
logtr.Verbosef("ntg.SearchStates: in working hours so setting ntg_last_search_states: %+v", jobs)
|
||||||
|
}
|
||||||
|
|
||||||
|
return jobs, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func getNTGTokenKey() string {
|
func getNTGTokenKey() string {
|
||||||
@@ -226,20 +306,20 @@ func setNTGToken(token string) {
|
|||||||
db.Set(getNTGTokenKey(), []byte(token))
|
db.Set(getNTGTokenKey(), []byte(token))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ntg NTGVision) search(states []config.State) (io.ReadCloser, error) {
|
func (ntg NTGVision) searchStates(states []config.State) (io.ReadCloser, error) {
|
||||||
if getNTGToken() == "" {
|
if getNTGToken() == "" {
|
||||||
logtr.Debugf("NTG token is empty, refreshing ntg auth")
|
logtr.Debugf("NTG token is empty, refreshing ntg auth")
|
||||||
if err := ntg.refreshAuth(); err != nil {
|
if err := ntg.refreshAuth(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
rc, err := ntg._search(states)
|
rc, err := ntg._searchStates(states)
|
||||||
if err == ErrNoAuth {
|
if err == ErrNoAuth {
|
||||||
logtr.Debugf("err no auth on search, refreshing ntg auth")
|
logtr.Debugf("err no auth on search, refreshing ntg auth")
|
||||||
if err := ntg.refreshAuth(); err != nil {
|
if err := ntg.refreshAuth(); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
rc, err = ntg._search(states)
|
rc, err = ntg._searchStates(states)
|
||||||
}
|
}
|
||||||
return rc, err
|
return rc, err
|
||||||
}
|
}
|
||||||
@@ -285,7 +365,7 @@ func (ntg NTGVision) _refreshAuth() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ntg NTGVision) _search(states []config.State) (io.ReadCloser, error) {
|
func (ntg NTGVision) _searchStates(states []config.State) (io.ReadCloser, error) {
|
||||||
request, err := ntg.newRequest(states)
|
request, err := ntg.newRequest(states)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -300,7 +380,7 @@ func (ntg NTGVision) _search(states []config.State) (io.ReadCloser, error) {
|
|||||||
request2, _ := ntg.newRequest(states)
|
request2, _ := ntg.newRequest(states)
|
||||||
requestb, _ := ioutil.ReadAll(request2.Body)
|
requestb, _ := ioutil.ReadAll(request2.Body)
|
||||||
logtr.Debugf("ntg auth bad status: url=%s, status=%v, body=%s, headers=%+v, request=%+v, requestb=%s", request.URL.String(), resp.StatusCode, b, resp.Header, request2, requestb)
|
logtr.Debugf("ntg auth bad status: url=%s, status=%v, body=%s, headers=%+v, request=%+v, requestb=%s", request.URL.String(), resp.StatusCode, b, resp.Header, request2, requestb)
|
||||||
if resp.StatusCode > 400 && resp.StatusCode < 404 {
|
if resp.StatusCode > 400 && resp.StatusCode < 404 || resp.StatusCode == 417 { // TODO wtf is 417 for
|
||||||
logtr.Debugf("ntg auth bad status: err no auth")
|
logtr.Debugf("ntg auth bad status: err no auth")
|
||||||
return nil, ErrNoAuth
|
return nil, ErrNoAuth
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ func NewNTGVisionMock() NTGVisionMock {
|
|||||||
return NTGVisionMock{}
|
return NTGVisionMock{}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ntgm NTGVisionMock) search(states []config.State) (io.ReadCloser, error) {
|
func (ntgm NTGVisionMock) searchStates(states []config.State) (io.ReadCloser, error) {
|
||||||
path := path.Join(os.Getenv("GOPATH"), "src", "local", "truckstop", "broker", "testdata", "ntgvision_response.json")
|
path := path.Join(os.Getenv("GOPATH"), "src", "local", "truckstop", "broker", "testdata", "ntgvision_response.json")
|
||||||
b, err := ioutil.ReadFile(path)
|
b, err := ioutil.ReadFile(path)
|
||||||
return io.NopCloser(bytes.NewReader(b)), err
|
return io.NopCloser(bytes.NewReader(b)), err
|
||||||
|
|||||||
22
broker/ntgvision_test.go
Normal file
22
broker/ntgvision_test.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package broker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"local/truckstop/config"
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestWorkingHoursNTG(t *testing.T) {
|
||||||
|
os.Setenv("CONFIG", "../config.json")
|
||||||
|
if err := config.Refresh(nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ntg := NTGVision{}
|
||||||
|
if !ntg.workingHours(time.Date(2022, 1, 27, 12, 0, 0, 0, time.FixedZone("MST", -7*60*60))) {
|
||||||
|
t.Fatal("noon MST not ok")
|
||||||
|
}
|
||||||
|
if ntg.workingHours(time.Date(2022, 1, 27, 23, 0, 0, 0, time.FixedZone("MST", -7*60*60))) {
|
||||||
|
t.Fatal("midnight MST ok")
|
||||||
|
}
|
||||||
|
}
|
||||||
28
config.json
28
config.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"Log": {
|
"Log": {
|
||||||
"Path": "/tmp/truckstop.log",
|
"Path": "/tmp/truckstop.log",
|
||||||
"Level": "debug",
|
"Level": "DEB",
|
||||||
"SOSMatrix": {
|
"SOSMatrix": {
|
||||||
"ReceiveEnabled": true,
|
"ReceiveEnabled": true,
|
||||||
"Mock": false,
|
"Mock": false,
|
||||||
@@ -48,6 +48,11 @@
|
|||||||
"States": [
|
"States": [
|
||||||
"NC"
|
"NC"
|
||||||
],
|
],
|
||||||
|
"Zips": [
|
||||||
|
"27006",
|
||||||
|
"73044",
|
||||||
|
"84058"
|
||||||
|
],
|
||||||
"IDs": {
|
"IDs": {
|
||||||
"Matrix": "@bel:m.bltrucks.top"
|
"Matrix": "@bel:m.bltrucks.top"
|
||||||
},
|
},
|
||||||
@@ -71,21 +76,26 @@
|
|||||||
},
|
},
|
||||||
"Once": false,
|
"Once": false,
|
||||||
"Brokers": {
|
"Brokers": {
|
||||||
"FastExact": {
|
"UseZips": true,
|
||||||
"RadiusMiles": 100,
|
"RadiusMiles": 200,
|
||||||
"Enabled": true,
|
|
||||||
"Mock": true,
|
|
||||||
"Username": "birdman",
|
|
||||||
"Password": "166647"
|
|
||||||
},
|
|
||||||
"NTG": {
|
"NTG": {
|
||||||
|
"Working": {
|
||||||
|
"Hours": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
|
||||||
|
"Weekdays": [1, 2, 3, 4, 5]
|
||||||
|
},
|
||||||
"Enabled": false,
|
"Enabled": false,
|
||||||
"JobInfo": true,
|
"JobInfo": true,
|
||||||
"Mock": true,
|
"Mock": true,
|
||||||
"LoadPageURIFormat": "https://ntgvision.com/LoadDetails?loadId=%d",
|
"LoadPageURIFormat": "https://ntgvision.com/LoadDetails?loadId=%d",
|
||||||
"LoadPageAPIURIFormat": "https://ntgvision.com/api/v1/load/LoadDetails?loadId==%d",
|
"LoadPageAPIURIFormat": "https://ntgvision.com/api/v1/load/LoadDetails?loadId=%d",
|
||||||
"Username": "noeasyrunstrucking@gmail.com",
|
"Username": "noeasyrunstrucking@gmail.com",
|
||||||
"Password": "thumper12345"
|
"Password": "thumper12345"
|
||||||
|
},
|
||||||
|
"FastExact": {
|
||||||
|
"Enabled": true,
|
||||||
|
"Mock": true,
|
||||||
|
"Username": "birdman",
|
||||||
|
"Password": "166647"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -48,6 +48,9 @@
|
|||||||
"States": [
|
"States": [
|
||||||
"NC"
|
"NC"
|
||||||
],
|
],
|
||||||
|
"Zips": [
|
||||||
|
"27006"
|
||||||
|
],
|
||||||
"IDs": {
|
"IDs": {
|
||||||
"Matrix": "@bel:m.bltrucks.top"
|
"Matrix": "@bel:m.bltrucks.top"
|
||||||
},
|
},
|
||||||
@@ -71,19 +74,24 @@
|
|||||||
},
|
},
|
||||||
"Once": true,
|
"Once": true,
|
||||||
"Brokers": {
|
"Brokers": {
|
||||||
|
"UseZips": true,
|
||||||
|
"RadiusMiles": 100,
|
||||||
"FastExact": {
|
"FastExact": {
|
||||||
"RadiusMiles": 100,
|
|
||||||
"Enabled": true,
|
"Enabled": true,
|
||||||
"Mock": true,
|
"Mock": true,
|
||||||
"Username": "u",
|
"Username": "u",
|
||||||
"Password": "p"
|
"Password": "p"
|
||||||
},
|
},
|
||||||
"NTG": {
|
"NTG": {
|
||||||
|
"Working": {
|
||||||
|
"Hours": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
|
||||||
|
"Weekdays": [0, 1, 2, 3, 4, 5, 6]
|
||||||
|
},
|
||||||
"Enabled": true,
|
"Enabled": true,
|
||||||
"JobInfo": true,
|
"JobInfo": true,
|
||||||
"Mock": true,
|
"Mock": true,
|
||||||
"LoadPageURIFormat": "https://ntgvision.com/LoadDetails?loadId=%d",
|
"LoadPageURIFormat": "https://ntgvision.com/LoadDetails?loadId=%d",
|
||||||
"LoadPageAPIURIFormat": "https://ntgvision.com/api/v1/load/LoadDetails?loadId==%d",
|
"LoadPageAPIURIFormat": "https://ntgvision.com/api/v1/load/LoadDetails?loadId=%d",
|
||||||
"Username": "noeasyrunstrucking@gmail.com",
|
"Username": "noeasyrunstrucking@gmail.com",
|
||||||
"Password": "thumper1234"
|
"Password": "thumper1234"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -64,7 +64,13 @@ type Config struct {
|
|||||||
}
|
}
|
||||||
Once bool
|
Once bool
|
||||||
Brokers struct {
|
Brokers struct {
|
||||||
NTG struct {
|
UseZips bool
|
||||||
|
RadiusMiles int
|
||||||
|
NTG struct {
|
||||||
|
Working struct {
|
||||||
|
Hours []int
|
||||||
|
Weekdays []int
|
||||||
|
}
|
||||||
Enabled bool
|
Enabled bool
|
||||||
JobInfo bool
|
JobInfo bool
|
||||||
Mock bool
|
Mock bool
|
||||||
@@ -74,11 +80,10 @@ type Config struct {
|
|||||||
Password string
|
Password string
|
||||||
}
|
}
|
||||||
FastExact struct {
|
FastExact struct {
|
||||||
Enabled bool
|
Enabled bool
|
||||||
RadiusMiles int
|
Mock bool
|
||||||
Mock bool
|
Username string
|
||||||
Username string
|
Password string
|
||||||
Password string
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,6 +93,7 @@ type Config struct {
|
|||||||
|
|
||||||
type Client struct {
|
type Client struct {
|
||||||
States []State
|
States []State
|
||||||
|
Zips []string
|
||||||
IDs struct {
|
IDs struct {
|
||||||
Matrix string
|
Matrix string
|
||||||
}
|
}
|
||||||
@@ -115,6 +121,20 @@ func Clients(t time.Time) map[string]Client {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func AllZips() []string {
|
||||||
|
zipm := map[string]struct{}{}
|
||||||
|
for _, v := range Clients(time.Now().Add(time.Hour * 24 * 365)) {
|
||||||
|
for _, state := range v.Zips {
|
||||||
|
zipm[state] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
zips := make([]string, 0, len(zipm)+1)
|
||||||
|
for k := range zipm {
|
||||||
|
zips = append(zips, k)
|
||||||
|
}
|
||||||
|
return zips
|
||||||
|
}
|
||||||
|
|
||||||
func AllStates() []State {
|
func AllStates() []State {
|
||||||
statem := map[State]struct{}{}
|
statem := map[State]struct{}{}
|
||||||
for _, v := range Clients(time.Now().Add(time.Hour * 24 * 365)) {
|
for _, v := range Clients(time.Now().Add(time.Hour * 24 * 365)) {
|
||||||
|
|||||||
207
main.go
207
main.go
@@ -13,12 +13,14 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"regexp"
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
var stateFinder = regexp.MustCompile(`[A-Za-z]+`)
|
var stateFinder = regexp.MustCompile(`[A-Za-z]+`)
|
||||||
|
var zipFinder = regexp.MustCompile(`[0-9]{5}[0-9]*`)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if err := _main(); err != nil {
|
if err := _main(); err != nil {
|
||||||
@@ -62,15 +64,15 @@ func _main() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func matrixrecv() error {
|
func matrixrecv() error {
|
||||||
logtr.Debugf("checking matrix...")
|
logtr.Verbosef("checking matrix...")
|
||||||
defer logtr.Debugf("/checking matrix...")
|
defer logtr.Verbosef("/checking matrix...")
|
||||||
sender := message.NewMatrix()
|
sender := message.NewMatrix()
|
||||||
messages, err := sender.Receive()
|
messages, err := sender.Receive()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
func() {
|
func() {
|
||||||
logtr.Debugf("looking for help")
|
logtr.Verbosef("looking for help")
|
||||||
printed := false
|
printed := false
|
||||||
for _, msg := range messages {
|
for _, msg := range messages {
|
||||||
if !strings.HasPrefix(msg.Content, "!help") {
|
if !strings.HasPrefix(msg.Content, "!help") {
|
||||||
@@ -81,7 +83,11 @@ func matrixrecv() error {
|
|||||||
if !printed {
|
if !printed {
|
||||||
if _, err := db.Get(key); err == storage.ErrNotFound {
|
if _, err := db.Get(key); err == storage.ErrNotFound {
|
||||||
logtr.Debugf("sending help")
|
logtr.Debugf("sending help")
|
||||||
help := fmt.Sprintf("commands:\n...`!help` print this help\n...`!state nc NC nC Nc` set states for self\n...`!available 2022-12-31` set date self is available for work\n\nrun a command for someone else: `!state ga @caleb`")
|
locationHelp := "`!state nc NC nC Nc` set states for self"
|
||||||
|
if config.Get().Brokers.UseZips {
|
||||||
|
locationHelp = "...`!zip 27006 84058` to set zip codes for self\n...`!radius 100` to set miles radius to 100, 200, or 300"
|
||||||
|
}
|
||||||
|
help := fmt.Sprintf("commands:\n...`!help` print this help\n%s\n\nrun a command for someone else: `!zip 2022-12-31 @caleb`", locationHelp)
|
||||||
if err := sender.Send(help); err != nil {
|
if err := sender.Send(help); err != nil {
|
||||||
logtr.Errorf("failed to send help: %v", err)
|
logtr.Errorf("failed to send help: %v", err)
|
||||||
} else {
|
} else {
|
||||||
@@ -99,7 +105,36 @@ func matrixrecv() error {
|
|||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
func() {
|
func() {
|
||||||
logtr.Debugf("looking for states")
|
logtr.Verbosef("looking for zips")
|
||||||
|
db := config.Get().DB()
|
||||||
|
zips := map[string]map[string]struct{}{}
|
||||||
|
for _, msg := range messages {
|
||||||
|
key := fmt.Sprintf("zips_%d", msg.Timestamp.Unix())
|
||||||
|
if !strings.HasPrefix(msg.Content, "!zip") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, ok := zips[msg.Sender]; ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := db.Get(key); err == storage.ErrNotFound {
|
||||||
|
zips[msg.Sender] = map[string]struct{}{}
|
||||||
|
for _, zip := range parseOutZips([]byte(msg.Content)) {
|
||||||
|
zips[msg.Sender][zip] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := db.Set(key, []byte{'k'}); err != nil {
|
||||||
|
logtr.Errorf("failed to mark state gathered @%s: %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if config.Get().Brokers.UseZips {
|
||||||
|
setNewZips(zips)
|
||||||
|
} else {
|
||||||
|
sender.Send("I don't accept !zip, only !state right now")
|
||||||
|
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
func() {
|
||||||
|
logtr.Verbosef("looking for states")
|
||||||
db := config.Get().DB()
|
db := config.Get().DB()
|
||||||
states := map[string]map[config.State]struct{}{}
|
states := map[string]map[config.State]struct{}{}
|
||||||
for _, msg := range messages {
|
for _, msg := range messages {
|
||||||
@@ -120,10 +155,40 @@ func matrixrecv() error {
|
|||||||
logtr.Errorf("failed to mark state gathered @%s: %v", key, err)
|
logtr.Errorf("failed to mark state gathered @%s: %v", key, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setNewStates(states)
|
if !config.Get().Brokers.UseZips {
|
||||||
|
setNewStates(states)
|
||||||
|
} else {
|
||||||
|
sender.Send("I don't accept !state, only !zip right now")
|
||||||
|
|
||||||
|
}
|
||||||
}()
|
}()
|
||||||
func() {
|
func() {
|
||||||
logtr.Debugf("looking for pauses")
|
logtr.Verbosef("looking for radius")
|
||||||
|
db := config.Get().DB()
|
||||||
|
var radius *int
|
||||||
|
for _, msg := range messages {
|
||||||
|
key := fmt.Sprintf("radius_%d", msg.Timestamp.Unix())
|
||||||
|
if !strings.HasPrefix(msg.Content, "!radius ") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, err := db.Get(key); err == storage.ErrNotFound {
|
||||||
|
cmd := msg.Content
|
||||||
|
for strings.HasPrefix(cmd, "!radius ") {
|
||||||
|
cmd = strings.TrimPrefix(cmd, "!radius ")
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(strings.TrimSpace(cmd))
|
||||||
|
if err == nil {
|
||||||
|
radius = &n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := db.Set(key, []byte{'k'}); err != nil {
|
||||||
|
logtr.Errorf("failed to mark radius gathered @%s: %v", key, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setNewRadius(radius)
|
||||||
|
}()
|
||||||
|
func() {
|
||||||
|
logtr.Verbosef("looking for pauses")
|
||||||
db := config.Get().DB()
|
db := config.Get().DB()
|
||||||
pauses := map[string]time.Time{}
|
pauses := map[string]time.Time{}
|
||||||
for _, msg := range messages {
|
for _, msg := range messages {
|
||||||
@@ -145,7 +210,7 @@ func matrixrecv() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err := db.Set(key, []byte{'k'}); err != nil {
|
if err := db.Set(key, []byte{'k'}); err != nil {
|
||||||
logtr.Errorf("failed to mark state gathered @%s: %v", key, err)
|
logtr.Errorf("failed to mark pause gathered @%s: %v", key, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
setNewPauses(pauses)
|
setNewPauses(pauses)
|
||||||
@@ -154,6 +219,33 @@ func matrixrecv() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func setNewRadius(radius *int) {
|
||||||
|
if radius == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sender := message.NewMatrix()
|
||||||
|
logtr.Debugf("set new radius: %d", *radius)
|
||||||
|
acceptable := map[int]struct{}{
|
||||||
|
100: struct{}{},
|
||||||
|
200: struct{}{},
|
||||||
|
300: struct{}{},
|
||||||
|
}
|
||||||
|
if _, ok := acceptable[*radius]; !ok {
|
||||||
|
sender.Send(fmt.Sprintf("radius of %v is not among acceptable %+v", *radius, acceptable))
|
||||||
|
logtr.Debugf("bad radius, not setting: %d", *radius)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conf := *config.Get()
|
||||||
|
if conf.Brokers.RadiusMiles == *radius {
|
||||||
|
logtr.Debugf("noop radius, not setting: %d", *radius)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conf.Brokers.RadiusMiles = *radius
|
||||||
|
logtr.Infof("updating config new pauses: %+v", conf)
|
||||||
|
config.Set(conf)
|
||||||
|
sender.Send(fmt.Sprintf("now using radius of %d mi for zip code search", *radius))
|
||||||
|
}
|
||||||
|
|
||||||
func setNewPauses(pauses map[string]time.Time) {
|
func setNewPauses(pauses map[string]time.Time) {
|
||||||
if len(pauses) == 0 {
|
if len(pauses) == 0 {
|
||||||
return
|
return
|
||||||
@@ -182,6 +274,41 @@ func setNewPauses(pauses map[string]time.Time) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func setNewZips(zips map[string]map[string]struct{}) {
|
||||||
|
if len(zips) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
conf := *config.Get()
|
||||||
|
changed := map[string][]string{}
|
||||||
|
for client, clientZips := range zips {
|
||||||
|
newzips := []string{}
|
||||||
|
for k := range clientZips {
|
||||||
|
newzips = append(newzips, k)
|
||||||
|
}
|
||||||
|
sort.Slice(newzips, func(i, j int) bool {
|
||||||
|
return newzips[i] < newzips[j]
|
||||||
|
})
|
||||||
|
clientconf := conf.Clients[client]
|
||||||
|
if fmt.Sprint(newzips) == fmt.Sprint(clientconf.Zips) {
|
||||||
|
message.NewMatrix().Send(fmt.Sprintf("%s: still searching for %+v", client, newzips))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
clientconf.Zips = newzips
|
||||||
|
conf.Clients[client] = clientconf
|
||||||
|
changed[client] = newzips
|
||||||
|
}
|
||||||
|
if len(changed) == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
logtr.Infof("updating config new zips: %+v", conf)
|
||||||
|
config.Set(conf)
|
||||||
|
for client, zips := range changed {
|
||||||
|
if err := sendNewZips(client, zips); err != nil {
|
||||||
|
logtr.Errorf("failed to send new zips %s/%+v: %v", client, zips, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func setNewStates(states map[string]map[config.State]struct{}) {
|
func setNewStates(states map[string]map[config.State]struct{}) {
|
||||||
if len(states) == 0 {
|
if len(states) == 0 {
|
||||||
return
|
return
|
||||||
@@ -217,6 +344,18 @@ func setNewStates(states map[string]map[config.State]struct{}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseOutZips(b []byte) []string {
|
||||||
|
var zips []string
|
||||||
|
candidates := zipFinder.FindAll(b, -1)
|
||||||
|
for _, candidate := range candidates {
|
||||||
|
if len(candidate) != 5 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
zips = append(zips, string(candidate))
|
||||||
|
}
|
||||||
|
return zips
|
||||||
|
}
|
||||||
|
|
||||||
func parseOutStates(b []byte) []config.State {
|
func parseOutStates(b []byte) []config.State {
|
||||||
var states []config.State
|
var states []config.State
|
||||||
var state config.State
|
var state config.State
|
||||||
@@ -242,7 +381,7 @@ func __main() error {
|
|||||||
logtr.Errorf("failed _main: %v", err)
|
logtr.Errorf("failed _main: %v", err)
|
||||||
}
|
}
|
||||||
if config.Get().Once {
|
if config.Get().Once {
|
||||||
time.Sleep(3 * time.Second)
|
time.Sleep(10 * time.Second)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -313,7 +452,39 @@ func once() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func getJobs() ([]broker.Job, error) {
|
func getJobs() ([]broker.Job, error) {
|
||||||
|
if config.Get().Brokers.UseZips {
|
||||||
|
return getJobsZips()
|
||||||
|
}
|
||||||
|
return getJobsStates()
|
||||||
|
}
|
||||||
|
|
||||||
|
func getJobsZips() ([]broker.Job, error) {
|
||||||
|
zips := config.AllZips()
|
||||||
|
jobs := []broker.Job{}
|
||||||
|
for _, broker := range getBrokers() {
|
||||||
|
somejobs, err := broker.SearchZips(zips)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
jobs = append(jobs, somejobs...)
|
||||||
|
}
|
||||||
|
return jobs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getJobsStates() ([]broker.Job, error) {
|
||||||
states := config.AllStates()
|
states := config.AllStates()
|
||||||
|
jobs := []broker.Job{}
|
||||||
|
for _, broker := range getBrokers() {
|
||||||
|
somejobs, err := broker.SearchStates(states)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
jobs = append(jobs, somejobs...)
|
||||||
|
}
|
||||||
|
return jobs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getBrokers() []broker.Broker {
|
||||||
brokers := []broker.Broker{}
|
brokers := []broker.Broker{}
|
||||||
if config.Get().Brokers.NTG.Enabled {
|
if config.Get().Brokers.NTG.Enabled {
|
||||||
logtr.Debugf("NTG enabled")
|
logtr.Debugf("NTG enabled")
|
||||||
@@ -323,16 +494,7 @@ func getJobs() ([]broker.Job, error) {
|
|||||||
logtr.Debugf("FastExact enabled")
|
logtr.Debugf("FastExact enabled")
|
||||||
brokers = append(brokers, broker.NewFastExact())
|
brokers = append(brokers, broker.NewFastExact())
|
||||||
}
|
}
|
||||||
logtr.Debugf("brokers=%+v", brokers)
|
return brokers
|
||||||
jobs := []broker.Job{}
|
|
||||||
for _, broker := range brokers {
|
|
||||||
somejobs, err := broker.Search(states)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
jobs = append(jobs, somejobs...)
|
|
||||||
}
|
|
||||||
return jobs, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type recordedJob struct {
|
type recordedJob struct {
|
||||||
@@ -517,9 +679,14 @@ func sendJob(job broker.Job) (bool, error) {
|
|||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func sendNewZips(client string, zips []string) error {
|
||||||
|
sender := message.NewMatrix()
|
||||||
|
return sender.Send(fmt.Sprintf("%s: now searching for loads from zip codes: %+v", client, zips))
|
||||||
|
}
|
||||||
|
|
||||||
func sendNewStates(client string, states []config.State) error {
|
func sendNewStates(client string, states []config.State) error {
|
||||||
sender := message.NewMatrix()
|
sender := message.NewMatrix()
|
||||||
return sender.Send(fmt.Sprintf("%s: now searching for loads from: %+v", client, states))
|
return sender.Send(fmt.Sprintf("%s: now searching for loads from states: %+v", client, states))
|
||||||
}
|
}
|
||||||
|
|
||||||
func sendNewPause(client string, pause time.Time) error {
|
func sendNewPause(client string, pause time.Time) error {
|
||||||
|
|||||||
@@ -84,7 +84,7 @@ func (m *Matrix) Receive() ([]Message, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
logtr.Debugf("%s => {Start:%s End:%v};; %v, (%d)", m.Continuation(), result.Start, result.End, err, len(result.Chunk))
|
logtr.Verbosef("%s => {Start:%s End:%v};; %v, (%d)", m.Continuation(), result.Start, result.End, err, len(result.Chunk))
|
||||||
m.continuation = result.End
|
m.continuation = result.End
|
||||||
for _, event := range result.Chunk {
|
for _, event := range result.Chunk {
|
||||||
logtr.Verbosef("matrix event: %+v", event)
|
logtr.Verbosef("matrix event: %+v", event)
|
||||||
@@ -100,7 +100,7 @@ func (m *Matrix) Receive() ([]Message, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
clientChange := regexp.MustCompile("@[a-z]+$")
|
clientChange := regexp.MustCompile("@[a-z]+$")
|
||||||
logtr.Debugf("rewriting messages based on @abc")
|
logtr.Verbosef("rewriting messages based on @abc")
|
||||||
for i := range messages {
|
for i := range messages {
|
||||||
if found := clientChange.FindString(messages[i].Content); found != "" {
|
if found := clientChange.FindString(messages[i].Content); found != "" {
|
||||||
messages[i].Content = strings.TrimSpace(strings.ReplaceAll(messages[i].Content, found, ""))
|
messages[i].Content = strings.TrimSpace(strings.ReplaceAll(messages[i].Content, found, ""))
|
||||||
@@ -114,7 +114,7 @@ func (m *Matrix) Receive() ([]Message, error) {
|
|||||||
}
|
}
|
||||||
messages[i].Content = strings.TrimSpace(messages[i].Content)
|
messages[i].Content = strings.TrimSpace(messages[i].Content)
|
||||||
}
|
}
|
||||||
logtr.Debugf("rewriting messages based on ! CoMmAnD ...")
|
logtr.Verbosef("rewriting messages based on ! CoMmAnD ...")
|
||||||
for i := range messages {
|
for i := range messages {
|
||||||
if strings.HasPrefix(messages[i].Content, "!") {
|
if strings.HasPrefix(messages[i].Content, "!") {
|
||||||
messages[i].Content = "!" + strings.TrimSpace(messages[i].Content[1:])
|
messages[i].Content = "!" + strings.TrimSpace(messages[i].Content[1:])
|
||||||
@@ -231,7 +231,7 @@ func (m Matrix) SendImageTracked(uri string) (string, error) {
|
|||||||
}
|
}
|
||||||
publicURI := mediaUpload.ContentURI
|
publicURI := mediaUpload.ContentURI
|
||||||
resp, err := c.SendImage(m.room, "img", publicURI)
|
resp, err := c.SendImage(m.room, "img", publicURI)
|
||||||
logtr.Debugf("sent image %s => %s: %+v", uri, publicURI, resp)
|
logtr.Verbosef("sent image %s => %s: %+v", uri, publicURI, resp)
|
||||||
return resp.EventID, err
|
return resp.EventID, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,4 @@
|
|||||||
todo:
|
todo:
|
||||||
- fast exact is dumb or...?
|
|
||||||
- modify old items once no longer available; drop stale jobs good candidate but requires new matrix interaction
|
|
||||||
- more than NTG; blue one
|
- more than NTG; blue one
|
||||||
- !states emits current state
|
- !states emits current state
|
||||||
- test each !command callbacks to matrix
|
- test each !command callbacks to matrix
|
||||||
@@ -13,7 +11,12 @@ todo:
|
|||||||
subtasks:
|
subtasks:
|
||||||
- banlist criteria like vendors, brokers, metadata
|
- banlist criteria like vendors, brokers, metadata
|
||||||
- set up copy for caleb, broc
|
- set up copy for caleb, broc
|
||||||
|
- move from main() and make more functions
|
||||||
done:
|
done:
|
||||||
|
- modify old items once no longer available; drop stale jobs good candidate but requires new matrix interaction
|
||||||
|
- from states to zip codes w/ range
|
||||||
|
- fast exact does not use ID in UID because they spammy
|
||||||
|
- fast exact is dumb or...?
|
||||||
- try search ntg by autoinc?
|
- try search ntg by autoinc?
|
||||||
- TEST. Just like, refactor and test to shit.
|
- TEST. Just like, refactor and test to shit.
|
||||||
- mark jobs no longer avail by modifying in matrix;; save matrix ID over dummy payload
|
- mark jobs no longer avail by modifying in matrix;; save matrix ID over dummy payload
|
||||||
|
|||||||
33121
zip/testdata/simplemaps_uszips_basicv1.79/uszips.csv
vendored
Executable file
33121
zip/testdata/simplemaps_uszips_basicv1.79/uszips.csv
vendored
Executable file
File diff suppressed because it is too large
Load Diff
112
zip/zip.go
Normal file
112
zip/zip.go
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
package zip
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "embed"
|
||||||
|
"local/truckstop/logtr"
|
||||||
|
"math"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed testdata/simplemaps_uszips_basicv1.79/uszips.csv
|
||||||
|
var csv string
|
||||||
|
|
||||||
|
type Zip struct {
|
||||||
|
Lat float64
|
||||||
|
Lng float64
|
||||||
|
City string
|
||||||
|
State string
|
||||||
|
}
|
||||||
|
|
||||||
|
var zips map[string]Zip
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if len(zips) > 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
zips = map[string]Zip{}
|
||||||
|
trim := func(s string) string {
|
||||||
|
return strings.Trim(s, `"`)
|
||||||
|
}
|
||||||
|
for _, line := range strings.Split(csv, "\n")[1:] {
|
||||||
|
strs := strings.Split(line, ",")
|
||||||
|
if len(strs) < 5 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
zip := trim(strs[0])
|
||||||
|
lat, _ := strconv.ParseFloat(trim(strs[1]), 32)
|
||||||
|
lng, _ := strconv.ParseFloat(trim(strs[2]), 32)
|
||||||
|
city := trim(alphafy(strs[3]))
|
||||||
|
state := strings.ToUpper(trim(strs[4]))
|
||||||
|
zips[zip] = Zip{
|
||||||
|
Lat: lat,
|
||||||
|
Lng: lng,
|
||||||
|
City: city,
|
||||||
|
State: state,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
logtr.Infof("loaded %d zip codes", len(zips))
|
||||||
|
}
|
||||||
|
|
||||||
|
func alphafy(s string) string {
|
||||||
|
bs := make([]byte, 0, len(s)+1)
|
||||||
|
for i := range s {
|
||||||
|
if (s[i] < 'a' || s[i] > 'z') && (s[i] < 'A' || s[i] > 'Z') {
|
||||||
|
} else {
|
||||||
|
bs = append(bs, s[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.ToLower(string(bs))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (zip Zip) MilesTo(other Zip) int {
|
||||||
|
// c**2 = a**2 + b**2
|
||||||
|
// 69.2 mi per lat
|
||||||
|
// 60.0 mi per lng
|
||||||
|
return int(math.Sqrt(
|
||||||
|
math.Pow(69.2*(math.Abs(zip.Lat)-math.Abs(other.Lat)), 2) +
|
||||||
|
math.Pow(60.0*(math.Abs(zip.Lng)-math.Abs(other.Lng)), 2),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
func Get(zip string) Zip {
|
||||||
|
if z, ok := zips[zip]; ok {
|
||||||
|
return z
|
||||||
|
}
|
||||||
|
zipAsI, err := strconv.Atoi(strings.Split(zip, "-")[0])
|
||||||
|
if err != nil {
|
||||||
|
return Zip{}
|
||||||
|
}
|
||||||
|
for i := 0; i < 5; i++ {
|
||||||
|
j := i - 2
|
||||||
|
if z2, ok := zips[strconv.Itoa(zipAsI+j)]; ok {
|
||||||
|
return z2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Zip{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetStatesWithin(zip Zip, miles int) []string {
|
||||||
|
states := map[string]struct{}{}
|
||||||
|
for _, other := range zips {
|
||||||
|
if zip.MilesTo(other) <= miles {
|
||||||
|
states[other.State] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result := []string{}
|
||||||
|
for state := range states {
|
||||||
|
result = append(result, state)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func FromCityState(city, state string) Zip {
|
||||||
|
city = alphafy(city)
|
||||||
|
state = strings.ToUpper(state)
|
||||||
|
for _, z := range zips {
|
||||||
|
if z.City == city && z.State == state {
|
||||||
|
return z
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Zip{}
|
||||||
|
}
|
||||||
28
zip/zip_test.go
Normal file
28
zip/zip_test.go
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package zip
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestZip(t *testing.T) {
|
||||||
|
_ = true
|
||||||
|
zip27006 := Get("27006")
|
||||||
|
zip84059 := Get("84059")
|
||||||
|
t.Logf("27006 = %+v", zip27006)
|
||||||
|
t.Logf("84059 = %+v", zip84059)
|
||||||
|
if zip27006.MilesTo(zip84059) < 1800 {
|
||||||
|
t.Error("failed to compute miles from advance to ut")
|
||||||
|
}
|
||||||
|
sorted := func(s []string) []string {
|
||||||
|
sort.Strings(s)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
if got := GetStatesWithin(Get("27006"), 100); fmt.Sprint(sorted(got)) != fmt.Sprint(sorted([]string{"NC", "SC", "TN", "VA"})) {
|
||||||
|
t.Error(got)
|
||||||
|
}
|
||||||
|
if got := FromCityState("ADVANCE", "nc"); got != zip27006 {
|
||||||
|
t.Error(got)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user