data_output_agent.rb 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. module Agents
  2. class DataOutputAgent < Agent
  3. cannot_be_scheduled!
  4. description do
  5. <<-MD
  6. The Agent outputs received events as either RSS or JSON. Use it to output a public or private stream of Huginn data.
  7. This Agent will output data at:
  8. `https://#{ENV['DOMAIN']}/users/#{user.id}/web_requests/#{id || '<id>'}/:secret.xml`
  9. where `:secret` is one of the allowed secrets specified in your options and the extension can be `xml` or `json`.
  10. You can setup multiple secrets so that you can individually authorize external systems to
  11. access your Huginn data.
  12. Options:
  13. * `secrets` - An array of tokens that the requestor must provide for light-weight authentication.
  14. * `expected_receive_period_in_days` - How often you expect data to be received by this Agent from other Agents.
  15. * `template` - A JSON object representing a mapping between item output keys and incoming event values. Use [Liquid](https://github.com/cantino/huginn/wiki/Formatting-Events-using-Liquid) to format the values. The `item` key will be repeated for every Event. The `pubDate` key for each item will have the creation time of the Event unless given.
  16. * `events_to_show` - The number of events to output in RSS or JSON. (default: `40`)
  17. * `ttl` - A value for the <ttl> element in RSS output. (default: `60`)
  18. If you'd like to output RSS tags with attributes, such as `enclosure`, use something like the following in your `template`:
  19. "enclosure": {
  20. "_attributes": {
  21. "url": "{{media_url}}",
  22. "length": "1234456789",
  23. "type": "audio/mpeg"
  24. }
  25. },
  26. "another_tag": {
  27. "_attributes": {
  28. "key": "value",
  29. "another_key": "another_value"
  30. },
  31. "_contents": "tag contents (can be an object for nesting)"
  32. }
  33. MD
  34. end
  35. def default_options
  36. {
  37. "secrets" => ["a-secret-key"],
  38. "expected_receive_period_in_days" => 2,
  39. "template" => {
  40. "title" => "XKCD comics as a feed",
  41. "description" => "This is a feed of recent XKCD comics, generated by Huginn",
  42. "item" => {
  43. "title" => "{{title}}",
  44. "description" => "Secret hovertext: {{hovertext}}",
  45. "link" => "{{url}}"
  46. }
  47. }
  48. }
  49. end
  50. def working?
  51. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  52. end
  53. def validate_options
  54. if options['secrets'].is_a?(Array) && options['secrets'].length > 0
  55. options['secrets'].each do |secret|
  56. case secret
  57. when %r{[/.]}
  58. errors.add(:base, "secret may not contain a slash or dot")
  59. when String
  60. else
  61. errors.add(:base, "secret must be a string")
  62. end
  63. end
  64. else
  65. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  66. end
  67. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  68. errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working")
  69. end
  70. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  71. errors.add(:base, "Please provide template and template.item")
  72. end
  73. end
  74. def events_to_show
  75. (interpolated['events_to_show'].presence || 40).to_i
  76. end
  77. def feed_ttl
  78. (interpolated['ttl'].presence || 60).to_i
  79. end
  80. def feed_title
  81. interpolated['template']['title'].presence || "#{name} Event Feed"
  82. end
  83. def feed_link
  84. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  85. end
  86. def feed_url(options = {})
  87. feed_link + Rails.application.routes.url_helpers.
  88. web_requests_path(agent_id: id || '<id>',
  89. user_id: user_id,
  90. secret: options[:secret],
  91. format: options[:format])
  92. end
  93. def feed_description
  94. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  95. end
  96. def receive_web_request(params, method, format)
  97. if interpolated['secrets'].include?(params['secret'])
  98. items = received_events.order('id desc').limit(events_to_show).map do |event|
  99. interpolated = interpolate_options(options['template']['item'], event)
  100. interpolated['guid'] = {'_attributes' => {'isPermaLink' => 'false'},
  101. '_contents' => interpolated['guid'].presence || event.id}
  102. date_string = interpolated['pubDate'].to_s
  103. date =
  104. begin
  105. Time.zone.parse(date_string) # may return nil
  106. rescue => e
  107. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  108. nil
  109. end || event.created_at
  110. interpolated['pubDate'] = date.rfc2822.to_s
  111. interpolated
  112. end
  113. if format =~ /json/
  114. content = {
  115. 'title' => feed_title,
  116. 'description' => feed_description,
  117. 'pubDate' => Time.now,
  118. 'items' => simplify_item_for_json(items)
  119. }
  120. return [content, 200]
  121. else
  122. content = Utils.unindent(<<-XML)
  123. <?xml version="1.0" encoding="UTF-8" ?>
  124. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  125. <channel>
  126. <atom:link href=#{feed_url(secret: params['secret'], format: :xml).encode(xml: :attr)} rel="self" type="application/rss+xml" />
  127. <title>#{feed_title.encode(xml: :text)}</title>
  128. <description>#{feed_description.encode(xml: :text)}</description>
  129. <link>#{feed_link.encode(xml: :text)}</link>
  130. <lastBuildDate>#{Time.now.rfc2822.to_s.encode(xml: :text)}</lastBuildDate>
  131. <pubDate>#{Time.now.rfc2822.to_s.encode(xml: :text)}</pubDate>
  132. <ttl>#{feed_ttl}</ttl>
  133. XML
  134. content += simplify_item_for_xml(items).to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1).gsub(/^<\/?items>/, '').strip
  135. content += Utils.unindent(<<-XML)
  136. </channel>
  137. </rss>
  138. XML
  139. return [content, 200, 'text/xml']
  140. end
  141. else
  142. if format =~ /json/
  143. return [{ error: "Not Authorized" }, 401]
  144. else
  145. return ["Not Authorized", 401]
  146. end
  147. end
  148. end
  149. private
  150. class XMLNode
  151. def initialize(tag_name, attributes, contents)
  152. @tag_name, @attributes, @contents = tag_name, attributes, contents
  153. end
  154. def to_xml(options)
  155. if @contents.is_a?(Hash)
  156. options[:builder].tag! @tag_name, @attributes do
  157. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  158. end
  159. else
  160. options[:builder].tag! @tag_name, @attributes, @contents
  161. end
  162. end
  163. end
  164. def simplify_item_for_xml(item)
  165. if item.is_a?(Hash)
  166. item.each.with_object({}) do |(key, value), memo|
  167. if value.is_a?(Hash)
  168. if value.key?('_attributes') || value.key?('_contents')
  169. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  170. else
  171. memo[key] = simplify_item_for_xml(value)
  172. end
  173. else
  174. memo[key] = value
  175. end
  176. end
  177. elsif item.is_a?(Array)
  178. item.map { |value| simplify_item_for_xml(value) }
  179. else
  180. item
  181. end
  182. end
  183. def simplify_item_for_json(item)
  184. if item.is_a?(Hash)
  185. item.each.with_object({}) do |(key, value), memo|
  186. if value.is_a?(Hash)
  187. if value.key?('_attributes') || value.key?('_contents')
  188. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  189. simplify_item_for_json(value['_contents'])
  190. elsif value['_contents']
  191. { "contents" => value['_contents'] }
  192. else
  193. {}
  194. end
  195. memo[key] = contents.merge(value['_attributes'] || {})
  196. else
  197. memo[key] = simplify_item_for_json(value)
  198. end
  199. else
  200. memo[key] = value
  201. end
  202. end
  203. elsif item.is_a?(Array)
  204. item.map { |value| simplify_item_for_json(value) }
  205. else
  206. item
  207. end
  208. end
  209. end
  210. end