Ir al contenido principal

Obten recordatorios de los cumpleaños de tus contactos en tu android

Como todavía no me he desliado la manta de la cabeza he parido otro gScript para una funcionalidad que echo muchísimo de menos en los móviles desde aquellos maravillosos nokia: El recordatorio de que hoy es el cumpleaños de tu abuela. Bueno y ahora el código:

//Script by Borja Garcia <debuti@gmail.com>
//GPL
//v0.0.1 - 20100925
//
//Changelog:
//v0.0.1 - Initial version
//
//Note:
//Configure it and add an 1pm trigger
function notifyBirthday() {
 
// Constants
  var ONE_MINUTE=60000; //milliseconds
  var ONE_HOUR=ONE_MINUTE*60;
  var ONE_DAY=ONE_HOUR*24;

  var SOURCE_CALENDAR = "Contacts' birthdays and events";
  var FINAL_CALENDAR = "[Warn]Birthdays";
  var HOUR_TO_NOTIFY_ME = 12;
  
// Helpers
  function getThatDayAtMidnight(thatDay) {
    var result = new Date();
    
    var dateInMillis = String(thatDay.getTime()/ONE_DAY);
    result.setTime(parseInt(dateInMillis.split(".")[0])*ONE_DAY);
    
    return result;   
  }
  
  function fetchTodayBirthdays() {
    var output = [ ["this is the name", "These are the years", "This is the email"]]
    var calendar = CalendarApp.getCalendarsByName(SOURCE_CALENDAR)[0];

    if (calendar != null) {
      var from = new Date()
      Logger.log(from)
      var events = calendar.getEventsForDay(from);
      if (events.length != 0) {
        for (index=0; index<events.length; index=index+1){
          var event = events[index].getTitle()
          var comma = event.indexOf("'s birthday")
          var contact = event.substring(0, comma)
          
          var allcontacts = ContactsApp.getAllContacts();
          var years = "undefined"
          var mail = "undefined"
        
          for (var i in allcontacts) {
            if (contact === allcontacts[i].getFullName()) {
              years = allcontacts[i].getUserDefinedField("Birthday");
              mail = allcontacts[i].getPrimaryEmail();
              break
            }
          }
        
          //Name goes to first position
          output[index][0] = contact
          //Years goes to second
          output[index][1] = years
          //Mail goes to third
          output[index][2] = mail
          Logger.log("Retrieved user " + contact + " with years " + years + " and email " + mail);        
        }
        return output;
      }
      else {
        Logger.log("There are no birthdays today");
        return null;
      }
    }
    else {
      Logger.log("Error: Calendar " + SOURCE_CALENDAR + " not fetched");
      return null;
    }
  }

  function moveToLocalBirthdayCalendar(birthdays) {            
    var doneCalendar = CalendarApp.getCalendarsByName(FINAL_CALENDAR)[0];   
    var startTime = getThatDayAtMidnight(new Date());
    startTime.setTime(startTime.getTime() + (HOUR_TO_NOTIFY_ME - 2) * ONE_HOUR); //I applied the timezone correction
    var endTime = new Date();
    endTime.setTime(startTime.getTime() + ONE_HOUR);
    //Logger.log(startTime);
    //Logger.log(endTime);
 
    for (index=0; index<birthdays.length; index=index+1){
      var result = doneCalendar.createEvent(birthdays[index][0], startTime, endTime, {description:"The person borns in " + birthdays[index][1] + ", you have to send a mail to " +  birthdays[index][2]});
      if (result != null) {
        Logger.log("Done moving the birthday " + birthdays[index][0]);
      }
      else {
        Logger.log("Error moving the birthday " + birthdays[index][0]);
      }
    }
 
  }
    
// Entry point
      
  birthdays = fetchTodayBirthdays()
  if (birthdays != null && birthdays.length > 0) {
    moveToLocalBirthdayCalendar(birthdays)
  }
    
}

Hay tres cosas que teneis que hacer:
  • Suscribiros al calendario "Contact birthdays and events", el cual se encuentra bajo el menú "Calendarios interesantes" de gCalendar.
  • Crear un nuevo calendario que va a ser el que se sincronizara con android. En este calendario tenéis que configurar que por defecto os notifique por "Pop-up".


  • Copiar este código en vuestro repositorio google apps scripts como ya indique en mi anterior post y configurar los parámetros de acuerdo con vuestras apetencias.
La idea buena de todo esto es que al tener los cumpleaños de los contactos almacenados en gContacts (podéis editarlos en www.google.com/contacts) automáticamente se actualizarán en el calendario que habéis importado, pero no podremos modificarlo para obtener notificaciones. Por eso, cada día el script se ejecutara y copiara los cumpleaños al calendario local de cumpleaños, el cual si podréis configurar para que os notifique.



Ala, ahora a no preocuparse mas.

pd. Chona, que sepas que esta va por ti! que tu cumple no se me pasaba ni de blas! jeje

Comentarios

Entradas populares de este blog

Yamaha XT 125R Manual

Para aquellos que lo hayan perdido y no quieran comprar uno nuevo por el doble de lo que cuesta cambiar el aceite.. https://mega.nz/#F!ZeYh3QzD !mSOhljTo5UWedfEWq5cCjw Algunos "trucos":  - Si os marca mal la velocidad es porque la teneis configurada mal (supermotard en enduro y viceversa), para cambiar este ajuste teneis que quitar la bateria varios minutos y al volver a enchufar con el boton azul seleccionar la correcta. La mia es enduro  - Si cambiais el aceite:    + Para no tener que desmontar media moto lo mejor es introducir una botella de cocacola de plástico cortada, con el tapón abierto y dejar que el aceite escurra a traves de ella hacia la lata dónde vais a desecharlo    + Para resetear el contador de kilómetros que quedan para el cambio de aceite hay que apagar la moto, pulsar el botón azul, encenderla y esperar hasta que en la pantalla aparezca reseteado

Tasker: Profiles with priorities

Hi! If you read Tasker docs, you may find that with Tasker its not possible to establish actions based on profile priorities if you have two of them activated at the same time; in the other hand Setting Profiles is a unmantained old app that can do this, but have no scripting capabilities like Tasker. Here is the solution using Tasker powerful environment. The main idea is to do this: Profiles/Init (44) A1: If [ %Profiles_pactivelast Is Set & %Profiles_pactivelast !~ %PACTIVE ] A2: Perform Task [ Name:Profiles/Profile/Default Stop:Off Priority:5 Parameter 1 (%par1): Parameter 2 (%par2): Return Value Variable: ]  A3: Variable Set [ Name:%profile_priority To:Work,Class,Study,Sleep,Low battery, Charging weak,Charging strong Do Maths:Off Append:Off ]  A4: Variable Split [ Name:%profile_priority Splitter:, Delete Base:Off ]  A5: For [ Variable:%profile Items:%profile_priority() ]  A6: [X] Flash [ Text:%profile Long:Off ]  A7: [X] Wait [ MS:0 Seconds:5 Minutes:0 Hour