summaryrefslogtreecommitdiffstats
path: root/gerrit-server/src/main/java/com/google/gerrit/server/mail/receive/MetadataParser.java
blob: 7085051b86df04b57d805cf752a9b4ebdb20fe7a (plain)
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
// Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.mail.receive;

import static com.google.gerrit.server.mail.MetadataName.toFooterWithDelimiter;
import static com.google.gerrit.server.mail.MetadataName.toHeaderWithDelimiter;

import com.google.common.base.Strings;
import com.google.common.primitives.Ints;
import com.google.gerrit.server.mail.MailUtil;
import com.google.gerrit.server.mail.MetadataName;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Parse metadata from inbound email */
public class MetadataParser {
  private static final Logger log = LoggerFactory.getLogger(MailProcessor.class);

  public static MailMetadata parse(MailMessage m) {
    MailMetadata metadata = new MailMetadata();
    // Find author
    metadata.author = m.from().getEmail();

    // Check email headers for X-Gerrit-<Name>
    for (String header : m.additionalHeaders()) {
      if (header.startsWith(toHeaderWithDelimiter(MetadataName.CHANGE_NUMBER))) {
        String num = header.substring(toHeaderWithDelimiter(MetadataName.CHANGE_NUMBER).length());
        metadata.changeNumber = Ints.tryParse(num);
      } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.PATCH_SET))) {
        String ps = header.substring(toHeaderWithDelimiter(MetadataName.PATCH_SET).length());
        metadata.patchSet = Ints.tryParse(ps);
      } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.TIMESTAMP))) {
        String ts = header.substring(toHeaderWithDelimiter(MetadataName.TIMESTAMP).length()).trim();
        try {
          metadata.timestamp = Timestamp.from(MailUtil.rfcDateformatter.parse(ts, Instant::from));
        } catch (DateTimeParseException e) {
          log.error("Mail: Error while parsing timestamp from header of message " + m.id(), e);
        }
      } else if (header.startsWith(toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE))) {
        metadata.messageType =
            header.substring(toHeaderWithDelimiter(MetadataName.MESSAGE_TYPE).length());
      }
    }
    if (metadata.hasRequiredFields()) {
      return metadata;
    }

    // If the required fields were not yet found, continue to parse the text
    if (!Strings.isNullOrEmpty(m.textContent())) {
      String[] lines = m.textContent().replace("\r\n", "\n").split("\n");
      extractFooters(lines, metadata, m);
      if (metadata.hasRequiredFields()) {
        return metadata;
      }
    }

    // If the required fields were not yet found, continue to parse the HTML
    // HTML footer are contained inside a <div> tag
    if (!Strings.isNullOrEmpty(m.htmlContent())) {
      String[] lines = m.htmlContent().replace("\r\n", "\n").split("</div>");
      extractFooters(lines, metadata, m);
      if (metadata.hasRequiredFields()) {
        return metadata;
      }
    }

    return metadata;
  }

  private static void extractFooters(String[] lines, MailMetadata metadata, MailMessage m) {
    for (String line : lines) {
      if (metadata.changeNumber == null && line.contains(MetadataName.CHANGE_NUMBER)) {
        metadata.changeNumber =
            Ints.tryParse(extractFooter(toFooterWithDelimiter(MetadataName.CHANGE_NUMBER), line));
      } else if (metadata.patchSet == null && line.contains(MetadataName.PATCH_SET)) {
        metadata.patchSet =
            Ints.tryParse(extractFooter(toFooterWithDelimiter(MetadataName.PATCH_SET), line));
      } else if (metadata.timestamp == null && line.contains(MetadataName.TIMESTAMP)) {
        String ts = extractFooter(toFooterWithDelimiter(MetadataName.TIMESTAMP), line);
        try {
          metadata.timestamp = Timestamp.from(MailUtil.rfcDateformatter.parse(ts, Instant::from));
        } catch (DateTimeParseException e) {
          log.error("Mail: Error while parsing timestamp from footer of message " + m.id(), e);
        }
      } else if (metadata.messageType == null && line.contains(MetadataName.MESSAGE_TYPE)) {
        metadata.messageType =
            extractFooter(toFooterWithDelimiter(MetadataName.MESSAGE_TYPE), line);
      }
    }
  }

  private static String extractFooter(String key, String line) {
    return line.substring(line.indexOf(key) + key.length(), line.length()).trim();
  }
}