#!/usr/local/bin/ruby

require 'httparty'
require 'feedjira'

def slugify(str)
  str.ljust(100).strip.gsub(/[\s\t\r\n\f]/,'_').gsub(/\W/,'').downcase
end

def fixhtml(content)
  content.gsub!(/<img /, '<img loading="lazy" ')
  content.gsub!(/<iframe.+?<\/iframe>/, '')
  content.gsub(/<script.+?<\/script>/, '')
end

file = File.open("getfeeds.conf")
uris = file.readlines.map.each { |line| line.chomp() }
file.close

feeds = []
max   = 5

uris.each do |uri|
  begin
    xml = HTTParty.get(uri).body
    feed = Feedjira.parse(xml)

    pos = 0
    feed.entries.each do |entry|
      if pos < max then
        feeds.push(entry)
        pos += 1
      else
        break
      end
    end
  rescue StandardError => e
    puts e.inspect
  end
end

index = File.open("river/index.html", "w")
index.write("---\ntitle: River\nlayout: default\n---\n\n")
pos = 0
nextv = 0

feeds.sort_by! { |x| x.published  }.reverse.each do |entry|
  nextv = pos + 1
  source = entry.url.gsub(/https?:\/\//, '').gsub(/\/.*/, '').gsub(/^www./, '')
  index.write("<h3><a name='%d'><a href='#%d'><img src='/assets/images/arrow_down64.png' style='float:left'/></a> <a href='%s'>%s: %s</a></h3>\n\n" %
              [pos, nextv, entry.url, source, entry.title])
  if entry.content then
    index.write(fixhtml(entry.content))
  else
    index.write(fixhtml(entry.summary))
  end
  index.write("\n<p class='author'>Posted: %04d-%02d-%02d by %s</p><p>&nbsp;</p>\n\n" %
             [entry.published.year, entry.published.month, entry.published.day, source] )
  pos += 1
end

index.close



