(no commit message)
[euphorik.git] / js / euphorik.js
1 // coding: utf-8
2 // Copyright 2008 Grégory Burri
3 //
4 // This file is part of Euphorik.
5 //
6 // Euphorik is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // Euphorik is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with Euphorik. If not, see <http://www.gnu.org/licenses/>.
18
19 /**
20 * Contient la base javascript pour le site euphorik.ch.
21 * Chaque page possède son propre fichier js nommé "page<nom de la page>.js".
22 * Auteur : GBurri
23 * Date : 6.11.2007
24 */
25
26
27 /**
28 * La configuration.
29 * Normalement 'const' à la place de 'var' mais non supporté par IE7.
30 */
31 var conf = {
32 nbMessageAffiche : 40, // (par page)
33 pseudoDefaut : "<nick>",
34 tempsAffichageMessageDialogue : 4000, // en ms
35 tempsKick : 15, // en minute
36 tempsBan : 60 * 24 * 3, // en minutes (3jours)
37 smiles : {
38 "smile" : [/:\)/g, /:-\)/g],
39 "bigsmile" : [/:D/g, /:-D/g],
40 "clin" : [/;\)/g, /;-\)/g],
41 "cool" : [/8\)/g, /8-\)/g],
42 "eheheh" : [/:P/g, /:-P/g],
43 "lol" : [/\[-lol\]/g],
44 "spliff" : [/\[-spliff\]/g],
45 "oh" : [/:o/g, /:O/g],
46 "heink" : [/\[-heink\]/g],
47 "hum" : [/\[-hum\]/g],
48 "boh" : [/\[-boh\]/g],
49 "sniff" : [/:\(/g, /:-\(/g],
50 "triste" : [/\[-triste\]/g],
51 "pascontent" : [/>\(/g, /&gt;\(/g],
52 "argn" : [/\[-argn\]/g],
53 "redface" : [/\[-redface\]/g],
54 "bunny" : [/\[-lapin\]/g],
55 "chat" : [/\[-chat\]/g],
56 "renne" : [/\[-renne\]/g],
57 "star" : [/\[-star\]/g],
58 "kirby" : [/\[-kirby\]/g],
59 "slurp" : [/\[-slurp\]/g],
60 "agreed" : [/\[-agreed\]/g],
61 "dodo" : [/\[-dodo\]/g],
62 "bn" : [/\[-bn\]/g]
63 }
64 }
65
66 ///////////////////////////////////////////////////////////////////////////////////////////////////
67
68 String.prototype.trim = function()
69 {
70 return jQuery.trim(this) // anciennement : this.replace(/^\s+|\s+$/g, "");
71 }
72
73 String.prototype.ltrim = function()
74 {
75 return this.replace(/^\s+/, "");
76 }
77
78 String.prototype.rtrim = function()
79 {
80 return this.replace(/\s+$/, "");
81 }
82
83 ///////////////////////////////////////////////////////////////////////////////////////////////////
84
85 /**
86 * Cette classe regroupe des fonctions utilitaires (helpers).
87 * @formateur est permet de formater les messages affichés à l'aide de messageDialogue (facultatif)
88 */
89 function Util(formateur)
90 {
91 $("#info .fermer").click(function(){
92 $("#info").slideUp(50)
93 })
94
95 $("body").append('<div id="flecheBulle"></div>').append('<div id="messageBulle"><p></p></div>')
96
97 this.formateur = formateur
98 this.bulleActive = true
99 }
100
101 var messageType = {informatif: 0, question: 1, erreur: 2}
102
103 /**
104 * Affiche une boite de dialogue avec un message à l'intérieur.
105 * @param message le message (string)
106 * @param type voir 'messageType'. par défaut messageType.informatif
107 * @param les boutons sous la forme d'un objet ou les clefs sont les labels des boutons
108 * et les valeurs les fonctions executées lorsqu'un bouton est activé.
109 * @param formate faut-il formaté le message ? true par défaut
110 */
111 Util.prototype.messageDialogue = function(message, type, boutons, formate)
112 {
113 var thisUtil = this
114
115 if (type == undefined)
116 type = messageType.informatif
117
118 if (formate == undefined)
119 formate = true
120
121 if (this.timeoutMessageDialogue != undefined)
122 clearTimeout(this.timeoutMessageDialogue)
123
124 var fermer = function(){$("#info").slideUp(100)}
125 fermer()
126
127 $("#info .message").html(thisUtil.formateur == undefined || !formate ? message : thisUtil.formateur.traitementComplet(message))
128 switch(type)
129 {
130 case messageType.informatif : $("#info #icone").attr("class", "information"); break
131 case messageType.question : $("#info #icone").attr("class", "interrogation"); break
132 case messageType.erreur : $("#info #icone").attr("class", "exclamation"); break
133 }
134 $("#info .boutons").html("")
135 for (var b in boutons)
136 $("#info .boutons").append("<div>" + b + "</div>").find("div:last").click(boutons[b]).click(fermer)
137
138 $("#info").slideDown(200)
139 this.timeoutMessageDialogue = setTimeout(fermer, conf.tempsAffichageMessageDialogue)
140 }
141
142 /**
143 * Affiche un info bulle lorsque le curseur survole l'élément donné.
144 * FIXME : le width de element ne tient pas compte du padding !?
145 */
146 Util.prototype.infoBulle = function(message, element)
147 {
148 var thisUtil = this
149
150 var cacherBulle = function()
151 {
152 $("#flecheBulle").hide()
153 $("#messageBulle").hide()
154 }
155
156 element.hover(
157 function(e)
158 {
159 if (!thisUtil.bulleActive)
160 return
161
162 var m = $("#messageBulle")
163 var f = $("#flecheBulle")
164
165 $("p", m).html(message)
166
167 var positionFleche = {
168 left : element.offset().left + element.width() / 2 - f.width() / 2,
169 top : element.offset().top - f.height()
170 }
171 var positionMessage = {
172 left : element.offset().left + element.width() / 2 - m.width() / 2,
173 top : element.offset().top - f.height() - m.height()
174 }
175 var depassementDroit = (positionMessage.left + m.width()) - $("body").width()
176 if (depassementDroit > 0)
177 positionMessage.left -= depassementDroit
178 else
179 {
180 if (positionMessage.left < 0)
181 positionMessage.left = 0
182 }
183
184 m.css("top", positionMessage.top).css("left", positionMessage.left).show()
185 f.css("top", positionFleche.top).css("left", positionFleche.left).show()
186 },
187 cacherBulle
188 ).click(cacherBulle)
189 }
190
191 /**
192 * Utilisé pour l'envoie de donnée avec la méthode ajax de jQuery.
193 */
194 Util.prototype.jsonVersAction = function(json)
195 {
196 return {action : JSON.stringify(json) }
197 }
198
199 Util.prototype.md5 = function(chaine)
200 {
201 return hex_md5(chaine)
202 }
203
204 // pompé de http://www.faqts.com/knowledge_base/view.phtml/aid/13562/fid/130
205 Util.prototype.setSelectionRange = function(input, selectionStart, selectionEnd)
206 {
207 if (input.setSelectionRange)
208 {
209 input.focus()
210 input.setSelectionRange(selectionStart, selectionEnd)
211 }
212 else if (input.createTextRange)
213 {
214 var range = input.createTextRange()
215 range.collapse(true)
216 range.moveEnd('character', selectionEnd)
217 range.moveStart('character', selectionStart)
218 range.select()
219 }
220 }
221
222 Util.prototype.setCaretToEnd = function(input)
223 {
224 this.setSelectionRange(input, input.value.length, input.value.length)
225 }
226 Util.prototype.setCaretToBegin = function(input)
227 {
228 this.setSelectionRange(input, 0, 0)
229 }
230 Util.prototype.setCaretToPos = function(input, pos)
231 {
232 this.setSelectionRange(input, pos, pos)
233 }
234 Util.prototype.selectString = function(input, string)
235 {
236 var match = new RegExp(string, "i").exec(input.value)
237 if (match)
238 {
239 this.setSelectionRange (input, match.index, match.index + match[0].length)
240 }
241 }
242 Util.prototype.replaceSelection = function(input, replaceString) {
243 if (input.setSelectionRange)
244 {
245 var selectionStart = input.selectionStart
246 var selectionEnd = input.selectionEnd
247 input.value = input.value.substring(0, selectionStart) + replaceString + input.value.substring(selectionEnd)
248
249 if (selectionStart != selectionEnd) // has there been a selection
250 this.setSelectionRange(input, selectionStart, selectionStart + replaceString.length)
251 else // set caret
252 this.setCaretToPos(input, selectionStart + replaceString.length)
253 }
254 else if (document.selection)
255 {
256 input.focus()
257 var range = document.selection.createRange()
258 if (range.parentElement() == input)
259 {
260 var isCollapsed = range.text == ''
261 range.text = replaceString
262 if (!isCollapsed)
263 {
264 range.moveStart('character', -replaceString.length);
265 }
266 }
267 }
268 }
269
270 Util.prototype.rot13 = function(chaine)
271 {
272 var ACode = 'A'.charCodeAt(0)
273 var aCode = 'a'.charCodeAt(0)
274 var MCode = 'M'.charCodeAt(0)
275 var mCode = 'm'.charCodeAt(0)
276 var ZCode = 'Z'.charCodeAt(0)
277 var zCode = 'z'.charCodeAt(0)
278
279 var f = function(ch, pos) {
280 if (pos == ch.length)
281 return ""
282
283 var c = ch.charCodeAt(pos);
284 return String.fromCharCode(
285 c +
286 (c >= ACode && c <= MCode || c >= aCode && c <= mCode ? 13 :
287 (c > MCode && c <= ZCode || c > mCode && c <= zCode ? -13 : 0))
288 ) + f(ch, pos + 1)
289 }
290 return f(chaine, 0)
291 }
292
293 ///////////////////////////////////////////////////////////////////////////////////////////////////
294
295 function Pages()
296 {
297 this.pageCourante = null
298 this.pages = {}
299 }
300
301 /**
302 * Accepte soit un objet soit un string.
303 * un string correspond au nom de la page, par exemple : "page" -> "page.html"
304 */
305 Pages.prototype.ajouterPage = function(page)
306 {
307 if (typeof page == "string")
308 {
309 this.pages[page] = page
310 }
311 else
312 {
313 page.pages = this // la magie des langages dynamiques : le foutoire
314 this.pages[page.nom] = page
315 }
316 }
317
318 Pages.prototype.afficherPage = function(nomPage, forcerChargement)
319 {
320 if (forcerChargement == undefined) forcerChargement = false
321
322 var page = this.pages[nomPage]
323 if (page == undefined || (!forcerChargement && page == this.pageCourante)) return
324
325 if (this.pageCourante != null && this.pageCourante.decharger)
326 this.pageCourante.decharger()
327
328 $("#menu li").removeClass("courante")
329 $("#menu li." + nomPage).addClass("courante")
330
331 this.pageCourante = page
332 var contenu = ""
333 if (typeof page == "string")
334 $.ajax({async: false, url: "pages/" + page + ".html", success : function(page) { contenu += page }})
335 else
336 contenu += this.pageCourante.contenu()
337 $("#page").html(contenu).removeClass().addClass(this.pageCourante.nom)
338
339 if (this.pageCourante.charger)
340 this.pageCourante.charger()
341 }
342
343 ///////////////////////////////////////////////////////////////////////////////////////////////////
344
345 /**
346 * Classe permettant de formater du texte par exemple pour la substitution des liens dans les
347 * message par "[url]".
348 * TODO : améliorer l'efficacité des méthods notamment lié au smiles.
349 */
350 function Formateur()
351 {
352 this.smiles = conf.smiles
353 this.protocoles = "http|https|ed2k"
354
355 this.regexUrl = new RegExp("(?:(?:" + this.protocoles + ")://|www\\.)[^ ]*", "gi")
356 this.regexImg = new RegExp("^.*?\\.(gif|jpg|png|jpeg|bmp|tiff)$", "i")
357 this.regexDomaine = new RegExp("^(?:(?:" + this.protocoles + ")://|www\\.).*?([^/.]+\\.[^/.]+)(?:$|/).*$", "i")
358 this.regexTestProtocoleExiste = new RegExp("^(?:" + this.protocoles + ")://.*$", "i")
359 this.regexNomProtocole = new RegExp("^(.*?)://")
360 }
361
362 /**
363 * Formate un pseudo saise par l'utilisateur.
364 * @param pseudo le pseudo brut
365 * @return le pseudo filtré
366 */
367 Formateur.prototype.filtrerInputPseudo = function(pseudo)
368 {
369 return pseudo.replace(/{|}/g, "").trim()
370 }
371
372 Formateur.prototype.getSmilesHTML = function()
373 {
374 var XHTML = ""
375 for (var sNom in this.smiles)
376 {
377 XHTML += "<img class=\"" + sNom + "\" src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />"
378 }
379 return XHTML
380 }
381
382 /**
383 * Formatage complet d'un texte.
384 * @M le message
385 * @pseudo facultatif, permet de contruire le label des images sous la forme : "<Pseudo> : <Message>"
386 */
387 Formateur.prototype.traitementComplet = function(M, pseudo)
388 {
389 return this.traiterLiensConv(this.traiterSmiles(this.traiterURL(this.traiterWikiSyntaxe(this.remplacerBalisesHTML(M)), pseudo)))
390 }
391
392 /**
393 * Transforme les liens en entités clickables.
394 * Un lien vers une conversation permet d'ouvrire celle ci, elle se marque comme ceci dans un message :
395 * "{5F}" ou 5F est la racine de la conversation.
396 * Ce lien sera transformer en <span class="lienConv">{5F}</span> pouvant être clické pour créer la conv 5F.
397 */
398 Formateur.prototype.traiterLiensConv = function(M)
399 {
400 return M.replace(
401 /\{\w+\}/g,
402 function(lien)
403 {
404 return "<span class=\"lienConv\">" + lien + "</span>"
405 }
406 )
407 }
408
409 /**
410 * FIXME : Cette méthode est attrocement lourde ! A optimiser.
411 * moyenne sur échantillon : 234ms
412 */
413 Formateur.prototype.traiterSmiles = function(M)
414 {
415 for (var sNom in this.smiles)
416 {
417 ss = this.smiles[sNom]
418 for (var i = 0; i < ss.length; i++)
419 M = M.replace(ss[i], "<img src=\"img/smileys/" + sNom + ".gif\" alt =\"" + sNom + "\" />")
420 }
421 return M
422 }
423
424 Formateur.prototype.remplacerBalisesHTML = function(M)
425 {
426 return M.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;")
427 }
428
429 Formateur.prototype.traiterURL = function(M, pseudo)
430 {
431 thisFormateur = this
432
433 var traitementUrl = function(url)
434 {
435 // si ya pas de protocole on rajoute "http://"
436 if (!thisFormateur.regexTestProtocoleExiste.test(url))
437 url = "http://" + url
438 var extension = thisFormateur.getShort(url)
439 return "<a " + (extension[1] ? "title=\"" + (pseudo == undefined ? "" : thisFormateur.traiterPourFenetreLightBox(pseudo, url) + ": ") + thisFormateur.traiterPourFenetreLightBox(M, url) + "\"" + " rel=\"lightbox\"" : "") + " href=\"" + url + "\" >[" + extension[0] + "]</a>"
440 }
441 return M.replace(this.regexUrl, traitementUrl)
442 }
443
444 /**
445 * Formatage en utilisant un sous-ensemble des règles de mediwiki.
446 * par exemple ''italic'' devient <i>italic</i>
447 */
448 Formateur.prototype.traiterWikiSyntaxe = function(M)
449 {
450 return M.replace(
451 /'''(.*?)'''/g,
452 function(texte, capture)
453 {
454 return "<b>" + capture + "</b>"
455 }
456 ).replace(
457 /''(.*?)''/g,
458 function(texte, capture)
459 {
460 return "<i>" + capture + "</i>"
461 }
462 )
463 }
464
465 /**
466 * Renvoie une version courte de l'url.
467 * par exemple : http://en.wikipedia.org/wiki/Yakov_Smirnoff devient wikipedia.org
468 */
469 Formateur.prototype.getShort = function(url)
470 {
471 var estUneImage = false
472 var versionShort = null
473 var rechercheImg = this.regexImg.exec(url)
474
475 if (rechercheImg != null)
476 {
477 versionShort = rechercheImg[1].toLowerCase()
478 if (versionShort == "jpeg") versionShort = "jpg" // jpeg -> jpg
479 estUneImage = true
480 }
481 else
482 {
483 var rechercheDomaine = this.regexDomaine.exec(url)
484 if (rechercheDomaine != null && rechercheDomaine.length >= 2)
485 versionShort = rechercheDomaine[1]
486 else
487 {
488 var nomProtocole = this.regexNomProtocole.exec(url)
489 if (nomProtocole != null && nomProtocole.length >= 2)
490 versionShort = nomProtocole[1]
491 }
492 }
493
494 return [versionShort == null ? "url" : versionShort, estUneImage]
495 }
496
497 /**
498 * Traite les pseudo et messages à être affiché dans le titre d'une image visualisé avec lightbox.
499 */
500 Formateur.prototype.traiterPourFenetreLightBox = function(M, urlCourante)
501 {
502 thisFormateur = this
503 var traitementUrl = function(url)
504 {
505 return "[" + thisFormateur.getShort(url)[0] + (urlCourante == url ? "*" : "") + "]"
506 }
507
508 return this.remplacerBalisesHTML(M).replace(this.regexUrl, traitementUrl)
509 }
510
511
512 ///////////////////////////////////////////////////////////////////////////////////////////////////
513
514 // les statuts possibes du client
515 var statutType = {
516 // mode enregistré, peut poster des messages et modifier son profile
517 auth_registered : 0,
518 // mode identifié, peut poster des messages mais n'a pas accès au profile
519 auth_not_registered : 1,
520 // mode déconnecté, ne peut pas poster de message
521 deconnected : 2
522 }
523
524 function Client(util)
525 {
526 this.util = util
527
528 this.cookie = null
529 this.regexCookie = new RegExp("^cookie=([^;]*)")
530
531 // données personnels
532 this.resetDonneesPersonnelles()
533
534 this.setStatut(statutType.deconnected)
535
536 // si true alors chaque modification du client est mémorisé sur le serveur
537 this.autoflush = $.browser["opera"]
538 }
539
540 Client.prototype.resetDonneesPersonnelles = function()
541 {
542 this.id = 0
543 this.pseudo = conf.pseudoDefaut
544 this.login = ""
545 this.password = ""
546 this.email = ""
547 this.css = $("link#cssPrincipale").attr("href")
548 this.nickFormat = "nick"
549 this.viewTimes = true
550 this.viewTooltips = true
551 this.cookie = undefined
552
553 this.pagePrincipale = 1
554 this.ekMaster = false
555
556 // les conversations, une conversation est un objet possédant les attributs suivants :
557 // - racine (entier)
558 // - page (entier)
559 this.conversations = new Array()
560 }
561
562 Client.prototype.setCss = function(css)
563 {
564 if (this.css == css || css == "")
565 return
566
567 this.css = css
568 $("link#cssPrincipale").attr("href", this.css)
569 this.majMenu()
570
571 if (this.autoflush) this.flush(true)
572 }
573
574 Client.prototype.pageSuivante = function(numConv)
575 {
576 if (numConv < 0 && this.pagePrincipale > 1)
577 this.pagePrincipale -= 1
578 else if (this.conversations[numConv].page > 1)
579 this.conversations[numConv].page -= 1
580 }
581
582 Client.prototype.pagePrecedente = function(numConv)
583 {
584 if (numConv < 0)
585 this.pagePrincipale += 1
586 else
587 this.conversations[numConv].page += 1
588 }
589
590 /**
591 * Définit la première page pour la conversation donnée.
592 * @return true si la page a changé sinon false
593 */
594 Client.prototype.goPremierePage = function(numConv)
595 {
596 if (numConv < 0)
597 {
598 if (this.pagePrincipale == 1)
599 return false
600 this.pagePrincipale = 1
601 }
602 else
603 {
604 if (this.conversations[numConv].page == 1)
605 return false
606 this.conversations[numConv].page = 1
607 }
608 return true
609 }
610
611 /**
612 * Ajoute une conversation à la vue de l'utilisateur.
613 * Le profile de l'utilisateur est directement sauvegardé sur le serveur.
614 * @param racines la racine de la conversation (integer)
615 * @return true si la conversation a été créée sinon false (par exemple si la conv existe déjà)
616 */
617 Client.prototype.ajouterConversation = function(racine)
618 {
619 // vérification s'il elle n'existe pas déjà
620 for (var i = 0; i < this.conversations.length; i++)
621 if (this.conversations[i].root == racine)
622 return false
623
624 this.conversations.push({root : racine, page : 1})
625
626 if (this.autoflush) this.flush(true)
627
628 return true
629 }
630
631 Client.prototype.supprimerConversation = function(num)
632 {
633 if (num < 0 || num >= this.conversations.length) return
634
635 // décalage TODO : supprimer le dernier élément
636 for (var i = num; i < this.conversations.length - 1; i++)
637 this.conversations[i] = this.conversations[i+1]
638 this.conversations.pop()
639
640 if (this.autoflush) this.flush(true)
641 }
642
643 Client.prototype.getJSONLogin = function(login, password)
644 {
645 return {
646 "action" : "authentification",
647 "login" : login,
648 "password" : password
649 }
650 }
651
652 Client.prototype.getJSONLoginCookie = function()
653 {
654 return {
655 "action" : "authentification",
656 "cookie" : this.cookie
657 }
658 }
659
660 /**
661 * le couple (login, password) est facultatif. S'il n'est pas fournit alors il ne sera pas possible
662 * de s'autentifier avec (login, password).
663 */
664 Client.prototype.getJSONEnregistrement = function(login, password)
665 {
666 var mess = { "action" : "register" }
667
668 if (login != undefined && password != undefined)
669 {
670 mess["login"] = login
671 mess["password"] = password
672 }
673
674 return mess;
675 }
676
677 Client.prototype.getJSONConversations = function()
678 {
679 var conversations = new Array()
680 for (var i = 0; i < this.conversations.length; i++)
681 conversations.push({ "root" : this.conversations[i].root, "page" : this.conversations[i].page})
682 return conversations
683 }
684
685 Client.prototype.getJSONProfile = function()
686 {
687 return {
688 "action" : "set_profile",
689 "cookie" : this.cookie,
690 "login" : this.login,
691 "password" : this.password,
692 "nick" : this.pseudo,
693 "email" : this.email,
694 "css" : this.css,
695 "nick_format" : this.nickFormat,
696 "view_times" : this.viewTimes,
697 "view_tooltips" : this.viewTooltips,
698 "main_page" : this.pagePrincipale < 1 ? 1 : this.pagePrincipale,
699 "conversations" : this.getJSONConversations()
700 }
701 }
702
703 /**
704 * Renvoie null si pas définit.
705 */
706 Client.prototype.getCookie = function()
707 {
708 var cookie = this.regexCookie.exec(document.cookie)
709 if (cookie == null) this.cookie = null
710 else this.cookie = cookie[1]
711 }
712
713 Client.prototype.delCookie = function()
714 {
715 document.cookie = "cookie=; max-age=0"
716 }
717
718 Client.prototype.setCookie = function()
719 {
720 if (this.cookie == null || this.cookie == undefined)
721 return
722
723 // ne fonctionne pas sous IE....
724 /*document.cookie = "cookie=" + this.cookie + "; max-age=" + (60 * 60 * 24 * 365) */
725
726 document.cookie =
727 "cookie="+this.cookie+"; expires=" + new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 365).toUTCString()
728 }
729
730 Client.prototype.authentifie = function()
731 {
732 return this.statut == statutType.auth_registered || this.statut == statutType.auth_not_registered
733 }
734
735 Client.prototype.setStatut = function(statut)
736 {
737 // conversation en "enum" si en "string"
738 if (typeof(statut) == "string")
739 {
740 statut =
741 statut == "auth_registered" ?
742 statutType.auth_registered :
743 (statut == "auth_not_registered" ? statutType.auth_not_registered : statutType.deconnected)
744 }
745
746 if (statut == this.statut) return
747
748 this.statut = statut
749 this.majMenu()
750 }
751
752 /**
753 * Effectue la connexion vers le serveur.
754 * Cette fonction est bloquante tant que la connexion n'a pas été établie.
755 * S'il existe un cookie en local on s'authentifie directement avec lui.
756 * Si il n'est pas possible de s'authentifier alors on affiche un captcha anti-bot.
757 */
758 Client.prototype.connexionCookie = function()
759 {
760 this.getCookie()
761 if (this.cookie == null) return false;
762 return this.connexion(this.getJSONLoginCookie())
763 }
764
765 Client.prototype.connexionLogin = function(login, password)
766 {
767 return this.connexion(this.getJSONLogin(login, password))
768 }
769
770 Client.prototype.enregistrement = function(login, password)
771 {
772 if (this.authentifie())
773 {
774 this.login = login
775 this.password = password
776 if(this.flush())
777 {
778 this.setStatut(statutType.auth_registered)
779 return true
780 }
781 return false
782 }
783 else
784 {
785 return this.connexion(this.getJSONEnregistrement(login, password))
786 }
787 }
788
789 Client.prototype.connexion = function(messageJson)
790 {
791 ;; dumpObj(messageJson)
792 thisClient = this
793 jQuery.ajax(
794 {
795 async: false,
796 type: "POST",
797 url: "request",
798 dataType: "json",
799 data: this.util.jsonVersAction(messageJson),
800 success:
801 function(data)
802 {
803 ;; dumpObj(data)
804 if (data["reply"] == "error")
805 thisClient.util.messageDialogue(data["error_message"])
806 else
807 thisClient.chargerDonnees(data)
808 }
809 }
810 )
811 return this.authentifie()
812 }
813
814 Client.prototype.deconnexion = function()
815 {
816 this.flush(true)
817 this.delCookie()
818 this.resetDonneesPersonnelles()
819 this.setStatut(statutType.deconnected) // deconnexion
820 }
821
822 Client.prototype.chargerDonnees = function(data)
823 {
824 // la modification du statut qui suit met à jour le menu, le menu dépend (page admin)
825 // de l'état ekMaster
826 this.ekMaster = data["ek_master"] != undefined ? data["ek_master"] : false
827
828 this.setStatut(data["status"])
829
830 if (this.authentifie())
831 {
832 this.cookie = data["cookie"]
833 this.setCookie()
834
835 this.id = data["id"]
836 this.login = data["login"]
837 this.pseudo = data["nick"]
838 this.email = data["email"]
839 this.setCss(data["css"])
840 this.nickFormat = data["nick_format"]
841 this.viewTimes = data["view_times"]
842 this.viewTooltips = data["view_tooltips"]
843
844 // la page de la conversation principale
845 this.pagePrincipale = data["main_page"] == undefined ? 1 : data["main_page"]
846
847 // les conversations
848 this.conversations = data["conversations"]
849
850 this.majBulle()
851 }
852 }
853
854 /**
855 * Met à jour les données personne sur serveur.
856 * @param async de manière asynchrone ? défaut = true
857 * @return false si le flush n'a pas pû se faire sinon true
858 */
859 Client.prototype.flush = function(async)
860 {
861 if (async == undefined)
862 async = false
863
864 if (!this.authentifie())
865 return false
866
867 var thisClient = this
868 var ok = true
869
870 ;; dumpObj(this.getJSONProfile())
871 jQuery.ajax(
872 {
873 async: async,
874 type: "POST",
875 url: "request",
876 dataType: "json",
877 data: this.util.jsonVersAction(this.getJSONProfile()),
878 success:
879 function(data)
880 {
881 ;; dumpObj(data)
882 if (data["reply"] == "error")
883 {
884 thisClient.util.messageDialogue(data["error_message"])
885 ok = false
886 }
887 else
888 {
889 thisClient.majBulle()
890 }
891 }
892 }
893 )
894
895 return ok
896 }
897
898 Client.prototype.majMenu = function()
899 {
900 // TODO : à virer : ne plus changer de style de display ... spa beau .. ou trouver une autre méthode
901 // var displayType = this.css == "css/3/euphorik.css" ? "block" : "inline" //this.client
902 displayType = "block"
903
904 $("#menu .admin").css("display", this.ekMaster ? displayType : "none")
905
906 // met à jour le menu
907 if (this.statut == statutType.auth_registered)
908 {
909 $("#menu .profile").css("display", displayType).text("profile")
910 $("#menu .logout").css("display", displayType)
911 $("#menu .register").css("display", "none")
912 }
913 else if (this.statut == statutType.auth_not_registered)
914 {
915 $("#menu .profile").css("display", "none")
916 $("#menu .logout").css("display", displayType)
917 $("#menu .register").css("display", displayType)
918 }
919 else
920 {
921 $("#menu .profile").css("display", displayType).text("login")
922 $("#menu .logout").css("display", "none")
923 $("#menu .register").css("display", displayType)
924 }
925 }
926
927 /**
928 * Met à jour l'affichage des infos bulles en fonction du profile.
929 */
930 Client.prototype.majBulle = function()
931 {
932 this.util.bulleActive = this.viewTooltips
933 }
934
935 Client.prototype.slap = function(userId, raison)
936 {
937 var thisClient = this
938
939 jQuery.ajax({
940 type: "POST",
941 url: "request",
942 dataType: "json",
943 data: this.util.jsonVersAction(
944 {
945 "action" : "slap",
946 "cookie" : thisClient.cookie,
947 "user_id" : userId,
948 "reason" : raison
949 }),
950 success:
951 function(data)
952 {
953 if (data["reply"] == "error")
954 thisClient.util.messageDialogue(data["error_message"])
955 }
956 })
957 }
958
959 Client.prototype.ban = function(userId, raison, minutes)
960 {
961 var thisClient = this
962
963 // par défaut un ban correspond à 3 jours
964 if (typeof(minutes) == "undefined")
965 minutes = conf.tempsBan;
966
967 jQuery.ajax({
968 type: "POST",
969 url: "request",
970 dataType: "json",
971 data: this.util.jsonVersAction(
972 {
973 "action" : "ban",
974 "cookie" : thisClient.cookie,
975 "duration" : minutes,
976 "user_id" : userId,
977 "reason" : raison
978 }),
979 success:
980 function(data)
981 {
982 if (data["reply"] == "error")
983 thisClient.util.messageDialogue(data["error_message"])
984 }
985 })
986 }
987
988 Client.prototype.kick = function(userId, raison)
989 {
990 this.ban(userId, raison, conf.tempsKick)
991 }
992
993 ///////////////////////////////////////////////////////////////////////////////////////////////////
994
995 /**
996 * classe permettant de gérer les événements (push serveur).
997 * l'information envoyé est sous la forme :
998 * {
999 * "action" : "wait_event"
1000 * "page" : <page>
1001 * [..]
1002 * }
1003 * l'information reçu est sous la forme :
1004 * {
1005 * "reply" : <reply>
1006 * }
1007 * @page la page
1008 */
1009 function PageEvent(page, util)
1010 {
1011 this.page = page
1012 this.util = util
1013
1014 // l'objet JSONHttpRequest représentant la connexion d'attente
1015 this.attenteCourante = null
1016
1017 // le multhreading du pauvre, merci javascript de m'offrire autant de primitives pour la gestion de la concurrence...
1018 this.stop = false
1019 }
1020
1021 /**
1022 * Arrête l'attente courante s'il y en a une.
1023 */
1024 PageEvent.prototype.stopAttenteCourante = function()
1025 {
1026 this.stop = true
1027
1028 if (this.attenteCourante != null)
1029 {
1030 this.attenteCourante.abort()
1031 }
1032 }
1033
1034 /**
1035 * Attend un événement lié à la page.
1036 * @funSend une fonction renvoyant les données json à envoyer
1037 * @funsReceive est un objet comprenant les fonctions à appeler en fonction du "reply"
1038 * les fonctions acceptent un paramètre correspondant au données reçues.
1039 * exemple : {"new_message" : function(data){ ... }}
1040 */
1041 PageEvent.prototype.waitEvent = function(funSend, funsReceive)
1042 {
1043 this.stopAttenteCourante()
1044
1045 this.stop = false
1046
1047 var thisPageEvent = this
1048
1049 // on doit conserver l'ordre des valeurs de l'objet JSON (le serveur les veut dans l'ordre définit dans le protocole)
1050 // TODO : ya pas mieux ?
1051 var dataToSend =
1052 {
1053 "action" : "wait_event",
1054 "page" : this.page
1055 }
1056 var poulpe = funSend()
1057 for (v in poulpe)
1058 dataToSend[v] = poulpe[v]
1059
1060 ;; dumpObj(dataToSend)
1061
1062 this.attenteCourante = jQuery.ajax({
1063 type: "POST",
1064 url: "request",
1065 dataType: "json",
1066 timeout: 300000, // timeout de 5min. Gros HACK pas beau. FIXME problème décrit ici : http://groups.google.com/group/jquery-en/browse_thread/thread/8724e64af3333a76
1067 data: this.util.jsonVersAction(dataToSend),
1068 success:
1069 function(data)
1070 {
1071 ;; dumpObj(data)
1072
1073 funsReceive[data["reply"]](data)
1074
1075 // rappel de la fonction dans 100 ms
1076 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funsReceive) }, 100)
1077 },
1078 error:
1079 function(XMLHttpRequest, textStatus, errorThrown)
1080 {
1081 ;; console.log("Connexion perdue dans waitEvent")
1082 setTimeout(function(){ thisPageEvent.waitEvent2(funSend, funsReceive) }, 1000)
1083 }
1084 })
1085 }
1086
1087 /**
1088 * Si un stopAttenteCourante survient un peu n'importe quand il faut imédiatement arreter de boucler.
1089 */
1090 PageEvent.prototype.waitEvent2 = function(funSend, funsReceive)
1091 {
1092 if (this.stop)
1093 return
1094 this.waitEvent(funSend, funsReceive)
1095 }
1096
1097 ///////////////////////////////////////////////////////////////////////////////////////////////////
1098
1099 function initialiserListeStyles(client)
1100 {
1101 $("#menuCss").change(
1102 function()
1103 {
1104 client.setCss("css/" + $("option:selected", this).attr("value") + "/euphorik.css")
1105 }
1106 )
1107 }
1108
1109 // charge dynamiquement le script de debug
1110 ;; jQuery.ajax({async : false, url : "js/debug.js", dataType : "script"})
1111
1112 // le main
1113 $(document).ready(
1114 function()
1115 {
1116 var formateur = new Formateur()
1117 var util = new Util(formateur)
1118 var client = new Client(util)
1119 var pages = new Pages()
1120
1121 // connexion vers le serveur (utilise un cookie qui traine)
1122 client.connexionCookie()
1123
1124 initialiserListeStyles(client)
1125
1126 // FIXME : ne fonctionne pas sous opera
1127 // voir : http://dev.jquery.com/ticket/2892#preview
1128 $(window).unload(function(){client.flush()})
1129
1130 $("#menu .minichat").click(function(){ pages.afficherPage("minichat") })
1131 $("#menu .admin").click(function(){ pages.afficherPage("admin") })
1132 $("#menu .profile").click(function(){ pages.afficherPage("profile") })
1133 $("#menu .logout").click(function(){
1134 util.messageDialogue("Êtes-vous sur de vouloir vous délogger ?", messageType.question,
1135 {"Oui" : function()
1136 {
1137 client.deconnexion();
1138 pages.afficherPage("minichat", true)
1139 },
1140 "Non" : function(){}
1141 }
1142 )
1143 })
1144 $("#menu .register").click(function(){ pages.afficherPage("register") })
1145 $("#menu .about").click(function(){ pages.afficherPage("about") })
1146
1147 // TODO : simplifier et pouvoir créer des liens par exemple : <span class="lien" href="conditions">Conditions d'utilisation</span>
1148 $("#footer .conditions").click(function(){ pages.afficherPage("conditions_utilisation") })
1149
1150 pages.ajouterPage(new PageMinichat(client, formateur, util))
1151 pages.ajouterPage(new PageAdmin(client, formateur, util))
1152 pages.ajouterPage(new PageProfile(client, formateur, util))
1153 pages.ajouterPage(new PageRegister(client, formateur, util))
1154 pages.ajouterPage(new PageAbout(client, formateur, util))
1155 pages.ajouterPage("conditions_utilisation")
1156
1157 pages.afficherPage("minichat")
1158 }
1159 )