agents_exporter.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. class AgentsExporter
  2. attr_accessor :options
  3. def initialize(options)
  4. self.options = options
  5. end
  6. # Filename should have no commas or special characters to support Content-Disposition on older browsers.
  7. def filename
  8. ((options[:name] || '').downcase.gsub(/[^a-z0-9_-]/, '-').gsub(/-+/, '-').gsub(/^-|-$/, '').presence || 'exported-agents') + ".json"
  9. end
  10. def as_json(opts = {})
  11. {
  12. :schema_version => 1,
  13. :name => options[:name].presence || 'No name provided',
  14. :description => options[:description].presence || 'No description provided',
  15. :source_url => options[:source_url],
  16. :guid => options[:guid],
  17. :tag_fg_color => options[:tag_fg_color],
  18. :tag_bg_color => options[:tag_bg_color],
  19. :exported_at => Time.now.utc.iso8601,
  20. :agents => agents.map { |agent| agent_as_json(agent) },
  21. :links => links
  22. }
  23. end
  24. def agents
  25. options[:agents].to_a
  26. end
  27. def links
  28. agent_ids = agents.map(&:id)
  29. contained_links = agents.map.with_index do |agent, index|
  30. agent.links_as_source.where(:receiver_id => agent_ids).map do |link|
  31. { :source => index, :receiver => agent_ids.index(link.receiver_id) }
  32. end
  33. end
  34. contained_links.flatten.compact
  35. end
  36. def agent_as_json(agent)
  37. {
  38. :type => agent.type,
  39. :name => agent.name,
  40. :disabled => agent.disabled,
  41. :guid => agent.guid,
  42. :options => agent.options
  43. }.tap do |options|
  44. options[:schedule] = agent.schedule if agent.can_be_scheduled?
  45. options[:keep_events_for] = agent.keep_events_for if agent.can_create_events?
  46. options[:propagate_immediately] = agent.propagate_immediately if agent.can_receive_events?
  47. end
  48. end
  49. end