6

我已经创建了简单的 Gmail 插件,现在我正在努力使用以下策略。

安装插件后,当第一个收件箱打开时,我们要求用户输入基本信息,当他打开第二个邮件时,我们不会再询问基本信息细节。

我该如何处理?

我尝试过物业服务,但没有运气。

更新

var MAX_THREADS = 5;

/**
 * Returns the array of cards that should be rendered for the current
 * e-mail thread. The name of this function is specified in the
 * manifest 'onTriggerFunction' field, indicating that this function
 * runs every time the add-on is started.
 *
 * @param {Object} e data provided by the Gmail UI.
 * @returns {Card[]}
 */
function buildAddOn(e) {
  // Activate temporary Gmail add-on scopes.
  //Logger.log('E', Session.getActiveUser());
  var accessToken = e.messageMetadata.accessToken;
  GmailApp.setCurrentMessageAccessToken(accessToken);
  var userProperties = PropertiesService.getUserProperties();
  var Token = userProperties.getProperty('Token');
  Logger.log('Token value:',typeof Token);
  if(Token != null ){
    var messageId = e.messageMetadata.messageId;
    var senderData = extractSenderData(messageId);
    var cards = [];

    // Build a card for each recent thread from this email's sender.
    if (senderData.recents.length > 0) {
      senderData.recents.forEach(function(threadData) {
        cards.push(buildRecentThreadCard(senderData.email, threadData));
      });
    } else {
      // Present a blank card if there are no recent threads from
      // this sender.
      cards.push(CardService.newCardBuilder()
        .setHeader(CardService.newCardHeader()
        .setTitle('No recent threads from this sender')).build());
    }
    return cards;
  } 
  else{
    var cards = []
    var login_card = build_login_card()
    cards.push(login_card);
    return cards;
  }
}

/**
 *  This function builds a set of data about this sender's presence in your
 *  inbox.
 *
 *  @param {String} messageId The message ID of the open message.
 *  @return {Object} a collection of sender information to display in cards.
 */
function extractSenderData(messageId) {
  // Use the Gmail service to access information about this message.
  var mail = GmailApp.getMessageById(messageId);
  var threadId = mail.getThread().getId();
  var senderEmail = extractEmailAddress(mail.getFrom());

  var recentThreads = GmailApp.search('from:' + senderEmail);
  var recents = [];

  // Retrieve information about up to 5 recent threads from the same sender.
  recentThreads.slice(0,MAX_THREADS).forEach(function(thread) {
    if (thread.getId() != threadId && ! thread.isInChats()) {
      recents.push({
        'subject': thread.getFirstMessageSubject(),
        'count': thread.getMessageCount(),
        'link': 'https://mail.google.com/mail/u/0/#inbox/' + thread.getId(),
        'lastDate': thread.getLastMessageDate().toDateString()
      });
    }
  });

  var senderData = {
    "email": senderEmail,
    'recents': recents
  };

  return senderData;
}

/**
 *  Given the result of GmailMessage.getFrom(), extract only the email address.
 *  getFrom() can return just the email address or a string in the form
 *  "Name <myemail@domain>".
 *
 *  @param {String} sender The results returned from getFrom().
 *  @return {String} Only the email address.
 */
function extractEmailAddress(sender) {
  var regex = /\<([^\@]+\@[^\>]+)\>/;
  var email = sender;  // Default to using the whole string.
  var match = regex.exec(sender);
  if (match) {
    email = match[1];
  }
  return email;
}

/**
 *  Builds a card to display information about a recent thread from this sender.
 *
 *  @param {String} senderEmail The sender email.
 *  @param {Object} threadData Infomation about the thread to display.
 *  @return {Card} a card that displays thread information.
 */
