aboutsummaryrefslogtreecommitdiffstats
path: root/server/client.erl
blob: 6c81349b30fa1681c167bb7b38236950e4379d63 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
-module(client).
-export([start/2, loop/2, register/2, login/2]).

start(Node, User) ->
    %% start linked processes on client and server to get notice if
    %% client disconnects and properly handle the logged in status
    process_flag(trap_exit, true),
    Client = server:start_on_node(Node, client, undef),
    link(Client),
    %% store the client pid in the client database to find the correct
    %% user on the exit message from the client
    cldb:set_client_pid(User, Client),
    Server = spawn_link(client, loop, [Client, User]),

    %% update the server process_id in the state of the client process,
    %% so that the client process knows its direct counterpart on the
    %% server
    case server:rpc(Client, {change_state, Server}) of
	{ok} ->
	    {ok, Client};
	Why ->
	    {error, {unknown_error, Why}}
    end.

execute(Client, F) ->
    %% execute F() with error handling
    %% (sends error message on exception)
    try F() of
	Result ->
	    Client ! {ok, Result}
    catch
	_: Why ->
	    Client ! {error, Why}
    end.

loop(Client, User) ->
    %% main loop for client module in server, handle the commands from
    %% the logged_in client
    receive
	{register, Name, Password} ->
	    case cldb:check_rights(User) of
		admin -> execute(Client, fun() -> cldb:register(Name, Password, none) end);
		_ -> Client ! {error, {no_rights}}
	    end;

	list ->
	    execute(Client, fun() -> media:all() end);

	get_votes ->
	    execute(Client, fun() -> cldb:get_votes(User) end);

	{vote, Artist, Title} ->
	    %% only allow voting if user has at least one vote
	    case cldb:dec_vote(User) of
	        {ok} -> execute(Client, fun() -> media:vote(Artist, Title) end);
	        _ -> Client ! {error, no_votes_available}
	    end;

	{devote, Artist, Title} ->
	    %% only allow devoting if user has at least one vote
	    case cldb:dec_vote(User) of
	        {ok} -> execute(Client, fun() -> media:devote(Artist, Title) end);
	        _ -> Client ! {error, no_votes_available}
	    end;

	Cmd ->
	    %% fallback for error messages
	    Client ! {error, {unknown_command, Cmd}}
    end,
    loop(Client, User).

register(Client, {Name, Password}) ->
    %% forward the register messages to the dispatcher (if user is not
    %% logged in)
    dis ! {Client, {register, {Name, Password}}}.

login(Client, {Node, Name, Password}) ->
    %% forward the login messages to the dispatcher
    dis ! {Client, {login, {Node, Name, Password}}}.