-
Notifications
You must be signed in to change notification settings - Fork 2
/
MQ2MeshManager.cpp
1883 lines (1769 loc) · 60.1 KB
/
MQ2MeshManager.cpp
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
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
// MQ2MeshManager.cpp : Defines the entry point for the DLL application.
//
// PLUGIN_API is only to be used for callbacks. All existing callbacks at this time
// are shown below. Remove the ones your plugin does not use. Always use Initialize
// and Shutdown for setup and cleanup.
#include <bitset>
#include <cerrno>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <regex>
#include <string>
#include <thread>
#include <ctype.h>
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <Windows.h>
// Json Parser
#include <nlohmann/json.hpp>
// Downloader
#include <curl/curl.h>
// Hashing Function
#include <cryptopp/files.h>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#include <cryptopp/md5.h>
#include <cryptopp/sha.h>
// MQ Stuff
#include <mq/Plugin.h>
#include "Prototypes.h"
#include <imgui/fonts/IconsFontAwesome.h>
using json = nlohmann::json;
namespace fs = std::filesystem;
PreSetup("MQ2MeshManager");
PLUGIN_VERSION(2.0);
/**
* GLOBALS
*
* Avoid Globals if at all possible, since they persist throughout your program.
* But if you must have them, here is the place to put them.
*/
static const std::string MeshPluginVersion = "2.0";
bool fAgree = false;
static std::chrono::steady_clock::time_point PulseTimer = std::chrono::steady_clock::now();
static std::chrono::steady_clock::time_point DownloadThreadTimer = std::chrono::steady_clock::now();
static std::chrono::steady_clock::time_point HashThreadTimer = std::chrono::steady_clock::now();
unsigned short DownloadThreadCount = 0;
unsigned short HashThreadCount = 0;
std::string fCurrentDL = "none", fLastDL = "none", fPathDL = "none", LastMsg = "none";
unsigned short fProgressDL = 0;
bool fDownloading = false;
std::list<DownloadListStorage> DownloadList;
std::list<HashListStorage> HashpipeList;
std::vector<std::string> IgnoreList;
bool fDownloadReady = false;
bool fHashReady = false;
int HideProgress = 1;
int DownloadThreads = 0, MaxDownloadThreads = 4;
int HashThreads = 0, MaxHashThreads = 4;
bool ThreadSafe = true;
int ThreadLockSeconds = 20;
bool AutoDownloadMissing = false, AutoCheckForUpdates = false;
bool _init = false;
int MaxZone = 546;
static const char* Zones[546] = { "aalishai", "abysmal", "acrylia", "airplane", "akanon", "akheva", "akhevatwo", "alkabormare", "anguish", "arcstone", "arelis", "arena", "argath", "arginhiz", "arthicrex", "arxmentis", "ashengate", "atiiki", "barindu", "barren", "basilica", "bazaar", "beastdomain", "befallen", "beholder", "bertoxtemple", "bixiewarfront", "blackburrow", "blacksail", "bloodfalls", "bloodfields", "bloodmoon", "bothunder", "breedinggrounds", "brellsarena", "brellsrest", "brellstemple", "broodlands", "brotherisland", "buriedsea", "burningwood", "butcher", "cabeast", "cabwest", "cauldron", "causeway", "cazicthule", "chamberoftears", "chambersa", "chambersb", "chambersc", "chambersd", "chamberse", "chambersf", "chapterhouse", "charasisb", "charasis", "charasistwo", "chardokb", "chardok", "chardoktwo", "chelsithreborn", "citymist", "cityofbronze", "cobaltscar", "cobaltscartwo", "codecayb", "codecay", "commonlands", "convorteum", "coolingchamber", "corathusa", "corathusb", "corathus", "cosul", "crescent", "crushbone", "cryptofshade", "crystallos", "crystal", "crystalshard", "crystaltwoa", "crystaltwob", "dalnir", "darklightcaverns", "dawnshroud", "deadbone", "deadhills", "deepshade", "degmar", "delvea", "delveb", "devastationa", "devastation", "direwind", "discord", "discordtower", "drachnidhivea", "drachnidhiveb", "drachnidhivec", "drachnidhive", "dragoncrypt", "dragonscalea", "dragonscaleb", "dragonscale", "dranikcatacombsa", "dranikcatacombsb", "dranikcatacombsc", "dranikhollowsa", "dranikhollowsb", "dranikhollowsc", "dranik", "draniksewersa", "draniksewersb", "draniksewersc", "draniksscar", "dreadlands", "dreadspire", "dredge", "drogab", "droga", "dulak", "eastkarana", "eastkorlacha", "eastkorlach", "eastsepulcher", "eastwastes", "eastwastesshard", "eastwastestwo", "echo", "elddara", "elddar", "emeraldjungle", "empyr", "endlesscaverns", "erudnext", "erudnint", "erudsxing", "esianti", "ethernere", "everfrost", "eviltree", "exaltedb", "exalted", "fallen", "fearplane", "feerrott2", "feerrott", "felwithea", "felwitheb", "ferubi", "fhalls", "fieldofbone", "firefallpass", "firiona", "foundation", "freeportacademy", "freeportarena", "freeportcityhall", "freeporteast", "freeporthall", "freeportmilitia", "freeportsewers", "freeporttheater", "freeportwest", "freporte", "freportn", "freportw", "frontiermtnsb", "frontiermtns", "frostcrypt", "frozenshadow", "frozenshadowtwo", "fungalforest", "fungusgrove", "gfaydark", "gnomemtn", "gorowyn", "greatdivide", "greatdividetwo", "grelleth", "griegsend", "grimling", "grobb", "growthplane", "guardian", "guildhall3", "guildhalllrg", "guildhall", "guildhallsml", "guildlobby", "guka", "gukb", "gukbottom", "gukc", "gukd", "guke", "gukf", "gukg", "gukh", "guktop", "gunthak", "gyrospireb", "gyrospirez", "halas", "harbingers", "hateplaneb", "hateplane", "hatesfury", "heartoffearb", "heartoffearc", "heartoffear", "highkeep", "highpasshold", "hillsofshade", "hohonora", "hohonorb", "hole", "hollowshade", "hollowshadetwo", "housegarden", "iceclad", "icefall", "ikkinz", "illsalina", "illsalinb", "illsalinc", "illsalin", "inktuta", "innothuleb", "jaggedpine", "jardelshook", "kael", "kaelshard", "kaeltwo", "kaesora", "kaladima", "kaladimb", "karnor", "kattacastrumb", "kattacastrum", "katta", "kedge", "kithicor", "kodtaz", "korascian", "korshaext", "korshaint", "kurn", "lakeofillomen", "lakerathe", "lavastorm", "lceanium", "letalis", "lfaydark", "lichencreep", "lopingplains", "maidenhouseint", "maiden", "maidensgrave", "maidentwo", "mansion", "mearatas", "mechanotus", "mesa", "miragulmare", "mira", "mirb", "mirc", "mird", "mire", "mirf", "mirg", "mirh", "miri", "mirj", "mischiefplane", "mistmoore", "mistythicket", "mmca", "mmcb", "mmcc", "mmcd", "mmce", "mmcf", "mmcg", "mmch", "mmci", "mmcj", "monkeyrock", "moors", "morellcastle", "mseru", "nadox", "najena", "natimbi", "necropolis", "necropolistwo", "nedaria", "neighborhood", "nektulosa", "nektulos", "neriaka", "neriakb", "neriakc", "neriakd", "netherbian", "nexus", "nightmareb", "northkarana", "northro", "nro", "nurga", "oceangreenhills", "oceangreenvillage", "oceanoftears", "oggok", "oldblackburrow", "oldbloodfield", "oldcommons", "olddranik", "oldfieldofboneb", "oldfieldofbone", "oldkaesoraa", "oldkaesorab", "oldkithicor", "oldkurn", "overthere", "overtheretwo", "paineel", "paludal", "paludaltwo", "paw", "pellucid", "permafrost", "phinteriortree", "phylactery", "pillarsalra", "plhdkeinteriors1a1", "plhdkeinteriors1a2", "plhdkeinteriors1a3", "plhdkeinteriors3a1", "plhdkeinteriors3a2", "plhdkeinteriors3a3", "plhogrinteriors1a1", "plhogrinteriors1a2", "plhogrinteriors3a1", "plhogrinteriors3a2", "plhogrinteriors3b1", "plhogrinteriors3b2", "poair", "podisease", "poeartha", "poearthb", "pofire", "pohealth", "poinnovation", "pojustice", "poknowledge", "ponightmare", "poshadow", "postorms", "potactics", "potimea", "potimeb", "potorment", "potranquility", "povalor", "powar", "powater", "precipiceofwar", "provinggrounds", "qcat", "qey2hh1", "qeynos2", "qeynos", "qeytoqrg", "qinimi", "qrg", "qvic", "ragea", "rage", "rathechamber", "rathemtn", "redfeather", "relic", "resplendent", "riftseekers", "rivervale", "riwwi", "roost", "rubak", "ruja", "rujb", "rujc", "rujd", "ruje", "rujf", "rujg", "rujh", "ruji", "rujj", "runnyeye", "sarithcity", "scarlet", "scorchedwoods", "sebilis", "sepulcher", "shadeweaver", "shadeweavertwo", "shadowedmount", "shadowhaven", "shadowhaventwo", "shadowrest", "shadowspine", "shadowvalley", "shardslanding", "sharvahl", "sharvahltwo", "shiningcity", "shipmvm", "shipmvp", "shipmvu", "shippvu", "shipuvu", "shipworkshop", "silyssar", "sirens", "skyfire", "skyfiretwo", "skylance", "skyshrine", "skyshrinetwo", "sleeper", "sleepertwo", "sncrematory", "snlair", "snplant", "snpool", "soldunga", "soldungb", "soldungc", "solrotower", "soltemple", "solteris", "somnium", "southkarana", "southro", "sseru", "ssratemple", "steamfactory", "steamfontmts", "steppes", "stillmoona", "stillmoonb", "stonebrunt", "stonehive", "stonesnake", "stratos", "suncrest", "sunderock", "swampofnohope", "tacvi", "taka", "takb", "takc", "takd", "take", "takf", "takg", "takh", "taki", "takishruinsa", "takishruins", "takj", "tempesttemple", "templeveeshan", "templeveeshantwo", "tenebrous", "thalassius", "theatera", "theater", "thedeep", "thegrey", "thenest", "thevoida", "thevoidb", "thevoidc", "thevoidd", "thevoide", "thevoidf", "thevoidg", "thevoidh", "thuledream", "thulehouse1", "thulehouse2", "thulelibrary", "thuliasaur", "thundercrest", "thurgadina", "thurgadinb", "timorous", "tipt", "torgiran", "toskirakk", "towerofrot", "toxxulia", "trakanon", "trialsofsmoke", "tutoriala", "tutorialb", "twilight", "txevu", "umbral", "umbraltwo", "underquarry", "unrest", "uqua", "valdeholm", "veeshan", "veeshantwo", "veksar", "velketor", "velketortwo", "vergalid", "vexthal", "vexthaltwo", "vxed", "wakening", "wallofslaughter", "warrens", "warslikswood", "weddingchapeldark", "weddingchapel", "well", "westkorlacha", "westkorlachb", "westkorlachc", "westkorlach", "westsepulcher", "westwastes", "westwastestwo", "windsong", "xorbb", "yxtta", "zhisza" };
std::error_code ec;
std::stringstream jParse;
json MeshDatabase = json::array();
json SettingsDatabase = json::array();
json IgnoreDatabase = json::array();
int RemoteMeshes = 0, LocalMeshes = 0;
/**
* File Paths - We use them enough that we should stop building them over and over and over
*/
const fs::path ConfPath = fs::path(gPathConfig) / "MQ2MeshManager";
const fs::path NavPath = fs::path(gPathResources) / "MQ2Nav";
const fs::path ResPath = fs::path(gPathResources) / "MQ2MeshManager";
const fs::path DbPath = fs::path(ResPath) / "meshdb.json";
const fs::path TmpPath = fs::path(ResPath) / "tmp";
/*
* UI GLOBALS
*/
bool ShowMeshManagerWindow = false;
bool already_clicked = false;
/**
* STRUCTURES
*
* For when you want to store data where it doesn't get lonely.
*
*/
struct DownloadListStorage
{
std::string FileName;
std::string FileUrl;
};
struct HashListStorage
{
std::string FileName;
std::string FilePath;
std::string FileUrl;
std::string HashType;
std::string RemoteHash;
};
struct ProgressMeter {
std::string Thread;
std::string FileUrl;
std::string FileName;
};
/**
* HELPER FUNCTIONS - vcpkg install cryptopp
*
* Functions created to make common tasks used quicker.
*
* Examples: Checking if a file exists, sending chat messages, calculating the hash of a file. Etc...
*
*/
std::string Get_Hash(const fs::path& p, const std::string& h = "md5")
{
if (fs::exists(p))
{
std::string str;
std::string out;
CryptoPP::FileSource file(p.string().c_str(), true, new CryptoPP::StringSink(str));
if (h == "md5")
out = MD5(str);
else if (h == "sha256")
out = SHA256(str);
else
MeshWriteChat("\arHasing Error. Unsupported hashing function.", false);
return out;
}
else
{
MeshWriteChat("\arHashing Error. Invalid Path", false);
return "0";
}
}
void Get_Hash_For_Update(const struct HashListStorage& tmp)
{
if (fs::exists(tmp.FilePath, ec))
{
DownloadListStorage tmpDownloadList;
std::string str;
std::string out;
std::string theFile = fmt::format("{}\\{}", tmp.FilePath, tmp.FileName);
try
{
CryptoPP::FileSource file(theFile.c_str(), true, new CryptoPP::StringSink(str));
}
catch (CryptoPP::FileStore::OpenErr const&)
{
MeshWriteChat(fmt::format("\arHashing Error:\aw {}", strerror(errno)), false);
}
if (tmp.HashType == "md5")
{
out = MD5(str);
}
else if (tmp.HashType == "sha256")
{
out = SHA256(str);
}
else
{
MeshWriteChat("\arHasing Error. Unsupported hashing function.", false);
HashThreads--;
}
if (out.compare(tmp.RemoteHash) != 0)
{
tmpDownloadList.FileName = tmp.FileName;
tmpDownloadList.FileUrl = tmp.FileUrl;
DownloadList.push_back(tmpDownloadList);
HashThreads--;
}
else
{
HashThreads--;
}
}
else
{
MeshWriteChat("\arHashing Error. Invalid Path.", false);
HashThreads--;
}
}
std::string MD5(const std::string& data)
{
std::string res;
CryptoPP::Weak::MD5 hash;
CryptoPP::byte digest[CryptoPP::Weak::MD5::DIGESTSIZE];
hash.CalculateDigest(digest, (CryptoPP::byte*)data.c_str(), data.size());
CryptoPP::HexEncoder encoder;
encoder.Attach(new CryptoPP::StringSink(res));
encoder.Put(digest, sizeof(digest));
encoder.MessageEnd();
return res;
}
std::string SHA256(const std::string& data)
{
std::string res;
CryptoPP::SHA256 hash;
CryptoPP::byte digest[CryptoPP::SHA256::DIGESTSIZE];
hash.CalculateDigest(digest, (CryptoPP::byte*)data.c_str(), data.size());
CryptoPP::HexEncoder encoder;
encoder.Attach(new CryptoPP::StringSink(res));
encoder.Put(digest, sizeof(digest));
encoder.MessageEnd();
return res;
}
bool InGameAndSpawned()
{
return(GetGameState() == GAMESTATE_INGAME && pLocalPC != NULL);
}
bool ValidateZoneShortName(const std::string& shortname)
{
for (int i = 0; i < MaxZone; i++)
{
if (mq::ci_equals(Zones[i], shortname))
return true;
}
return false;
}
int number_of_files_in_directory(std::filesystem::path path, std::vector<std::string> extension)
{
unsigned int count = 0;
for (auto& p : fs::recursive_directory_iterator(path))
{
for (auto& e : extension)
{
if (p.path().extension() == e)
{
count++;
}
}
}
return count;
}
// Migration function. Used to quickly move files from Resources to Config.
int move_multiple_files(std::filesystem::path source, std::filesystem::path destination, std::vector<std::string> extensions, std::vector<std::string> excludes)
{
unsigned int count = 0;
for (auto& p : fs::recursive_directory_iterator(source))
{
for (auto& e : extensions)
{
if (p.path().extension() == e)
{
for (auto& x : excludes)
{
if (p.path().filename() != x)
{
bool filemoved = move_single_file(fs::path(p.path()), fs::path(destination) / p.path().filename());
if (filemoved)
{
count++;
}
else
{
MeshWriteChat(fmt::format("Error Moving File: {}", p.path().filename().string()), false);
}
}
}
}
}
}
return count;
}
bool move_single_file(std::filesystem::path& source, std::filesystem::path& destination)
{
return MoveFileEx(source.string().c_str(), destination.string().c_str(), MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
}
/**
* Chat function that won't spam you to death. When calling chat,
* use true for plugin spam, use false for failure messages and
* when responding to user commands.
*/
void MeshWriteChat(const std::string& msg, bool AntiSpam)
{
static const char* const prefix = "\ag[\a-tMQ2MeshManager\ag]\aw ";
if (AntiSpam)
{
if (msg == LastMsg)
return;
else
LastMsg = msg;
}
WriteChatf("%s%s", prefix, msg.c_str());
}
/**
* MESH DATABASE FUNCTIONS - vcpkg install nlohmann-json
*
* Uses nlohmann/json single file json parser.
*
*/
void MeshLoadDatabase()
{
if (!fs::exists(DbPath, ec))
{
MeshWriteChat("\arDatabase file does not exist. Use \aw/mesh updatedb\ar first.", false);
}
else
{
FILE* jFile;
const errno_t err = fopen_s(&jFile, DbPath.string().c_str(), "r");
if (err == 0)
{
MeshDatabase.clear();
try {
MeshDatabase = json::parse(jFile);
RemoteMeshes = static_cast<int>(MeshDatabase.size());
}
catch (json::parse_error& e)
{
MeshWriteChat(fmt::format("\arInvalid or empty database file. \a-r[\arError\aw: {}\a-r]", e.what()), false);
MeshWriteChat(fmt::format("\arDelete \a-r'\aw{}\a-r'\ar and try \aw/mesh updatedb\ar again.", DbPath.string()), false);
}
MeshWriteChat("\agDatabase Initialized.", false);
fclose(jFile);
}
else
{
MeshWriteChat("\arError opening database file for reading.", false);
}
}
}
bool MeshIsDatabaseEmpty(json object) {
if (object.empty())
return true;
else
return false;
}
/**
* DOWNLOADER - vpkg install curl zlib
*
* Streams data into a size_t in chunks before writing it to disk. Includes
* functions for tracking progress.
*
*/
size_t Curl_Write_Data(void* ptr, size_t size, size_t nmemb, FILE* stream)
{
size_t written = fwrite(ptr, size, nmemb, stream);
return written;
}
int Curl_Progress_Report(void* ptr, double TotalToDownload, double NowDownloaded, double TotalToUpload, double NowUploaded)
{
struct ProgressMeter* pm = (struct ProgressMeter*)ptr;
if (TotalToDownload <= 0.0)
{
return 0;
}
int progress = (int)round(NowDownloaded * 100 / TotalToDownload);
MeshWriteChat(fmt::format("\ag[\atThread\aw: {}\ag] \awDownload of\ay {} \awis\at {}%\aw complete.", pm->Thread, pm->FileName, std::to_string(progress)), true);
fProgressDL = progress;
return CURL_PROGRESSFUNC_CONTINUE;
}
void MeshDownloadFile(const std::string& url, const std::string& filename, const std::string& savepath, bool single)
{
struct ProgressMeter pm;
CURL* curl;
FILE* fp;
CURLcode result;
const std::string FinalPath = fmt::format("{}\\{}", savepath, filename);
// Update TLOs
fCurrentDL = filename;
fPathDL = FinalPath;
curl = curl_easy_init();
fDownloading = true;
if (curl)
{
pm.FileName = filename;
pm.FileUrl = url;
pm.Thread = std::to_string(DownloadThreads);
errno_t fw = fopen_s(&fp, FinalPath.c_str(), "wb");
// 13 = File locked for write access (Another client already has it)
if (fw != 0 && fw != 13)
{
char errstr[3]{};
sprintf_s(errstr, "%d", fw);
if (DownloadThreads > 0)
{
DownloadThreads--;
}
MeshWriteChat(fmt::format("\arError opening\aw {} \arfor writing. \a-r[\arError\aw: {}\a-r]", filename, errstr), false);
curl_easy_cleanup(curl);
fCurrentDL = "none";
fPathDL = "none";
fDownloading = false;
}
else if (fw == 13)
{
if (DownloadThreads > 0)
{
DownloadThreads--;
}
curl_easy_cleanup(curl);
fCurrentDL = "none";
fPathDL = "none";
fDownloading = false;
}
else
{
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_SSL_ENABLE_ALPN, 1L);
curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &pm);
curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, Curl_Progress_Report);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Curl_Write_Data);
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, HideProgress);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
result = curl_easy_perform(curl);
if (result == CURLE_OK)
{
if (DownloadThreads > 0)
{
DownloadThreads--;
}
MeshWriteChat(fmt::format("\awDownload of\ag {} \awcomplete.", filename), true);
}
else
{
if (DownloadThreads > 0)
{
DownloadThreads--;
}
MeshWriteChat(fmt::format("\arError downloading file\aw {}\ar.\n\a-r[\arError Code:\aw {}\a-r]", filename, curl_easy_strerror(result)), false);
}
curl_easy_cleanup(curl);
fclose(fp);
// Reload Database after we download it
if (!filename.empty() && filename == "meshdb.json")
{
MeshLoadDatabase();
}
// Update TLOS
fLastDL = (!filename.empty()) ? filename : "none";
fCurrentDL = "none";
fPathDL = "none";
fDownloading = false;
if (DownloadThreads == 0 && !fDownloadReady)
{
MeshWriteChat("\agAll downloads complete.", true);
}
}
}
}
/**
* TOP LEVEL OBJECTS
*
* TLOs available to grab information about current download (filename, progress, path, is a download running currently etc..)
*
* Will Add checking if mesh for current zone is up to date, mesh for a picked zone is up to date etc later when the code for that becomes
* available in the future.
*
*/
class MQ2MeshManagerType* pMeshTypes = 0;
class MQ2MeshManagerType : public MQ2Type
{
public:
enum Information
{
IsDownloading = 1,
DownloadCurrent = 2,
DownloadLast = 3,
DownloadProgress = 4,
DownloadPath = 5
};
MQ2MeshManagerType() :MQ2Type("MeshManager")
{
TypeMember(IsDownloading);
TypeMember(DownloadCurrent);
TypeMember(DownloadLast);
TypeMember(DownloadProgress);
TypeMember(DownloadPath);
}
virtual bool MQ2MeshManagerType::GetMember(MQVarPtr VarPtr, const char* Member, char* Index, MQTypeVar& Dest) override
{
auto pMember = MQ2MeshManagerType::FindMember(Member);
if (pMember)
{
switch ((Information)pMember->ID)
{
case IsDownloading:
Dest.DWord = fDownloading;
Dest.Type = mq::datatypes::pBoolType;
return true;
case DownloadCurrent:
Dest.Ptr = &fCurrentDL;
Dest.Type = mq::datatypes::pStringType;
return true;
case DownloadLast:
Dest.Ptr = &fLastDL;
Dest.Type = mq::datatypes::pStringType;
return true;
case DownloadProgress:
Dest.Int = fProgressDL;
Dest.Type = mq::datatypes::pIntType;
return true;
case DownloadPath:
Dest.Ptr = &fPathDL;
Dest.Type = mq::datatypes::pStringType;
return true;
}
}
}
};
bool DataMeshManager(const char* Index, MQTypeVar& Dest)
{
Dest.Type = pMeshTypes;
Dest.DWord = 1;
return true;
}
/**
* Settings/Configuration File
*
* Here's where we load/save our settings.
*
*/
void MeshManagerSaveSettings()
{
const std::string FileName = fmt::format("{}_{}.json", pEverQuestInfo->WorldServerShortname, pLocalPC->Name);
const fs::path f = fs::path(ConfPath) / FileName;
FILE* jFile;
json tmp;
auto& settings = tmp["Settings"];
settings["MaxDownloads"] = MaxDownloadThreads;
settings["MaxHashes"] = MaxHashThreads;
settings["DownloadMissing"] = AutoDownloadMissing;
settings["AutoUpdate"] = AutoCheckForUpdates;
settings["ProgressMeter"] = HideProgress;
settings["ThreadSafety"] = ThreadSafe;
const errno_t err = fopen_s(&jFile, f.string().c_str(), "wb");
if (err == 0)
{
fputs(tmp.dump().c_str(), jFile);
fclose(jFile);
}
else
{
MeshWriteChat("\arError opening settings file for writing.", false);
}
MeshManagerLoadSettings();
}
void MeshManagerLoadSettings()
{
const std::string FileName = fmt::format("{}_{}.json", pEverQuestInfo->WorldServerShortname, pLocalPC->Name);
const fs::path f = fs::path(ConfPath) / FileName;
FILE* jFile;
if (!fs::exists(f, ec))
{
MeshWriteChat("\arSettings File Doesn't Exist. Loading Default Settings.", false);
MeshManagerSaveSettings();
}
else
{
SettingsDatabase.clear();
const errno_t err = fopen_s(&jFile, f.string().c_str(), "rb");
if (err == 0)
{
try {
SettingsDatabase = json::parse(jFile);
}
catch (json::parse_error& e)
{
MeshWriteChat(fmt::format("\arInvalid or empty settings file. \a-r[\arError\aw: {}\a-r]", e.what()), false);
MeshWriteChat(fmt::format("\arDelete \a-r'\aw{}\a-r'\ar and reload the plugin.", f.string()), false);
}
fclose(jFile);
auto& settings = SettingsDatabase["Settings"];
MaxDownloadThreads = settings["MaxDownloads"];
MaxHashThreads = settings["MaxHashes"];
AutoDownloadMissing = settings["DownloadMissing"];
AutoCheckForUpdates = settings["AutoUpdate"];
HideProgress = settings["ProgressMeter"];
ThreadSafe = settings["ThreadSafety"];
}
else
{
MeshWriteChat("\arError opening settings file for reading.", false);
}
}
}
/**
* ZONE IGNORE
*
* For when you have a custom mesh and don't want it to get nuked by the updater.
*
*/
void MeshManagerSaveIgnores()
{
const fs::path p = fs::path(ConfPath) / "ZoneIgnores.json";
FILE* jFile;
json tmp;
std::string dummyobjline = "DO NOT DELETE DUMMY OBJECT";
if (!IgnoreList.empty())
{
for (int i = 0; i <= IgnoreList.size() - 1; i++)
{
if (IgnoreList[i] == std::to_string(0))
{
tmp["0"] = dummyobjline;
}
else
{
tmp[IgnoreList[i]] = true;
}
}
}
else
{
tmp["0"] = dummyobjline;
}
const errno_t err = fopen_s(&jFile, p.string().c_str(), "wb");
if (err == 0)
{
fputs(tmp.dump().c_str(), jFile);
fclose(jFile);
}
else
{
MeshWriteChat("\arError opening settings file for writing.", false);
}
MeshManagerLoadIgnores();
}
void MeshManagerLoadIgnores()
{
const fs::path p = fs::path(ConfPath) / "ZoneIgnores.json";
FILE* jFile;
if (!fs::exists(p, ec))
{
MeshManagerSaveIgnores();
}
else
{
IgnoreDatabase.clear();
const errno_t err = fopen_s(&jFile, p.string().c_str(), "rb");
if (err == 0)
{
try {
IgnoreDatabase = json::parse(jFile);
}
catch (json::parse_error& e)
{
MeshWriteChat(fmt::format("\arInvalid or empty ignores file. \a-r[\arError\aw: {}\a-r]", e.what()), false);
MeshWriteChat(fmt::format("\arDelete \a-r'\aw{}\a-r'\ar and recreate your ignore list.", p.string()), false);
}
fclose(jFile);
IgnoreList.clear();
for (auto i = IgnoreDatabase.begin(); i != IgnoreDatabase.end(); ++i)
{
if (i.key() == "0" || ValidateZoneShortName(i.key()))
{
IgnoreList.push_back(i.key());
}
}
}
else
{
MeshWriteChat("\arError opening ignore file for reading.", false);
}
}
}
void MeshManagerIgnore(const std::string& Param2, const std::string& Param3)
{
std::string zonename = GetShortZone(pLocalPC->zoneId);
if (Param2[0] == '\0' || mq::ci_equals(Param2, "list"))
{
MeshManagerMenu("ignorelist");
}
if (mq::ci_equals(Param2, "add"))
{
if (Param3[0] == '\0')
{
auto zn = std::find(IgnoreList.begin(), IgnoreList.end(), zonename);
if (zn == std::end(IgnoreList))
{
IgnoreList.push_back(zonename);
MeshWriteChat(fmt::format("\a-tAdded Zone\ag {} \a-tto download ignore list.", zonename), false);
MeshManagerSaveIgnores();
}
else
{
MeshWriteChat(fmt::format("\arZone\aw {} \aralready exists in the ignore list.", zonename), false);
}
}
else
{
auto p3 = mq::to_lower_copy(Param3);
if (ValidateZoneShortName(p3))
{
auto p3a = std::find(IgnoreList.begin(), IgnoreList.end(), p3);
if (p3a == std::end(IgnoreList))
{
IgnoreList.push_back(p3);
MeshWriteChat(fmt::format("\a-tAdded Zone\ag {} \a-tto download ignore list", p3), false);
MeshManagerSaveIgnores();
}
else
{
MeshWriteChat(fmt::format("\arZone\aw {} \aralready exists in the ignore list.", p3), false);
}
}
else
{
MeshWriteChat("\arInvalid zone shortname. Try again.", false);
}
}
}
if (mq::ci_equals(Param2, "del") || mq::ci_equals(Param2, "delete") ||
mq::ci_equals(Param2, "rem") || mq::ci_equals(Param2, "remove"))
{
if (Param3[0] == '\0')
{
auto zn = std::find(IgnoreList.begin(), IgnoreList.end(), zonename);
if (zn != std::end(IgnoreList))
{
for (int i = 0; i < (int)IgnoreList.size(); i++)
{
if (IgnoreList[i] == zonename)
{
IgnoreList.erase(std::next(IgnoreList.begin(), i));
MeshWriteChat(fmt::format("\a-tRemoved zone\ar {} \a-tfrom download ignore list.", zonename), false);
MeshManagerSaveIgnores();
break;
}
}
}
else
{
MeshWriteChat(fmt::format("\arZone\aw {} \ardoes not exist on the ignore list.", zonename), false);
}
}
else
{
auto p3 = mq::to_lower_copy(Param3);
if (ValidateZoneShortName(p3))
{
auto p3a = std::find(IgnoreList.begin(), IgnoreList.end(), p3);
if (p3a != std::end(IgnoreList))
{
IgnoreList.erase(p3a);
MeshWriteChat(fmt::format("\a-tRemoved zone\ar {} \a-tfrom download ignore list.", p3), false);
MeshManagerSaveIgnores();
}
else
{
MeshWriteChat(fmt::format("\arZone\aw {} \ardoes not exist on the ignore list.", p3), false);
}
}
else
{
MeshWriteChat("\arInvalid zone shortname. Try again.", false);
}
}
}
}
void MeshManagerConfirmAgreement()
{
fs::path fp = fs::path(ConfPath) / "confirmed.txt";
if (!fs::exists(fp, ec))
{
std::ofstream output(fp);
MeshWriteChat("\agAgreement Confirmed!", true);
}
else
{
MeshWriteChat("\arPermissions error. Can't open agreement file for writing.", false);
return;
}
}
/**
* COMMANDS
*
* Slash commands to operate plugin in game.
*
*/
void MeshManager(SPAWNINFO* pChar, char* szLine)
{
char fMsg[256] = { 0 };
bool syntaxError = false;
char Param1[MAX_STRING];
char Param2[MAX_STRING];
char Param3[MAX_STRING];
GetArg(Param1, szLine, 1);
GetArg(Param2, szLine, 2);
GetArg(Param3, szLine, 3);
if (InGameAndSpawned())
{
if (szLine[0] == 0)
{
MeshManagerMenu("help");
}
else if (mq::ci_equals(Param1, "help"))
{
MeshManagerMenu("help");
}
else if (mq::ci_equals(Param1, "agree"))
{
if (!fAgree)
{
if (mq::ci_equals(Param2, "confirm"))
{
MeshManagerConfirmAgreement();
}
else
{
MeshManagerMenu("agreement");
}
}
else
{
MeshWriteChat("\agAgreement already accepted!", false);
return;
}
}
else if (mq::ci_equals(Param1, "hash"))
{
MeshManagerDisplayHashes(Param2);
}
else if (mq::ci_equals(Param1, "ignore"))
{
MeshManagerIgnore(Param2, Param3);
}
else if (mq::ci_equals(Param1, "settings"))
{
MeshManagerMenu("settings");
}
else if (mq::ci_equals(Param1, "set"))
{
if (Param2[0] == '\0')
{
MeshManagerMenu("set");
}
else if (mq::ci_equals(Param2, "autoupdate"))
{
std::string AutoFeature;
if (Param3[0] == '\0')
{
AutoFeature = (AutoCheckForUpdates) ? "\agOn" : "\arOff";
MeshWriteChat(fmt::format("\a-tAutomatically Check For Updates\aw: {}", AutoFeature), false);
}
else if (Param3[0] != '\0')
{
if (mq::ci_equals(Param3, "on") || mq::ci_equals(Param3, "1") || mq::ci_equals(Param3, "true"))
{
AutoCheckForUpdates = true;
MeshWriteChat(fmt::format("\a-tAutomatically Check For Updates\aw:\ag {}", Param3), false);
MeshManagerSaveSettings();
}
else if (mq::ci_equals(Param3, "off") || mq::ci_equals(Param3, "0") || mq::ci_equals(Param3, "false"))
{
AutoCheckForUpdates = false;
MeshWriteChat(fmt::format("\a-tAutomatically Check For Updates\aw:\ar {}", Param3), false);
MeshManagerSaveSettings();
}
else
{
MeshWriteChat("\ar/mesh set autoupdaate <on/off/1/0/true/false>", false);
return;
}
}
}
else if (mq::ci_equals(Param2, "maxdownloads"))
{
if (Param3[0] == '\0')
{
MeshWriteChat(fmt::format("\a-tMax Download Threads\aw:\ag {}", std::to_string(MaxDownloadThreads)), false);
}
else if (Param3[0] != '\0')
{
if (!mq::IsNumber(Param3))
{
MeshWriteChat("\ar/mesh set maxdownloads requires a number 1-10.", false);
}
else
{
int p3 = mq::GetIntFromString(Param3, 0);
if (p3 <= 0 || p3 > 10)
{
MeshWriteChat("\ar/mesh set maxdownloads requires a number 1-10.", false);
}
else
{
MeshWriteChat(fmt::format("\a-tMax Download Threads\aw:\ag {}", p3), false);
MaxDownloadThreads = p3;
MeshManagerSaveSettings();
}
}
}
}
else if (mq::ci_equals(Param2, "maxhashes"))
{
if (Param3[0] == '\0')
{
MeshWriteChat(fmt::format("\a-tMax Hash Threads\aw:\ar {}", std::to_string(MaxHashThreads)), false);
}
else if (Param3[0] != '\0')
{
if (!mq::IsNumber(Param3))
{
MeshWriteChat("\ar/mesh set maxhashes requires a number 1-10.", false);
return;
}
else
{
int p3 = mq::GetIntFromString(Param3, 0);
if (p3 <= 0 || p3 > 10)
{
MeshWriteChat("\ar/mesh set maxhashes requires a number 1-10.", false);
return;
}
else
{
MeshWriteChat(fmt::format("\a-tMax Hash Threads\aw:\ag {}", Param3), false);
MaxHashThreads = p3;
MeshManagerSaveSettings();
}
}
}
}
else if (mq::ci_equals(Param2, "missing"))
{
std::string AutoFeature;
if (Param3[0] == '\0')
{
AutoFeature = (AutoDownloadMissing) ? "\agOn" : "\arOff";
MeshWriteChat(fmt::format("\a-tAutomatically Download Missing Meshes\aw: {}", AutoFeature), false);
}
else if (Param3[0] != '\0')
{