1
0

data_output_agent.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. module Agents
  2. class DataOutputAgent < Agent
  3. include WebRequestConcern
  4. cannot_be_scheduled!
  5. cannot_create_events!
  6. description do
  7. <<-MD
  8. The Data Output Agent outputs received events as either RSS or JSON. Use it to output a public or private stream of Huginn data.
  9. This Agent will output data at:
  10. `https://#{ENV['DOMAIN']}#{Rails.application.routes.url_helpers.web_requests_path(agent_id: ':id', user_id: user_id, secret: ':secret', format: :xml)}`
  11. where `:secret` is one of the allowed secrets specified in your options and the extension can be `xml` or `json`.
  12. You can setup multiple secrets so that you can individually authorize external systems to
  13. access your Huginn data.
  14. Options:
  15. * `secrets` - An array of tokens that the requestor must provide for light-weight authentication.
  16. * `expected_receive_period_in_days` - How often you expect data to be received by this Agent from other Agents.
  17. * `template` - A JSON object representing a mapping between item output keys and incoming event values. Use [Liquid](https://github.com/huginn/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.
  18. * `events_to_show` - The number of events to output in RSS or JSON. (default: `40`)
  19. * `ttl` - A value for the \\<ttl\\> element in RSS output. (default: `60`)
  20. * `ns_media` - Add [yahoo media namespace](https://en.wikipedia.org/wiki/Media_RSS) in output xml
  21. * `ns_itunes` - Add [itunes compatible namespace](http://lists.apple.com/archives/syndication-dev/2005/Nov/msg00002.html) in output xml
  22. * `rss_content_type` - Content-Type for RSS output (default: `application/rss+xml`)
  23. * `response_headers` - An object with any custom response headers. (example: `{"Access-Control-Allow-Origin": "*"}`)
  24. * `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`.
  25. If you'd like to output RSS tags with attributes, such as `enclosure`, use something like the following in your `template`:
  26. "enclosure": {
  27. "_attributes": {
  28. "url": "{{media_url}}",
  29. "length": "1234456789",
  30. "type": "audio/mpeg"
  31. }
  32. },
  33. "another_tag": {
  34. "_attributes": {
  35. "key": "value",
  36. "another_key": "another_value"
  37. },
  38. "_contents": "tag contents (can be an object for nesting)"
  39. }
  40. # Ordering events
  41. #{description_events_order('events')}
  42. DataOutputAgent will select the last `events_to_show` entries of its received events sorted in the order specified by `events_order`, which is defaulted to the event creation time.
  43. So, if you have multiple source agents that may create many events in a run, you may want to either increase `events_to_show` to have a larger "window", or specify the `events_order` option to an appropriate value (like `date_published`) so events from various sources are properly mixed in the resulted feed.
  44. There is also an option `events_list_order` that only controls the order of events listed in the final output, without attempting to maintain a total order of received events. It has the same format as `events_order` and is defaulted to `#{Utils.jsonify(DEFAULT_EVENTS_ORDER['events_list_order'])}` so the selected events are listed in reverse order like most popular RSS feeds list their articles.
  45. # Liquid Templating
  46. In [Liquid](https://github.com/huginn/huginn/wiki/Formatting-Events-using-Liquid) templating, the following variable is available:
  47. * `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}}`.
  48. MD
  49. end
  50. def default_options
  51. {
  52. "secrets" => ["a-secret-key"],
  53. "expected_receive_period_in_days" => 2,
  54. "template" => {
  55. "title" => "XKCD comics as a feed",
  56. "description" => "This is a feed of recent XKCD comics, generated by Huginn",
  57. "item" => {
  58. "title" => "{{title}}",
  59. "description" => "Secret hovertext: {{hovertext}}",
  60. "link" => "{{url}}"
  61. }
  62. },
  63. "ns_media" => "true"
  64. }
  65. end
  66. def working?
  67. last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
  68. end
  69. def validate_options
  70. if options['secrets'].is_a?(Array) && options['secrets'].length > 0
  71. options['secrets'].each do |secret|
  72. case secret
  73. when %r{[/.]}
  74. errors.add(:base, "secret may not contain a slash or dot")
  75. when String
  76. else
  77. errors.add(:base, "secret must be a string")
  78. end
  79. end
  80. else
  81. errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
  82. end
  83. unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
  84. 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")
  85. end
  86. unless options['template'].present? && options['template']['item'].present? && options['template']['item'].is_a?(Hash)
  87. errors.add(:base, "Please provide template and template.item")
  88. end
  89. case options['push_hubs']
  90. when nil
  91. when Array
  92. options['push_hubs'].each do |hub|
  93. case hub
  94. when /\{/
  95. # Liquid templating
  96. when String
  97. begin
  98. URI.parse(hub)
  99. rescue URI::Error
  100. errors.add(:base, "invalid URL found in push_hubs")
  101. break
  102. end
  103. else
  104. errors.add(:base, "push_hubs must be an array of endpoint URLs")
  105. break
  106. end
  107. end
  108. else
  109. errors.add(:base, "push_hubs must be an array")
  110. end
  111. end
  112. def events_to_show
  113. (interpolated['events_to_show'].presence || 40).to_i
  114. end
  115. def feed_ttl
  116. (interpolated['ttl'].presence || 60).to_i
  117. end
  118. def feed_title
  119. interpolated['template']['title'].presence || "#{name} Event Feed"
  120. end
  121. def feed_link
  122. interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
  123. end
  124. def feed_url(options = {})
  125. interpolated['template']['self'].presence ||
  126. feed_link + Rails.application.routes.url_helpers.
  127. web_requests_path(agent_id: id || ':id',
  128. user_id: user_id,
  129. secret: options[:secret],
  130. format: options[:format])
  131. end
  132. def feed_icon
  133. interpolated['template']['icon'].presence || feed_link + '/favicon.ico'
  134. end
  135. def itunes_icon
  136. if(boolify(interpolated['ns_itunes']))
  137. "<itunes:image href=#{feed_icon.encode(xml: :attr)} />"
  138. end
  139. end
  140. def feed_description
  141. interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
  142. end
  143. def rss_content_type
  144. interpolated['rss_content_type'].presence || 'application/rss+xml'
  145. end
  146. def xml_namespace
  147. namespaces = ['xmlns:atom="http://www.w3.org/2005/Atom"']
  148. if (boolify(interpolated['ns_media']))
  149. namespaces << 'xmlns:media="http://search.yahoo.com/mrss/"'
  150. end
  151. if (boolify(interpolated['ns_itunes']))
  152. namespaces << 'xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"'
  153. end
  154. namespaces.join(' ')
  155. end
  156. def push_hubs
  157. interpolated['push_hubs'].presence || []
  158. end
  159. DEFAULT_EVENTS_ORDER = {
  160. 'events_order' => nil,
  161. 'events_list_order' => [["{{_index_}}", "number", true]],
  162. }
  163. def events_order(key = SortableEvents::EVENTS_ORDER_KEY)
  164. super || DEFAULT_EVENTS_ORDER[key]
  165. end
  166. def latest_events(reload = false)
  167. received_events = received_events().reorder(id: :asc)
  168. events =
  169. if (event_ids = memory[:event_ids]) &&
  170. memory[:events_order] == events_order &&
  171. memory[:events_to_show] >= events_to_show
  172. received_events.where(id: event_ids).to_a
  173. else
  174. memory[:last_event_id] = nil
  175. reload = true
  176. []
  177. end
  178. if reload
  179. memory[:events_order] = events_order
  180. memory[:events_to_show] = events_to_show
  181. new_events =
  182. if last_event_id = memory[:last_event_id]
  183. received_events.where(Event.arel_table[:id].gt(last_event_id)).to_a
  184. else
  185. source_ids.flat_map { |source_id|
  186. # dig twice as many events as the number of
  187. # `events_to_show`
  188. received_events.where(agent_id: source_id).
  189. last(2 * events_to_show)
  190. }.sort_by(&:id)
  191. end
  192. unless new_events.empty?
  193. memory[:last_event_id] = new_events.last.id
  194. events.concat(new_events)
  195. end
  196. end
  197. events = sort_events(events).last(events_to_show)
  198. if reload
  199. memory[:event_ids] = events.map(&:id)
  200. end
  201. events
  202. end
  203. def receive_web_request(params, method, format)
  204. unless interpolated['secrets'].include?(params['secret'])
  205. if format =~ /json/
  206. return [{ error: "Not Authorized" }, 401]
  207. else
  208. return ["Not Authorized", 401]
  209. end
  210. end
  211. source_events = sort_events(latest_events(), 'events_list_order')
  212. interpolate_with('events' => source_events) do
  213. items = source_events.map do |event|
  214. interpolated = interpolate_options(options['template']['item'], event)
  215. interpolated['guid'] = {'_attributes' => {'isPermaLink' => 'false'},
  216. '_contents' => interpolated['guid'].presence || event.id}
  217. date_string = interpolated['pubDate'].to_s
  218. date =
  219. begin
  220. Time.zone.parse(date_string) # may return nil
  221. rescue => e
  222. error "Error parsing a \"pubDate\" value \"#{date_string}\": #{e.message}"
  223. nil
  224. end || event.created_at
  225. interpolated['pubDate'] = date.rfc2822.to_s
  226. interpolated
  227. end
  228. now = Time.now
  229. if format =~ /json/
  230. content = {
  231. 'title' => feed_title,
  232. 'description' => feed_description,
  233. 'pubDate' => now,
  234. 'items' => simplify_item_for_json(items)
  235. }
  236. return [content, 200, "application/json", interpolated['response_headers'].presence]
  237. else
  238. hub_links = push_hubs.map { |hub|
  239. <<-XML
  240. <atom:link rel="hub" href=#{hub.encode(xml: :attr)}/>
  241. XML
  242. }.join
  243. items = items_to_xml(items)
  244. return [<<-XML, 200, rss_content_type, interpolated['response_headers'].presence]
  245. <?xml version="1.0" encoding="UTF-8" ?>
  246. <rss version="2.0" #{xml_namespace}>
  247. <channel>
  248. <atom:link href=#{feed_url(secret: params['secret'], format: :xml).encode(xml: :attr)} rel="self" type="application/rss+xml" />
  249. <atom:icon>#{feed_icon.encode(xml: :text)}</atom:icon>
  250. #{itunes_icon}
  251. #{hub_links}
  252. <title>#{feed_title.encode(xml: :text)}</title>
  253. <description>#{feed_description.encode(xml: :text)}</description>
  254. <link>#{feed_link.encode(xml: :text)}</link>
  255. <lastBuildDate>#{now.rfc2822.to_s.encode(xml: :text)}</lastBuildDate>
  256. <pubDate>#{now.rfc2822.to_s.encode(xml: :text)}</pubDate>
  257. <ttl>#{feed_ttl}</ttl>
  258. #{items}
  259. </channel>
  260. </rss>
  261. XML
  262. end
  263. end
  264. end
  265. def receive(incoming_events)
  266. url = feed_url(secret: interpolated['secrets'].first, format: :xml)
  267. # Reload new events and update cache
  268. latest_events(true)
  269. push_hubs.each do |hub|
  270. push_to_hub(hub, url)
  271. end
  272. end
  273. private
  274. class XMLNode
  275. def initialize(tag_name, attributes, contents)
  276. @tag_name, @attributes, @contents = tag_name, attributes, contents
  277. end
  278. def to_xml(options)
  279. if @contents.is_a?(Hash)
  280. options[:builder].tag! @tag_name, @attributes do
  281. @contents.each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options.merge(skip_instruct: true)) }
  282. end
  283. else
  284. options[:builder].tag! @tag_name, @attributes, @contents
  285. end
  286. end
  287. end
  288. def simplify_item_for_xml(item)
  289. if item.is_a?(Hash)
  290. item.each.with_object({}) do |(key, value), memo|
  291. if value.is_a?(Hash)
  292. if value.key?('_attributes') || value.key?('_contents')
  293. memo[key] = XMLNode.new(key, value['_attributes'], simplify_item_for_xml(value['_contents']))
  294. else
  295. memo[key] = simplify_item_for_xml(value)
  296. end
  297. else
  298. memo[key] = value
  299. end
  300. end
  301. elsif item.is_a?(Array)
  302. item.map { |value| simplify_item_for_xml(value) }
  303. else
  304. item
  305. end
  306. end
  307. def simplify_item_for_json(item)
  308. if item.is_a?(Hash)
  309. item.each.with_object({}) do |(key, value), memo|
  310. if value.is_a?(Hash)
  311. if value.key?('_attributes') || value.key?('_contents')
  312. contents = if value['_contents'] && value['_contents'].is_a?(Hash)
  313. simplify_item_for_json(value['_contents'])
  314. elsif value['_contents']
  315. { "contents" => value['_contents'] }
  316. else
  317. {}
  318. end
  319. memo[key] = contents.merge(value['_attributes'] || {})
  320. else
  321. memo[key] = simplify_item_for_json(value)
  322. end
  323. else
  324. memo[key] = value
  325. end
  326. end
  327. elsif item.is_a?(Array)
  328. item.map { |value| simplify_item_for_json(value) }
  329. else
  330. item
  331. end
  332. end
  333. def items_to_xml(items)
  334. simplify_item_for_xml(items)
  335. .to_xml(skip_types: true, root: "items", skip_instruct: true, indent: 1)
  336. .gsub(%r{
  337. (?<indent> ^\ + ) < (?<tagname> [^> ]+ ) > \n
  338. (?<children>
  339. (?: \k<indent> \ < \k<tagname> (?:\ [^>]*)? > [^<>]*? </ \k<tagname> > \n )+
  340. )
  341. \k<indent> </ \k<tagname> > \n
  342. }mx) { $~[:children].gsub(/^ /, '') } # delete redundant nesting of array elements
  343. .gsub(%r{
  344. (?<indent> ^\ + ) < [^> ]+ /> \n
  345. }mx, '') # delete empty elements
  346. .gsub(%r{^</?items>\n}, '')
  347. end
  348. def push_to_hub(hub, url)
  349. hub_uri =
  350. begin
  351. URI.parse(hub)
  352. rescue URI::Error
  353. nil
  354. end
  355. if !hub_uri.is_a?(URI::HTTP)
  356. error "Invalid push endpoint: #{hub}"
  357. return
  358. end
  359. log "Pushing #{url} to #{hub_uri}"
  360. return if dry_run?
  361. begin
  362. faraday.post hub_uri, {
  363. 'hub.mode' => 'publish',
  364. 'hub.url' => url
  365. }
  366. rescue => e
  367. error "Push failed: #{e.message}"
  368. end
  369. end
  370. end
  371. end