-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
1279 lines (1122 loc) · 38.1 KB
/
bot.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"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"io"
"io/fs"
"math"
"mime/multipart"
"net/http"
"net/url"
"os"
"regexp"
"slices"
"strings"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gocolly/colly"
"github.com/hasura/go-graphql-client"
"github.com/otiai10/opengraph"
"github.com/vincent-petithory/dataurl"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-retryablehttp"
"github.com/spf13/pflag"
"golang.org/x/image/draw"
)
const CC_PLUG = "Help promote your favourite venues with: https://concertcloud.live/contribute"
const DEFAULT_IMAGE_URL = "https://mobilisons.ch/img/mobilizon_default_card.png"
const MAX_IMG_SIZE = 1024 * 1024 * 10 // ten megabytes
const IMAGE_RESIZE_WIDTH = 600
const SERVER_CRASH_WAIT_TIME = time.Duration(3 * int64(time.Minute))
// Options represents the full set of command-line options for the bot
type Options struct {
City *string
Country *string
Limit *string
Page *string
Radius *string
Date *string
File *string
AuthConfig *string
Config *string
ActorID *string
GroupID *string
Timezone *string
NoOp *bool
Register *bool
Authorize *bool
Draft *bool
Debug *bool
}
var opts Options
// Response represents the json reponse from https://api.concertcloud.com/
// and is used to Unmarshal that json
// FIXME it might be possible to import this from the official repo
type Response struct {
Event []Event `json:"data"`
Page int `json:"page"`
Limit int `json:"limit"`
Total int `json:"total"`
LastPage int `json:"last_page"`
}
// Event represents the Event objects which is the main part of the
// concertcloud response.
// FIXME it might be possible to import this from the official repo
type Event struct {
Title string `json:"title"`
Location string `json:"location"`
City string `json:"city"`
Country string `json:"country"`
URL string `json:"url"`
Comment string `json:"comment"`
Type string `json:"type"`
SourceUrl string `json:"sourceUrl"`
Date time.Time `json:"date"`
ImageUrl string `json:"imageUrl"`
}
// UUID represents the GraphQL UUID type
// FIXME move to a library
type UUID string
// MediaUpload represents the GraphQL MediaUpload type
// FIXME move to a library
type MediaUpload struct {
Id string `json:"id"`
}
// MediaData represents the mediaUpload object of a GraphQL mediaUpload mutation
// FIXME move to a library
type MediaData struct {
Upload MediaUpload `json:"uploadMedia"`
}
// MediaData represents the response object of a GraphQL mediaUpload mutation
// FIXME move to a library
type MediaResponse struct {
Data MediaData `json:"data"`
}
// Address represents the OpenStreetMap address for a given place
type Address struct {
Amenity string `json:"amenity"`
HouseNumber string `json:"house_number"`
Road string `json:"road"`
Neighbourhood string `json:"neighbourhood"`
City string `json:"city"`
County string `json:"county"`
State string `json:"state"`
ISOCode string `json:"ISO3166-2-lvl4"`
PostCode string `json:"postcode"`
Country string `json:"country"`
CountryCode string `json:"country_code"`
}
// Place represents a place as returned by openstreetmap
type Place struct {
PlaceId int `json:"place_id"`
Name string `json:"name"`
Lat string `json:"lat"`
Lon string `json:"lon"`
Type string `json:"type"`
Address Address `json:"address"`
DisplayName string `json:"display_name"`
}
// NominatumResponse represents the response returned from OpenStreetMap
type NominatumResponse []Place
// Point represents the latitude and longitude of a place in Mobilizòn
// FIXME move to a library
type Point string
// AddressInput represents address data in Mobilizòn GraphQL mutations like
// createEvent and updateEvent
// FIXME move to a library
type AddressInput struct {
Id int `json:"id"`
Description string `json:"description"`
Locality string `json:"locality"`
PostalCode string `json:"postalCode"`
Street string `json:"street"`
Country string `json:"country"`
Region string `json:"region"`
Geom Point `json:"geom"`
}
// MediaInput represents media data in Mobilizòn GraphQL mutations like
// createEvent and updateEvent
type MediaInput struct {
// FIXME move to a library
MediaId graphql.ID `json:"mediaId"`
}
// NominatumBaseURL is the URL we use to call nominatim
var NominatumBaseURL = "https://nominatim.openstreetmap.org/search"
// EventCategory represents the list of possible event categories present
// in Mobilizòn. Obviously this list must be maintained here as the list in
// the Mobilizòn codebase changes.
// FIXME move to a library
type EventCategory string
const (
ARTS EventCategory = "ARTS"
AUTO_BOAT_AIR EventCategory = "AUTO_BOAT_AIR"
BOOK_CLUBS EventCategory = "BOOK_CLUBS"
BUSINESS EventCategory = "BUSINESS"
CAUSES EventCategory = "CAUSES"
COMEDY EventCategory = "COMEDY"
COMMUNITY EventCategory = "COMMUNITY"
CRAFTS EventCategory = "CRAFTS"
FAMILY_EDUCATION EventCategory = "FAMILY_EDUCATION"
FASHION_BEAUTY EventCategory = "FASHION_BEAUTY"
FILM_MEDIA EventCategory = "FILM_MEDIA"
FOOD_DRINK EventCategory = "FOOD_DRINK"
GAMES EventCategory = "GAMES"
HEALTH EventCategory = "HEALTH"
LANGUAGE_CULTURE EventCategory = "LANGUAGE_CULTURE"
LEARNING EventCategory = "LEARNING"
LGBTQ EventCategory = "LGBTQ"
MEETING EventCategory = "MEETING"
MOVEMENTS_POLITICS EventCategory = "MOVEMENTS_POLITICS"
MUSIC EventCategory = "MUSIC"
NETWORKING EventCategory = "NETWORKING"
OUTDOORS_ADVENTURE EventCategory = "OUTDOORS_ADVENTURE"
PARTY EventCategory = "PARTY"
PERFORMING_VISUAL_ARTS EventCategory = "PERFORMING_VISUAL_ARTS"
PETS EventCategory = "PETS"
PHOTOGRAPHY EventCategory = "PHOTOGRAPHY"
SCIENCE_TECH EventCategory = "SCIENCE_TECH"
SPIRITUALITY_RELIGION_BELIEFS EventCategory = "SPIRITUALITY_RELIGION_BELIEFS"
SPORTS EventCategory = "SPORTS"
THEATRE EventCategory = "THEATRE"
)
var EventTypeStrings = []string{
"ARTS",
"AUTO_BOAT_AIR",
"BOOK_CLUBS",
"BUSINESS",
"CAUSES",
"COMEDY",
"COMMUNITY",
"CRAFTS",
"FAMILY_EDUCATION",
"FASHION_BEAUTY",
"FILM_MEDIA",
"FOOD_DRINK",
"GAMES",
"HEALTH",
"LANGUAGE_CULTURE",
"LEARNING",
"LGBTQ",
"MEETING",
"MOVEMENTS_POLITICS",
"MUSIC",
"NETWORKING",
"OUTDOORS_ADVENTURE",
"PARTY",
"PERFORMING_VISUAL_ARTS",
"PETS",
"PHOTOGRAPHY",
"SCIENCE_TECH",
"SPIRITUALITY_RELIGION_BELIEFS",
"SPORTS",
"THEATRE",
}
// EventVisibility represents the EventVisibility Mobilizòn GraphQL type
// FIXME move to a library
type EventVisibility string
const (
PRIVATE EventVisibility = "PRIVATE"
PUBLIC EventVisibility = "PUBLIC"
RESTRICTED EventVisibility = "RESTRICTED"
UNLISTED EventVisibility = "UNLISTED"
)
// EventJoinOptions represents the EventJoinOptions Mobilizòn GraphQL type
// FIXME move to a library
type EventJoinOptions string
const (
FREE EventJoinOptions = "FREE"
EXTERNAL EventJoinOptions = "EXTERNAL"
)
// DateTime represents the DateTime Mobilizòn GraphQL type
// FIXME move to a library
type DateTime string
// EventCommentModeration represents the EventCommentModeration Mobilizòn
// GraphQL type
// FIXME move to a library
type EventCommentModeration string
const (
ALLOW_ALL EventCommentModeration = "ALLOW_ALL"
CLOSED EventCommentModeration = "CLOSED"
MODERATED EventCommentModeration = "MODERATED"
)
// Timezone represents the cooresponding Mobilizòn GraphQL type
// FIXME move to a library
type Timezone string
// EventOptionsInput represents the cooresponding Mobilizòn GraphQL type
// FIXME move to a library
type EventOptionsInput struct {
CommentModeration EventCommentModeration `json:"commentModeration"`
ShowStartTime graphql.Boolean `json:"showStartTime"`
ShowEndTime graphql.Boolean `json:"showEndTime"`
Timezone Timezone `json:"timezone"`
}
// AuthConfig is the OAuth2 response presented by Mobilizòn for
// authorization and reauthorization. Becomes the structure of the auth
// FIXME move to a library
type AuthConfig struct {
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
RefreshTokenExpiresIn int `json:"refresh_token_expires_in"`
Scopes string `json:"scopes"`
TokenType string `json:"token_type"`
}
// local fields
var auth AuthConfig
var actorID *string
var groupID *string
var timezone *string
var addrs map[string]AddressInput
var httpClient *http.Client
var gqlClient *graphql.Client
// Log is our hclog local instance
var Log hclog.Logger
// init sets up logging and initializes the addr map
func init() {
Log = hclog.New(&hclog.LoggerOptions{
Name: "Mobilizon bot",
Level: hclog.LevelFromString("INFO"),
})
addrs = make(map[string]AddressInput)
}
// main still does too much of the work FIXME
func main() {
// set up our config dir if it's not already there
confdir, err := os.UserConfigDir()
if err != nil {
Log.Error("User config dir not found", err)
os.Exit(1)
}
err = os.Mkdir(confdir+"/mobilizon", 0700)
if err != nil && !errors.Is(err, fs.ErrExist) {
Log.Error("Error creating directory", err)
os.Exit(1)
}
opts.City = pflag.String("city", "X", "The concertcloud API param 'city'") // defaults to X to avoid accidental flooding
opts.Country = pflag.String("country", "", "The concertcloud API param 'country'")
opts.Limit = pflag.String("limit", "", "The concertcloud API param 'limit'")
opts.Page = pflag.String("page", "", "The concertcloud API param 'page'")
opts.Radius = pflag.String("radius", "", "The concertcloud API param 'radius'")
opts.Date = pflag.String("date", "", "The concertcloud API param 'date'")
opts.File = pflag.String("file", "", "Instead of fetching from concertcloud, use local file.")
opts.ActorID = pflag.String("actor", "", "The Mobilizon actor ID to use as the event organizer.")
opts.GroupID = pflag.String("group", "", "The Mobilizon group ID to use for the event attribution.")
opts.Timezone = pflag.String("timezone", "Europe/Zurich", "The timezone to use for the event attribution.")
opts.AuthConfig = pflag.String("authconfig", confdir+"/mobilizon/auth.json", "Use this file for authorization tokens.")
opts.Config = pflag.String("config", confdir+"/mobilizon", "Use this directory for configuration.")
opts.NoOp = pflag.Bool("noop", false, "Gather all required information and report on it, but do not create events in Mobilizòn.")
opts.Register = pflag.Bool("register", false, "Register this bot and quit. A client id and client secret will be output.")
opts.Authorize = pflag.Bool("authorize", false, "Authorize this bot and quit. An auth token and renew token will be output.")
opts.Draft = pflag.Bool("draft", false, "Create events in draft mode.")
opts.Debug = pflag.Bool("debug", false, "Debug mode.")
pflag.Parse()
if *opts.Register {
registerApp()
return
}
// do the authorization regardless ...
authorizeApp()
// and if that's all there is to do exit
if *opts.Authorize {
return
}
// set up the ContentCloud query
ccQuery := ""
if *opts.City != "X" && *opts.City != "" {
ccQuery = fmt.Sprintf("%s&city=%s", ccQuery, url.QueryEscape(*opts.City))
}
if *opts.Country != "" {
ccQuery = fmt.Sprintf("%s&country=%s", ccQuery, url.QueryEscape(*opts.Country))
}
if *opts.Limit != "" {
ccQuery = fmt.Sprintf("%s&limit=%s", ccQuery, *opts.Limit)
}
if *opts.Page != "" {
ccQuery = fmt.Sprintf("%s&page=%s", ccQuery, *opts.Page)
}
if *opts.Radius != "" {
ccQuery = fmt.Sprintf("%s&radius=%s", ccQuery, *opts.Radius)
}
if *opts.Date != "" {
ccQuery = fmt.Sprintf("%s&date=%s", ccQuery, url.QueryEscape(*opts.Date))
}
if *opts.Debug {
Log.SetLevel(hclog.LevelFromString("DEBUG"))
}
// set up an HTTPClient with automated retries
retryClient := retryablehttp.NewClient()
retryClient.RetryWaitMin = SERVER_CRASH_WAIT_TIME
retryClient.RetryWaitMax = time.Duration(10 * int64(time.Minute))
retryClient.RetryMax = 120
retryClient.CheckRetry = mobilizònRetryPolicy
retryClient.Backoff = mobilizònErrorBackoff
retryClient.Logger = Log
httpClient = retryClient.StandardClient()
gqlClient = graphql.NewClient("https://mobilisons.ch/api", httpClient)
gqlClient = gqlClient.WithRequestModifier(func(r *http.Request) {
r.Header.Set("Authorization", "Bearer "+auth.AccessToken)
})
// this will hold our json object whether local or from ConcertCloud
var jsonEventInput Response
if *opts.File != "" {
Log.Info("using local file:", "file", *opts.File)
dat, err := os.ReadFile(*opts.File)
if err != nil {
Log.Error("error", err)
os.Exit(1)
}
json.Unmarshal(dat, &jsonEventInput)
} else {
// Fetch some concerts from Concert Cloud
fetchUrl := fmt.Sprintf("%s?%s", "https://api.concertcloud.live/api/events", ccQuery)
response, err := http.Get(fetchUrl)
if err != nil {
Log.Error("error", err)
os.Exit(1) // no point in continuing
}
responseData, err := io.ReadAll(response.Body)
if err != nil {
Log.Error("", err)
os.Exit(1) // no point in continuing
}
json.Unmarshal(responseData, &jsonEventInput)
}
fetchAddrs(jsonEventInput)
createEvents(jsonEventInput)
}
// fetchAddrs loads the local addr.json file cache and then attempts to
// fetch any missing addresses from OpenStreetMap and Mobilizòn
// FIXME this still probably does too much for one function
func fetchAddrs(responseObject Response) {
addrsfile := *opts.Config + "/addrs.json"
// Read the local file, if it exists. We can trap errors here
// since we can just recreate the file if necessary.
dat, err := os.ReadFile(addrsfile)
if err != nil {
Log.Error(err.Error())
}
// FIXME: this should be a real json format just dumping the map is not
// good json
err = json.Unmarshal(dat, &addrs)
if err != nil {
Log.Error(err.Error())
}
for _, event := range responseObject.Event {
fetchAddr(event)
}
// FIXME: this should be a real json format just dumping the map is not
// good json
data, err := json.MarshalIndent(&addrs, "", " ")
if err != nil {
Log.Error(err.Error())
}
err = os.WriteFile(addrsfile, data, 0600)
if err != nil {
Log.Error(err.Error())
}
}
// fetchAddr uses OpenStreetMap Nominatim to create a query string which
// should in almost all cases return the correct location object when run
// against the Mobilizòn address search.
func fetchAddr(event Event) {
Log.Debug("Searching for: ", "location", event.Location)
// if we already have the don't bother with the query
_, ok := addrs[event.Location]
if ok {
Log.Debug("Skipping cached location", "location", event.Location)
return
}
// get the addr from OpenStreetMap first
query := fetchOSMAddr(event)
Log.Debug("Returned from OSM:", "query", query)
// now query Mobilizòn to make sure we use the same address object
var s struct {
SearchAddress []AddressInput `graphql:"searchAddress(query: $query)"`
}
vars := map[string]interface{}{
"query": query,
}
err := gqlClient.Query(context.Background(), &s, vars)
if err != nil {
Log.Error("fetchAddrs", err)
time.Sleep(3 * time.Second)
gqlClient.Query(context.Background(), &s, vars)
}
if len(s.SearchAddress) == 0 {
Log.Info("Address not found: ", "query", query)
return
}
for _, a := range s.SearchAddress {
Log.Debug("Mobilizòn returned: '" + a.Description + " " + a.Street + " " + a.Locality + " for " + event.Location + " " + event.City)
if a.Description == event.Location && a.Locality == event.City {
addrs[event.Location] = a
return
}
}
// just use the last one
addrs[event.Location] = s.SearchAddress[len(s.SearchAddress)-1]
}
// fetchOSMAddr takes a single Event object from the json input and returns
// a query string for Mobilizòn which should return the location object
// which Mobilizòn has constructed for the event address.
//
// Doing it this way improves our chances of getting an exact hit when we
// run the query against Mobilizòn itself.
func fetchOSMAddr(event Event) string {
var addr Place
Log.Debug("Doing lookup in OpenStreetMap")
var querystring = fmt.Sprintf("amenity=%s&city=%s&format=json&addressdetails=1",
url.QueryEscape(event.Location),
url.QueryEscape(event.City))
var nurl = fmt.Sprintf("%s?%s", NominatumBaseURL, querystring)
nresp, err := http.Get(nurl)
if err != nil {
Log.Debug(err.Error())
os.Exit(1)
}
addrData, err := io.ReadAll(nresp.Body)
if err != nil {
Log.Error("", err)
os.Exit(1)
}
var addrObject NominatumResponse
json.Unmarshal(addrData, &addrObject)
if len(addrObject) == 0 {
Log.Debug("OSM Place Not found:", "location", event.Location, "city", event.City)
return event.Location + " " + event.City
} else if len(addrObject) == 1 {
addr = addrObject[0]
} else {
for _, p := range addrObject {
if p.Type == "nightclub" || p.Type == "bar" || p.Type == "restaurant" || p.Type == "theatre" || p.Type == "cinema" || p.Type == "arts_centre" {
Log.Debug("Addr Type:", p.Type)
addr = p
break
}
}
}
return event.Location + " " + addr.Address.Road + " " + addr.Address.City
}
// createEvents loops through all of the events in the json input, sets up
// their variables map, and runs createEvents on them
func createEvents(r Response) {
for _, event := range r.Event {
// Do not upload events from bejazz.ch. They don't like us.
// opt out FIXME this should be loaded from a file or something
match, _ := regexp.MatchString("bejazz.ch", event.URL)
if match {
Log.Info("Skipping BeJazz.")
continue
}
// trim the title to produce better matches
event.Title = strings.TrimSpace(event.Title)
// titles must be at least 3 characters long in Mobilizòn
if len(event.Title) < 3 {
event.Title = event.Title + " ..."
}
// guard clauses
if eventExists(event) {
// updateEvent(vars)
continue
}
if *opts.NoOp {
continue
}
vars, err := populateVariables(event)
if err != nil {
Log.Error("Error populating vars", "error", err, "vars", spew.Sdump(vars))
continue
}
createEvent(vars)
}
}
// populateVariables takes an Event object from the json input and returns
// a map which can be used as the variables input for the Mobilizòn GraphQL
// mutations createEvent or updateEvent
func populateVariables(e Event) (map[string]interface{}, error) {
// add a plug for ConcertCloud
e.Comment = e.Comment + " <p/><p> " + CC_PLUG
vars := map[string]interface{}{
"organizerActorId": graphql.ID(*opts.ActorID),
"attributedToId": graphql.ID(*opts.GroupID),
"category": populateCategory(e),
"visibility": EventVisibility("PUBLIC"),
"joinOptions": EventJoinOptions("EXTERNAL"),
"title": e.Title,
"description": e.Comment,
"physicalAddress": addrs[e.Location],
"beginsOn": DateTime(e.Date.Format(time.RFC3339)),
"endsOn": DateTime(e.Date.Add(time.Hour * 2).Format(time.RFC3339)),
"draft": graphql.Boolean(*opts.Draft),
"onlineAddress": e.URL,
"externalParticipationUrl": e.URL,
"tags": populateTags(e),
"options": populateEventOptions(),
}
e = populateImageUrl(e)
path, err := downloadFile(e.ImageUrl)
if err != nil {
Log.Error("Media download error", "URL", e.ImageUrl, "path", path)
return vars, err
}
id, err := uploadEventImage(path)
if err != nil {
Log.Error("Media uploade error", "URL", e.ImageUrl, "path", path, "id", id)
return vars, err
}
mi := new(MediaInput)
mi.MediaId = id
vars["picture"] = mi
return vars, err
}
// populateImageUrl validates the imageUrl of an event object from the json
// input and if necessary finds one from the event URL. It updates the
// ImageUrl field of the Event object in place.
func populateImageUrl(e Event) Event {
if e.ImageUrl != "" && e.ImageUrl != e.SourceUrl && !strings.HasSuffix(e.ImageUrl, "/") {
return e
}
// fetch the opengraph image for the event if there is no event image
e.ImageUrl = fetchOGImageUrl(e.URL)
if strings.HasPrefix(e.ImageUrl, "http") {
return e
}
// fetch a backup image if we don't already have something
e.ImageUrl = guessEventImage(e.URL)
if strings.HasPrefix(e.ImageUrl, "http") {
return e
}
Log.Info("No image found for", "url", e.URL)
e.ImageUrl = DEFAULT_IMAGE_URL
return e
}
// uploadEventImage uploads the file at the given path, and returns its
// mobilison IT and any error which occurs in the process
func uploadEventImage(path string) (graphql.ID, error) {
multi, err := newfileUploadRequest(path)
if err != nil {
Log.Error("Error constructing media request", "path", path, "error", err)
return "", err
}
response, err := httpClient.Do(multi)
if err != nil {
Log.Error("Error uploading image", "path", path, "error", err)
return "", err
}
responseData, err := io.ReadAll(response.Body)
if err != nil {
Log.Error("Error getting media response", "path", path, "error", err)
return "", err
}
var mediaObject MediaResponse
json.Unmarshal(responseData, &mediaObject)
if mediaObject.Data.Upload.Id == "" {
err = errors.New("Image id not found in upload response. " + path)
}
return (graphql.ID)(mediaObject.Data.Upload.Id), err
}
// populateTags constructs an eventTags object for the createEvent mutation
func populateTags(e Event) []string {
return []string{
e.Location,
e.City,
}
}
// populateEventOptions creates a default eventOptionsInput object
// FIXME should od this in init()
func populateEventOptions() EventOptionsInput {
tz := Timezone(*opts.Timezone)
return EventOptionsInput{
CommentModeration: EventCommentModeration("ALLOW_ALL"),
ShowStartTime: graphql.Boolean(true),
ShowEndTime: graphql.Boolean(false),
Timezone: tz,
}
}
// populateCategory takes an event and returns either the event's own
// category if it is found in the list of Mobilizòn's event categories or
// the default category
// FIXME refactor this as an Event object method. Make the default a constant.
func populateCategory(e Event) EventCategory {
if slices.Contains(EventTypeStrings, e.Type) {
return EventCategory(e.Type)
}
return EventCategory("MUSIC")
}
// createEvent implements the Mobilizòn graphQL createEvent mutation
// taking a map of strings to objects to populate its variables
// FIXME split this out to a library
func createEvent(vars map[string]interface{}) {
var m struct {
CreateEvent struct {
Id string
Uuid string
} `graphql:"createEvent(organizerActorId: $organizerActorId, attributedToId: $attributedToId, title: $title, category: $category, visibility: $visibility, description: $description, physicalAddress: $physicalAddress, beginsOn: $beginsOn, endsOn: $endsOn, draft: $draft, onlineAddress: $onlineAddress, externalParticipationUrl: $externalParticipationUrl, tags: $tags, joinOptions: $joinOptions, options: $options, picture: $picture)"`
}
err := gqlClient.Mutate(context.Background(), &m, vars)
if err != nil {
Log.Error("Error creating event", "error", err, "vars", spew.Sdump(vars))
return
}
Log.Info("Created Event", "id", m.CreateEvent.Id, "UUID", m.CreateEvent.Uuid)
}
// updateEvent is a stub which will eventually implement the updateEvent
// Mobilizòn GraphQL mutation
// FIXME split this out to a library
func updateEvent(vars map[string]interface{}) {
// FIXME : stub
}
// registerApp registers an OAuth2 client called "Concert Cloud Bot" and
// and exports the resulting environmental variables as well as printing
// them on the commend line
func registerApp() {
type Registration struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
var posturl = "https://mobilisons.ch/apps"
body := []byte(`name=Concert%20Cloud%20Bot&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient&website=https://concertcloud.live&scope=write:event:create%20write:media:upload`)
r, err := http.NewRequest("POST", posturl, bytes.NewBuffer(body))
if err != nil {
Log.Error("", err)
os.Exit(1)
}
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
c := &http.Client{}
res, err := c.Do(r)
if err != nil {
Log.Error("", err)
os.Exit(1)
}
resData, err := io.ReadAll(res.Body)
if err != nil {
Log.Error("", err)
os.Exit(1)
}
var reg Registration
json.Unmarshal(resData, ®)
os.Setenv("GRAPHQL_CLIENT_ID", reg.ClientID)
os.Setenv("GRAPHQL_CLIENT_SECRET", reg.ClientSecret)
fmt.Println("export GRAPHQL_CLIENT_ID=" + reg.ClientID)
fmt.Println("export GRAPHQL_CLIENT_SECRET=" + reg.ClientSecret)
}
// authorizeApp does the OAuth2 authorization handshake using the device
// flow, which seems to work best for Mobilizòn, and nicely avoids the
// problem of having to copy URLs back and forth
func authorizeApp() {
// Let's first check for a valid refreshToken in our config
// If that doesn't work then we need to authorize interactively
err := refreshAuthorization()
if err == nil {
return
}
var posturl = "https://mobilisons.ch/login/device/code"
clientID := os.Getenv("GRAPHQL_CLIENT_ID")
body := []byte("client_id=" + clientID + "&scope=write:event:create%20write:media:upload")
r, err := http.NewRequest("POST", posturl, bytes.NewBuffer(body))
if err != nil {
Log.Error("", err)
os.Exit(1)
}
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
c := &http.Client{}
res, err := c.Do(r)
if err != nil {
Log.Error("", err)
os.Exit(1)
}
resData, err := io.ReadAll(res.Body)
if err != nil {
Log.Error("", err)
os.Exit(1)
}
type DeviceCodeGrant struct {
DeviceCode string `json:"device_code"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
Error string `json:"error"`
}
var resp DeviceCodeGrant
err = json.Unmarshal(resData, &resp)
if err != nil {
Log.Error("Error unmarshaling json:", err.Error())
}
if resp.Error != "" {
Log.Error(resp.Error)
}
fmt.Println("Please visit this URL and enter the code below " + resp.VerificationURI)
fmt.Println()
fmt.Println(resp.UserCode)
fmt.Println()
fmt.Println("Then press any key to continue.")
// wait for input
fmt.Scanln()
var token_url = "https://mobilisons.ch/oauth/token"
token_body := []byte("client_id=" + clientID + "&device_code=" + resp.DeviceCode + "&grant_type=urn:ietf:params:oauth:grant-type:device_code")
tokreq, err := http.NewRequest("POST", token_url, bytes.NewBuffer(token_body))
if err != nil {
Log.Error("", err)
os.Exit(1)
}
tokreq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
tokres, err := c.Do(tokreq)
resData, err = io.ReadAll(tokres.Body)
if err != nil {
Log.Error("", err)
os.Exit(1)
}
err = os.WriteFile(*opts.AuthConfig, resData, 0600)
}
// fetchOGImageUrl finds takes the URL of a specific event and returns the
// Open Ggraph image URL found there, if one exists.
// See https://ogp.me/
func fetchOGImageUrl(url string) string {
Log.Debug("Fetching opengraph image url.")
// get the ogp object
ogp, err := opengraph.Fetch(url)
if err != nil {
Log.Error("fetchOGImage", "error", err)
}
if len(ogp.Image) == 0 {
Log.Debug("No opengraph image found")
return ""
}
// convert URLs to absolute
ogp.ToAbsURL()
if strings.Contains(url, ogp.Image[0].URL) {
Log.Debug("Opengraph image URL is a substring of the base URL")
return ""
}
//but check that it works first
res, err := http.Head(ogp.Image[0].URL)
if err != nil {
Log.Error("fetchOGImage", "error", err)
return ""
}
if res.StatusCode != 200 {
Log.Error("fetchOGImage", "status", res.StatusCode)
return ""
}
Log.Debug("Returning first opengraph image URL", "url", ogp.Image[0].URL)
return ogp.Image[0].URL
}
// guessEventImage tries to find a reasonable image on the page found at an
// event URL. If it succeeds it returns the image URL otherwise it returns
// ""
//
// The best image is so far defined as the largest image in a src attribute
// on the page. This is far from ideal, but it's a fallback.
func guessEventImage(url string) string {
Log.Debug("Attempting to guess an image URL for", "url", url)
var srcs []string
c := colly.NewCollector()
// claim to be a browser
c.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
c.OnHTML("img[src]", func(e *colly.HTMLElement) {
i := e.Request.AbsoluteURL(e.Attr("src"))
srcs = append(srcs, i)
})
c.Visit(url)
c.Wait()
if len(srcs) < 1 {
return ""
}
// Is biggest best? Well maybe not, but that's what we have to work with.
var best = -1
var size int64 = 0
for i, src := range srcs {
// occassionally we get an inline image
if strings.HasPrefix(src, "data:") {
continue
}
// sometimes we don't get the absolute URL
if strings.HasPrefix(src, "/") {
continue
}
if strings.HasSuffix(src, ".svg") {
continue
}
res, err := http.Head(src)
if err != nil {
Log.Error("Could not perform HEAD method for image", "src", src, "error", err)
}
cl := res.ContentLength
if cl > size && cl < MAX_IMG_SIZE {
best = i
size = cl
}
Log.Debug("Choosing image by size", "i", i, "size", size, "cl", cl, "best", best)
}
if best == -1 {
return ""
}
return srcs[best]
}
// newfileUploadRequest constructs an http request object for Mobilizòn
// file uploads when given a local file path. It returns the request object
// and an error object.
func newfileUploadRequest(path string) (*http.Request, error) {
var fileContents []byte
var fi fs.FileInfo
if strings.HasPrefix(path, "data:") {
Log.Debug("newFileUploadRequest", path)
dataURL, err := dataurl.DecodeString(path)
if err != nil {
return nil, err
}
fileContents, err = base64.StdEncoding.DecodeString(dataURL.String())
if err != nil {
return nil, err