Globalize the etorrent_t_peer_group_mgr and rename it to etorrent_choker while here.
[etorrent.git] / lib / etorrent-1.0 / src / etorrent_t_manager.erl
blobca398e867fbd3999af7a1760f37165f22068e3cd
1 %%%
2 %%% This module is responsible for managing the run of set of torrent files.
3 %%%
4 -module(etorrent_t_manager).
5 -behaviour(gen_server).
7 -include("etorrent_mnesia_table.hrl").
9 -export([start_link/1,
11 start_torrent/1, stop_torrent/1,
12 check_torrent/1]).
13 -export([handle_cast/2, handle_call/3, init/1, terminate/2]).
14 -export([handle_info/2, code_change/3]).
16 -define(SERVER, ?MODULE).
19 -record(state, {local_peer_id}).
21 %% API
23 %% Start a new etorrent_t_manager process
24 start_link(PeerId) ->
25 gen_server:start_link({local, ?SERVER}, ?MODULE, [PeerId], []).
27 %% Ask the manager process to start a new torrent, given in File.
28 start_torrent(File) ->
29 gen_server:cast(?SERVER, {start_torrent, File}).
31 %% Check a torrents contents
32 check_torrent(Id) ->
33 gen_server:cast(?SERVER, {check_torrent, Id}).
35 %% Ask the manager process to stop a torrent, identified by File.
36 stop_torrent(File) ->
37 gen_server:cast(?SERVER, {stop_torrent, File}).
39 %% Callbacks
40 init([PeerId]) ->
41 {ok, #state { local_peer_id = PeerId}}.
43 handle_cast({start_torrent, F}, S) ->
44 case torrent_duplicate(F) of
45 true -> {noreply, S};
46 false ->
47 {ok, _} =
48 etorrent_t_pool_sup:add_torrent(
50 S#state.local_peer_id,
51 etorrent_sequence:next(torrent)),
52 {noreply, S}
53 end;
54 handle_cast({check_torrent, Id}, S) ->
55 {atomic, [T]} = etorrent_tracking_map:select(Id),
56 SPid = T#tracking_map.supervisor_pid,
57 Child = etorrent_t_sup:get_pid(SPid, control),
58 etorrent_t_control:check_torrent(Child),
59 {noreply, S};
60 handle_cast({stop_torrent, F}, S) ->
61 stop_torrent(F, S).
63 handle_call(_A, _B, S) ->
64 {noreply, S}.
66 handle_info(Info, State) ->
67 error_logger:info_msg("Unknown message: ~p~n", [Info]),
68 {noreply, State}.
70 terminate(_Foo, _State) ->
71 ok.
73 code_change(_OldVsn, State, _Extra) ->
74 {ok, State}.
76 %% Internal functions
77 stop_torrent(F, S) ->
78 error_logger:info_msg("Stopping ~p~n", [F]),
79 case etorrent_tracking_map:select({filename, F}) of
80 {atomic, [T]} when is_record(T, tracking_map) ->
81 etorrent_t_pool_sup:stop_torrent(F),
82 ok;
83 {atomic, []} ->
84 %% Was already removed, it is ok.
86 end,
87 {noreply, S}.
90 torrent_duplicate(F) ->
91 case etorrent_tracking_map:select({filename, F}) of
92 {atomic, []} -> false;
93 {atomic, [T]} -> duplicate =:= T#tracking_map.state
94 end.