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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
|
-module(client).
-export([register/3, login/3, list/0, handle/2, getVotes/0, vote/2, devote/2]).
contains([], _) ->
false;
contains([H|_], H) ->
true;
contains([_|T], Search) ->
contains(T, Search).
checkLogin(Value) ->
checkLogin(Value, contains(registered(), cli)).
checkLogin(Value, Value) ->
true;
checkLogin(_, _) ->
throw({error, login_state}).
buildNode(Server) ->
list_to_atom("distributed_music_system_main_node@" ++ Server).
rpc(Server, Function, Params) ->
rpc:call(buildNode(Server), client, Function, Params).
register(Server, Name, Password) ->
rpc(Server, register, [self(), {Name, Password}]),
receive
{_, Msg} ->
Msg
end.
login(Server, Name, Password) ->
code:purge(server),
code:load_abs("../common/server"),
try checkLogin(false) of
_ ->
rpc(Server, login, [self(), {node(), Name, Password}]),
receive
{ok, {ok, {logged_in, Pid}}} ->
register(cli, Pid),
{ok, logged_in};
{_, Msg} ->
Msg;
Msg ->
Msg
end
catch
{error, login_state} ->
{error, logged_in}
end.
list() ->
try checkLogin(true) of
_ ->
server:rpc(cli, list)
catch
{error, login_state} ->
{error, not_logged_in}
end.
handle(list, Server) ->
Server ! list,
receive
{ok, Msg} ->
{Msg, Server};
Msg ->
{Msg, Server}
end;
handle(get_votes, Server) ->
Server ! get_votes,
receive
{ok, Msg} ->
{Msg, Server};
Msg ->
{Msg, Server}
end;
handle({vote, Artist, Title}, Server) ->
Server ! {vote, Artist, Title},
receive
{ok, Msg} ->
{Msg, Server};
Msg ->
{Msg, Server}
end;
handle({devote, Artist, Title}, Server) ->
Server ! {vote, Artist, Title},
receive
{ok, Msg} ->
{Msg, Server};
Msg ->
{Msg, Server}
end;
handle({change_state, NewState}, _) ->
{{ok}, NewState};
handle(Cmd, Server) ->
{{error, {unknown_command, Cmd}}, Server}.
%queries the server for the current votes this client possesses
getVotes() ->
try checkLogin(true) of
_ ->
server:rpc(cli, get_votes)
catch
{error, login_state} ->
{error, not_logged_in}
end.
%positive vote, increments the votes for {Artist, Title} by one
vote(Artist, Title) ->
try checkLogin(true) of
_ ->
server:rpc(cli, {vote, Artist, Title})
catch
{error, login_state} ->
{error, not_logged_in}
end.
%negative vote, decrements the votes for {Artist, Title} by one
devote(Artist, Title) ->
try checkLogin(true) of
_ ->
server:rpc(cli, {devote, Artist, Title})
catch
{error, login_state} ->
{error, not_logged_in}
end.
|