REPORT de la branche 1.0
[euphorik.git] / modules / erl / euphorik_protocole.erl
index 08624ae..ae79d84 100755 (executable)
@@ -1,7 +1,25 @@
-% coding: utf-8
+% coding: utf-8\r
+% Copyright 2008 Grégory Burri\r
+%\r
+% This file is part of Euphorik.\r
+%\r
+% Euphorik is free software: you can redistribute it and/or modify\r
+% it under the terms of the GNU General Public License as published by\r
+% the Free Software Foundation, either version 3 of the License, or\r
+% (at your option) any later version.\r
+%\r
+% Euphorik is distributed in the hope that it will be useful,\r
+% but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+% GNU General Public License for more details.\r
+%\r
+% You should have received a copy of the GNU General Public License\r
+% along with Euphorik.  If not, see <http://www.gnu.org/licenses/>.\r
+% 
 % 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
+\r
 
 -module(euphorik_protocole).
 -export([
    put_troll/1,
    mod_troll/1,
    del_troll/1,
+   unban_ip/1,
+   list_banned_ips/1,
    erreur/1
 ]).
--include_lib("xmerl/include/xmerl.hrl").
 -include("../include/euphorik_bd.hrl").\r
 -include("../include/euphorik_defines.hrl").\r
 
@@ -66,13 +85,13 @@ loginUser({ok, User}, IP) ->
    json_reponse_login_ok(User);
 loginUser(_, _) ->
    % ajoute un délais d'attente
-   timer:sleep(1000),
-   erreur("Erreur login").
+   timer:sleep(?TEMPS_ATTENTE_ERREUR_LOGIN),
+   erreur("Couple login/pass introuvable").
    
    \r
 % Renvoie un string() représentant un cookie en base 36. Il y a 10^32 possibillités.\r
 generer_cookie() ->
-   {A1,A2,A3} = now(),
+   {A1, A2, A3} = now(),
    random:seed(A1, A2, A3),\r
    erlang:integer_to_list(random:uniform(math:pow(10, 32)), 36).\r
 
@@ -92,6 +111,8 @@ profile(
       {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}}
    ]
@@ -109,7 +130,19 @@ profile(
       [],
       Conversations_json
    ),
-   case euphorik_bd:set_profile(Cookie, Login, Password, Pseudo, Email, Css, list_to_atom(Nick_format_str), Main_page, Conversations) of
+   %  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 ->
@@ -151,7 +184,13 @@ wait_event([{page, "chat"} | Data]) ->
          R
    end;
 wait_event([{page, "admin"}, {last_troll, Last_troll}]) ->
-   case euphorik_bd:trolls_attente(Last_troll) of
+   case wait_event_page_admin(Last_troll) of
+      banned_ips_refresh ->
+         {struct, 
+            [
+               {reply, "banned_ips_refresh"}
+            ]
+         };
       {mod, Troll} ->
          {struct,
             [
@@ -203,6 +242,7 @@ wait_event_page_chat(User, Racines_conversations, Message_count, Last_message_id
          {struct, [
             {reply, "new_troll"},
             {troll_id, Current#troll.id},
+            {message_id, euphorik_bd:message_id_associe(Current#troll.id)},
             {content, Current#troll.content}
          ]};
       _ ->
@@ -278,7 +318,59 @@ wait_event_bd_page_chat() ->
    % Après 60 minutes de connexion, le client doit donc reétablir une connexion
    after 1000 * 60 * 60 -> 
       timeout
-   end.           
+   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
@@ -312,21 +404,6 @@ put_message(
    _ ->
       erreur("Utilisateur inconnu")
    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) ++ "h"; true -> "" end ++
-   if Minutes == 0 ->
-         "";
-      true ->
-         lists:flatten(io_lib:format(if Jours =:= 0, Heures =:= 0 -> "~w"; true -> "~2.2.0w" end, [Minutes])) ++ "min"
-   end.
 
 
 % bannissement d'un utilisateur (son ip est bannie)
@@ -345,10 +422,10 @@ ban(
                   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",
+                  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 User2#user.login =:= [] -> ""; true -> " (" ++ User2#user.login ++ ")" end,
                         if Duration =< 15 -> "kické"; true -> "banni" end,
                         format_minutes(Duration),
                         if Reason =/= [] -> " - Raison: " ++ Reason; true -> "" end ++ "."
@@ -469,6 +546,61 @@ del_troll(
          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(euphorik_common: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, 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("Seul les ekMaster peuvent connaitre la liste des ips bannies")
+   end.
+
 
 % Construit une erreur
 erreur(Message) ->
@@ -479,6 +611,21 @@ erreur(Message) ->
       ]
    }.
    
+   
+% 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.
+   
    \r
 % Formatage d'une heure\r
 % local_time() -> string\r
@@ -518,6 +665,8 @@ json_reponse_login_ok(User) ->
          {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,