2 %%% This module is responsible for managing the run of set of torrent files.
5 -behaviour(gen_server
).
7 -include("etorrent_mnesia_table.hrl").
11 start_torrent
/1, stop_torrent
/1,
14 stop_all_torrents
/0]).
16 -export([handle_cast
/2, handle_call
/3, init
/1, terminate
/2]).
17 -export([handle_info
/2, code_change
/3]).
19 -define(SERVER
, ?MODULE
).
22 -record(state
, {local_peer_id
}).
26 %% Start a new etorrent_t_manager process
28 gen_server:start_link({local
, ?SERVER
}, ?MODULE
, [PeerId
], []).
30 %% Ask the manager process to start a new torrent, given in File.
31 start_torrent(File
) ->
32 gen_server:cast(?SERVER
, {start_torrent
, File
}).
34 %% Check a torrents contents
36 gen_server:cast(?SERVER
, {check_torrent
, Id
}).
38 %% Ask the manager process to stop a torrent, identified by File.
40 gen_server:cast(?SERVER
, {stop_torrent
, File
}).
42 stop_all_torrents() ->
43 gen_server:call(?SERVER
, stop_all_torrents
, 120000).
47 {ok
, #state
{ local_peer_id
= PeerId
}}.
49 handle_cast({start_torrent
, F
}, S
) ->
50 case torrent_duplicate(F
) of
54 etorrent_t_pool_sup:add_torrent(
56 S#state
.local_peer_id
,
57 etorrent_counters:next(torrent
)),
60 handle_cast({check_torrent
, Id
}, S
) ->
61 {atomic
, [T
]} = etorrent_tracking_map:select(Id
),
62 SPid
= T#tracking_map
.supervisor_pid
,
63 Child
= etorrent_t_sup:get_pid(SPid
, control
),
64 etorrent_t_control:check_torrent(Child
),
66 handle_cast({stop_torrent
, F
}, S
) ->
69 handle_call(stop_all_torrents
, _From
, S
) ->
70 {atomic
, Torrents
} = etorrent_tracking_map:all(),
71 lists:foreach(fun(#tracking_map
{ filename
= F
}) ->
72 etorrent_t_pool_sup:stop_torrent(F
),
77 handle_call(_A
, _B
, S
) ->
80 handle_info(Info
, State
) ->
81 error_logger:info_msg("Unknown message: ~p~n", [Info
]),
84 terminate(_Foo
, _State
) ->
87 code_change(_OldVsn
, State
, _Extra
) ->
92 error_logger:info_msg("Stopping ~p~n", [F
]),
93 case etorrent_tracking_map:select({filename
, F
}) of
94 {atomic
, [T
]} when is_record(T
, tracking_map
) ->
95 etorrent_t_pool_sup:stop_torrent(F
),
98 %% Was already removed, it is ok.
104 torrent_duplicate(F
) ->
105 case etorrent_tracking_map:select({filename
, F
}) of
106 {atomic
, []} -> false
;
107 {atomic
, [T
]} -> duplicate
=:= T#tracking_map
.state