require 'pathname' require_relative 'post/generic' require_relative 'post/code' require_relative 'post/image' require_relative 'post/link' require_relative 'post/markdown' require_relative 'post/spotify' require_relative 'post/youtube' class FrenchPress # This represents a post in a FrenchPress blog class Post def self.new_post(item) type = parse_type item file = nil if type =~ /^file-[^-]+$/ item, file = parse_file item type = type.gsub 'file-', '' end case type when 'text' FrenchPress::Post::Generic.new(item) when 'code' FrenchPress::Post::Code.new(item, file) when 'markdown' FrenchPress::Post::Markdown.new(item) when 'image' FrenchPress::Post::Image.new(item, type.split('-')[1]) when 'link' FrenchPress::Post::Link.new(item) when 'spotify' FrenchPress::Post::Spotify.new(item) when 'youtube' FrenchPress::Post::Youtube.new(item) end end def self.new_post_from_multiple(*args) # Check we really have multiple arguments return new_post(args[0]) if args.length == 1 args.map!(&method(:new_post)) # Run new_post on each item in args args.map!(&:render) # Render each item in args (which are now posts) # Then join them with newlines, and pass them to a new, combined post FrenchPress::Post::Generic.new args.join("\n\n") end def self.generate_reply(original_url, *args) original = get_post_from_url original_url reply = new_post_from_multiple(*args) # Form a reply from all other args new_post_from_multiple original.render_as_quote, reply.render end def self.parse_type(item) if item =~ /\A#{URI.regexp(%w(http https))}\z/ if item.include?('open.spotify.com') return 'spotify' elsif item.include?('youtube.com') return 'youtube' else return 'link' end elsif File.exist?(item) filetype = item.split('.').pop # it's a file that's being posted # is it a text or markdown file? # or possibly a code snippet if %w(md markdown).include?(filetype) return 'file-markdown' elsif %w(rb py c go cpp rs swift js yml).include?(filetype) return 'file-code' elsif %w(png jpg).include?(filetype) return "file-image-#{filetype}" else return 'file-text' end else return 'text' end end def self.get_post_from_url(url_string) # Ensure we have http:// prefix url_string = url_string.gsub('http://', '').gsub('https://', '') url_string = url_string.prepend('https://') # i'm an optimist post_uri = URI.parse(url_string) # Update path to point to raw file post_uri.path = post_uri.path.split('/').pop.prepend('/raw/') dl = nil begin dl = post_uri.open.read.dup # Dup to remove frozen state rescue begin url_string = url_string.gsub 'https://', 'http://' post_uri = URI.parse url_string post_uri.path = post_uri.path.split('/').pop.prepend('/raw/') dl = post_uri.open.read.dup rescue StandardError => e puts "Woah! I can't grab the original post. Check your internet." puts e exit 1 end end post = FrenchPress::Post.new_post dl post.parent_blog = { url: url_string, host: post_uri.host } post end def self.parse_file(f) file = File.open f r = file.read file.close [r, f.split('.').pop] end end end