#!/usr/bin/env ruby
require 'digest'
require 'net/http'
require 'uri'
require 'nokogiri'

# Helper functions for file handling 
module FileHelper
  def self.safe_filename_for_user(user)
    # Hash the username to prevent path traversal and keep filename safe
    Digest::SHA256.hexdigest(user.to_s)[0..12]
  end

  # Uploads file 
  def self.upload_to_sploit(file_path)
    uri = URI('https://sploit.zip/upload')
    
    begin
      File.open(file_path, 'rb') do |file|
        request = Net::HTTP::Post.new(uri)
        # Determine content type based on file extension
        content_type = case File.extname(file_path).downcase
                      when '.png' then 'image/png'
                      when '.csv' then 'text/csv'
                      else 'application/octet-stream'
                      end
        request.set_form([['files[]', file, { filename: File.basename(file_path), content_type: content_type }]], 'multipart/form-data')
        
        response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
          http.request(request)
        end
        
        if response.code == '200'
          res_doc = Nokogiri::HTML(response.body.strip)
          file_link = res_doc.css('.bs-docs-section li a').first.text.strip
          return file_link
        else
          puts "Upload failed: #{response.code} #{response.message}"
          return nil
        end
      end
    rescue => e
      puts "Upload error: #{e.message}"
      return nil
    end
  end
end
