MediaWiki:Common.js/Wikinoticias:Titulares en Portada/leadGenerator

De Wikinoticias, la fuente libre de noticias

Nota: Después de guardar, debes recargar la caché de tu navegador para ver los cambios:

  • Mozilla: Pulsa Recargar (o Ctrl-R)
  • Internet Explorer / Opera: Ctrl-F5
  • Safari: Cmd-R
  • Konqueror Ctrl-R.
mw.loader.load('//en.wikinews.org/w/index.php?title=user:Bawolff/mwapilib2.js&action=raw&ctype=text/javascript');
if (!window.Bawolff) {
 window.Bawolff = {};
}
// //en.wikinews.org/w/api.php?action=query&prop=revisions&titles=template:Lead%20article%201|template:Lead%20article%202|template:Lead%20article%203|template:Lead%20article%204|template:Lead%20article%205&rvprop=timestamp|content
//Llamada como Bawolff.leadGen(pageName, 1, alert)
//Reemplazando 1 con el que conduce (1-5), alerta con su devolución de llamada
//Opcionalmente toma resumén del metodo (como argumento numérico). elegir 0-4
Bawolff.leadGen = function (title, leadNumb, callback, summaryMethod) {
 api(title).getPage().lift(Bawolff.leadGen.extract, title, summaryMethod).lift(Bawolff.leadGen.create, leadNumb).lift(callback, title).exec();
}


/********
Esta es una lista de varios mapas, categorías e infoboxes para imágenes genericas

Nota: Esto no considera plantillas con sus parámetros
********/

Bawolff.leadGen.imgMap = { "Brasil": "Flag of Brazil.svg",
 "Canadá": "Flag of Canada.svg",
 "Estados Unidos": "Flag of the United States.svg",
 "Francia": "Flag of France.svg",
 "Chile": "Flag of Chile.svg",
 "España": "Flag of Spain.svg",
 "Argentina": "Flag of Argentina.svg",
 "Alemania": "Flag of Germany.svg",
 "Australia": "Flag of Australia.svg",
 "Perú": "Flag of Peru.svg",
 "Bolivia": "Flag of Bolivia.svg",
 "Colombia": "Flag of Colombia.svg",
 "Ecuador": "Flag of Ecuador.svg",
 "Paraguay": "Flag of Paraguay.svg",
 "Uruguay": "Flag of Uruguay.svg",
 "Portugal": "Flag of Portugal.svg",
 "Venezuela": "Flag of Venezuela.svg",
 "México": "Flag of Mexico.svg",
 "Cuba": "Flag of Cuba.svg",
 "Nicaragua": "Flag of Nicaragua.svg",
 "Guatemala": "Flag of Guatemala.svg",
 "Tailandia": "Flag of Thailand.svg",
 "Turquía": "Flag of Turkey.svg",
 "Japón": "Flag of Japan.svg",
 "China": "Flag of China.svg",
 "Rusia": "Flag of Russia.svg",
 "Haití": "Flag of Haiti.svg",
 "Ontario": "Flag of Ontario.svg",
 "Québec": "Flag of Quebec.svg",
 "Reino Unido": "Flag of the United Kingdom.svg",
 "India": "Flag of India.svg",
 "Siria": "Flag of Syria.svg",
 "Costa Rica": "Flag of Costa Rica.svg",
 "Corea del Norte": "Flag of North Korea.svg",
 "Corea del Sur": "Flag of South Korea.svg",
 "Nueva Zelanda": "Flag of New Zeland.svg",
 "Países Bajos": "Flag of the Netherlands.svg",
 "Santiago de Chile": "Flag of Santiago de Chile.svg",
 "Internet": "Internet map 1024.jpg",
 "Obituario": "Wikiobituaries.svg",
 "Fútbol": "Wikinews-football.svg",
 "Clima": "MonthlyMeanT.gif",
 "Política": "Uni Freiburg - Philosophen 4.jpg",
 "Terremotos": "Ondas sísmicas s p.svg",
 "Economía y Negocios": "Wikinoticias Economía y Negocios.svg",
 "Ciencia y tecnología": "Science-symbol-2.svg",
 "Desastres y accidentes": "CID post-impact 3.jpg",
 "Arte, cultura y entretenimiento": "Printing4 Walk of Ideas Berlin.JPG" }

