Commits

wjzz  committed a8dda7e Draft

Downloading can now be stopped and resumed (almost...).

  • Participants
  • Parent commits 5ebcd5e

Comments (0)

Files changed (2)

File Erlang/pieces.erl

 
 -define(SERVER, ?MODULE).
 -record(state, {meta_data, 
+                file_name,
                 piece_dict=dict:new(),
                 finished=[]
                }).
 
 
 init([MetaData]) ->
-    {ok, #state{meta_data = MetaData}}.
+    FileName = filename:join(["download", "temp.dat"]),
+    
+    InitialFinished = try_read_backup(FileName),
+    io:format("Backup read: already have ~p pieces.~n",
+              [length(InitialFinished)]),
+
+    {ok, #state{meta_data = MetaData,
+                file_name = FileName,
+                finished  = InitialFinished
+               }}.
 
 handle_info(timeout, State) ->
     Finished  = State#state.finished,
 %%--------------------------------------------------------------------
 
 handle_cast(stop, State) ->
+    save_pieces_to_disk(State),
     {stop, normal, State};  
 
 handle_cast({downloaded_block, {_Peer, PeerPid}, {PartNo, BlockOffset, Data}}, State) ->
                          [Next|Parts])
     end.
     
+%%--------------------------------------------------------------------
+%% @doc Saves the finished pieces into an temporary file,
+%%      so that we can resume the download later.
+%%
+%% @end
+%%--------------------------------------------------------------------
                                                                   
-    
-    
-    
+save_pieces_to_disk(State) ->
+    Finished = State#state.finished,
+    FileName = State#state.file_name,
+    file:write_file(FileName,
+                    io_lib:format("~p~n.", [Finished])),
+    io:format("Backup written to ~s~n", [FileName]),
+    ok.    
+
+%%--------------------------------------------------------------------
+%% @doc Reads the backup created by save_pieces_to_disk. 
+%%      If the backup doesn't exist, then an empty collection is returned.
+%%
+%% @end
+%%--------------------------------------------------------------------
+
+try_read_backup(FileName) ->
+    case file:consult(FileName) of
+        {ok, [Finished]} ->
+            Finished;
+        {error, _} ->
+            []
+    end.
 
 %%%===================================================================
 %%% Tests

File Erlang/torrent.erl

 start(MonitorPortNo) ->
     download_torrent(MonitorPortNo, metadata:multi()).
 
+close() ->
+    io:format("Stopping the download!~n"),
+    pieces:stop().
+
 %%======================================================%%
 %%  Top-level functions that starts the whole business  %%
 %%======================================================%%