forked from steve8x8/geotoad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
geotoad.rb
executable file
·1182 lines (1046 loc) · 40.8 KB
/
geotoad.rb
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
#!/usr/bin/env ruby
#
# This is the main geotoad binary.
#
require 'pathname'
$BASEDIR = File.dirname(File.realpath(__FILE__))
$LOAD_PATH << $BASEDIR
$LOAD_PATH << File.join($BASEDIR, 'lib')
Encoding.default_external = Encoding::UTF_8
$delimiters = /[\|:]/
$delimiter = '|'
$my_lat = nil
$my_lon = nil
# toss in our own libraries.
require 'interface/progressbar'
require 'lib/common'
require 'lib/messages'
require 'interface/input'
require 'lib/shadowget'
require 'lib/search'
require 'lib/filter'
require 'lib/output'
require 'lib/details'
require 'lib/auth'
require 'lib/version'
require 'getoptlong'
require 'fileutils'
require 'find' # for cleanup
require 'zlib'
require 'cgi'
require 'net/https' # for openssl
require 'rexml/document' # for xml parsing
class GeoToad
include Common
include Messages
include Auth
$VERSION = GTVersion.version
# with the new progressive slowdown, start with 1 second
$SLEEP = 1.0
# *if* cache D/T/S extraction works, early filtering is possible
$DTSFILTER = true
# time to use for "unknown" creation dates
$ZEROTIME = 946728000 # 2000-01-01T13:00:00Z
# conversion miles to kilometres
$MILE2KM = 1.609344
def initialize
$debugMode = 0
# output = Output.new
# $validFormats = output.formatList.sort
@uin = Input.new
$CACHE_DIR = findCacheDir()
@configDir = findConfigDir
# $mapping = loadMapping()
$membership = nil # unknown before searching
end
def populate
output = Output.new
$validFormats = output.formatList.sort
$mapping = loadMapping()
end
def caches(num, what = "cache", length = 4)
if (num > 0)
counter = "#{num.to_s}"
else
counter = "no"
end
return "#{counter.rjust(length)} #{what}" + ((num != 1) ? 's' : '')
end
def getoptions
if ARGV[0]
# command line arguments
@option = @uin.getopt
$mode = 'CLI'
else
# Then go into interactive.
print "** Press Enter to start the Text User Interface: "
$stdin.gets
@option = @uin.interactive
$mode = 'TUI'
end
# if version info requested, skip other checks
if @option['version']
return @option
end
# enable synchronous output if selected by user
if (@option['unbufferedOutput'])
if (! $stdout.sync)
$stdout.flush
$stdout.sync = true
puts "(***) Switched to unbuffered output"
end
end
# may be nil, a number, or "something non-nil" (=1)
if (@option['verbose'])
if (@option['verbose'].to_i > 0)
displayInfo "Setting debug level to #{@option['verbose']}"
enableDebug(@option['verbose'].to_i)
else
displayInfo "Setting debug level to 1"
enableDebug
end
else
debug "Suppressing debug output"
disableDebug
end
if @option['proxy']
ENV['HTTP_PROXY'] = @option['proxy']
end
# We need this for the check following
@queryType = @option['queryType'] || 'location'
@queryArg = @option['queryArg'] || nil
# Get this out of the way now.
if @option['help']
@uin.usage
exit
end
if (! @option['user']) || (! @option['password'])
debug "No user/password option given, loading from config."
(@option['user'], @option['password']) = @uin.loadUserAndPasswordFromConfig()
if (! @option['user']) || (! @option['password'])
displayError "You must specify a username and password!"
exit
end
end
# switch -X to disable early DTS filtering
if (@option['disableEarlyFilter'])
$DTSFILTER = false
end
@preserveCache = @option['preserveCache']
@formatTypes = @option['format'] || 'gpx'
# there is no "usemetric" cmdline option but the TUI may set it
@useMetric = @option['usemetric']
# distanceMax from command line can contain the unit
@distanceMax = @option['distanceMax'].to_f
if @distanceMax == 0.0
@distanceMax = 10
end
if @option['distanceMax'] =~ /(mi|km)/
@useMetric = ($1 == "km" || nil)
# else leave usemetric unchanged
end
if @useMetric
# convert to miles, round to multiple of ~.5ft
@distanceMax = sprintf("%.4f", @distanceMax / $MILE2KM).to_f
end
debug "Internally using distance #{@distanceMax} miles."
# include query type, will be parsed by output.rb
@queryTitle = "GeoToad: #{@queryType} = #{@queryArg}"
@defaultOutputFile = "gt_" + @queryArg.to_s
# collect additional title and output filename text
# key: short option
# 'f': filename << "#{key}#{h['f']}"
# 't': title << "#{h['t']} #{h['f']}"}"
@appliedFilters = Hash.new
# No early format validity check
@limitPages = @option['limitSearchPages'].to_i
debug "Limiting search to #{@limitPages.inspect} pages" if (@limitPages != 0)
# check for a gpx track to pase
# uses the maxDistance for its calculation so needs to be after distance determination
if @option['gpxTrack'] and !@queryArg
@queryType = 'coord'
# set the GPX Trackpoints as query array
@queryArg = parseGPXTrack(@option['gpxTrack'])
end
if ! @option['clearCache'] && ! @option['myLogs'] && ! @option['myTrackables'] && ! @queryArg
displayError "You forgot to specify a #{@queryType} search argument"
@uin.usage
exit
end
return @option
end
## Check the version #######################
def comparableVersion(text)
# Make a calculatable/comparable version number
parts = text.split('.')
version = (parts[0].to_i * 10000) + (parts[1].to_i * 100) + parts[2].to_i
return version
end
def versionCheck
checkurl = "https://raw.githubusercontent.com/wiki/steve8x8/geotoad/CurrentVersion.md"
wikiurl = "https://github.com/steve8x8/geotoad/wiki/CurrentVersion"
version = ShadowFetch.new(checkurl)
version.localExpiry = 1 * 86400 # 1 day
version.maxFailures = 0
version.fetch
# version=a.bb.cc[*] in wiki page (* marks "supersedes all")
if version.data =~ /version=(\d\.\d+[\.\d]+)(\*)?/
latestVersion = $1
obsoleteOlder = ! $2.to_s.empty?
if comparableVersion(latestVersion) > comparableVersion($VERSION)
displayBar
displayWarning "VersionCheck: GeoToad #{latestVersion} is now available!"
displayBar
version.data.scan(/version=\S*\s*(.*?)\s*---/im) do |notes|
text = notes[0].dup
text.gsub!(/^#\s/, "\n\* ")
text.gsub!(/^##\s/, "\n\+ ")
text.gsub!(/^###\s/, "\n\- ")
text.gsub!(/#+$/, "")
text.gsub!(/\n\n+/, "\n")
text.gsub!(/\ /, '-')
textlines = text.split("\n")
(1..20).each{ |line|
displayBox textlines[line] if textlines[line]
}
displayBox "... see #{wikiurl} for more" if textlines.length > 20
if obsoleteOlder
displayBar
displayWarning "Older versions do not work any longer. Update NOW!"
displayBar
end
end
displayBar
if $VERSION !~ /CURRENT/
displayInfo "(sleeping for 30 seconds)"
sleep(30)
end
end
end
debug "Check complete."
end
def findRemoveFiles(where, age, pattern = ".*\\..*", writable = nil)
# inspired by ruby-forum.com/topic/149925
regexp = Regexp.compile(pattern)
debug "findRemoveFiles() age=#{age}, pattern=#{pattern}, writable=#{writable.inspect}"
filelist = Array.new
begin # catch filesystem problems
Find.find(where){ |file|
# never touch directories
next if not File.file?(file)
next if (age * 86400) > (Time.now - File.mtime(file)).to_i
next if not regexp.match(File.basename(file))
next if writable and not File.writable?(file)
filelist.push file
}
rescue => error
displayWarning "Cannot parse #{where}: #{error}"
return
end
filecount = filelist.length
debug2 "found #{filecount} files to remove: #{filelist.inspect}"
if not filelist.empty?
displayInfo "... #{filecount} files to remove"
filelist.each{ |file|
begin
File.delete(file)
rescue => error
displayWarning "Cannot delete #{file}: #{error}"
end
}
end
end
def clearCacheDirectory
displayMessage "Clearing #{$CACHE_DIR} selectively"
displayInfo "Clearing account data older than 7 days"
findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "account"), 7)
# obsolete again 2014-10-28
#findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "myaccount"), 7)
displayInfo "Clearing login data older than 7 days"
findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "login"), 7)
# We do NOT clear cdpf files, in NO case. Instead, preserve old descriptions!
# If you really want this functionality, uncomment the following two lines:
#displayInfo "Clearing cache descriptions older than 31 days"
#findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "seek"), 31, "^cdpf\\.aspx.*", true)
displayInfo "Clearing cache details older than 3 days"
findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "seek"), 3, "^cache_details\\.aspx.*", true)
displayInfo "Clearing log submission pages older than 3 days"
findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "seek"), 3, "^log\\.aspx.*", true)
displayInfo "Clearing lat/lon query data older than 3 days"
findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "seek"), 3, "^nearest\\.aspx.*_lat_.*_lng_.*", true)
displayInfo "Clearing state and country query data older than 3 days"
findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "seek"), 3, "^nearest\\.aspx.*_(country|state)_id_.*", true)
displayInfo "Clearing other query data older than 7 days"
findRemoveFiles(File.join($CACHE_DIR, "www.geocaching.com", "seek"), 7, "^nearest\\.aspx.*", true)
displayMessage "Cleared!"
$CACHE_DIR = findCacheDir()
end
## Make the Initial Query ############################
def downloadGeocacheList
displayInfo "Cache directory: " + $CACHE_DIR
# Mike Capito contributed a patch to allow for multiple
# queries. He did it as a hash earlier, I'm just simplifying
# and making it as an array because you probably don't want to
# mix multiple @queryType's anyways
@combinedWaypoints = Hash.new
displayMessage "Logging in as #{@option['user']}"
@cookie = login(@option['user'], @option['password'])
debug "Login returned cookie #{hideCookie(@cookie).inspect}"
if (@cookie)
displayMessage "Login successful"
else
displayWarning "Login failed! Check network connection, username and password!"
displayWarning "Note: Subsequent operations may fail. You've been warned."
end
displayMessage "Querying user preferences"
@dateFormat, prefLang, $my_lat, $my_lon, $my_src = getPreferences()
displayInfo "Using date format #{@dateFormat}, language #{prefLang}"
displayInfo "Using home location (#{$my_lat || 'nil'}, #{$my_lon || 'nil'}) from #{$my_src}"
if @option['myLogs'] || @option['myTrackables']
displayMessage "Retrieving my logs"
message = ""
if @option['myLogs']
foundcount, logcount = getMyLogs()
message << "Found count: #{foundcount}. "
message << "Cache logs: #{logcount}. "
end
if @option['myTrackables']
logcount = getMyTrks()
message << "Trackable logs: #{logcount}."
end
displayInfo message
end
# search radius applies to all queryArgs, show only once
if @queryType == 'location' || @queryType == 'coord'
# choose correct unit for query title and output filename
# strip off trailing 0's and period
# keep information close to the query location
if @useMetric
dist_km = sprintf("%.3f", @distanceMax * $MILE2KM).gsub(/\.?0*$/, '')
@queryTitle << " (#{dist_km} km radius)"
@defaultOutputFile << "-y#{dist_km}km"
else
dist_mi = sprintf("%.3f", @distanceMax).gsub(/\.?0*$/, '')
@queryTitle << " (#{@distanceMax} mi radius)"
@defaultOutputFile << "-y#{dist_mi}"
end
end
displayBar
#puts ""
@queryArg.to_s.split($delimiters).each{ |queryArg0|
queryArg = queryArg0.gsub(/^\s+/, '').gsub(/\s+$/, '')
message = "\"#{@queryType}\" search for \"#{queryArg}\""
search = SearchCache.new
# radius is only valid for location or coordinate searches
if @queryType == 'location' || @queryType == 'coord'
message << ", constraining to "
if @useMetric
message << "#{dist_km} km"
else
message << "#{dist_mi} miles"
end
search.distance = @distanceMax
end
# limit search page count
search.max_pages = @limitPages
if @option['cacheType']
# filter by cacheType
cacheTypes = @option['cacheType'].split($delimiters)
cacheType0 = cacheTypes[0]
if (cacheTypes.length == 1)
# inverted filter? careful...
if (cacheType0 !~ /-$/)
# if only one type, use tx= parameter (pre-filtering)
message << ", filter for \"#{cacheType0}\""
search.txfilter = cacheType0
end
# otherwise, warn if "all xxx" is in the list
elsif cacheTypes.map{ |t| (t =~ /\+$/) ? "x" : nil }.any?
displayWarning "\"all\" only works as single cache type - your results will be wrong!"
sleep 10
end
end
displayMessage message
# exclude own found
search.notyetfound = (@option['notFoundByMe'] ? true : false)
# this is kind of late, but we did our best
# we had to set txfilter and notyetfound before because setType creates the search URL
if (! search.setType(@queryType, queryArg))
displayWarning "Search \"#{@queryType}\" for \"#{queryArg}\" unknown."
displayWarning "Check for special characters or try a \"coord\" search instead."
sleep 10
next
end
waypoints = search.getResults()
# this gives us support for multiple searches. It adds together the search.waypoints hashes
# and pops them into the @combinedWaypoints hash.
@combinedWaypoints.update(waypoints)
@combinedWaypoints.rehash
}
# Here we make sure that the amount of waypoints we've downloaded (@combinedWaypoints) matches the
# amount of waypoints we found information for. This is just to check for buggy search code, and
# really doesn't make much sense.
waypointsExtracted = 0
@combinedWaypoints.each_key{ |wp|
debug2 "pre-filter: #{wp}"
waypointsExtracted = waypointsExtracted + 1
}
debug "waypoints extracted: #{waypointsExtracted}, combined: #{@combinedWaypoints.length}"
if (waypointsExtracted < @combinedWaypoints.length)
displayWarning "Downloaded #{@combinedWaypoints.length} waypoints, but only #{waypointsExtracted} parsed!"
end
#puts ""
return waypointsExtracted
end
def prepareFilter
# Prepare for the manipulation
@filtered = Filter.new(@combinedWaypoints)
if @option['notFoundByMe']
@appliedFilters['-N'] = { 'f' => "", 't' => "not done by #{@option['user']}" }
end
# This is where we do a little bit of cheating. In order to avoid downloading the
# cache details for each cache to see if it's been visited, we do a search for the
# users on the include or exclude list. We then populate @combinedWaypoints[wid]['visitors']
# with our discovery.
userLookups = Array.new
if @option['userExclude'] and not @option['userExclude'].empty?
@appliedFilters['-E'] = { 'f' => "#{@option['userExclude']}", 't' => "not done by" }
userLookups = @option['userExclude'].split($delimiters)
end
if @option['userInclude'] and not @option['userInclude'].empty?
@appliedFilters['-e'] = { 'f' => "#{@option['userInclude']}", 't' => "done by" }
userLookups = userLookups + @option['userInclude'].split($delimiters)
end
userLookups.each{ |user|
# issue 236: if "user" is file, read that
if (user =~ /(.*)=(.*)/)
username = $1
filename = $2
#puts ""
displayMessage "Read #{filename} for #{username}"
counter = 0
# read file (1st column)
begin
File.foreach(filename){ |line|
if (line =~ /^(GC\w+)/i)
wid = $1
debug2 "Add #{wid} for #{username}"
@filtered.addVisitor(wid, username)
counter = counter + 1
end
}
displayInfo "Total of #{counter} WIDs read"
rescue
displayWarning "Problems reading #{filename} for #{username}"
end
else
search = SearchCache.new
search.setType('user', user)
waypoints = search.getResults()
waypoints.keys.each{ |wid|
@filtered.addVisitor(wid, user)
}
end
}
end
def showRemoved(count, text)
if (count > 0)
text10 = text.ljust(10)
displayMessage "#{text10} filtering removed #{caches(count)}."
end
end
## step #1 in filtering! ############################
# This step filters out all the geocaches by information
# found from the searches.
def preFetchFilter
#puts ""
@filtered = Filter.new(@combinedWaypoints)
debug "Filter running cycle 1, #{caches(@filtered.totalWaypoints)} left."
beforeFilterTotal = @filtered.totalWaypoints
if @option['cacheType']
# post-filter by cacheType
@appliedFilters['-c'] = { 'f' => "#{@option['cacheType']}", 't' => "type" }
if @option['cacheType'] !~ /\+$/
# but only if there's no "all xxx" chosen
@filtered.cacheType(@option['cacheType'])
else
displayWarning "Not filtering for cache type!"
end
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Cache type")
# exclude Premium Member Only caches on request
beforeFilterTotal = @filtered.totalWaypoints
if @option['noPMO']
@filtered.removeByElement('membersonly')
end
# may not be accurate before fetching details?
if @option['onlyPMO']
@filtered.removeByElement('membersonly', false)
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "PM-Only")
if $DTSFILTER
#-------------------
beforeFilterTotal = @filtered.totalWaypoints
if @option['difficultyMin']
@appliedFilters['-d'] = { 'f' => "#{@option['difficultyMin']}", 't' => "difficulty min" }
@filtered.difficultyMin(@option['difficultyMin'].to_f)
end
if @option['difficultyMax']
@appliedFilters['-D'] = { 'f' => "#{@option['difficultyMax']}", 't' => "difficulty max" }
@filtered.difficultyMax(@option['difficultyMax'].to_f)
end
if @option['terrainMin']
@appliedFilters['-t'] = { 'f' => "#{@option['terrainMin']}", 't' => "terrain min" }
@filtered.terrainMin(@option['terrainMin'].to_f)
end
if @option['terrainMax']
@appliedFilters['-T'] = { 'f' => "#{@option['terrainMax']}", 't' => "terrain max" }
@filtered.terrainMax(@option['terrainMax'].to_f)
end
if @option['sizeMin']
@appliedFilters['-s'] = { 'f' => "#{@option['sizeMin']}", 't' => "size min" }
@filtered.sizeMin(@option['sizeMin'])
end
if @option['sizeMax']
@appliedFilters['-S'] = { 'f' => "#{@option['sizeMax']}", 't' => "size max" }
@filtered.sizeMax(@option['sizeMax'])
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "D/T/Size")
#-------------------
end # $DTSFILTER
debug "Filter running cycle 2, #{caches(@filtered.totalWaypoints)} left."
beforeFilterTotal = @filtered.totalWaypoints
if @option['foundDateInclude']
@appliedFilters['-r'] = { 'f' => "#{@option['foundDateInclude']}", 't' => "found age max" }
@filtered.foundDateInclude(@option['foundDateInclude'].to_f)
end
if @option['foundDateExclude']
@appliedFilters['-R'] = { 'f' => "#{@option['foundDateExclude']}", 't' => "found age min" }
@filtered.foundDateExclude(@option['foundDateExclude'].to_f)
end
if @option['placeDateInclude']
@appliedFilters['-j'] = { 'f' => "#{@option['placeDateInclude']}", 't' => "cache age max" }
@filtered.placeDateInclude(@option['placeDateInclude'].to_f)
end
if @option['placeDateExclude']
@appliedFilters['-J'] = { 'f' => "#{@option['placeDateExclude']}", 't' => "cache age min" }
@filtered.placeDateExclude(@option['placeDateExclude'].to_f)
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Date")
debug "Filter running cycle 3, #{caches(@filtered.totalWaypoints)} left."
beforeFilterTotal = @filtered.totalWaypoints
if @option['notFound']
@appliedFilters['-n'] = { 'f' => "", 't' => "virgins" }
@filtered.notFound
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Unfound")
beforeFilterTotal = @filtered.totalWaypoints
if @option['travelBug']
@appliedFilters['-b'] = { 'f' => "", 't' => "trackables" }
@filtered.travelBug
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Trackable")
beforeFilterTotal = @filtered.totalWaypoints
if (@option['ownerExclude'])
@appliedFilters['-I'] = { 'f' => "#{@option['ownerExclude']}", 't' => "not owned by" }
@option['ownerExclude'].split($delimiters).each{ |owner|
@filtered.ownerExclude(owner)
}
end
if (@option['ownerInclude'])
@appliedFilters['-i'] = { 'f' => "#{@option['ownerInclude']}", 't' => "owned by" }
@option['ownerInclude'].split($delimiters).each{ |owner|
@filtered.ownerInclude(owner)
}
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Owner")
beforeFilterTotal = @filtered.totalWaypoints
if (@option['userExclude'])
@appliedFilters['-E'] = { 'f' => "#{@option['userExclude']}", 't' => "not done by" }
@option['userExclude'].split($delimiters).each{ |user|
@filtered.userExclude(user)
}
end
if (@option['userInclude'])
@appliedFilters['-e'] = { 'f' => "#{@option['userInclude']}", 't' => "done by" }
@option['userInclude'].split($delimiters).each{ |user|
@filtered.userInclude(user)
}
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "User")
beforeFilterTotal = @filtered.totalWaypoints
if @option['titleKeyword']
@appliedFilters['-k'] = { 'f' => "#{@option['titleKeyword']}", 't' => "matching title keyword" }
@filtered.titleKeyword(@option['titleKeyword'])
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Title")
displayMessage "Pre-fetch filter complete, #{caches(@filtered.totalWaypoints)} left."
end
def copyGeocaches
# don't load details, just copy from search results
wpFiltered = @filtered.waypoints
@detail = CacheDetails.new(wpFiltered)
end
def fetchGeocaches
#puts ""
if $membership
displayMessage "Fetching geocache pages as \"#{$membership}\""
else
displayMessage "Fetching geocache pages"
end
wpFiltered = @filtered.waypoints
progress = ProgressBar.new(0, @filtered.totalWaypoints, "")
@detail = CacheDetails.new(wpFiltered)
@detail.preserve = @preserveCache
token = 0
wpFiltered.each_key{ |wid|
token = token + 1
detailURL = @detail.fullURL(wid)
page = ShadowFetch.new(detailURL)
status = @detail.fetch(wid)
message = nil
if status == 'login-required'
displayMessage "Cookie does not appear to be valid, logging in as #{@option['user']}"
@detail.cookie = login(@option['user'], @option['password'])
status = @detail.fetch(wid)
end
message = ""
warning = wpFiltered[wid]['warning']
keepdata = true
# status is hash; false/nil/empty or string if problem
if ! status #status.to_s.empty?
message << "[W:\"#{warning}\"]"
keepdata = false
elsif status.class != Hash
debug "Could not parse page, S:#{status}, W:#{warning}"
if status == 'unpublished'
message << "(unpublished)"
keepdata = false
elsif status == 'login-required'
message << "[PMO? \"#{status}\"]"
keepdata = false
elsif status == 'subscriber-only'
message << "[PMO] \"#{warning}\""
keepdata = true
elsif status == 'no-coords'
message << "[PMO? \"#{status}\"]"
keepdata = true
else # unknown status?
message << "[??? \"#{status}\"]"
keepdata = false
end
else
if (wpFiltered[wid]['membersonly'])
message << "[PMO]"
elsif (warning)
message << "[W:\"#{warning}\"]"
end
end
# archived/disabled
if (wpFiltered[wid]['archived'])
message << "[%]"
elsif (wpFiltered[wid]['disabled'])
message << "[?]"
end
name = wpFiltered[wid]['name']
# remove HTML cruft from name, may fail in rare cases (emoji)
begin
temp = CGI::unescapeHTML(name)
rescue
temp = name.gsub(/\&/, '+')
end
name = temp
message << (keepdata ? "" : "(del)")
progress.updateText(token, "[#{wid}]".ljust(9)+" \"#{name}\" (#{page.src.gsub(/(\w)\w*/){$1}}) #{message}")
if ! keepdata
debug "Page for #{wid} \"#{wpFiltered[wid]['name']}\" failed to be parsed, invalidating cache."
wpFiltered.delete(wid)
page.invalidate()
end
}
end
## step #2 in filtering! ############################
# In this stage, we actually have to download all the information on the caches in order to decide
# whether or not they are keepers.
def postFetchFilter
#puts ""
@filtered= Filter.new(@detail.waypoints)
# caches with warnings we choose not to include.
beforeFilterTotal = @filtered.totalWaypoints
if @option['includeArchived']
@appliedFilters['--includeArchived'] = { 'f' => "", 't' => "also archived" }
else
# this would cause too much noise, don't advertise
#@appliedFilters['--excludeArchived'] = { 'f' => "", 't' => "not archived" }
@filtered.removeByElement('archived')
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Archived")
#
beforeFilterTotal = @filtered.totalWaypoints
if @option['includeDisabled']
@appliedFilters['-z'] = { 'f' => "", 't' => "also disabled" }
else
@appliedFilters['+z'] = { 'f' => "", 't' => "not disabled" }
@filtered.removeByElement('disabled')
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Disabled")
# exclude Premium Member Only caches on request
beforeFilterTotal = @filtered.totalWaypoints
if @option['noPMO']
@appliedFilters['-O'] = { 'f' => "", 't' => "no PMO" }
@filtered.removeByElement('membersonly')
end
if @option['onlyPMO']
@appliedFilters['-Q'] = { 'f' => "", 't' => "PMO" }
@filtered.removeByElement('membersonly', false)
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "PM-Only")
beforeFilterTotal = @filtered.totalWaypoints
if @option['descKeyword']
@appliedFilters['-K'] = { 'f' => "#{@option['descKeyword']}", 't' => "matching descr. keyword" }
@filtered.descKeyword(@option['descKeyword'])
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Keyword")
##if not $DTSFILTER
#-------------------
beforeFilterTotal = @filtered.totalWaypoints
if @option['difficultyMin']
@appliedFilters['-d'] = { 'f' => "#{@option['difficultyMin']}", 't' => "difficulty min" }
@filtered.difficultyMin(@option['difficultyMin'].to_f)
end
if @option['difficultyMax']
@appliedFilters['-D'] = { 'f' => "#{@option['difficultyMax']}", 't' => "difficulty max" }
@filtered.difficultyMax(@option['difficultyMax'].to_f)
end
if @option['terrainMin']
@appliedFilters['-t'] = { 'f' => "#{@option['terrainMin']}", 't' => "terrain min" }
@filtered.terrainMin(@option['terrainMin'].to_f)
end
if @option['terrainMax']
@appliedFilters['-T'] = { 'f' => "#{@option['terrainMax']}", 't' => "terrain max" }
@filtered.terrainMax(@option['terrainMax'].to_f)
end
if @option['sizeMin']
@appliedFilters['-s'] = { 'f' => "#{@option['sizeMin']}", 't' => "size min" }
@filtered.sizeMin(@option['sizeMin'])
end
if @option['sizeMax']
@appliedFilters['-S'] = { 'f' => "#{@option['sizeMax']}", 't' => "size max" }
@filtered.sizeMax(@option['sizeMax'])
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "D/T/Size")
#-------------------
##end # not $DTSFILTER
beforeFilterTotal = @filtered.totalWaypoints
if @option['favFactorMin']
@appliedFilters['-g'] = { 'f' => "#{@option['favFactorMin']}", 't' => "favFactor min" }
@filtered.favFactorMin(@option['favFactorMin'].to_f)
end
if @option['favFactorMax']
@appliedFilters['-G'] = { 'f' => "#{@option['favFactorMax']}", 't' => "favFactor max" }
@filtered.favFactorMax(@option['favFactorMax'].to_f)
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "FavFactor")
# We filter for users again. While this may be a bit obsessive, this is in case
# our local cache is not valid.
beforeFilterTotal = @filtered.totalWaypoints
if (@option['userExclude'])
@appliedFilters['-E'] = { 'f' => "#{@option['userExclude']}", 't' => "not done by" }
@option['userExclude'].split($delimiters).each{ |user|
@filtered.userExclude(user)
}
end
if (@option['userInclude'])
@appliedFilters['-e'] = { 'f' => "#{@option['userInclude']}", 't' => "done by" }
@option['userInclude'].split($delimiters).each{ |user|
@filtered.userInclude(user)
}
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "User")
beforeFilterTotal = @filtered.totalWaypoints
if (@option['attributeExclude'])
@appliedFilters['-A'] = { 'f' => "#{@option['attributeExclude']}", 't' => "attr no" }
@option['attributeExclude'].split($delimiters).each{ |attribute|
@filtered.attributeExclude(attribute)
}
end
if (@option['attributeInclude'])
@appliedFilters['-a'] = { 'f' => "#{@option['attributeExclude']}", 't' => "attr yes" }
@option['attributeInclude'].split($delimiters).each{ |attribute|
@filtered.attributeInclude(attribute)
}
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Attribute")
beforeFilterTotal = @filtered.totalWaypoints
if (@option['minLongitude'])
@appliedFilters['--minLon'] = { 'f' => "#{@option['minLongitude']}", 't' => "West" }
@filtered.longMin(@option['minLongitude'])
end
if (@option['maxLongitude'])
@appliedFilters['--maxLon'] = { 'f' => "#{@option['maxLongitude']}", 't' => "East" }
@filtered.longMax(@option['maxLongitude'])
end
if (@option['minLatitude'])
@appliedFilters['--minLat'] = { 'f' => "#{@option['minLatitude']}", 't' => "South" }
@filtered.latMin(@option['minLatitude'])
end
if (@option['maxLatitude'])
@appliedFilters['--maxLat'] = { 'f' => "#{@option['maxLatitude']}", 't' => "North" }
@filtered.latMax(@option['maxLatitude'])
end
excludedFilterTotal = beforeFilterTotal - @filtered.totalWaypoints
showRemoved(excludedFilterTotal, "Lat/Lon")
displayMessage "Post-fetch filter complete, #{caches(@filtered.totalWaypoints)} left."
return @filtered.totalWaypoints
end
## save the file #############################################
def saveFile
#puts ""
formatTypeCounter = 0
# @appliedFilters: sort by option letter, ignore case
debug3 "appliedFilters: #{@appliedFilters.inspect}"
queryTitleAdd = @appliedFilters.sort{ |a,b|
a.join.upcase <=> b.join.upcase
}.map{ |k,v|
v['t'] + (v['f'].empty? ? "": " #{v['f']}")
}.join(', ')
debug "title+ #{queryTitleAdd}"
@queryTitle << '; ' + queryTitleAdd
defaultOutputFileAdd = @appliedFilters.sort{ |a,b|
a.join.upcase <=> b.join.upcase
}.map{ |k,v|
(k =~ /^-/) ? "#{k}#{v['f']}" : ""
}.join
debug "fname+ #{defaultOutputFileAdd}"
@defaultOutputFile << defaultOutputFileAdd
# 'output' may be a directory, with or without trailing slash (should exist)
# if there's nil or empty (no path at all), use current working directory
# or the filename for the first output file, explicitly given
if ! @option['output'].to_s.empty?
filename = @option['output'].dup
else
filename = Dir.pwd
end
filename.gsub!('\\', '/')
# if it's a directory, append a slash just in case
if File.directory?(filename)
filename = File.join(filename, '')
end
message = "Pattern: #{filename}"
# we can now check for a trailing slash safely
if filename =~ /\/$/
# automatic mode
outputDir = filename
outputFileBase = nil
message << " (automatic)"
# flag as automatic for suffixing
@option['output'] = nil
outputFileBase = @defaultOutputFile.gsub(/[^0-9A-Za-z\.-]/, '_')
outputFileBase.gsub!(/_+/, '_')
# shorten at a somewhat randomly chosen place to fit in filesystem
if outputFileBase.length > 220
outputFileBase = outputFileBase[0..215] + "_etc"
end
else
outputFileBase = File.basename(filename)
#
outputDir = File.dirname(filename + 'x')
end
displayInfo message
debug "Using output #{outputDir}/#{outputFileBase}"
# loop over all chosen formats
@formatTypes.split($delimiters).each{ |formatType0|
# does the formatType string contain a "="?
formatType = formatType0.split(/=/)[0]
if ! $validFormats.include?(formatType)
displayWarning "#{formatType} is not a valid supported format - skipping."
next
end
output = Output.new
displayInfo "Format: #{output.formatDesc(formatType)} (#{formatType})"
output.input(@filtered.waypoints)
output.formatType = formatType
if (@option['waypointLength'])
output.waypointLength=@option['waypointLength'].to_i
end
if (@option['logCount'])
output.commentLimit=@option['logCount'].to_i
end
# keep filename if first run and not automatic
# strip suffix only on subsequent runs
if (formatTypeCounter > 0)
outputFileBase.gsub!(/\.[^\.]*$/, '')
end
# append suffix if automatic or subsequent runs
if (not @option['output']) || (formatTypeCounter > 0)
outputFileExt = output.formatExtension(formatType)