# frozen_string_literal: true require "fileutils" require "uri" require 'open-uri' module Kanal module Plugins module Batteries module Attachments class Attachment attr_reader :url def initialize(url) @url = url end # Extension checks like jpg?, mp3?, mp4?, doc? etc. fall here def method_missing(method) extension == method.to_s.delete("?") end def image? [jpg?, jpeg?, png?, bmp?, gif?].any? end def audio? [mp3?, wav?, ogg?].any? end def video? [mp4?, mov?, mkv?].any? end def document? [doc?, docx?, odf?].any? end # # Method that returns extension of url file if possible # For example calling extension https://123.txt?something=1 will return 'txt' # # @return [String, nil] # def extension uri = URI.parse(@url) return nil if uri.path.nil? File.extname(uri.path).split(".").last if File.basename(uri.path).include? "." end # # Saves file to specified path. End user provides full filepath. # # @param [String] # @param [Boolean] # # @return [void] # def save(filepath, create_dirs = false) stream = URI.open(@url) save_stream_to_file stream, filepath, create_dirs end # # Saves file. End user provides directory only. Filename gets generated, extension is read from url. # # @param [String] # @param [Boolean] # @param [Integer] # # @return [String] Full filepath to saved file # def quick_save(directory, create_dir = false, filename_length = 32) filename = generate_filename filename_length, extension return quick_save directory, create_dir, filename_length if File.exist? filename save directory + filename, create_dir directory + filename end private def generate_filename(filename_length, extension = nil) alphanumeric = "abcdefghijkmnopQRSTUVWNXYZW12345676789-".chars name = "" filename_length.times do name += alphanumeric.sample end extension ? "#{name}.#{extension}" : name end def save_stream_to_file(stream, filepath, create_dirs) raise "File with that name already exists!" if File.exist? filepath if create_dirs == true FileUtils.mkdir_p(File.dirname(filepath)) unless File.directory?(File.dirname(filepath)) end IO.copy_stream stream, filepath end end end end end end