view bin/ed2k @ 328:936adea50fde

Merge.
author Edho Arief <edho@myconan.net>
date Sun, 18 Mar 2012 16:47:46 +0700
parents 94ee419ad047
children bcdf320dabf4
line wrap: on
line source

#!/usr/bin/env ruby
require 'openssl'

def file_ed2k(file_name, output_mode = "hash")
  ed2k_block = 9500*1024 #ed2k block size is 9500 KiB
  ed2k_hash = ""
  file = File.open(file_name, 'rb')
  file_size = file.stat.size #while at it, fetch the size of the file
  while (block = file.read(ed2k_block)) do
    ed2k_hash << OpenSSL::Digest::MD4.digest(block) #hashes are concatenated md4 per block size for ed2k hash
  end
  ed2k_hash << OpenSSL::Digest::MD4.digest("") if file_size % ed2k_block == 0 #on size of modulo block size, append another md4 hash of a blank string
  file.close
  ed2k_hash = OpenSSL::Digest::MD4.hexdigest(ed2k_hash) #finally
  return case output_mode #there are 2 modes, just the has, or complete with link.
    when "hash"
      ed2k_hash
    when "link"
      "ed2k://|file|#{File.basename(file_name)}|#{file_size}|#{ed2k_hash}|"
    end
end

ARGV.each do |file_name|
  next unless File.file?(file_name) and File.readable?(file_name)
  printf("%s\n", file_ed2k(file_name,"link"))
end