agents_exporter.rb 2.1 KB

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