FIX #75 : problème de ban d'ip
[euphorik.git] / js / pageAdmin.js
index 9be3ca1..fc1d51a 100644 (file)
 // coding: utf-8
+// Copyright 2008 Grégory Burri
+//
+// This file is part of Euphorik.
+//
+// Euphorik is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+//
+// Euphorik is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License
+// along with Euphorik.  If not, see <http://www.gnu.org/licenses/>.
+// 
+// La page d'administation, ne peut être accédée que par les ekMaster (admins)
 
-function PageAdmin(client, formateur, util)
-{
-   this.nom = "admin"
+/*jslint laxbreak:true */
+
+
+euphorik.PageAdmin = function(client, formateur, util) {
+   this.nom = "admin";
+   
+   this.client = client;
+   this.formateur = formateur;
+   this.util = util;
    
-   this.client = client
-   this.formateur = formateur
-   this.util = util
-}
-
-PageAdmin.prototype.contenu = function()
-{
-   return '<h1>Trolls</h1>\
-   <p>Chaque semaine un troll est choisit au hasard parmis les trolls proposés et devient le troll de la semaine.</p>\
-   <form id="nouveauTroll"><p>\
-      <input class="troll" name="troll" type="text" size="80" maxlength="500" value=""></input>\
-      <button class="return" value="return">poster</button>\
-   </p></form><div id="trolls"></div>'
-}
-
-PageAdmin.prototype.charger = function()
-{      
-   $("#page form#nouveauTroll").submit(function(){return false})
+   this.comet = new Comet("admin", euphorik.conf.versionProtocole);
+   
+   // le timer qui rappelle periodiquement le rafraichissement des IP bannies
+   this.timeoutIDmajIPs = null;
+};
+
+/**
+  * Interface des pages.
+  */
+euphorik.PageAdmin.prototype.contenu = function() {
+   return '<h1>Trolls</h1>' +
+   '<p>Un troll est un sujet à débat, en général une question, affiché sur la page principale.</p>' +
+   '<p>Chaque semaine un troll est choisi au hasard parmis les trolls proposés et devient le troll de la semaine.</p>' +
+   '<form action="" id="nouveauTroll">' +
+   '   <p>' +
+   '      <input class="troll" name="troll" type="text" maxlength="500" value=""></input>' +
+   '      <button class="return" value="return">poster</button>' +
+   '   </p>' +
+   '</form>' +
+   '<div id="trolls"></div>' +
+   '<h1>IPs bannies</h1>' +
+   '<div id="ips"></div>';
+};
+
+/**
+  * Interface des pages.
+  */
+euphorik.PageAdmin.prototype.charger = function() {      
+   $("#page form#nouveauTroll").submit(function(){ return false; });
       
-   var thisPage = this
+   var thisPage = this;
+   
+   // la liste des trolls proposés par les ekMasters
+   this.trolls = new euphorik.Trolls(this.client, this.util, this.formateur);
+   
+   this.waitEvent();
    
-   this.trolls = new Trolls(this.client, this.util, this.formateur)
-   this.trolls.rafraichirTrolls()
+   this.majIPs();
+   
+   $("#page form#nouveauTroll  input.troll").focus();
    
    $("#page form#nouveauTroll button.return").click(
-      function()
-      {
-         thisPage.posterTroll()
+      function() {
+         thisPage.posterTroll();
       }
-   )
-}
+   );
+};
 
-PageAdmin.prototype.decharger = function()
-{
-   this.trolls.pageEvent.stopAttenteCourante()
-}
+/**
+  * Interface des pages.
+  */
+euphorik.PageAdmin.prototype.decharger = function() {
+   this.comet.stopAttenteCourante();
+   
+   // supprime le rafraichissement période des ips
+   if (this.timeoutIDmajIPs) {
+      clearTimeout(this.timeoutIDmajIPs);
+   }
+};
 
