Skip to content

Instantly share code, notes, and snippets.

@supersupermomonga
Created September 28, 2015 07:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save supersupermomonga/111e9d399ed8fc411012 to your computer and use it in GitHub Desktop.
Save supersupermomonga/111e9d399ed8fc411012 to your computer and use it in GitHub Desktop.
/**
* Observe MailBox
*
* @param {string} condition メール検索条件(require)
* @param {function} onSuccess 条件合致時のコールバック(optional)
* @param {function} onFailure 例外発生時のコールバック(optional)
**/
function observe(condition, onSuccess, onFailure) {
try {
var observer = new GmailObserver(condition),
response = observer.getMails();
return onSuccess ? onSuccess(response) : response;
} catch(ex) {
var response = ex.toString();
return onFailure ? onFailure(response) : response;
}
}
/**
* Constructor GmailObserver
*
* @param {string} condition メール検索条件(require)
**/
function GmailObserver(condition) {
this.condition = condition;
this.setProcessedIds();
}
/**
* Set processed ids
*
**/
GmailObserver.prototype.setProcessedIds = function () {
var ids = PropertiesService.getUserProperties().getProperty(this.condition);
this.processed_ids = ids ? ids.split(',') : [];
}
/**
* Update processed ids
*
**/
GmailObserver.prototype.updateProcessedIds = function () {
PropertiesService.getUserProperties().setProperty(this.condition, this.processed_ids.join(','));
}
/**
* Get mails that match the condition
*
* @return {object} array [GmailMessage, ...]
**/
GmailObserver.prototype.getMails = function () {
var threads = GmailApp.search(this.condition),
result = [];
for(var i in threads) {
var messages = threads[i].getMessages();
for(var j in messages) {
var id = messages[j].getId();
if (this.processed_ids.indexOf(id) == -1) {
result.push(messages[j]);
this.processed_ids.push(id);
}
}
}
this.updateProcessedIds();
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment