Compare commits

...

18 Commits

Author SHA1 Message Date
Bel LaPointe
2e9e0c5816 try another cookie format, ntg submits ntgauthtoken as cookie 2022-01-27 14:01:13 -07:00
Bel LaPointe
ba2156133a cookie jar go 2022-01-27 11:00:05 -07:00
bel
60c88375ad wip 2022-01-27 10:38:41 -07:00
bel
a127d9fd25 no newline in log 2022-01-27 08:16:20 -07:00
bel
8c6b55301d moer logging 2022-01-27 08:13:32 -07:00
bel
3c36948269 whoops cant compile 2022-01-27 07:49:46 -07:00
bel
bc2efe928a better ntg errs 2022-01-27 07:47:55 -07:00
bel
e1b4460ebd add day to log as i can only login to ntg 30 times per week it seems 2022-01-27 07:44:30 -07:00
bel
9bb9929ff6 cant edit, but on job no more, del entry 2022-01-19 06:12:13 -07:00
bel
a6c1b8505a ew at least del image 2022-01-18 14:43:04 -07:00
bel
c755aa88fb no 2022-01-18 14:41:37 -07:00
bel
b451ed93bf origin from date lower 2022-01-18 11:27:32 -07:00
bel
76b7211d6c todo 2022-01-18 07:55:25 -07:00
bel
31a608d7f8 whoops tahts not an err 2022-01-18 07:46:24 -07:00
bel
0c3419a1fb impl job uid in case somebody reuses ids 2022-01-18 07:42:23 -07:00
bel
6ea4d4700c whoops dont reuse not same uri 2022-01-18 06:40:55 -07:00
bel
451f741f5a wrap errs for easier read 2022-01-18 06:37:06 -07:00
bel
ecf22c3a3d todo 2022-01-17 22:04:57 -07:00
12 changed files with 365 additions and 83 deletions

View File

@@ -2,9 +2,13 @@ package broker
import ( import (
"context" "context"
"encoding/json"
"local/storage"
"local/truckstop/config" "local/truckstop/config"
"local/truckstop/logtr"
"net/http" "net/http"
"strings" "strings"
"time"
"golang.org/x/time/rate" "golang.org/x/time/rate"
) )
@@ -20,9 +24,77 @@ type Broker interface {
} }
func do(r *http.Request) (*http.Response, error) { func do(r *http.Request) (*http.Response, error) {
return _do(config.Get().DB(), r)
}
func _do(db storage.DB, r *http.Request) (*http.Response, error) {
limiter.Wait(context.Background()) limiter.Wait(context.Background())
if strings.Contains(strings.ToLower(r.URL.Path), "login") { if strings.Contains(strings.ToLower(r.URL.Path), "login") {
authlimiter.Wait(context.Background()) authlimiter.Wait(context.Background())
} }
return http.DefaultClient.Do(r) client := &http.Client{
Timeout: time.Hour,
}
cookieJarKey := "cookies_" + r.URL.Host
cookies, err := getCookies(db, cookieJarKey)
if err != nil {
logtr.Errorf("failed to get cookies: %v", err)
} else {
logtr.Verbosef("got cookies for %s: %+v", cookieJarKey, cookies)
for _, cookie := range cookies {
r.Header.Add("Cookie", cookie)
}
}
logtr.Verbosef("_do: %+v", r)
resp, err := client.Do(r)
if err != nil {
return nil, err
}
if err := setCookies(db, cookieJarKey, resp); err != nil {
logtr.Errorf("failed to set cookies: %v", err)
}
return resp, err
}
func getCookies(db storage.DB, host string) ([]string, error) {
b, err := db.Get(host)
if err != nil {
return nil, err
}
var result []string
err = json.Unmarshal(b, &result)
return result, err
}
func setCookies(db storage.DB, host string, resp *http.Response) error {
nameValues := [][2]string{}
old, _ := getCookies(db, host)
for _, value := range old {
name := strings.Split(value, "=")[0]
nameValues = append(nameValues, [2]string{name, value})
}
for _, value := range resp.Header["Set-Cookie"] {
name := strings.Split(value, "=")[0]
found := false
for i := range nameValues {
if nameValues[i][0] == name {
found = true
nameValues[i][1] = value
}
}
if !found {
nameValues = append(nameValues, [2]string{name, value})
}
}
result := []string{}
for i := range nameValues {
result = append(result, nameValues[i][1])
}
logtr.Verbosef("setting cookies for %s: %+v", host, result)
b, err := json.Marshal(result)
if err != nil {
return err
}
return db.Set(host, b)
} }

