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