//Tareas en la fuente en una página wiki, extraer el primer nombre de la imagen sin considerar el espacio de nombres "archivo"
Bawolff.leadGen.extractImg = function (page) {
 var imgRegex = /\[\[(?:[iI][mM][aA][gG][eE][nN]\:|[fF][Ii][lL][eE]\:|[Aai][rRm][cCa][hHg][iIe][vVn][oO]\:)((?:[^\|\]])*?\.[pPsSjJgG][nNvVpPiI][gGeEfF][gG]?)[\|\]]?/;
 var img = imgRegex.exec(page);
 if (img && img.length >= 2) {
  return img[1];
 }
 else {

  var infoboxRegex = /\{\{([^|}]*)\}\}/g;
  var categoryRegex = /\[\[[cC]ategor[yí]a?:([^|\]]*)(?:\|[^\]]*)?\]\]/g;
  //JS parece reutilizar estos objetos de llamadas previas sin restablecer lastIndex. Restablecer lastIndex.
  infoboxRegex.lastIndex = categoryRegex.lastIndex = 0;
  var item; //note doesn't match infoboxes w/params

  while (item = infoboxRegex.exec(page)) {
   item = item[1];
   item = item.charAt(0).toUpperCase() + item.substring(1, item.length);
   if (Bawolff.leadGen.imgMap[item]) return Bawolff.leadGen.imgMap[item];
  }
  while (item = categoryRegex.exec(page)) {
   item = item[1];
   item = item.charAt(0).toUpperCase() + item.substring(1, item.length);
   if (Bawolff.leadGen.imgMap[item]) return Bawolff.leadGen.imgMap[item];
  }

  return "Wikinews-logo.png"; //Imagen por defecto
 // Return "";
 } 

}

Bawolff.leadGen.extractAudio = function (page) {
//Versión audio|Ares I-X lancement réussi.ogg
 var res = page.match(/\{\{[vV]ersion audio\|([^|}]*)\|?[^}]*\}\}/);
 if (res) return res[1];
 return "";
}
Bawolff.leadGen.extractDate = function (page) {
 var ress = page.match(/\{\{[Ff]echa\|([^|}]*)\|?[^}]*\}\}/);
 if (ress) return ress[1];
 return "";
}
Bawolff.leadGen.extractType = function (page) {
 //Tipos validos son: Reportaje Original, Última Hora, o más.
 if (page.match(/\{\{[úuÚU]ltima hora(?: cours)?\}\}/)) {
  return "breaking";
 }
 else if (page.match(/\{\{[rR]eportaje(?: original)?(?:\|[^}]*)?\}\}/i)) {
  return "original";
 }
 else {
  //Por defecto
  return "none";
 }

}

