MOD mise à jour mineur sur la présentation du code
[euphorik.git] / modules / erl / euphorik_protocole.erl
1 % coding: utf-8
2 % Ce module gére les différents message envoyé par le client (javascript) via AJAX.
3 % Par exemple le client peut demander les derniers messages du minichat.
4 % Les messages sont au format XML, la plus part des fonctions accepte un xmlDocument() et renvoie un string()
5 % qui est la réponse XML.
6 % Example XML : http://www.erlang.org/doc/apps/xmerl/xmerl_ug.html.
7 % @author G.Burri
8
9 -module(euphorik_protocole).
10 -export([
11 generation_captcha/1,
12 nouveau_user_captcha/1,
13 nouveau_user_login/1,
14 login/1,
15 logout/1,
16 profile/1,
17 refreshMessage/1,
18 message/1
19 ]).
20
21 -include_lib("xmerl/include/xmerl.hrl").
22 -include("../include/euphorik_bd.hrl").
23 -include("../include/euphorik_defines.hrl").
24
25
26 % Génère un nouveau captchat dans ?DOSSIER_CAPTCHA
27 % Obsolète
28 %~ generation_captcha(_) ->
29 %~ {Mot_crypt, Nom_fichier} = captcha:create(5, ?DOSSIER_CAPTCHA),
30 %~ simple_xml_to_string(xml_reponse_generation_captcha(?DOSSIER_CAPTCHA_RELATIF "/" ++ Nom_fichier, Mot_crypt)).
31
32
33 % Un nouvel utilisateur doit être créé.
34 % Obolète : le captcha n'existe plus
35 % Action est un xmlElement().
36 %~ nouveau_user_captcha(Action) ->
37 %~ simple_xml_to_string(
38 %~ case {xmerl_xpath:string("captchaCrypt", Action), xmerl_xpath:string("captchaInput", Action)} of
39 %~ {[#xmlElement{content = [#xmlText{value = C1}]}], [#xmlElement{content = [#xmlText{value = C2}]}]} ->
40 %~ C2_crypt = common:crypt(C2),
41 %~ if C1 =:= C2_crypt ->
42 %~ Cookie = generer_cookie(),
43 %~ User = euphorik_minichat:nouveau_user("Paul", Cookie),
44 %~ xml_reponse_login_ok(User);
45 %~ true ->
46 %~ xml_reponse_login_pas_ok("Captcha incorrect")
47 %~ end;
48 %~ _ ->
49 %~ xml_reponse_login_pas_ok("XML malformé")
50 %~ end
51 %~ ).
52
53
54 % Une utilisateur s'enregistre avec un tuple {Login, Password}.
55 % @spec nouveau_user_login(xmerl:xmlElement()) -> string()
56 nouveau_user_login(Action) ->
57 {Login, Password, Login_deja_pris} = case {xmerl_xpath:string("login", Action), xmerl_xpath:string("password", Action)} of
58 {[#xmlElement{content = [#xmlText{value = L}]}], [#xmlElement{content = [#xmlText{value = P}]}]} ->
59 {L, P, case euphorik_minichat:user_by_login(L) of {ok, _} -> true; _ -> false end};
60 _ -> {[], [], false}
61 end,
62 simple_xml_to_string(
63 if Login_deja_pris->
64 xml_reponse_login_pas_ok("Login déjà pris");
65 true ->
66 Cookie = generer_cookie(),
67 User = euphorik_minichat:nouveau_user(Login, Password, Cookie),
68 xml_reponse_login_ok(User)
69 end
70 ).
71
72
73 % Un utilisateur se logge.
74 login(Action) ->
75 case xmerl_xpath:string("cookie", Action) of
76 [#xmlElement{content = [#xmlText{value = Cookie}]}] ->
77 loginUser(euphorik_minichat:user_by_cookie(Cookie));
78 _ ->
79 case {xmerl_xpath:string("login", Action), xmerl_xpath:string("password", Action)} of
80 {[#xmlElement{content = [#xmlText{value = Login}]}], [#xmlElement{content = [#xmlText{value = Password}]}]} ->
81 loginUser(euphorik_minichat:user_by_login_password(Login, Password));
82 _ ->
83 simple_xml_to_string(xml_reponse_login_pas_ok("XML malformé"))
84 end
85 end.
86 loginUser({ok, User}) ->
87 euphorik_minichat:update_date_derniere_connexion(User#user.id),
88 simple_xml_to_string(xml_reponse_login_ok(User));
89 loginUser(_) ->
90 simple_xml_to_string(xml_reponse_login_pas_ok("Erreur de login")).
91
92
93 % Renvoie un string() représentant un cookie en base 36. Il y a 10^32 possibillités.
94 generer_cookie() ->
95 {A1,A2,A3} = now(),
96 random:seed(A1, A2, A3),
97 erlang:integer_to_list(random:uniform(math:pow(10, 32)), 36).
98
99
100 % Un utilisateur se délogge.
101 logout(_) ->
102 do_nothing.
103
104
105 % Modification du profile.
106 profile(Action) ->
107 simple_xml_to_string(
108 case xmerl_xpath:string("cookie", Action) of
109 [#xmlElement{content = [#xmlText{value = Cookie}]}] ->
110 Login = case xmerl_xpath:string("login", Action) of [#xmlElement{content = [#xmlText{value = L}]}] -> L; _ -> undefined end,
111 Password = case xmerl_xpath:string("password", Action) of [#xmlElement{content = [#xmlText{value = P}]}] -> P; _ -> undefined end,
112 Pseudo = case xmerl_xpath:string("pseudo", Action) of [#xmlElement{content = [#xmlText{value = P2}]}] -> P2; _ -> Login end,
113 Email = case xmerl_xpath:string("email", Action) of [#xmlElement{content = [#xmlText{value = E}]}] -> E; _ -> undefined end,
114 Css = case xmerl_xpath:string("css", Action) of [#xmlElement{content = [#xmlText{value = C}]}] -> C; _ -> undefined end,
115 case euphorik_minichat:set_profile(Cookie, Login, Password, Pseudo, Email, Css) of
116 ok ->
117 xml_reponse_profile_ok();
118 login_deja_pris ->
119 xml_reponse_profile_pas_ok("Login déjà pris");
120 _ ->
121 xml_reponse_profile_pas_ok("Impossible de mettre à jour le profile")
122 end;
123 _ ->
124 xml_reponse_profile_pas_ok("XML malformé")
125 end
126 ).
127
128
129 % Renvoie les messages appropriés.
130 refreshMessage(Action) ->
131 simple_xml_to_string(
132 case {
133 xmerl_xpath:string("nombreMessage", Action), % le nombre de message qu'affiche le client
134 xmerl_xpath:string("page", Action) % la page désiré, la première (les derniers messages) étant la 1
135 } of
136 {
137 [#xmlElement{content = [#xmlText{value = Nb_message_str}]}],
138 [#xmlElement{content = [#xmlText{value = Page_str}]}]
139 } ->
140 Nb_message = list_to_integer(Nb_message_str),
141 Page = list_to_integer(Page_str),
142 Dernier_id = case xmerl_xpath:string("dernierMessageId", Action) of % l'id du dernier message que connait le client
143 [#xmlElement{content = [#xmlText{value = D}]}] -> erlang:list_to_integer(D, 36);
144 _ -> 0
145 end,
146 User = case xmerl_xpath:string("cookie", Action) of
147 [#xmlElement{content = [#xmlText{value = Cookie}]}] ->
148 case euphorik_minichat:user_by_cookie(Cookie) of
149 {ok, U} -> U;
150 _ -> inconnu
151 end;
152 _ -> inconnu
153 end,
154 % extraction des conversations en [{id, page}, ..]
155 Conversations = lists:map(
156 fun(Conv) ->
157 [#xmlElement{content = [#xmlText{value = Id_racine_str}]}] = xmerl_xpath:string("racine", Conv),
158 [#xmlElement{content = [#xmlText{value = Page_conv_str}]}] = xmerl_xpath:string("page", Conv),
159 {erlang:list_to_integer(Id_racine_str, 36), erlang:list_to_integer(Page_conv_str)}
160 end,
161 xmerl_xpath:string("conversation", Action)
162 ),
163 Poulpe = euphorik_minichat_conversation:conversations(Conversations, Nb_message, Dernier_id, Page),
164 io:format("Poulpe = ~p~n", [Poulpe]),
165 % accrochez-vous ca va siouxer ;)
166 [{reponse, [{name, "refreshMessages"}],
167 lists:map(
168 fun({Conv, Plus}) ->
169 {conversation, [],
170 [{autresPages, [], [atom_to_list(Plus)]} |
171 lists:map(
172 fun({Mess, Repond_a}) ->
173 Est_proprietaire = User =/= inconnu andalso User#user.id =:= Mess#minichat.auteur_id,
174 A_repondu_a_message = User =/= inconnu andalso euphorik_minichat:a_repondu_a_message(User#user.id, Mess#minichat.id),
175 Est_une_reponse_a_user = User =/= inconnu andalso euphorik_minichat:est_une_reponse_a_user(User#user.id, Mess#minichat.id),
176 User_mess =
177 if Mess#minichat.auteur_id =:= 0 ->
178 inconnu;
179 true ->
180 {ok, U2} = euphorik_minichat:user_by_id(Mess#minichat.auteur_id),
181 U2
182 end,
183 {message, [{id, erlang:integer_to_list(Mess#minichat.id, 36)}],
184 [
185 {date, [], [format_date(Mess#minichat.date)]},
186 {systeme, [], [atom_to_list(Mess#minichat.auteur_id =:= 0)]},
187 {proprietaire, [], [atom_to_list(Est_proprietaire)]},
188 {repondu, [], [atom_to_list(A_repondu_a_message)]},
189 {reponse, [], [atom_to_list(Est_une_reponse_a_user)]},
190 {pseudo, [], [Mess#minichat.pseudo]},
191 {login, [], [if User_mess =:= inconnu -> Mess#minichat.pseudo; true -> User_mess#user.login end]},
192 {contenu, [], [Mess#minichat.contenu]},
193 {repondA, [], xml_repond_a(Repond_a)}
194 ]
195 }
196 end,
197 Conv
198 )
199 ]
200 }
201 end,
202 Poulpe
203 )
204 }];
205 _ ->
206 [{reponse, [{name, "refreshMessages"}], [{erreur, [], ["erreur"]}]}]
207 end
208 ).
209
210
211 % Prend une liste de xml text node et en resort un string()
212 % xmerl : "test & test" devient deux fragments de texte : "test " et "& test", il faut donc rassembler les morceaux...
213 defragmenter(Text_nodes) ->
214 lists:foldl(fun(Node, Acc) -> #xmlText{value = V} = Node, Acc ++ V end, [], Text_nodes).
215
216
217 % Un utilisateur envoie un message
218 message(Action) ->
219 simple_xml_to_string(
220 case {
221 xmerl_xpath:string("cookie", Action),
222 xmerl_xpath:string("pseudo", Action),
223 xmerl_xpath:string("contenu", Action)
224 } of
225 {
226 [#xmlElement{content = [#xmlText{value = Cookie}]}],
227 [#xmlElement{content = Pseudo_fragments}],
228 [#xmlElement{content = Contenu_fragments}]
229 } ->
230 case euphorik_minichat:user_by_cookie(Cookie) of
231 {ok, U} ->
232 Pseudo = defragmenter(Pseudo_fragments),
233 Contenu = defragmenter(Contenu_fragments),
234 % met à jour le pseudo du user
235 euphorik_minichat:update_pseudo_user(U#user.id, Pseudo),
236 Reponses = case xmerl_xpath:string("reponses", Action) of
237 [#xmlElement{content = C}] ->
238 lists:map(
239 fun (Reponse) ->
240 #xmlElement{attributes = [#xmlAttribute{name = id, value = Id_reponse}]} = Reponse,
241 erlang:list_to_integer(Id_reponse, 36)
242 end
243 , C);
244 _ -> []
245 end,
246 Contenu_strip = string:strip(Contenu),
247 if Contenu_strip =:= [] -> xml_reponse_message(pas_ok);
248 true ->
249 case euphorik_minichat:nouveau_message(Contenu, U#user.id, Reponses) of
250 erreur -> xml_reponse_message(pas_ok);
251 _ -> xml_reponse_message(ok)
252 end
253 end;
254 _ -> xml_reponse_message(pas_ok)
255 end;
256 _ ->
257 xml_reponse_message(pas_ok)
258 end
259 ).
260
261
262 % Formatage d'une heure
263 % local_time() -> string
264 format_date(Date) ->
265 DateLocal = calendar:now_to_local_time(Date),
266 DateNowLocal = calendar:local_time(),
267 {{Annee, Mois, Jour}, {Heure, Minute, Seconde}} = DateLocal,
268 {{AnneeNow, _, _}, {_, _, _}} = DateNowLocal,
269 Hier = calendar:date_to_gregorian_days(element(1, DateLocal)) =:= calendar:date_to_gregorian_days(element(1, DateNowLocal)) - 1,
270 if element(1, DateLocal) =:= element(1, DateNowLocal) ->
271 "";
272 Hier ->
273 "Hier ";
274 Annee =:= AnneeNow ->
275 io_lib:format("~2.10.0B/~2.10.0B ", [Jour, Mois]);
276 true ->
277 io_lib:format("~2.10.0B/~2.10.0B/~B ", [Jour, Mois, Annee])
278 end ++
279 io_lib:format("~2.10.0B:~2.10.0B:~2.10.0B", [Heure, Minute, Seconde]).
280
281
282 %%%%%%%%% <Réponses XML> %%%%%%%%%
283 simple_xml_to_string(XML) ->
284 io:format("~p~n", [XML]),
285 lists:flatten(xmerl:export_simple(XML, xmerl_xml, [{prolog, ["<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"]}])).
286
287
288 % Construit une réponse positive à un login
289 % si Enregistre vaut true alors cela veut dire que la personne s'est enregistré (elle possède au moins un login et un password)
290 xml_reponse_login_ok(User) ->
291 [{reponse, [{name, "login"}],
292 [
293 {statut, [if (User#user.password =/= []) and (User#user.login =/= []) -> "enregistre"; true -> "identifie" end]},
294 {cookie, [User#user.cookie]},
295 {id, [erlang:integer_to_list(User#user.id, 36)]},
296 {pseudo, [User#user.pseudo]},
297 {login, [User#user.login]},
298 {email, [User#user.email]},
299 {css, [User#user.css]}
300 ]
301 }].
302
303
304 % Construit un réponse négative à un login
305 xml_reponse_login_pas_ok(Message) ->
306 [{reponse, [{name, "login"}],
307 [
308 {statut, ["erreur"]},
309 {information, [Message]}
310 ]
311 }].
312
313
314 xml_reponse_profile_ok() ->
315 [{reponse, [{name, "profile"}],
316 [
317 {statut, ["ok"]}
318 ]
319 }].
320
321
322 xml_reponse_profile_pas_ok(Message) ->
323 [{reponse, [{name, "profile"}],
324 [
325 {statut, ["pas ok"]},
326 {information, [Message]}
327 ]
328 }].
329
330
331 % Pas utilisé
332 %~ xml_conversation(Mess_id, Nb) ->
333 %~ {Mess_id, Conversation} = minichat:conversation(Mess_id, Nb),
334 %~ xml_conversation(Conversation).
335 %~ xml_conversation([]) -> [];
336 %~ xml_conversation(Liste_id) ->
337 %~ lists:map(
338 %~ fun({Id, Sous_liste}) ->
339 %~ {id, [{id, erlang:integer_to_list(Id, 36)}], xml_conversation(Sous_liste)}
340 %~ end,
341 %~ Liste_id
342 %~ ).
343
344
345 % Renvoie un element XML representant une liste de messages auquel le message M_id repond
346 xml_repond_a(Reponses) ->
347 lists:map(
348 fun(Id_mess) ->
349 {ok, M} = euphorik_minichat:message_by_id(Id_mess),
350 {ok, User} = euphorik_minichat:user_by_mess(Id_mess),
351 {id, [{id, erlang:integer_to_list(M#minichat.id, 36)}, {pseudo, M#minichat.pseudo}, {login, User#user.login}], []}
352 end,
353 Reponses
354 ).
355
356
357 xml_reponse_message(Ok) ->
358 [
359 {reponse, [{name, "message"}],
360 [
361 {statut, [], [case Ok of ok -> "ok"; pas_ok -> "pas ok" end]}
362 ]
363 }
364 ].
365
366
367 % Obsolète
368 %~ xml_reponse_generation_captcha(Chemin, Captcha) ->
369 %~ [
370 %~ {reponse, [{name, "generationCaptcha"}],
371 %~ [
372 %~ {chemin, [], [Chemin]},
373 %~ {captchaCrypt, [], [Captcha]}
374 %~ ]
375 %~ }
376 %~ ].
377 %%%%%%%%% </réponses XML> %%%%%%%%%