This repository has been archived by the owner on Jan 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheddnlistener.go
1399 lines (1272 loc) · 38.7 KB
/
eddnlistener.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"compress/zlib"
"database/sql"
"encoding/json"
"errors"
"io"
"log"
"math"
"runtime"
"strconv"
"strings"
"time"
"./config"
"./dataDefs"
_ "github.com/mattn/go-sqlite3" // SQLite driver
zmq "github.com/pebbe/zmq4" // ZeroMQ
)
// Constants
var dataDir string = config.GetEnvWithDefault("EDDP_API_DATA_DIR", "./data")
var eddnListenerURL string = config.GetEnvWithDefault("EDDP_API_EDDN_LISTENER_URL", "tcp://eddn.edcd.io:9500")
var eddnPublisherURL string = config.GetEnvWithDefault("EDDP_API_EDDN_PUBLISHER_URL", "tcp://*:5556")
var msgChannelBufferCount int = 100
// Database connections
var eddpDb *sql.DB
type Systems struct {
System []struct {
data map[string]interface{}
}
}
func assertNil(e error) {
if e != nil {
log.Print(e)
panic(e)
}
}
func errFound(e error, msg string) bool {
if e != nil {
log.Print(e)
log.Print(msg)
return true
}
return false
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
for {
var err error
eddpDb, err = sql.Open("sqlite3", dataDir+"/sqlite/eddp.sqlite")
if err != nil {
log.Print(err)
}
defer eddpDb.Close()
subscriber, _ := zmq.NewSocket(zmq.SUB)
defer subscriber.Close()
subscriber.Connect(eddnListenerURL)
subscriber.SetSubscribe("")
publisher, _ := zmq.NewSocket(zmq.PUB)
publisher.Bind(eddnPublisherURL)
defer publisher.Close()
msgChannel := make(chan [][]byte, msgChannelBufferCount)
quitChannel := make(chan bool)
go HandlerLoop(publisher, msgChannel, quitChannel)
for {
raw, err := subscriber.RecvMessageBytes(0)
if err != nil {
quitChannel <- true
break
}
msgChannel <- raw
}
}
}
func HandlerLoop(publisher *zmq.Socket, msgChannel chan [][]byte, quitChannel chan bool) {
for {
select {
case <-quitChannel:
break
case raw := <-msgChannel:
{
go func() {
var msg bytes.Buffer
r, _ := zlib.NewReader(bytes.NewReader(raw[0]))
// TODO: not convinced we need this copy -- pass interfaces instead
io.Copy(&msg, r)
r.Close()
HandleMessage(&msg, publisher)
}()
}
}
}
}
func HandleMessage(msg *bytes.Buffer, publisher *zmq.Socket) {
// Turn the message in to JSON
d := json.NewDecoder(strings.NewReader(msg.String()))
d.UseNumber()
var data map[string]interface{}
err := d.Decode(&data)
if errFound(err, msg.String()) {
return
}
// Check to see if it is interesting to us and not blocked
clientName := data["header"].(map[string]interface{})["softwareName"].(string)
clientVersion := data["header"].(map[string]interface{})["softwareVersion"].(string)
if !ClientAllowed(clientName, clientVersion) {
return
}
schema := data["$schemaRef"].(string)
if schema == "https://eddn.edcd.io/schemas/journal/1" {
event := data["message"].(map[string]interface{})["event"].(string)
if event == "FSDJump" {
HandleFSDJumpEvent(msg.String(), data["message"].(map[string]interface{}), publisher)
} else if event == "Docked" {
HandleDockedEvent(msg.String(), data["message"].(map[string]interface{}), publisher)
} else if event == "Scan" {
stellarMass := data["message"].(map[string]interface{})["StellarMass"]
if stellarMass == nil {
HandleBodyScanEvent(msg.String(), data["message"].(map[string]interface{}), publisher)
} else {
HandleStarScanEvent(msg.String(), data["message"].(map[string]interface{}), publisher)
}
}
} else if schema == "https://eddn.edcd.io/schemas/commodity/3" {
HandleCommodity3Schema(msg.String(), data["message"].(map[string]interface{}), publisher)
} else if schema == "https://eddn.edcd.io/schemas/outfitting/2" {
HandleOutfitting2Schema(msg.String(), data["message"].(map[string]interface{}), publisher)
}
}
func ClientAllowed(client string, version string) bool {
// ED-IBE sends bad timestamps (e.g. 2017-01-17T20:43:33+01:00Z) so we can't use it
if client == "ED-IBE (API)" {
return false
}
// EDCE sends bad timestamps (e.g. 2017-01-18T15:04:04.582385) so we can't use it
if client == "EDCE" {
return false
}
// Elite G19s Companion App sends bad timestamps (e.g. 2017-01-20T09:19:13) so we can't use it
if client == "Elite G19s Companion App" {
return false
}
// EVA [iPhone] sends bad timestamps (e.g 2017-01-19T10:53:28 pmZ) so we can't use it
if client == "EVA [iPhone]" {
return false
}
// EVA [iPad] sends bad timestamps (e.g 2017-01-19T10:53:28 pmZ) so we can't use it
if client == "EVA [iPad]" {
return false
}
return true
}
func HandleBodyScanEvent(raw string, event map[string]interface{}, publisher *zmq.Socket) {
systemname := event["StarSystem"].(string)
bodyname := event["BodyName"].(string)
// Fetch the current system from the database
systemx, err := Float(event["StarPos"].([]interface{})[0])
assertNil(err)
systemx = fixCoord(systemx)
systemy, err := Float(event["StarPos"].([]interface{})[1])
assertNil(err)
systemy = fixCoord(systemy)
systemz, err := Float(event["StarPos"].([]interface{})[2])
assertNil(err)
systemz = fixCoord(systemz)
systemdata, err := FetchSystem(systemname, systemx, systemy, systemz)
if err != nil {
// System doesn't exist - ignore
} else {
// Turn the system in to JSON
d := json.NewDecoder(strings.NewReader(systemdata))
d.UseNumber()
var system map[string]interface{}
err = d.Decode(&system)
if errFound(err, raw) {
return
}
// Now fetch the body
systemId, err := Int(system["id"])
if errFound(err, raw) {
return
}
body, err := FetchBody(systemId, bodyname)
var exists bool
if err != nil {
exists = false
body = make(map[string]interface{})
body["created_at"] = int32(time.Now().Unix())
} else {
exists = true
}
body["updated_at"] = int32(time.Now().Unix())
// Periapsis
periapsis, err := Float(event["Periapsis"])
if err == nil {
body["arg_of_periapsis"] = periapsis
}
// Distance
distance, err := Float(event["DistanceFromArrivalLS"])
if err == nil {
body["distance_to_arrival"] = distance
}
// Eccentricity
eccentricity, err := Float(event["Eccentricity"])
if err == nil {
body["orbital_eccentricity"] = eccentricity
}
// Mass
mass, err := Float(event["MassEM"])
if err == nil {
body["earth_masses"] = mass
}
// Gravity
gravity, err := Float(event["Gravity"])
if err == nil {
body["gravity"] = gravity / 9.80665
}
body["group_id"] = 6
body["group_name"] = "Planet"
body["is_landable"] = event["Landable"]
body["is_rotational_period_tidally_locked"] = event["TidalLock"]
// Materials
if event["Materials"] != nil {
switch v := event["Materials"].(type) {
case []interface{}:
materials := event["Materials"].([]interface{})
// Build materials
var materialsJson []map[string]interface{}
materialsJson = make([]map[string]interface{}, len(materials))
// transform each
for i := range materials {
var materialJson map[string]interface{}
materialJson = make(map[string]interface{})
material := materials[i].(map[string]interface{})
materialJson["material_name"] = TranslateMaterial(material["Name"].(string))
share, err := Float(material["Percent"])
if err == nil {
materialJson["share"] = share
}
materialsJson[i] = materialJson
}
body["materials"] = materialsJson
default:
log.Print("Unhandled materials type ", v, "; event is ", event)
}
}
body["name"] = bodyname
// Orbital inclination
inclination, err := Float(event["OrbitalInclination"])
if err == nil {
body["orbital_inclination"] = inclination
}
// Orbital period
orbitalPeriod, err := Float(event["OrbitalPeriod"])
if err == nil {
body["orbital_period"] = orbitalPeriod
}
// Radius
radius, err := Float(event["Radius"])
if err == nil {
body["radius"] = radius / 1000
}
// Rotational period
rotationalPeriod, err := Float(event["RotationPeriod"])
if err == nil {
body["rotational_period"] = rotationalPeriod / 86400
}
// Semi-major axis
semiMajorAxis, err := Float(event["SemiMajorAxis"])
if err == nil {
body["semi_major_axis"] = semiMajorAxis / 149597870700
}
// Surface pressure
pressure, err := Float(event["SurfacePressure"])
if err == nil {
body["surface_pressure"] = pressure / 101325
}
// Surface temperature
surfaceTemperature, err := Float(event["SurfaceTemperature"])
if err == nil {
body["surface_temperature"] = surfaceTemperature
}
// Terraforming state
terraformState := event["TerraformState"]
if terraformState == "" {
body["terraforming_state_id"] = 1
body["terraforming_state_name"] = "Not terraformable"
} else if terraformState == "Terraformable" {
body["terraforming_state_id"] = 2
body["terraforming_state_name"] = "Candidate for terraforming"
} else if terraformState == "Terraforming" {
body["terraforming_state_id"] = 3
body["terraforming_state_name"] = "Terraforming completed"
} else if terraformState == "Terraformed" {
body["terraforming_state_id"] = 4
body["terraforming_state_name"] = "Being terraformed"
}
// Type
planetClass := event["PlanetClass"]
if planetClass == "Sudarsky class I gas giant" {
body["type_id"] = 21
body["type"] = "Class I gas giant"
} else if planetClass == "Sudarsky class II gas giant" {
body["type_id"] = 22
body["type"] = "Class II gas giant"
} else if planetClass == "Sudarsky class III gas giant" {
body["type_id"] = 23
body["type"] = "Class III gas giant"
} else if planetClass == "Sudarsky class IV gas giant" {
body["type_id"] = 24
body["type"] = "Class IV gas giant"
} else if planetClass == "Sudarsky class V gas giant" {
body["type_id"] = 25
body["type"] = "Class V gas giant"
} else if planetClass == "Earthlike body" {
body["type_id"] = 26
body["type"] = "Earth-like world"
} else if planetClass == "Gas giant with ammonia based life" {
body["type_id"] = 27
body["type"] = "Gas giant with ammonia-based life"
} else if planetClass == "Gas giant with water based life" {
body["type_id"] = 28
body["type"] = "Gas giant with water-based life"
} else if planetClass == "Helium rich gas giant" {
body["type_id"] = 29
body["type"] = "Helium-rich gas giant"
} else if planetClass == "High metal content body" {
body["type_id"] = 30
body["type"] = "High metal content world"
} else if planetClass == "Icy body" {
body["type_id"] = 31
body["type"] = "Icy body"
} else if planetClass == "Metal rich body" {
body["type_id"] = 32
body["type"] = "Metal-rich body"
} else if planetClass == "Rocky body" {
body["type_id"] = 33
body["type"] = "Rocky body"
} else if planetClass == "Rocky ice body" {
body["type_id"] = 34
body["type"] = "Rocky ice world"
} else if planetClass == "Water giant" {
body["type_id"] = 35
body["type"] = "Water giant"
} else if planetClass == "Water world" {
body["type_id"] = 36
body["type"] = "Water world"
}
if event["Volcanism"] != nil && event["Volcanism"] != "" && event["Volcanism"] != "No volcanism" {
volcanism := event["Volcanism"].(string)
volcanismJson := make(map[string]interface{})
volcanism = strings.Replace(volcanism, " volcanism", "", 1)
// Volcanism type
if strings.HasSuffix(volcanism, " geysers") {
volcanism = strings.Replace(volcanism, " geysers", "", 1)
volcanismJson["type"] = "Geysers"
} else if strings.HasSuffix(volcanism, " magma") {
volcanism = strings.Replace(volcanism, " magma", "", 1)
volcanismJson["type"] = "Magma"
}
// Volcanism amount
if strings.HasPrefix(volcanism, "major") {
volcanism = strings.Replace(volcanism, "major ", "", 1)
volcanismJson["amount"] = "Major"
} else if strings.HasPrefix(volcanism, "minor") {
volcanism = strings.Replace(volcanism, "minor ", "", 1)
volcanismJson["amount"] = "Minor"
}
// Volcanism composition
volcanismJson["composition"] = TranslateVolcanism(volcanism)
body["volcanism"] = volcanismJson
}
// Create or update
bodystr, err := json.Marshal(body)
if errFound(err, raw) {
return
}
if exists {
bodyId, err := Int(body["id"])
if errFound(err, raw) {
return
}
err = UpdateBody(bodyId, string(bodystr))
if errFound(err, raw) {
return
}
} else {
err = InsertBody(systemId, bodyname, string(bodystr))
if errFound(err, raw) {
return
}
}
}
log.Print(bodyname, "@", systemname, " body scanned")
}
func HandleStarScanEvent(raw string, event map[string]interface{}, publisher *zmq.Socket) {
systemname := event["StarSystem"].(string)
bodyname := event["BodyName"].(string)
// Fetch the current system from the database
systemx, err := Float(event["StarPos"].([]interface{})[0])
assertNil(err)
systemx = fixCoord(systemx)
systemy, err := Float(event["StarPos"].([]interface{})[1])
assertNil(err)
systemy = fixCoord(systemy)
systemz, err := Float(event["StarPos"].([]interface{})[2])
assertNil(err)
systemz = fixCoord(systemz)
systemdata, err := FetchSystem(systemname, systemx, systemy, systemz)
if err != nil {
// System doesn't exist - ignore
} else {
// Turn the system in to JSON
d := json.NewDecoder(strings.NewReader(systemdata))
d.UseNumber()
var system map[string]interface{}
err = d.Decode(&system)
if errFound(err, raw) {
return
}
// Now fetch the body
systemId, err := Int(system["id"])
if errFound(err, raw) {
return
}
body, err := FetchBody(systemId, bodyname)
var exists bool
if err != nil {
exists = false
body = make(map[string]interface{})
body["created_at"] = int32(time.Now().Unix())
} else {
exists = true
}
body["updated_at"] = int32(time.Now().Unix())
// Age
age, err := Int(event["Age_MY"])
if err == nil {
body["age"] = age
}
// Periapsis
periapsis, err := Float(event["Periapsis"])
if err == nil {
body["arg_of_periapsis"] = periapsis
}
// Distance
distance, err := Float(event["DistanceFromArrivalLS"])
if err == nil {
body["distance_to_arrival"] = distance
}
body["group_id"] = 2
body["group_name"] = "Star"
body["is_landable"] = 0
if distance == 0 {
body["is_main_star"] = true
} else {
body["is_main_star"] = false
}
body["is_rotational_period_tidally_locked"] = false
body["name"] = bodyname
// Orbital eccentricity
eccentricity, err := Float(event["Eccentricity"])
if err == nil {
body["orbital_eccentricity"] = eccentricity
}
// Orbital inclination
inclination, err := Float(event["OrbitalInclination"])
if err == nil {
body["orbital_inclination"] = inclination
}
// Orbital period
orbitalPeriod, err := Float(event["OrbitalPeriod"])
if err == nil {
body["orbital_period"] = orbitalPeriod
}
// Rotational period
rotationalPeriod, err := Float(event["RotationPeriod"])
if err == nil {
body["rotational_period"] = rotationalPeriod / 86400
}
// Semi-major axis
semiMajorAxis, err := Float(event["SemiMajorAxis"])
if err == nil {
body["semi_major_axis"] = semiMajorAxis / 149597870700
}
// Stellar mass
stellarMass, err := Float(event["StellarMass"])
if err == nil {
body["solar_masses"] = stellarMass
}
// Radius
radius, err := Float(event["Radius"])
if err == nil {
body["solar_radius"] = radius / 695700000
}
// Stellar class
body["spectral_class"] = event["StarType"]
// Surface temperature
surfaceTemperature, err := Float(event["SurfaceTemperature"])
if err == nil {
body["surface_temperature"] = surfaceTemperature
}
// Update body data
// d := json.NewDecoder(strings.NewReader(systemdata))
// d.UseNumber()
// var body map[string]interface{}
// err = d.Decode(&body)
// if errFound(err, raw) {
// return
// }
// Create or update
bodystr, err := json.Marshal(body)
if errFound(err, raw) {
return
}
if exists {
bodyId, err := Int(body["id"])
if errFound(err, raw) {
return
}
err = UpdateBody(bodyId, string(bodystr))
if errFound(err, raw) {
return
}
} else {
err = InsertBody(systemId, bodyname, string(bodystr))
if errFound(err, raw) {
return
}
}
log.Print(bodyname, "@", systemname, " star scanned")
}
}
func HandleDockedEvent(raw string, event map[string]interface{}, publisher *zmq.Socket) {
systemname := event["StarSystem"].(string)
stationname := event["StationName"].(string)
stationfaction := event["StationFaction"]
if stationfaction == nil {
stationfaction = ""
}
// For 'Docked' events a missing allegiance implies Independent
stationallegiance := event["StationAllegiance"]
if stationallegiance == nil {
stationallegiance = "Faction_Independent"
}
stationallegiance = TranslateAllegiance(stationallegiance.(string))
stationeconomy := event["StationEconomy"]
if stationeconomy == nil {
stationeconomy = ""
}
stationeconomy = TranslateEconomy(stationeconomy.(string))
stationgovernment := event["StationGovernment"]
if stationgovernment == nil {
stationgovernment = ""
}
stationgovernment = TranslateGovernment(stationgovernment.(string))
stationstate := event["FactionState"]
if stationstate == nil {
stationstate = ""
}
stationstate = TranslateState(stationstate.(string))
// Fetch the current system from the database
systemx, err := Float(event["StarPos"].([]interface{})[0])
assertNil(err)
systemx = fixCoord(systemx)
systemy, err := Float(event["StarPos"].([]interface{})[1])
assertNil(err)
systemy = fixCoord(systemy)
systemz, err := Float(event["StarPos"].([]interface{})[2])
assertNil(err)
systemz = fixCoord(systemz)
systemdata, err := FetchSystem(systemname, systemx, systemy, systemz)
if err != nil {
// System doesn't exist - make it
} else {
// Turn the system in to JSON
d := json.NewDecoder(strings.NewReader(systemdata))
d.UseNumber()
var system map[string]interface{}
err = d.Decode(&system)
if errFound(err, raw) {
return
}
// Only if the event's timestamp is after the last time we updated the data
eventTime, err := time.Parse(time.RFC3339, event["timestamp"].(string))
if errFound(err, raw) {
return
}
updateTime := IntOr(system["updated_at"], 0)
if eventTime.Unix() > updateTime {
systemId, err := Int(system["id"])
if errFound(err, raw) {
return
}
stationdata, err := FetchStation(systemId, stationname)
if err != nil {
// Station doesn't exist - create it
} else {
// Turn the station into JSON
d2 := json.NewDecoder(strings.NewReader(stationdata))
d2.UseNumber()
var station map[string]interface{}
err = d2.Decode(&station)
if errFound(err, raw) {
return
}
var update map[string]interface{}
update = make(map[string]interface{})
updaterequired := false
dballegiance := JsonString(station["allegiance"])
if dballegiance != stationallegiance {
updaterequired = true
log.Print(stationname, "@", system["name"], " station allegiance ", dballegiance, " -> ", stationallegiance)
if dballegiance != "" {
update["oldallegiance"] = dballegiance
update["newallegiance"] = stationallegiance
}
}
dbeconomy := JsonString(station["primary_economy"])
if dbeconomy != stationeconomy {
updaterequired = true
log.Print(stationname, "@", system["name"], " station economy ", dbeconomy, " -> ", stationeconomy)
if dbeconomy != "" {
update["oldeconomy"] = dbeconomy
update["neweconomy"] = stationeconomy
}
}
dbgovernment := JsonString(station["government"])
if dbgovernment != stationgovernment {
updaterequired = true
log.Print(stationname, "@", system["name"], " station government ", dbgovernment, " -> ", stationstate)
if dbgovernment != "" {
update["oldgovernment"] = dbgovernment
update["newgovernment"] = stationgovernment
}
}
dbfaction := JsonString(station["controlling_faction"])
if dbfaction != stationfaction {
updaterequired = true
log.Print(stationname, "@", system["name"], " station controllling faction ", dbfaction, " -> ", stationfaction)
if dbfaction != "" {
update["oldfaction"] = dbfaction
update["newfaction"] = stationfaction
}
}
dbstate := JsonString(station["state"])
if dbstate != stationstate {
updaterequired = true
log.Print(stationname, "@", system["name"], " station state ", dbstate, " -> ", stationstate)
if dbstate != "" {
update["oldstate"] = dbstate
update["newstate"] = stationstate
}
}
if updaterequired {
// Update the database
station["allegiance"] = stationallegiance
station["primary_economy"] = stationeconomy
station["government"] = stationgovernment
station["state"] = stationstate
station["updated_at"] = int32(time.Now().Unix())
station["controlling_faction"] = stationfaction
updatedStation, err := json.Marshal(station)
if errFound(err, raw) {
return
}
stationId, err := Int(station["id"])
if errFound(err, raw) {
return
}
UpdateStation(systemId, stationId, string(updatedStation))
if errFound(err, raw) {
return
}
// Send notification
update["systemname"] = systemname
update["stationname"] = stationname
update["x"] = systemx
update["y"] = systemy
update["z"] = systemz
updateJson, err := json.Marshal(update)
if errFound(err, raw) {
return
}
_, _ = publisher.SendMessage("eddp.delta.station", string(updateJson))
}
}
}
}
}
func HandleOutfitting2Schema(raw string, message map[string]interface{}, publisher *zmq.Socket) {
// Obtain the system
systemname := message["systemName"].(string)
systemdata, err := FetchFirstSystem(systemname)
if err == nil {
// Turn the system in to JSON
d := json.NewDecoder(strings.NewReader(systemdata))
d.UseNumber()
var system map[string]interface{}
err = d.Decode(&system)
if errFound(err, raw) {
return
}
// Obtain the station
stationname := message["stationName"].(string)
systemId, err := Int(system["id"])
if errFound(err, raw) {
return
}
stationdata, err := FetchStation(systemId, stationname)
if err == nil {
// Turn the station in to JSON
d := json.NewDecoder(strings.NewReader(stationdata))
d.UseNumber()
var station map[string]interface{}
err = d.Decode(&station)
if errFound(err, raw) {
return
}
stationId, err := Int(station["id"])
if errFound(err, raw) {
return
}
// Only if the message's timestamp is after the last time we updated the data
messageTime, err := time.Parse(time.RFC3339, message["timestamp"].(string))
if errFound(err, raw) {
return
}
updateTime := IntOr(station["outfitting_updated_at"], 0)
if errFound(err, raw) {
return
}
if messageTime.Unix() > updateTime {
station["selling_modules"] = message["modules"]
// Update timestamp
station["outfitting_updated_at"] = int32(time.Now().Unix())
dbstation, err := json.Marshal(station)
err = UpdateStation(systemId, stationId, string(dbstation))
if errFound(err, raw) {
return
}
log.Print(stationname, "@", systemname, " outfitting updated")
}
}
}
}
func HandleCommodity3Schema(raw string, message map[string]interface{}, publisher *zmq.Socket) {
// Obtain the system
systemname := message["systemName"].(string)
systemdata, err := FetchFirstSystem(systemname)
if err == nil {
// Turn the system in to JSON
d := json.NewDecoder(strings.NewReader(systemdata))
d.UseNumber()
var system map[string]interface{}
err = d.Decode(&system)
if errFound(err, raw) {
return
}
// Obtain the station
stationname := message["stationName"].(string)
systemId, err := Int(system["id"])
if errFound(err, raw) {
return
}
stationdata, err := FetchStation(systemId, stationname)
if err == nil {
// Turn the station in to JSON
d := json.NewDecoder(strings.NewReader(stationdata))
d.UseNumber()
var station map[string]interface{}
err = d.Decode(&station)
if errFound(err, raw) {
return
}
stationId, err := Int(station["id"])
if errFound(err, raw) {
return
}
// Only if the message's timestamp is after the last time we updated the data
messageTime, err := time.Parse(time.RFC3339, message["timestamp"].(string))
if errFound(err, raw) {
return
}
updateTime := IntOr(station["market_updated_at"], 0)
if messageTime.Unix() > updateTime {
commodities := message["commodities"].([]interface{})
// Build updated commodities
var dbcommodities []map[string]interface{}
dbcommodities = make([]map[string]interface{}, len(commodities))
// transform each
for i := range commodities {
var dbcommodity map[string]interface{}
dbcommodity = make(map[string]interface{})
commodity := commodities[i].(map[string]interface{})
// Obtain name and ID
name := commodity["name"]
name = TranslateCommodity(name.(string))
dbcommodity["name"] = name
id, exists := dataDefs.CommodityIDs[name.(string)]
if !exists {
id = -1
}
dbcommodity["id"] = id
// See if it is being sold
var stockbracket int64
tmpstockbracket := commodity["stockBracket"]
switch t := tmpstockbracket.(type) {
case json.Number:
stockbracket, err = tmpstockbracket.(json.Number).Int64()
if errFound(err, raw) {
return
}
case string:
// This can happen if the stock bracket is "", which is rather surprisingly
// a valid value and means "not normally but at the moment yes"
stockbracket = 3
default:
log.Print("unexpected type %T\n", t)
}
if stockbracket > 0 {
stock, err := Int(commodity["stock"])
if errFound(err, raw) {
return
}
if stock > 0 {
dbcommodity["supply"] = stock
price, err := Int(commodity["buyPrice"])
if errFound(err, raw) {
return
}
dbcommodity["buy_price"] = price
}
}
// See if it is being bought
var demandbracket int64
tmpdemandbracket := commodity["demandBracket"]
switch t := tmpdemandbracket.(type) {
case json.Number:
demandbracket, err = tmpdemandbracket.(json.Number).Int64()
if errFound(err, raw) {
return
}
case string:
// This can happen if the demand bracket is "", which is rather surprisingly
// a valid value and means "not normally but at the moment yes"
demandbracket = 3
default:
log.Print("unexpected type %T\n", t)
}
if demandbracket > 0 {
demand, err := Int(commodity["demand"])
if errFound(err, raw) {
return
}
if demand > 0 {
dbcommodity["demand"] = demand
price, err := Int(commodity["sellPrice"])
if errFound(err, raw) {
return
}
dbcommodity["sell_price"] = price
}
}
dbcommodities[i] = dbcommodity
}
// Replace existing station commodities
station["commodities"] = dbcommodities
// Update timestamp
station["market_updated_at"] = int32(time.Now().Unix())
dbstation, err := json.Marshal(station)
err = UpdateStation(systemId, stationId, string(dbstation))
if errFound(err, raw) {
return
}
log.Print(stationname, "@", systemname, " market updated")
}
}
}
}
func HandleFSDJumpEvent(raw string, event map[string]interface{}, publisher *zmq.Socket) {
systemname := event["StarSystem"].(string)
systemsecurity := event["SystemSecurity"]
if systemsecurity == nil {
systemsecurity = ""
}
systemsecurity = TranslateSecurity(systemsecurity.(string))
systemallegiance := event["SystemAllegiance"]
if systemallegiance == nil {
systemallegiance = ""
}
systemallegiance = TranslateAllegiance(systemallegiance.(string))
systemeconomy := event["SystemEconomy"]
if systemeconomy == nil {
systemeconomy = ""
}
systemeconomy = TranslateEconomy(systemeconomy.(string))
systemgovernment := event["SystemGovernment"]
if systemgovernment == nil {
systemgovernment = ""
}
systemgovernment = TranslateGovernment(systemgovernment.(string))
systemstate := event["FactionState"]
if systemstate == nil {
systemstate = ""
}
systemstate = TranslateState(systemstate.(string))
// Fetch the current information from the DB
systemx, err := Float(event["StarPos"].([]interface{})[0])
assertNil(err)
systemx = fixCoord(systemx)
systemy, err := Float(event["StarPos"].([]interface{})[1])
assertNil(err)
systemy = fixCoord(systemy)
systemz, err := Float(event["StarPos"].([]interface{})[2])
assertNil(err)