data_output_agent.rb 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. module Agents
  2. class DataOutputAgent < Agent
  3. include WebRequestConcern
  4. cannot_be_scheduled!
  5. description do
  6. <<-MD
  7. The Data Output Agent outputs received events as either RSS or JSON. Use it to output a public or private stream of Huginn data.
  8. This Agent will output data at:
  9. `https://#{ENV['DOMAIN']}#{Rails.application.routes.url_helpers.web_requests_path(agent_id: ':id', user_id: user_id, secret: ':secret', format: :xml)}`
  10. where `:secret` is one of the allowed secrets specified in your options and the extension can be `xml` or `json`.
  11. You can setup multiple secrets so that you can individually authorize external systems to
  12. access your Huginn data.
  13. Options:
  14. * `secrets` - An array of tokens that the requestor must provide for light-weight authentication.
  15. * `expected_receive_period_in_days` - How often you expect data to be received by this Agent from other Agents.
  16. * `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. Values of the `link`, `title`, `description` and `icon` keys will be put into the \\<channel\\> section of RSS output. Value of the `self` key will be used as URL for this feed itself, which is useful when you serve it via reverse proxy. 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.
  17. * `events_to_show` - The number of events to output in RSS or JSON. (default: `40`)
  18. * `ttl` - A value for the \\<ttl\\> element in RSS output. (default: `60`)
  19. * `ns_media` - Add [yahoo media namespace](https://en.wikipedia.org/wiki/Media_RSS) in output xml
  20. * `ns_itunes` - Add [itunes compatible namespace](http://lists.apple.com/archives/syndication-dev/2005/Nov/msg00002.html) in output xml
  21. * `push_hubs` - Set to a list of PubSubHubbub endpoints you want to publish an update to every time this agent receives an event. (default: none) Popular hubs include [Superfeedr](https://pubsubhubbub.superfeedr.com/) and [Google](https://pubsubhubbub.appspot.com/). Note that publishing updates will make your feed URL known to the public, so if you want to keep it secret, set up a reverse proxy to serve your feed via a safe URL and specify it in `template.self`.
  22. If you'd like to output RSS tags with attributes, such as `enclosure`, use something like the following in your `template`:
  23. "enclosure": {
  24. "_attributes": {
  25. "url": "{{media_url}}",
  26. "length": "1234456789",
  27. "type": "audio/mpeg"
  28. }
  29. },
  30. "another_tag": {
  31. "_attributes": {
  32. "key": "value",
  33. "another_key": "another_value"
  34. },
  35. "_contents": "tag contents (can be an object for nesting)"
  36. }
  37. # Ordering events in the output
  38. #{description_events_order('events in the output')}
  39. # Liquid Templating
  40. In Liquid templating, the following variable is available:
  41. * `events`: An array of events being output, sorted in the given order, up to `events_to_show` in number. For example, if source events contain a site title in the `site_title` key, you can refer to it in `template.title` by putting `{{events.first.site_title}}`.
  42. MD
  43. end
  44. def default_options
  45. {
  46. "secrets" => ["a-secret-key"],
  47. "expected_receive_period_in_days" => 2,
  48. "template" => {
  49. "title" => "XKCD comics as a feed",
  50. "description" => "This is a feed of recent XKCD comics, generated by Huginn",
  51. "item" => {
  52. "title" => "{{title}}",
  53. "description" => "Secret hovertext: {{hovertext}}",
  54. "link" => "{{url}}"
  55. }
  56. },
  57. "ns_media" => "true"
  58. }
  59. end
  60. def working?
  61. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  62. end
  63. def validate_options
  64. if options['secrets'].is_a?(Array) && options['secrets'].length > 0
  65. options['secrets'].each do |secret|
  66. case secret
  67. when %r{[/.]}
  68. errors.add(:base, "secret may not contain a slash or dot")
  69. when String
  70. else
  71. errors.add(:base, "secret must be a string")
  72. end
  73. end
  74. else
  75. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  76. end
  77. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  78. 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")
  79. end
  80. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  81. errors.add(:base, "Please provide template and template.item")
  82. end
  83. case options['push_hubs']
  84. when nil
  85. when Array
  86. options['push_hubs'].each do |hub|
  87. case hub
  88. when /\{/
  89. # Liquid templating
  90. when String
  91. begin
  92. URI.parse(hub)
  93. rescue URI::Error
  94. errors.add(:base, "invalid URL found in push_hubs")
  95. break
  96. end
  97. else
  98. errors.add(:base, "push_hubs must be an array of endpoint URLs")
  99. break
  100. end
  101. end
  102. else
  103. errors.add(:base, "push_hubs must be an array")
  104. end
  105. end
  106. def events_to_show
  107. (interpolated['events_to_show'].presence || 40).to_i
  108. end
  109. def feed_ttl
  110. (interpolated['ttl'].presence || 60).to_i
  111. end
  112. def feed_title
  113. interpolated['template']['title'].presence || "#{name} Event Feed"
  114. end
  115. def feed_link
  116. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  117. end
  118. def feed_url(options = {})
  119. interpolated['template']['self'].presence ||
  120. feed_link + Rails.application.routes.url_helpers.
  121. web_requests_path(agent_id: id || ':id',
  122. user_id: user_id,
  123. secret: options[:secret],
  124. format: options[:format])
  125. end
  126. def feed_icon
  127. interpolated['template']['icon'].presence || feed_link + '/favicon.ico'
  128. end
  129. def feed_description
  130. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  131. end
  132. def xml_namespace
  133. namespaces = ['xmlns:atom="http://www.w3.org/2005/Atom"']
  134. if (boolify(interpolated['ns_media']))
  135. namespaces << 'xmlns:media="http://search.yahoo.com/mrss/"'
  136. end
  137. if (boolify(interpolated['ns_itunes']))
  138. namespaces << 'xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"'
  139. end
  140. namespaces.join(' ')
  141. end
  142. def push_hubs
  143. interpolated['push_hubs'].presence || []
  144. end
  145. def receive_web_request(params, method, format)
  146. unless interpolated['secrets'].include?(params['secret'])
  147. if format =~ /json/
  148. return [{ error: "Not Authorized" }, 401]
  149. else
  150. return ["Not Authorized", 401]
  151. end
  152. end
  153. source_events = sort_events(received_events.order(id: :desc).limit(events_to_show).to_a)
  154. interpolation_context.stack do
  155. interpolation_context['events'] = source_events
  156. items = source_events.map do |event|
  157. interpolated = interpolate_options(options['template']['item'], event)
  158. interpolated['guid'] = {'_attributes' => {'isPermaLink' => 'false'},
  159. '_contents' => interpolated['guid'].presence || event.id}
  160. date_string = interpolated['pubDate'].to_s
  161. date =
  162. begin
  163. Time.zone.parse(date_string) # may return nil
  164. rescue => e
  165. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  166. nil
  167. end || event.created_at
  168. interpolated['pubDate'] = date.rfc2822.to_s
  169. interpolated
  170. end
  171. now = Time.now
  172. if format =~ /json/
  173. content = {
  174. 'title' => feed_title,
  175. 'description' => feed_description,
  176. 'pubDate' => now,
  177. 'items' => simplify_item_for_json(items)
  178. }
  179. return [content, 200]
  180. else
  181. hub_links = push_hubs.map { |hub|
  182. <<-XML
  183. <atom:link rel="hub" href=#{hub.encode(xml: :attr)}/>
  184. XML
  185. }.join
  186. items = simplify_item_for_xml(items)
  187. .to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1)
  188. .gsub(%r{^</?items>\n}, '')
  189. return [<<-XML, 200, 'text/xml']
  190. <?xml version="1.0" encoding="UTF-8" ?>
  191. <rss version="2.0" #{xml_namespace}>
  192. <channel>
  193. <atom:link href=#{feed_url(secret: params['secret'], format: :xml).encode(xml: :attr)} rel="self" type="application/rss+xml" />
  194. <atom:icon>#{feed_icon.encode(xml: :text)}</atom:icon>
  195. #{hub_links}
  196. <title>#{feed_title.encode(xml: :text)}</title>
  197. <description>#{feed_description.encode(xml: :text)}</description>
  198. <link>#{feed_link.encode(xml: :text)}</link>
  199. <lastBuildDate>#{now.rfc2822.to_s.encode(xml: :text)}</lastBuildDate>
  200. <pubDate>#{now.rfc2822.to_s.encode(xml: :text)}</pubDate>
  201. <ttl>#{feed_ttl}</ttl>
  202. #{items}
  203. </channel>
  204. </rss>
  205. XML
  206. end
  207. end
  208. end
  209. def receive(incoming_events)
  210. url = feed_url(secret: interpolated['secrets'].first, format: :xml)
  211. push_hubs.each do |hub|
  212. push_to_hub(hub, url)
  213. end
  214. end
  215. private
  216. class XMLNode
  217. def initialize(tag_name, attributes, contents)
  218. @tag_name, @attributes, @contents = tag_name, attributes, contents
  219. end
  220. def to_xml(options)
  221. if @contents.is_a?(Hash)
  222. options[:builder].tag! @tag_name, @attributes do
  223. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  224. end
  225. else
  226. options[:builder].tag! @tag_name, @attributes, @contents
  227. end
  228. end
  229. end
  230. def simplify_item_for_xml(item)
  231. if item.is_a?(Hash)
  232. item.each.with_object({}) do |(key, value), memo|
  233. if value.is_a?(Hash)
  234. if value.key?('_attributes') || value.key?('_contents')
  235. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  236. else
  237. memo[key] = simplify_item_for_xml(value)
  238. end
  239. else
  240. memo[key] = value
  241. end
  242. end
  243. elsif item.is_a?(Array)
  244. item.map { |value| simplify_item_for_xml(value) }
  245. else
  246. item
  247. end
  248. end
  249. def simplify_item_for_json(item)
  250. if item.is_a?(Hash)
  251. item.each.with_object({}) do |(key, value), memo|
  252. if value.is_a?(Hash)
  253. if value.key?('_attributes') || value.key?('_contents')
  254. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  255. simplify_item_for_json(value['_contents'])
  256. elsif value['_contents']
  257. { "contents" => value['_contents'] }
  258. else
  259. {}
  260. end
  261. memo[key] = contents.merge(value['_attributes'] || {})
  262. else
  263. memo[key] = simplify_item_for_json(value)
  264. end
  265. else
  266. memo[key] = value
  267. end
  268. end
  269. elsif item.is_a?(Array)
  270. item.map { |value| simplify_item_for_json(value) }
  271. else
  272. item
  273. end
  274. end
  275. def push_to_hub(hub, url)
  276. hub_uri =
  277. begin
  278. URI.parse(hub)
  279. rescue URI::Error
  280. nil
  281. end
  282. if !hub_uri.is_a?(URI::HTTP)
  283. error "Invalid push endpoint: #{hub}"
  284. return
  285. end
  286. log "Pushing #{url} to #{hub_uri}"
  287. return if dry_run?
  288. begin
  289. faraday.post hub_uri, {
  290. 'hub.mode' => 'publish',
  291. 'hub.url' => url
  292. }
  293. rescue => e
  294. error "Push failed: #{e.message}"
  295. end
  296. end
  297. end
  298. end