require 'net/http'
multithreading = true
Net::HTTP.start("2ch.hk", :use_ssl => true) do |http|
  thread = http.get("/b/res/133429168.html").body
  sources = []
  thread.scan(/<a class="desktop" target="_blank" href=".+">.+<\/a>/).each do |a|
    source = "/b#{/<a class="desktop" target="_blank" href="\.\.(.+)">.+<\/a>/.match(a).to_a[1]}"
    sources << source
  end
  i = 0
  start = Time.now
  if multithreading
    threads = []
    sources.each do |source|
      threads << Thread.new(i) { |j|
        file = http.get(source).body #breaks everything
        # type = /.+\.(.+)/.match(source)[1]
        # open("#{j}.#{type}","wb") { |new_file|
        #   new_file.write(file)
        # }
      }
      i += 1
    end
    threads.each do |thr|
      thr.join
    end
    # until downloade=sources.size
    #
    # end
  else
    sources.each do |source|
      file = http.get(source).body
      type = /.+\.(.+)/.match(source)[1]
      open("#{i}.#{type}","wb") { |new_file|
        new_file.write(file)
      }
      i += 1
      print "#{(((i).to_f / sources.size) * 100).round(2)}% "
    end
    puts
  end
  puts "Done. #{i} files were downloaded. It took #{Time.now - start} seconds"
end
