Tizen 2.1 base
[platform/framework/web/wrt-plugins-common.git] / src / modules / tizen / Messaging / EmailUtils.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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  * @author          Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
18  */
19 #include <sstream>
20 #include <pcrecpp.h>
21
22 #include <Commons/Exception.h>
23 #include <Commons/StringBuilder.h>
24 #include <Commons/StringUtils.h>
25 #include "EmailUtils.h"
26
27 namespace {
28 const char* EMAIL_ADDRESS_REGEX =
29     "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}";
30
31 using WrtDeviceApis::Commons::StringBuilder;
32
33 const std::string EMAIL_ADDRESS_REGEX_GROUP =
34     StringBuilder()
35         .append("(")
36         .append(EMAIL_ADDRESS_REGEX)
37         .append(")")
38         .toString();
39 }
40
41 namespace WrtDeviceApis {
42 namespace Messaging {
43 namespace EmailUtils {
44 std::string formatAddress(const std::string& address,
45         const std::string& name)
46 {
47     if (address.empty()) {
48         ThrowMsg(Commons::PlatformException, "Address is empty.");
49     }
50
51     std::stringstream ss;
52     if (!name.empty()) {
53         ss << "\"" << name << "\" ";
54     }
55     ss << "<" << address << ">";
56
57     return ss.str();
58 }
59
60 std::string formatAddressLine(const Api::Recipients& recipients)
61 {
62     std::string result;
63     for (size_t i = 0; i < recipients.getRecipientSize(); ++i) {
64         result += formatAddress(recipients.getRecipient(i)) + ";";
65     }
66     return result;
67 }
68
69 std::string stripAddress(const std::string& address)
70 {
71     std::string result;
72     pcrecpp::RE re(EMAIL_ADDRESS_REGEX_GROUP);
73     if (!re.PartialMatch(address, &result)) {
74         ThrowMsg(Commons::PlatformException, "Couldn't discover email address");
75     }
76     return result;
77 }
78
79 Api::Recipients stripAddressLine(const std::string& addressLine)
80 {
81     typedef std::vector<std::string> Addresses;
82
83     Api::Recipients result;
84     Addresses addresses = Commons::String::split(addressLine, ';');
85     for (Addresses::iterator it = addresses.begin();
86          it != addresses.end();
87          ++it) {
88         result.appendRecipient(stripAddress(*it));
89     }
90     return result;
91 }
92 }
93 }
94 }