Update change log and spec for wrt-plugins-tizen_0.4.59
[framework/web/wrt-plugins-tizen.git] / src / Messaging / Email.cpp
1 //
2 // Tizen Web Device API
3 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
4 //
5 // Licensed under the Apache License, Version 2.0 (the License);
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 // http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 //
17
18 #include <unistd.h>
19 #include <cstdio>
20 #include <cstddef>
21 #include <cstdlib>
22 #include <ctime>
23 #include <email-types.h>
24 #include <email-api.h>
25 #include <dpl/scoped_fclose.h>
26 #include <dpl/scoped_ptr.h>
27 #include <Commons/Exception.h>
28 #include <Commons/StringUtils.h>
29 #include "MessageFactory.h"
30 #include "Messaging.h"
31 #include "Email.h"
32 #include "EmailService.h"
33 #include "EmailUtils.h"
34 #include "EmailConverter.h"
35 #include "MailSender.h"
36 #include "MailSync.h"
37 #include "MessagingService.h"
38 #include "MessagingServiceManager.h"
39 #include "Attachment.h"
40 #include <Logger.h>
41
42 #define LOG_ENTER LoggerD("---> ENTER");
43 #define LOG_EXIT LoggerD("---> EXIT");
44
45 using namespace std;
46 using namespace WrtDeviceApis::Commons;
47
48 namespace DeviceAPI {
49 namespace Messaging {
50
51 namespace {
52 const char* COMMAND_NAME = "/bin/cp";
53 const char* COMMAND_SWITCH_RECURSIVE = "-r";
54 //const char* COMMAND_SWITCH_FORCE = "-f";
55 }
56
57 Email::Email(const string& id) :
58         IMessage(EMAIL, id) {
59         LOG_ENTER
60
61         try {
62                 if (getIdRef().empty()) {
63                         //exception
64                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, " message id is invalid");
65                 }
66
67                 reload();
68         } catch (const WrtDeviceApis::Commons::PlatformException& ex) {
69                 LoggerE("Exception: " << ex.DumpToString());
70         }
71
72         LOG_EXIT
73 }
74
75 Email::Email(const std::string& id, int accountId) :
76         IMessage(EMAIL, id)
77 {
78         LOG_ENTER
79
80         try {
81                 if (getIdRef().empty()) {
82                         //exception
83                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, " message id is invalid");
84                 }
85
86                 LoggerD("Account ID = " << accountId);
87                 m_accountId = accountId;
88                 reload();
89
90         } catch (const WrtDeviceApis::Commons::PlatformException& ex) {
91                 LoggerE("Exception: " << ex.DumpToString());
92         }
93
94
95         LOG_EXIT
96 }
97
98 Email::Email(EmailAccountInfo& account) : IMessage(EMAIL)
99 {
100     LOG_ENTER
101
102     try {
103          if (getIdRef().empty()) {
104                 create(account);
105          }
106
107         reload();
108     }
109     catch (const WrtDeviceApis::Commons::PlatformException& ex) {
110         LoggerE("Exception: " << ex.DumpToString());
111     }
112
113     LOG_EXIT
114 }
115
116 Email::Email(const FolderType folder) : IMessage(EMAIL)
117 {
118     LOG_ENTER
119
120     try {
121          if (folder == TEMP_FOLDER) {
122                 create();
123          }
124            else {
125               ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Folder Type is miss-matched");
126            }
127     }
128     catch (const WrtDeviceApis::Commons::PlatformException& ex) {
129         LoggerE("Exception: " << ex.DumpToString());
130     }
131
132     LOG_EXIT
133 }
134
135 Email::~Email()
136 {
137     LoggerD("ENTER");
138 }
139
140 int Email::send()
141 {
142     LOG_ENTER
143
144 //    update();
145
146     int handle = MailSender::getInstance().send(
147         MessageFactory::convertToEmail(SharedFromThis())
148         );
149
150     return handle;
151     LOG_EXIT
152 }
153
154 void Email::sendCancel(int handle)
155 {
156     LOG_ENTER
157
158     MailSender::getInstance().cancel(handle);
159
160     LOG_EXIT
161 }
162
163 int Email::downloadBody()
164 {
165         LOG_ENTER
166         return MailSync::getInstance().downloadBody( MessageFactory::convertToEmail(SharedFromThis()) );
167         LOG_EXIT
168 }
169
170 void Email::downloadBodyCancel( int handle)
171 {
172         return MailSync::getInstance().cancelDownloadBody(handle);
173 }
174
175 int Email::downloadAttachment( const IAttachmentPtr& attachment)
176 {
177         LOG_ENTER
178         return MailSync::getInstance().downloadAttachment( MessageFactory::convertToEmail(SharedFromThis()), attachment );
179         LOG_EXIT
180 }
181
182 void Email::downloadAttachmentCancel( int handle)
183 {
184         LOG_ENTER
185         return MailSync::getInstance().cancelDownloadAttachment(handle);
186         LOG_EXIT
187 }
188
189 void Email::update(bool draftsOnly)
190 {
191     LOG_ENTER
192
193     DPL::Mutex::ScopedLock mx(&m_updateMutex);
194
195     if (!m_mail) {
196         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL.");
197     }
198
199     updateSubject();
200     updateBody();
201     updateRecipients();
202     updateAttachments();
203     updateReadStatus();
204
205     email_attachment_data_t* attachment=NULL;
206     int attachmentCount = 0;
207     int error = email_get_attachment_data_list( m_mail->mail_id, &attachment, &attachmentCount);
208     if (EMAIL_ERROR_NONE != error) {
209           LoggerW("Nothing to update or error. [" << error << "]");
210     }
211
212     error = email_update_mail( m_mail.Get(), attachment, attachmentCount, NULL, 0);
213     if (EMAIL_ERROR_NONE != error) {
214           LoggerW("Nothing to update or error. [" << error << "]");
215     }
216
217     if (attachment)
218     {
219             error = email_free_attachment_data(&attachment, attachmentCount);
220             if (EMAIL_ERROR_NONE != error) {
221                   LoggerW("Nothing to update or error. [" << error << "]");
222             }
223     }
224
225     LOG_EXIT
226 }
227
228 int Email::getAccountID()
229 {
230         LOG_ENTER
231
232         if ( m_mail )
233                 return m_mail->account_id;
234         else
235                 return -1;
236
237         LOG_EXIT
238 }
239
240 int Email::getUID()
241 {
242         LOG_ENTER
243
244         if (m_mail)
245                 return m_mail->mail_id;
246         else
247                 return -1;
248
249         LOG_EXIT
250 }
251
252 int Email::isBodyDownloaded()
253 {
254
255         if (m_mail)
256                 if ( m_mail->body_download_status == 1 )        // 1 is fully downloaded body.
257                         return true;
258                 else
259                         return false;
260         else
261                 return false;
262
263 }
264
265 bool Email::hasAttachment()
266 {
267         std::size_t attachmentSize = getAttachmentsCount();
268         if ( attachmentSize > 0)
269                         return true;
270                 else
271                         return false;
272 }
273
274 void Email::readAllData()
275 {
276     reload();
277 }
278
279 void Email::moveToFolder(const FolderType newFolder)
280 {
281 /*
282
283     LOG_ENTER
284     moveToFolder(EmailConverter::toMailboxType(newFolder));
285     LOG_EXIT
286 */
287 }
288
289 void Email::moveToFolder(const string& newFolder)
290 {
291 /*
292         Assert(m_mail && "mail is NULL.");
293
294         update();
295
296         int accountId = m_mail->account_id;
297         int mailId = getIntId();
298
299         emf_mailbox_t* mailbox = EmailService::alloc<emf_mailbox_t>();
300         mailbox->account_id = accountId;
301         mailbox->name = (NULL != newFolder.c_str() ? strdup(newFolder.c_str()) : NULL);
302
303         int error = email_move_mail_to_mailbox(&mailId, 1, mailbox);
304         if (EMF_ERROR_NONE != error) {
305         ThrowMsg(
306             WrtDeviceApis::Commons::PlatformException,
307             "Couldn't move mail to folder: " << newFolder << ". [" <<
308             error << "]");
309         }
310
311         error = email_free_mailbox(&mailbox, 1);        //free
312         if (EMF_ERROR_NONE != error) {
313             LoggerE("Failed to destroy mailbox: " << error);
314         }
315 */
316 }
317
318 void Email::copyToFolder(const FolderType newFolder)
319 {
320     LOG_ENTER
321
322     copyToFolder(EmailConverter::toMailboxName(newFolder));
323
324     LOG_EXIT
325 }
326
327 void Email::copyToFolder(const string& newFolder)
328 {
329         LOG_ENTER
330 /*
331         Assert(m_mail && "mail is NULL.");
332
333         update();
334
335         int accountId = m_mail->account_id;
336         ScopedMail mail(EmailService::cloneMail(m_mail.Get())); //clone
337         mail->mailbox_name = (NULL != newFolder.c_str() ? strdup(newFolder.c_str()) : NULL);
338         mail->account_id = accountId;
339
340         //Attachment
341         email_attachment_data_t* attachment = NULL;
342         int attachmentCount = 0;
343         int error = email_get_attachment_data_list( m_mail->mail_id, &attachment, &attachmentCount);    //get Attachment list
344         if (EMAIL_ERROR_NONE != error) {
345                 ThrowMsg( WrtDeviceApis::Commons::PlatformException,
346                         "Couldn't get attachment list: " << newFolder << ". [" << error << "]");
347         }
348
349         int mailId = EmailService::addMail( mail.Get(), attachment );
350         if (0 == mailId) {
351             ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Cloned mail didn't get new id.");
352         }
353 */
354     LOG_EXIT
355 }
356
357 void Email::remove()
358 {
359     EmailService::deleteMail(m_accountId, getIntId());
360 }
361
362 #if 0
363 void Email::create()
364 {
365     LOG_ENTER
366
367     EmailAccountInfo account = IMessaging::getInstance().getCurrentEmailAccount();
368     m_accountId = account.getIntId();
369     ScopedMail mail(EmailService::createMail(account));
370     ScopedMailbox mailbox(
371         EmailService::getMailboxByType(account.getIntId(),
372                                        EMAIL_MAILBOX_TYPE_DRAFT)
373         );
374     setId(convertId(EmailService::addMailToMailbox(mail.Get(), mailbox.Get())));
375     setFolderType(DRAFTBOX);
376     setMessageStatus(MESSAGE_STATUS_DRAFT);
377
378     LOG_EXIT
379 }
380 #endif
381
382 void Email::create()
383 {
384     LOG_ENTER
385     setFolderType(TEMP_FOLDER);
386     setMessageStatus(MESSAGE_STATUS_CREATED);
387     LOG_EXIT
388 }
389
390 void Email::create( EmailAccountInfo& account )
391 {
392         LOG_ENTER
393
394         m_accountId = account.getIntId();
395         //MailSender::getInstance();
396
397         LoggerD("account ID : " << m_accountId);
398         ScopedMail mail(EmailService::createMailData(account));
399
400         setEmailAccount(account);       //save account
401
402         mail->mailbox_type = EMAIL_MAILBOX_TYPE_DRAFT;
403
404         setId(convertId(EmailService::addMail(mail.Get(), NULL)));
405         setFolderType(DRAFTBOX);
406         setMessageStatus(MESSAGE_STATUS_DRAFT);
407
408     LOG_EXIT
409 }
410
411 void Email::reload()
412 {
413     LOG_ENTER
414
415     LoggerD("mail ID :" << getIntId());
416     m_mail.Reset(EmailService::readMail(getIntId()));           //reset Mail Data
417
418     readHeader();
419     readBody();
420     readInfo();
421
422     //if (m_mail->head) { readHeader(); }
423     //if (m_mail->body) { readBody(); }
424     //if (m_mail->info) { readInfo(); }
425
426     //m_mailbox.Reset(EmailService::getMailboxByMailId(m_accountId, getIntId()) );
427     //setFolderType(EmailConverter::toFolderType(m_mailbox->mailbox_type));
428
429     setFolderType(EmailConverter::toFolderType(m_mail->mailbox_type));
430     setMessageStatus(EmailConverter::toMessageStatus(m_mail->mailbox_type));
431
432     LOG_EXIT
433 }
434
435 void Email::readHeader()
436 {
437     LOG_ENTER
438
439     if (!m_mail) {
440         LoggerE("Header is NULL");
441         Throw(WrtDeviceApis::Commons::PlatformException);
442     }
443
444     if (m_mail->subject) {
445         setSubject(m_mail->subject);
446     }
447
448     if (m_mail->full_address_to) {
449         appendToRecipients(EmailUtils::stripAddressLine(m_mail->full_address_to));
450     }
451
452     if (m_mail->full_address_cc) {
453         appendCcRecipients(EmailUtils::stripAddressLine(m_mail->full_address_cc));
454     }
455
456     if (m_mail->full_address_bcc) {
457         appendBccRecipients(EmailUtils::stripAddressLine(m_mail->full_address_bcc));
458     }
459
460 #if 1
461     LoggerD(" " << m_mail->date_time);
462     tm* time = localtime(&m_mail->date_time);
463     if (!time) {
464         LoggerE("localtime failed");
465         Throw(WrtDeviceApis::Commons::PlatformException);
466     }
467     setDateTime(*time);
468 #else
469
470         if (m_mail->datetime[0] != '\0')
471         {
472                 char buf[MAX_DATETIME_STRING_LENGTH];
473                 char *targetBuf = m_mail->datetime;
474                 struct tm timeinfo;
475
476                 memset(buf, 0x00, sizeof(buf));
477                 targetBuf += snprintf(buf, sizeof(buf), "%.4s", targetBuf);
478                 timeinfo.tm_year = atoi(buf) - 1900;
479
480                 memset(buf, 0x00, sizeof(buf));
481                 targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf);
482                 timeinfo.tm_mon =  atoi(buf) - 1;
483
484                 memset(buf, 0x00, sizeof(buf));
485                 targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf);
486                 timeinfo.tm_mday =      atoi(buf);
487
488                 memset(buf, 0x00, sizeof(buf));
489                 targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf);
490                 timeinfo.tm_hour = atoi(buf);
491
492                 memset(buf, 0x00, sizeof(buf));
493                 targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf);
494                 timeinfo.tm_min = atoi(buf);
495
496                 memset(buf, 0x00, sizeof(buf));
497                 targetBuf += snprintf(buf, sizeof(buf), "%.2s", targetBuf);
498                 timeinfo.tm_sec = atoi(buf);
499
500                 setDateTime(timeinfo);
501         }
502
503 #endif
504
505 #if 0
506     time_t rawtime;
507     time(&rawtime);
508     struct tm tmpTime = *(localtime(&rawtime));
509
510     tmpTime.tm_year = m_mail->head->datetime.year;
511     tmpTime.tm_mon = m_mail->head->datetime.month;
512     tmpTime.tm_mday = m_mail->head->datetime.day;
513     tmpTime.tm_hour = m_mail->head->datetime.hour;
514     tmpTime.tm_min = m_mail->head->datetime.minute;
515     tmpTime.tm_sec = m_mail->head->datetime.second;
516     mktime(&tmpTime);
517     setDateTime(tmpTime);
518 #endif
519
520     if (m_mail->full_address_from) {
521         Recipients from;
522         from.setRecipients(EmailUtils::stripAddress(m_mail->full_address_from));
523         setSourceAddress(from);
524         setSourceAddressValidity(true); //not needed to update in platform
525         setFrom(EmailUtils::stripAddress(m_mail->full_address_from));
526         setFromValidity(true);
527     }
528
529     LOG_EXIT
530 }
531
532 void Email::readBody() {
533         LOG_ENTER
534
535     if (!m_mail) {
536         LoggerE("Body is NULL");
537         Throw(WrtDeviceApis::Commons::PlatformException);
538     }
539
540         if (m_mail->file_path_plain) {
541                 LoggerD("m_mail->file_path_plain : " << m_mail->file_path_plain);
542                 DPL::ScopedFClose file(::fopen(m_mail->file_path_plain, "r"));
543                 if (!file) {
544                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
545                                         "Cannot read body file: " << m_mail->file_path_plain);
546                 }
547                 fseek(file.Get(), 0, SEEK_END);
548                 long int size = ftell(file.Get());
549
550                 if (size < 0) {
551                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
552                                         "Cannot read plain body size");
553                 }
554
555                 fseek(file.Get(), 0, SEEK_SET);
556                 DPL::ScopedPtr<char> data(new char[size + 1]);
557                 memset(data.Get(), 0, size + 1);
558                 TEMP_FAILURE_RETRY(fread(data.Get(), 1, size, file.Get()) &&
559                                                         ferror(file.Get()) == 0 ? -1 : 0);
560                 setBody(data.Get());
561         }
562
563         //html body.
564         if (m_mail->file_path_html) {
565                 LoggerD("m_mail->file_path_html : " << m_mail->file_path_html);
566                 DPL::ScopedFClose file(::fopen(m_mail->file_path_html, "r")); //auto close, scopedFClose
567                 if (!file) {
568                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
569                                         "Cannot read html body file: " << m_mail->file_path_html);
570                 }
571
572                 fseek(file.Get(), 0, SEEK_END);
573                 long int size = ftell(file.Get());
574
575                 if (size < 0) {
576                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
577                                         "Cannot read html body size");
578                 }
579
580                 fseek(file.Get(), 0, SEEK_SET);
581                 DPL::ScopedPtr<char> data(new char[size + 1]);
582                 memset(data.Get(), 0, size + 1);
583         TEMP_FAILURE_RETRY(fread(data.Get(), 1, size, file.Get()) &&
584                            ferror(file.Get()) == 0 ? -1 : 0);
585                 setHtmlBody(data.Get()); //setHtmlBody declarate in Email Calss.
586         }
587
588         //Attachment
589         //email_attachment_info_t* attachment = NULL;
590         email_attachment_data_t* attachment = NULL;
591         int attachmentCount = 0;
592
593         int error = email_get_attachment_data_list( m_mail->mail_id, &attachment, &attachmentCount);    //get Attachment list
594         if (EMAIL_ERROR_NONE != error) {
595                 ThrowMsg( WrtDeviceApis::Commons::PlatformException, "Couldn't get attachment list: ");
596         }
597
598         if ( attachment && attachmentCount > 0)
599         {
600                 LoggerD("reading attachments , attahcment count = " << attachmentCount);
601                 int i = 0;
602
603                 for ( i = 0; i < attachmentCount; i++)
604                 {
605                         Try {
606                                 LoggerD("attachment ID : [" << attachment[i].attachment_id
607                         << "] name : [" << attachment[i].attachment_name
608                         << "] download : [" << attachment[i].save_status
609                         << "] savefile : [" << attachment[i].attachment_path
610                         << "] mimetype : [" << attachment[i].attachment_mime_type
611                         << "]");
612                                 LoggerD("attachment inline status : ["
613                         << attachment[i].inline_content_status << "]");
614                                 IAttachmentPtr tmpAtt(new Attachment());
615                                 if (attachment[i].attachment_path)
616                                         tmpAtt->init(attachment[i].attachment_path, false);
617
618                                 if (tmpAtt)
619                                 {
620                                         LoggerD("attachment[i].inline_content_status : ["
621                             << attachment[i].inline_content_status << "]");
622                                         tmpAtt->rename(std::string(attachment[i].attachment_name));
623                                         tmpAtt->setAttachmentID(attachment[i].attachment_id);
624                                         tmpAtt->setDownloaded(attachment[i].save_status);
625                                         tmpAtt->setIsInlineAttachment((bool)attachment[i].inline_content_status);
626                                         if(attachment[i].attachment_mime_type)
627                                         {
628                                                 tmpAtt->setMimeType(attachment[i].attachment_mime_type);
629                                         }
630                                         tmpAtt->setNth(i+1);
631                                         LoggerD(" setNth(i+1) : " << i+1);
632                                         if(attachment[i].inline_content_status == 0)
633                                         {
634                                         appendAttachment(tmpAtt);
635                                         }
636                                         else
637                                         {
638                                                 appendInlineAttachment(tmpAtt);
639                                         }
640                                 }
641                                 LoggerD(" append Attachment complete");
642
643
644                         }
645                         catch ( const WrtDeviceApis::Commons::Exception& ex )
646                         {
647                                 LoggerE("Error while trying to append attachment " << attachment[i].attachment_path << ": " << ex.DumpToString());
648                         }
649
650                 }
651
652         }
653
654         if (attachment)
655         {
656                 error = email_free_attachment_data(&attachment, attachmentCount);
657                 if (EMAIL_ERROR_NONE != error) {
658                         ThrowMsg( WrtDeviceApis::Commons::PlatformException, " attachment_data free error! ");
659                 }
660         }
661
662         LOG_EXIT
663 }
664
665 void Email::readInfo()
666 {
667         LOG_ENTER
668
669         if (!m_mail)
670         {
671                 LoggerD("m_mail is NULL");
672                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Info is NULL.");
673         }
674
675         setReadStatus(m_mail->flags_seen_field == 1);
676
677         m_accountId = m_mail->account_id;
678         setConvId(m_mail->thread_id);
679         setPriority( EmailConverter::toMessagePriority( m_mail->priority ) );
680         setSize(m_mail->mail_size);
681         setCurrentFolderId(m_mail->mailbox_id);
682
683         LOG_EXIT
684 }
685
686 void Email::updateBody()
687 {
688         LOG_ENTER
689
690         int error = 0;
691         bool locationChecker = false;
692
693         if (isBodyValid()) { return; }
694
695         if (!m_mail) {
696                 LoggerD("m_mail is NULL");
697                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL.");
698         }
699         if (!m_mail->file_path_plain) {
700                 LoggerD("file_path_plain is NULL");
701                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Plain Body is NULL.");
702         }
703
704         // For Plain Body
705         locationChecker = EmailUtils::isFrameworkEmailData(m_mail->file_path_plain);
706         if(locationChecker == true)     // already exist palin body file on email frame work, we can not update that file so make new temp file
707         {
708                 LoggerD("create new plain body");
709                 char buf[] = "XXXXXX";
710                 mode_t mask = umask(S_IWGRP | S_IWOTH);
711                 error = mkstemp(buf);
712                 umask(mask);
713                 std::string bodyFile = buf;
714                 bodyFile = EmailUtils::TMP_DIR_PREFIX+bodyFile;
715                 LoggerD("bodyFile : " << bodyFile);
716
717                 FILE* f = fopen(bodyFile.c_str(), "w");
718                 if (NULL != f) {
719                         fclose(f);
720                 }
721
722                 m_mail->file_path_plain = strdup(bodyFile.c_str());
723         }
724
725         FILE* f = fopen(m_mail->file_path_plain, "w");
726         if (NULL != f) {
727                 fwrite(getBodyRef().c_str(), strlen(getBodyRef().c_str()), 1, f);
728                 fclose(f);
729         }
730         else
731         {
732                 LoggerD("Plain Body file open fail : " << m_mail->file_path_plain);
733                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Plain Body File Open Error");
734         }
735
736         // For Html Body
737         locationChecker = EmailUtils::isFrameworkEmailData(m_mail->file_path_html);
738         if((locationChecker == true) || (!m_mail->file_path_html))      // html file is not exist or exist on email frame work then create tmp html file
739         {
740                 LoggerD("create new html body");
741                 char buf[] = "XXXXXX";
742                 mode_t mask = umask(S_IWGRP | S_IWOTH);
743                 error = mkstemp(buf);
744                 umask(mask);
745                 std::string htmlFile = buf;
746                 htmlFile = EmailUtils::TMP_DIR_PREFIX+htmlFile;
747                 LoggerD("htmlFile : " << htmlFile);
748
749                 FILE* f = fopen(htmlFile.c_str(), "w");
750                 if (NULL != f) {
751                         fclose(f);
752                 }
753                 m_mail->file_path_html = strdup(htmlFile.c_str());
754
755                 if(!m_mail->file_path_html)
756                 {
757                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Html Body file is NULL.");
758                 }
759         }
760
761         f = fopen(m_mail->file_path_html, "w");
762         if (NULL != f) {
763                 if(strlen(getHtmlBody().c_str()) > 0)   // check html data is exist if not exist copy plain body to html body
764                 {
765                         fwrite(getHtmlBody().c_str(), strlen(getHtmlBody().c_str()), 1, f);
766                 }
767                 else if(strlen(getBodyRef().c_str()) > 0)
768                 {
769                         // htmlbody is empty and plainBody exist. copy plainBody to htmlBody
770                         fwrite(getBodyRef().c_str(), strlen(getBodyRef().c_str()), 1, f);
771                 }
772                 else
773                 {
774                         // htmlBody is empty.
775                 }
776                 fclose(f);
777         }
778         else
779         {
780                 LoggerD("html Body file open fail : " << m_mail->file_path_html);
781                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "html Body File Open Error");
782         }
783
784         m_mail->body_download_status = 1;
785
786         setBodyValidity(true);
787
788         LOG_EXIT
789
790 }
791
792 void Email::updateSubject()
793 {
794     LOG_ENTER
795
796     if (isSubjectValid()) { return; }
797
798     LoggerD("update subject, msgId=" << getIdRef());
799
800     if (!m_mail) {
801         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail not allocated.");
802     }
803
804     m_mail->subject = String::strdup(getSubjectRef());
805     setSubjectValidity(true);
806
807     LOG_EXIT
808 }
809
810 void Email::updateReadStatus()
811 {
812     LOG_ENTER
813
814     if (isReadStatusValid()) { return; }
815
816     LoggerD("update read, msgId=" << getIdRef());
817
818     if (!m_mail) {
819         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail not allocated.");
820     }
821
822     m_mail->flags_seen_field = isRead();
823     setReadStatusValidity(true);
824
825     LOG_EXIT
826 }
827
828 void Email::updateIsRead()
829 {
830     LOG_ENTER
831     if (isReadChangeStatusValid()) {
832         // do not update if not changed
833         return;
834     }
835
836     EmailService::updateSeenFlag(getAccountID(), getIntId(), isReadChangeStatus());
837     setisReadChangeStatusValidity(true);
838     LOG_EXIT
839 }
840
841 void Email::updateMessage()
842 {
843         LOG_ENTER
844         email_meeting_request_t *meeting_req = NULL;
845
846         DPL::Mutex::ScopedLock mx(&m_updateMutex);
847
848         if (!m_mail) {
849                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL.");
850         }
851
852         LoggerD("getCurrentFolder() = " << getCurrentFolder() );
853         LoggerD("m_mail->mail_id = " << m_mail->mail_id );
854         LoggerD("m_mail->file_path_plain = " << m_mail->file_path_plain );
855         LoggerD("m_mail->file_path_html = " << m_mail->file_path_html );
856
857         if(getCurrentFolder() == DRAFTBOX)
858         {
859 //              updateBody();
860                 updateSubject();
861 //              updateRecipients();
862 //              updateFrom();
863 //              updateAttachments();
864                 updatePriority();
865         }
866         updateReadStatus();
867
868         //get attachment
869         email_attachment_data_t* attachment=NULL;
870         int attachmentCount = 0;
871         int error = email_get_attachment_data_list( m_mail->mail_id, &attachment, &attachmentCount);
872         if (EMAIL_ERROR_NONE != error) {
873                 LoggerW("email_get_attachment_data_list [" << error << "]");
874         }
875
876         LoggerW("meeting_request_status " << m_mail->meeting_request_status);
877
878         if( m_mail->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_REQUEST
879                 || m_mail->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_RESPONSE
880                 || m_mail->meeting_request_status == EMAIL_MAIL_TYPE_MEETING_ORIGINATINGREQUEST)
881         {
882                 error = email_get_meeting_request(m_mail->mail_id, &meeting_req);
883                 if (EMAIL_ERROR_NONE != error) {
884                         LoggerW("email_get_meeting_request() failed [" << error <<"]");
885                 }
886         }
887         error = email_update_mail( m_mail.Get(), attachment, attachmentCount, meeting_req, 0);
888         if (EMAIL_ERROR_NONE != error) {
889                 LoggerW("Nothing to update or error. [" << error << "]");
890 /*
891                 if(error == EMAIL_ERROR_DB_FAILURE)
892                 {
893                         int retry = 0;
894                         while (retry < 2) {
895                                 LoggerW("wait 300 ms");
896                                 usleep(300 * 1000);
897                                 email_update_mail( m_mail.Get(), attachment, attachmentCount, meeting_req, 0);
898                                 LoggerW("error. [" << error << "]");
899                                 if (EMAIL_ERROR_NONE == error) {
900                                         break;
901                                 }
902                                 retry++;
903
904                         }
905                 }
906 */
907         }
908
909         if(getCurrentFolder() == DRAFTBOX)
910         {
911         
912 //              updateAttachments();
913
914                 
915                 email_mail_data_t* result = NULL;
916                 
917                 error = email_get_mail_data(m_mail->mail_id, &result);
918                 if (EMAIL_ERROR_NONE != error) {
919                         LoggerW("email_get_mail_data error. [" << error << "]");
920                 }
921                 else
922                 {
923                         if(result->body_download_status != 1)
924                         {
925                                 LoggerD("result->body_download_status " << result->body_download_status);
926                                 int mail_id_array[1];
927                                 email_mail_attribute_type attribute_type;
928                                 email_mail_attribute_value_t attribute_value;
929
930                                 mail_id_array[0] = result->mail_id;
931                                 LoggerD("result->mail_id " << result->mail_id);
932                                 attribute_type = EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS;
933                                 attribute_value.integer_type_value = 1;
934
935                                 error =  email_update_mail_attribute(m_accountId, mail_id_array, 1, EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS, attribute_value);
936                                 if (EMAIL_ERROR_NONE != error) {
937                                         LoggerW("email_update_mail_attribute error. [" << error << "]");
938                                 }
939                         }
940
941                         tm* time = localtime(&result->date_time);
942                         if (!time) {
943                                 LoggerE("localtime failed");
944                                 Throw(WrtDeviceApis::Commons::PlatformException);
945                         }
946                         setDateTime(*time);
947
948                 }
949                 if(result != NULL)
950                 {
951                         error = email_free_mail_data(&result, 1);
952                         if (EMAIL_ERROR_NONE != error) {
953                                 LoggerW("email_free_mail_data error. [" << error << "]");
954                         }
955                 }
956
957         }
958
959         if(meeting_req) {
960                 email_free_meeting_request(&meeting_req, 1);
961         }
962
963         if (attachment)
964         {
965                 error = email_free_attachment_data(&attachment, attachmentCount);
966                 if (EMAIL_ERROR_NONE != error) {
967                         LoggerW("email_free_attachment_data [" << error << "]");
968                 }
969         }
970
971         LOG_EXIT
972 }
973
974 void Email::createSendMessage()
975 {
976         LOG_ENTER
977
978     MailSender::getInstance(); //start email service
979         LoggerD("getUID:  " << getUID());
980         if ( getUID() > 0 && m_accountId > 0)
981         {
982                 update();
983         }
984         else
985         {
986         DPL::Mutex::ScopedLock mx(&m_updateMutex);
987
988                 EmailAccountInfo account = getEmailAccount();
989                 m_accountId = account.getIntId();       //set account ID
990                 LoggerD("account ID : " << m_accountId);
991                 m_mail.Reset(EmailService::createMailData(account));
992
993                 updateSubject();
994                 updateBody();
995                 updateRecipients();
996                 updatePriority();
997                 updateReadStatus();
998
999                 email_mailbox_t* mailbox;
1000                 int error = email_get_mailbox_by_mailbox_type(m_accountId, EMAIL_MAILBOX_TYPE_OUTBOX, &mailbox );
1001                 if (EMAIL_ERROR_NONE != error) {
1002                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1003                         "Couldn't add message to mailbox. [" << error << "]");
1004                 }
1005                 if ( mailbox->mailbox_id )
1006                         m_mail->mailbox_id = mailbox->mailbox_id;
1007                 LoggerD("mail MailBox id :" << m_mail->mailbox_id);
1008
1009                 error = email_add_mail(m_mail.Get(), NULL, 0, NULL, 0);
1010                 if (EMAIL_ERROR_NONE != error) {
1011                        ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1012                                 "Couldn't add message to mailbox. [" << error << "]");
1013                 }
1014
1015                 LoggerD("m_mail->mail_id =" << m_mail->mail_id);
1016
1017                 setId(convertId(m_mail->mail_id));
1018                 setFolderType(OUTBOX);
1019                 setMessageStatus(MESSAGE_STATUS_SENDING);
1020
1021                 updateAttachments();    //update Attachment.
1022
1023                 error = email_free_mailbox(&mailbox, 1);
1024                 if (EMAIL_ERROR_NONE != error) {
1025                         LoggerE("Failed to destroy mailbox: " << error);
1026                 }
1027
1028                 setConvId(m_mail->thread_id);
1029
1030                 email_mail_data_t* result = NULL;
1031
1032                 error = email_get_mail_data(m_mail->mail_id, &result);
1033                 if (EMAIL_ERROR_NONE != error) {
1034                     ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1035                              "Couldn't find message " << m_mail->mail_id << ". [" << error << "]");
1036                 }
1037
1038                 if (m_mail->file_path_plain)
1039                         free(m_mail->file_path_plain);
1040                 m_mail->file_path_plain = strdup(result->file_path_plain);
1041
1042                 if ( m_mail->file_path_html)
1043                 {
1044                         free(m_mail->file_path_html);
1045                 }
1046
1047                 if(result->file_path_html)
1048                 {
1049                         m_mail->file_path_html = strdup(result->file_path_html);
1050                 }
1051
1052                 if (result->full_address_from) {
1053                         Recipients from;
1054                         from.setRecipients(EmailUtils::stripAddress(result->full_address_from));
1055                         setSourceAddress(from);
1056                         setSourceAddressValidity(true); //not needed to update in platform
1057                 }
1058                 setCurrentFolderId(result->mailbox_id);
1059
1060                 error = email_free_mail_data(&result, 1);
1061                 if (EMAIL_ERROR_NONE != error) {
1062                     ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1063                              "Couldn't find message " << m_mail->mail_id << ". [" << error << "]");
1064                 }
1065
1066     }
1067         LOG_EXIT
1068 }
1069
1070
1071 void Email::addMessageToDraft()
1072 {
1073     LOG_ENTER
1074
1075     MailSender::getInstance(); //start email service
1076
1077         LoggerD("getUID:  " << getUID());
1078     if ( getUID() > 0 && m_accountId > 0)
1079     {
1080                 update();
1081     }
1082     else
1083     {
1084                 DPL::Mutex::ScopedLock mx(&m_updateMutex);
1085                 EmailAccountInfo account = getEmailAccount();
1086                 m_accountId = account.getIntId();       //set account ID
1087                 LoggerD("account ID : " << m_accountId);
1088                 m_mail.Reset(EmailService::createMailData(account));
1089
1090                 updateSubject();
1091                 updateBody();
1092                 updateRecipients();
1093                 updatePriority();
1094                 updateReadStatus();
1095
1096                 email_mailbox_t* mailbox;
1097                 int error = email_get_mailbox_by_mailbox_type(m_accountId, EMAIL_MAILBOX_TYPE_DRAFT, &mailbox );
1098                 if (EMAIL_ERROR_NONE != error) {
1099                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1100                         "Couldn't add message to mailbox. [" << error << "]");
1101                 }
1102                 if ( mailbox->mailbox_id )
1103                 {
1104                         m_mail->mailbox_id = mailbox->mailbox_id;
1105                         LoggerD("mail MailBox id :" << m_mail->mailbox_id);
1106                 }
1107
1108                 error = email_add_mail(m_mail.Get(), NULL, 0, NULL, 0);
1109                 if (EMAIL_ERROR_NONE != error) {
1110                         LoggerE("Couldn't add message to mailbox");
1111                        ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1112                                 "Couldn't add message to mailbox. [" << error << "]");
1113                 }
1114
1115                 LoggerD("message id =" << m_mail->mail_id);
1116
1117                 setId(convertId(m_mail->mail_id));
1118                 setFolderType(DRAFTBOX);
1119                 setMessageStatus(MESSAGE_STATUS_DRAFT);
1120
1121                 updateAttachments();    //update Attachment.
1122
1123                 error = email_free_mailbox(&mailbox, 1);
1124                 if (EMAIL_ERROR_NONE != error) {
1125                         LoggerE("Failed to destroy mailbox: " << error);
1126                 }
1127
1128                 loadDraftMessage();
1129     }
1130
1131     LOG_EXIT
1132 }
1133
1134 void Email::loadDraftMessage()
1135 {
1136     LOG_ENTER
1137
1138         email_mail_data_t* result = NULL;
1139         
1140         int error = email_get_mail_data(m_mail->mail_id, &result);
1141         if (EMAIL_ERROR_NONE != error) {
1142                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1143                                  "Couldn't find message " << m_mail->mail_id << ". [" << error << "]");
1144         }
1145
1146         if(result->body_download_status != 1)
1147         {
1148                 LoggerD("result->body_download_status " << result->body_download_status);
1149                 int mail_id_array[1];
1150                 email_mail_attribute_type attribute_type;
1151                 email_mail_attribute_value_t attribute_value;
1152
1153                 mail_id_array[0] = result->mail_id;
1154                 LoggerD("result->mail_id " << result->mail_id);
1155                 attribute_type = EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS;
1156                 attribute_value.integer_type_value = 1;
1157
1158                 email_update_mail_attribute(m_accountId, mail_id_array, 1, EMAIL_MAIL_ATTRIBUTE_BODY_DOWNLOAD_STATUS, attribute_value);
1159         }
1160
1161     tm* time = localtime(&result->date_time);
1162     if (!time) {
1163         LoggerE("localtime failed");
1164         Throw(WrtDeviceApis::Commons::PlatformException);
1165     }
1166     setDateTime(*time);
1167
1168         setReadStatus(result->flags_seen_field == 1);
1169
1170         m_accountId = result->account_id;
1171         setConvId(result->thread_id);
1172         setPriority( EmailConverter::toMessagePriority( result->priority ) );
1173         setSize(result->mail_size);
1174         setCurrentFolderId(result->mailbox_id);
1175
1176         if (m_mail->file_path_plain)
1177         {
1178                 free(m_mail->file_path_plain);
1179         }
1180         if(result->file_path_plain)
1181         {
1182                 m_mail->file_path_plain = strdup(result->file_path_plain);
1183         }
1184
1185         if ( m_mail->file_path_html)
1186         {
1187                 free(m_mail->file_path_html);
1188         }
1189
1190         if(result->file_path_html)
1191         {
1192                 m_mail->file_path_html = strdup(result->file_path_html);
1193         }
1194
1195         if (result->full_address_from) {
1196                 Recipients from;
1197                 from.setRecipients(EmailUtils::stripAddress(result->full_address_from));
1198                 setSourceAddress(from);
1199                 setSourceAddressValidity(true); //not needed to update in platform
1200                 setFrom(result->full_address_from);
1201         }
1202         m_mail->save_status = result->save_status;
1203
1204         error = email_free_mail_data(&result, 1);
1205         if (EMAIL_ERROR_NONE != error) {
1206                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1207                                  "Couldn't find message " << m_mail->mail_id << ". [" << error << "]");
1208         }
1209
1210     LOG_EXIT
1211 }
1212
1213 void Email::updateRecipients()
1214 {
1215     LOG_ENTER
1216
1217     if (getToValidity() && getCcValidity() && getBccValidity()) { return; }
1218
1219     if (!m_mail) {
1220         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL.");
1221     }
1222
1223     if (!getToValidity()) {
1224         std::string addressLine = EmailUtils::formatAddressLine(getToRecipients());
1225         if (m_mail->full_address_to) {
1226             free(m_mail->full_address_to);
1227         }
1228         m_mail->full_address_to = String::strdup(addressLine);
1229         setToValidity(true);
1230     }
1231
1232     if (!getCcValidity()) {
1233         std::string addressLine = EmailUtils::formatAddressLine(getCcRecipients());
1234         if (m_mail->full_address_cc) {
1235             free(m_mail->full_address_cc);
1236         }
1237         m_mail->full_address_cc = String::strdup(addressLine);
1238         setCcValidity(true);
1239     }
1240
1241     if (!getBccValidity()) {
1242         std::string addressLine = EmailUtils::formatAddressLine(getBccRecipients());
1243         if (m_mail->full_address_bcc) {
1244             free(m_mail->full_address_bcc);
1245         }
1246         m_mail->full_address_bcc = String::strdup(addressLine);
1247         setBccValidity(true);
1248     }
1249
1250     LOG_EXIT
1251 }
1252
1253 void Email::updateFrom()
1254 {
1255     LOG_ENTER
1256
1257     if (getFromValidity()) { return; }
1258
1259     if (!m_mail) {
1260         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL.");
1261     }
1262
1263     m_mail->account_id = m_accountId;
1264
1265     if (m_mail->full_address_from) {
1266           free(m_mail->full_address_from);
1267     }
1268     m_mail->full_address_from = String::strdup(getFrom());
1269
1270     setFromValidity(true);
1271
1272     LOG_EXIT
1273 }
1274
1275 void Email::updateAttachments()
1276 {
1277     LOG_ENTER
1278
1279     if (isAttachmentsValid()) { return; }
1280
1281     if (!m_mail) {
1282         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail is NULL.");
1283     }
1284
1285     email_attachment_data_t* attachment = NULL;
1286     int attachmentCount = 0;
1287     email_mailbox_t* mailBox = NULL;
1288     int error = 0;
1289
1290     Try {
1291                  //clean attachment
1292                 LoggerD("update attachments, msgId=" << getIdRef());
1293                 LoggerD("m_mail->mail_id=" << m_mail->mail_id);
1294                 error = email_get_attachment_data_list( m_mail->mail_id, &attachment, &attachmentCount);        //get Attachment list
1295                 if (EMAIL_ERROR_NONE != error) {
1296                         ThrowMsg( WrtDeviceApis::Commons::PlatformException, "Couldn't get attachment list: ");
1297                 }
1298                 error = email_get_mailbox_by_mailbox_id(m_mail->mailbox_id, &mailBox);
1299
1300                 if (EMAIL_ERROR_NONE != error) {
1301                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1302                         "Couldn't get mailbox. [" << error << "]");
1303                 }
1304
1305                 if ( attachmentCount > 0 )
1306                 {
1307                         LoggerD("attachmentCount=" << attachmentCount);
1308                         int i = 0;
1309                         std::stringstream stream;
1310                         for ( i = 0; i < attachmentCount; i++)
1311                         {
1312                                 LoggerD("file name:" << attachment[i].attachment_name << " file path :" << attachment[i].attachment_path);
1313                                 int attachmentId = attachment[i].attachment_id;
1314
1315                                 int error = email_delete_attachment(attachmentId);
1316                                 if (EMAIL_ERROR_NONE != error) {
1317                                     LoggerD("Error Num = " << error);
1318                                     ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1319                                              "Error while adding attachment. [" << error << "]");
1320                                 }
1321                                 stream.str("");
1322                         }
1323
1324                         if ( attachment )
1325                         {
1326                                 error = email_free_attachment_data(&attachment, attachmentCount);
1327                                 if (EMAIL_ERROR_NONE != error) {
1328                                         ThrowMsg( WrtDeviceApis::Commons::PlatformException, " attachment_data free error! ");
1329                                 }
1330                         }
1331
1332                 }
1333
1334                 //set Attachment
1335                 std::size_t attachmentSize = getAttachmentsCount();
1336                 std::size_t inlineAttachmentSize = getInlineAttachmentsCount();
1337
1338                 LoggerD("update attachments, attachmentSize=" << attachmentSize);
1339                 if (attachmentSize > 0)
1340                 {
1341                         email_attachment_data_t* attachment_info = NULL;
1342                         for (std::size_t i = 0; i < attachmentSize; ++i)
1343                         {
1344                                 IAttachmentPtr att = getAttachment(i);
1345                                 if (!att) {
1346                                         LoggerD("skip att" << i);
1347                                         continue;
1348                                 }
1349
1350                                 //copy attachment file
1351                                 std::stringstream cp_cmd;
1352                                 char buf[] = "/tmp/XXXXXX";
1353                                 mode_t mask = umask(S_IWGRP | S_IWOTH);
1354                                 error = mkstemp(buf);
1355                                 umask(mask);
1356
1357                                 cp_cmd << COMMAND_NAME;
1358                                 cp_cmd << " " << COMMAND_SWITCH_RECURSIVE;
1359                                 cp_cmd << " \"" << att->getFullPath() << "\"";
1360                                 cp_cmd << " \"" << buf << "\"";
1361
1362                                 attachment_info = EmailService::alloc<email_attachment_data_t>();
1363                                 attachment_info->attachment_name = String::strdup(att->getShortName());
1364                                 attachment_info->attachment_path = String::strdup( buf );
1365                                 attachment_info->save_status = true;
1366                                 attachment_info->inline_content_status = 0;
1367                                 if(att->getMimeType().size() > 0)
1368                                 {
1369                                         attachment_info->attachment_mime_type = String::strdup(att->getMimeType());
1370                                 }
1371
1372                                 LoggerD("attachment_info->attachment_name=" << attachment_info->attachment_name);
1373                                 LoggerD("attachment_info->attachment_path=" << attachment_info->attachment_path);
1374                                 LoggerD("attachment_info->save_status=" << attachment_info->save_status);
1375                                 LoggerD("attachment_info->inline_content_status=" << attachment_info->inline_content_status);
1376                                 LoggerD("attachment_info->attachment_mime_type=" << attachment_info->attachment_mime_type);
1377
1378                                 LoggerD("Copy Command=" << cp_cmd.str());
1379                                 if (EINA_TRUE != ecore_file_is_dir(att->getFullPath().c_str())) {
1380                                         LoggerD("att->getFullPath().c_str()=" << att->getFullPath().c_str());
1381                                         if (EINA_TRUE != ecore_file_cp(att->getFullPath().c_str(), buf)) {
1382                                                 LoggerD("buf=" << buf);
1383                                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to copy file");
1384                                         }
1385                                 }
1386
1387 /*
1388                                 int result = system(cp_cmd.str().c_str());
1389                                 if (-1 != result) {
1390                                         if (0 != WIFEXITED(result)) {
1391                                                 if (0 != WEXITSTATUS(result)) {
1392                                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Command failed.");
1393                                                 }
1394                                         } else {
1395                                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1396                                                 "Command terminated abnormally.");
1397                                         }
1398                                 } else {
1399                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Couldn't launch command.");
1400                                 }
1401 */
1402
1403                                 LoggerD("add Attachment");
1404                                 int error = email_add_attachment(m_mail->mail_id, attachment_info);
1405                                 if (EMAIL_ERROR_NONE != error) {
1406                                         LoggerD("error :" << error);
1407                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Error while adding attachment. [" << error << "]");
1408                                 }
1409                                 else
1410                                 {
1411                                         LoggerD(" attachment id : " << attachment_info->attachment_id);
1412                                         LoggerD(" attachment inline : " << attachment_info->inline_content_status);
1413                                         LoggerD(" setNth(i+1) : " << i+1);
1414                                         att->setDownloaded(true);
1415                                         att->setIsInlineAttachment(FALSE);
1416                                         att->setAttachmentID(attachment_info->attachment_id);
1417                                         att->setMessage(SharedFromThis());
1418                                         att->setNth(i+1);
1419                                 }
1420
1421                                 if (attachment_info)
1422                                         EmailService::freeAttachment(attachment_info);
1423                         }
1424
1425                 }
1426                 LoggerD("update attachments, inlineAttachmentSize=" << inlineAttachmentSize);
1427                 if (inlineAttachmentSize > 0)
1428                 {
1429                         email_attachment_data_t* attachment_info = NULL;
1430                         for (std::size_t i = 0; i < inlineAttachmentSize; ++i)
1431                         {
1432                                 IAttachmentPtr att = getInlineAttachment(i);
1433                                 if (!att) {
1434                                         continue;
1435                                 }
1436
1437                                 //copy attachment file
1438                                 std::stringstream cp_cmd;
1439                                 char buf[] = "/tmp/XXXXXX";
1440                                 mode_t mask = umask(S_IWGRP | S_IWOTH);
1441                                 error = mkstemp(buf);
1442                                 umask(mask);
1443
1444                                 cp_cmd << COMMAND_NAME;
1445                                 cp_cmd << " " << COMMAND_SWITCH_RECURSIVE;
1446                                 cp_cmd << " \"" << att->getFullPath() << "\"";
1447                                 cp_cmd << " \"" << buf << "\"";
1448
1449                                 attachment_info = EmailService::alloc<email_attachment_data_t>();
1450                                 attachment_info->attachment_name = String::strdup(att->getShortName());
1451                                 attachment_info->attachment_path = String::strdup( buf );
1452                                 attachment_info->save_status = true;
1453                                 attachment_info->inline_content_status = 1;
1454                                 LoggerD("attachment_info->inline_content_status=" << attachment_info->inline_content_status);
1455                                 if(att->getMimeType().size() > 0)
1456                                 {
1457                                         attachment_info->attachment_mime_type = String::strdup(att->getMimeType());
1458                                 }
1459
1460                                 LoggerD("Copy Command=" << cp_cmd.str());
1461                                 if (EINA_TRUE != ecore_file_is_dir(att->getFullPath().c_str())) {
1462                                         LoggerD("att->getFullPath().c_str()=" << att->getFullPath().c_str());
1463                                         if (EINA_TRUE != ecore_file_cp(att->getFullPath().c_str(), buf)) {
1464                                                 LoggerD("buf=" << buf);
1465                                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Failed to copy file");
1466                                         }
1467                                 }
1468                                 LoggerD("attachment_info->attachment_mime_type=" << attachment_info->attachment_mime_type);
1469
1470 /*
1471                                 int result = system(cp_cmd.str().c_str());
1472                                 if (-1 != result) {
1473                                         if (0 != WIFEXITED(result)) {
1474                                                 if (0 != WEXITSTATUS(result)) {
1475                                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Command failed.");
1476                                                 }
1477                                         } else {
1478                                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1479                                                 "Command terminated abnormally.");
1480                                         }
1481                                 } else {
1482                                         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Couldn't launch command.");
1483                                 }
1484 */
1485
1486
1487                                 LoggerD("add Attachment");
1488                                 int error = email_add_attachment(m_mail->mail_id, attachment_info);
1489                                 if (EMAIL_ERROR_NONE != error) {
1490                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1491                                      "Error while adding attachment. [" << error << "]");
1492                                 }
1493                                 else
1494                                 {
1495                                         LoggerD(" attachment id : " << attachment_info->attachment_id);
1496                                         LoggerD(" attachment inline : " << attachment_info->inline_content_status);
1497                                         LoggerD(" setNth(i+(int)attachmentSize+1) : " << i+(int)attachmentSize+1);
1498                                         att->setDownloaded(true);
1499                                         att->setIsInlineAttachment(TRUE);
1500                                         att->setAttachmentID(attachment_info->attachment_id);
1501                                         att->setMessage(SharedFromThis());
1502 //                                      att->setNth(i+1);
1503                                         att->setNth(i + (int)attachmentSize + 1);
1504                                 }
1505
1506                                 if (attachment_info)
1507                                         EmailService::freeAttachment(attachment_info);
1508                         }
1509
1510                 }
1511         }
1512         Catch(WrtDeviceApis::Commons::PlatformException) {
1513            if (attachment)
1514            {
1515                 int error = email_free_attachment_data(&attachment, attachmentCount);
1516                 if (EMAIL_ERROR_NONE != error) {
1517                         ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1518                                      "Error while adding attachment data [" << error << "]");
1519                 }
1520
1521                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,
1522                                      "Error attachment Update");
1523            }
1524         }
1525
1526     LOG_EXIT
1527 }
1528
1529 void Email::updatePriority()
1530 {
1531     LOG_ENTER
1532
1533     if (isPriorityValid()) { return; }
1534
1535     if (!m_mail) {
1536         ThrowMsg(WrtDeviceApis::Commons::PlatformException, "Mail not allocated.");
1537     }
1538
1539     m_mail->priority = EmailConverter::toMailPriority( getPriority());
1540     setPriorityValid(true);
1541
1542     LOG_EXIT
1543 }
1544
1545 int Email::getIntId() const
1546 {
1547     return convertId(getIdRef());
1548 }
1549
1550 }
1551 }