data_output_agent.rb 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. unless options['secrets'].is_a?(Array) && options['secrets'].length > 0
  55. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  56. end
  57. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  58. 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")
  59. end
  60. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  61. errors.add(:base, "Please provide template and template.item")
  62. end
  63. end
  64. def events_to_show
  65. (interpolated['events_to_show'].presence || 40).to_i
  66. end
  67. def feed_ttl
  68. (interpolated['ttl'].presence || 60).to_i
  69. end
  70. def feed_title
  71. interpolated['template']['title'].presence || "#{name} Event Feed"
  72. end
  73. def feed_link
  74. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  75. end
  76. def feed_description
  77. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  78. end
  79. def receive_web_request(params, method, format)
  80. if interpolated['secrets'].include?(params['secret'])
  81. items = received_events.order('id desc').limit(events_to_show).map do |event|
  82. interpolated = interpolate_options(options['template']['item'], event)
  83. interpolated['guid'] = {'_attributes' => {'isPermaLink' => 'false'},
  84. '_contents' => interpolated['guid'].presence || event.id}
  85. date_string = interpolated['pubDate'].to_s
  86. date =
  87. begin
  88. Time.zone.parse(date_string) # may return nil
  89. rescue => e
  90. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  91. nil
  92. end || event.created_at
  93. interpolated['pubDate'] = date.rfc2822.to_s
  94. interpolated
  95. end
  96. if format =~ /json/
  97. content = {
  98. 'title' => feed_title,
  99. 'description' => feed_description,
  100. 'pubDate' => Time.now,
  101. 'items' => simplify_item_for_json(items)
  102. }
  103. return [content, 200]
  104. else
  105. content = Utils.unindent(<<-XML)
  106. <?xml version="1.0" encoding="UTF-8" ?>
  107. <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  108. <channel>
  109. <atom:link href="#{feed_link.encode(:xml => :text)}/users/#{user.id}/web_requests/#{id || '<id>'}/#{params['secret']}.xml" rel="self" type="application/rss+xml" />
  110. <title>#{feed_title.encode(:xml => :text)}</title>
  111. <description>#{feed_description.encode(:xml => :text)}</description>
  112. <link>#{feed_link.encode(:xml => :text)}</link>
  113. <lastBuildDate>#{Time.now.rfc2822.to_s.encode(:xml => :text)}</lastBuildDate>
  114. <pubDate>#{Time.now.rfc2822.to_s.encode(:xml => :text)}</pubDate>
  115. <ttl>#{feed_ttl}</ttl>
  116. XML
  117. content += simplify_item_for_xml(items).to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1).gsub(/^<\/?items>/, '').strip
  118. content += Utils.unindent(<<-XML)
  119. </channel>
  120. </rss>
  121. XML
  122. return [content, 200, 'text/xml']
  123. end
  124. else
  125. if format =~ /json/
  126. return [{ :error => "Not Authorized" }, 401]
  127. else
  128. return ["Not Authorized", 401]
  129. end
  130. end
  131. end
  132. private
  133. class XMLNode
  134. def initialize(tag_name, attributes, contents)
  135. @tag_name, @attributes, @contents = tag_name, attributes, contents
  136. end
  137. def to_xml(options)
  138. if @contents.is_a?(Hash)
  139. options[:builder].tag! @tag_name, @attributes do
  140. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  141. end
  142. else
  143. options[:builder].tag! @tag_name, @attributes, @contents
  144. end
  145. end
  146. end
  147. def simplify_item_for_xml(item)
  148. if item.is_a?(Hash)
  149. item.each.with_object({}) do |(key, value), memo|
  150. if value.is_a?(Hash)
  151. if value.key?('_attributes') || value.key?('_contents')
  152. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  153. else
  154. memo[key] = simplify_item_for_xml(value)
  155. end
  156. else
  157. memo[key] = value
  158. end
  159. end
  160. elsif item.is_a?(Array)
  161. item.map { |value| simplify_item_for_xml(value) }
  162. else
  163. item
  164. end
  165. end
  166. def simplify_item_for_json(item)
  167. if item.is_a?(Hash)
  168. item.each.with_object({}) do |(key, value), memo|
  169. if value.is_a?(Hash)
  170. if value.key?('_attributes') || value.key?('_contents')
  171. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  172. simplify_item_for_json(value['_contents'])
  173. elsif value['_contents']
  174. { "contents" => value['_contents'] }
  175. else
  176. {}
  177. end
  178. memo[key] = contents.merge(value['_attributes'] || {})
  179. else
  180. memo[key] = simplify_item_for_json(value)
  181. end
  182. else
  183. memo[key] = value
  184. end
  185. end
  186. elsif item.is_a?(Array)
  187. item.map { |value| simplify_item_for_json(value) }
  188. else
  189. item
  190. end
  191. end
  192. end
  193. end