/
webui_helper.rb
544 lines (475 loc) · 17.5 KB
/
webui_helper.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
# vim: sw=2 et
require 'digest/md5'
module Webui::WebuiHelper
include ActionView::Helpers::JavaScriptHelper
include ActionView::Helpers::AssetTagHelper
def get_frontend_url_for(opt = {})
opt[:host] ||= CONFIG['external_frontend_host'] || CONFIG['frontend_host']
opt[:port] ||= CONFIG['external_frontend_port'] || CONFIG['frontend_port']
opt[:protocol] ||= CONFIG['external_frontend_protocol'] || CONFIG['frontend_protocol']
if not opt[:controller]
logger.error 'No controller given for get_frontend_url_for().'
return
end
return "#{opt[:protocol]}://#{opt[:host]}:#{opt[:port]}/#{opt[:controller]}"
end
def bugzilla_url(email_list = '', desc = '')
return '' if @configuration['bugzilla_url'].blank?
assignee = email_list.first if email_list
if email_list.length > 1
cc = ('&cc=' + email_list[1..-1].join('&cc=')) if email_list
end
# rubocop:disable Metrics/LineLength
URI.escape("#{@configuration['bugzilla_url']}/enter_bug.cgi?classification=7340&product=openSUSE.org&component=3rd party software&assigned_to=#{assignee}#{cc}&short_desc=#{desc}")
# rubocop:enable Metrics/LineLength
end
def image_url(source)
abs_path = image_path(source)
unless abs_path =~ /^http/
abs_path = "#{request.protocol}#{request.host_with_port}#{abs_path}"
end
abs_path
end
def user_icon(user, size = 20, css_class = nil, alt = nil)
user = User.find_by_login!(user) unless user.is_a? User
alt ||= user.realname
alt = user.login if alt.empty?
image_tag(url_for(controller: :user, action: :user_icon, icon: user.login, size: size),
width: size, height: size, alt: alt, class: css_class)
end
def fuzzy_time(time)
if Time.now - time < 60
return 'now' # rails' 'less than a minute' is a bit long
end
time_ago_in_words(time) + ' ago'
end
def fuzzy_time_string(timestring)
fuzzy_time(Time.parse(timestring))
end
def status_for(repo, arch, package)
@statushash[repo][arch][package] || { 'package' => package }
end
def format_projectname(prjname, login)
splitted = prjname.split(':', 3)
if splitted[0] == 'home'
if login and splitted[1] == login
prjname = '~'
else
prjname = '~' + splitted[1]
end
if splitted.length > 2
prjname += ':' + splitted[-1]
end
end
prjname
end
def status_id_for(repo, arch, package)
valid_xml_id("id-#{package}_#{repo}_#{arch}")
end
def arch_repo_table_cell(repo, arch, packname)
status = status_for(repo, arch, packname)
status_id = status_id_for(repo, arch, packname)
link_title = status['details']
if status['code']
code = status['code']
theclass='status_' + code.gsub(/[- ]/, '_')
else
code = ''
theclass=''
end
out = "<td class='#{theclass} buildstatus'>"
if %w(unresolvable blocked).include? code
out += link_to code, '#', title: link_title, id: status_id, class: code
elsif %w(- excluded).include? code
out += code
elsif @localpackages and not @localpackages.has_key? packname
# Scheduled packages have no raw log file...
if 'scheduled' == code
out += code
else
out += link_to( code.gsub(/\s/, ' '),
raw_logfile_path(package: packname,
project: @project.to_s,
arch: arch, repository: repo),
title: link_title, rel: 'nofollow')
end
else
out += link_to code.gsub(/\s/, ' '), { action: :live_build_log,
package: packname, project: @project.to_s, arch: arch,
controller: 'package', repository: repo }, { title: link_title, rel: 'nofollow' }
end
out += '</td>'
return out.html_safe
end
REPO_STATUS_ICONS = {
'published' => 'lorry',
'publishing' => 'cog_go',
'outdated_published' => 'lorry_error',
'outdated_publishing' => 'cog_error',
'unpublished' => 'lorry_flatbed',
'outdated_unpublished' => 'lorry_error',
'building' => 'cog',
'outdated_building' => 'cog_error',
'finished' => 'time',
'outdated_finished' => 'time_error',
'blocked' => 'time',
'outdated_blocked' => 'time_error',
'broken' => 'exclamation',
'outdated_broken' => 'exclamation',
'scheduling' => 'cog',
'outdated_scheduling' => 'cog_error'
}
REPO_STATUS_DESCRIPTIONS = {
'published' => 'Repository has been published',
'publishing' => 'Repository is being created right now',
'unpublished' => 'Build finished, but repository publishing is disabled',
'building' => 'Build jobs exists',
'finished' => 'Build jobs have been processed, new repository is not yet created',
'blocked' => 'No build possible atm, waiting for jobs in other repositories',
'broken' => 'The repository setup is broken, build or publish not possible',
'scheduling' => 'The repository state is being calculated right now'
}
def repo_status_icon(status, details = nil)
icon = REPO_STATUS_ICONS[status] || 'eye'
outdated = nil
if status =~ /^outdated_/
status.gsub!(%r{^outdated_}, '')
outdated = true
end
description = REPO_STATUS_DESCRIPTIONS[status] || 'Unknown state of repository'
description = 'State needs recalculations, former state was: ' + description if outdated
description += " (" + details + ")" if details
sprite_tag icon, title: description
end
def flag_status(flagname, flags, repository, arch)
flag = determine_most_specific_flag(arch, flags, repository)
return '' unless flag
image, title = flag_image(flag, flagname)
if (@package && User.current.can_modify_package?(@package)) ||
(@project && User.current.can_modify_project?(@project.api_obj))
opts = { project: @project, package: @package, action: :repositories }
data = { flag: flagname }
data[:repository] = repository if repository
data[:arch] = arch if arch
content_tag(:div, class: 'flagimage', data: data) do
content_tag(:div, class: "icons-#{image} icon_24") do
content_tag(:div, class: 'hidden flagtoggle') do
out = ''.html_safe
unless flag[1].has_key? :explicit and flag[0] == 'disable'
out += content_tag(:div, class: 'iconwrapper') do
content_tag(:div, '', class: "icons-#{flagname}_disabled_blue icon_24")
end
out += link_to('Explicitly disable', opts, class: 'nowrap flag_trigger', data: { cmd: :set_flag, status: :disable })
end
if flag[0] == 'disable'
out += content_tag(:div, class: 'iconwrapper') do
content_tag(:div, '', class: "icons-#{flagname}_enabled_grey icon_24")
end
out += link_to('Take default', opts, class: 'nowrap flag_trigger', data: { cmd: :remove_flag })
else
out += content_tag(:div, class: 'iconwrapper') do
content_tag(:div, '', class: "icons-#{flagname}_disabled_grey icon_24")
end
out += link_to('Take default', opts, class: 'nowrap flag_trigger', data: { cmd: :remove_flag })
end if flag[1].has_key? :explicit
unless flag[1].has_key? :explicit and flag[0] != 'disable'
out += content_tag(:div, class: 'iconwrapper') do
content_tag(:div, '', class: "icons-#{flagname}_enabled_blue icon_24")
end
out += link_to('Explicitly enable', opts, class: 'nowrap flag_trigger', data: { cmd: :set_flag, status: :enable })
end
out
end
end
end
else
sprite_tag(image, title: title)
end
end
def flag_image(flag, flagname)
suffix = flag[1].has_key?(:explicit) ? 'blue' : 'grey'
if flag[0] == 'disable'
["#{flagname}_disabled_#{suffix}", 'disabled']
else
["#{flagname}_enabled_#{suffix}", 'enabled']
end
end
def determine_most_specific_flag(arch, flags, repository)
flag = nil
flags.each do |status, f|
if f.has_key? :repository
next if f[:repository].to_s != repository
else
next if repository
end
if f.has_key? :arch
next if f[:arch].to_s != arch
else
next if arch
end
flag = [status, f]
break
end
flag
end
def plural(count, singular, plural)
count > 1 ? plural : singular
end
def valid_xml_id(rawid)
rawid = '_' + rawid if rawid !~ /^[A-Za-z_]/ # xs:ID elements have to start with character or '_'
ERB::Util::h(rawid.gsub(/[+&: .\/\~\(\)@#]/, '_'))
end
def tab(id, text, opts)
opts[:package] = @package.to_s if @package
opts[:project] = @project.to_s if @project
link_opts = { id: "tab-#{id}" }
if @current_action.to_s == opts[:action].to_s and @current_controller.to_s == opts[:controller].to_s
link_opts[:class] = 'selected'
end
return content_tag('li', link_to(h(text), opts), link_opts)
end
# Shortens a text if it longer than 'length'.
def elide(text, length = 20, mode = :middle)
shortened_text = text.to_s # make sure it's a String
return '' if text.blank?
return '...' if length <= 3 # corner case
if text.length > length
case mode
when :left # shorten at the beginning
shortened_text = '...' + text[text.length - length + 3 .. text.length]
when :middle # shorten in the middle
pre = text[0 .. length / 2 - 2]
offset = 2 # depends if (shortened) length is even or odd
offset = 1 if length.odd?
post = text[text.length - length / 2 + offset .. text.length]
shortened_text = pre + '...' + post
when :right # shorten at the end
shortened_text = text[0 .. length - 4] + '...'
end
end
return shortened_text
end
def elide_two(text1, text2, overall_length = 40, mode = :middle)
half_length = overall_length / 2
text1_free = half_length - text1.length
text1_free = 0 if text1_free < 0
text2_free = half_length - text2.length
text2_free = 0 if text2_free < 0
return [elide(text1, half_length + text2_free, mode), elide(text2, half_length + text1_free, mode)]
end
def force_utf8_and_transform_nonprintables(text)
text.force_encoding('UTF-8')
unless text.valid_encoding?
text = 'The file you look at is not valid UTF-8 text. Please convert the file.'
end
# Ged rid of stuff that shouldn't be part of PCDATA:
return text.gsub(/([^a-zA-Z0-9&;<>\/\n \t()])/) do
if $1[0].getbyte(0) < 32
''
else
$1
end
end
end
def description_wrapper(description)
if description.blank?
content_tag(:p, id: 'description_text') do
content_tag(:i, 'No description set')
end
else
content_tag(:pre, description, id: 'description_text', class: 'plain')
end
end
def is_advanced_tab?
%w(prjconf index meta status).include? @current_action.to_s
end
def mobile_device?
request.env['mobile_device_type'] == :mobile
end
def sprite_tag(icon, opts = {})
if opts.has_key? :class
opts[:class] += " icons-#{icon}"
else
opts[:class] = "icons-#{icon}"
end
unless opts.has_key? :alt
alt = icon
if opts[:title]
alt = opts[:title]
else
Rails.logger.warn 'No alt/title text for sprite_tag'
end
opts[:alt] = alt
end
image_tag('s.gif', opts)
end
def sprited_text(icon, text)
sprite_tag(icon, title: text) + ' ' + text
end
def next_codemirror_uid
@codemirror_editor_setup = @codemirror_editor_setup + 1
return @codemirror_editor_setup
end
def setup_codemirror_editor(opts = {})
if @codemirror_editor_setup
return next_codemirror_uid
end
@codemirror_editor_setup = 0
opts.reverse_merge!({ read_only: false, no_border: false, width: 'auto' })
content_for(:content_for_head, javascript_include_tag('webui/application/cm2/index'))
style = ''
style += ".CodeMirror {\n"
if opts[:no_border] || opts[:read_only]
style += "border-width: 0 0 0 0;\n"
end
style += "height: #{opts[:height]};\n" unless opts[:height] == 'auto'
style += "width: #{opts[:width]}; \n" unless opts[:width] == 'auto'
style += "}\n"
content_for(:head_style, style)
return @codemirror_editor_setup
end
def remove_dialog_tag(text)
link_to(text, '#', title: 'Close', id: 'remove_dialog')
end
# dialog_init is a function name called before dialog is shown
def render_dialog(dialog_init = nil)
check_ajax
@dialog_html = escape_javascript(render_to_string(partial: @current_action.to_s))
@dialog_init = dialog_init
render partial: 'dialog', content_type: 'application/javascript'
end
# @param [String] user login of the user
# @param [String] role title of the login
# @param [Hash] options boolean flags :short, :no_icon and :no_link
def user_and_role(user, role = nil, options = {})
opt = { short: false, no_icon: false, no_link: false }.merge(options)
realname = User.realname_for_login(user)
output = ''
output += user_icon(user) unless opt[:no_icon]
if !(realname.empty? || opt[:short] == true)
printed_name = realname + ' (' + user + ')'
else
printed_name = user
end
if role
printed_name += ' as ' + role
end
if User.current.is_nobody?
output += printed_name
else
output += link_to_if(!opt[:no_link], printed_name, user_show_path(user))
end
output.html_safe
end
def package_link(pack, opts = {})
opts[:project] = pack.project.name
opts[:package] = pack.name
project_or_package_link opts
end
def link_to_package(prj, pkg, opts)
opts[:project_text] ||= opts[:project]
opts[:package_text] ||= opts[:package]
opts[:project_text], opts[:package_text] =
elide_two(opts[:project_text], opts[:package_text], opts[:trim_to]) unless opts[:trim_to].nil?
if opts[:short]
out = ''.html_safe
else
out = 'package '.html_safe
end
opts[:short] = true # for project
out += link_to_project(prj, opts) + ' / ' +
link_to_if(pkg, opts[:package_text],
{ controller: 'package', action: 'show',
project: opts[:project],
package: opts[:package] }, { class: 'package', title: opts[:package] })
if opts[:rev] && pkg
out += ' ('.html_safe +
link_to("revision #{elide(opts[:rev], 10)}",
{ controller: 'package', action: 'show',
project: opts[:project], package: opts[:package], rev: opts[:rev] },
{ class: 'package', title: opts[:rev] }) + ')'.html_safe
end
out
end
def link_to_project(prj, opts)
opts[:project_text] ||= opts[:project]
if opts[:short]
out = ''.html_safe
else
out = 'project '.html_safe
end
project_text = opts[:trim_to].nil? ? opts[:project_text] : elide(opts[:project_text], opts[:trim_to])
out + link_to_if(prj, project_text,
{ controller: 'project', action: 'show', project: opts[:project] },
{ class: 'project', title: opts[:project] })
end
def project_or_package_link(opts)
defaults = { package: nil, rev: nil, short: false, trim_to: 40 }
opts = defaults.merge(opts)
CacheLine.fetch(['project_or_package_link', opts], project: opts[:project], package: opts[:package]) do
# only care for database entries
prj = Project.where(name: opts[:project]).select(:id, :name).first
if prj && opts[:creator]
opts[:project_text] ||= format_projectname(opts[:project], opts[:creator])
end
if opts[:package] && prj && opts[:package] != :multiple
pkg = prj.packages.where(name: opts[:package]).select(:id, :name, :project_id).first
end
if opts[:package]
link_to_package(prj, pkg, opts)
else
link_to_project(prj, opts)
end
end
end
def user_with_realname_and_icon(user, opts = {})
defaults = { short: false, no_icon: false, no_link: false }
opts = defaults.merge(opts)
user = User.find_by_login(user) unless user.is_a? User
return '' unless user
Rails.cache.fetch([user, 'realname_and_icon', opts, ::Configuration.first]) do
realname = user.realname
if opts[:short] || realname.empty?
printed_name = user.login
else
printed_name = "#{realname} (#{user.login})"
end
user_icon(user) + ' ' + link_to_if(!opts[:no_link], printed_name,
user_show_path(user))
end
end
# If there is any content add the ul tag
def possibly_empty_ul(html_opts, &block)
content = capture(&block)
if content.blank?
html_opts[:fallback]
else
html_opts.delete :fallback
content_tag(:ul, content, html_opts)
end
end
def array_cachekey(array)
Digest::MD5.hexdigest(array.join)
end
def can_register
return true if User.current.try(:is_admin?)
begin
UnregisteredUser.can_register?
rescue APIException
return false
end
return true
end
def escape_nested_list(list)
# The input list is not html_safe
# because it's user input which we
# should never trust!!!
list.map { |item|
"['".html_safe +
escape_javascript(item[0]) +
"', '".html_safe +
escape_javascript(item[1]) +
"']".html_safe
}.join(",\n").html_safe
end
end