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