Home | History | Annotate | Download | only in mail
      1 /*
      2  * Copyright (C) 2008 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.android.email.mail;
     18 
     19 import com.android.email.Utility;
     20 
     21 import org.apache.james.mime4j.codec.EncoderUtil;
     22 import org.apache.james.mime4j.decoder.DecoderUtil;
     23 
     24 import android.text.TextUtils;
     25 import android.text.util.Rfc822Token;
     26 import android.text.util.Rfc822Tokenizer;
     27 
     28 import java.io.UnsupportedEncodingException;
     29 import java.net.URLEncoder;
     30 import java.util.ArrayList;
     31 import java.util.regex.Pattern;
     32 
     33 /**
     34  * This class represent email address.
     35  *
     36  * RFC822 email address may have following format.
     37  *   "name" <address> (comment)
     38  *   "name" <address>
     39  *   name <address>
     40  *   address
     41  * Name and comment part should be MIME/base64 encoded in header if necessary.
     42  *
     43  */
     44 public class Address {
     45     /**
     46      *  Address part, in the form local_part@domain_part. No surrounding angle brackets.
     47      */
     48     String mAddress;
     49 
     50     /**
     51      * Name part. No surrounding double quote, and no MIME/base64 encoding.
     52      * This must be null if Address has no name part.
     53      */
     54     String mPersonal;
     55 
     56     // Regex that matches address surrounded by '<>' optionally. '^<?([^>]+)>?$'
     57     private static final Pattern REMOVE_OPTIONAL_BRACKET = Pattern.compile("^<?([^>]+)>?$");
     58     // Regex that matches personal name surrounded by '""' optionally. '^"?([^"]+)"?$'
     59     private static final Pattern REMOVE_OPTIONAL_DQUOTE = Pattern.compile("^\"?([^\"]*)\"?$");
     60     // Regex that matches escaped character '\\([\\"])'
     61     private static final Pattern UNQUOTE = Pattern.compile("\\\\([\\\\\"])");
     62 
     63     private static final Address[] EMPTY_ADDRESS_ARRAY = new Address[0];
     64 
     65     // delimiters are chars that do not appear in an email address, used by pack/unpack
     66     private static final char LIST_DELIMITER_EMAIL = '\1';
     67     private static final char LIST_DELIMITER_PERSONAL = '\2';
     68 
     69     public Address(String address, String personal) {
     70         setAddress(address);
     71         setPersonal(personal);
     72     }
     73 
     74     public Address(String address) {
     75         setAddress(address);
     76     }
     77 
     78     public String getAddress() {
     79         return mAddress;
     80     }
     81 
     82     public void setAddress(String address) {
     83         this.mAddress = REMOVE_OPTIONAL_BRACKET.matcher(address).replaceAll("$1");;
     84     }
     85 
     86     /**
     87      * Get name part as UTF-16 string. No surrounding double quote, and no MIME/base64 encoding.
     88      *
     89      * @return Name part of email address. Returns null if it is omitted.
     90      */
     91     public String getPersonal() {
     92         return mPersonal;
     93     }
     94 
     95     /**
     96      * Set name part from UTF-16 string. Optional surrounding double quote will be removed.
     97      * It will be also unquoted and MIME/base64 decoded.
     98      *
     99      * @param Personal name part of email address as UTF-16 string. Null is acceptable.
    100      */
    101     public void setPersonal(String personal) {
    102         if (personal != null) {
    103             personal = REMOVE_OPTIONAL_DQUOTE.matcher(personal).replaceAll("$1");
    104             personal = UNQUOTE.matcher(personal).replaceAll("$1");
    105             personal = DecoderUtil.decodeEncodedWords(personal);
    106             if (personal.length() == 0) {
    107                 personal = null;
    108             }
    109         }
    110         this.mPersonal = personal;
    111     }
    112 
    113     /**
    114      * This method is used to check that all the addresses that the user
    115      * entered in a list (e.g. To:) are valid, so that none is dropped.
    116      */
    117     public static boolean isAllValid(String addressList) {
    118         // This code mimics the parse() method below.
    119         // I don't know how to better avoid the code-duplication.
    120         if (addressList != null && addressList.length() > 0) {
    121             Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressList);
    122             for (int i = 0, length = tokens.length; i < length; ++i) {
    123                 Rfc822Token token = tokens[i];
    124                 String address = token.getAddress();
    125                 if (!TextUtils.isEmpty(address) && !isValidAddress(address)) {
    126                     return false;
    127                 }
    128             }
    129         }
    130         return true;
    131     }
    132 
    133     /**
    134      * Parse a comma-delimited list of addresses in RFC822 format and return an
    135      * array of Address objects.
    136      *
    137      * @param addressList Address list in comma-delimited string.
    138      * @return An array of 0 or more Addresses.
    139      */
    140     public static Address[] parse(String addressList) {
    141         if (addressList == null || addressList.length() == 0) {
    142             return EMPTY_ADDRESS_ARRAY;
    143         }
    144         Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressList);
    145         ArrayList<Address> addresses = new ArrayList<Address>();
    146         for (int i = 0, length = tokens.length; i < length; ++i) {
    147             Rfc822Token token = tokens[i];
    148             String address = token.getAddress();
    149             if (!TextUtils.isEmpty(address)) {
    150                 if (isValidAddress(address)) {
    151                     String name = token.getName();
    152                     if (TextUtils.isEmpty(name)) {
    153                         name = null;
    154                     }
    155                     addresses.add(new Address(address, name));
    156                 }
    157             }
    158         }
    159         return addresses.toArray(new Address[] {});
    160     }
    161 
    162     /**
    163      * Checks whether a string email address is valid.
    164      * E.g. name (at) domain.com is valid.
    165      */
    166     /* package */ static boolean isValidAddress(String address) {
    167         // Note: Some email provider may violate the standard, so here we only check that
    168         // address consists of two part that are separated by '@', and domain part contains
    169         // at least one '.'.
    170         int len = address.length();
    171         int firstAt = address.indexOf('@');
    172         int lastAt = address.lastIndexOf('@');
    173         int firstDot = address.indexOf('.', lastAt + 1);
    174         int lastDot = address.lastIndexOf('.');
    175         return firstAt > 0 && firstAt == lastAt && lastAt + 1 < firstDot
    176             && firstDot <= lastDot && lastDot < len - 1;
    177     }
    178 
    179     @Override
    180     public boolean equals(Object o) {
    181         if (o instanceof Address) {
    182             // It seems that the spec says that the "user" part is case-sensitive,
    183             // while the domain part in case-insesitive.
    184             // So foo (at) yahoo.com and Foo (at) yahoo.com are different.
    185             // This may seem non-intuitive from the user POV, so we
    186             // may re-consider it if it creates UI trouble.
    187             // A problem case is "replyAll" sending to both
    188             // a (at) b.c and to A (at) b.c, which turn out to be the same on the server.
    189             // Leave unchanged for now (i.e. case-sensitive).
    190             return getAddress().equals(((Address) o).getAddress());
    191         }
    192         return super.equals(o);
    193     }
    194 
    195     /**
    196      * Get human readable address string.
    197      * Do not use this for email header.
    198      *
    199      * @return Human readable address string.  Not quoted and not encoded.
    200      */
    201     public String toString() {
    202         if (mPersonal != null) {
    203             if (mPersonal.matches(".*[\\(\\)<>@,;:\\\\\".\\[\\]].*")) {
    204                 return Utility.quoteString(mPersonal) + " <" + mAddress + ">";
    205             } else {
    206                 return mPersonal + " <" + mAddress + ">";
    207             }
    208         } else {
    209             return mAddress;
    210         }
    211     }
    212 
    213     /**
    214      * Get human readable comma-delimited address string.
    215      *
    216      * @param addresses Address array
    217      * @return Human readable comma-delimited address string.
    218      */
    219     public static String toString(Address[] addresses) {
    220         if (addresses == null || addresses.length == 0) {
    221             return null;
    222         }
    223         if (addresses.length == 1) {
    224             return addresses[0].toString();
    225         }
    226         StringBuffer sb = new StringBuffer(addresses[0].toString());
    227         for (int i = 1; i < addresses.length; i++) {
    228             sb.append(',');
    229             sb.append(addresses[i].toString());
    230         }
    231         return sb.toString();
    232     }
    233 
    234     /**
    235      * Get RFC822/MIME compatible address string.
    236      *
    237      * @return RFC822/MIME compatible address string.
    238      * It may be surrounded by double quote or quoted and MIME/base64 encoded if necessary.
    239      */
    240     public String toHeader() {
    241         if (mPersonal != null) {
    242             return EncoderUtil.encodeAddressDisplayName(mPersonal) + " <" + mAddress + ">";
    243         } else {
    244             return mAddress;
    245         }
    246     }
    247 
    248     /**
    249      * Get RFC822/MIME compatible comma-delimited address string.
    250      *
    251      * @param addresses Address array
    252      * @return RFC822/MIME compatible comma-delimited address string.
    253      * it may be surrounded by double quoted or quoted and MIME/base64 encoded if necessary.
    254      */
    255     public static String toHeader(Address[] addresses) {
    256         if (addresses == null || addresses.length == 0) {
    257             return null;
    258         }
    259         if (addresses.length == 1) {
    260             return addresses[0].toHeader();
    261         }
    262         StringBuffer sb = new StringBuffer(addresses[0].toHeader());
    263         for (int i = 1; i < addresses.length; i++) {
    264             // We need space character to be able to fold line.
    265             sb.append(", ");
    266             sb.append(addresses[i].toHeader());
    267         }
    268         return sb.toString();
    269     }
    270 
    271     /**
    272      * Get Human friendly address string.
    273      *
    274      * @return the personal part of this Address, or the address part if the
    275      * personal part is not available
    276      */
    277     public String toFriendly() {
    278         if (mPersonal != null && mPersonal.length() > 0) {
    279             return mPersonal;
    280         } else {
    281             return mAddress;
    282         }
    283     }
    284 
    285     /**
    286      * Creates a comma-delimited list of addresses in the "friendly" format (see toFriendly() for
    287      * details on the per-address conversion).
    288      *
    289      * @param addresses Array of Address[] values
    290      * @return A comma-delimited string listing all of the addresses supplied.  Null if source
    291      * was null or empty.
    292      */
    293     public static String toFriendly(Address[] addresses) {
    294         if (addresses == null || addresses.length == 0) {
    295             return null;
    296         }
    297         if (addresses.length == 1) {
    298             return addresses[0].toFriendly();
    299         }
    300         StringBuffer sb = new StringBuffer(addresses[0].toFriendly());
    301         for (int i = 1; i < addresses.length; i++) {
    302             sb.append(',');
    303             sb.append(addresses[i].toFriendly());
    304         }
    305         return sb.toString();
    306     }
    307 
    308     /**
    309      * Returns exactly the same result as Address.toString(Address.unpack(packedList)).
    310      */
    311     public static String unpackToString(String packedList) {
    312         return toString(unpack(packedList));
    313     }
    314 
    315     /**
    316      * Returns exactly the same result as Address.pack(Address.parse(textList)).
    317      */
    318     public static String parseAndPack(String textList) {
    319         return Address.pack(Address.parse(textList));
    320     }
    321 
    322     /**
    323      * Returns null if the packedList has 0 addresses, otherwise returns the first address.
    324      * The same as Address.unpack(packedList)[0] for non-empty list.
    325      * This is an utility method that offers some performance optimization opportunities.
    326      */
    327     public static Address unpackFirst(String packedList) {
    328         Address[] array = unpack(packedList);
    329         return array.length > 0 ? array[0] : null;
    330     }
    331 
    332     /**
    333      * Convert a packed list of addresses to a form suitable for use in an RFC822 header.
    334      * This implementation is brute-force, and could be replaced with a more efficient version
    335      * if desired.
    336      */
    337     public static String packedToHeader(String packedList) {
    338         return toHeader(unpack(packedList));
    339     }
    340 
    341     /**
    342      * Unpacks an address list previously packed with pack()
    343      * @param addressList String with packed addresses as returned by pack()
    344      * @return array of addresses resulting from unpack
    345      */
    346     public static Address[] unpack(String addressList) {
    347         if (addressList == null || addressList.length() == 0) {
    348             return EMPTY_ADDRESS_ARRAY;
    349         }
    350         ArrayList<Address> addresses = new ArrayList<Address>();
    351         int length = addressList.length();
    352         int pairStartIndex = 0;
    353         int pairEndIndex = 0;
    354 
    355         /* addressEndIndex is only re-scanned (indexOf()) when a LIST_DELIMITER_PERSONAL
    356            is used, not for every email address; i.e. not for every iteration of the while().
    357            This reduces the theoretical complexity from quadratic to linear,
    358            and provides some speed-up in practice by removing redundant scans of the string.
    359         */
    360         int addressEndIndex = addressList.indexOf(LIST_DELIMITER_PERSONAL);
    361 
    362         while (pairStartIndex < length) {
    363             pairEndIndex = addressList.indexOf(LIST_DELIMITER_EMAIL, pairStartIndex);
    364             if (pairEndIndex == -1) {
    365                 pairEndIndex = length;
    366             }
    367             Address address;
    368             if (addressEndIndex == -1 || pairEndIndex <= addressEndIndex) {
    369                 // in this case the DELIMITER_PERSONAL is in a future pair,
    370                 // so don't use personal, and don't update addressEndIndex
    371                 address = new Address(addressList.substring(pairStartIndex, pairEndIndex), null);
    372             } else {
    373                 address = new Address(addressList.substring(pairStartIndex, addressEndIndex),
    374                                       addressList.substring(addressEndIndex + 1, pairEndIndex));
    375                 // only update addressEndIndex when we use the LIST_DELIMITER_PERSONAL
    376                 addressEndIndex = addressList.indexOf(LIST_DELIMITER_PERSONAL, pairEndIndex + 1);
    377             }
    378             addresses.add(address);
    379             pairStartIndex = pairEndIndex + 1;
    380         }
    381         return addresses.toArray(EMPTY_ADDRESS_ARRAY);
    382     }
    383 
    384     /**
    385      * Packs an address list into a String that is very quick to read
    386      * and parse. Packed lists can be unpacked with unpack().
    387      * The format is a series of packed addresses separated by LIST_DELIMITER_EMAIL.
    388      * Each address is packed as
    389      * a pair of address and personal separated by LIST_DELIMITER_PERSONAL,
    390      * where the personal and delimiter are optional.
    391      * E.g. "foo (at) x.com\1joe (at) x.com\2Joe Doe"
    392      * @param addresses Array of addresses
    393      * @return a string containing the packed addresses.
    394      */
    395     public static String pack(Address[] addresses) {
    396         // TODO: return same value for both null & empty list
    397         if (addresses == null) {
    398             return null;
    399         }
    400         final int nAddr = addresses.length;
    401         if (nAddr == 0) {
    402             return "";
    403         }
    404 
    405         // shortcut: one email with no displayName
    406         if (nAddr == 1 && addresses[0].getPersonal() == null) {
    407             return addresses[0].getAddress();
    408         }
    409 
    410         StringBuffer sb = new StringBuffer();
    411         for (int i = 0; i < nAddr; i++) {
    412             if (i != 0) {
    413                 sb.append(LIST_DELIMITER_EMAIL);
    414             }
    415             final Address address = addresses[i];
    416             sb.append(address.getAddress());
    417             final String displayName = address.getPersonal();
    418             if (displayName != null) {
    419                 sb.append(LIST_DELIMITER_PERSONAL);
    420                 sb.append(displayName);
    421             }
    422         }
    423         return sb.toString();
    424     }
    425 
    426     /**
    427      * Produces the same result as pack(array), but only packs one (this) address.
    428      */
    429     public String pack() {
    430         final String address = getAddress();
    431         final String personal = getPersonal();
    432         if (personal == null) {
    433             return address;
    434         } else {
    435             return address + LIST_DELIMITER_PERSONAL + personal;
    436         }
    437     }
    438 
    439     /**
    440      * Legacy unpack() used for reading the old data (migration),
    441      * as found in LocalStore (Donut; db version up to 24).
    442      * @See unpack()
    443      */
    444     public static Address[] legacyUnpack(String addressList) {
    445         if (addressList == null || addressList.length() == 0) {
    446             return new Address[] { };
    447         }
    448         ArrayList<Address> addresses = new ArrayList<Address>();
    449         int length = addressList.length();
    450         int pairStartIndex = 0;
    451         int pairEndIndex = 0;
    452         int addressEndIndex = 0;
    453         while (pairStartIndex < length) {
    454             pairEndIndex = addressList.indexOf(',', pairStartIndex);
    455             if (pairEndIndex == -1) {
    456                 pairEndIndex = length;
    457             }
    458             addressEndIndex = addressList.indexOf(';', pairStartIndex);
    459             String address = null;
    460             String personal = null;
    461             if (addressEndIndex == -1 || addressEndIndex > pairEndIndex) {
    462                 address =
    463                     Utility.fastUrlDecode(addressList.substring(pairStartIndex, pairEndIndex));
    464             }
    465             else {
    466                 address =
    467                     Utility.fastUrlDecode(addressList.substring(pairStartIndex, addressEndIndex));
    468                 personal =
    469                     Utility.fastUrlDecode(addressList.substring(addressEndIndex + 1, pairEndIndex));
    470             }
    471             addresses.add(new Address(address, personal));
    472             pairStartIndex = pairEndIndex + 1;
    473         }
    474         return addresses.toArray(new Address[] { });
    475     }
    476 
    477     /**
    478      * Legacy pack() used for writing to old data (migration),
    479      * as found in LocalStore (Donut; db version up to 24).
    480      * @See unpack()
    481      */
    482     public static String legacyPack(Address[] addresses) {
    483         if (addresses == null) {
    484             return null;
    485         } else if (addresses.length == 0) {
    486             return "";
    487         }
    488         StringBuffer sb = new StringBuffer();
    489         for (int i = 0, count = addresses.length; i < count; i++) {
    490             Address address = addresses[i];
    491             try {
    492                 sb.append(URLEncoder.encode(address.getAddress(), "UTF-8"));
    493                 if (address.getPersonal() != null) {
    494                     sb.append(';');
    495                     sb.append(URLEncoder.encode(address.getPersonal(), "UTF-8"));
    496                 }
    497                 if (i < count - 1) {
    498                     sb.append(',');
    499                 }
    500             }
    501             catch (UnsupportedEncodingException uee) {
    502                 return null;
    503             }
    504         }
    505         return sb.toString();
    506     }
    507 }
    508