69
broker/broker_test.go Normal file
View File

@@ -0,0 +1,69 @@
package broker
import (
"fmt"
"local/storage"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"golang.org/x/time/rate"
)
func TestBrokerInterface(t *testing.T) {
var b Broker
b = NTGVision{}
_ = b
}
func TestDoCookies(t *testing.T) {
limiter = rate.NewLimiter(rate.Limit(20.0), 1)
calls := 0
db := storage.NewMap()
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls += 1
if calls != 1 {
if !strings.Contains(fmt.Sprint(r.Header["Cookie"]), "name=value"+strconv.Itoa(calls-1)) {
w.WriteHeader(http.StatusBadRequest)
t.Error("cookie not set as latest")
}
if !strings.Contains(fmt.Sprint(r.Header["Cookie"]), "Expires") {
w.WriteHeader(http.StatusBadRequest)
t.Error("cookie not expiration: ", r.Header["Cookie"])
}
}
http.SetCookie(w, &http.Cookie{
Name: "name",
Value: "value" + strconv.Itoa(calls),
Expires: time.Now().Add(time.Hour),
})
}))
defer s.Close()
req, _ := http.NewRequest(http.MethodGet, s.URL, nil)
if cookies, err := getCookies(db, "cookies_"+req.URL.Host); err == nil {
t.Fatal(err)
} else if len(cookies) != 0 {
t.Fatal(cookies)
}
for i := 0; i < 3; i++ {
resp, err := _do(db, req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusOK {
t.Fatal(resp.StatusCode)
}
resp.Body.Close()
if cookies, err := getCookies(db, "cookies_"+req.URL.Host); err != nil {
t.Fatal(err)
} else if len(cookies) == 0 {
t.Fatal(cookies)
}
}
}

View File

