% coding: utf-8
% Copyright 2008 Grégory Burri
%
% This file is part of Euphorik.
%
% Euphorik is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% Euphorik is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with Euphorik. If not, see .
%
% Ce module gére les différents messages envoyés par le client (javascript) via AJAX.
% Les messages donnés ainsi que les réponses sont au format JSON.
% @author G.Burri
-module(euphorik_protocole).
-export([
register/2,
login/2,
logout/1,
profile/1,
wait_event/1,
put_message/1,
ban/1,
slap/1,
put_troll/1,
mod_troll/1,
del_troll/1,
unban_ip/1,
list_banned_ips/1,
erreur/1
]).
-include("../include/euphorik_bd.hrl").
-include("../include/euphorik_defines.hrl").
% Une utilisateur s'enregistre avec un tuple {Login, Password}.
register([{login, Login}, {password, Password}], IP) ->
Can_register = euphorik_bd:can_register(IP),
if Can_register ->
case euphorik_bd:user_by_login(Login) of
{ok, _} ->
erreur("Login déjà existant");
_ ->
User = euphorik_bd:nouveau_user(Login, Password, generer_cookie()),
euphorik_bd:update_ip(User#user.id, IP),
json_reponse_login_ok(User)
end;
true ->
erreur_register_flood()
end;
% Enregistrement sans {Login, Password}
register([], IP) ->
Can_register = euphorik_bd:can_register(IP),
if Can_register ->
User = euphorik_bd:nouveau_user("", generer_cookie()),
euphorik_bd:update_ip(User#user.id, IP),
json_reponse_login_ok(User);
true ->
erreur_register_flood()
end.
erreur_register_flood() ->
erreur("Trop de register (flood)").
% Un utilisateur se logge (avec un couple {login, mot de passe})
login([{login, Login}, {password, Password}], IP) ->
loginUser(euphorik_bd:user_by_login_password(Login, Password), IP);
% Un utilisateur se logge (avec un cookie)
login([{cookie, Cookie}], IP) ->
loginUser(euphorik_bd:user_by_cookie(Cookie), IP).
loginUser({ok, User}, IP) ->
euphorik_bd:update_ip(User#user.id, IP),
euphorik_bd:update_date_derniere_connexion(User#user.id),
json_reponse_login_ok(User);
loginUser(_, _) ->
% ajoute un délais d'attente
timer:sleep(?TEMPS_ATTENTE_ERREUR_LOGIN),
erreur("Couple login/pass introuvable").
% Renvoie un string() représentant un cookie en base 36. Il y a 10^32 possibillités.
generer_cookie() ->
{A1,A2,A3} = now(),
random:seed(A1, A2, A3),
erlang:integer_to_list(random:uniform(math:pow(10, 32)), 36).
% Un utilisateur se délogge.
logout(_) ->
do_nothing.
% Modification du profile.
profile(
[
{cookie, Cookie},
{login, Login},
{password, Password},
{nick, Pseudo},
{email, Email},
{css, Css},
{nick_format, Nick_format_str},
{view_times, View_times},
{view_tooltips, View_tooltips},
{main_page, Main_page},
{conversations, {array, Conversations_json}}
]
) ->
% est-ce que les messages auquel on répond existent ?
Conversations = lists:foldr(
fun({struct, [{root, Root}, {page, Page}]}, Acc) ->
Message_existe = euphorik_bd:message_existe(Root),
if Message_existe ->
[{Root, Page} | Acc];
true ->
Acc
end
end,
[],
Conversations_json
),
% TODO : pas très beau, mieux vaut construire un #user
case euphorik_bd:set_profile(
Cookie,
Login,
Password,
Pseudo,
Email,
Css,
list_to_atom(Nick_format_str),
View_times,
View_tooltips,
Main_page,
Conversations) of
ok ->
json_reponse_ok();
login_deja_pris ->
erreur("Login déjà pris");
_ ->
erreur("Impossible de mettre à jour le profile")
end.
% Renvoie les messages appropriés.
% last_message id et cookie sont facultatifs
wait_event([{page, "chat"} | Data]) ->
% traitement des inputs
Cookie = case lists:keysearch(cookie, 1, Data) of {value, {_, C}} -> C; _ -> inconnu end,
Last_message_id = case lists:keysearch(last_message_id, 1, Data) of {value, {_, Id}} -> Id; _ -> 0 end,
{value, {_, Message_count}} = lists:keysearch(message_count, 1, Data),
Main_page = case lists:keysearch(main_page, 1, Data) of {value, {_, P}} -> P; _ -> 1 end,
Troll_id = case lists:keysearch(troll_id, 1, Data) of {value, {_, T}} -> T; _ -> 0 end,
{value, {_, {array, Conversations_json}}} = lists:keysearch(conversations, 1, Data),
Racines_conversations = lists:map(
fun({struct, [{root, Racine}, {page, Page} | Reste]}) ->
Last_mess_conv = case Reste of [{last_message_id, L}] -> L; _ -> 0 end,
{Racine, Page, Last_mess_conv}
end,
Conversations_json
),
User = case euphorik_bd:user_by_cookie(Cookie) of
{ok, U} -> U;
_ -> inconnu
end,
case {mnesia:subscribe({table, minichat, detailed}), mnesia:subscribe({table, troll, detailed})} of
{{error, E}, _} -> E;
{_, {error, E}} -> E;
_ ->
% attente d'événements
R = wait_event_page_chat(User, Racines_conversations, Message_count, Last_message_id, Main_page, Troll_id),
mnesia:unsubscribe({table, minichat, detailed}),
mnesia:unsubscribe({table, troll, detailed}),
R
end;
wait_event([{page, "admin"}, {last_troll, Last_troll}]) ->
case wait_event_page_admin(Last_troll) of
banned_ips_refresh ->
{struct,
[
{reply, "banned_ips_refresh"}
]
};
{mod, Troll} ->
{struct,
[
{reply, "troll_modified"},
{troll_id, Troll#troll.id},
{content, Troll#troll.content}
]
};
{add, Trolls} ->
{struct,
[
{reply, "troll_added"},
{trolls, {array,
lists:map(
fun(T) ->
{ok, User} = euphorik_bd:user_by_id(T#troll.id_user),
{struct,
[
{troll_id, T#troll.id},
{content, T#troll.content},
{author, User#user.pseudo},
{author_id, User#user.id}
]
}
end,
Trolls
)
}}
]
};
{del, Troll_id} ->
{struct,
[
{reply, "troll_deleted"},
{troll_id, Troll_id}
]
};
_ ->
erreur("timeout")
end;
wait_event(_) ->
erreur("Page inconnue").
wait_event_page_chat(User, Racines_conversations, Message_count, Last_message_id, Main_page, Troll_id) ->
% est-ce que le troll est à jour ?
case euphorik_bd:current_troll() of
Current when is_record(Current, troll), Current#troll.id =/= Troll_id ->
{struct, [
{reply, "new_troll"},
{troll_id, Current#troll.id},
{message_id, euphorik_bd:message_id_associe(Current#troll.id)},
{content, Current#troll.content}
]};
_ ->
% est-ce qu'il y a des nouveaux messages ?
case euphorik_minichat_conversation:conversations(Racines_conversations, Message_count, Last_message_id, Main_page) of
vide ->
wait_event_bd_page_chat(),
% TODO : l'appel est-il bien tail-recursive ?
wait_event_page_chat(User, Racines_conversations, Message_count, Last_message_id, Main_page, Troll_id);
Conversations ->
% accrochez-vous ca va siouxer ;)
{struct, [
{reply, "new_messages"},
{conversations, {array,
lists:map(
fun({Conv, Plus}) ->
{struct, [
{last_page, not Plus},
{messages, {array,
lists:map(
fun({Mess, Repond_a}) ->
Est_proprietaire = User =/= inconnu andalso User#user.id =:= Mess#minichat.auteur_id,
A_repondu_a_message = User =/= inconnu andalso euphorik_bd:a_repondu_a_message(User#user.id, Mess#minichat.id),
Est_une_reponse_a_user = User =/= inconnu andalso euphorik_bd:est_une_reponse_a_user(User#user.id, Mess#minichat.id),
{ok, User_mess } = euphorik_bd:user_by_id(Mess#minichat.auteur_id),
{struct, [
{id, Mess#minichat.id},
{user_id, User_mess#user.id},
{date, format_date(Mess#minichat.date)},
{system, Mess#minichat.auteur_id =:= 0},
{owner, Est_proprietaire},
{answered, A_repondu_a_message},
{is_a_reply, Est_une_reponse_a_user},
{nick, Mess#minichat.pseudo},
{login, User_mess#user.login},
{content, Mess#minichat.contenu},
{answer_to, {array, lists:map(
fun(Id_mess) ->
{ok, M} = euphorik_bd:message_by_id(Id_mess),
{ok, User_reponse} = euphorik_bd:user_by_mess(M#minichat.id),
{struct, [{id, M#minichat.id}, {nick, M#minichat.pseudo}, {login, User_reponse#user.login}]}
end,
Repond_a
)}},
{ek_master, User_mess#user.ek_master}
]}
end,
Conv
)
}}
]}
end,
Conversations
)
}}
]}
end
end.
% Attend un événement lié à la page 'chat'.
wait_event_bd_page_chat() ->
receive % attente d'un post
{mnesia_table_event, {write, minichat, _Message, [], _}} ->
ok;
{mnesia_table_event, {write, troll, Troll, [Old_troll | _], _}} when Troll#troll.date_post =/= undefined, Old_troll#troll.date_post == undefined ->
ok;
{tcp_closed, _} ->
exit(normal);
_ ->
wait_event_bd_page_chat()
% 60 minutes de timeout (on ne sais jamais)
% Après 60 minutes de connexion, le client doit donc reétablir une connexion
after 1000 * 60 * 60 ->
timeout
end.
% Attent un événement concernant la page admin
% Renvoie les trolls manquants posté après Last_id ou banned_ips_refresh.
% Si pas de trolls alors attend un événement tel qu'un ajout, une modification ou une suppression.
% renvoie :
% {mod, Troll}
% ou {add, [Trolls]}
% ou {del, Troll_id}
% ou banned_ips_refresh
% ou timeout
wait_event_page_admin(Last_id) ->
case {mnesia:subscribe({table, troll, detailed}), mnesia:subscribe({table, ip_table, detailed})} of
{{error, E}, _ } -> E;
{_, {error, E}} -> E;
_ ->
R = case euphorik_bd:trolls(Last_id) of
[] -> % pas de trolls
wait_event_page_admin();
Trolls ->
{add, Trolls}
end,
mnesia:unsubscribe({table, troll, detailed}),
mnesia:unsubscribe({table, ip_table, detailed}),
R
end.
wait_event_page_admin() ->
% s'il n'y a pas de trolls que l'utilisateur n'a pas connaissance alors on attend un événement
receive
% cas où un troll est choisit comme courant
{mnesia_table_event, {write, troll, Troll, [Old_troll | _], _}}
when Old_troll#troll.date_post =:= undefined, Troll#troll.date_post =/= undefined ->
{del, Troll#troll.id};
{mnesia_table_event, {write, troll, Troll, [_Old_troll | _], _}} ->
{mod, Troll};
{mnesia_table_event, {write, troll, Troll, [], _}} ->
{add, [Troll]};
{mnesia_table_event, {delete, troll, {troll, Id}, _, _}} ->
{del, Id};
{mnesia_table_event, {write, ip_table, IP, [Old_IP | _], _}}
when Old_IP#ip_table.ban =/= IP#ip_table.ban; Old_IP#ip_table.ban_duration =/= IP#ip_table.ban_duration ->
banned_ips_refresh;
{tcp_closed, _} ->
exit(normal);
_ ->
wait_event_page_admin()
% 60 minutes de timeout (on ne sais jamais)
% Après 60 minutes de connexion, le client doit donc reétablir une connexion
after 1000 * 60 * 60 ->
timeout
end.
% Un utilisateur envoie un message
put_message(
[
{cookie, Cookie},
{nick, Nick},
{content, Content},
{answer_to, {array, Answer_to}}
]
) ->
case euphorik_bd:user_by_cookie(Cookie) of
{ok, User} ->
case euphorik_bd:est_banni(User#user.id) of
{true, Temps_restant} ->
erreur("Vous êtes banni pour encore " ++ format_minutes(Temps_restant));
_ ->
Strip_content = string:strip(Content),
if Strip_content =:= [] ->
erreur("Message vide");
true ->
% TODO : non-atomique (update_pseudo+nouveau_message)
euphorik_bd:update_pseudo_user(User#user.id, Nick),
case euphorik_bd:nouveau_message(Strip_content, User#user.id, Answer_to) of
{erreur, R} -> erreur("Impossible d'ajouter un nouveau message. Raison : " ++ R);
_ ->
json_reponse_ok()
end
end
end;
_ ->
erreur("Utilisateur inconnu")
end.
% bannissement d'un utilisateur (son ip est bannie)
ban(
[
{cookie, Cookie},
{duration, Duration},
{user_id, User_id},
{reason, Reason}
]) ->
% controle que l'utilisateur est un admin
case euphorik_bd:user_by_cookie(Cookie) of
{ok, User1 = #user{ek_master = true}} ->
case euphorik_bd:user_by_id(User_id) of
{ok, User1} ->
erreur("Il n'est pas possible de s'auto bannir");
{ok, User2 = #user{ek_master = false}} ->
euphorik_bd:ban(User2#user.last_ip, Duration),
euphorik_bd:nouveau_message_sys(lists:flatten(io_lib:format("''~s~s'' est ~s pour ~s.~s",
[
User2#user.pseudo,
if User2#user.login =:= [] -> ""; true -> " (" ++ User2#user.login ++ ")" end,
if Duration =< 15 -> "kické"; true -> "banni" end,
format_minutes(Duration),
if Reason =/= [] -> " - Raison: " ++ Reason; true -> "" end ++ "."
]
))),
json_reponse_ok();
{ok, _} ->
erreur("L'utilisateur est lui même un ekMaster");
_ ->
erreur("Utilisateur à bannir inconnu")
end;
_ ->
erreur("Utilisateur inconnu ou non ek master")
end.
% slapage d'un user (avertissement)
slap(
[
{cookie, Cookie},
{user_id, User_id},
{reason, Reason}
]) ->
% controle que l'utilisateur est un admin
case euphorik_bd:user_by_cookie(Cookie) of
{ok, User1 = #user{ek_master = true}} ->
case euphorik_bd:user_by_id(User_id) of
{ok, User1} ->
euphorik_bd:nouveau_message_sys(lists:flatten(io_lib:format("~s s'auto slap~s.",
[
User1#user.pseudo,
if Reason =/= [] -> " - Raison: " ++ Reason; true -> "" end
]
))),
json_reponse_ok();
{ok, User2 = #user{ek_master = false}} ->
euphorik_bd:nouveau_message_sys(lists:flatten(io_lib:format("~s se fait slaper par ~s.~s",
[
User2#user.pseudo,
User1#user.pseudo,
if Reason =/= [] -> " - Raison: " ++ Reason; true -> "" end ++ "."
]
))),
json_reponse_ok();
{ok, _} ->
erreur("L'utilisateur est lui même un ekMaster");
_ ->
erreur("Utilisateur à slaper inconnu")
end;
_ ->
erreur("Utilisateur inconnu ou non ek master")
end.
put_troll(
[
{cookie, Cookie},
{content, Content}
]
) ->
% controle que l'utilisateur est un admin
case euphorik_bd:user_by_cookie(Cookie) of
{ok, User = #user{ek_master = true}} ->
case euphorik_bd:put_troll(User#user.id, Content) of
max_troll_reached_per_user ->
erreur(lists:flatten(io_lib:format("Le nombre de troll maximum par utilisateur est atteint : ~w ", [?NB_MAX_TROLL_WAITING_BY_USER])));
max_troll_reached ->
erreur(lists:flatten(io_lib:format("Le nombre de troll maximum en attente est atteint : ~w ", [?NB_MAX_TROLL_WAITING])));
_Id ->
json_reponse_ok()
end;
_ ->
erreur("Seul les ekMaster peuvent proposer des trolls")
end.
mod_troll(
[
{cookie, Cookie},
{troll_id, Troll_id},
{content, Content}
]
) ->
% controle que l'utilisateur est un admin
case euphorik_bd:user_by_cookie(Cookie) of
{ok, User = #user{ek_master = true}} ->
User_id = User#user.id,
case euphorik_bd:troll_by_id(Troll_id) of
{ok, #troll{id_user = User_id}} ->
euphorik_bd:mod_troll(Troll_id, Content),
json_reponse_ok();
_ ->
erreur("Vous ne posséder pas ce troll")
end;
_ ->
erreur("Seul les ekMaster peuvent proposer des trolls")
end.
del_troll(
[
{cookie, Cookie},
{troll_id, Troll_id}
]
) ->
% controle que l'utilisateur est un admin
case euphorik_bd:user_by_cookie(Cookie) of
{ok, User = #user{ek_master = true}} ->
User_id = User#user.id,
case euphorik_bd:troll_by_id(Troll_id) of
{ok, #troll{id_user = User_id}} ->
euphorik_bd:del_troll(Troll_id),
json_reponse_ok();
_ ->
erreur("Vous ne posséder pas ce troll")
end;
_ ->
erreur("Seul les ekMaster peuvent proposer des trolls")
end.
unban_ip(
[
{cookie, Cookie},
{ip, IP}
]
) ->
case euphorik_bd:user_by_cookie(Cookie) of
{ok, #user{ek_master = true}} ->
euphorik_bd:deban(unserialize_ip(IP)),
json_reponse_ok();
_ ->
erreur("Seul les ekMaster peuvent connaitre la liste des ips bannies")
end.
list_banned_ips(
[
{cookie, Cookie}
]
) ->
case euphorik_bd:user_by_cookie(Cookie) of
{ok, #user{ek_master = true}} ->
{
struct,
[
{reply, "list_banned_ips"},
{list, {array, lists:map(
fun({IP, T, Users}) ->
{struct,
[
{ip, serialize_ip(IP)},
{remaining_time, format_minutes(T)},
{users, {array, lists:map(
fun({Pseudo, Login}) ->
{struct,
[
{nick, Pseudo},
{login, Login}
]
}
end,
Users
)}}
]
}
end,
euphorik_bd:list_ban()
)}}
]
};
_ ->
erreur("Seul les ekMaster peuvent connaitre la liste des ips bannies")
end.
% Construit une erreur
erreur(Message) ->
{
struct, [
{reply, "error"},
{error_message, Message}
]
}.
serialize_ip(IP) ->
lists:flatten(io_lib:format("~w.~w.~w.~w", tuple_to_list(IP))).
unserialize_ip(IP) ->
case io_lib:fread("~d.~d.~d.~d", IP) of
{ok, [A, B, C, D], []} -> {A, B, C, D};
_ -> erreur
end.
% Formatage de minutes.
% par exemple : "1min", "45min", "1h23min", "1jour 2h34min"
format_minutes(Min) ->
Jours = Min div (60 * 24),
Heures = Min rem (60 * 24) div 60,
Minutes = Min rem (60),
if Jours =/= 0 -> integer_to_list(Jours) ++ " Jour" ++ if Jours > 1 -> "s"; true -> "" end ++ " "; true -> "" end ++
if Heures =/= 0 -> integer_to_list(Heures) ++ " heure" ++ if Heures > 1 -> "s"; true -> "" end; true -> "" end ++
if Minutes == 0 ->
"";
true ->
" " ++ integer_to_list(Minutes) ++ " minute" ++ if Minutes > 1 -> "s"; true -> "" end
end.
% Formatage d'une heure
% local_time() -> string
format_date(Date) ->
DateLocal = calendar:now_to_local_time(Date),
DateNowLocal = calendar:local_time(),
{{Annee, Mois, Jour}, {Heure, Minute, Seconde}} = DateLocal,
{{AnneeNow, _, _}, {_, _, _}} = DateNowLocal,
Hier = calendar:date_to_gregorian_days(element(1, DateLocal)) =:= calendar:date_to_gregorian_days(element(1, DateNowLocal)) - 1,
lists:flatten(
if element(1, DateLocal) =:= element(1, DateNowLocal) ->
"";
Hier ->
"Hier ";
Annee =:= AnneeNow ->
io_lib:format("~2.10.0B/~2.10.0B ", [Jour, Mois]);
true ->
io_lib:format("~2.10.0B/~2.10.0B/~B ", [Jour, Mois, Annee])
end ++
io_lib:format("~2.10.0B:~2.10.0B:~2.10.0B", [Heure, Minute, Seconde])
).
json_reponse_ok() ->
{struct, [{reply, "ok"}]}.
json_reponse_login_ok(User) ->
{
struct, [
{reply, "login"},
{status, if (User#user.password =/= []) and (User#user.login =/= []) -> "auth_registered"; true -> "auth_not_registered" end},
{cookie, User#user.cookie},
{id, User#user.id},
{nick, User#user.pseudo},
{login, User#user.login},
{email, User#user.email},
{css, User#user.css},
{nick_format, atom_to_list(User#user.nick_format)},
{view_times, User#user.view_times},
{view_tooltips, User#user.view_tooltips},
{main_page, User#user.page_principale},
{conversations,
{array,
lists:map(
fun(C) ->
{struct,
[
{root, element(1, C)},
{page, element(2, C)}
]
}
end,
User#user.conversations
)
}
},
{ek_master, User#user.ek_master}
]
}.