-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathwebserver.go
More file actions
1335 lines (1158 loc) · 40.2 KB
/
Copy pathwebserver.go
File metadata and controls
1335 lines (1158 loc) · 40.2 KB
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"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"time"
_ "github.com/mantyr/go-charset/data"
"github.com/tibiadata/tibiadata-api-go/src/validation"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"github.com/PuerkitoBio/goquery"
"github.com/gin-contrib/gzip"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
)
var (
// TibiaData app resty vars
TibiaDataUserAgent, TibiaDataProxyDomain string
// ErrorNotFound will be returned if the requests ends up in a 404
ErrorNotFound = errors.New("page not found")
)
// DebugOutInformation wraps OutInformation with some debug info
type DebugOutInformation struct {
Information Information `json:"information"`
Debug Debug `json:"debug"`
}
// OutInformation wraps Information in other for all json outputs be consistent
type OutInformation struct {
Information Information `json:"information"`
}
// Information stores some API related data
type Information struct {
APIDetails APIDetails `json:"api"` // The API details.
Timestamp string `json:"timestamp"` // The timestamp from when the data was processed.
TibiaURLs []string `json:"tibia_urls"` // The links to the sources of the data on tibia.com
Status Status `json:"status"` // The response status information.
}
// API details store information about this API
type APIDetails struct {
Version int `json:"version"` // The API major version currently running.
Release string `json:"release"` // The API release currently running.
Commit string `json:"commit"` // The API GitHub commit sha.
}
// Status stores information about the response
type Status struct {
HTTPCode int `json:"http_code"` // The HTTP response code from the API.
Error int `json:"error,omitempty"` // The error code thrown by TibiaData API for identification of issue.
Message string `json:"message,omitempty"` // The error message thrown by TibiaData API for human readability.
}
// TibiaDataRequest is the struct of request information
type TibiaDataRequestStruct struct {
Method string `json:"method"` // Request method (default: GET)
URL string `json:"url"` // Request URL
FormData map[string]string `json:"form_data"` // Request form content (used when POST)
RawBody bool `json:"raw_body"` // If set to true the whole content from tibia.com will be passed down
}
// RunWebServer starts the gin server
// It blocks the code and will only finish execution on shutdown
func runWebServer() {
// Setting gin-application to certain mode if GIN_MODE is set to release, test or debug (default is release)
switch ginMode := getEnv("GIN_MODE", "release"); ginMode {
case "test":
gin.SetMode(gin.TestMode)
case "debug":
gin.SetMode(gin.DebugMode)
default:
gin.SetMode(gin.ReleaseMode)
}
// Logging the gin.mode
log.Printf("[info] TibiaData API gin-mode: %s", gin.Mode())
// Starting an Engine instance
router := gin.Default()
// Gin middleware to enable GZIP support
router.Use(gzip.Gzip(gzip.DefaultCompression))
// Set 404 not found page
router.NoRoute(func(c *gin.Context) {
TibiaDataErrorHandler(
c,
ErrorNotFound,
http.StatusNotFound,
)
})
// Set proxy feature of gin
if isEnvExist("GIN_TRUSTED_PROXIES") {
trustedProxies := getEnv("GIN_TRUSTED_PROXIES", "")
_ = router.SetTrustedProxies(strings.Split(trustedProxies, ","))
log.Printf("[info] TibiaData API gin-trusted-proxies: %s", strings.Split(trustedProxies, ","))
} else {
_ = router.SetTrustedProxies(nil)
}
// Set the TibiaData restriction mode
TibiaDataRestrictionMode = getEnvAsBool("TIBIADATA_RESTRICTION_MODE", false)
log.Printf("[info] TibiaData API restriction-mode: %t", TibiaDataRestrictionMode)
// Set the ping endpoint
router.GET("/ping", func(c *gin.Context) {
data := Information{
APIDetails: TibiaDataAPIDetails,
Timestamp: TibiaDataDatetime(""),
TibiaURLs: []string{},
Status: Status{
HTTPCode: http.StatusOK,
Message: "pong",
},
}
var output OutInformation
output.Information = data
c.JSON(http.StatusOK, output)
})
// health endpoints for kubernetes
router.GET("/", rootz)
router.GET("/health", healthz)
router.GET("/healthz", healthz)
router.GET("/readyz", readyz)
// Set the debug endpoint
router.GET("/debug", debugHandler)
// TibiaData API version 3 endpoints
router.GET("/v3/*action", func(c *gin.Context) {
c.JSON(299, gin.H{
"error": "TibiaData v3 is deprecated.",
"information": InformationV3{
APIversion: 3,
Timestamp: TibiaDataDatetime(""),
},
})
})
// TibiaData API version 4 endpoints
v4 := router.Group("/v4")
{
// Tibia characters
v4.GET("/boostablebosses", tibiaBoostableBosses)
// Tibia characters
v4.GET("/character/:name", tibiaCharactersCharacter)
// Tibia creatures
v4.GET("/creature/:race", tibiaCreaturesCreature)
v4.GET("/creatures", tibiaCreaturesOverview)
// Tibia fansites
v4.GET("/fansites", tibiaFansites)
// Tibia guilds
v4.GET("/guild/:name", tibiaGuildsGuild)
// v4.GET("/guild/:name/events",TibiaGuildsGuildEvents)
// v4.GET("/guild/:name/wars",TibiaGuildsGuildWars)
v4.GET("/guilds/:world", tibiaGuildsOverview)
// Tibia highscores
v4.GET("/highscores/:world", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, v4.BasePath()+"/highscores/"+c.Param("world")+"/experience/"+TibiaDataDefaultVoc+"/1")
})
v4.GET("/highscores/:world/:category", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, v4.BasePath()+"/highscores/"+c.Param("world")+"/"+c.Param("category")+"/"+TibiaDataDefaultVoc+"/1")
})
v4.GET("/highscores/:world/:category/:vocation", tibiaHighscores)
v4.GET("/highscores/:world/:category/:vocation/:page", tibiaHighscores)
// Tibia houses
v4.GET("/house/:world/:house_id", tibiaHousesHouse)
v4.GET("/houses/:world/:town", tibiaHousesOverview)
// Tibia killstatistics
v4.GET("/killstatistics/:world", tibiaKillstatistics)
// Tibia news
v4.GET("/news/archive", tibiaNewslist) // all categories (default 90 days)
v4.GET("/news/archive/:days", tibiaNewslist) // all categories
v4.GET("/news/id/:news_id", tibiaNews) // shows one news entry
v4.GET("/news/latest", tibiaNewslist) // only news and articles
v4.GET("/news/newsticker", tibiaNewslist) // only news_ticker
// Tibia spells
v4.GET("/spell/:spell_id", tibiaSpellsSpell)
v4.GET("/spells", tibiaSpellsOverview)
// Tibia worlds
v4.GET("/world/:name", tibiaWorldsWorld)
v4.GET("/worlds", tibiaWorldsOverview)
}
// Container version details endpoint
router.GET("/versions", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"release": TibiaDataBuildRelease,
"build": TibiaDataBuildBuilder,
"commit": TibiaDataBuildCommit,
"edition": TibiaDataBuildEdition,
})
})
// Build the http server
server := &http.Server{
Addr: ":8080", // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
Handler: router,
}
// Prepare for a graceful shutdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
// Run a go routine that will receive the shutdown input
go func() {
<-quit
log.Println("[info] TibiaData API received shutdown input")
if err := server.Close(); err != nil {
log.Fatal("[error] TibiaData API server close error:", err)
}
}()
// setting readyz endpoint to true
isReady.Store(true)
log.Println("[info] TibiaData API starting webserver")
// Run the server
if err := server.ListenAndServe(); err != nil {
if err == http.ErrServerClosed {
log.Println("[info] TibiaData API server gracefully shut down")
} else {
log.Fatal("[error] TibiaData API server closed unexpectedly")
}
}
}
// BoostableBosses godoc
// @Summary List of boostable bosses
// @Description Show all boostable bosses listed
// @Tags boostable bosses
// @Accept json
// @Produce json
// @Success 200 {object} BoostableBossesOverviewResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/boostablebosses [get]
func tibiaBoostableBosses(c *gin.Context) {
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/library/?subtopic=boostablebosses",
RawBody: true,
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaBoostableBossesOverviewImpl(BoxContentHTML, tibiadataRequest.URL)
},
"TibiaBoostableBosses")
}
// Character godoc
// @Summary Show one character
// @Description Show all information about one character available
// @Tags characters
// @Accept json
// @Produce json
// @Param name path string true "The character name" extensions(x-example=Trollefar)
// @Success 200 {object} CharacterResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/character/{name} [get]
func tibiaCharactersCharacter(c *gin.Context) {
// Getting params from URL
name := c.Param("name")
// Validate the name
err := validation.IsCharacterNameValid(name)
if err != nil {
TibiaDataErrorHandler(c, err, http.StatusBadRequest)
return
}
// Build the request structure
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/community/?subtopic=characters&name=" + TibiaDataQueryEscapeString(name),
}
// Handle the request
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaCharactersCharacterImpl(BoxContentHTML, tibiadataRequest.URL)
},
"TibiaCharactersCharacter")
}
// Creatures godoc
// @Summary List of creatures
// @Description Show all creatures listed
// @Tags creatures
// @Accept json
// @Produce json
// @Success 200 {object} CreaturesOverviewResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/creatures [get]
func tibiaCreaturesOverview(c *gin.Context) {
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/library/?subtopic=creatures",
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaCreaturesOverviewImpl(BoxContentHTML, tibiadataRequest.URL)
},
"TibiaCreaturesOverview")
}
// Creature godoc
// @Summary Show one creature
// @Description Show all information about one creature
// @Tags creatures
// @Accept json
// @Produce json
// @Param race path string true "The race of creature" extensions(x-example=nightmare)
// @Success 200 {object} CreatureResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/creature/{race} [get]
func tibiaCreaturesCreature(c *gin.Context) {
// getting params from URL
race := c.Param("race")
// Validate the race
endpoint, err := validation.IsCreatureNameValid(race)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/library/?subtopic=creatures&race=" + endpoint,
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaCreaturesCreatureImpl(endpoint, BoxContentHTML, tibiadataRequest.URL)
},
"TibiaCreaturesCreature")
}
// Fansites godoc
// @Summary Promoted and supported fansites
// @Description List of all promoted and supported fansites
// @Tags fansites
// @Accept json
// @Produce json
// @Success 200 {object} FansitesResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/fansites [get]
func tibiaFansites(c *gin.Context) {
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/community/?subtopic=fansites",
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaFansitesImpl(BoxContentHTML, tibiadataRequest.URL)
},
"TibiaFansites")
}
// Guild godoc
// @Summary Show one guild
// @Description Show all information about one guild
// @Tags guilds
// @Accept json
// @Produce json
// @Param name path string true "The name of guild" extensions(x-example=Elysium)
// @Success 200 {object} GuildResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/guild/{name} [get]
func tibiaGuildsGuild(c *gin.Context) {
// getting params from URL
guild := c.Param("name")
// Validate the name
err := validation.IsGuildNameValid(guild)
if err != nil {
TibiaDataErrorHandler(c, err, http.StatusBadRequest)
return
}
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/community/?subtopic=guilds&page=view&GuildName=" + TibiaDataQueryEscapeString(guild),
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaGuildsGuildImpl(guild, BoxContentHTML, tibiadataRequest.URL)
},
"TibiaGuildsGuild")
}
// Guilds godoc
// @Summary List all guilds from a world
// @Description Show all guilds on a certain world
// @Tags guilds
// @Accept json
// @Produce json
// @Param world path string true "The world" extensions(x-example=Antica)
// @Success 200 {object} GuildsOverviewResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/guilds/{world} [get]
func tibiaGuildsOverview(c *gin.Context) {
// getting params from URL
world := c.Param("world")
// Check if world exists
exists, err := validation.WorldExists(world)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
if !exists {
TibiaDataErrorHandler(c, validation.ErrorWorldDoesNotExist, http.StatusBadRequest)
return
}
// Adding fix for First letter to be upper and rest lower
world = TibiaDataStringWorldFormatToTitle(world)
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/community/?subtopic=guilds&world=" + TibiaDataQueryEscapeString(world),
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaGuildsOverviewImpl(world, BoxContentHTML, tibiadataRequest.URL)
},
"TibiaGuildsOverview")
}
// Highscores godoc
// @Summary Highscores of tibia
// @Description Show all highscores of tibia
// @Description In restriction mode, the valid vocation option is all.
// @Tags highscores
// @Accept json
// @Produce json
// @Param world path string true "The world" default(all) extensions(x-example=Antica)
// @Param category path string true "The category" default(experience) Enums(achievements, axefighting, charmpoints, clubfighting, distancefighting, experience, fishing, fistfighting, goshnarstaint, loyaltypoints, magiclevel, shielding, swordfighting, dromescore, bosspoints) extensions(x-example=fishing)
// @Param vocation path string true "The vocation" default(all) Enums(all, knights, paladins, sorcerers, druids, monks) extensions(x-example=all)
// @Param page path int true "The current page" default(1) minimum(1) extensions(x-example=1)
// @Success 200 {object} HighscoresResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/highscores/{world}/{category}/{vocation}/{page} [get]
func tibiaHighscores(c *gin.Context) {
// getting params from URL
world := c.Param("world")
category := c.Param("category")
vocation := c.Param("vocation")
page := c.Param("page")
// Check if vocation is valid
err := validation.IsVocationValid(vocation)
if err != nil {
TibiaDataErrorHandler(c, err, http.StatusBadRequest)
return
}
// Adding fix for First letter to be upper and rest lower
if strings.EqualFold(world, "all") {
world = ""
} else {
world = TibiaDataStringWorldFormatToTitle(world)
}
if world != "" {
// Check if world exists
exists, err := validation.WorldExists(world)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
if !exists {
TibiaDataErrorHandler(c, validation.ErrorWorldDoesNotExist, http.StatusBadRequest)
return
}
}
if category != "" {
err = validation.IsHighscoreCategoryValid(category)
if err != nil {
TibiaDataErrorHandler(c, validation.ErrorHighscoreCategoryDoesNotExist, http.StatusBadRequest)
return
}
}
highscoreCategory := validation.HighscoreCategoryFromString(category)
// Sanitize of vocation input
vocationName, vocationid := TibiaDataVocationValidator(vocation)
// Check if restriction mode is enabled
if TibiaDataRestrictionMode && vocationName != "all" {
TibiaDataErrorHandler(c, validation.ErrorRestrictionMode, http.StatusBadRequest)
return
}
// checking the page provided
if page == "" {
page = "1"
}
if TibiaDataStringToInteger(page) < 1 {
TibiaDataErrorHandler(c, validation.ErrorHighscorePageInvalid, http.StatusBadRequest)
return
}
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/community/?subtopic=highscores&world=" + TibiaDataQueryEscapeString(world) + "&category=" + strconv.Itoa(int(highscoreCategory)) + "&profession=" + TibiaDataQueryEscapeString(vocationid) + "¤tpage=" + TibiaDataQueryEscapeString(page),
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaHighscoresImpl(world, highscoreCategory, vocationName, TibiaDataStringToInteger(page), BoxContentHTML, tibiadataRequest.URL)
},
"TibiaHighscores")
}
// House godoc
// @Summary House view
// @Description Show all information about one house
// @Tags houses
// @Accept json
// @Produce json
// @Param world path string true "The world to show" extensions(x-example=Antica)
// @Param house_id path int true "The ID of the house" extensions(x-example=35019)
// @Success 200 {object} HouseResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/house/{world}/{house_id} [get]
func tibiaHousesHouse(c *gin.Context) {
// getting params from URL
world := c.Param("world")
houseidStr := c.Param("house_id")
houseid, err := strconv.Atoi(houseidStr)
if err != nil {
TibiaDataErrorHandler(c, validation.ErrorStringCanNotBeConvertedToInt, http.StatusBadRequest)
return
}
// Adding fix for First letter to be upper and rest lower
world = TibiaDataStringWorldFormatToTitle(world)
// Check if world exists
exists, err := validation.WorldExists(world)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
if !exists {
TibiaDataErrorHandler(c, validation.ErrorWorldDoesNotExist, http.StatusBadRequest)
return
}
// check if house exists
exists, err = validation.HouseExistsRaw(houseid)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
if !exists {
TibiaDataErrorHandler(c, validation.ErrorHouseDoesNotExist, http.StatusBadRequest)
return
}
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/community/?subtopic=houses&page=view&world=" + TibiaDataQueryEscapeString(world) + "&houseid=" + TibiaDataQueryEscapeString(houseidStr),
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaHousesHouseImpl(houseid, BoxContentHTML, tibiadataRequest.URL)
},
"TibiaHousesHouse")
}
// Houses godoc
// @Summary List of houses
// @Description Show all houses filtered on world and town
// @Tags houses
// @Accept json
// @Produce json
// @Param world path string true "The world to show" extensions(x-example=Antica)
// @Param town path string true "The town to show" extensions(x-example=Venore)
// @Success 200 {object} HousesOverviewResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/houses/{world}/{town} [get]
// TODO: This API needs to be refactored somehow to use tibiaDataRequestHandler
func tibiaHousesOverview(c *gin.Context) {
// getting params from URL
world := c.Param("world")
town := c.Param("town")
// Adding fix for First letter to be upper and rest lower
world = TibiaDataStringWorldFormatToTitle(world)
town = strings.ReplaceAll(TibiaDataStringWorldFormatToTitle(town), "+", " ")
// Check if world exists
exists, err := validation.WorldExists(world)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
if !exists {
TibiaDataErrorHandler(c, validation.ErrorWorldDoesNotExist, http.StatusBadRequest)
return
}
// Check if town exists
exists, err = validation.TownExists(town)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
if !exists {
TibiaDataErrorHandler(c, validation.ErrorTownDoesNotExist, http.StatusBadRequest)
return
}
// Ab'Dendriel gets formatted as Ab'dendriel by TibiaDataStringWorldFormatToTitle
// which makes tibia.com not recognize it and return an empty response.
if strings.EqualFold(town, "ab'dendriel") {
town = "Ab'Dendriel"
}
jsonData, err := TibiaHousesOverviewImpl(c, world, town, TibiaDataHTMLDataCollector)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
// return jsonData
TibiaDataAPIHandleResponse(c, "TibiaHousesOverview", jsonData)
}
// Killstatistics godoc
// @Summary The killstatistics
// @Description Show all killstatistics filtered on world
// @Tags killstatistics
// @Accept json
// @Produce json
// @Param world path string true "The world to show" extensions(x-example=Antica)
// @Success 200 {object} KillStatisticsResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/killstatistics/{world} [get]
func tibiaKillstatistics(c *gin.Context) {
// getting params from URL
world := c.Param("world")
// Adding fix for First letter to be upper and rest lower
world = TibiaDataStringWorldFormatToTitle(world)
// Check if world exists
exists, err := validation.WorldExists(world)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
if !exists {
TibiaDataErrorHandler(c, validation.ErrorWorldDoesNotExist, http.StatusBadRequest)
return
}
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/community/?subtopic=killstatistics&world=" + TibiaDataQueryEscapeString(world),
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaKillstatisticsImpl(world, BoxContentHTML, tibiadataRequest.URL)
},
"TibiaKillstatistics")
}
// News archive godoc
// @Summary Show news archive (90 days)
// @Description Show news archive with a filtering on 90 days
// @Tags news
// @Accept json
// @Produce json
// @Success 200 {object} NewsListResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/news/archive [get]
func tibiaNewslistArchive() bool {
// Not used function.. but required for documentation purpose
return false
}
// News archive (with day filter) godoc
// @Summary Show news archive (with days filter)
// @Description Show news archive with a filtering option on days
// @Tags news
// @Accept json
// @Produce json
// @Param days path int true "The number of days to show" default(90) minimum(1) extensions(x-example=30)
// @Success 200 {object} NewsListResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/news/archive/{days} [get]
func tibiaNewslistArchiveDays() bool {
// Not used function.. but required for documentation purpose
return false
}
// Latest news godoc
// @Summary Show newslist (90 days)
// @Description Show newslist with filtering on articles and news of last 90 days
// @Tags news
// @Accept json
// @Produce json
// @Success 200 {object} NewsListResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/news/latest [get]
func tibiaNewslistLatest() bool {
// Not used function.. but required for documentation purpose
return false
}
// News ticker godoc
// @Summary Show news tickers (90 days)
// @Description Show news of type news tickers of last 90 days
// @Tags news
// @Accept json
// @Produce json
// @Success 200 {object} NewsListResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/news/newsticker [get]
func tibiaNewslist(c *gin.Context) {
// getting params from URL
daysStr := c.Param("days")
var (
days int
err error
)
if daysStr != "" {
// convert param to int
days, err = strconv.Atoi(daysStr)
if err != nil {
TibiaDataErrorHandler(c, validation.ErrorStringCanNotBeConvertedToInt, http.StatusBadRequest)
return
}
}
if days == 0 {
days = 90 // default for recent posts
}
// generating dates to pass to FormData
DateBegin := time.Now().AddDate(0, 0, -days)
DateEnd := time.Now()
tibiadataRequest := TibiaDataRequestStruct{
Method: http.MethodPost,
URL: "https://www.tibia.com/news/?subtopic=newsarchive",
FormData: map[string]string{
"filter_begin_day": strconv.Itoa(DateBegin.UTC().Day()), // period
"filter_begin_month": strconv.Itoa(int(DateBegin.UTC().Month())), // period
"filter_begin_year": strconv.Itoa(DateBegin.UTC().Year()), // period
"filter_end_day": strconv.Itoa(DateEnd.UTC().Day()), // period
"filter_end_month": strconv.Itoa(int(DateEnd.UTC().Month())), // period
"filter_end_year": strconv.Itoa(DateEnd.UTC().Year()), // period
"filter_cipsoft": "cipsoft", // category
"filter_community": "community", // category
"filter_development": "development", // category
"filter_support": "support", // category
"filter_technical": "technical", // category
},
}
if c.Request != nil {
// getting type of news list
switch tmp := strings.Split(c.Request.URL.Path, "/"); tmp[3] {
case "newsticker":
tibiadataRequest.FormData["filter_ticker"] = "ticker"
case "latest":
tibiadataRequest.FormData["filter_article"] = "article"
tibiadataRequest.FormData["filter_news"] = "news"
case "archive":
tibiadataRequest.FormData["filter_ticker"] = "ticker"
tibiadataRequest.FormData["filter_article"] = "article"
tibiadataRequest.FormData["filter_news"] = "news"
}
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaNewslistImpl(days, BoxContentHTML, tibiadataRequest.URL)
},
"TibiaNewslist")
}
// News entry godoc
// @Summary Show one news entry
// @Description Show one news entry
// @Tags news
// @Accept json
// @Produce json
// @Param news_id path int true "The ID of news entry" extensions(x-example=6512)
// @Success 200 {object} NewsResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/news/id/{news_id} [get]
func tibiaNews(c *gin.Context) {
// getting params from URL
newsIDStr := c.Param("news_id")
// convert param to int
newsID, err := strconv.Atoi(newsIDStr)
if err != nil {
TibiaDataErrorHandler(c, validation.ErrorStringCanNotBeConvertedToInt, http.StatusBadRequest)
return
}
// checking the NewsID provided
err = validation.IsNewsIDValid(newsID)
if err != nil {
TibiaDataErrorHandler(c, err, http.StatusBadRequest)
return
}
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/news/?subtopic=newsarchive&id=" + newsIDStr,
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaNewsImpl(newsID, tibiadataRequest.URL, BoxContentHTML)
},
"TibiaNews")
}
// Spells godoc
// @Summary List all spells
// @Description Show all spells
// @Tags spells
// @Accept json
// @Produce json
// @Success 200 {object} SpellsOverviewResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/spells [get]
func tibiaSpellsOverview(c *gin.Context) {
// getting params from URL
vocation := c.Param("vocation")
if vocation == "" {
vocation = TibiaDataDefaultVoc
}
err := validation.IsVocationValid(vocation)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}
// Sanitize of vocation input
vocationName, _ := TibiaDataVocationValidator(vocation)
if vocationName == "all" || vocationName == "none" {
vocationName = ""
} else {
// removes the last letter (s) from the string (required for spells page)
vocationName = strings.TrimSuffix(vocationName, "s")
vocationName = cases.Title(language.English).String(vocationName)
}
tibiadataRequest := TibiaDataRequestStruct{
Method: resty.MethodGet,
URL: "https://www.tibia.com/library/?subtopic=spells&vocation=" + TibiaDataQueryEscapeString(vocationName),
}
tibiaDataRequestHandler(
c,
tibiadataRequest,
func(BoxContentHTML string) (interface{}, error) {
return TibiaSpellsOverviewImpl(vocationName, BoxContentHTML, tibiadataRequest.URL)
},
"TibiaSpellsOverview")
}
// Spell godoc
// @Summary Show one spell
// @Description Show all information about one spell
// @Tags spells
// @Accept json
// @Produce json
// @Param spell_id path string true "The name of spell" extensions(x-example=stronghaste)
// @Success 200 {object} SpellInformationResponse
// @Failure 400 {object} Information
// @Failure 404 {object} Information
// @Failure 503 {object} Information
// @Router /v4/spell/{spell_id} [get]
func tibiaSpellsSpell(c *gin.Context) {
// getting params from URL
spellRaw := c.Param("spell_id")
spell, err := validation.IsSpellNameOrFormulaValid(spellRaw)
if err != nil {
TibiaDataErrorHandler(c, err, 0)
return
}