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