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