Bawolff.leadGen.takeIntro = function (pageText, method) {
 //Primera prueba para redirecciones.
 var isRedirect = pageText.match(/^#redirect\s?\[\[([^\]]*)\]\]/i)
 if (isRedirect) {
  alert("Parece que intenta utilizar como titular una página de redirección. Utilice por favor el nombre real de la página en lugar de (" + isRedirect[1] + ").");
  throw new Error("La página es una redirección: " + isRedirect[1] );
 }

 //No manejar los enlaces que se convierten en [1].
 //Intencionalmente no tira carácteres ' (negrita o cursiva)
 //Ya que esto a menudo marca las cosas con períodos (E. coli)
 //El método es un número (debe ser un número, ningún tipo de conversión realizada).
 // 0: 1 (Primera Posición)
 // 1: 2 (Segunda Posición)
 // 2: 3 (Tercera Posición)
 // 3: 4 (Cuarta Posición)
 // 4: 5 (Quinta Posición)
 var fixWLink = /\{\{[wW]\|([^\}]+)\}\}/g
 var fixformatnum = /\{\{[Ff]ormatnum\:([^\}]+)\}\}/g
 var stripTemplates = /\{\{[^\}\{]*(?:\{\{[^\}\{]*(?:\{\{[^\}\{]*(?:\{\{[^\}\{]*\}\})?\}\})?\}\})?\}\}/g;
 var stripCitations = /\{\{(?:"\s?"|[Cc]ita|[Qq]uote|[Cc]quote?)\|([^}]*)\}\}/g; //Nota: Esto lo malinterpreta la plantilla:""
 var stripRefs = /\<ref[^>]*\>[\s\S]*?\<\/ref>/g;
 //Las expresiones regulares de los espacios de nombres de las imágenes, busca un comienzo de la imagen, comprueva vinculos internos anidados, archivos externos, y que terminan en ]]
 //Las plantillas ya deben ser esquivadas en este momento. (fr image = Fichier)
 var img = /\[\[[IifFaA][mMIirR][aALlcC][GgEehH][eEiI]?[eEnNvV]?[rRoO]?\:(?:\[\[(?:[^\]]*)\]\]|[^\]]|\](?!\]))*]]/g

 //Nota: Estos se ejecutan varias veces de manera cronometrada para hacer frente a la anidación.
 pageText = pageText.replace(fixWLink, '[[$1]]');
 pageText = pageText.replace(fixformatnum, '[[$1]]');
 pageText = pageText.replace(stripCitations, '{{Cita}}');
 pageText = pageText.replace(stripCitations, '{{Cquote}}');
 pageText = pageText.replace(stripCitations, '{{Quote}}');
 pageText = pageText.replace(stripTemplates, '');
 pageText = pageText.replace(stripTemplates, '');
 pageText = pageText.replace(stripTemplates, '');
 pageText = pageText.replace(stripTemplates, '');
 pageText = pageText.replace(stripRefs, '');
 pageText = pageText.replace(img, '');
 var pipedLink = /\[\[[^\]\|]*\|([^\]\|]*)\]\]/g;
 pageText = pageText.replace(pipedLink, '$1');
 var normLink = /\[\[([^\]\|]*)\]\]/g;
 pageText = pageText.replace(normLink, '$1');
 var extLink = /\[(?:http|ftp|gopher|irc|https)\:[^\]\s]*\s?([^\]]*)]/g
 pageText = pageText.replace(extLink, '$1');
 var firstPar;
 switch (method) {
  case 1: //Primeras 2 Frases o Primer Párrafo
   firstPar = /[^\n]+?\s[^\s\.]*\.(?=\s)(?:[^\n]+?\s[^\s\.]*\.(?=\s)|(?=\s))/;
   pageText = pageText.match(firstPar)[0];
   break;
  case 2: //Primer Párrafo
   firstPar = /[^\n]+?(?=\n)/;
   pageText = pageText.match(firstPar)[0];
   break;
  case 3: //Primeras 200 Letras
   firstPar = /[^\n]{2,250}.*?\b/;
   pageText = pageText.match(firstPar)[0] + "...";
   break;
  case 4: //Primeras 500 Letras
   firstPar = /[^\n]{2,500}.*?\b/;
   pageText = pageText.match(firstPar)[0] + "...";
   break;
  default: //Predeterminado, Primera Frase
   firstPar = /[^\n]+?\s[^\s\.]*\.(?=\s)/;
   pageText = pageText.match(firstPar)[0];
   break;
 }
 return pageText;
}

Bawolff.leadGen.extract = function(pageText, pageName, summaryMethod) {
//El enlace de edición es mostrado más tarde.
return { width:'200px',
         image: Bawolff.leadGen.extractImg(pageText),
         title: pageName,
         synopsis: Bawolff.leadGen.takeIntro(pageText, summaryMethod),
         edit_this: 'Wikinoticias:Zona de pruebas',
         audio: Bawolff.leadGen.extractAudio(pageText),
         date: Bawolff.leadGen.extractDate(pageText)
         };
}


