This repository has been archived by the owner on Apr 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
whedon_api.rb
576 lines (499 loc) · 18.6 KB
/
whedon_api.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
require_relative 'github'
require_relative 'workers'
require 'chronic'
require 'date'
require 'sinatra/base'
require 'fileutils'
require 'json'
require 'octokit'
require 'rest-client'
require 'securerandom'
require 'sinatra/config_file'
require 'whedon'
require 'yaml'
require 'pry'
include GitHub
class WhedonApi < Sinatra::Base
register Sinatra::ConfigFile
set :views, Proc.new { File.join(root, "responses") }
config_file "config/settings-#{ENV['RACK_ENV']}.yml"
set :configs, {}
set :initialized, false
before do
set_configs unless journal_configs_initialized?
if %w[dispatch].include? request.path_info.split('/')[1]
sleep(2) unless testing? # This seems to help with auto-updating GitHub issue threads
params = JSON.parse(request.env["rack.input"].read)
# Only work with issues. Halt if there isn't an issue in the JSON
halt 422 if params['issue'].nil?
@action = params['action']
@payload = params
if @action == 'opened' || @action == 'closed'
@message = params['issue']['body']
elsif @action == 'created'
@message = params['comment']['body']
@comment_id = params['comment']['id']
end
@sender = params['sender']['login']
@issue_id = params['issue']['number']
@nwo = params['repository']['full_name']
@config = settings.configs[@nwo]
halt 422 unless @config # We probably want to restrict this
else
pass
end
end
def journal_configs_initialized?
settings.initialized
end
def testing?
ENV['RACK_ENV'] == "test"
end
def serialized_config
@config.to_h
end
def set_configs
# 'settings.journals' comes from sinatra/config_file
settings.journals.each do |journal|
journal.each do |nwo, params|
team_id = params["editor_team_id"]
params["editors"] = github_client.team_members(team_id).collect { |e| e.login }.sort
settings.configs[nwo] = OpenStruct.new params
end
end
settings.initialized = true
end
def say_hello
if issue.title.match(/^\[REVIEW\]:/)
respond erb :reviewer_welcome, :locals => { :reviewer => reviewers, :nwo => @nwo, :reviewers => @config.reviewers }
reviewers.each {|r| schedule_reminder(r, '2', 'weeks', quiet=true)}
# Newly created [PRE REVIEW] issue with assignees.
elsif issue.title.match(/^\[PRE REVIEW\]:/) && assignees.any?
respond erb :welcome, :locals => { :editor => assignees.first, :reviewers => @config.reviewers }
# Newly created [PRE REVIEW] issue without assignees.
elsif issue.title.match(/^\[PRE REVIEW\]:/)
respond erb :welcome, :locals => { :editor => nil, :reviewers => @config.reviewers }
# Newly created issue, not created by JOSS, probably as a result of the 'convert to issue' feature on GitHub
else
respond erb :close
close_issue(@nwo, @issue_id)
halt
end
repo_detect(nil)
check_references(nil)
process_pdf(nil)
end
# When an issue is closed we want to encourage authors to add the JOSS status
# badge to their README but also potentially donate to JOSS (and sign up as a
# future reviewer)
def say_goodbye
if review_issue?
# If the REVIEW has been marked as 'accepted'
if issue.labels.collect {|l| l.name }.include?('accepted')
respond erb :goodbye, :locals => {:site_host => @config.site_host,
:site_name => @config.site_name,
:reviewers => @config.reviewers_signup,
:doi_prefix => @config.doi_prefix,
:doi_journal => @config.journal_alias,
:issue_id => @issue_id,
:donate_url => @config.donate_url}
end
end
end
def review_issue?
issue.title.match(/^\[REVIEW\]:/)
end
def assignees
@assignees ||= github_client.issue(@nwo, @issue_id).assignees.collect { |a| a.login }
end
# One giant case statement to decide how to handle an incoming message...
def robawt_respond
case @message
when /\A@whedon commands/i
if @config.editors.include?(@sender)
respond erb :commands
else
respond erb :commands_public
end
when /\A@whedon assign (.*) as reviewer/i
check_editor
if editor?
assign_reviewer($1)
respond "OK, #{$1} is now a reviewer"
else
respond "You need to assign an editor first."
end
when /\A@whedon add (.*) as reviewer/i
check_editor
if editor?
add_reviewer($1)
respond "OK, #{$1} is now a reviewer"
else
respond "You need to assign an editor first."
end
when /\A@whedon remove (.*) as reviewer/i
check_editor
remove_reviewer($1)
respond "OK, #{$1} is no longer a reviewer"
when /\A@whedon assign (.*) as editor/i
check_editor
new_editor = assign_editor($1)
respond "OK, the editor is @#{new_editor}"
when /\A@whedon invite (.*) as editor/i
check_eic
invite_editor($1)
when /\A@whedon set (.*) as archive/
check_editor
assign_archive($1)
when /\A@whedon set (.*) as version/
check_editor
assign_version($1)
when /\A@whedon start review/i
check_editor
if editor && reviewers.any?
review_issue_id = start_review
respond erb :start_review, :locals => { :review_issue_id => review_issue_id, :nwo => @nwo }
close_issue(@nwo, @issue_id)
else
respond erb :missing_editor_reviewer
halt
end
when /\A@whedon list editors/i
respond erb :editors, :locals => { :editors => @config.editors }
when /\A@whedon list reviewers/i
respond all_reviewers
when /\A@whedon generate my checklist/i
check_reviewer
generate_checklist
when /\A@whedon generate pdf from branch (.\S*)/
process_pdf($1)
when /\A@whedon generate pdf/i
process_pdf(nil)
when /\A@whedon accept deposit=true from branch (.\S*)/i
check_eic
deposit(dry_run=false, $1)
when /\A@whedon accept deposit=true/i
check_eic
deposit(dry_run=false)
when /\A@whedon recommend-accept from branch (.\S*)/i
check_editor
deposit(dry_run=true, $1)
when /\A@whedon recommend-accept/i
check_editor
deposit(dry_run=true)
when /\A@whedon accept/i
check_editor
if editor
respond "To recommend a paper to be accepted use `@whedon recommend-accept`"
end
when /\A@whedon reject/i
check_eic
reject_paper
when /\A@whedon withdraw/i
check_eic
withdraw_paper
when /\A@whedon check references from branch (.\S*)/
check_references($1)
when /\A@whedon check references/i
check_references(nil)
when /\A@whedon check repository from branch (.\S*)/i
repo_detect($1)
when /\A@whedon check repository/i
repo_detect(nil)
# Detect strings like '@whedon remind @arfon in 2 weeks'
when /\A@whedon remind (.*) in (.*) (.*)/i
check_editor
schedule_reminder($1, $2, $3)
when /\A@whedon query scope/
check_editor
label_issue(@nwo, @issue_id, ['query-scope'])
respond "Submission flagged for editorial review."
# We don't understand the command so say as much...
when /\A@whedon/i
respond erb :sorry unless @sender == "whedon"
end
end
def invite_editor(editor)
editor_handle = editor.gsub(/^\@/, "").strip
url = "#{@config.site_host}/papers/api_editor_invite?id=#{@issue_id}&editor=#{editor_handle}&secret=#{@config.site_api_key}"
response = RestClient.post(url, "")
if response.code == 204
respond "@#{editor_handle} has been invited to edit this submission."
else
respond "There was a problem inviting `@#{editor_handle}` to edit this submission."
end
end
def reject_paper
url = "#{@config.site_host}/papers/api_reject?id=#{@issue_id}&secret=#{@config.site_api_key}"
response = RestClient.post(url, "")
if response.code == 204
label_issue(@nwo, @issue_id, ['rejected'])
respond "Paper rejected."
close_issue(@nwo, @issue_id)
else
respond "There was a problem rejecting the paper."
end
end
def withdraw_paper
url = "#{@config.site_host}/papers/api_withdraw?id=#{@issue_id}&secret=#{@config.site_api_key}"
response = RestClient.post(url, "")
if response.code == 204
label_issue(@nwo, @issue_id, ['withdrawn'])
respond "Paper withdrawn."
close_issue(@nwo, @issue_id)
else
respond "There was a problem withdrawing the paper."
end
end
def schedule_reminder(human, size, unit, quiet=false)
# Check that the person we're expecting to remind is actually
# mentioned in the issue body (i.e. is a reviewer or author)
issue = github_client.issue(@nwo, @issue_id)
unless issue.body.match(/#{human}/m) || @config.editors.include?(@sender)
respond "#{human} doesn't seem to be a reviewer or author for this submission."
halt
end
unless issue.title.match(/^\[REVIEW\]:/)
respond "Sorry, I can't set reminders on PRE-REVIEW issues."
halt
end
schedule_at = target_time(size, unit)
if schedule_at
# Schedule reminder
ReviewReminderWorker.perform_at(schedule_at, human, @nwo, @issue_id, serialized_config)
respond "Reminder set for #{human} in #{size} #{unit}" unless quiet
else
respond "I don't recognize this description of time '#{size}' '#{unit}'."
end
end
# Return Date object + some number of days specified
def target_time(size, unit)
Chronic.parse("in #{size} #{unit}")
end
# How Whedon talks
def respond(comment, nwo=nil, issue_id=nil)
nwo ||= @nwo
issue_id ||= @issue_id
github_client.add_comment(nwo, issue_id, comment)
end
# Check if the review issue has an archive DOI set already
def archive_doi?
archive = issue.body[/(?<=\*\*Archive:\*\*.<a\shref=)"(.*?)"/]
if archive
return true
else
return false
end
end
def check_references(custom_branch=nil)
if custom_branch
respond "```\nAttempting to check references... from custom branch #{custom_branch}\n```"
end
DOIWorker.perform_async(@nwo, @issue_id, serialized_config, custom_branch)
end
def deposit(dry_run, custom_branch=nil)
if review_issue?
if !archive_doi?
respond "No archive DOI set, provide the Zenodo DOI of the repository. Exiting..."
return
end
if dry_run == true
respond "```\nAttempting dry run of processing paper acceptance...\n```"
DOIWorker.perform_async(@nwo, @issue_id, serialized_config, custom_branch)
DepositWorker.perform_async(@nwo, @issue_id, serialized_config, custom_branch, dry_run=true)
else
respond "```\nDoing it live! Attempting automated processing of paper acceptance...\n```"
DepositWorker.perform_async(@nwo, @issue_id, serialized_config, custom_branch, dry_run=false)
end
else
respond "I can't accept a paper that hasn't been reviewed!"
end
end
# Download and compile the PDF
def process_pdf(custom_branch=nil)
# TODO refactor this so we're not passing so many arguments to the method
if custom_branch
respond "```\nAttempting PDF compilation from custom branch #{custom_branch}. Reticulating splines etc...\n```"
end
PDFWorker.perform_async(@nwo, @issue_id, serialized_config, custom_branch)
end
# Detect the languages and license of the review repository.
# Also checks the paper for a statement of need and the word count.
def repo_detect(custom_branch=nil)
RepoWorker.perform_async(@nwo, @issue_id, serialized_config, custom_branch)
end
# Update the archive on the review issue
def assign_archive(doi_string)
doi = doi_string[/\b(10[.][0-9]{4,}(?:[.][0-9]+)*\/(?:(?!["&\'<>])\S)+)\b/]
if doi
doi_with_url = "<a href=\"https://doi.org/#{doi}\" target=\"_blank\">#{doi}</a>"
new_body = issue.body.gsub(/\*\*Archive:\*\*\s*(.*|Pending)/i, "**Archive:** #{doi_with_url}")
github_client.update_issue(@nwo, @issue_id, issue.title, new_body)
respond "OK. #{doi_with_url} is the archive."
else
respond "#{doi_string} doesn't look like an archive DOI."
end
end
# Update the version on the review issue
def assign_version(version_string)
if version_string
new_body = issue.body.gsub(/\*\*Version:\*\*\s*(.*)/i, "**Version:** #{version_string}")
github_client.update_issue(@nwo, @issue_id, issue.title, new_body)
respond "OK. #{version_string} is the version."
else
respond "#{version_string} doesn't look like a valid version string."
end
end
# Update sender's comment with a reviewer checklist
def generate_checklist
if !review_issue?
respond "Reviewer checklists can only be added from the review issue"
halt 422
end
# update comment
submitting_author = issue.body.match(/\*\*Submitting author:\*\*\s*.(@\S*)/)[1]
repository_url = issue.body.match(/\*\*Repository:\*\*\s*<a href="([^"]*)"/)[1]
checklist = erb :reviewer_checklist, locals: { reviewer: @sender, submitting_author: submitting_author, repository_url: repository_url }
github_client.update_comment(@nwo, @comment_id, checklist)
# link checklist from issue's body
text = "[- Review checklist for @#{@sender}](https://github.com/#{@nwo}/issues/#{@issue_id}#issuecomment-#{@comment_id})"
new_body = issue.body + "\n" + text
github_client.update_issue(@nwo, @issue_id, issue.title, new_body)
end
# Returns a string response with URL to Gist of reviewers
def all_reviewers
"Here's the current list of reviewers: #{@config.reviewers}"
end
# Change the editor on an issue. This is a two-step process:
# 1. Change the review issue assignee
# 2. Update the editor listed at the top of the issue
# TODO: Refactor this mess
def assign_editor(new_editor)
new_editor = @sender if new_editor == "me"
new_editor = new_editor.gsub(/^\@/, "").strip
new_body = issue.body.gsub(/\*\*Editor:\*\*\s*(@\S*|Pending)/i, "**Editor:** @#{new_editor}")
# This line updates the GitHub issue with the new editor
github_client.update_issue(@nwo, @issue_id, issue.title, new_body, :assignees => [])
url = "#{@config.site_host}/papers/api_assign_editor?id=#{@issue_id}&editor=#{new_editor}&secret=#{@config.site_api_key}"
response = RestClient.post(url, "")
update_assignees([new_editor] | reviewer_logins)
new_editor
end
# Change the reviewer listed at the top of the issue (clobber any that exist)
def assign_reviewer(new_reviewer)
set_reviewers([new_reviewer])
end
# Add a reviewer (don't clobber existing ones)
def add_reviewer(reviewer)
set_reviewers(reviewers + [reviewer])
end
# Remove a reviewer from the list
def remove_reviewer(reviewer)
set_reviewers(reviewers - [reviewer])
end
def set_reviewers(reviewer_list)
new_reviewer_logins = reviewer_list.map { |reviewer_name| reviewer_name.sub(/^@/, "").downcase }.uniq
label = reviewer_list.empty? ? "Pending" : reviewer_list.join(", ")
new_body = issue.body.gsub(/\*\*Reviewers?:\*\*\s*(.+?)\r?\n/i, "**Reviewers:** #{label}\r\n")
github_client.update_issue(@nwo, @issue_id, issue.title, new_body)
end
def editor?
!issue.body.match(/\*\*Editor:\*\*\s*.@(\S*)/).nil?
end
def editor
issue.body.match(/\*\*Editor:\*\*\s*.@(\S*)/)[1]
end
def reviewers
issue.body.match(/Reviewers?:\*\*\s*(.+?)\r?\n/)[1].split(", ") - ["Pending"]
end
def reviewer_logins
@reviewer_logins ||= reviewers.map { |reviewer_name| reviewer_name.sub(/^@/, "").strip }
end
# Send an HTTP POST to the GitHub API here due to Octokit problems
def update_assignees(logins)
data = { "assignees" => logins }
url = "https://api.github.com/repos/#{@nwo}/issues/#{@issue_id}/assignees"
RestClient.post(url, data.to_json, {:Authorization => "token #{ENV['GH_TOKEN']}"})
end
# This method is called when an editor says: '@whedon start review'.
# At this point, Whedon talks to the JOSS/JOSE application which creates
# the actual review issue and responds with the serialized paper which
# includes the 'review_issue_id' which is posted back into the PRE-REVIEW
def start_review
# Check we have an editor and a reviewer
if review_issue? # Don't start a review if it has already started
respond "Can't start a review when the review has already started"
halt 422
end
if reviewers.empty?
respond "Can't start a review without reviewers"
halt 422
end
if !editor
respond "Can't start a review without an editor"
halt 422
end
url = "#{@config.site_host}/papers/api_start_review?id=#{@issue_id}&editor=#{editor}&reviewers=#{reviewer_logins.join(',')}&secret=#{@config.site_api_key}"
# TODO let's do some error handling here please
response = RestClient.post(url, "")
paper = JSON.parse(response)
return paper['review_issue_id']
end
# Return an Octokit GitHub Issue
def issue
@issue ||= github_client.issue(@nwo, @issue_id)
end
# Check that the person sending the command is a reviewer
def check_reviewer
unless reviewer_logins.include?(@sender)
respond "I'm sorry @#{@sender}, I'm afraid I can't do that. That's something only the reviewers are allowed to do."
halt 403
end
end
# Check that the person sending the command is an editor
def check_editor
unless @config.editors.include?(@sender)
respond "I'm sorry @#{@sender}, I'm afraid I can't do that. That's something only editors are allowed to do."
halt 403
end
end
# Check that the person sending the command is an editor-in-chief
def check_eic
unless @config.eics.include?(@sender)
respond "I'm sorry @#{@sender}, I'm afraid I can't do that. That's something only editor-in-chiefs are allowed to do."
halt 403
end
end
# The actual Sinatra URL path methods
get '/heartbeat' do
"BOOM boom. BOOM boom. BOOM boom."
end
get '/' do
erb :preview
end
post '/preview' do
sha = SecureRandom.hex
branch = params[:branch].empty? ? nil : params[:branch]
job_id = PaperPreviewWorker.perform_async(params[:repository], params[:journal], branch, sha)
redirect "/preview?id=#{job_id}"
end
get '/preview' do
begin
container = SidekiqStatus::Container.load(params[:id])
erb :status, :locals => { :status => container.status, :payload => container.payload }
rescue SidekiqStatus::Container::StatusNotFound
erb :status, :locals => { :status => 'missing' }
end
end
post '/dispatch' do
if @action == "opened"
say_hello
halt
end
if @action == "closed"
say_goodbye
halt
end
robawt_respond if @message
end
end