[go: up one dir, main page]

Menu

[r18]: / trunk / ajax.js  Maximize  Restore  History

Download this file

242 lines (211 with data), 7.5 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// ajax.js
// requires: ratax.js
if ( typeof(ratax) != 'function' ) {
throw new Error('ratax.js is required');
}
function RatChat() {
//var r = new Object();
var xhr = new ratax();
xhr.rpcuri = 'ajax.php';
var chat = this;
var lastMsg = 0;
var input = null;
var output = null;
var channel = 0;
var pollFreq = 600;
var pollInterval = null;
var that = this;
var timezone = 0;
// Establecer la frecuencia de actualización (en segundos)
this.setFreq = function (seconds) { pollFreq = seconds; }
// Obtiene la frecuencia de actualización (en segundos)
this.getFreq = function () { return pollFreq; }
this.onPost = function () { chat.pollMsg(); }
// Fijar un <INPUT> como campo de entrada
this.setInput = function (textfield) {
input = textfield;
var f = input.onkeypress;
if ( typeof(f) != 'function' ) f=function () {};
var c = this;
input.onkeypress = function (e) {
var key;
if(window.event) key = window.event.keyCode; //IE
else key = e.which; //firefox
f();
if(key == 13) { c.sendMsg(); return false; } else return true;
}
}
// Enviar un mensaje (versión interna)
this.sendMsg = function () {
var msg = input.value;
input.value='';
if ( msg.match(/^\//) ) return this.command(msg);
if ( msg.match(/^$/)==null ) { this.post(msg); }
this.pollMsg();
}
// Fijar un <DIV> para la salida
this.setOutput = function (div) {
output = div;
}
// Establecer el nickname a utilizar
this.setNick = function (nick) { return xhr.call('setNick',{'nick':nick},null,false); }
// Obtener el nickname actual
this.getNick = function () { return xhr.call('getNick',null,null,false); }
this.setChannel = function (chanid) { channel = chanid; }
this.getChannel = function () { return channel; }
this.getDefaultChannel = function () { return xhr.call('getDefaultChannel',null,null,false); }
// Enviar un mensaje al canal activo
this.post = function (msg) { return this.postChannel(channel,msg); }
// Enviar mensaje a cualquier canal
this.postChannel = function (channel,msg) {
try {
return xhr.call('post',{'chanid':channel,'msg':msg},this.onPost,true);
}
catch (e) {
if ( e == 'Error: No nick' ) {
var n = prompt('Escribe tu nombre:','');
if ( n!=null && n!='' ) {
this.setNick();
return this.postChannel(channel,msg);
}
else if ( n==null ) {
displaySysMsg({'msg':'Si no apareció una ventana pidiendo tu nombre, escribe: /nick tunombre'});
}
}
}
}
// Obtener los mensajes del canal activo
this.get = function () {
var m = xhr.call('get',{'chanid':channel,'lastmsg':lastMsg},null,false);
if ( m.length>0 ) { lastMsg = m[0].lastmsg; }
return m;
}
// Iniciar las peticiones periódicas (polling)
this.startPolling = function () {
var n = this.getNick();
while ( this.getNick() == null ) {
var a = prompt('Escribe tu nombre:');
this.setNick(a);
}
displaySysMsg({'msg':'Hola '+this.getNick()+', bienvenid@ al canal '+this.getChannel()});
this.pollMsg();
pollInterval = setInterval(this.pollMsg, pollFreq*1000);
}
// Detener la petición periódica (polling)
this.stopPolling = function () { clearInterval(pollInterval); }
// Polling de los mensajes del canal activo
var pollingBusy = false;
this.pollMsg = function () {
if ( pollingBusy ) return;
pollingBusy = true;
var m = chat.get();
for ( var i=0 ; i < m.length ; i++ ) {
displayMsg(m[i]);
}
pollingBusy = false;
}
// Mostrar un mensaje
function displayMsg(m) {
if ( m.userid.match(/^[[]/) ) { return displaySysMsg(m); }
// Creamos algunos elementos
var p = document.createElement('P');
var chan = document.createElement('SPAN');
var ts = document.createElement('SPAN');
var name = document.createElement('SPAN');
var msg = document.createElement('SPAN');
// Clases CSS
ts.className = 'timestamp';
name.className = 'username';
msg.className = 'msg';
chan.className = 'channel';
// Contenido
var date = new Date(m.time*1000);
ts.appendChild(document.createTextNode( date.getHours()+':'+String(date.getMinutes()).replace(/^(.)$/,'0$1') ));
name.title = 'Fecha/Hora: '+date.toLocaleString();
name.appendChild( document.createTextNode(m.userid) );
msg.appendChild( document.createTextNode(m.msg) );
chan.appendChild( document.createTextNode(m.chanid) );
// Inserción
p.appendChild(ts);
if ( m.chanid != channel ) p.appendChild(chan);
p.appendChild(name);
p.appendChild(msg);
output.appendChild(p);
// Scrolldown y limpieza
output.scrollTop = output.scrollHeight;
while ( output.childNodes.length > 100 ) {
output.removeChild(output.childNodes[0]);
}
}
function displaySysMsg(m) {
// Creamos algunos elementos
var p = document.createElement('P');
var msg = document.createElement('SPAN');
// Clases CSS
msg.className = 'sysmsg';
// Contenido
msg.appendChild( document.createTextNode(m.msg) );
// Inserción
p.appendChild(msg);
output.appendChild(p);
// Scrolldown y limpieza
output.scrollTop = output.scrollHeight;
while ( output.childNodes.length > 100 ) {
output.removeChild(output.childNodes[0]);
}
}
this.command = function (string) {
var cmd = string.replace(/^\/([a-z]+).*$/,'$1');
var m = {"time":"","userid":"","msg":""};
switch (cmd) {
case 'nick':
var nick = string.replace(/^[^ ]+ ([^ ]+).*$/,'$1');
var pass = string.replace(/^[^ ]+ [^ ]+ (.*)$|^.*$/,'$1');
xhr.call('setNick',{'nick':nick,'pass':pass},null,false);
m.msg = 'Ahora eres conocido como '+xhr.call('getNick',null,null,false);
break;
case 'freq':
var f = Number(string.replace(/^[^ ]+ (.*)$/,'$1'));
if ( f > 0 ) {
this.setFreq(f);
}
m.msg = 'Frecuencia actual: '+this.getFreq()+' seg ('+Math.floor(this.getFreq()/60)+' min)';
break;
case 'msg':
var who = string.match(/\/msg ([^ ]+) (.*$)/);
var now = new Date();
m.msg = now.getHours()+':'+now.getMinutes()+' '+'@'+who[1]+':'+who[2];
this.postChannel('@'+who[1],who[2]);
break;
case 'whoami':
m.msg = 'Tú eres '+this.getNick();
break;
case 'who':
var minutes = string.replace(/[^0-9]/g,'');
if ( 0+minutes < 1 ) minutes=20;
var who = xhr.call('who',{'channel':this.getChannel(),'seconds':minutes*60},null,false);
//m.msg = xhr.serializer(who); displaySysMsg(m);
m.msg = who.length+' usuarios activos en los últimos '+minutes+' minutos: ';
for (var i=0; i<who.length; i++) {
m.msg += who[i];
if ( i+1 < who.length ) m.msg+=', ';
}
break;
case 'help':
m.msg = 'Comandos permitidos';displaySysMsg(m);
m.msg = '/help — este mensaje';displaySysMsg(m);
m.msg = '/msg usuario texto — enviar un texto privado a un usuario';displaySysMsg(m);
m.msg = '/nick nombre [password] — establece tu nombre ';displaySysMsg(m);
m.msg = '/freq [segundos] — cada cuántos segundos se consulta el servidor';displaySysMsg(m);
m.msg = '/who [minutos] — quién está activo en los últimos minutos';displaySysMsg(m);
return;
break;
default:
m.msg = '/help para obtener ayuda';
}
displaySysMsg(m);
}
channel = this.getDefaultChannel();
return this;
}
var chat = new RatChat();