Bawolff.leadGen.create = function (leadObj, leadNumb) {
 var res = '{' + '{Portada:Titular';
 res += "\n | id       = <!-- Este parámetro no debe modificarse --> " + leadNumb;
 res += "\n | ancho    = <!-- Ancho de la imagen, ajustado en 150px (vertical) o 250px (horizontal) de manera predeterminada --> " + leadObj.width;
 res += "\n | fecha    = <!-- Fecha de la noticia --> " + leadObj.date;
 res += "\n | imagen   = <!-- Solo el nombre, sin Archivo: ni similares --> " + leadObj.image;
 res += "\n | titulo   = <!-- Título completo de la noticia --> " + leadObj.title;
 res += "\n | breve    = <!-- Nombre más corto del título (úsese en caso de que sea muy largo) --> "
 res += "\n | resumen  = <!-- Resumen (sin enlaces), generalmente la primera oración de la noticia --> " + leadObj.synopsis;
 res += "\n}}"
 return res;
}
//Llamadas a su argumento dándole un objeto con meta información acerca de los titulares actuales.
//Probablemente desea usar Bawolff.leadGen.makeLeadTable en su lugar.

Bawolff.leadGen.makeLeadMetaObject = function (callback) {
 var leadObj = function (doc) {
  var exTitle = function (text) {
   text = text.replace(/[\s\S]*?\|Titulo=([^\|]*)[\s\S]*/, '$1');
   text = text.replace(/\s*$/, '');
   return text;
  }
  var pages = doc.getElementsByTagName('page');

  var obj = {}, time, time2 = Infinity;
  for (var i = 0; i < pages.length; i++) {
   pages[i].getElementsByTagName('rev')[0].normalize();
   time = Bawolff.mwapi.parseAPIDate(pages[i].getElementsByTagName('rev')[0].getAttribute('timestamp'));
   //Colocar el titular más antiguo en una variable global.
   if (time < time2) { //Esto compaara milisegundos pasados de época
    Bawolff.leadGen.oldestLead = pages[i].getAttribute('title');
    time2 = time;
   }
   obj[pages[i].getAttribute('title')] = {timestamp: time,
   title: exTitle(pages[i].getElementsByTagName('rev')[0].firstChild.data)};
  }
  return obj;
 }
 api().makeRequest({action: 'query', prop: 'revisions', titles: 'Plantilla:Portada:Titular 1|Plantilla:Portada:Titular 2|Plantilla:Portada:Titular 3|Plantilla:Portada:Titular 4|Plantilla:Portada:Titular 5', prop: 'revisions', rvprop: 'timestamp|content', redirects: true}, leadObj).lift(callback).exec();
}


Bawolff.leadGen.oldestLead = null;
Bawolff.leadGen.makeLeadTable = function (callback) {
 var wrapper = function(leadObj) {
  var html = '<table class="wikitable"><caption>Titulares Actuales</caption>';
  html += '<tr><th>#</th><th>Posición</th><th>Artículo</th><th>Tiempo en la Portada</th></tr>';
  for (var i in leadObj) {
   if (leadObj.hasOwnProperty(i)) {
    var numb = i.charAt(i.length - 1);
    html += '<tr><th>';
    html += numb; //Último carácter
    html += '</th><td>';
    html += Bawolff.leadGen.leadToPosition(numb);
    html += '</td><td>';
    html += leadObj[i].title;
    html += '</td><td>';
    var time = leadObj[i].timestamp.getTime(); //Conversión a milisegundos
    var d = (new Date).getTime();
    var delta = Math.round((d - time) / (1000*60*60));
    var timeStr;
    if (delta === 1) {
     timeStr = delta + ' hora';
    }
    else {
     timeStr = delta + ' horas';
    }
    html += timeStr;
    html += "</td></tr>";
   }
  }
  html += '</table>';
  callback(html);
 }
 Bawolff.leadGen.makeLeadMetaObject(wrapper);
}

Bawolff.leadGen.leadToPosition = function (numb) {
//Doble signo igual a partir de la cadena para igualar la conversión
 if (numb == 1 || numb === 'e') {
  return "Primera Posición";
 }
 if (numb == 2) {
  return "Segunda Posición";
 }
 if (numb == 3) {
  return "Tercera Posición";
 }
 if (numb == 4) {
  return "Cuarta Posición";
 }
 if (numb == 5) {
  return "Quinta Posición";
 }
 else {
  throw new Error("El número del titular no es válido (" + numb +") Bawolff.leadGen.leadToPosition");
 }
}