MOD fin du système de page et cleanage 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, Obsolète
12 %nouveau_user_captcha/1, Obsolète
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 Page_principale = case xmerl_xpath:string("pagePrincipale", Action) of [#xmlElement{content = [#xmlText{value = P3}]}] -> list_to_integer(P3); _ -> undefined end,
116 Conversations = lists:map(
117 fun(Conv) ->
118 [#xmlElement{content = [#xmlText{value = Id_racine_str}]}] = xmerl_xpath:string("racine", Conv),
119 [#xmlElement{content = [#xmlText{value = Page_conv_str}]}] = xmerl_xpath:string("page", Conv),
120 {erlang:list_to_integer(Id_racine_str, 36), list_to_integer(Page_conv_str)}
121 end,
122 xmerl_xpath:string("conversation", Action)
123 ),
124 case euphorik_minichat:set_profile(Cookie, Login, Password, Pseudo, Email, Css, Page_principale, Conversations) of
125 ok ->
126 xml_reponse_profile_ok();
127 login_deja_pris ->
128 xml_reponse_profile_pas_ok("Login déjà pris");
129 _ ->
130 xml_reponse_profile_pas_ok("Impossible de mettre à jour le profile")
131 end;
132 _ ->
133 xml_reponse_profile_pas_ok("XML malformé")
134 end
135 ).
136
137
138 % Renvoie les messages appropriés.
139 refreshMessage(Action) ->
140 simple_xml_to_string(
141 case xmerl_xpath:string("nombreMessage", Action) of % le nombre de message qu'affiche le client
142 [#xmlElement{content = [#xmlText{value = Nb_message_str}]}] ->
143 Nb_message = list_to_integer(Nb_message_str),
144 Dernier_id = case xmerl_xpath:string("dernierMessageId", Action) of % l'id du dernier message que connait le client
145 [#xmlElement{content = [#xmlText{value = D}]}] -> erlang:list_to_integer(D, 36);
146 _ -> 0
147 end,
148 User = case xmerl_xpath:string("cookie", Action) of
149 [#xmlElement{content = [#xmlText{value = Cookie}]}] ->
150 case euphorik_minichat:user_by_cookie(Cookie) of
151 {ok, U} -> U;
152 _ -> inconnu
153 end;
154 _ -> inconnu
155 end,
156 % extraction des conversations en [{id, page}, ..]
157 % Obsolète : obtenu depuis la table 'user'
158 %~ Conversations = lists:map(
159 %~ fun(Conv) ->
160 %~ [#xmlElement{content = [#xmlText{value = Id_racine_str}]}] = xmerl_xpath:string("racine", Conv),
161 %~ [#xmlElement{content = [#xmlText{value = Page_conv_str}]}] = xmerl_xpath:string("page", Conv),
162 %~ {erlang:list_to_integer(Id_racine_str, 36), erlang:list_to_integer(Page_conv_str)}
163 %~ end,
164 %~ xmerl_xpath:string("conversation", Action)
165 %~ ),
166 % accrochez-vous ca va siouxer ;)
167 [{reponse, [{name, "refreshMessages"}],
168 lists:map(
169 fun({Conv, Plus}) ->
170 {conversation, [],
171 [{autresPages, [], [atom_to_list(Plus)]} |
172 lists:map(
173 fun({Mess, Repond_a}) ->
174 Est_proprietaire = User =/= inconnu andalso User#user.id =:= Mess#minichat.auteur_id,
175 A_repondu_a_message = User =/= inconnu andalso euphorik_minichat:a_repondu_a_message(User#user.id, Mess#minichat.id),
176 Est_une_reponse_a_user = User =/= inconnu andalso euphorik_minichat:est_une_reponse_a_user(User#user.id, Mess#minichat.id),
177 User_mess =
178 if Mess#minichat.auteur_id =:= 0 ->
179 inconnu;
180 true ->
181 {ok, U2} = euphorik_minichat:user_by_id(Mess#minichat.auteur_id),
182 U2
183 end,
184 {message, [{id, erlang:integer_to_list(Mess#minichat.id, 36)}],
185 [
186 {date, [], [format_date(Mess#minichat.date)]},
187 {systeme, [], [atom_to_list(Mess#minichat.auteur_id =:= 0)]},
188 {proprietaire, [], [atom_to_list(Est_proprietaire)]},
189 {repondu, [], [atom_to_list(A_repondu_a_message)]},
190 {reponse, [], [atom_to_list(Est_une_reponse_a_user)]},
191 {pseudo, [], [Mess#minichat.pseudo]},
192 {login, [], [if User_mess =:= inconnu -> Mess#minichat.pseudo; true -> User_mess#user.login end]},
193 {contenu, [], [Mess#minichat.contenu]},
194 {repondA, [], xml_repond_a(Repond_a)}
195 ]
196 }
197 end,
198 Conv
199 )
200 ]
201 }
202 end,
203 euphorik_minichat_conversation:conversations(User#user.conversations, Nb_message, Dernier_id, User#user.page_principale)
204 )
205 }];
206 _ ->
207 [{reponse, [{name, "refreshMessages"}], [{erreur, [], ["erreur"]}]}]
208 end
209 ).
210
211
212 % Prend une liste de xml text node et en resort un string()
213 % xmerl : "test & test" devient deux fragments de texte : "test " et "& test", il faut donc rassembler les morceaux...
214 defragmenter(Text_nodes) ->
215 lists:foldl(fun(Node, Acc) -> #xmlText{value = V} = Node, Acc ++ V end, [], Text_nodes).
216
217
218 % Un utilisateur envoie un message
219 message(Action) ->
220 simple_xml_to_string(
221 case {
222 xmerl_xpath:string("cookie", Action),
223 xmerl_xpath:string("pseudo", Action),
224 xmerl_xpath:string("contenu", Action)
225 } of
226 {
227 [#xmlElement{content = [#xmlText{value = Cookie}]}],
228 [#xmlElement{content = Pseudo_fragments}],
229 [#xmlElement{content = Contenu_fragments}]
230 } ->
231 case euphorik_minichat:user_by_cookie(Cookie) of
232 {ok, U} ->
233 Pseudo = defragmenter(Pseudo_fragments),
234 Contenu = defragmenter(Contenu_fragments),
235 % met à jour le pseudo du user
236 euphorik_minichat:update_pseudo_user(U#user.id, Pseudo),
237 Reponses = case xmerl_xpath:string("reponses", Action) of
238 [#xmlElement{content = C}] ->
239 lists:map(
240 fun (Reponse) ->
241 #xmlElement{attributes = [#xmlAttribute{name = id, value = Id_reponse}]} = Reponse,
242 erlang:list_to_integer(Id_reponse, 36)
243 end
244 , C);
245 _ -> []
246 end,
247 Contenu_strip = string:strip(Contenu),
248 if Contenu_strip =:= [] -> xml_reponse_message(pas_ok);
249 true ->
250 case euphorik_minichat:nouveau_message(Contenu, U#user.id, Reponses) of
251 erreur -> xml_reponse_message(pas_ok);
252 _ -> xml_reponse_message(ok)
253 end
254 end;
255 _ -> xml_reponse_message(pas_ok)
256 end;
257 _ ->
258 xml_reponse_message(pas_ok)
259 end
260 ).
261
262
263 % Formatage d'une heure
264 % local_time() -> string
265 format_date(Date) ->
266 DateLocal = calendar:now_to_local_time(Date),
267 DateNowLocal = calendar:local_time(),
268 {{Annee, Mois, Jour}, {Heure, Minute, Seconde}} = DateLocal,
269 {{AnneeNow, _, _}, {_, _, _}} = DateNowLocal,
270 Hier = calendar:date_to_gregorian_days(element(1, DateLocal)) =:= calendar:date_to_gregorian_days(element(1, DateNowLocal)) - 1,
271 if element(1, DateLocal) =:= element(1, DateNowLocal) ->
272 "";
273 Hier ->
274 "Hier ";
275 Annee =:= AnneeNow ->
276 io_lib:format("~2.10.0B/~2.10.0B ", [Jour, Mois]);
277 true ->
278 io_lib:format("~2.10.0B/~2.10.0B/~B ", [Jour, Mois, Annee])
279 end ++
280 io_lib:format("~2.10.0B:~2.10.0B:~2.10.0B", [Heure, Minute, Seconde]).
281
282
283 %%%%%%%%% <Réponses XML> %%%%%%%%%
284 simple_xml_to_string(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 {pagePrincipale, [integer_to_list(User#user.page_principale)]}
301 ] ++
302 lists:map(
303 fun(C) ->
304 {conversation,
305 [
306 {racine, [erlang:integer_to_list(element(1, C), 36)]},
307 {page, [integer_to_list(element(2, C))]}
308 ]
309 }
310 end,
311 User#user.conversations
312 )
313 }].
314
315
316 % Construit un réponse négative à un login
317 xml_reponse_login_pas_ok(Message) ->
318 [{reponse, [{name, "login"}],
319 [
320 {statut, ["erreur"]},
321 {information, [Message]}
322 ]
323 }].
324
325
326 xml_reponse_profile_ok() ->
327 [{reponse, [{name, "profile"}],
328 [
329 {statut, ["ok"]}
330 ]
331 }].
332
333
334 xml_reponse_profile_pas_ok(Message) ->
335 [{reponse, [{name, "profile"}],
336 [
337 {statut, ["pas ok"]},
338 {information, [Message]}
339 ]
340 }].
341
342
343 % Pas utilisé
344 %~ xml_conversation(Mess_id, Nb) ->
345 %~ {Mess_id, Conversation} = minichat:conversation(Mess_id, Nb),
346 %~ xml_conversation(Conversation).
347 %~ xml_conversation([]) -> [];
348 %~ xml_conversation(Liste_id) ->
349 %~ lists:map(
350 %~ fun({Id, Sous_liste}) ->
351 %~ {id, [{id, erlang:integer_to_list(Id, 36)}], xml_conversation(Sous_liste)}
352 %~ end,
353 %~ Liste_id
354 %~ ).
355
356
357 % Renvoie un element XML representant une liste de messages auquel le message M_id repond
358 xml_repond_a(Reponses) ->
359 lists:map(
360 fun(Id_mess) ->
361 {ok, M} = euphorik_minichat:message_by_id(Id_mess),
362 {ok, User} = euphorik_minichat:user_by_mess(Id_mess),
363 {id, [{id, erlang:integer_to_list(M#minichat.id, 36)}, {pseudo, M#minichat.pseudo}, {login, User#user.login}], []}
364 end,
365 Reponses
366 ).
367
368
369 xml_reponse_message(Ok) ->
370 [
371 {reponse, [{name, "message"}],
372 [
373 {statut, [], [case Ok of ok -> "ok"; pas_ok -> "pas ok" end]}
374 ]
375 }
376 ].
377
378
379 % Obsolète
380 %~ xml_reponse_generation_captcha(Chemin, Captcha) ->
381 %~ [
382 %~ {reponse, [{name, "generationCaptcha"}],
383 %~ [
384 %~ {chemin, [], [Chemin]},
385 %~ {captchaCrypt, [], [Captcha]}
386 %~ ]
387 %~ }
388 %~ ].
389 %%%%%%%%% </réponses XML> %%%%%%%%%