2 % Copyright 2008 Grégory Burri
4 % This file is part of Euphorik.
6 % Euphorik is free software: you can redistribute it and/or modify
7 % it under the terms of the GNU General Public License as published by
8 % the Free Software Foundation, either version 3 of the License, or
9 % (at your option) any later version.
11 % Euphorik is distributed in the hope that it will be useful,
12 % but WITHOUT ANY WARRANTY; without even the implied warranty of
13 % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 % GNU General Public License for more details.
16 % You should have received a copy of the GNU General Public License
17 % along with Euphorik. If not, see <http://www.gnu.org/licenses/>.
19 % Ce module gére les différents messages envoyés par le client (javascript) via AJAX.
20 % Les messages donnés ainsi que les réponses sont au format JSON.
24 -module(euphorik_protocole
).
40 -include("../include/euphorik_bd.hrl").
41 -include("../include/euphorik_defines.hrl").
44 % Une utilisateur s'enregistre avec un tuple {Login, Password}.
45 register([{login
, Login
}, {password
, Password
}, {profile
, Profile_json
}], IP
) ->
46 Can_register
= euphorik_bd:can_register(IP
),
48 case euphorik_bd:user_by_login(Login
) of
52 User
= euphorik_bd:nouveau_user(Login
, Password
, generer_cookie(), profile_from_json(Profile_json
)),
53 euphorik_bd:update_ip(User#user
.id
, IP
),
54 json_reponse_login_ok(User
)
57 erreur_register_flood()
59 % Enregistrement sans {Login, Password}
60 register([{profile
, Profile_json
}], IP
) ->
61 Can_register
= euphorik_bd:can_register(IP
),
63 Profile
= profile_from_json(Profile_json
),
64 User
= euphorik_bd:nouveau_user(generer_cookie(), Profile#profile
{pseudo
= "<nick>"}),
65 euphorik_bd:update_ip(User#user
.id
, IP
),
66 json_reponse_login_ok(User
);
68 erreur_register_flood()
71 erreur_register_flood() ->
75 % Un utilisateur se logge (avec un couple {login, mot de passe})
76 login([{login
, Login
}, {password
, Password
}], IP
) ->
77 case euphorik_bd:user_by_login_password(Login
, Password
) of
81 timer:sleep(?TEMPS_ATTENTE_ERREUR_LOGIN
),
84 % Un utilisateur se logge (avec un cookie)
85 login([{cookie
, Cookie
}], IP
) ->
86 case euphorik_bd:user_by_cookie(Cookie
) of
90 timer:sleep(?TEMPS_ATTENTE_ERREUR_LOGIN
),
95 % L'utilisateur donné se logge avec l'ip donnée.
96 loginUser(User
, IP
) ->
97 euphorik_bd:update_ip(User#user
.id
, IP
),
98 euphorik_bd:update_date_derniere_connexion(User#user
.id
),
99 json_reponse_login_ok(User
).
102 % Renvoie un string() représentant un cookie en base 36. Il y a 10^32 possibillités.
104 {A1
, A2
, A3
} = now(),
105 random:seed(A1
, A2
, A3
),
106 erlang:integer_to_list(random:uniform(math:pow(10, 32)), 36).
109 % Modification du profile.
114 {password
, Password
},
115 {profile
, Profile_json
}
118 case profile_from_json(Profile_json
) of
121 case euphorik_bd:set_profile(Cookie
, Login
, Password
, Profile
) of
132 % Construit un #user à partir des données JSON
139 {chat_order
, Chat_order_str
},
140 {nick_format
, Nick_format_str
},
141 {view_times
, View_times
},
142 {view_tooltips
, View_tooltips
},
143 {conversations
, {array
, Conversations_json
}},
144 {ostentatious_master
, Ostentatious_master_str
}
148 % décomposition de la strucure JSON
149 Conversations
= lists:foldr(
150 fun({struct
, [{root
, Racine
}, {minimized
, Reduit
}]}, A
) ->
151 % virage des messages qui n'existent pas
152 Message_exite
= euphorik_bd:message_existe(Racine
),
154 [ {Racine
, Reduit
} | A
];
162 % vérification des données JSON
163 Chat_order
= list_to_atom(Chat_order_str
),
164 Chat_order_valide
= lists:any(fun(E
) -> E
=:= Chat_order
end, [reverse
, chrono
]),
165 if not Chat_order_valide
->
166 {erreur
, Chat_order_str
++ " n'est pas une valeur acceptée pour 'chat_order'"};
168 Nick_format
= list_to_atom(Nick_format_str
),
169 Nick_format_valide
= lists:any(fun(E
) -> E
=:= Nick_format
end, [nick
, login
, nick_login
]),
170 if not Nick_format_valide
->
171 {erreur
, Nick_format_str
++ " n'est pas une valeur acceptée pour 'nick_format'"};
173 Ostentatious_master
= list_to_atom(Ostentatious_master_str
),
174 Ostentatious_master_valide
= lists:any(fun(E
) -> E
=:= Ostentatious_master
end, [invisible
, light
, heavy
]),
175 if not Ostentatious_master_valide
->
176 {erreur
, Ostentatious_master_str
++ " n'est pas une valeur acceptée pour 'ostentatious_master'"};
182 chat_order
= Chat_order
,
183 nick_format
= Nick_format
,
184 view_times
= View_times
,
185 view_tooltips
= View_tooltips
,
186 conversations
= Conversations
,
187 ostentatious_master
= Ostentatious_master
194 % Attend un événement pour la page "Chat"
195 % last_message id et cookie sont facultatifs
196 wait_event([{page
, "chat"} | Data
]) ->
197 % traitement des inputs
198 Cookie
= case lists:keysearch(cookie
, 1, Data
) of {value
, {_
, C
}} -> C
; _
-> inconnu
end,
199 Last_message_id
= case lists:keysearch(last_message_id
, 1, Data
) of {value
, {_
, Id
}} -> Id
; _
-> 0 end,
200 {value
, {_
, Message_count
}} = lists:keysearch(message_count
, 1, Data
),
201 Main_page
= case lists:keysearch(main_page
, 1, Data
) of {value
, {_
, P
}} -> P
; _
-> 1 end,
202 Troll_id
= case lists:keysearch(troll_id
, 1, Data
) of {value
, {_
, T
}} -> T
; _
-> 0 end,
203 {value
, {_
, {array
, Conversations_json
}}} = lists:keysearch(conversations
, 1, Data
),
204 Racines_conversations
= lists:map(
205 fun({struct
, [{root
, Racine
}, {page
, Page
} | Reste
]}) ->
206 Last_mess_conv
= case Reste
of [{last_message_id
, L
}] -> L
; _
-> 0 end,
207 {Racine
, Page
, Last_mess_conv
}
211 User
= case euphorik_bd:user_by_cookie(Cookie
) of
215 case {mnesia:subscribe({table
, minichat
, detailed
}), mnesia:subscribe({table
, troll
, detailed
})} of
216 {{error
, E
}, _
} -> E
;
217 {_
, {error
, E
}} -> E
;
219 % attente d'événements
220 R
= wait_event_page_chat(User
, Racines_conversations
, Message_count
, Last_message_id
, Main_page
, Troll_id
),
221 mnesia:unsubscribe({table
, minichat
, detailed
}),
222 mnesia:unsubscribe({table
, troll
, detailed
}),
225 % Attend un événement pour la page "Admin"
226 wait_event([{page
, "admin"}, {last_troll
, Last_troll
}]) ->
227 case wait_event_page_admin(Last_troll
) of
228 banned_ips_refresh
->
231 {reply
, "banned_ips_refresh"}
237 {reply
, "troll_modified"},
238 {troll_id
, Troll#troll
.id
},
239 {content
, Troll#troll
.content
}
245 {reply
, "troll_added"},
249 {ok
, #user
{profile
= Profile
} = User
} = euphorik_bd:user_by_id(T#troll
.id_user
),
252 {troll_id
, T#troll
.id
},
253 {content
, T#troll
.content
},
254 {author
, Profile#profile
.pseudo
},
255 {author_id
, User#user
.id
}
267 {reply
, "troll_deleted"},
278 % Attend un événement pour la page "Chat" et renvoie soit un troll soit les messages manquants au client.
279 wait_event_page_chat(User
, Racines_conversations
, Message_count
, Last_message_id
, Main_page
, Troll_id
) ->
280 % est-ce que le troll est à jour ?
281 case euphorik_bd:current_troll() of
282 Current
when is_record(Current
, troll
), Current#troll
.id
=/= Troll_id
->
284 {reply
, "new_troll"},
285 {troll_id
, Current#troll
.id
},
286 {message_id
, Current#troll
.id_minichat
},
287 {content
, Current#troll
.content
}
290 % est-ce qu'il y a des nouveaux messages ?
291 case euphorik_minichat_conversation:conversations(Racines_conversations
, Message_count
, Last_message_id
, Main_page
) of
293 wait_event_bd_page_chat(),
294 wait_event_page_chat(User
, Racines_conversations
, Message_count
, Last_message_id
, Main_page
, Troll_id
);
296 % accrochez-vous ca va siouxer ;)
298 {reply
, "new_messages"},
299 {conversations
, {array
,
301 fun({Racine
, {Conv
, Plus
}}) ->
303 {last_page
, not Plus
},
304 {first
, % le premier message de la conversation
305 if Racine
=:= undefined orelse Conv
=:= [] ->
308 {Racine_id
, _
, _
} = Racine
,
309 case euphorik_bd:message_by_id(Racine_id
) of
311 json_message(Mess
, euphorik_bd:parents(Racine
), User
);
319 fun({Mess
, Repond_a
}) ->
320 json_message(Mess
, Repond_a
, User
)
327 % on ajoute un 'undefined' correspondant à la premier conversation qui ne possède pas de racine
328 % TODO : peut être à revoir car un peu lourd est compliqué
329 aggregation_racines_conversations([undefined
| Racines_conversations
], Conversations
)
337 aggregation_racines_conversations(L1
, L2
) ->
338 aggregation_racines_conversations(L1
, L2
, []).
339 aggregation_racines_conversations([], [], L
) -> lists:reverse(L
);
340 aggregation_racines_conversations([E1
|R1
], [E2
|R2
], L
) ->
341 aggregation_racines_conversations(R1
, R2
, [{E1
, E2
} | L
]).
345 % Attend un événement lié à la page 'chat'.
346 wait_event_bd_page_chat() ->
347 receive % attente d'un post
348 {mnesia_table_event
, {write
, minichat
, _Message
, [], _
}} ->
350 {mnesia_table_event
, {write
, troll
, Troll
, [Old_troll
| _
], _
}} when Troll#troll
.date_post
=/= undefined
, Old_troll#troll
.date_post
== undefined
->
355 wait_event_bd_page_chat()
356 % 60 minutes de timeout (on ne sais jamais)
357 % Après 60 minutes de connexion, le client doit donc reétablir une connexion
358 after 1000 * 60 * 60 ->
363 % Attent un événement concernant la page admin
364 % Renvoie les trolls manquants posté après Last_id ou banned_ips_refresh.
365 % Si pas de trolls alors attend un événement tel qu'un ajout, une modification ou une suppression.
370 % ou banned_ips_refresh
372 wait_event_page_admin(Last_id
) ->
373 case {mnesia:subscribe({table
, troll
, detailed
}), mnesia:subscribe({table
, ip_table
, detailed
})} of
374 {{error
, E
}, _
} -> E
;
375 {_
, {error
, E
}} -> E
;
377 R
= case euphorik_bd:trolls(Last_id
) of
378 [] -> % pas de trolls
379 wait_event_page_admin();
383 mnesia:unsubscribe({table
, troll
, detailed
}),
384 mnesia:unsubscribe({table
, ip_table
, detailed
}),
388 wait_event_page_admin() ->
389 % s'il n'y a pas de trolls que l'utilisateur n'a pas connaissance alors on attend un événement
391 % cas où un troll est choisit comme courant
392 {mnesia_table_event
, {write
, troll
, Troll
, [Old_troll
| _
], _
}}
393 when Old_troll#troll
.date_post
=:= undefined
, Troll#troll
.date_post
=/= undefined
->
394 {del
, Troll#troll
.id
};
395 {mnesia_table_event
, {write
, troll
, Troll
, [_Old_troll
| _
], _
}} ->
397 {mnesia_table_event
, {write
, troll
, Troll
, [], _
}} ->
399 {mnesia_table_event
, {delete
, troll
, {troll
, Id
}, _
, _
}} ->
401 {mnesia_table_event
, {write
, ip_table
, IP
, [Old_IP
| _
], _
}}
402 when Old_IP#ip_table
.ban
=/= IP#ip_table
.ban
; Old_IP#ip_table
.ban_duration
=/= IP#ip_table
.ban_duration
->
407 wait_event_page_admin()
408 % 60 minutes de timeout (on ne sais jamais)
409 % Après 60 minutes de connexion, le client doit donc reétablir une connexion
410 after 1000 * 60 * 60 ->
415 % Un utilisateur envoie un message
416 % Answer_to est une liste d'id (int)
422 {answer_to
, {array
, Answer_to
}}
425 case euphorik_bd:user_by_cookie(Cookie
) of
427 case euphorik_bd:est_banni(User#user
.id
) of
428 {true
, Temps_restant
} ->
429 erreur(80, [format_minutes(Temps_restant
)]);
431 Strip_content
= string:strip(Content
),
432 if Strip_content
=:= [] ->
435 % attention : non-atomique (update_pseudo+nouveau_message)
436 euphorik_bd:update_pseudo_user(User#user
.id
, Nick
),
437 case euphorik_bd:nouveau_message(Strip_content
, User#user
.id
, Answer_to
) of
438 {erreur
, R
} -> erreur(100, [R
]);
449 % bannissement d'un utilisateur (son ip est bannie)
453 {duration
, Duration
},
457 % controle que l'utilisateur est un admin
458 case euphorik_bd:user_by_cookie(Cookie
) of
459 {ok
, User1
= #user
{ek_master
= true
}} ->
460 case euphorik_bd:user_by_id(User_id
) of
463 {ok
, #user
{ek_master
= false
, profile
= Profile2
} = User2
} ->
464 euphorik_bd:ban(User2#user
.last_ip
, Duration
),
465 euphorik_bd:nouveau_message_sys(lists:flatten(io_lib:format("\"~s~s\" est ~s pour ~s.~s",
467 Profile2#profile
.pseudo
,
468 if User2#user
.login
=:= [] -> ""; true
-> " (" ++ User2#user
.login
++ ")" end,
469 if Duration
=< 15 -> "kické"; true
-> "banni" end,
470 format_minutes(Duration
),
471 if Reason
=/= [] -> " - Raison: " ++ Reason
; true
-> "" end ++ "."
485 % slapage d'un user (avertissement)
492 % controle que l'utilisateur est un admin
493 case euphorik_bd:user_by_cookie(Cookie
) of
494 {ok
, User1
= #user
{ek_master
= true
, profile
= Profile1
}} ->
495 case euphorik_bd:user_by_id(User_id
) of
497 euphorik_bd:nouveau_message_sys(lists:flatten(io_lib:format("~s s'auto slap~s.",
499 Profile1#profile
.pseudo
,
500 if Reason
=/= [] -> " - Raison: " ++ Reason
; true
-> "" end
504 {ok
, #user
{ek_master
= false
, profile
= Profile2
}} ->
505 euphorik_bd:nouveau_message_sys(lists:flatten(io_lib:format("~s se fait slaper par ~s.~s",
507 Profile2#profile
.pseudo
,
508 Profile1#profile
.pseudo
,
509 if Reason
=/= [] -> " - Raison: " ++ Reason
; true
-> "" end ++ "."
529 % controle que l'utilisateur est un admin
530 case euphorik_bd:user_by_cookie(Cookie
) of
531 {ok
, User
= #user
{ek_master
= true
}} ->
532 case euphorik_bd:put_troll(User#user
.id
, Content
) of
533 max_troll_reached_per_user
->
534 erreur(180, [?NB_MAX_TROLL_WAITING_BY_USER
]);
536 erreur(190, [?NB_MAX_TROLL_WAITING
]);
548 {troll_id
, Troll_id
},
552 % controle que l'utilisateur est un admin
553 case euphorik_bd:user_by_cookie(Cookie
) of
554 {ok
, User
= #user
{ek_master
= true
}} ->
555 User_id
= User#user
.id
,
556 case euphorik_bd:troll_by_id(Troll_id
) of
557 {ok
, #troll
{id_user
= User_id
}} ->
558 euphorik_bd:mod_troll(Troll_id
, Content
),
574 % controle que l'utilisateur est un admin
575 case euphorik_bd:user_by_cookie(Cookie
) of
576 {ok
, User
= #user
{ek_master
= true
}} ->
577 User_id
= User#user
.id
,
578 case euphorik_bd:troll_by_id(Troll_id
) of
579 {ok
, #troll
{id_user
= User_id
}} ->
580 euphorik_bd:del_troll(Troll_id
),
596 case euphorik_bd:user_by_cookie(Cookie
) of
597 {ok
, #user
{ek_master
= true
}} ->
598 euphorik_bd:deban(euphorik_common:unserialize_ip(IP
)),
610 case euphorik_bd:user_by_cookie(Cookie
) of
611 {ok
, #user
{ek_master
= true
}} ->
615 {reply
, "list_banned_ips"},
616 {list, {array
, lists:map(
617 fun({IP
, T
, Users
}) ->
620 {ip
, euphorik_common:serialize_ip(IP
)},
621 {remaining_time
, format_minutes(T
)},
622 {users
, {array
, lists:map(
623 fun({Pseudo
, Login
}) ->
636 euphorik_bd:list_ban()
645 % Construit une erreur
647 erreur_json(Num
, lists:flatten(io_lib:format(euphorik_bd:get_texte(Num
), Args
))).
651 erreur_json(Num
, euphorik_bd:get_texte(Num
)).
654 erreur_json(Num
, Mess
) ->
659 {error_message
, Mess
}
664 % Formatage de minutes.
665 % par exemple : "1min", "45min", "1h23min", "1jour 2h34min"
666 format_minutes(Min
) ->
667 Jours
= Min
div (60 * 24),
668 Heures
= Min
rem (60 * 24) div
60,
669 Minutes
= Min
rem (60),
670 if Jours
=/= 0 -> integer_to_list(Jours
) ++ " Jour" ++ if Jours
> 1 -> "s"; true
-> "" end ++ " "; true
-> "" end ++
671 if Heures
=/= 0 -> integer_to_list(Heures
) ++ " heure" ++ if Heures
> 1 -> "s"; true
-> "" end; true
-> "" end ++
675 " " ++ integer_to_list(Minutes
) ++ " minute" ++ if Minutes
> 1 -> "s"; true
-> "" end
679 % Formatage d'une heure
680 % local_time() -> string
682 DateLocal
= calendar:now_to_local_time(Date
),
683 DateNowLocal
= calendar:local_time(),
684 {{Annee
, Mois
, Jour
}, {Heure
, Minute
, Seconde
}} = DateLocal
,
685 {{AnneeNow
, _
, _
}, {_
, _
, _
}} = DateNowLocal
,
686 Hier
= calendar:date_to_gregorian_days(element(1, DateLocal
)) =:= calendar:date_to_gregorian_days(element(1, DateNowLocal
)) - 1,
688 if element(1, DateLocal
) =:= element(1, DateNowLocal
) ->
692 Annee
=:= AnneeNow
->
693 io_lib:format("~2.10.0B/~2.10.0B ", [Jour
, Mois
]);
695 io_lib:format("~2.10.0B/~2.10.0B/~B ", [Jour
, Mois
, Annee
])
697 io_lib:format("~2.10.0B:~2.10.0B:~2.10.0B", [Heure
, Minute
, Seconde
])
702 {struct
, [{reply
, "ok"}]}.
705 json_reponse_login_ok(#user
{profile
= Profile
} = User
) ->
709 {status
, if (User#user
.password
=/= []) and (User#user
.login
=/= []) -> "auth_registered"; true
-> "auth_not_registered" end},
710 {cookie
, User#user
.cookie
},
712 {login
, User#user
.login
},
713 {ek_master
, User#user
.ek_master
},
716 {nick
, Profile#profile
.pseudo
},
717 {email
, Profile#profile
.email
},
718 {css
, Profile#profile
.css
},
719 {chat_order
, atom_to_list(Profile#profile
.chat_order
)},
720 {nick_format
, atom_to_list(Profile#profile
.nick_format
)},
721 {view_times
, Profile#profile
.view_times
},
722 {view_tooltips
, Profile#profile
.view_tooltips
},
723 {conversations
, {array
, lists:map(
724 fun({Racine
, Reduit
}) ->
725 {struct
, [{root
, Racine
}, {minimized
, Reduit
}]}
727 Profile#profile
.conversations
729 {ostentatious_master
, atom_to_list(Profile#profile
.ostentatious_master
)}
735 % Renvoie le message formaté en JSON.
736 % Mess est de type #minichat
737 % Repond_a est une liste d'id des messages auquel répond Mess
738 % User est l'utilisateur courant de type #user
739 json_message(Mess
, Repond_a
, User
) ->
740 Est_proprietaire
= User
=/= inconnu andalso User#user
.id
=:= Mess#minichat
.auteur_id
,
741 A_repondu_a_message
= User
=/= inconnu andalso
euphorik_bd:a_repondu_a_message(User#user
.id
, Mess#minichat
.id
),
742 Est_une_reponse_a_user
= User
=/= inconnu andalso
euphorik_bd:est_une_reponse_a_user(User#user
.id
, Mess#minichat
.id
),
743 {ok
, #user
{profile
= Profile_mess
} = User_mess
} = euphorik_bd:user_by_id(Mess#minichat
.auteur_id
),
745 {id
, Mess#minichat
.id
},
746 {user_id
, User_mess#user
.id
},
747 {date, format_date(Mess#minichat
.date)},
748 {system
, Mess#minichat
.auteur_id
=:= 0},
749 {owner
, Est_proprietaire
},
750 {answered
, A_repondu_a_message
},
751 {is_a_reply
, Est_une_reponse_a_user
},
752 {nick
, Mess#minichat
.pseudo
},
753 {login
, User_mess#user
.login
},
754 {content
, Mess#minichat
.contenu
},
755 {root
, Mess#minichat
.racine_id
},
756 {answer_to
, {array
, lists:map(
758 {ok
, M
} = euphorik_bd:message_by_id(Id_mess
),
759 {ok
, User_reponse
} = euphorik_bd:user_by_mess(M#minichat
.id
),
760 {struct
, [{id
, M#minichat
.id
}, {nick
, M#minichat
.pseudo
}, {login
, User_reponse#user
.login
}]}
764 {ek_master
, User_mess#user
.ek_master
},
765 {ostentatious_master
, atom_to_list(Profile_mess#profile
.ostentatious_master
)}