-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.rb
More file actions
2767 lines (2225 loc) · 73.2 KB
/
app.rb
File metadata and controls
2767 lines (2225 loc) · 73.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'bundler/setup'
require 'sinatra'
require 'sinatra/reloader' if development?
require 'rack/attack'
require_relative './lib/abuse_middleware'
require_relative './boot'
disable :protection
set :host_authorization, { permitted_hosts: [] }
authenticated_request = lambda do |req|
begin
cookies = Rack::Utils.parse_cookies(req.env)
return true if cookies['rack.session']
auth_header = req.env['HTTP_AUTHORIZATION'].to_s
return false if auth_header.empty?
token_string = auth_header.sub(/\ABearer\s+/i, '').strip
return false if token_string.empty?
api_token = Tables::ApiToken.find_by_raw_token(token_string)
api_token && !api_token.expired?
rescue StandardError
false
end
end
use Rack::Attack
use Rack::AbuseMiddleware,
redis: REDIS,
limit: 30,
window: 120,
block_time: 3600,
skip_if: authenticated_request
Rack::Attack.cache.store = ActiveSupport::Cache::RedisCacheStore.new(redis: REDIS)
# Rate limit all logged-out requests by IP (mostly to slow down crawlers)
# Note: Rack::Attack runs before Sinatra's session middleware, so we check
# for the session cookie to determine if a user is likely logged in.
Rack::Attack.throttle('req/ip', limit: 60, period: 60) do |req|
unless req.path.start_with?('/images/', '/js/', '/station/') || req.path.end_with?('.css', '.js', '.png', '.ico')
req.ip unless authenticated_request.call(req)
end
end
# Rate limit login endpoints by IP
Rack::Attack.throttle('login/ip', limit: 5, period: 15.minutes) do |req|
req.ip if (req.path == '/login' || req.path == '/api/auth/login') && req.post?
end
# Rate limit login endpoints by call sign
Rack::Attack.throttle('login/call_sign', limit: 5, period: 15.minutes) do |req|
if req.post?
if req.path == '/login'
req.params['call_sign'].to_s.strip.downcase.presence
elsif req.path == '/api/auth/login'
body = req.env['rack.input'].read
req.env['rack.input'] = StringIO.new(body)
begin
JSON.parse(body)['call_sign'].to_s.strip.downcase.presence
rescue JSON::ParserError
nil
end
end
end
end
Rack::Attack.throttled_responder = lambda do |request|
match_data = request.env['rack.attack.match_data'] || {}
retry_after = (match_data[:period] || 60) - (Time.now.to_i % (match_data[:period] || 60))
message = 'Too many requests. Please slow down.'
headers = { 'retry-after' => retry_after.to_s }
if request.env['HTTP_AUTHORIZATION'] || request.env['HTTP_ACCEPT']&.include?('application/json')
headers['content-type'] = 'application/json'
[429, headers, [{ error: message }.to_json]]
else
headers['content-type'] = 'text/html'
[429, headers, ["<html><body><h1>#{message}</h1></body></html>"]]
end
end
enable :sessions
set :session_secret, ENV.fetch('SESSION_SECRET') { SecureRandom.hex(64) }
set :sessions, same_site: :lax, expire_after: 365 * 24 * 60 * 60 # 1 year
set :static_cache_control, [:public, max_age: 60]
set :bind, '0.0.0.0'
CREATE_NET_REQUIRED_PARAMS = {
club_id: {},
net_name: { length: 32, format: /\A[A-Za-z0-9][A-Za-z0-9 \(\)-]*\z/, message: 'Net name must contain only letters, numbers, spaces, parentheses, and/or hyphens, and must start with a letter or number.' },
net_password: { length: 20 },
frequency: { length: 16 },
band: { length: 10 },
mode: { length: 10 },
net_control: { length: 20 },
}
if development?
Dir['./lib/**/*.rb'].each do |path|
also_reload(path)
end
end
before do
is_app_domain = request.host == 'ragchew.app' ||
request.host == 'www.ragchew.app' ||
params[:domain] == 'ragchew.app'
if is_app_domain
if request.path == '/'
halt erb(:app_landing, layout: false)
else
redirect "https://ragchew.site#{request.fullpath}", 302
return
end
end
end
before do
@user = get_user
touch_user_activity!(@user) if @user
if @user
headers['X-RagChew-User'] = @user.call_sign
headers['X-RagChew-Role'] = @user.admin? ? 'admin' : 'user'
end
@theme = request.env['HTTP_X_RAGCHEW_THEME'] || @user&.theme
@for_mobile = request.env['HTTP_X_RAGCHEW_UI'] == 'mobile'
end
helpers do
def nav
if @user
links = [
"<a href='/user'>#{erb "<%== @user.call_sign %>"}</a>",
"<a href='/favorites'>favorites</a>",
@user.admin? ? "<a href='/admin'>admin</a>" : nil,
(!@user.logging_net && !@user.net_creation_blocked?) ? "<a href='/create-net'>create net</a>" : nil,
"<a href='/logout' data-method='post'>log out</a>"
].compact
else
links = [
"<a href='/login'>log in</a>"
]
end
if @user&.logging_net && @net != @user.logging_net
links << "logging: <a href='/net/#{url_escape @user.logging_net.name}' class='warning'>#{erb "<%== @user.logging_net.name %>"}</a>"
end
erb :_nav, locals: { links: }
end
def format_time(ts, time_only: false)
return '' unless ts
"<span class='time #{time_only ? 'time-only' : ''}' title='#{distance_of_time_in_words(ts, Time.now)} ago' data-time='#{ts.strftime('%Y-%m-%dT%H:%M:%S.000Z')}'>#{ts.strftime('%Y-%m-%d %H:%M:%S UTC')}</span>"
end
def url_escape(s)
CGI.escape(s.to_s)
end
def canonical_net_path(canonical_net)
"/net/#{url_escape(canonical_net.canonical_name)}"
end
def make_url_safe_for_html_attribute(s)
s.to_s.gsub('"', '%22')
end
def make_value_safe_for_html_attribute(s)
s.to_s.gsub('"', '"')
end
def pretty_url(url)
url.sub(/^https?:\/\//, '').sub(/\/$/, '')
end
def development?
ENV['RACK_ENV'] == 'development'
end
def pluralize(word, count)
if count == 1
word
else
"#{word}s"
end
end
def club_logo_image_tag(club, class_name: nil)
return unless club&.logo_url.present?
"<a href=\"/group/#{url_escape(club.name)}\">" \
"<img class='club-logo #{class_name}'" \
"src=\"#{make_url_safe_for_html_attribute(club.logo_url)}\"/>" \
'</a>'
end
def is_admin?
@user&.admin?
end
def has_net_logger_role?
@user&.net_logger?
end
def json_for_html_attribute(hash)
hash.to_json.gsub('&', '&').gsub('"', '"')
end
def script_tag(filename)
ts = File.stat(File.join('public', filename)).mtime.to_i
"<script type=\"module\" src=\"/#{filename}?_ts=#{ts}\"></script>"
end
def style_tag(filename)
ts = File.stat(File.join('public', filename)).mtime.to_i
"<link rel=\"stylesheet\" href=\"/#{filename}?_ts=#{ts}\"/>"
end
def canonical_name_order_sql(table_name)
Arel.sql("LOWER(COALESCE(canonical_nets.canonical_name, #{table_name}.name))")
end
def pusher_url
@pusher_url ||= URI.parse(ENV.fetch('PUSHER_URL'))
end
def pusher_key = pusher_url.user
def pusher_cluster
@pusher_cluster ||= pusher_url.host.split('.').first.split('-').last
end
def club_noun
if @club && @club.full_name.to_s =~ /club/i
'club'
else
'group'
end
end
def hours_in_range(range)
return to_enum(__method__, range) unless block_given?
t = range.begin.beginning_of_hour
while t < range.end
yield t
t += 1.hour
end
end
def dates_in_range(range)
return to_enum(__method__, range) unless block_given?
t = range.begin.beginning_of_day
while t < range.end
yield t
t = (t + 1.day).beginning_of_day
end
end
def weeks_in_range(range)
return to_enum(__method__, range) unless block_given?
t = range.begin.beginning_of_week
while t < range.end
yield t
t = (t + 1.week).beginning_of_week
end
end
def stat_values_by_week(weeks, names)
names = Array(names)
records = Tables::Stat.where(name: names, period: weeks).to_a.index_by do |record|
[record.period, record.name]
end
weeks.map do |week|
period = week.beginning_of_week
value = nil
names.each do |name|
record = records[[period, name]]
if record
value = record.value
break
end
end
value || 0
end
end
def active_user_count(column_name, since:)
Tables::User.where("#{column_name} > ?", since).count
end
def touch_timestamp!(record, column_name, now: Time.now)
current_value = record.public_send(column_name)
return if current_value && now - current_value < 20.minutes
record.update!(column_name => now)
end
def touch_user_activity!(user, now: Time.now)
case request.env['ragchew.auth_type']
when 'bearer'
touch_timestamp!(user, :last_mobile_active_at, now:)
when 'session'
touch_timestamp!(user, :last_web_active_at, now:)
end
end
def sort_heading(column, label, other_attributes = [])
query = other_attributes.map do |attr|
"#{attr}=#{url_escape params[attr]}"
end.join('&')
direction = params[:sort].to_s =~ /^#{column}(?! desc)/ ? 'desc' : 'asc'
if params[:sort].to_s.start_with?(column)
arrow = direction == 'asc' ? '↑' : '↓'
end
"<a href=\"?#{query}&sort=#{column} #{direction}\">#{label}</a> #{arrow}"
end
def admin_table_klass(table_name)
Tables.const_get(table_name.classify)
rescue NameError
halt 404, 'table not found'
end
def admin_table_attributes_from_params(klass, raw_attributes)
columns = klass.columns.index_by(&:name)
raw_attributes.to_h.each_with_object({}) do |(name, raw_value), attrs|
next unless columns.key?(name)
column = columns[name]
value = raw_value
value = nil if value == '' && ![:string, :text].include?(column.type)
attrs[name] = klass.type_for_attribute(name).cast(value)
end
end
end
include DOTIW::Methods
ENV['TZ'] = 'UTC'
MAX_FAVORITES = 50
BASE_URL = ENV['BASE_URL'] || 'https://ragchew.site'
SUPPORT_EMAIL = ENV['SUPPORT_EMAIL'] || 'tim@timmorgan.org'
ONE_PIXEL_IMAGE = File.read(File.expand_path('./public/images/1x1.png', __dir__))
get '/.well-known/apple-app-site-association' do
content_type 'application/json'
'{"webcredentials":{"apps":["U244D4WPSF.org.timmorgan.ragchewapp"]}}'
end
get '/' do
@homepage = true
frequency_order_cast = Arel.sql('CAST(frequency AS DOUBLE)')
band_order_cast = Arel.sql("CAST(REPLACE(REPLACE(band, '70cm', '0'), 'm', '') AS UNSIGNED)")
order = case params[:order]
when 'name', nil
{ canonical_name_order_sql('nets') => :asc }
when 'frequency'
{ frequency_order_cast => :asc }
when 'mode,frequency'
{ mode: :asc, frequency_order_cast => :asc }
when 'band,frequency'
{ band_order_cast => :asc, frequency_order_cast => :asc }
when 'started_at'
{ started_at: :desc }
end
service = NetList.new
@nets = service.list(order:)
@last_updated_at = Tables::Server.maximum(:net_list_fetched_at)
@update_interval = 30
@update_backoff = 5
@centers = net_centers(@nets)
erb :index
end
get '/api/user' do
content_type 'application/json'
{ user: @user }.to_json
end
get '/api/nets' do
content_type 'application/json'
service = NetList.new
nets = service.list(order: { canonical_name_order_sql('nets') => :asc })
centers = net_centers(nets)
{
nets:,
centers:,
}.to_json
end
get '/about' do
erb :about
end
get '/support' do
@page_title = 'Support'
erb :support
end
get '/privacy' do
@page_title = 'Privacy Policy'
erb :privacy
end
get '/net/:name' do
params[:name] = CGI.unescape(params[:name])
@canonical_net = CanonicalNetResolver.resolve(params[:name])
service = NetInfo.new(name: params[:name])
service.update!
@net = service.net
@canonical_net ||= @net.canonical_net
@page_title = @canonical_net&.canonical_name || @net.name
if @user&.monitoring_net == @net
@user.update!(monitoring_net_last_refreshed_at: Time.now)
end
if @user
@is_logger = @user.logging_net == @net
@messages = @net.messages.order(:sent_at).to_a
@monitors = @net.monitors.order(:call_sign).to_a
@favorites = @user.favorites.pluck(:call_sign)
@favorited_net = @user.favorite_nets.where(canonical_net_id: @canonical_net&.id).any?
@blocked_stations = @user.blocked_stations.pluck(:call_sign)
@net_blocked_stations = @is_logger ? @net.blocked_stations.pluck(:call_sign) : []
@last_updated_at = @net.fully_updated_at
@update_interval = @net.update_interval_in_seconds + 1
erb :net
else
@is_logger = false
@checkin_count = @net.checkins.count
@message_count = @net.messages.count
@monitor_count = @net.monitors.count
erb :net_limited
end
rescue NetInfo::NotFoundError
@net_count = Tables::Net.count
if Tables::BlockedNet.blocked?(params[:name])
@name = nil
else
@canonical_net = CanonicalNetResolver.resolve(params[:name])
@closed_net = if @canonical_net
@canonical_net.representative_closed_net
else
Tables::ClosedNet.where(name: params[:name]).order(started_at: :desc).first
end
@page_title = @name = @canonical_net&.canonical_name || @closed_net&.name
end
if @closed_net
@canonical_net ||= @closed_net.canonical_net
@favorited_net = @user.favorite_nets.where(canonical_net_id: @canonical_net&.id).any? if @user
@checkin_count = @closed_net.checkin_count
@message_count = @closed_net.message_count
@monitor_count = @closed_net.monitor_count
if request.xhr?
# force JS to reload page
status 404
'net is closed'
else
erb :closed_net
end
else
status 404
erb :missing_net
end
end
get '/api/net_id/:name' do
content_type 'application/json'
params[:name] = CGI.unescape(params[:name])
canonical_net = CanonicalNetResolver.resolve(params[:name])
if (net = canonical_net&.representative_active_net)
{ id: net.id, canonicalNetId: canonical_net.id }.to_json
else
status 404
if canonical_net && (closed_net = canonical_net.representative_closed_net)
{ error: "net closed", closedNetId: closed_net.id, canonicalNetId: canonical_net.id }.to_json
else
{ error: "not found" }.to_json
end
end
end
get '/api/net/:id/details' do
content_type 'application/json'
service = NetInfo.new(id: params[:id])
service.update!
net = service.net
checkins = net.checkins.order(:num).to_a
coords = checkins.filter_map do |checkin|
lat, lon = GridSquare.new(checkin.grid_square).to_a
if lat && lon
{ lat:, lon:, callSign: checkin.call_sign, name: checkin.name }
end
end
messagesCount = net.messages.count
monitors = net.monitors.order(:call_sign).to_a
unless @user
if net.show_circle?
circle = {
latitude: net.center_latitude,
longitude: net.center_longitude,
radius: net.center_radius
}
end
return {
net:,
checkinCount: checkins.size,
messagesCount:,
monitorCount: monitors.size,
circle:
}.to_json
end
monitoring_this_net = @user.monitoring_net == net
if monitoring_this_net
@user.update!(monitoring_net_last_refreshed_at: Time.now)
end
messages = monitoring_this_net ? net.messages.includes(:message_reactions).order(:sent_at).to_a : []
messages.reject! { |m| m.blocked? && m.call_sign.upcase != @user.call_sign.upcase }
favorites = @user.favorites.pluck(:call_sign)
favorited_net = @user.favorite_nets.where(canonical_net_id: net.canonical_net_id).any?
{
net:,
canonicalNet: net.canonical_net,
checkins:,
coords:,
messages: messages.as_json(include_reactions: true),
messagesCount:,
monitors:,
favorites:,
favoritedNet: favorited_net,
lastUpdatedAt: net.updated_at.rfc3339,
monitoringThisNet: monitoring_this_net,
timeFormat: @user.time_format,
}.to_json
rescue NetInfo::NotFoundError
status 404
content_type 'application/json'
{ error: 'net not found' }.to_json
end
get '/net/:id/log' do
require_user!
service = NetInfo.new(id: params[:id])
content_type 'text/plain'
attachment "#{service.net.name}.log"
service.to_log
rescue NetInfo::NotFoundError
status 404
erb :missing_net
end
get '/create-net' do
require_user!
if @user.net_creation_blocked?
status 403
return "Net creation is unavailable."
end
check_if_already_started_a_net!(@user)
@my_clubs = @user.clubs
erb :create_net
end
post '/api/create-net' do
content_type 'application/json'
payload = params.merge(JSON.parse(request.body.read)).transform_keys(&:to_sym)
ragchew_only_testing_net = payload[:ragchew_only_testing_net] == true || payload[:ragchew_only_testing_net] == 'true'
if ragchew_only_testing_net && !is_admin?
status 401
return { error: 'not authorized' }.to_json
end
require_net_logger_role! unless ragchew_only_testing_net
if @user.net_creation_blocked?
status 403
return { error: "Net creation is unavailable." }.to_json
end
check_if_already_started_a_net!(@user)
missing = CREATE_NET_REQUIRED_PARAMS.keys.reject do |param|
payload[param].present?
end
if missing.any?
status 400
return { error: "Some required fields are missing: #{missing.join(', ')}.", fields: missing }.to_json
end
club = nil
if payload[:club_id].present? && payload[:club_id] != 'no_club'
club = Tables::Club.find(payload[:club_id])
unless club.club_members.where(user_id: @user.id).any?
status 400
return { error: 'You are not a member of this club.' }.to_json
end
end
CREATE_NET_REQUIRED_PARAMS.each do |param, requirements|
next unless (length = requirements[:length])
if payload[param].size > length
status 400
return { error: "#{param} is too long.", fields: [param] }.to_json
end
end
CREATE_NET_REQUIRED_PARAMS.each do |param, requirements|
next unless (format = requirements[:format])
if payload[param] !~ format
status 400
return { error: "#{param} contains characters not allowed.", fields: [param] }.to_json
end
end
if Tables::Net.where(name: payload[:net_name]).exists?
status 400
return { error: 'A net with this name is already in progress.', fields: [:net_name] }.to_json
end
NetInfo.create!(
ragchew_only_testing_net:,
club:,
name: payload[:net_name],
password: payload[:net_password],
frequency: payload[:frequency],
net_control: payload[:net_control],
user: @user,
mode: payload[:mode],
band: payload[:band],
blocked_stations: payload[:blocked_stations],
)
NetInfo.new(name: payload[:net_name]).monitor!(user: @user)
redirect "/net/#{url_escape payload[:net_name]}"
end
post '/start-logging/:id' do
require_net_logger_role!
if @user.logging_net
halt 401, 'already logging a net'
end
net_service = NetInfo.new(id: params[:id])
@net = net_service.net
unless @user.can_log_for_club?(@net.club)
halt 401, 'not authorized'
end
net_service = NetInfo.start_logging!(id: @net.id, password: params[:net_password], user: @user)
redirect "/net/#{url_escape net_service.name}"
rescue NetInfo::PasswordIncorrectError
halt 401, 'incorrect password'
rescue NetInfo::NotFoundError
halt 404, 'net not found'
end
post '/stop-logging/:id' do
require_user!
@user.update!(logging_net: nil, logging_password: nil)
net_service = NetInfo.new(id: params[:id])
redirect "/net/#{url_escape net_service.name}"
rescue NetInfo::NotFoundError
redirect '/'
end
patch '/api/log/:id/:num' do
require_net_logger_role!
@params = params.merge(JSON.parse(request.body.read))
net_service = NetInfo.new(id: params[:id])
net_service.update_log_entry!(num: params.fetch(:num).to_i, params:, user: @user)
content_type 'application/json'
return { success: true }.to_json
rescue NetInfo::NotAuthorizedError
halt 401, 'not authorized'
end
delete '/api/log/:id/:num' do
require_net_logger_role!
net_service = NetInfo.new(id: params[:id])
net_service.delete_log_entry!(num: params.fetch(:num).to_i, user: @user)
content_type 'application/json'
return { success: true }.to_json
rescue NetInfo::NotAuthorizedError
halt 401, 'not authorized'
end
patch '/api/highlight/:id/:num' do
require_net_logger_role!
net_service = NetInfo.new(id: params[:id])
requested_num = params.fetch(:num).to_i
if net_service.current_highlight_num(user: @user) == requested_num
highlight_num = 0
else
highlight_num = requested_num
end
net_service.highlight!(num: highlight_num, user: @user)
content_type 'application/json'
return { success: true }.to_json
rescue NetInfo::NotAuthorizedError
halt 401, 'not authorized'
end
post '/close-net/:id' do
require_net_logger_role!
net_service = NetInfo.new(id: params[:id])
net_service.close!(user: @user)
@user.update!(
monitoring_net: nil,
monitoring_net_last_refreshed_at: nil,
logging_net: nil,
logging_password: nil,
)
redirect '/'
rescue NetInfo::NotAuthorizedError
halt 401, 'not authorized'
rescue NetInfo::CouldNotCloseError => e
halt 400, "there was an error closing this net: #{e.message}"
end
get '/closed-nets' do
params[:days] ||= '1'
scope = Tables::ClosedNet.left_outer_joins(:canonical_net).includes(:canonical_net)
if params[:days] != 'all'
start = params[:days].to_i.days.ago
if start > Time.new(2000, 1, 1, 0, 0)
scope = scope.where('started_at > ?', start)
end
end
sort_name, sort_direction = params[:sort].to_s.split(' ', 2)
sort_name = 'name' unless %w[name frequency band mode started_at].include?(sort_name)
sort_direction = 'asc' unless %w[asc desc].include?(sort_direction)
sort = {
(sort_name == 'name' ? canonical_name_order_sql('closed_nets') : sort_name) => sort_direction
}
if sort_name == 'started_at'
sort[canonical_name_order_sql('closed_nets')] = 'asc'
else
sort[:started_at] = 'asc'
end
params[:sort] = "#{sort_name} #{sort_direction}"
scope = scope.order(sort)
if params[:name].present?
scope = scope.where('closed_nets.name like :name or frequency like :name', { name: "%#{params[:name].gsub(/%/, '\%')}%" })
end
@closed_nets = scope
@total_days = ((Time.now - Tables::ClosedNet.order(:started_at).first.started_at) / 60 / 60 / 24).ceil
@total_count = @closed_nets.count
@closed_nets = @closed_nets.offset(params[:offset])
@per_page = 100
@more_pages = @total_count > @per_page
@closed_nets = @closed_nets.limit(@per_page)
@blocked_net_names = Tables::BlockedNet.pluck(:name)
erb :closed_nets
end
get '/api/closed-nets' do
content_type 'application/json'
params[:days] ||= '1'
scope = Tables::ClosedNet.left_outer_joins(:canonical_net).includes(:canonical_net)
if params[:days] != 'all'
start = params[:days].to_i.days.ago
if start > Time.new(2000, 1, 1, 0, 0)
scope = scope.where('started_at > ?', start)
end
end
sort_name, sort_direction = params[:sort].to_s.split(' ', 2)
sort_name = 'name' unless %w[name frequency band mode started_at].include?(sort_name)
sort_direction = 'asc' unless %w[asc desc].include?(sort_direction)
sort = {
(sort_name == 'name' ? canonical_name_order_sql('closed_nets') : sort_name) => sort_direction
}
if sort_name == 'started_at'
sort[canonical_name_order_sql('closed_nets')] = 'asc'
else
sort[:started_at] = 'asc'
end
scope = scope.order(sort)
if params[:name].present?
scope = scope.where('closed_nets.name like :name or frequency like :name', { name: "%#{params[:name].gsub(/%/, '\%')}%" })
end
total_count = scope.count
per_page = 100
scope = scope.offset(params[:offset]).limit(per_page)
{
closed_nets: scope,
total_count:,
per_page:,
}.to_json
end
get '/closed-net/:id' do
set_closed_net_details
@page_title = @name
erb :closed_net
rescue ActiveRecord::RecordNotFound
status 404
erb :missing_net
end
get '/api/closed-net/:id' do
set_closed_net_details
content_type 'application/json'
{
net: @closed_net.as_json(include: :club),
canonicalNet: @canonical_net,
checkinCount: @checkin_count,
messageCount: @message_count,
monitorCount: @monitor_count,
netCount: @net_count,
favoritedNet: @favorited_net,
moreRecentClosedNet: @more_recent_closed_net,
openNet: @open_net,
}.to_json
rescue ActiveRecord::RecordNotFound
status 404
{ error: 'not found' }.to_json
end
get '/groups' do
@clubs = Tables::Club.order_by_name.pluck(:name, :full_name)
erb :clubs
end
get '/api/groups' do
content_type 'application/json'
clubs = Tables::Club.order_by_name.to_a
groups = clubs.map do |club|
{
id: club.id,
name: club.name,
full_name: club.full_name,
website: club.about_url,
description: club.description,
logo_url: club.logo_url,
}
end
groups.to_json
end
get '/api/group/:id' do
content_type 'application/json'
club = Tables::Club.find(params[:id])
nets = club.canonical_nets.includes(:nets, :closed_nets).order(:canonical_name).filter_map do |canonical_net|
records = canonical_net.nets.to_a + canonical_net.closed_nets.to_a
next if records.empty?
record = records.max_by { |net| [net.started_at || Time.at(0), net.id] }
{
id: record.id,
name: canonical_net.canonical_name,
band: record.band,
mode: record.mode,
frequency: record.frequency,
}
end
{
club: club.as_json.merge(
slug: club.name,
website: club.about_url,
),
nets: nets,
}.to_json
rescue ActiveRecord::RecordNotFound
status 404
{ error: 'not found' }.to_json
end
get '/suggest-club' do
if @user
erb :suggest_club
else
erb "<p>Please <a href='/login'>log in</a> first.</p>"
end
end
post '/suggest-club' do
require_user!
Tables::SuggestedClub.create!(
name: params[:name],
full_name: params[:full_name],
website: params[:website],
description: params[:description],
nets: params[:nets],
suggested_by: @user.call_sign
)
redirect '/groups?suggested=1'
end
post '/join-group/:id' do
require_user!
@club = Tables::Club.find(params[:id])
@club.club_members.create!(user: @user)
redirect "/group/#{url_escape @club.name}"
end
post '/leave-group/:id' do
require_user!
@club = Tables::Club.find(params[:id])
@club.club_members.where(user_id: @user.id).delete_all
if params[:return] == '/user'
redirect '/user'
else
redirect "/group/#{url_escape @club.name}"
end
end
get '/api/station_search/:query' do
require_net_logger_role!
content_type 'application/json'
unless params[:club_id]
status 400
return { 'error' => 'must supply club_id' }.to_json
end
if params[:query].size < 2
status 400
return [].to_json
end
call_signs = Tables::ClubStation
.joins(:station)
.where(club_id: params[:club_id])
.where('club_stations.call_sign like :query or club_stations.preferred_name like :query or stations.first_name like :query or stations.last_name like :query', query: "%#{params[:query]}%")
.order(updated_at: :desc)
.limit(15)
.pluck(:call_sign)
Tables::Station.where(call_sign: call_signs).to_json
end