function buildRecentThreadCard(senderEmail, threadData) {
  var card = CardService.newCardBuilder();
  card.setHeader(CardService.newCardHeader().setTitle(threadData.subject));
  var section = CardService.newCardSection()
    .setHeader("<font color=\"#1257e0\">Recent thread</font>");
  section.addWidget(CardService.newTextParagraph().setText(threadData.subject));
  section.addWidget(CardService.newKeyValue()
    .setTopLabel('Sender')
    .setContent(senderEmail));
  section.addWidget(CardService.newKeyValue()
    .setTopLabel('Number of messages')
    .setContent(threadData.count.toString()));
  section.addWidget(CardService.newKeyValue()
    .setTopLabel('Last updated')
    .setContent(threadData.lastDate.toString()));

  var threadLink = CardService.newOpenLink()
    .setUrl(threadData.link)
    .setOpenAs(CardService.OpenAs.FULL_SIZE);
  var button = CardService.newTextButton()
    .setText('Open Thread')
    .setOpenLink(threadLink);
  section.addWidget(CardService.newButtonSet().addButton(button));

  card.addSection(section);
  return card.build();
}
function build_login_card(){
  var card = CardService.newCardBuilder();
  card.setHeader(CardService.newCardHeader().setTitle("Login Here"));
  var userProperties = PropertiesService.getUserProperties();
  var Token = userProperties.setProperty('Token',"Token");
  return card.build()
}
4

2 回答 2

3

根据评论,这里的主要问题是卸载插件不会从 UserProperties 数据存储中删除位,因此如果重新安装插件,则无法再次执行插件配置步骤。

通用附加解决方案

如果这不是 Gmail 插件,则可以通过基于时间的触发器简单地解决此问题,因为根据文档:

加载项触发器将在以下任何情况下停止触发:
- 如果用户卸载了
加载项 - 如果在文档中禁用了加载项(如果重新启用,触发器将再次变为可操作)
- 如果开发者取消发布插件或向插件商店提交损坏的版本

即,您只需将当天的日期写入每天的键(例如LAST_SEENPropertiesService#UserProperties,然后在决定显示哪张卡片时检查 TOKEN 和 LAST_SEEN。


Gmail 插件解决方案:

根据 Gmail 插件文档,您不能在 Gmail 插件中创建或使用 Apps 脚本简单/可安装触发器。因此,最简单的解决方案实施不可用。但是,我们仍然可以使用这种方法,通过移动更新该LAST_SEEN密钥的区域。

目前(2018 年 3 月),Gmail 插件唯一可用的触发器是上下文触发器unconditional

目前,唯一可用的上下文触发类型是unconditional,无论内容如何,​​它都会触发所有电子邮件。

因此,如果您绑定到此上下文触发器,则在安装插件时,只要用户打开电子邮件,它就会运行一个函数。然后,解决方案是让您的上下文触发函数包含代码段

PropertiesService.getUserProperties().setProperty("LAST_SEEN", String(new Date().getTime()));

如果您在上下文触发的函数中有其他事情要做,那么该代码将不受此添加的影响。如果您没有上下文触发的功能,那么您会想要return [](一个空的卡片堆栈)以避免显示任何 UI。

要使用此新属性,buildAddon(e)除了您正在使用的 TOKEN 属性之外,您还希望在您的方法中查询此值:

var userProps = PropertiesService.getUserProperties().getAll();
var Token = userProps["Token"];
var lastSeen = userProps["LAST_SEEN"] || 0; // If found, will be milliseconds since epoch.
var absence = new Date().getTime() - lastSeen; // Time in ms since last use of add-on.
if (Token == null || absence > /* some duration you choose */ ) {
  // New install, or user has started using app again.
  return [build_login_card()];
} else {
  // User is still using add-on, so do normal stuff.
}

  • 这显然不是一个完美的解决方案(即uninstall上下文触发会更好),但可以帮助检测缺乏使用的情况
  • 写入 PropertiesService 的频率有速率限制。如果您有快速/“超级”用户,他们可能会超出配额。
    • 可以结合 CacheService 和 PropertiesService 来处理“短”会话中的频繁读取(自上次存储到缓存后长达 6 小时)。
于 2018-03-21T01:17:49.240 回答
0

罗伯特,你试过缓存用户输入吗?

我在事件处理程序中进行缓存。

function onDomainChange(e){
    var cache = CacheService.getScriptCache();
    Logger.log(e.formInput);
    cache.put('domain',e.formInput.domain);
    Logger.log(cache.get('domain'));
}

参考缓存文档

于 2018-06-01T02:16:44.310 回答