-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
1432 lines (1142 loc) · 33.6 KB
/
app.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
require 'bundler/setup'
require 'sinatra'
require 'sinatra/reloader' if development?
require_relative './boot'
disable :protection
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
helpers do
def nav
if @user
links = [
"<a href='/user'>#{erb "<%== @user.call_sign %>"}</a>",
@user.admin? ? "<a href='/admin'>admin</a>" : nil,
@user.net_logger? && !@user.logging_net ? "<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' : ''}' 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 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 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 stat_values_by_hour(hours, name)
records = Tables::Stat.where(name:, period: hours).to_a
hours.map do |hour|
records.detect { |r| r.period == hour }&.value || 0
end
end
def stat_values_by_date(dates, name)
records = Tables::Stat.where(name:, period: dates).to_a
dates.map do |date|
records.detect { |r| r.period == date.beginning_of_day }&.value || 0
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
end
include DOTIW::Methods
ENV['TZ'] = 'UTC'
MAX_FAVORITES = 50
BASE_URL = ENV['BASE_URL'] || 'https://ragchew.app'
SUPPORT_EMAIL = ENV['SUPPORT_EMAIL'] || 'tim@timmorgan.org'
ONE_PIXEL_IMAGE = File.read(File.expand_path('./public/images/1x1.png', __dir__))
get '/' do
@homepage = true
@user = get_user
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
{ name: :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 = @nets.map do |net|
next unless net.show_circle?
{
latitude: net.center_latitude,
longitude: net.center_longitude,
radius: net.center_radius,
name: net.name,
url: "/net/#{url_escape(net.name)}",
}
end.compact.sort_by { |c| c[:radius] }.reverse
erb :index
end
get '/about' do
@user = get_user
erb :about
end
get '/net/:name' do
@user = get_user
params[:name] = CGI.unescape(params[:name])
service = NetInfo.new(name: params[:name])
service.update!
@net = service.net
@page_title = @net.name
if @user&.monitoring_net == @net
@user.update!(monitoring_net_last_refreshed_at: Time.now)
end
if @user
@messages = @net.messages.order(:sent_at).to_a
@monitors = @net.monitors.order(:call_sign).to_a
@favorites = @user.favorites.pluck(:call_sign)
@last_updated_at = @net.fully_updated_at
@update_interval = @net.update_interval_in_seconds + 1
erb :net
else
@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
@closed_net = Tables::ClosedNet.where(name: params[:name]).order(started_at: :desc).first
@page_title = @name = @closed_net&.name
end
if @closed_net
@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 '/net/:id/details' do
@user = get_user
require_user!
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
monitoring_this_net = @user.monitoring_net == net
if monitoring_this_net
@user.update!(monitoring_net_last_refreshed_at: Time.now)
end
messagesCount = net.messages.count
messages = monitoring_this_net ? net.messages.order(:sent_at).to_a : []
messages.reject! { |m| m.blocked? && m.call_sign.upcase != @user.call_sign.upcase }
monitors = net.monitors.order(:call_sign).to_a
favorites = @user.favorites.pluck(:call_sign)
content_type 'application/json'
{
checkins:,
coords:,
messages:,
messagesCount:,
monitors:,
favorites:,
lastUpdatedAt: net.updated_at.rfc3339,
monitoringThisNet: monitoring_this_net,
}.to_json
rescue NetInfo::NotFoundError
status 404
content_type 'application/json'
{ error: 'net not found' }.to_json
end
get '/net/:id/log' do
@user = get_user
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
@user = get_user
require_net_logger_role!
check_if_already_started_a_net!(@user)
@my_clubs = @user.clubs
erb :create_net
end
post '/create-net' do
@user = get_user
require_net_logger_role!
check_if_already_started_a_net!(@user)
content_type 'application/json'
@params = params.merge(JSON.parse(request.body.read))
missing = CREATE_NET_REQUIRED_PARAMS.keys.reject do |param|
params[param].present?
end
if missing.any?
status 400
return { error: "Some required fields are missing: #{missing.join(', ')}.", fields: missing }.to_json
end
club = Tables::Club.find(params[: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
CREATE_NET_REQUIRED_PARAMS.each do |param, requirements|
next unless (length = requirements[:length])
if params[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 params[param] !~ format
status 400
return { error: "#{param} contains characters not allowed.", fields: [param] }.to_json
end
end
if Tables::Net.where(name: params[:net_name]).exists?
status 400
return { error: 'A net with this name is already in progress.', fields: [:net_name] }.to_json
end
NetLogger.create_net!(
club:,
name: params[:net_name],
password: params[:net_password],
frequency: params[:frequency],
net_control: params[:net_control],
user: @user,
mode: params[:mode],
band: params[:band],
)
NetInfo.new(name: params[:net_name]).monitor!(user: @user)
redirect "/net/#{url_escape params[:net_name]}"
end
post '/start-logging/:id' do
@user = get_user
require_net_logger_role!
if @user.logging_net
halt 401, 'already logging a net'
end
@net = Tables::Net.find(params[:id])
unless @user.can_log_for_club?(@net.club)
halt 401, 'not authorized'
end
net_info = NetInfo.new(id: @net.id)
NetLogger.start_logging(net_info, password: params[:net_password], user: @user)
redirect "/net/#{url_escape net_info.name}"
rescue NetLogger::PasswordIncorrectError
halt 401, 'incorrect password'
end
post '/stop-logging/:id' do
@user = get_user
require_user!
@user.update!(logging_net: nil, logging_password: nil)
@net = Tables::Net.find(params[:id])
redirect "/net/#{url_escape @net.name}"
rescue ActiveRecord::RecordNotFound
redirect '/'
end
patch '/log/:id/:num' do
@user = get_user
require_net_logger_role!
@params = params.merge(JSON.parse(request.body.read))
logger = NetLogger.new(NetInfo.new(id: params[:id]), user: @user)
logger.update!(params.fetch(:num).to_i, params)
content_type 'application/json'
return { success: true }.to_json
rescue NetLogger::NotAuthorizedError
halt 401, 'not authorized'
end
delete '/log/:id/:num' do
@user = get_user
require_net_logger_role!
logger = NetLogger.new(NetInfo.new(id: params[:id]), user: @user)
logger.delete!(params.fetch(:num).to_i)
return { success: true }.to_json
rescue NetLogger::NotAuthorizedError
halt 401, 'not authorized'
end
patch '/highlight/:id/:num' do
@user = get_user
require_net_logger_role!
logger = NetLogger.new(NetInfo.new(id: params[:id]), user: @user)
logger.highlight!(params.fetch(:num).to_i)
return { success: true }.to_json
rescue NetLogger::NotAuthorizedError
halt 401, 'not authorized'
end
post '/close-net/:id' do
@user = get_user
require_net_logger_role!
logger = NetLogger.new(NetInfo.new(id: params[:id]), user: @user)
logger.close_net!
@user.update!(
monitoring_net: nil,
monitoring_net_last_refreshed_at: nil,
logging_net: nil,
logging_password: nil,
)
redirect '/'
rescue NetLogger::NotAuthorizedError
halt 401, 'not authorized'
rescue NetLogger::CouldNotCloseNetError => e
halt 400, "there was an error closing this net: #{e.message}"
end
get '/closed-nets' do
@user = get_user
params[:days] ||= '1'
scope = Tables::ClosedNet.all
if params[:days] != 'all'
days = params[:days].to_i
scope = scope.where('started_at > ?', Time.now - (days * 24 * 60 * 60))
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 => sort_direction }
if sort_name == 'started_at'
sort[:name] = 'asc'
else
sort[:started_at] = 'asc'
end
params[:sort] = "#{sort_name} #{sort_direction}"
scope = scope.order(sort)
if params[:name].present?
scope = scope.where('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 = @closed_nets.count > @per_page
@closed_nets = @closed_nets.limit(@per_page)
erb :closed_nets
end
get '/closed-net/:id' do
@user = get_user
@closed_net = Tables::ClosedNet.find(params[:id])
@page_title = @name = @closed_net&.name
@checkin_count = @closed_net.checkin_count
@message_count = @closed_net.message_count
@monitor_count = @closed_net.monitor_count
@net_count = Tables::Net.count
@more_recent_closed_net = Tables::ClosedNet.where(name: @closed_net.name).where('started_at > ?', @closed_net.started_at).order(started_at: :desc).first
@open_net = Tables::Net.find_by(name: @closed_net.name)
erb :closed_net
rescue ActiveRecord::RecordNotFound
status 404
erb :missing_net
end
get '/groups' do
@clubs = Tables::Club.order_by_name.pluck(:name, :full_name)
erb :clubs
end
post '/join-group/:id' do
@user = get_user
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
@user = get_user
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 '/station/:call_sign' do
@user = get_user
require_net_logger_role!
content_type 'application/json'
begin
station = StationUpdater.new(params[:call_sign]).call
rescue StationUpdater::NotFound => e
status 404
return { 'error' => e.message }.to_json
rescue Qrz::Error => e
status 500
return { 'error' => e.message }.to_json
end
attributes = station.attributes
if (club_station = params[:club_id] && Tables::ClubStation.where(club_id: params[:club_id], call_sign: params[:call_sign]).first)
attributes.merge!(club_station.attributes.slice('preferred_name', 'notes'))
end
attributes.to_json
end
get '/station/:call_sign/image' do
@user = get_user
require_user!
expires Tables::Station::EXPIRATION_IN_SECONDS, :public, :must_revalidate
begin
station = StationUpdater.new(params[:call_sign]).call
rescue StationUpdater::NotFound
content_type 'image/png'
return ONE_PIXEL_IMAGE
rescue Qrz::Error => e
status 500
return erb("qrz error: #{e.message}")
end
image_url = station.image.presence
unless image_url
content_type 'image/png'
return ONE_PIXEL_IMAGE
end
redirect image_url
end
# from form
post '/favorite' do
@user = get_user
require_user!
if @user.favorites.count >= MAX_FAVORITES
status 400
erb "<p><em>You cannot have more than #{MAX_FAVORITES} favorites.</em></p>"
end
begin
station = QrzAutoSession.new.lookup(params[:call_sign])
rescue Qrz::Error
end
@user.favorites.create!(
call_sign: station ? station[:call_sign] : params[:call_sign].upcase,
first_name: station && station[:first_name],
last_name: station && station[:last_name],
)
redirect '/user'
rescue ActiveRecord::RecordNotUnique
redirect '/user'
rescue Qrz::NotFound
status 400
erb "<p><em>That call sign was not found in QRZ.</em></p>"
end
# from JS
post '/favorite/:call_sign' do
@user = get_user
content_type 'application/json'
return { error: 'not logged in' }.to_json unless @user
if @user.favorites.count >= MAX_FAVORITES
return {
error: "ERROR: You cannot have more than #{MAX_FAVORITES} favorites."
}.to_json
end
begin
station = QrzAutoSession.new.lookup(params[:call_sign])
rescue Qrz::Error
end
@user.favorites.create!(
call_sign: station ? station[:call_sign] : params[:call_sign].upcase,
first_name: station && station[:first_name],
last_name: station && station[:last_name],
)
{
html: erb(
:_favorite,
locals: { call_sign: params[:call_sign], favorited: true },
layout: false
)
}.to_json
end
post '/unfavorite/:call_sign' do
@user = get_user
content_type 'application/json'
return { error: 'not logged in' }.to_json unless @user
@user.favorites.where(call_sign: params[:call_sign]).delete_all
{
html: erb(
:_favorite,
locals: { call_sign: params[:call_sign], favorited: false },
layout: false
)
}.to_json
end
get '/user' do
@user = get_user
require_user!
@my_clubs = @user.clubs.order_by_name
@favorites = @user.favorites.order(:call_sign).to_a
@page_title = 'User Profile and Settings'
erb :user
end
post '/preferences' do
@user = get_user
require_user!
@user.time_format = params[:time_format]
@user.save!
redirect '/'
end
get '/login' do
@page_title = 'Log in'
erb :login
end
post '/login' do
params[:net] = CGI.unescape(params[:net]) if params[:net]
qrz = Qrz.login(
username: params[:call_sign],
password: params[:password],
)
result = qrz.lookup(params[:call_sign])
@user = Tables::User.find_or_initialize_by(call_sign: result[:call_sign])
@user.last_signed_in_at = Time.now
@user.update!(result.slice(:call_sign, :first_name, :last_name, :image))
session.clear
session[:user_id] = @user.id
session[:qrz_session] = qrz.session
redirect params[:net] ? "/net/#{url_escape params[:net]}" : '/'
rescue Qrz::Error => e
@error = e.message
erb :login
end
get '/logout' do
erb :logout
end
post '/logout' do
session.clear
redirect '/'
end
def gather_hourly_stats
time_range = 7.days.ago..Time.zone.now
times = hours_in_range(time_range).to_a
new_user_values = stat_values_by_hour(times, 'new_users_per_hour')
active_user_values = stat_values_by_hour(times, 'active_users_per_hour').zip(new_user_values).map { |active, new| active - new }
@user_stats_hourly = {
new_users: {
x: times,
y: new_user_values,
name: 'new',
type: 'bar'
},
active_users: {
x: times,
y: active_user_values,
name: 'existing',
type: 'bar'
}
}
@net_stats_hourly = {
x: times,
y: stat_values_by_hour(times, 'nets_per_hour'),
type: 'bar'
}
end
def gather_daily_stats
Time.zone = 'America/Chicago'
time_range = 30.days.ago..Time.zone.now
dates = dates_in_range(time_range).to_a
new_user_values = stat_values_by_date(dates, 'new_users_per_day')
active_user_values = stat_values_by_date(dates, 'active_users_per_day').zip(new_user_values).map { |active, new| active - new }
@user_stats_daily = {
new_users: {
x: dates,
y: new_user_values,
name: 'new',
type: 'bar'
},
active_users: {
x: dates,
y: active_user_values,
name: 'existing',
type: 'bar'
}
}
@net_stats_daily = {
x: dates,
y: stat_values_by_date(dates, 'nets_per_day'),
type: 'bar'
}
end
get '/admin' do
@user = get_user
require_admin!
@page_title = 'Admin'
gather_daily_stats
erb :admin
end
get '/admin/stats' do
@user = get_user
require_admin!
@page_title = 'Admin'
Time.zone = 'America/Chicago'
gather_hourly_stats
gather_daily_stats
erb :admin_stats
end
get '/admin/users' do
@user = get_user
require_admin!
@page_title = 'Admin - Users'
@per_page = 100
order = case params[:order]
when 'call_sign'
{ call_sign: :asc }
when 'first_name,last_name'
{ first_name: :asc, last_name: :asc }
when 'created_at'
{ created_at: :desc }
when 'last_signed_in_at', nil
{ last_signed_in_at: :desc }
end
scope = Tables::User.order(order)
scope = scope.where('call_sign like ?', '%' + params[:call_sign] + '%') if params[:call_sign]
scope = scope.offset(params[:offset]) if params[:offset]
@more_pages = scope.count > @per_page
scope = scope.limit(@per_page)
@users = scope.to_a
@user_count_total = Tables::User.count
@user_count_last_30_days = Tables::User.where('last_signed_in_at > ?', Time.now - (30 * 24 * 60 * 60)).count
@user_count_last_7_days = Tables::User.where('last_signed_in_at > ?', Time.now - (7 * 24 * 60 * 60)).count
@user_count_last_24_hours = Tables::User.where('last_signed_in_at > ?', Time.now - (24 * 60 * 60)).count
@user_count_last_1_hour = Tables::User.where('last_signed_in_at > ?', Time.now - (1 * 60 * 60)).count
erb :admin_users
end
get '/admin/users/:id' do
@user = get_user
require_admin!
@page_title = 'Admin - User'
@user_to_edit = Tables::User.find(params[:id])
@club_members = @user_to_edit.club_members.includes(:club).order('clubs.name').to_a
erb :admin_user
end
post '/admin/users/:id' do
@user = get_user
require_admin!
@user_to_edit = Tables::User.find(params[:id])
@user_to_edit.admin = params[:admin] == 'true'
@user_to_edit.net_logger = params[:net_logger] == 'true'
@user_to_edit.save!
redirect "/admin/users/#{params[:id]}"
end
get '/admin/closed-nets' do
@user = get_user
require_admin!
per_page = 20
scope = Tables::ClosedNet.order(started_at: :desc)
scope = scope.where('name like ?', '%' + params[:name] + '%') if params[:name]
@total_count = scope.count
scope = scope.where('started_at < ?', params[:started_at]) if params[:started_at]
@more_pages = scope.count - per_page > 0
@closed_nets = scope.limit(per_page)
erb :admin_closed_nets
end
delete '/admin/closed-net/:id' do
@user = get_user
require_admin!
Tables::ClosedNet.where(id: params[:id]).delete_all
redirect '/admin/closed-nets'
end
get '/admin/clubs' do
@user = get_user
require_admin!
scope = Tables::Club.order(:name)
scope = scope.where(
'name like :query or full_name like :query',
query: '%' + params[:name] + '%'
) if params[:name]
@clubs = scope.to_a
erb :admin_clubs
end
get '/admin/clubs/new' do
@user = get_user
require_admin!
@club = Tables::Club.new
@url = "/admin/clubs"
erb :admin_club_edit
end
get '/admin/clubs/:id/edit' do
@user = get_user
require_admin!
@club = Tables::Club.find(params[:id])
@club_members = @club.club_members.includes(:user).order('users.call_sign').to_a
@url = "/admin/clubs/#{@club.id}"
erb :admin_club_edit
end
post '/admin/clubs' do
@user = get_user
require_admin!
@club = Tables::Club.create!(name: params[:club][:name])
fix_club_params(params)
@club.update!(params[:club])
only_blank = params[:force_update_existing_nets] != 'true'
AssociateClubWithNets.new(@club, only_blank:).call
AssociateNetWithClub.clear_clubs_cache
redirect "/admin/clubs/#{@club.id}/edit"
rescue JSON::ParserError
status 400
'error parsing JSON'
rescue ActiveRecord::RecordInvalid => e
status 400