@@ -1,6 +1,7 @@
package broker package broker
import ( import (
"encoding/base64"
"fmt" "fmt"
"local/truckstop/config" "local/truckstop/config"
"local/truckstop/logtr" "local/truckstop/logtr"
@@ -26,6 +27,18 @@ type JobLocation struct {
State string State string
} }
func (j Job) UID() string {
return fmt.Sprintf(
"%v-%s-%s-%s-%s-%v",
j.ID,
j.Pickup.State,
base64.StdEncoding.EncodeToString([]byte(j.Pickup.City)),
j.Dropoff.State,
base64.StdEncoding.EncodeToString([]byte(j.Dropoff.City)),
j.Pickup.Date.Unix(),
)
}
func (j *Job) Secrets() { func (j *Job) Secrets() {
if j.secrets == nil { if j.secrets == nil {
return return

View File

@@ -109,7 +109,7 @@ func (ntgJob *ntgVisionJob) JobInfo() (ntgVisionJobInfo, error) {
func (ntg NTGVision) searchJob(id int64) (io.ReadCloser, error) { func (ntg NTGVision) searchJob(id int64) (io.ReadCloser, error) {
time.Sleep(config.Get().Interval.JobInfo.Get()) time.Sleep(config.Get().Interval.JobInfo.Get())
request, err := http.NewRequest(http.MethodGet, fmt.Sprintf(config.Get().Brokers.NTG.LoadPageURIFormat, id), nil) request, err := http.NewRequest(http.MethodGet, fmt.Sprintf(config.Get().Brokers.NTG.LoadPageAPIURIFormat, id), nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -175,8 +175,15 @@ func (ntg NTGVision) SearchJob(id int64) (ntgVisionJobInfo, error) {
return ntgVisionJobInfo{}, err return ntgVisionJobInfo{}, err
} }
defer rc.Close() defer rc.Close()
b, err := ioutil.ReadAll(rc)
if err != nil {
return ntgVisionJobInfo{}, fmt.Errorf("failed to readall search job result: %w", err)
}
var result ntgVisionJobInfo var result ntgVisionJobInfo
err = json.NewDecoder(rc).Decode(&result) err = json.Unmarshal(b, &result)
if err != nil {
err = fmt.Errorf("failed to parse job info: %w: %s", err, b)
}
return result, err return result, err
} }
@@ -221,12 +228,14 @@ func setNTGToken(token string) {
func (ntg NTGVision) search(states []config.State) (io.ReadCloser, error) { func (ntg NTGVision) search(states []config.State) (io.ReadCloser, error) {
if getNTGToken() == "" { if getNTGToken() == "" {
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._search(states)
if err == ErrNoAuth { if err == ErrNoAuth {
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
} }
@@ -288,7 +297,11 @@ func (ntg NTGVision) _search(states []config.State) (io.ReadCloser, error) {
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
b, _ := ioutil.ReadAll(resp.Body) b, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close() resp.Body.Close()
if resp.StatusCode > 400 && resp.StatusCode < 500 && resp.StatusCode != 404 && resp.StatusCode != 410 { request2, _ := ntg.newRequest(states)
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)
if resp.StatusCode > 400 && resp.StatusCode < 404 {
logtr.Debugf("ntg auth bad status: err no auth")
return nil, ErrNoAuth return nil, ErrNoAuth
} }
return nil, fmt.Errorf("bad status searching ntg: %d: %s", resp.StatusCode, b) return nil, fmt.Errorf("bad status searching ntg: %d: %s", resp.StatusCode, b)
@@ -298,7 +311,7 @@ func (ntg NTGVision) _search(states []config.State) (io.ReadCloser, error) {
func (ntg NTGVision) newRequest(states []config.State) (*http.Request, error) { func (ntg NTGVision) newRequest(states []config.State) (*http.Request, error) {
body, err := json.Marshal(map[string]interface{}{ body, err := json.Marshal(map[string]interface{}{
"OriginFromDate": time.Now().UTC().Format("2006-01-02T15:04:05.000Z"), "OriginFromDate": time.Now().Add(time.Hour * -24).UTC().Format("2006-01-02T15:04:05.000Z"),
"OriginToDate": time.Now().UTC().Add(time.Hour * 24 * 30).Format("2006-01-02T15:04:05.000Z"), "OriginToDate": time.Now().UTC().Add(time.Hour * 24 * 30).Format("2006-01-02T15:04:05.000Z"),
"DestinationFromDate": nil, "DestinationFromDate": nil,
"DestinationToDate": nil, "DestinationToDate": nil,
@@ -322,6 +335,7 @@ func (ntg NTGVision) newRequest(states []config.State) (*http.Request, error) {
} }
setNTGHeaders(request) setNTGHeaders(request)
request.Header.Set("Authorization", "Bearer "+getNTGToken()) request.Header.Set("Authorization", "Bearer "+getNTGToken())
request.Header.Set("Cookie", "NTGAuthToken="+getNTGToken())
return request, nil return request, nil
} }

View File

@@ -75,8 +75,9 @@
"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",
"Username": "noeasyrunstrucking@gmail.com", "Username": "noeasyrunstrucking@gmail.com",
"Password": "thumper1234" "Password": "thumper12345"
} }
} }
} }

83
config.main_test.json Normal file
View File

@@ -0,0 +1,83 @@
{
"Log": {
"Path": "/tmp/truckstop.log",
"Level": "sos",
"SOSMatrix": {
"ReceiveEnabled": true,
"Mock": true,
"Homeserver": "https://m.bltrucks.top",
"Username": "@bot.m.bltrucks.top",
"Token": "mvDWB96KXMF8XhOam8EC5XVdQvSEw0CDeClcSWocBcYkwZX3FPNWZ5uOnQk2EmT1cjpzfeuD7gDYPPjOuyZlI3bE9TE35UjNOlZgi0Tugm25s91iVsbIF6kMZsCIhVMSmEf6w3jxX6wQYOWvmDZ4mu6f5c8wr221EMDcOpEzQV09d1zuBSWgKLBgjqAkYHJZ5dTRIWpEDpPgujhOFZa2ld1HiAOxrJKlIrlfDBN0CUsTlGOGplujDAr4VtpFzNRS",
"Device": "TGNIOGKATZ",
"Room": "!OYZqtInrBCn1cyz90D:m.bltrucks.top"
}
},
"Interval": {
"Input": "5s..10s",
"OK": "6h0m0s..6h0m0s",
"Error": "6h0m0s..6h0m0s",
"JobInfo": "10s..20s"
},
"Images": {
"ClientID": "d9ac7cabe813d10",
"ClientSecret": "9d0b3d82800b30ca88f595d3bcd6985f627d7d82",
"RefreshToken": "171417741bf762b99b0b9f9137491b7a69874a77",
"AccessToken": "e63db98f92d2db7ac7f56914a2030c889b378e9b",
"RefreshURI": "https://api.imgur.com/oauth2/token",
"RefreshFormat": "refresh_token=%s\u0026client_id=%s\u0026client_secret=%s\u0026grant_type=refresh_token",
"RefreshMethod": "POST",
"UploadURI": "https://api.imgur.com/3/image?name=something.jpeg",
"UploadMethod": "POST"
},
"Maps": {
"URIFormat": "https://maps.googleapis.com/maps/api/staticmap?center=%s\u0026markers=label=A|%s\u0026zoom=5\u0026size=250x250\u0026scale=1\u0026format=jpeg\u0026maptype=roadmap\u0026key=AIzaSyBkACm-LQkoSfsTO5_XAzBVZE9-JQzcNkg",
"Pickup": false,
"Dropoff": false,
"Pathed": {
"Enabled": true,
"DirectionsURIFormat": "https://maps.googleapis.com/maps/api/directions/json?origin=%s\u0026destination=%s\u0026mode=driving\u0026key=AIzaSyBkACm-LQkoSfsTO5_XAzBVZE9-JQzcNkg",
"PathedURIFormat": "https://maps.googleapis.com/maps/api/staticmap?size=250x250\u0026path=%s\u0026format=jpeg\u0026maptype=roadmap\u0026key=AIzaSyBkACm-LQkoSfsTO5_XAzBVZE9-JQzcNkg\u0026size=250x250\u0026markers=%s|%s",
"Zoom": {
"AcceptableLatLngDelta": 2,
"Override": 5
}
}
},
"Clients": {
"bel": {
"States": [
"NC"
],
"IDs": {
"Matrix": "@bel:m.bltrucks.top"
},
"Available": 1512328400
}
},
"Storage": [
"files",
"/tmp/play"
],
"Message": {
"Matrix": {
"ReceiveEnabled": true,
"Mock": true,
"Homeserver": "https://m.bltrucks.top",
"Username": "@bot.m.bltrucks.top",
"Token": "mvDWB96KXMF8XhOam8EC5XVdQvSEw0CDeClcSWocBcYkwZX3FPNWZ5uOnQk2EmT1cjpzfeuD7gDYPPjOuyZlI3bE9TE35UjNOlZgi0Tugm25s91iVsbIF6kMZsCIhVMSmEf6w3jxX6wQYOWvmDZ4mu6f5c8wr221EMDcOpEzQV09d1zuBSWgKLBgjqAkYHJZ5dTRIWpEDpPgujhOFZa2ld1HiAOxrJKlIrlfDBN0CUsTlGOGplujDAr4VtpFzNRS",
"Device": "TGNIOGKATZ",
"Room": "!OYZqtInrBCn1cyz90D:m.bltrucks.top"
}
},
"Once": true,
"Brokers": {
"NTG": {
"JobInfo": true,
"Mock": true,
"LoadPageURIFormat": "https://ntgvision.com/LoadDetails?loadId=%d",
"LoadPageAPIURIFormat": "https://ntgvision.com/api/v1/load/LoadDetails?loadId==%d",
"Username": "noeasyrunstrucking@gmail.com",
"Password": "thumper1234"
}
}
}

View File

@@ -65,11 +65,17 @@ type Config struct {
Once bool Once bool
Brokers struct { Brokers struct {
NTG struct { NTG struct {
JobInfo bool JobInfo bool
Mock bool Mock bool
LoadPageURIFormat string LoadPageURIFormat string
Username string LoadPageAPIURIFormat string
Password string Username string
Password string
}
FastExact struct {
Mock bool
Username string
Password string
} }
} }

View File

@@ -7,56 +7,56 @@ import (
type State string type State string
var States = map[string]State{ var States = map[State]string{
"99654": "AL", "AL": "99654",
"72401": "AR", "AR": "72401",
"85364": "AZ", "AZ": "85364",
"90011": "CA", "CA": "90011",
"80013": "CO", "CO": "80013",
"06902": "CT", "CT": "06902",
"19720": "DE", "DE": "19720",
"33024": "FL", "FL": "33024",
"30043": "GA", "GA": "30043",
"96706": "HI", "HI": "96706",
"50613": "IA", "IA": "50613",
"83646": "ID", "ID": "83646",
"60629": "IL", "IL": "60629",
"47906": "IN", "IN": "47906",
"66062": "KS", "KS": "66062",
"40475": "KY", "KY": "40475",
"70726": "LA", "LA": "70726",
"02301": "MA", "MA": "02301",
"20906": "MD", "MD": "20906",
"04401": "ME", "ME": "04401",
"48197": "MI", "MI": "48197",
"55106": "MN", "MN": "55106",
"63376": "MO", "MO": "63376",
"39503": "MS", "MS": "39503",
"59901": "MT", "MT": "59901",
"27006": "NC", "NC": "27006",
"58103": "ND", "ND": "58103",
"68516": "NE", "NE": "68516",
"03103": "NH", "NH": "03103",
"08701": "NJ", "NJ": "08701",
"87121": "NM", "NM": "87121",
"89108": "NV", "NV": "89108",
"11368": "NY", "NY": "11368",
"45011": "OH", "OH": "45011",
"73099": "OK", "OK": "73099",
"97006": "OR", "OR": "97006",
"19120": "PA", "PA": "19120",
"02860": "RI", "RI": "02860",
"29483": "SC", "SC": "29483",
"57106": "SD", "SD": "57106",
"37013": "TN", "TN": "37013",
"77449": "TX", "TX": "77449",
"84058": "UT", "UT": "84058",
"22193": "VA", "VA": "22193",
"05401": "VT", "VT": "05401",
"99301": "WA", "WA": "99301",
"53215": "WI", "WI": "53215",
"26554": "WV", "WV": "26554",
"82001": "WY", "WY": "82001",
} }
func (state *State) UnmarshalJSON(b []byte) error { func (state *State) UnmarshalJSON(b []byte) error {
@@ -65,8 +65,8 @@ func (state *State) UnmarshalJSON(b []byte) error {
return err return err
} }
for k := range States { for k := range States {
if string(States[k]) == s { if string(k) == s {
*state = States[k] *state = k
return nil return nil
} }
} }

View File

@@ -82,15 +82,18 @@ func SetLevel(l Level) {
} }
func logf(l Level, format string, args []interface{}) { func logf(l Level, format string, args []interface{}) {
format = fmt.Sprintf("%v: %v: %s\n", time.Now().Format("15:04:05"), l.String(), strings.TrimSpace(format)) format = fmt.Sprintf("%v: %v: %s\n", time.Now().Format("01-02T15:04:05"), l.String(), strings.TrimSpace(format))
logContent := strings.ReplaceAll(fmt.Sprintf(format, args...), "\n", "") + "\n"
cLevel := level cLevel := level
cAnsoser := ansoser cAnsoser := ansoser
if l >= cLevel { if l >= cLevel {
fmt.Fprintf(os.Stderr, format, args...) fmt.Fprint(os.Stderr, logContent)
} }
fmt.Fprintf(logger, format, args...) fmt.Fprint(logger, logContent)
if l == SOS && cAnsoser != nil { if l == SOS && cAnsoser != nil {
cAnsoser.Send(fmt.Sprintf(format, args...)) if err := cAnsoser.Send(logContent); err != nil {
Errorf("failed to SOS: %v", err)
}
} }
} }

37
main.go
View File

@@ -9,7 +9,6 @@ import (
"local/truckstop/config" "local/truckstop/config"
"local/truckstop/logtr" "local/truckstop/logtr"
"local/truckstop/message" "local/truckstop/message"
"log"
"net/http" "net/http"
"net/url" "net/url"
"regexp" "regexp"
@@ -22,13 +21,19 @@ import (
var stateFinder = regexp.MustCompile(`[A-Za-z]+`) var stateFinder = regexp.MustCompile(`[A-Za-z]+`)
func main() { func main() {
if err := config.Refresh(message.NewSOSMatrix); err != nil { if err := _main(); err != nil {
panic(err) panic(err)
} }
}
func _main() error {
if err := config.Refresh(message.NewSOSMatrix); err != nil {
return err
}
if config.Get().Message.Matrix.ReceiveEnabled { if config.Get().Message.Matrix.ReceiveEnabled {
if err := matrixrecv(); err != nil { if err := matrixrecv(); err != nil {
logtr.SOSf("failed to recv matrix on boot: %v", err) logtr.SOSf("failed to recv matrix on boot: %v", err)
panic(err) return err
} }
} }
lock := &sync.Mutex{} lock := &sync.Mutex{}
@@ -48,11 +53,12 @@ func main() {
} }
} }
}() }()
if err := _main(); err != nil { if err := __main(); err != nil {
logtr.SOSf("failed _main: %v", err) logtr.SOSf("failed __main: %v", err)
panic(err) return err
} }
lock.Lock() lock.Lock()
return nil
} }
func matrixrecv() error { func matrixrecv() error {
@@ -229,9 +235,9 @@ func parseOutStates(b []byte) []config.State {
return states return states
} }
func _main() error { func __main() error {
for { for {
err := _mainOne() err := __mainOne()
if err != nil { if err != nil {
logtr.Errorf("failed _main: %v", err) logtr.Errorf("failed _main: %v", err)
} }
@@ -248,7 +254,7 @@ func _main() error {
return nil return nil
} }
func _mainOne() error { func __mainOne() error {
logtr.Debugf("config.refreshing...") logtr.Debugf("config.refreshing...")
if err := config.Refresh(message.NewSOSMatrix); err != nil { if err := config.Refresh(message.NewSOSMatrix); err != nil {
logtr.SOSf("bad config: %v", err) logtr.SOSf("bad config: %v", err)
@@ -259,7 +265,7 @@ func _mainOne() error {
logtr.SOSf("failed once(): %v", err) logtr.SOSf("failed once(): %v", err)
return err return err
} }
logtr.Debugf("/_mainOne") logtr.Debugf("/__mainOne")
return nil return nil
} }
@@ -292,12 +298,13 @@ func once() error {
jobs[i].Secrets() jobs[i].Secrets()
} }
logtr.Infof("once: sending jobs: %+v", jobs) logtr.Infof("once: sending jobs: %+v", jobs)
db := config.Get().DB()
for i := range jobs { for i := range jobs {
if ok, err := sendJob(jobs[i]); err != nil { if ok, err := sendJob(jobs[i]); err != nil {
return err return err
} else if ok { } else if ok {
logtr.Debugf("sent job", jobs[i]) logtr.Debugf("sent job", jobs[i])
if err := config.Get().DB().Set(jobs[i].ID, []byte(`sent`)); err != nil { if err := db.Set(jobs[i].UID(), []byte(`sent`)); err != nil {
return err return err
} }
} }
@@ -333,7 +340,6 @@ func updateDeadJobs(jobs []broker.Job) error {
if err != nil { if err != nil {
return err return err
} }
log.Printf("db.List() => %+v", list)
for _, listEntry := range list { for _, listEntry := range list {
wouldBe := strings.TrimPrefix(listEntry, "sent_job_") wouldBe := strings.TrimPrefix(listEntry, "sent_job_")
found := false found := false
@@ -351,9 +357,14 @@ func updateDeadJobs(jobs []broker.Job) error {
if err := json.Unmarshal(b, &recorded); err != nil { if err := json.Unmarshal(b, &recorded); err != nil {
return err return err
} }
/* // TODO this beeps on fluffychat
if err := message.NewMatrix().Update(recorded.MatrixID, recorded.Job.FormatMultilineTextDead()); err != nil { if err := message.NewMatrix().Update(recorded.MatrixID, recorded.Job.FormatMultilineTextDead()); err != nil {
return err return err
} }
*/
if err := message.NewMatrix().Remove(recorded.MatrixID); err != nil {
return err
}
if err := db.Set(listEntry, nil); err != nil { if err := db.Set(listEntry, nil); err != nil {
return err return err
} }
@@ -370,7 +381,7 @@ func updateDeadJobs(jobs []broker.Job) error {
func dropStaleJobs(jobs []broker.Job) ([]broker.Job, error) { func dropStaleJobs(jobs []broker.Job) ([]broker.Job, error) {
db := config.Get().DB() db := config.Get().DB()
for i := len(jobs) - 1; i >= 0; i-- { for i := len(jobs) - 1; i >= 0; i-- {
if _, err := db.Get(jobs[i].ID); err == storage.ErrNotFound { if _, err := db.Get(jobs[i].UID()); err == storage.ErrNotFound {
} else if err != nil { } else if err != nil {
return nil, err return nil, err
} else { } else {

View File

@@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"local/truckstop/config" "local/truckstop/config"
"os"
"testing" "testing"
) )
@@ -33,3 +34,10 @@ Content-Type: text/html; charset="UTF-8"
t.Fatal(want, got) t.Fatal(want, got)
} }
} }
func TestMain(t *testing.T) {
os.Setenv("CONFIG", "./config.main_test.json")
if err := _main(); err != nil {
t.Fatal(err)
}
}

View File

@@ -1,10 +1,11 @@
todo: todo:
- mark jobs no longer avail by modifying in matrix;; save matrix ID over dummy payload - !states emits current state
- recv-as for clients so pa receives mas commands as writes - TEST. Just like, refactor and test to shit.
- try search ntg by autoinc? - try search ntg by autoinc?
- test each !command callbacks to matrix
- recv-as for clients so pa receives mas commands as writes
- continuation is garbo, but I can still do better client side to avoid get-set high level - continuation is garbo, but I can still do better client side to avoid get-set high level
- no hard code jpeg or have it in multiple places - no hard code jpeg or have it in multiple places
- test each !command callbacks to matrix
- change matrix so I test my custom logic even if I dont fetch remote - change matrix so I test my custom logic even if I dont fetch remote
- warn/err/etc. on clobbering ids.matrix since clients can mess with one another - warn/err/etc. on clobbering ids.matrix since clients can mess with one another
- modify old items once no longer available; drop stale jobs good candidate but requires new matrix interaction - modify old items once no longer available; drop stale jobs good candidate but requires new matrix interaction
@@ -14,6 +15,7 @@ todo:
- banlist criteria like vendors, brokers, metadata - banlist criteria like vendors, brokers, metadata
- set up copy for caleb, broc - set up copy for caleb, broc
done: done:
- mark jobs no longer avail by modifying in matrix;; save matrix ID over dummy payload
- TEST its falling apart - TEST its falling apart
- help() log on truckstop for stuff like perma 403 - help() log on truckstop for stuff like perma 403
- figure out zoom on maps;; is there like an auto-zoom I can leverage? - figure out zoom on maps;; is there like an auto-zoom I can leverage?