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