-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsanity-uploader.rb
executable file
·1454 lines (1370 loc) · 50.9 KB
/
insanity-uploader.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
####
# Copyright 2016-2017 John Messenger
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
####
require 'rubygems'
require 'date'
require 'json'
require 'logger'
require 'mechanize'
require 'nokogiri'
require 'open-uri'
require 'rest-client'
require 'rubyXL'
require 'slop'
require 'yaml'
require 'open-uri'
require 'dirtp'
class String
def casecmp?(other)
self.casecmp(other).zero?
end
end
PARPATTERN = /802.1[a-zA-Z]+|802[a-zA-Z]|802$/
####
# Log in to the Maintenance Database API
####
def login(api, username, password)
login_request = {}
login_request['user'] = {}
login_request['user']['email'] = username
login_request['user']['password'] = password
begin
res = api['users/sign_in'].post login_request.to_json, { content_type: :json, accept: :json }
rescue RestClient::ExceptionWithResponse => e
abort "Could not log in: #{e.response}"
end
res
end
####
# Format a date suitable for a Slack message: https://api.slack.com/docs/message-formatting#formatting_dates
####
def slack_date(date)
"<!date^#{date.to_time.to_i}^{date_pretty}|#{date.strftime('%c')}>"
end
####
# Post a message to Slack about an event
####
def slack_post_event(proj, event, type: nil)
return unless $slack
datediff = (Date.today - event[:date]).to_i
if (datediff > 3) || (datediff < -1)
$logger.debug "Not slackposting event because #{event[:date].to_s} is out of range: #{event[:description]}"
return
end
slackdata = {
"attachments": [
{
"fallback": event[:description],
"color": "good",
#"author_name": "#{newreq['name']}",
#"author_link": "mailto:#{newreq['email']}",
"pretext": "802.1 announcement",
"title": proj['designation'] + ": " + event[:description],
"title_link": event[:url],
"text": proj['title'],
"fields": [
{
"title": "Start date",
"value": slack_date(event[:date]),
"short": true
}
],
"footer": "802.1",
"footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
"ts": event[:date].to_time.to_i
}
]
}
slackdata[:attachments][0][:fields] << { "title": "End date", "value": slack_date(event[:end_date]), "short": true } if event[:end_date]
if proj['draft_url'] && event[:event_type] != "draft"
slackdata[:attachments][0][:fields] << { "title": "Draft", "value": "<#{proj['draft_url']}|#{proj['draft_no']}>", "short": true }
end
$logger.info "Slackposting date: #{event[:date].to_s} event: #{event[:description]}"
res = $slack.post slackdata.to_json, { content_type: :json, accept: :json}
end
####
# Search the Database for a task group with the specified name and return the parsed item
####
def find_task_group(api, name)
search_result = api['task_groups'].get accept: :json, params: { search: name }
tgs = JSON.parse(search_result.body)
return nil if tgs.empty?
thisid = tgs[0]['id']
JSON.parse(api["task_groups/#{thisid}"].get accept: :json)
end
####
# Fetch the list of task groups from the database and return the parsed list
####
def find_task_groups(api)
search_result = api['task_groups'].get accept: :json
tgs = JSON.parse(search_result.body)
return nil if tgs.empty?
tgs
end
####
# Find a project. If a task_group is specified, look there. Otherwise, look at all projects.
# For the project to be found, the designation supplied must match the designation of the project in the database.
# For an "exact" match, only case differences are allowed. For an :allow_rev match, two matches are tried:
# either designation or designation-REV must be the same as the designation of the project in the database, again
# allowing case variation.
####
def find_project_in_tg(api, tg, designation, match_style: :exact_match)
designation = designation.to_s # force it to be a string
if tg.nil?
search_result = api["projects"].get accept: :json, params: { search: designation }
else
tgid = tg['id']
search_result = api["task_groups/#{tgid}/projects"].get accept: :json, params: { search: designation }
end
projects = JSON.parse(search_result.body)
return nil if projects.empty?
thisid = nil
projects.each do |project|
thisdesig = project['designation']
revdesig = designation + '-REV'
if designation.casecmp?(thisdesig) || (match_style == :allow_rev && revdesig.casecmp?(thisdesig))
thisid = project['id']
end
end
return nil unless thisid
JSON.parse(api["projects/#{thisid}"].get accept: :json)
end
####
# Create a new project in an existing Task Group
####
def add_project_to_tg(api, cookie, tg, newproj)
tgid = tg['id']
option_hash = { content_type: :json, accept: :json, cookies: cookie }
begin
res = api["task_groups/#{tgid}/projects"].post newproj.to_json, option_hash unless $dryrun
twit = 11
rescue => e
$logger.fatal "add_project_to_tg => exception #{e.class.name} : #{e.message}"
if (ej = JSON.parse(e.response)) && (eje = ej['errors'])
eje.each do |k, v|
$logger.fatal "#{k}: #{v.first}"
end
exit(1)
end
end
res && JSON.parse(res)
end
####
# Update a project that already exists
####
def update_project(api, cookie, proj, update)
tgid = proj['task_group_id']
projid = proj['id']
option_hash = { content_type: :json, accept: :json, cookies: cookie }
begin
res = api["task_groups/#{tgid}/projects/#{projid}"].patch update.to_json, option_hash unless $dryrun
twit = 11
rescue => e
$logger.fatal "update_project => exception #{e.class.name} : #{e.message}"
if (ej = JSON.parse(e.response)) && (eje = ej['errors'])
eje.each do |k, v|
$logger.fatal "#{k}: #{v.first}"
end
exit(1)
end
end
end
####
# Find an Event in a Project.
####
# @param [RestClient::Resource] api
# @param [proj_hash] proj
# @param [string] event_name
def find_event_in_proj(api, proj, event_name)
projid = proj['id']
tgid = proj['task_group_id']
JSON.parse(api["task_groups/#{tgid}/projects/#{projid}/events"].get accept: :json, params: { search: event_name })
end
####
# Add events to a Project. If an event of that name is already present, then update it.
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [proj_hash] proj
# @param [Array] events
def add_events_to_project(api, cookie, proj, events)
projid = proj['id']
tgid = proj['task_group_id']
option_hash = { content_type: :json, accept: :json, cookies: cookie }
res = nil
begin
events.each do |event|
found = false
ev = find_event_in_proj(api, proj, event[:name])
if ev.empty?
$logger.warn("Adding event #{event[:name]} to project #{proj['designation']}")
res = api["task_groups/#{tgid}/projects/#{projid}/events"].post event.to_json, option_hash unless $dryrun
slack_post_event(proj, event)
else
ev.each do |e|
if e['name'] == event[:name] && e['date'].to_s == event[:date].to_date.to_s # dropped end-date check
# the end date check was hard because it's blank sometimes
found = true
$logger.debug("Found matching event #{event[:name]} for project #{proj['designation']}")
end
end
unless found
$logger.warn("Adding extra event #{event[:name]} to project #{proj['designation']}")
res = api["task_groups/#{tgid}/projects/#{projid}/events"].post event.to_json, option_hash unless $dryrun
slack_post_event(proj, event, type: :extra)
end
end
end
twit = 11 ##########
rescue => e
$logger.fatal "add_events_to_project => exception #{e.class.name} : #{e.message}"
if (ej = JSON.parse(e.response)) && (eje = ej['errors'])
eje.each do |k, v|
$logger.fatal "#{k}: #{v.first}"
end
exit(1)
end
end
end
###
# Parse the status message from the spreadsheet into a status value and an optional event
###
def parse_status(sts_string)
s, e = sts_string.split(' - ')
orig_s = s
case
when s.match(/WG\s*[bB]allot[- ]*[rR]ecirc/)
s = 'WgBallotRecirc'
when s.match(/WG\s*[bB]allot$/)
s = 'WgBallot'
when s.match(/TG\s*[bB]allot[- ]*[rR]ecirc/)
s = 'TgBallotRecirc'
when s.match(/TG\s*[bB]allot$/)
s = 'TgBallot'
when s.match(/Editor/)
s = 'EditorsDraft'
when s.match(/Sponsor\s*[bB]allot[- ]*[cC]ond/)
s = 'SponsorBallotCond'
when s.match(/Sponsor\s*[bB]allot$/)
s = 'SponsorBallot'
when s.match(/PAR\s*[dD]evelop/)
s = 'ParDevelopment'
when s.match(/PAR\s*[aA]pproved/)
s = 'ParApproved'
end
events = []
if e
events << { date: Date.parse(e), name: s, description: orig_s + ': ' + Date.parse(e).to_s }
end
[s, events]
end
###
# Parse the Last Motion and Next Action from the spreadsheet into a standard form.
# If you don't give a value, you get 'Done'.
###
# @param [String] motion_string
def parse_motion(motion_string)
s = motion_string
case
when s.nil? || s.empty?
s = 'Done'
when s.match(/WG\s*[bB]allot[- ]*[rR]ecirc/)
s = 'WgBallotRecirc'
when s.match(/WG\s*[bB]allot$/)
s = 'WgBallot'
when s.match(/TG\s*[bB]allot[- ]*[rR]ecirc/)
s = 'TgBallotRecirc'
when s.match(/TG\s*[bB]allot$/)
s = 'TgBallot'
when s.match(/Editor/)
s = 'EditorsDraft'
when s.match(/Sponsor\s*[bB]allot[- ]*[cC]ond/)
s = 'SponsorBallotCond'
when s.match(/Sponsor\s*[bB]allot$/)
s = 'SponsorBallot'
when s.match(/PAR\s*[dD]evelop/)
s = 'ParDevelopment'
when s.match(/PAR\s*[aA]pproval/)
s = 'ParApproval'
when s.match(/PAR\s*[mM]od/)
s = 'ParMod'
when s.match(/RevCom\s*[-*]\s*[cC]ond/)
s = 'RevComCond'
when s.match(/RevCom$/)
s = 'RevCom'
when s.match(/[wW]ithdraw/)
s = 'Withdrawal'
end
s
end
###
# Parse the Last Motion and Next Action from the spreadsheet into a standard form.
# If you don't give a value, you get 'Done'.
###
# @param [String] desig_string
def parse_desig(desig_string)
if (result = /P*(802(\.(\d+))*([A-Z]+|[a-z]+))([a-z]*)/.match(desig_string))
base, unused, wg, projletters, amd = result.captures
ptype = amd.empty? ? 'NewStandard' : 'Amendment'
elsif (result = /P*(802(\.(\d+))([A-Z]+|[a-z]+))-[rR][eE][vV]/.match(desig_string))
base, unused, wg, projletters = result.captures
ptype = 'Revision'
elsif (result = /P*(802(\.(\d+))([A-Z]+|[a-z]+)-*\d*)\/[cC][oO][rR]-*(\d+)/.match(desig_string))
base, unused, wg, projletters, amd = result.captures
ptype = 'Corrigendum'
elsif (result = /P*(802(\.(\d+))([A-Z]+|[a-z]+)-*\d*)\/[eE][rR][rR]-*(\d+)/.match(desig_string))
base, unused, wg, projletters, amd = result.captures
ptype = 'Erratum'
end
[ptype, base]
end
###
# Parse the Last Motion and Next Action from the spreadsheet into a standard form.
# If you don't give a value, you get 'Done'.
###
# @param [String] short_date_string
def parse_short_date(short_date_string)
if (result = /(jan|feb|mar|apr|may|june?|july?|aug|sep|oct|nov|dec)\s*(\d\d)/i.match(short_date_string))
Date.parse($1 + " '" + $2)
else
Date.parse(short_date_string)
end
end
####
# Delete a project from a task group, including its events
####
def delete_project(api, cookie, tg, project)
option_hash = { accept: :json, cookies: cookie }
events_result = api["task_groups/#{tg['id']}/projects/#{project['id']}/events"].get option_hash
if events_result && !events_result.empty?
events = JSON.parse(events_result)
$logger.info "Project #{project['designation']} has #{events.count} events"
events.each do |event|
res = api["task_groups/#{tg['id']}/projects/#{project['id']}/events/#{event['id']}"].delete option_hash unless $dryrun
end
end
res = api["task_groups/#{tg['id']}/projects/#{project['id']}"].delete option_hash unless $dryrun
twit = 14
end
####
# Create a new item and add a request to it - UNUSED!
####
def add_new_item(api, cookie, number, subject, newreq)
item = nil
option_hash = { content_type: :json, accept: :json, cookies: cookie }
newitem = { number: number, clause: newreq['clauseno'], date: newreq['date'], standard: newreq['standard'],
subject: subject }
res = api["items"].post newitem.to_json, option_hash unless $dryrun
if res&.code == 201
item = JSON.parse(res.body)
reqres = add_request_to_item(api, cookie, item, newreq)
end
item
end
####
# Find a person
####
# @param [RestClient::Resource] api
# @param [string] first
# @param [string] last
# @param [string] role
####
def find_person(api, first, last, role)
return nil if first.nil? || last.nil?
res = api["people"].get accept: :json, params: { search: last }
if res.code == 200
people = JSON.parse(res.body)
people.each do |pers|
if pers['role'] == role && pers['first_name']&.casecmp?(first) && pers['last_name']&.casecmp?(last)
return pers
end
end
end
nil
end
####
# Create a new person
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [Hash] person
####
def add_new_person(api, cookie, person)
pers = nil
option_hash = { content_type: :json, accept: :json, cookies: cookie }
res = api["people"].post person.to_json, option_hash unless $dryrun
if res&.code == 201
pers = JSON.parse(res.body)
end
pers
end
####
# Update an existing person
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [Hash] perstoupdate
# @param [Hash] person
####
def update_person(api, cookie, perstoupdate, person)
pers_id = perstoupdate['id']
option_hash = { content_type: :json, accept: :json, cookies: cookie }
pers = nil
res = api["people/#{pers_id}"].patch person.to_json, option_hash unless $dryrun
if res&.code == 201
pers = JSON.parse(res.body)
end
pers
end
####
# Create a new task group
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [string] abbrev
# @param [string] tgname
# @param [Hash] person
####
def add_new_task_group(api, cookie, abbrev, tgname, person)
pers_id = person['id']
newtg = { abbrev: abbrev, name: tgname, chair_id: pers_id }
tg = nil
option_hash = { content_type: :json, accept: :json, cookies: cookie }
res = api["task_groups"].post newtg.to_json, option_hash unless $dryrun
if res&.code == 201
tg = JSON.parse(res.body)
end
tg
end
####
# Update an existing task group
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [Hash] tgtoupdate
# @param [Hash] person
####
def update_task_group(api, cookie, tgtoupdate, person)
tg_id = tgtoupdate['id']
option_hash = { content_type: :json, accept: :json, cookies: cookie }
tgtoupdate['chair_id'] = person['id']
tg = nil
res = api["task_groups/#{tg_id}"].patch tgtoupdate.to_json, option_hash unless $dryrun
if res&.code == 201 # actually it seems to return 204.
tg = JSON.parse(res.body)
end
tg
end
####
# Create a new motion in an existing Meeting
####
def add_motion_to_mtg(api, cookie, mtg, newmotion)
mtgid = mtg['id']
option_hash = { content_type: :json, accept: :json, cookies: cookie }
begin
res = api["meetings/#{mtgid}/motions"].post newmotion.to_json, option_hash unless $dryrun
twit = 11
rescue => e
$logger.fatal "add_motion_to_mtg => exception #{e.class.name} : #{e.message}"
if (ej = JSON.parse(e.response)) && (eje = ej['errors'])
eje.each do |k, v|
$logger.fatal "#{k}: #{v.first}"
end
exit(1)
end
end
res && JSON.parse(res)
end
####
# Safely parse a date which might not be present
####
# @param [string] maybedate
def safe_date(maybedate)
begin
parsed_date = Date.parse(maybedate)
rescue ArgumentError
return nil
end
parsed_date
end
####
# Add or update projects from the Insanity Spreadsheet. Optionally update the People and Task Groups
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [string] filepath
# @param [Slop::Result] opts
def parse_insanity_spreadsheet(api, cookie, filepath, opts)
book = RubyXL::Parser.parse filepath
# book.worksheets.each do |w|
# puts w.sheet_name
# end
if opts.people?
peepsheet = book['People']
people = []
peepsheet[(i = 0)..peepsheet.count - 1].each do |peeprow|
person = {
role: peeprow && peeprow[0].value,
first_name: peeprow && peeprow[1].value,
last_name: peeprow && peeprow[2].value,
email: peeprow && peeprow[3].value,
affiliation: peeprow && peeprow[4].value
}
people << person
end
people.each do |person|
pers = find_person(api, person[:first_name], person[:last_name], person[:role])
if pers.nil?
$logger.warn("Adding new person #{person[:first_name]} #{person[:last_name]} as #{person[:role]}")
add_new_person(api, cookie, person)
else
unless (pers['email'].casecmp?(person[:email])) && (pers['affiliation'].casecmp?(person[:affiliation]))
$logger.warn("Updating person #{person[:first_name]} #{person[:last_name]} as #{person[:role]}")
update_person(api, cookie, pers, person)
else
$logger.info("Up-to-date person #{pers['first_name']} #{pers['last_name']} as #{pers['role']}")
end
end
end
end
tgsheet = book['TaskGroups']
tgnames = {}
tgsheet[(i = 0)..tgsheet.count - 1].each do |tgrow|
tgnames[tgrow[0].value] = { name: tgrow[1].value, chair_first_name: tgrow[2]&.value, chair_last_name: tgrow[3]&.value }
end
tgnames.each do |abbrev, taskgroup|
puts "TG #{abbrev}: #{taskgroup}" if $DEBUG
if opts.task_groups? && !/->/.match(abbrev)
pers = find_person(api, taskgroup[:chair_first_name], taskgroup[:chair_last_name], 'Chair')
if pers.nil?
$logger.error("Chair #{taskgroup[:chair_first_name]} #{taskgroup[:chair_last_name]} not found" +
" for task group #{taskgroup[:name]}")
next
end
tg = find_task_group(api, taskgroup[:name])
if tg.nil?
$logger.warn "Creating task group #{taskgroup[:name]}."
tg = add_new_task_group(api, cookie, abbrev, taskgroup[:name], pers)
else
$logger.warn "Updating existing task group #{taskgroup[:name]}"
tg = update_task_group(api, cookie, tg, pers)
end
end
end
projsheet = book['Projects']
projsheet[(i = 1)..projsheet.count - 1].each do |projrow|
tgshortname = projrow && projrow[9]&.value
tgname = tgnames[tgshortname][:name]
tg = find_task_group(api, tgname)
unless tg
$logger.error "Taskgroup #{tgname} not found"
next
end
$logger.debug tgname
desig = projrow && projrow[0]&.value
if desig
# Want desig to match projects named exactly that
proj = find_project_in_tg(api, tg, desig)
if proj.nil? || opts.update?
$logger.info "Project #{desig} was not found for TG #{tgname}" if proj.nil?
$logger.info "Project #{desig} will be updated" if opts.update?
status, events = parse_status(projrow && projrow[3]&.value)
ptype, base = parse_desig(desig)
newproj = {
designation: desig,
project_type: ptype,
base: base,
short_title: projrow && projrow[1]&.value,
title: 'unset',
draft_no: projrow && projrow[4]&.value,
status: status,
last_motion: parse_motion(projrow && projrow[2]&.value),
next_action: parse_motion(projrow && projrow[5]&.value),
award: projrow && projrow[14]&.value
}
if opts.delete_existing? && !proj.nil?
$logger.warn "Deleting existing project #{desig}"
delete_project(api, cookie, tg, proj)
end
$logger.warn "Adding project #{desig} to TG #{tgname}"
proj = add_project_to_tg(api, cookie, tg, newproj)
unless proj
$logger.error "Addition failed."
raise('ProjAdditionFailed')
end
# then add extra stuff to it like events
if projrow && projrow[6]&.value
date = parse_short_date(projrow[6]&.value)
events << { date: date, name: 'PAR ends', description: "PAR ends: #{date}" }
end
if projrow && projrow[11]&.value
date = parse_short_date(projrow[11]&.value)
events << { date: date, end_date: date + 213, name: 'Pool', description: "Sponsor ballot pool: #{date}" }
end
if projrow && projrow[12]&.value
date = parse_short_date(projrow[12]&.value)
events << { date: date, end_date: date + 30, name: 'MEC', description: "Manadatory Editorial Co-ordination: #{date}" }
end
unless events.empty?
add_events_to_project(api, cookie, proj, events)
end
else
$logger.debug "Project #{desig} exists as #{proj['short_title']}"
end
else
$logger.info "Skipping undesignated project in row #{i}"
end
# exit
end
end
####
# Follow the PAR detail link to get the PAR's dates, full title, etc.
####
# @param [Mechanize] agent
# @param [uri] link
def parse_par_page(agent, link)
events = []
fulltitle = ''
projpage = agent.get(link)
box = projpage.css('div.tab-content-box')
par_path = box.css('div.task_menu').children.first.attributes['href'].to_s
par_url = URI.parse(link) + URI.parse(par_path)
ptype = ''
(0..box.children.count - 1).each do |parlineno|
case box.children[parlineno].to_s
when /Type of Project/
case box.children[parlineno + 1].to_s
when /Modify Existing/
ptype = 'Modification'
when /Revision to/
ptype = 'Revision'
when /Amendment to/
ptype = 'Amendment'
when /New IEEE/
ptype = 'New'
end
when /PAR Request Date/
mydate = safe_date(box.children[parlineno + 1].to_s)
if mydate
name = if ptype == 'Modification'
'PAR Modification Requested'
else
'PAR Requested'
end
events << { date: mydate, name: name, description: "#{name}: " + mydate.to_s }
end
when /PAR Approval Date/
mydate = safe_date(box.children[parlineno + 1].to_s)
if mydate
name = if ptype == 'Modification'
'PAR Modification Approval'
else
'PAR Approval'
end
$logger.debug "Creating EVENT for #{name} #{mydate.to_s}"
events << { date: mydate, name: name, description: "#{name}: " + mydate.to_s }
end
when /PAR Expiration Date/
mydate = safe_date(box.children[parlineno + 1].to_s)
name = 'PAR Expiry'
events << { date: mydate, name: name, description: "#{name}: " + mydate.to_s } if mydate
# This is for PAR Modifications, which include the date of approval of the Root PAR so:
when /Approved on/
mydate = safe_date(box.children[parlineno].to_s)
name = 'PAR Approval'
$logger.debug "Creating EVENT (root) for #{name} #{mydate.to_s}"
events << { date: mydate, name: name, description: "#{name}: " + mydate.to_s } if mydate
when /2.1 Title/
if box.children[parlineno].css('td.b_align_nw').empty?
fulltitle = box.children[parlineno + 1].to_s
else
fulltitle = box.children[parlineno].css('td.b_align_nw')[0].children[1].to_s
end
when /4.2.*Initial Sponsor Ballot/
mydate = safe_date(box.children[parlineno + 1].to_s)
name = 'Expected Initial Sponsor Ballot'
events << { date: mydate, name: name, description: "#{name}: " + mydate.to_s } if mydate
when /4.3.*RevCom/
mydate = safe_date(box.children[parlineno + 1].to_s)
name = 'Expected RevCom'
events << { date: mydate, name: name, description: "#{name}: " + mydate.to_s } if mydate
end
end
return fulltitle, par_url.to_s, events
end
####
# Follow the notification detail link to get the ballot's dates.
####
# @param [Mechanize] agent
# @param [uri] link
# @param [String] text
def parse_sb_notification(agent, link, text)
events = []
sbpage = agent.get(link)
prose = sbpage.css('p.prose')
opening = nil
closing = nil
(0..prose.children.count - 1).each do |plineno|
ptype = ''
case prose.children[plineno].to_s
when /BALLOT OPENS:/
opening = safe_date(prose.children[plineno].to_s)
when /BALLOT CLOSES:/
closing = safe_date(prose.children[plineno].to_s)
events << { date: opening, end_date: closing, name: text, description: text }
end
end
return events
end
####
# Add or update projects from the Development Server's Active PARs page.
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [string] dev_host
# @param [string] user
# @param [string] pw
# noinspection RubyInstanceMethodNamingConvention
def update_projects_from_active_pars(api, cookie, dev_host, user, pw)
agent = Mechanize.new
if $DEBUG
agent.set_proxy('localhost', 8888)
agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
$logger.info("Updating projects from Active PARs page on development server")
# Assume that we are not logged in, and log in to the Development server
page = agent.get('http://' + dev_host)
f = page.forms.first
f.x1 = user
f.x2 = pw
f.f0 = '3' # myproject
f.checkboxes_with name: 'privacyconsent' do |cbxs|
cbxs.first.check
end
page = agent.submit(f, f.buttons.first)
# puts page.pretty_print_inspect if $DEBUG
nextlink = URI::HTTP.build(host: dev_host, path: '/pub/active-pars', query: 's=802.1')
# Find the "Active PARs" page.
# Process each page of the list of active projects
until nextlink.nil?
$logger.debug("New page with nextlink #{nextlink}")
searchresult = agent.get(nextlink)
# puts searchresult.pretty_print_inspect
# Examine each data row representing an active project. Extract dates to create events in the project timeline.
searchresult.parser.css('tr.b_data_row').each do |row|
tds = row.css('td')
desig = tds[1].children.first.children.to_s
next unless PARPATTERN.match(desig)
$logger.debug("Considering project #{desig}")
events = []
par_link = tds[1].children.first.attributes['href'].to_s
par_url = tds[3]&.children&.first&.children.to_s
par_approval = safe_date(tds[4].children.css('noscript').children.to_s)
events << { date: par_approval, name: 'PAR Approval', description: 'PAR Approval: ' + par_approval.to_s } if par_approval
fulltitle, ign, e = parse_par_page(agent, par_link)
events += e
# Look up the project in the database without using a task group
desig[/^P*/] = '' # Remove leading P
# Want desig to match projects named exactly that or desig-REV
proj = find_project_in_tg(api, nil, desig, match_style: :allow_rev)
if proj.nil?
$logger.error("Expected project #{desig} (from Active PARs) not found in database")
next
else
$logger.debug("Matching PAR #{desig} to project #{proj['designation']}")
end
# Overwrite existing project information and add new events to the project.
add_events_to_project(api, cookie, proj, events) unless events.empty?
update_project(api, cookie, proj, { title: fulltitle, par_url: par_url }) unless fulltitle.empty? and
par_url.empty?
twit = 34
end
# Find the link to the next page of projects.
pager = searchresult.parser.css('div.pager').children
nextstr = pager[-1].children[-1].children.to_s
nextlink = nextstr.empty? ? nil : pager.css('a')[-1].attributes['href'].to_s
end
end
####
# Update the list of sponsor ballots for projects from the Development Server's Notifications page.
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [string] dev_host
# @param [string] user
# @param [string] pw
# @param [Array<String>] onlydesigs
# noinspection RubyInstanceMethodNamingConvention
def add_sponsor_ballots_from_dev_server(api, cookie, dev_host, user, pw, onlydesigs)
agent = Mechanize.new
if $DEBUG
agent.set_proxy('localhost', 8888)
agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
$logger.info("Adding sponsor ballot info from Development Server")
# Assume that we are not logged in, and log in to the Development server
page = agent.get('http://' + dev_host)
f = page.forms.first
f.x1 = user
f.x2 = pw
f.f0 = '3' # myproject
f.checkboxes_with name: 'privacyconsent' do |cbxs|
cbxs.first.check
end
page = agent.submit(f, f.buttons.first)
# puts page.pretty_print_inspect if $DEBUG
# Find the "Notifications" or Messages page.
nextlink = URI::HTTP.build(host: dev_host) + (page.links.select { |link| link.text == "Messages" }).first.uri
# Process each page of the list of active projects
until nextlink.nil?
$logger.debug("New page with nextlink #{nextlink}")
searchresult = agent.get(nextlink)
# puts searchresult.pretty_print_inspect
# Examine each data row representing notification. Look for ballot opening and closing announcements
# and ballot invitations.
# Extract dates to create events in the project timeline.
searchresult.parser.css('tr.b_data_row').each do |row|
tds = row.css('td')
events = []
date = safe_date(tds[0].css('noscript').first.children.to_s)
subja = tds[4].css('a')
subject = subja.text
notification_url = URI::HTTP.build(host: dev_host) + subja.first['href']
$logger.debug("Examining announcement #{subject}")
matches = /P?(?<desig>(802.1[a-zA-Z]+|802[a-zA-Z]))/.match(subject)
next unless matches
desig = matches['desig']
desig[/^P*/] = '' # Remove leading P
if onlydesigs
if ! onlydesigs.include? desig.downcase
$logger.debug("Ignoring announcement about #{desig}: #{subject}")
next
end
end
$logger.debug("Considering announcement about #{desig}: #{subject}")
case subject
when /^Sponsor Ballot Opening/
events += parse_sb_notification(agent, notification_url, 'Sponsor Ballot')
when /^Ballot Recirculation/
events += parse_sb_notification(agent, notification_url, 'Sponsor Ballot recirc')
twit = 37
end
next if events.nil? || events.empty?
# Look up the project in the database without using a task group
# Want desig to match projects named exactly that or desig-REV
proj = find_project_in_tg(api, nil, desig, match_style: :allow_rev)
if proj.nil?
$logger.error("Expected project #{desig} (from SB Notification) not found in database")
next
else
$logger.debug("Matching Sponsor Ballot #{desig} to project #{proj['designation']}")
end
startev = find_event_in_proj(api, proj, 'PAR Approval')
if startev.empty?
$logger.error("Project #{desig} has no PAR Approval date")
next
end
if events.first[:date] < Date.parse(startev&.first['date'])
$logger.debug("Not adding sponsor ballot on #{desig} as it starts before #{startev&.first['date']}: #{notification_url}")
next
end
endev = find_event_in_proj(api, proj, 'PAR Expiry')
if endev.empty?
$logger.error("Project #{desig} has no PAR Expiry date")
next
end
if events.first[:date] > Date.parse(endev&.first['date'])
$logger.info("Not adding sponsor ballot on #{desig} as it starts after #{endev&.first['date']}: #{notification_url}")
next
end
# Add new events to the project.
add_events_to_project(api, cookie, proj, events) unless events.empty?
twit = 134
end
# Find the link to the next page of announcements.
pager = searchresult.parser.css('div.pager').children
nextstr = pager[-1].children[-1].children.to_s
nextlink = nextstr.empty? ? nil : pager.css('a')[-1].attributes['href'].to_s
end
end
####
# Add or update projects from the Development Server's PAR report page.
# It wouldn't be a good idea to just add them all: There are multiple projects with the same designation.
# This is because revision projects don't have unique names. Therefore, we use a list of names
# read from a file.
####
# @param [RestClient::Resource] api
# @param [cookie] cookie
# @param [string] dev_host
# @param [string] user
# @param [string] pw
# @param [Hash] projects
# @param [Array] task_groups
# noinspection RubyInstanceMethodNamingConvention
def update_projects_from_par_report(api, cookie, dev_host, user, pw, projects, task_groups)
agent = Mechanize.new
if $DEBUG
agent.set_proxy('localhost', 8888)
agent.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
$logger.info("Updating projects from PAR report on development server")
# Assume that we are not logged in, and log in to the Development server
page = agent.get('http://' + dev_host)
f = page.forms.first
f.x1 = user
f.x2 = pw
f.f0 = '3' # myproject
f.checkboxes_with name: 'privacyconsent' do |cbxs|
cbxs.first.check
end
page = agent.submit(f, f.buttons.first)
# puts page.pretty_print_inspect if $DEBUG
nextlink = URI::HTTP.build(host: dev_host, path: '/pub/par-report', query: 'par_report=1&committee_id=&s=802.1')
# Find the "PAR Report" page.
# Process each page of the list of active projects
until nextlink.nil?
$logger.debug("New PAR report page with nextlink #{nextlink}")
searchresult = agent.get(nextlink)
# puts searchresult.pretty_print_inspect
# Examine each data row representing a project. Extract dates to create events in the project timeline.
searchresult.parser.css('tr.b_data_row').each do |row|
tds = row.css('td')
desig = tds[0].children.first.children.to_s
next unless PARPATTERN.match(desig)