Last active
February 16, 2021 07:18
-
-
Save hopsor/fa187507d40ad576607fe8e2fab56f8e to your computer and use it in GitHub Desktop.
ftp download using elixir and erlang interop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Reporter do | |
def progress(last_data, file_name, {size_type, chunk_size}) do | |
IO.inspect({last_data[:downloaded], "#{last_data[:rate]} MB/s", file_name, size_type, chunk_size}) | |
new_timestamp = :os.system_time(:milli_seconds) | |
timestamp_diff = new_timestamp - last_data[:last_timestamp] | |
case chunk_size do | |
:unknown -> | |
downloaded = 0 | |
rate = 0 | |
_ -> | |
downloaded = last_data[:downloaded] + chunk_size | |
# Kilobytes per second | |
cond do | |
timestamp_diff > 0 -> | |
rate = (chunk_size/1000000)/(timestamp_diff/1000) | |
true -> | |
rate = last_data[:rate] | |
end | |
end | |
%{downloaded: downloaded, last_timestamp: new_timestamp, rate: rate} | |
end | |
end | |
cfg = [ | |
host: 'ftp.iinet.net.au', | |
progress: { | |
Reporter, | |
:progress, | |
%{ | |
downloaded: 0, | |
last_timestamp: :os.system_time(:milli_seconds), | |
rate: 0 | |
} | |
} | |
] | |
:inets.start | |
{:ok, pid} = :inets.start(:ftpc, cfg) | |
:ftp.user(pid, 'anonymous', 'anonymous') | |
:ftp.type(pid, :binary) | |
:ftp.ls(pid) | |
a = :os.system_time(:milli_seconds) | |
:ftp.recv(pid, '1mb.dat') | |
b = :os.system_time(:milli_seconds) | |
IO.puts "Time spent: #{(b-a)/1000} seconds" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Calculating the transfer rate within the progress block doesn't seem feasible. Maybe it's better for each download to start a different process that watches the progress each 1-2 seconds.