-PageAdmin.prototype.posterTroll = function()
-{
-   var thisPageAdmin = this
+/**
+  * Post un troll, le contenu est lu à partir de "input.troll".
+  */
+euphorik.PageAdmin.prototype.posterTroll = function() {
+   var thisPageAdmin = this;
    
-   var content = $("#page form#nouveauTroll input.troll").val()
+   var content = $("#page form#nouveauTroll input.troll").val();
    
-   content = content.trim()
-   if (content == "")
-   {
-      this.util.messageDialogue("Le troll est vide")
-      return
+   content = content.trim();
+   if (content === "") {
+      this.util.messageDialogue("Le troll est vide");
+      return;
    }
 
-   var dataToSend = 
-      {
-         "action" : "put_troll", 
-         "cookie" : this.client.cookie,
-         "content" : content
-      }
+   var dataToSend = {
+      "header" : { "action" : "put_troll", "version" : euphorik.conf.versionProtocole },
+      "cookie" : this.client.cookie,
+      "content" : content
+   };
 
-   ;;; dumpObj(dataToSend)
-   jQuery.ajax(
-      {
-         type: "POST",
-         url: "request",
-         dataType: "json",
-         data: this.util.jsonVersAction(dataToSend),
-         success:
-            function(data)
-            {
-               ;;; dumpObj(data)
-               
-               if (data["reply"] == "ok")
-               {
-                  $("#page form#nouveauTroll input.troll").val("")
-               }
-               else if (data["reply"] == "error")
-               {
-                  thisPageAdmin.util.messageDialogue(data["error_message"])
-               }
+   jQuery.ajax({
+      type: "POST",
+      url: "request",
+      dataType: "json",
+      data: this.util.jsonVersAction(dataToSend),
+      success:
+         function(data){               
+            if (data.reply === "ok") {
+               $("#page form#nouveauTroll input.troll").val("");
+            } else if (data.reply === "error") {
+               thisPageAdmin.util.messageDialogue(data.error_message);
             }
-      }
-   )
-}
-
-///////////////////////////////////////////////////////////////////////////////////////////////////
+         }
+   });
+};
 
-function Trolls(client, util, formateur)
-{
-   this.client = client
-   this.util = util
-   this.formateur = formateur
-   this.dernierTroll = 0
-   this.pageEvent = new PageEvent("admin", this.util)
-}
+/**
+  * Met à jour la liste des IP bannies.
+  */
+euphorik.PageAdmin.prototype.majIPs = function() {
+   if (this.timeoutIDmajIPs) {
+      clearTimeout(this.timeoutIDmajIPs);
+   }
 
+   var thisPageAdmin = this;
 
-Trolls.prototype.modifier = function(id, content)
-{
-   var dataToSend =
-      {
-         "action" : "mod_troll",
-         "cookie" : this.client.cookie,
-         "troll_id" : id,
-         "content" : content
-      }
+   var dataToSend = {
+      "header" : { "action" : "list_banned_ips", "version" : euphorik.conf.versionProtocole },
+      "cookie" : this.client.cookie
+   };
 
-   ;;; dumpObj(dataToSend)
-   jQuery.ajax(
-      {
-         type: "POST",
-         url: "request",
-         dataType: "json",
-         data: this.util.jsonVersAction(dataToSend),
-         success:
-            function(data)
-            {
-               ;;; dumpObj(data)
-               if (data["reply"] == "error")
-               {
-                  thisPageAdmin.util.messageDialogue(data["error_message"])
+   jQuery.ajax({
+      type: "POST",
+      url: "request",
+      dataType: "json",
+      data: this.util.jsonVersAction(dataToSend),
+      success:
+         function(data) {               
+            if (data.reply === "list_banned_ips") {
+               var XHTML = "";
+               data.list.each(function(i, ip) {
+                  XHTML += '<div class="ban"><span class="ip">' + ip.ip + '</span>|' +
+                     '<span class="temps">' +
+                     ip.remaining_time +
+                     '</span>|';
+                  ip.users.each(function(j, user) {
+                     XHTML += (j > 0 ? ", " : "") +
+                        '<span class="pseudo">' + thisPageAdmin.formateur.traitementComplet(user.nick) + '</span>' +
+                        (user.login === "" ? "" : '<span class="login">(' + thisPageAdmin.formateur.traitementComplet(user.login) + ')</span>');
+                  });
+                  XHTML += '<span class="deban">débannir</span></div>';
+               });
+               
+               if (data.list.length === 0) {
+                  XHTML += '<p>Aucune IP bannie</p>';
                }
+                  
+               $("#ips").html(XHTML);
+               
+               $(".ban").each(function() {
+                  var ip = $(".ip", this).html();
+                  $(".deban", this).click(
+                     function() {
+                        thisPageAdmin.util.messageDialogue("Êtes-vous sur de vouloir débannir l'IP ''" + ip + "'' ?", euphorik.Util.messageType.question,
+                           {"Oui" : function() {
+                                 thisPageAdmin.deban(ip);
+                              },
+                            "Non" : function(){}
+                           }
+                        );
+                     }
+                  );
+               });
+            } else if (data.reply === "error") {
+               thisPageAdmin.util.messageDialogue(data.error_message);
             }
-      }
-   )
-}
+            
+            // rafraichissement toutes les minutes (je sais c'est mal)
+            // le problème est le rafraichissement des temps restant de bannissement qui doit être fait du coté client
+            thisPageAdmin.timeoutIDmajIPs = setTimeout(function(){ thisPageAdmin.majIPs(); }, 60 * 1000);
+         }
+   });
+};
 
 /**
-  * Supprime un troll en fonction de son id.
+  * Débannie une ip donnée.
   */
-Trolls.prototype.supprimer = function(id) 
-{
-   var dataToSend =
-      {
-         "action" : "del_troll",
-         "cookie" : this.client.cookie,
-         "troll_id" : id
-      }
+euphorik.PageAdmin.prototype.deban = function(ip) {
+   var thisPageAdmin = this;
+
+   var dataToSend = {
+      "header" : { "action" : "unban", "version" : euphorik.conf.versionProtocole },
+      "cookie" : this.client.cookie,
+      "ip" : ip
+   };
 
-   ;;; dumpObj(dataToSend)
-   jQuery.ajax(
+   jQuery.ajax({
+      type: "POST",
+      url: "request",
+      dataType: "json",
+      data: this.util.jsonVersAction(dataToSend),
+      success:
+         function(data){
+            if(data.reply === "error") {
+               thisPageAdmin.util.messageDialogue(data.error_message);
+            }
+         }
+   });
+};
+
+/**
+  * Attente d'événement de la part du serveur.
+  */
+euphorik.PageAdmin.prototype.waitEvent = function() {
+   var thisPageAdmin = this;
+         
+   this.comet.waitEvent(
+      function() { return { "last_troll" : thisPageAdmin.trolls.dernierTroll }; },
       {
-         type: "POST",
-         url: "request",
-         dataType: "json",
-         data: this.util.jsonVersAction(dataToSend),
-         success:
-            function(data)
-            {
-               ;;; dumpObj(data)
-               if (data["reply"] == "error")
-               {
-                  thisPageAdmin.util.messageDialogue(data["error_message"])
-               }
+         "troll_added" : function(data){ thisPageAdmin.trolls.ajouterTrollEvent(data); },
+         "troll_modified" : function(data){ thisPageAdmin.trolls.modifierTrollEvent(data); },
+         "troll_deleted" : function(data){ thisPageAdmin.trolls.supprimerTrollEvent(data); },
+         "banned_ips_refresh" : function(data){ thisPageAdmin.majIPs(); },
+         "error" :
+            function(data) {
+               thisTrolls.util.messageDialogue(data.error_message);
             }
       }
-   )
-}
+   );
+};
+
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+/**
+  * Représente un troll, pas grand chose finalement.
+  */
+euphorik.Troll = function(content, author) {
+   this.content = content;
+   this.author = author;
+};
 
-Trolls.prototype.rafraichirTrolls = function()
-{
-   var thisTrolls = this
+///////////////////////////////////////////////////////////////////////////////////////////////////
+
+euphorik.Trolls = function(client, util, formateur) {
+   this.client = client;
+   this.util = util;
+   this.formateur = formateur;
+   this.dernierTroll = 0;
+   
+   this.trolls = {};
+};
+
+euphorik.Trolls.prototype.ajouterTrollEvent = function(data) {
+   var thisTrolls = this;
+
+   var XHTML = "";
+   data.trolls.each(function(i, trollData) {
+      var troll = new euphorik.Troll(trollData.content, trollData.author);
+      var trollId = trollData.troll_id;
+      thisTrolls.trolls[trollId] = troll;
+      
+      XHTML +=
+         '<div id="troll' + trollId + '" class="troll">' +
+         '<span class="content">' + thisTrolls.formateur.traitementComplet(troll.content, troll.author) + '</span>' +
+         '<span class="author"> - ' + thisTrolls.formateur.traitementComplet(troll.author) + '</span>' +
+         (trollData.author_id === thisTrolls.client.id ? '<span class="editTroll">éditer</span><span class="delTroll">Supprimer</span>' : '') +
+         '</div>';
+   });
+   $("#trolls").append(XHTML);
+   $("#trolls .troll").filter(function() { return parseInt($(this).attr("id").substr(5), 10) > thisTrolls.dernierTroll; }).each(
+      function() {
+         var troll = this;
+         var id = parseInt($(this).attr("id").substr(5), 10);
          
-   this.pageEvent.waitEvent(
-      function() { return { "last_troll" : thisTrolls.dernierTroll }},
-      function(data)
-      {
-         switch (data["reply"])
-         {
-            case "troll_added" :
-               var XHTML = ""
-               for (var i = 0; i < data["trolls"].length; i++)
-               {
-                  XHTML +=
-                     '<div id="troll' + data["trolls"][i]["troll_id"] + '" class="troll">' +
-                     '<span class="content">' + thisTrolls.formateur.traitementComplet(data["trolls"][i]["content"], data["trolls"][i]["author"]) + '</span>' +
-                     '<span class="author">' + thisTrolls.formateur.traitementComplet(data["trolls"][i]["author"]) + '</span>' +
-                     (data["trolls"][i]["author_id"] == thisTrolls.client.id ? '<span class="editTroll">éditer</span><span class="delTroll">Supprimer</span>' : '') +
-                     '</div>'
+         $("a[@rel*=lightbox]", this).lightBox();
+         
+         $(this).keypress(
+            function(e) {
+               if (e.which === 13) { // return
+                  $(".modifier", this).click();
                }
-               $("#trolls").append(XHTML)
-               $("#trolls .troll").filter(function(){return parseInt($(this).attr("id").substr(5)) > thisTrolls.dernierTroll}).each(
-                  function()
+            }
+         );
+         
+         $(".delTroll", this).click(
+            function() {
+               thisTrolls.util.messageDialogue(
+                  "Êtes-vous sur de vouloir supprimer le troll \"" + thisTrolls.trolls[id].content + "\" ?",
+                  euphorik.Util.messageType.question,
                   {
-                     var troll = this
-                     var id = parseInt($(this).attr("id").substr(5))
-                     $(".delTroll", this).click(
-                        function()
-                        {
-                           thisTrolls.util.messageDialogue(
-                              "Êtes-vous sur de vouloir supprimer le troll \"" + $("#trolls .troll .content").html() + "\" ?",
-                              messageType.question,
-                              {
-                                 "oui" : function()
-                                    {
-                                       thisTrolls.supprimer(id)
-                                    },
-                                 "non" : function(){}
-                              }
-                           )
-                        }
-                     )
-                     $(".editTroll", this).click(
-                        function()
-                        {
-                           $("span", troll).css("display", "none")
-                           $(troll).append(
-                              '<form><p><input class="content" type="text" size="50" maxlength="500" value="' + $(".content", troll).html() + '"></input><button class="modifier">modifier</button><button class="annuler">annuler</button></p></form>'
-                           )
-                           var virerLeFormulaire = function()
-                           {
-                              $("form", troll).remove()
-                              $("span", troll).css("display", "inline")
-                           }
-                           $("button.modifier", troll).click(
-                              function()
-                              {
-                                 var content = $("form input.content", troll).val()
-                                 virerLeFormulaire()
-                                 thisTrolls.modifier(id, content)
-                              }
-                           )
-                           $("button.annuler", troll).click( virerLeFormulaire )
-                           $("form", troll).submit(function(){ return false})
-                        }  
-                     )
+                     "oui" : function() {
+                           thisTrolls.supprimer(id);
+                        },
+                     "non" : function(){}
                   }
-               )
+               );
+            }
+         );
+         
+         $(".editTroll", this).click(
+            function() {
+               $("span", troll).css("display", "none");
+               $(troll).append(
+                  '<form><p><input class="content" type="text" size="50" maxlength="500" value="' +
+                  thisTrolls.trolls[id].content +
+                  '"></input><span class="modifier">modifier</span><span class="annuler">annuler</span></p></form>'
+               );
+               $("form input.content").focus();
                
-               if (data["trolls"].length > 0)
-                  thisTrolls.dernierTroll = data["trolls"][data["trolls"].length - 1]["troll_id"]
-               break
-            case "troll_modified" :
-               $("#trolls #troll" + data["troll_id"] + " .content").html(data["content"])
-               break
-            case "troll_deleted" :
-               $("#trolls #troll"+data["troll_id"]).remove()
-               break
-         }
+               var virerLeFormulaire = function() {
+                  $('form', troll).remove();
+                  $('span', troll).css("display", "inline");
+               };
+               $("span.modifier", troll).click(
+                  function() {
+                     var content = $("form input.content", troll).val();
+                     virerLeFormulaire();
+                     thisTrolls.modifier(id, content);
+                  }
+               );
+               $("span.annuler", troll).click( virerLeFormulaire );
+               $("form", troll).submit(function(){ return false; });
+            }
+         );
       }
-   )
-}
\ No newline at end of file
+   );
+   
+   if (data.trolls.length > 0) {
+      thisTrolls.dernierTroll = data.trolls[data.trolls.length - 1].troll_id;
+   }
+};
+
+euphorik.Trolls.prototype.modifierTrollEvent = function(data) {
+   var thisTrolls = this;
+   $("#trolls #troll" + data.troll_id + " .content").html(thisTrolls.formateur.traitementComplet(data.content, thisTrolls.trolls[data.troll_id].author));
+   $("#trolls #troll" + data.troll_id + " a[@rel*=lightbox]").lightBox();
+   thisTrolls.trolls[data.troll_id].content = data.content;
+};
+
+euphorik.Trolls.prototype.supprimerTrollEvent = function(data) {
+   $("#trolls #troll" + data.troll_id).remove();
+};
+
+euphorik.Trolls.prototype.modifier = function(id, content) {
+   var thisTrolls = this;
+   
+   var dataToSend = {
+      "header" : { "action" : "mod_troll", "version" : euphorik.conf.versionProtocole },
+      "cookie" : this.client.cookie,
+      "troll_id" : id,
+      "content" : content
+   };
+
+   jQuery.ajax({
+      type: "POST",
+      url: "request",
+      dataType: "json",
+      data: this.util.jsonVersAction(dataToSend),
+      success:
+         function(data) {
+            if (data.reply === "error") {
+               thisTrolls.util.messageDialogue(data.error_message);
+            }
+         }
+   });
+};
+
+/**
+  * Supprime un troll en fonction de son id.
+  */
+euphorik.Trolls.prototype.supprimer = function(id) {
+   var thisTrolls = this;
+
+   var dataToSend = {
+      "header" : { "action" : "del_troll", "version" : euphorik.conf.versionProtocole },
+      "cookie" : this.client.cookie,
+      "troll_id" : id
+   };
+
+   jQuery.ajax({
+      type: "POST",
+      url: "request",
+      dataType: "json",
+      data: this.util.jsonVersAction(dataToSend),
+      success:
+         function(data) {
+            if (data.reply === "error") {
+               thisTrolls.util.messageDialogue(data.error_message);
+            }
+         }
+   });
+};