% 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,
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}, {profile, Profile_json}], IP) ->
Can_register = euphorik_bd:can_register(IP),
if Can_register ->
case euphorik_bd:user_by_login(Login) of
{ok, _} ->
erreur(10);
_ ->
User = euphorik_bd:nouveau_user(Login, Password, generer_cookie(), profile_from_json(Profile_json)),
euphorik_bd:update_ip(User#user.id, IP),
json_reponse_login_ok(User)
end;
true ->
erreur_register_flood()
end;
% Enregistrement sans {Login, Password}
register([{profile, Profile_json}], IP) ->
Can_register = euphorik_bd:can_register(IP),
if Can_register ->
Profile = profile_from_json(Profile_json),
User = euphorik_bd:nouveau_user(generer_cookie(), Profile#profile{pseudo = ""}),
euphorik_bd:update_ip(User#user.id, IP),
json_reponse_login_ok(User);
true ->
erreur_register_flood()
end.
erreur_register_flood() ->
erreur(20).
% Un utilisateur se logge (avec un couple {login, mot de passe})
login([{login, Login}, {password, Password}], IP) ->
case euphorik_bd:user_by_login_password(Login, Password) of
{ok, User} ->
loginUser(User, IP);
_ ->
timer:sleep(?TEMPS_ATTENTE_ERREUR_LOGIN),
erreur(30)
end;
% Un utilisateur se logge (avec un cookie)
login([{cookie, Cookie}], IP) ->
case euphorik_bd:user_by_cookie(Cookie) of
{ok, User} ->
loginUser(User, IP);
_ ->
timer:sleep(?TEMPS_ATTENTE_ERREUR_LOGIN),
erreur(40)
end.
% L'utilisateur donné se logge avec l'ip donnée.
loginUser(User, IP) ->
euphorik_bd:update_ip(User#user.id, IP),
euphorik_bd:update_date_derniere_connexion(User#user.id),
json_reponse_login_ok(User).
% 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).
% Modification du profile.
profile(
[
{cookie, Cookie},
{login, Login},
{password, Password},
{profile, Profile_json}
]
) ->
case profile_from_json(Profile_json) of
{erreur, E} -> E;
Profile ->
case euphorik_bd:set_profile(Cookie, Login, Password, Profile) of
ok ->
json_reponse_ok();
login_deja_pris ->
erreur(10);
_ ->
erreur(50)
end
end.
% Construit un #user à partir des données JSON
profile_from_json(
{struct,
[
{nick, Pseudo},
{email, Email},
{css, Css},
{chat_order, Chat_order_str},
{nick_format, Nick_format_str},
{view_times, View_times},
{view_tooltips, View_tooltips},
{conversations, {array, Conversations_json}},
{ostentatious_master, Ostentatious_master_str}
]
}
) ->
% décomposition de la strucure JSON
Conversations = lists:foldr(
fun({struct, [{root, Racine}, {minimized, Reduit}]}, A) ->
% virage des messages qui n'existent pas
Message_exite = euphorik_bd:message_existe(Racine),
if Message_exite ->
[ {Racine, Reduit} | A];
true ->
A
end
end,
[],
Conversations_json
),
% vérification des données JSON
Chat_order = list_to_atom(Chat_order_str),
Chat_order_valide = lists:any(fun(E) -> E =:= Chat_order end, [reverse, chrono]),
if not Chat_order_valide ->
{erreur, Chat_order_str ++ " n'est pas une valeur acceptée pour 'chat_order'"};
true ->
Nick_format = list_to_atom(Nick_format_str),
Nick_format_valide = lists:any(fun(E) -> E =:= Nick_format end, [nick, login, nick_login]),
if not Nick_format_valide ->
{erreur, Nick_format_str ++ " n'est pas une valeur acceptée pour 'nick_format'"};
true ->
Ostentatious_master = list_to_atom(Ostentatious_master_str),
Ostentatious_master_valide = lists:any(fun(E) -> E =:= Ostentatious_master end, [invisible, light, heavy]),
if not Ostentatious_master_valide ->
{erreur, Ostentatious_master_str ++ " n'est pas une valeur acceptée pour 'ostentatious_master'"};
true ->
#profile{
pseudo = Pseudo,
email = Email,
css = Css,
chat_order = Chat_order,
nick_format = Nick_format,
view_times = View_times,
view_tooltips = View_tooltips,
conversations = Conversations,
ostentatious_master = Ostentatious_master
}
end
end
end.
% Attend un événement pour la page "Chat"
% 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;
% Attend un événement pour la page "Admin"
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{profile = Profile} = User} = euphorik_bd:user_by_id(T#troll.id_user),
{struct,
[
{troll_id, T#troll.id},
{content, T#troll.content},
{author, Profile#profile.pseudo},
{author_id, User#user.id}
]
}
end,
Trolls
)
}}
]
};
{del, Troll_id} ->
{struct,
[
{reply, "troll_deleted"},
{troll_id, Troll_id}
]
};
_ ->
erreur(60)
end;
wait_event(_) ->
erreur(70).
% Attend un événement pour la page "Chat" et renvoie soit un troll soit les messages manquants au client.
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, Current#troll.id_minichat},
{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(),
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({Racine, {Conv, Plus}}) ->
{struct, [
{last_page, not Plus},
{first, % le premier message de la conversation
if Racine =:= undefined orelse Conv =:= [] ->
null;
true ->
{Racine_id, _, _} = Racine,
case euphorik_bd:message_by_id(Racine_id) of
{ok, Mess} ->
json_message(Mess, euphorik_bd:parents(Racine_id), User);
_ ->
null
end
end
},
{messages, {array,
lists:map(
fun({Mess, Repond_a}) ->
json_message(Mess, Repond_a, User)
end,
Conv
)
}}
]}
end,
% on ajoute un 'undefined' correspondant à la premier conversation qui ne possède pas de racine
% TODO : peut être à revoir car un peu lourd est compliqué
aggregation_racines_conversations([undefined | Racines_conversations], Conversations)
)
}}
]}
end
end.
aggregation_racines_conversations(L1, L2) ->
aggregation_racines_conversations(L1, L2, []).
aggregation_racines_conversations([], [], L) -> lists:reverse(L);
aggregation_racines_conversations([E1|R1], [E2|R2], L) ->
aggregation_racines_conversations(R1, R2, [{E1, E2} | L]).
% 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
% Answer_to est une liste d'id (int)
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(80, [format_minutes(Temps_restant)]);
_ ->
Strip_content = string:strip(Content),
if Strip_content =:= [] ->
erreur(90);
true ->
% attention : 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(100, [R]);
_ ->
json_reponse_ok()
end
end
end;
_ ->
erreur(110)
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(120);
{ok, #user{ek_master = false, profile = Profile2} = User2} ->
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",
[
Profile2#profile.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(130);
_ ->
erreur(140)
end;
_ ->
erreur(150)
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, profile = Profile1}} ->
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.",
[
Profile1#profile.pseudo,
if Reason =/= [] -> " - Raison: " ++ Reason; true -> "" end
]
))),
json_reponse_ok();
{ok, #user{ek_master = false, profile = Profile2}} ->
euphorik_bd:nouveau_message_sys(lists:flatten(io_lib:format("~s se fait slaper par ~s.~s",
[
Profile2#profile.pseudo,
Profile1#profile.pseudo,
if Reason =/= [] -> " - Raison: " ++ Reason; true -> "" end ++ "."
]
))),
json_reponse_ok();
{ok, _} ->
erreur(130);
_ ->
erreur(160)
end;
_ ->
erreur(170)
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(180, [?NB_MAX_TROLL_WAITING_BY_USER]);
max_troll_reached ->
erreur(190, [?NB_MAX_TROLL_WAITING]);
_Id ->
json_reponse_ok()
end;
_ ->
erreur(200)
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(210)
end;
_ ->
erreur(220)
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(210)
end;
_ ->
erreur(220)
end.
unban_ip(
[
{cookie, Cookie},
{ip, IP}
]
) ->
case euphorik_bd:user_by_cookie(Cookie) of
{ok, #user{ek_master = true}} ->
euphorik_bd:deban(euphorik_common:unserialize_ip(IP)),
json_reponse_ok();
_ ->
erreur(230)
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, euphorik_common: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(230)
end.
% Construit une erreur
erreur(Num, Args) ->
erreur_json(Num, lists:flatten(io_lib:format(euphorik_bd:get_texte(Num), Args))).
erreur(Num) ->
erreur_json(Num, euphorik_bd:get_texte(Num)).
erreur_json(Num, Mess) ->
{
struct, [
{reply, "error"},
{no, Num},
{error_message, Mess}
]
}.
% 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{profile = Profile} = 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},
{login, User#user.login},
{ek_master, User#user.ek_master},
{profile, {struct,
[
{nick, Profile#profile.pseudo},
{email, Profile#profile.email},
{css, Profile#profile.css},
{chat_order, atom_to_list(Profile#profile.chat_order)},
{nick_format, atom_to_list(Profile#profile.nick_format)},
{view_times, Profile#profile.view_times},
{view_tooltips, Profile#profile.view_tooltips},
{conversations, {array, lists:map(
fun({Racine, Reduit}) ->
{struct, [{root, Racine}, {minimized, Reduit}]}
end,
Profile#profile.conversations
)}},
{ostentatious_master, atom_to_list(Profile#profile.ostentatious_master)}
]
}}
]
}.
% Renvoie le message formaté en JSON.
% Mess est de type #minichat
% Repond_a est une liste d'id des messages auquel répond Mess
% User est l'utilisateur courant de type #user
json_message(Mess, Repond_a, User) ->
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{profile = Profile_mess} = User_mess } = euphorik_bd:user_by_id(Mess#minichat.auteur_id),
{struct, [
{id, Mess#minichat.id},
{user_id, User_mess#user.id},
{date, case Mess#minichat.date of undefined -> "?"; _ -> format_date(Mess#minichat.date) end},
{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},
{root, Mess#minichat.racine_id},
{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},
{ostentatious_master, atom_to_list(Profile_mess#profile.ostentatious_master)}
]}.