-
Notifications
You must be signed in to change notification settings - Fork 178
/
dependency.lic
1852 lines (1568 loc) · 61.1 KB
/
dependency.lic
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
=begin
Documentation: https://elanthipedia.play.net/Lich_script_development#dependency
=end
require 'json'
require 'net/http'
require 'base64'
require 'yaml'
require 'ostruct'
require 'digest/sha1'
require 'monitor'
$DEPENDENCY_VERSION = '2.0.5'
$MIN_RUBY_VERSION = '3.2.2'
DRINFOMON_IN_CORE_LICH ||= false
DRINFOMON_CORE_LICH_DEFINES ||= Array.new
no_pause_all
no_kill_all
unless XMLData.game =~ /^DR/
echo("This script is not intended for usage with games other than Dragonrealms. Exiting now")
exit
end
while Script.running?('repository')
echo("Repository is running, pausing for 10 seconds.")
pause 10
end
unless Settings['dependency_version'] == $DEPENDENCY_VERSION
echo("New dependency version detected. Resetting repository auto-update settings.")
Script.start("repository", "reset-update-settings")
if XMLData.game == "DRX" || XMLData.game == "DRF"
if XMLData.game == "DRX"
echo("DR Plat instance detected. Setting map to not auto-update.")
elsif XMLData.game == "DRF"
echo("DR Fallen instance detected. Setting map to not auto-update.")
end
Script.start("repository", "unset-mapdb-updatable")
end
Settings['dependency_version'] = $DEPENDENCY_VERSION
Settings.save
end
class Object
# IMPORT FUTURE LAWLZ
def itself
self
end
end
class ArgParser
def parse_args(data, flex_args = false)
raw_args = variable.first
baselist = variable.drop(1).dup || Array.new
unless baselist.size == 1 && baselist.grep(/^help$|^\?$|^h$/).any?
result = data.map { |definition| check_match(definition, baselist.dup, flex_args) }.compact
return result.first if result.length == 1
if result.empty?
echo "***INVALID ARGUMENTS DON'T MATCH ANY PATTERN***"
respond "Provided Arguments: '#{raw_args}'"
elsif result.length > 1
echo '***INVALID ARGUMENTS MATCH MULTIPLE PATTERNS***'
respond "Provided Arguments: '#{raw_args}'"
end
end
display_args(data)
exit
end
def display_args(data)
# This section displays help output for a script. It recognizes when a script call has been given
# with the wrong number or incorrect arguments, or when a script has been called via
# ;script-name help. It outputs an example script call, including arguments, with optional
# arguments enclosed in brackets. If an optional script_summary argument has been specified within
# the script, it also outputs a summary of the script. Further, if yaml settings have been
# outlined in base-help.yaml, it will output help information for the yaml settings used.
# Example output when all help settings have been specified:
#
# >;circlecheck help
# SCRIPT SUMMARY: Checks your circle and skills to next circle. Optionally checks skills for a target circle.
#
# SCRIPT CALL FORMAT AND ARG DESCRIPTIONS (arguments in brackets are optional):
# ;circlecheck [debug] [mode] [target] [script_summary]
# debug Runs the script with debug messages.
# mode Only display requirements you don't meet [brief, short, next]
# target See requirements for a specific circle
#
# YAML SETTINGS USED:
# circlecheck_prettyprint: Tells circlecheck to use the pretty print formatting for output. [Ex: true/false]
if Script.current.name != "bootstrap"
data.each do |def_set|
def_set
.select { |x| x[:name].to_s == "script_summary" }
.each { |x| respond " SCRIPT SUMMARY: #{x[:description]} " }
respond ''
respond " SCRIPT CALL FORMAT AND ARG DESCRIPTIONS (arguments in brackets are optional):"
respond " ;#{Script.current.name} " + def_set.map { |x| format_item(x) unless x[:name].to_s == "script_summary" }.join(' ')
def_set
.reject { |x| x[:name].to_s == "script_summary" }
.each { |x| respond " #{(x[:display] || x[:name]).ljust(12)} #{x[:description]} #{x[:options] ? '[' + x[:options].join(', ') + ']' : ''}" }
end
# Display help output for settings used in the script. Relies on base-help.yaml.
yaml_data = get_data('help').to_h
yaml_settings = yaml_data.select { |_field, info| info["referenced_by"].include?(Script.current.name) }
unless yaml_settings.empty?
respond ''
respond " YAML SETTINGS USED:"
yaml_settings.each do |field, info|
setting_line += " #{field}: #{info["description"]} #{info["specific_descriptions"][Script.current.name]}"
setting_line += " [Ex: #{info["example"]}]" unless info["example"].to_s.nil? || info["example"].to_s.empty?
respond setting_line
end
respond ""
end
end
end
private
def matches_def(definition, item)
echo "#{definition}:#{item}" if UserVars.parse_args_debug
return true if definition[:regex] && definition[:regex] =~ item
return true if definition[:options] && definition[:options].find { |option| item =~ /^#{option}#{'$' if definition[:option_exact]}/i }
false
end
def check_match(defs, vars, flex)
args = OpenStruct.new
defs.reject { |x| x[:optional] }.each do |definition|
return nil unless matches_def(definition, vars.first)
args[definition[:name]] = vars.first.downcase
vars.shift
end
defs.select { |x| x[:optional] }.each do |definition|
if (match = vars.find { |x| matches_def(definition, x) })
args[definition[:name]] = match.downcase
vars.delete(match)
end
end
if flex
args.flex = vars
# Check to see if a yaml profile has same name as script arg. Only matters when we're flexing
# args and attempting to call a yaml profile with the flexed arg.
profiles = Dir[File.join(SCRIPT_DIR, 'profiles/*.*')]
profiles.each do |profile|
profile = profile[/.*#{checkname}-(\w*).yaml/, 1]
args.to_h.values.each do |arg|
if arg == profile
echo "WARNING: yaml profile '#{checkname}-#{arg}.yaml' matches script argument '#{arg}'."
echo "Favoring the script argument. Rename the file if you intend to call it as a flexed settings file."
end
end
end
else
return nil unless vars.empty?
end
args
end
def format_item(definition)
item = definition[:display] || definition[:name]
if definition[:optional]
item = "[#{item}]"
elsif definition[:variable] || definition[:options]
item = "<#{item}>"
end
item
end
end
def parse_args(defn, flex_args = false)
ArgParser.new.parse_args(defn, flex_args)
end
def display_args(defn)
ArgParser.new.display_args(defn)
end
arg_definitions = [
[
{ name: 'debug', regex: /debug/i, optional: true },
{ name: 'install', regex: /install/i, optional: true }
]
]
args = parse_args(arg_definitions)
debug = args.debug || UserVars.debug_dependency
install = args.install
class ScriptManager
attr_reader :autostarts
def initialize(debug)
unless LICH_VERSION.match?(/^5/)
_respond("<pushBold/>*****************************************************************************<popBold/>")
_respond("<pushBold/>* Unsupported Lich versions detected. *<popBold/>")
_respond("<pushBold/>* See https://github.com/elanthia-online/dr-scripts/wiki/First-Time-Setup *<popBold/>")
_respond("<pushBold/>* For an update path. *<popBold/>")
_respond("<pushBold/>*****************************************************************************<popBold/>")
exit
end
@debug = debug
@paste_bin_token = 'dca351a27a8af501a8d3123e29af7981'
@paste_bin_url = 'https://pastebin.com/api/api_post.php'
@firebase_url = 'https://dr-scripts.firebaseio.com/'
@status_url = 'https://api.github.com/repos/elanthia-online/dr-scripts/git/trees/main'
# Gating setting lich_url on lich version
UserVars.autostart_scripts ||= []
UserVars.autostart_scripts.uniq!
UserVars.autostart_scripts = UserVars.autostart_scripts - ['dependency']
Settings['autostart'] ||= Array.new
unless Settings['autostart'] == Settings['autostart'].uniq
echo("Duplicate autostarts found.")
echo("Removing #{Settings['autostart'] - Settings['autostart'].uniq}")
Settings['autostart'].uniq!
Settings.save
end
if Settings['autostart'].include?('dependency')
echo("Dependency found in autostarts. It doesn't belond here. Removing it.")
Settings['autostart'] -= ['dependency']
Settings.save
end
# Setting Settings['lich_fork_sha'] to nil if using lich5. This setting isn't used anymore.
Settings['base_versions'] ||= {}
CharSettings['next_ruby_version_check_datetime'] = Time.now
@add_autos = []
@remove_autos = []
update_autostarts
@self_updated = false
@thievery_queue = []
@shop_update_queue = []
@request_authorization = manage_github_token
@versions = nil
end
def updated_dependency?
@self_updated
end
def update_autostarts
@autostarts = (UserVars.autostart_scripts + Settings['autostart']).uniq
end
def add_global_auto(script)
@add_autos << script
end
def remove_global_auto(script)
@remove_autos << script
end
def get_versions
if @versions
@versions
else
@versions = build_version_hash
end
end
def build_version_hash
Dir[File.join(SCRIPT_DIR, '*.lic')].each_with_object({}) do |path, versions|
file = File.basename(path)
body = File.open(File.join(SCRIPT_DIR, "#{file}"), 'r').readlines.join('')
sha = Digest::SHA1.hexdigest('blob' + " #{body.size}" + "\0" + body)
versions[file] = sha
end
end
def autos_proccessed?
@add_autos.empty? && @remove_autos.empty?
end
def queue_thieving_update(id, update)
@thievery_queue << [id, update]
end
def queue_shop_update(shop_data)
@shop_update_queue << shop_data
end
def run_queue
validate_supported_ruby_version
update = false
unless @add_autos.empty?
update = true
@add_autos.each { |script| Settings['autostart'] << script }
Settings.save
@add_autos = []
end
unless @remove_autos.empty?
update = true
@remove_autos.each { |script| Settings['autostart'].delete(script) }
Settings.save
@remove_autos = []
end
submit_thieving_update(*@thievery_queue.pop) unless @thievery_queue.empty?
submit_shop_update(@shop_update_queue.pop) unless @shop_update_queue.empty?
update_autostarts if update
end
def submit_shop_update(shop_data)
partial = shop_data[:surfaces].nil?
key = "#{shop_data[:root_room]}-#{shop_data[:entrance]}"
uri = URI.parse("#{@firebase_url}/shop-data/#{key}.json")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
begin
request = partial ? Net::HTTP::Patch.new(uri.request_uri) : Net::HTTP::Put.new(uri.request_uri)
request['Content-Type'] = 'application/json'
request.body = shop_data.to_json
response = http.request(request)
response.body.chomp
rescue => e
echo(e)
echo('Error in submitting shop data')
end
end
def get_script(filename, force = false)
filename = filename.dup
echo("checking:#{filename} force:#{force}") if @debug
download_script(filename, force)
end
def repo_scripts
$manager.get_status['tree'].map { |element| element['path'] }.select { |file| file.include?('.lic') && !file.include?('-setup') }
end
def start_scripts(force = false)
start_time = Time.now
@versions = nil
repo_scripts.each { |(name, _)| get_script(name, force) }
autostarts.each do |script|
if script == 'drinfomon'
respond "\n---\ndrinfomon found in autostarts. This method is no longer used. Attempting to remove it now. If unsuccessful, it can be safely removed with `#{$clean_lich_char}e stop_autostart('drinfomon')`\n---\n"
stop_autostart('drinfomon')
next
end
custom_require.call(script)
loop do
pause 0.2
break unless !Script.running.find_all { |s| s.name =~ /bootstrap/ }.empty?
end
end
finish_time = Time.now
run_time = finish_time - start_time
echo("Time spent in start_scripts is #{run_time}") if @debug
end
def download_script(filename, force = false)
return if filename.nil? || filename.empty?
echo("downloading:#{filename}") if @debug
info = get_file_status(filename)
return unless info
return if get_versions[filename] == info['sha'] && !force
if filename == 'dependency.lic' && File.exist?(File.join(SCRIPT_DIR, filename))
body = File.open(File.join(SCRIPT_DIR, filename), 'r').readlines.join('')
@versions[filename] = Digest::SHA1.hexdigest('blob' + " #{body.size}" + "\0" + body)
return if info['sha'] == @versions[filename]
end
echo("info:#{info}") if @debug
blob = make_request(info['url'])
File.open(File.join(SCRIPT_DIR, "#{filename}"), 'w') { |file| file.print(Base64.decode64(blob['content'])) }
@self_updated = true if filename == 'dependency.lic'
end
def verify_or_make_dir(path)
Dir.mkdir(path) unless Dir.exist?(path)
end
def setup_profiles
verify_or_make_dir File.join(SCRIPT_DIR, 'profiles')
profile_tree_url = get_status['tree'].find { |element| element['path'] == 'profiles' }['url']
make_request(profile_tree_url)['tree']
# Select only base.yaml and base-empty.yaml
.select { |data| /^base(?:-empty)?\.yaml/ =~ data['path'] }
.each do |setup_file|
echo("downloading #{setup_file}") if @debug
blob = make_request(setup_file['url'])
File.open(File.join(SCRIPT_DIR, "profiles/#{setup_file['path']}"), 'w') { |file| file.print(Base64.decode64(blob['content'])) }
end
end
def setup_data
verify_or_make_dir File.join(SCRIPT_DIR, 'data')
data_tree_url = get_status['tree'].find { |element| element['path'] == 'data' }['url']
make_request(data_tree_url)['tree'].each do |setup_file|
echo("downloading #{setup_file}") if @debug
blob = make_request(setup_file['url'])
File.open(File.join(SCRIPT_DIR, "data/#{setup_file['path']}"), 'w') { |file| file.print(Base64.decode64(blob['content'])) }
end
end
def update_local_stealing_yaml(id, update, new_entry = false)
stealing_path = File.join(SCRIPT_DIR, 'data/base-stealing.yaml')
stealing_data = $setupfiles.safe_load_yaml(stealing_path)
result = nil
if new_entry
stealing_data[:stealing_options].push(update)
else
stealing_data[:stealing_options].each do |data|
if data['id'] == id
result = data.dup
data.merge!(update)
end
end
end
File.open(stealing_path, 'w') { |file| file.print(stealing_data.to_yaml) }
result
end
def check_base_files
start_time = Time.now
verify_or_make_dir File.join(SCRIPT_DIR, 'profiles')
profile_tree_url = get_status['tree'].find { |element| element['path'] == 'profiles' }['url']
make_request(profile_tree_url)['tree']
# Select only base.yaml and base-empty.yaml
.select { |data| /^base(?:-empty)?\.yaml/ =~ data['path'] }
# Reject files that exist, and have the same shasum as those on the repo.
.reject { |setup_file| File.exist?(File.join(SCRIPT_DIR, 'profiles', setup_file['path'])) && setup_file['sha'] == Settings['base_versions'][setup_file['path']] }
.each do |setup_file|
echo("downloading #{setup_file}") if @debug
blob = make_request(setup_file['url'])
File.open(File.join(SCRIPT_DIR, "profiles/#{setup_file['path']}"), 'w') { |file| file.print(Base64.decode64(blob['content'])) }
Settings['base_versions'][setup_file['path']] = setup_file['sha']
end
Settings.save
finish_time = Time.now
run_time = finish_time - start_time
echo("Time spent in check_base_files is #{run_time}") if @debug
end
def check_data_files
start_time = Time.now
verify_or_make_dir File.join(SCRIPT_DIR, 'data')
profile_tree_url = get_status['tree'].find { |element| element['path'] == 'data' }['url']
make_request(profile_tree_url)['tree']
.select { |data| /^base.+yaml/ =~ data['path'] }
# Reject files that exist, and have the same shasum as those on the repo.
.reject { |setup_file| File.exist?(File.join(SCRIPT_DIR, 'data', setup_file['path'])) && setup_file['sha'] == Settings['base_versions'][setup_file['path']] }
.each do |setup_file|
echo("downloading #{setup_file}") if @debug
blob = make_request(setup_file['url'])
File.open(File.join(SCRIPT_DIR, "data/#{setup_file['path']}"), 'w') { |file| file.print(Base64.decode64(blob['content'])) }
Settings['base_versions'][setup_file['path']] = setup_file['sha']
end
Settings.save
finish_time = Time.now
run_time = finish_time - start_time
echo("Time spent in check_data_files is #{run_time}") if @debug
end
def run_script(filename)
filename.sub!(/\.lic$/, '')
echo("refresh:#{filename}") if @debug
stop_script(filename) if Script.running?(filename)
pause 0.1 while Script.running?(filename)
start_script(filename)
end
def get_file_status(filename)
get_status['tree'].find { |element| element['path'] == filename }
end
def get_status
if Settings['status'] && Time.now - Settings['status_time'] <= 3600
echo("Returning cached status response") if @debug
return Settings['status']
end
Settings['status_time'] = Time.now
Settings['status'] = make_request(@status_url)
Settings.save
return Settings['status']
end
def make_request(raw_uri)
echo "make_request:raw_uri = #{raw_uri}" if @debug
uri = URI.parse(raw_uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
request['Authorization'] = @request_authorization
response = http.request(request)
JSON.parse(response.body)
end
def manage_github_token
# This method manages some checking of the GitHub token we'll be using. We allow a personal
# GitHub token to be specified in the /data folder, or we can use the general Lich token.
# If using a personal GitHub token, we'll verify the token is valid, and we'll also do some
# checking of the rate limit for the token we're using. If the rate limit is above a certain
# threshold, we'll warn but won't fail, as Lich can still function when the rate limit is
# exceeded, albeit with some reduced functionality.
# Returns: request['Authorization'] token string
github_token = [
'Z2hwX21XN1',
'V0RkdORXdGYlpmVDF1S3AzM2I1TV',
'J5bHlTNjBXc09VNw==',
'\n'
].join('')
# Set up our rate limit check URL and items
url = URI("https://api.github.com/rate_limit")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
# Check if the user has a githubtoken.txt file and use the token in that file if so. If they
# do have a personal token specified, verify valid. Else, use general token. Note: the .strip
# is apparently necessary to have the File.read function in Linux.
if File.exist?("#{DATA_DIR}/githubtoken.txt")
echo "Using personal GitHub token."
request['Authorization'] = "token #{File.read("#{DATA_DIR}/githubtoken.txt").strip}"
# Verify the GitHub token is valid. If not, swap to the general token.
if http.request(request).body =~ /Bad credentials/
echo "Bad personal GitHub token. Reverting to Lich's general token."
echo "Please update /lich/data/githubtoken.txt"
request['Authorization'] = "token #{Base64.decode64(github_token)}"
end
else
echo "Using general GitHub token." if @debug
request['Authorization'] = "token #{Base64.decode64(github_token)}"
end
response = http.request(request)
parsed_response = JSON.parse(response.body)
used = parsed_response["resources"]["core"]["used"].to_i
limit = parsed_response["resources"]["core"]["limit"].to_i
echo "Current token rate limit usage: #{used}/#{limit}" if @debug
# Warn if rate limit is currently above 80% usage.
if used.to_f / limit >= 0.8 && @debug
echo ""
echo "*** WARNING: GitHub rate currently #{used}/#{limit} ***"
echo "*** Please report in Discord or GitHub. ***"
echo ""
end
return request['Authorization']
end
def submit_thieving_update(id, update)
return submit_new_thieving_item(id, update) if update.delete('new')
old_data = update_local_stealing_yaml(id, update)
# return
data = get_current_stealing_data(id)
update.delete_if do |key, value|
echo("checking:#{data[key]}:#{old_data[key]}") if UserVars.crossing_trainer_debug
key =~ /_min$/ ? data[key] && data[key] != old_data[key] && value >= data[key] : data[key] && data[key] != old_data[key] && value <= data[key]
end
if update.empty?
echo('Nothing left to update') if UserVars.crossing_trainer_debug
return
end
echo("submitting:#{id}:#{update}") if UserVars.crossing_trainer_debug
uri = URI.parse("#{@firebase_url}/stealing-options/#{id}.json")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Patch.new(uri.request_uri)
request['Content-Type'] = 'application/json'
request.body = update.to_json
response = http.request(request)
response.body.chomp
end
def submit_new_thieving_item(id, data)
id = (id.to_i + 1).to_s while get_current_stealing_data(id)
data['id'] = id
update_local_stealing_yaml(id, data, true)
echo("submittingNEW:#{id}:#{data}") if UserVars.crossing_trainer_debug
uri = URI.parse("#{@firebase_url}/stealing-options/#{id}.json")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Put.new(uri.request_uri)
request['Content-Type'] = 'application/json'
request.body = data.to_json
response = http.request(request)
response.body.chomp
end
def get_current_stealing_data(id)
uri = URI.parse("#{@firebase_url}/stealing-options/#{id}.json")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
request['Content-Type'] = 'application/json'
response = http.request(request)
return nil if response.body.nil?
begin
JSON.parse(response.body.chomp)
rescue
return nil
end
end
def make_map_edits
echo("Applying personal map overrides")
# Get base and personal wayto overrides
base_wayto_overrides = get_settings.base_wayto_overrides
personal_wayto_overrides = get_settings.personal_wayto_overrides
# Merge the two hashes into a single hash, favoring personal overrides for duplicate keys.
wayto_overrides = base_wayto_overrides.merge(personal_wayto_overrides)
# Iterate through the aggregated map wayto overrides from above and set new stringprocs
wayto_overrides.each do |_key, values|
start_room_id = values['start_room'].to_i
end_room_id = values['end_room'].to_i
start_room = Map.list[start_room_id]
old_wayto = start_room.wayto["#{end_room_id}"]
old_timeto = start_room.timeto["#{end_room_id}"]
new_wayto = old_wayto
new_timeto = old_timeto
if values['str_proc']
new_wayto = StringProc.new("#{values['str_proc']}")
end
if values['travel_time']
new_timeto = values['travel_time'].to_f
end
start_room.wayto["#{end_room_id}"] = new_wayto
start_room.timeto["#{end_room_id}"] = new_timeto
end
# Pull personal map custom targets, if any
personal_map_targets = get_settings.personal_map_targets
if personal_map_targets
custom_targets = (GameSettings['custom targets'] || Hash.new)
custom_targets.merge!(personal_map_targets)
GameSettings['custom targets'] = custom_targets
end
end
end
class BankbotManager
def initialize(debug)
@debug = debug
@save = false
@load = false
@transaction = ''
@ledger = {}
end
attr_reader :ledger
def loaded?
!@load
end
def run_queue
save_transaction
load_ledger
end
def save_bankbot_transaction(transaction, ledger)
@transaction = transaction
@ledger = ledger.to_yaml
@save = true
end
def load_bankbot_ledger
@load = true
end
private
def save_transaction
return unless @save
File.open(File.join(LICH_DIR, "#{checkname}-transactions.log"), 'a') do |file|
file.puts('----------')
file.puts(Time.now)
file.puts(@transaction)
file.puts(@ledger)
file.puts('----------')
end
File.open(File.join(LICH_DIR, "#{checkname}-ledger.yaml"), 'wb') { |file| file.puts(@ledger) }
@save = false
end
def load_ledger
return unless @load
@ledger = safe_load_yaml("./#{checkname}-ledger.yaml")
@load = false
end
def safe_load_yaml(path)
if (RUBY_VERSION =~ /^2/)
OpenStruct.new(YAML.load_file(path)).to_h
elsif (RUBY_VERSION =~ /^3/)
OpenStruct.new(YAML.unsafe_load_file(path)).to_h
end
rescue => e
echo('*** ERROR PARSING YAML FILE ***')
echo(e.message)
return {}
end
end
class ReportbotManager
def initialize(debug)
@debug = debug
@save = false
@load = false
@whitelist = []
end
attr_reader :whitelist
def loaded?
!@load
end
def run_queue
save_whitelist
load_whitelist
end
def save_reportbot_whitelist(whitelist)
@whitelist = whitelist.to_yaml
@save = true
end
def load_reportbot_whitelist
@load = true
end
private
def save_whitelist
return unless @save
File.open(File.join(LICH_DIR, 'reportbot-whitelist.yaml'), 'wb') { |file| file.puts(@whitelist) }
@save = false
end
def load_whitelist
return unless @load
@whitelist = safe_load_yaml('./reportbot-whitelist.yaml')
@load = false
end
def safe_load_yaml(path)
if (RUBY_VERSION =~ /^2/)
YAML.load_file(path)
elsif (RUBY_VERSION =~ /^3/)
YAML.unsafe_load_file(path)
end
rescue => e
echo('*** ERROR PARSING YAML FILE ***')
echo(e.message)
return []
end
end
class SlackbotManager
def initialize(debug)
@debug = debug
@slackbot = nil
@username = nil
@messages = []
end
def run_queue
register_slackbot
send_messages
end
def register(username)
return if @slackbot
@username = username
end
def queue_message(message)
return unless message
@messages << message
end
private
def register_slackbot
return unless @username
return unless @slackbot.nil?
echo("Registering Slackbot")
custom_require.call('slackbot')
@slackbot = SlackBot.new
end
def send_messages
return unless @slackbot
until @messages.empty?
message = @messages.shift
@slackbot.direct_message(@username, message)
end
end
end
class SetupFiles
# http://www.druby.org/sidruby/5-3-thread-safe-communication-using-locking-mutex-and-monitormixin.html#sec.monitormixin
include MonitorMixin
class FileInfo
attr_reader :path, :name, :mtime
def initialize(path:, name:, data:, mtime:)
@path = path
@name = name
@data = data
@mtime = mtime
end
def data
# Create deep clone of data to mitigate scripts changing settings in-memory
# because that leads to hard to track down bugs and unpredictable script behaviors.
Marshal.load(Marshal.dump(@data))
end
def peek(property)
# An efficient and safe way to return a specific property
# from the yaml file without the risks of passing around shallow copies.
# This marshals the one property which is magnitudes faster than
# marshalling the entire file to access one property.
Marshal.load(Marshal.dump(@data[property.to_sym]))
end
def to_s
File.join(@path, @name)
end
def inspect
"#<SetupFiles::FileInfo @name=#{@name}, @path=#{@path}, @mtime=#{@mtime}>"
end
end
def initialize(debug = false)
super() # Must call super() to initialize the MonitorMixin
@files_cache = {} # map of filenames => FileInfo objects
@debug = debug
end
def safe_load_yaml(filepath)
if (RUBY_VERSION =~ /^2/)
OpenStruct.new(YAML.load_file(filepath)).to_h
elsif (RUBY_VERSION =~ /^3/)
OpenStruct.new(YAML.unsafe_load_file(filepath)).to_h
end
rescue => e
echo('*** ERROR PARSING YAML FILE ***')
echo(e.message)
return {}
end
# Returns your character's settings.
# base.yaml, base-empty.yaml, and MyChar-setup.yaml are always loaded.
# You can also provide an array of character yaml suffixes to load additionally.
# For example, ['hunt'] to load 'scripts/profiles/MyChar-hunt.yaml'.
# The suffixes feature is primarily used by hunting-buddy.
def get_settings(character_suffixes = [])
character_suffixes = ['setup', character_suffixes].flatten.compact.uniq
character_filenames = character_suffixes_to_filenames(character_suffixes)
# Ensure latest profiles are loaded into cache
reload_profiles(character_filenames)
# Get 'include' filenames, suffixes to other files where players externalize
# reusable settings that they share/include in other character setting files.
include_filenames = character_filenames
.reduce([]) do |result, filename|
result + (cache_get_by_filename(filename).peek('include') || [])
end
.map do |suffix|
to_include_filename(suffix)
end
reload_profiles(include_filenames)
# Merge base and character settings
settings = [
'base.yaml',
'base-empty.yaml',
include_filenames,
character_filenames
].flatten.reduce({}) do |result, filename|
result.merge(cache_get_by_filename(filename).data || {})
end
# Transform settings for quality of life improvements
transform_settings(settings)
end
# Returns the config in a 'scripts/data/base-{type}.yaml' file.
# For example, type could be 'spells' or 'town' to return base-spells.yaml or base-town.yaml.
def get_data(type)
filename = to_base_filename(type)
# Ensure latest data is loaded into cache
reload_data([filename])
# Transform data for quality of life improvements
transform_data(cache_get_by_filename(filename).data)
end
# Designed to be called once before dependency enters its run loop.
# Purpose is to check for file changes and reload them into cache.
def reload
reload_profiles(character_suffixes_to_filenames(['setup']))
reload_data
end
private
SCRIPTS_DATA_PATH = File.join(SCRIPT_DIR, 'data')
# use alternate location for settings to allow folks to use lich with
# alternate configurations in Test/Platinum/Fallen
if File.exist?(File.join(DATA_DIR, XMLData.game, "base.yaml")) && File.exist?(File.join(DATA_DIR, XMLData.game, "base-empty.yaml")) && File.exist?(File.join(DATA_DIR, XMLData.game, "#{checkname}-setup.yaml"))
echo("Detected game instance-specific files. Loading settings from #{File.join(DATA_DIR, XMLData.game)}")
SCRIPTS_PROFILES_PATH = File.join(DATA_DIR, XMLData.game)
else
SCRIPTS_PROFILES_PATH = File.join(SCRIPT_DIR, 'profiles')
end
# Reloads the base profiles plus any that match the filenames given.
def reload_profiles(filenames = [])
load_files(get_profiles_glob_patterns(filenames))
end
# Reloads the base data plus any that match the filenames given.
def reload_data(filenames = [])
load_files(get_data_glob_patterns(filenames))
end
# Gets glob patterns for the profiles directory.
# Includes base profiles plus any specified in the filenames argument.
def get_profiles_glob_patterns(filenames = [])
get_glob_patterns(SCRIPTS_PROFILES_PATH, filenames)
end
# Gets glob patterns for the data directory.
# Includes base data plus any specified in the filenames argument.
def get_data_glob_patterns(filenames = [])
get_glob_patterns(SCRIPTS_DATA_PATH, filenames)
end