aboutsummaryrefslogblamecommitdiffstats
path: root/server/dispatcher.erl
blob: e5e05720cc911a5404e72d4286938706f0e92b96 (plain) (tree)
1
2
3
4
5
6
7
8
9
                    
                                     

          

                                                

                                      
 
                                             







                                                                             
 


                                                                    
                                        
               


                                           




                                                           


               
                                             

                                 
                                             
            
                                                    


                                                                  
                                                
                                 
                         


                                                   

                                                           
                
            


                                                     


                               
                    
                                                    
                                            
-module(dispatcher).
-export([start/0, init/0, handle/2]).

start() ->
    %% load server module from common directory,
    %% used form server and client
    code:purge(server),
    code:load_abs("../common/server"),

    %% spawn media backend in seperat process
    try spawn(media, init, []) of
	_ ->
	    io:format("Media-Backend started!~n")
    catch
	_: Why ->
	    io:format("Error starting media backend: ~w! Exiting.~n", [Why]),
	    exit(1)
    end,

    %% start server (registered as dis)
    %% server-module will call handle if message arrives and init to
    %% initialize the status
    try server:start(dis, dispatcher) of
	true ->
	    io:format("Server started!~n"),
	    true
    catch
	_ ->
	    io:format("Error starting server! Exiting.~n"),
	    exit(1)
    end.

init() ->
    dict:new().

handle({register, {User, Password}}, Dict) ->
    case dict:find(User, Dict) of
	{ok, _}->
	    {{error, duplicated_user}, Dict};
	_ ->
	    io:format("User created: ~s~n", [User]),
	    {{ok, user_created}, dict:store(User, Password, Dict)}
    end;

handle({login, {Node, User, Password}}, Dict) ->
    case dict:find(User, Dict) of
	{ok, Password} ->
	    case client:start(Node) of
		{ok, Pid} ->
		    {{ok, {logged_in, Pid}}, Dict};
		Why ->
		    {{error, {unable_to_login, Why}}, Dict}
	    end;
	_ ->
	    {{error, user_or_password_invalid}, Dict}
    end;

handle({'EXIT', _, _}, Dict) ->
    Dict;

handle(Cmd, Dict) ->
    %% standard command, to find transmission errors
    {{error, {unknown_command, Cmd}}, Dict}.