agents_exporter.rb 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. :control_links => control_links
  23. }
  24. end
  25. def agents
  26. options[:agents].to_a
  27. end
  28. def links
  29. agent_ids = agents.map(&:id)
  30. contained_links = agents.map.with_index do |agent, index|
  31. agent.links_as_source.where(receiver_id: agent_ids).map do |link|
  32. { source: index, receiver: agent_ids.index(link.receiver_id) }
  33. end
  34. end
  35. contained_links.flatten.compact
  36. end
  37. def control_links
  38. agent_ids = agents.map(&:id)
  39. contained_controller_links = agents.map.with_index do |agent, index|
  40. agent.control_links_as_controller.where(control_target_id: agent_ids).map do |control_link|
  41. { controller: index, control_target: agent_ids.index(control_link.control_target_id) }
  42. end
  43. end
  44. contained_controller_links.flatten.compact
  45. end
  46. def agent_as_json(agent)
  47. {
  48. :type => agent.type,
  49. :name => agent.name,
  50. :disabled => agent.disabled,
  51. :guid => agent.guid,
  52. :options => agent.options
  53. }.tap do |options|
  54. options[:schedule] = agent.schedule if agent.can_be_scheduled?
  55. options[:keep_events_for] = agent.keep_events_for if agent.can_create_events?
  56. options[:propagate_immediately] = agent.propagate_immediately if agent.can_receive_events?
  57. end
  58. end
  59. end