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