69d88de761a42003a5c8789c4f673b0229def10f
[framework/web/wrt-plugins-tizen.git] / src / Messaging / JSMessagingService.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 "JSMessagingService.h"
19 #include "MessagingController.h"
20 #include <CommonsJavaScript/Converter.h>
21 #include <CommonsJavaScript/Validator.h>
22 #include <CommonsJavaScript/JSUtils.h>
23 #include <CommonsJavaScript/JSCallbackManager.h>
24 #include <CommonsJavaScript/Utils.h>                                    
25 #include <CommonsJavaScript/ScopedJSStringRef.h>
26 #include <CommonsJavaScript/JSPendingOperation.h>
27 #include <CommonsJavaScript/JSDOMExceptionFactory.h>
28 #include <Commons/StringUtils.h>
29
30 #include "ReqReceiverMessage.h"
31 #include <JSTizenExceptionFactory.h>
32 #include <JSTizenException.h>
33 #include <SecurityExceptions.h>
34
35 #include "MessagingErrorMsg.h"
36 #include "ConverterMessage.h"
37 #include "MessagingListener.h"
38 #include "JSMessagingStorage.h"
39 #include "JSMessage.h"
40 #include "EventSendMessagePrivateData.h"        //for send message
41 #include "EventMessagingServicePrivateData.h"
42 #include "MessageAsyncCallbackManager.h"
43 #include "plugin_config.h"
44
45 using namespace std;
46 using namespace DPL;
47 using namespace WrtDeviceApis;
48 using namespace WrtDeviceApis::Commons;
49 using namespace WrtDeviceApis::CommonsJavaScript;
50 using namespace DeviceAPI::Messaging;
51 using namespace DeviceAPI::Common;
52
53 namespace DeviceAPI {
54 namespace Messaging {
55
56         JSClassRef JSMessagingService::m_jsClassRef = NULL;
57         JSClassDefinition JSMessagingService::m_classInfo = {
58                 0,
59                 kJSClassAttributeNone,
60                 "MessageService",
61                 NULL,
62                 m_property,
63                 m_function,
64                 initialize,
65                 finalize,
66                 NULL, //hasProperty,
67                 NULL, //getProperty,
68                 NULL, //setProperty,
69                 NULL, //deleteProperty,Geolocation
70                 NULL, //getPropertyNames,
71                 NULL,
72                 NULL,
73                 hasInstance,
74                 NULL
75         };
76
77         JSStaticValue JSMessagingService::m_property[] =
78         {
79             {"id",                      getProperty, NULL, kJSPropertyAttributeReadOnly},
80             {"type",                            getProperty, NULL, kJSPropertyAttributeReadOnly},
81             {"name",                            getProperty, NULL, kJSPropertyAttributeReadOnly},
82             {"messageStorage",                          getProperty, NULL, kJSPropertyAttributeReadOnly},
83             { 0, 0, 0, 0 }
84         };
85
86         JSStaticFunction JSMessagingService::m_function[] = {
87                         //{ "createMessage",      JSMessagingService::createMessage,       kJSPropertyAttributeNone },
88                         { "sendMessage",          JSMessagingService::sendMessage,         kJSPropertyAttributeNone },
89                         { "loadMessageBody",      JSMessagingService::loadMessageBody,     kJSPropertyAttributeNone },
90                         { "loadMessageAttachment",        JSMessagingService::loadMessageAttachment,       kJSPropertyAttributeNone },
91                         { "sync",         JSMessagingService::sync,        kJSPropertyAttributeNone },
92                         { "syncFolder",   JSMessagingService::syncFolder,          kJSPropertyAttributeNone },
93                         //{ "cancelOperation",   JSMessagingService::cancelOperation,      kJSPropertyAttributeNone },
94                         { "stopSync",   JSMessagingService::stopSync,      kJSPropertyAttributeNone },
95                         { 0, 0, 0 }
96         };
97
98         const JSClassRef JSMessagingService::getClassRef() {
99                 if (!m_jsClassRef) {
100                         m_jsClassRef = JSClassCreate(&m_classInfo);
101                 }
102                 return m_jsClassRef;
103         }
104
105         void JSMessagingService::initialize(JSContextRef context, JSObjectRef object) {
106                 LogDebug("creation messaging Service instance");
107         }
108
109         void JSMessagingService::finalize(JSObjectRef object) {
110                 LogDebug("finalize messaging instance");
111                 //JSMessagingServicePriv *priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(object));
112                 JSMessagingServicePriv *priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(object));
113                 delete priv;
114         }
115
116         bool JSMessagingService::hasInstance(JSContextRef context, JSObjectRef constructor, JSValueRef possibleInstance, JSValueRef* exception) {
117                 return JSValueIsObjectOfClass(context, possibleInstance, getClassRef());
118         }
119
120         JSObjectRef JSMessagingService::createJSObject(JSContextRef context, const IMessagingServicePtr &messagingService)
121         {
122                 JSMessagingServicePriv* priv = new JSMessagingServicePriv( context, messagingService);  //make private class.
123                 return JSObjectMake(context, getClassRef(), priv);
124         }
125
126         JSValueRef JSMessagingService::getProperty(JSContextRef context, JSObjectRef object, JSStringRef propertyName, JSValueRef* exception)
127         {
128                 LogDebug("<<< ");
129                 JSValueRef retVal = NULL;
130
131                 JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(object));        //get private object
132             if (priv)
133                 {
134                         IMessagingServicePtr imessagingService = priv->getObject();
135                         Try{
136                                 ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context);
137
138                                 if (JSStringIsEqualToUTF8CString(propertyName, "type")) {
139                                         LogDebug("type" << ":" << imessagingService->getType());
140                                         retVal = converter->toJSValueRef(converter->toMessageType(imessagingService->getType()));                                       
141                                 } else if (JSStringIsEqualToUTF8CString(propertyName, "name")) {
142                                         LogDebug("name" << ":" <<  imessagingService->getName());
143                                         retVal = converter->toJSValueRef(imessagingService->getName());
144                                 } else if (JSStringIsEqualToUTF8CString(propertyName, "id")) {
145                                         LogDebug("accountId" << ":" <<  imessagingService->getAccountID());
146                                         
147                                         std::stringstream stream;
148                                         stream << imessagingService->getAccountID();
149                                         if (stream.fail()) {        
150                                                 ThrowMsg(WrtDeviceApis::Commons::UnknownException,"Couldn't convert e-mail account id");
151                                         }
152                                         
153                                         retVal = converter->toJSValueRef(stream.str());
154                                 } else if (JSStringIsEqualToUTF8CString(propertyName, "messageStorage")) {
155                                         JSContextRef l_globalContext = converter->toJSGlobalContext(object);                                    
156                                         MessagingStoragePrivObjPtr storagePriv(new MessagingStoragePrivObj());
157 //                                      MessagingListenerPtr listener_priv = MessagingListener::getInstance(l_globalContext) ;
158                                         storagePriv->m_index = imessagingService->getAccountID();
159                                         storagePriv->m_type = imessagingService->getType();
160                                         LogDebug("type" << ":" << imessagingService->getType());
161                                         LogDebug("accountId" << ":" <<  imessagingService->getAccountID());
162                                         
163                                         MessagingStoragePriv *priv = new MessagingStoragePriv(l_globalContext, storagePriv);
164                                         //MessagingStoragePrivObjPtr storagePriv = priv->getObject();
165
166 //                                      retVal = JSUtils::makeObject(l_globalContext, JSMessagingStorage::getClassRef(), priv);
167                                         retVal = JSObjectMake(l_globalContext, JSMessagingStorage::getClassRef(), priv);
168
169                                 } else{
170                                         retVal = JSValueMakeUndefined(context);
171                                 }
172
173                         } Catch (WrtDeviceApis::Commons::Exception){
174                                 LogError("Exception: " << _rethrown_exception.GetMessage());
175                                 return JSTizenExceptionFactory::postException(context, exception, 
176                                         JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN);                    
177                         }
178
179                         LogDebug(">>>");
180                         return retVal;
181                         
182                 }
183                 else
184                 {       
185                         LogDebug(" Private Object is NULL ");
186                         return JSTizenExceptionFactory::postException(context, exception, 
187                                         JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND);
188                 }
189                 
190         }
191
192         JSValueRef JSMessagingService::createMessage(JSContextRef context, JSObjectRef object, JSObjectRef thisObject, size_t argumentCount,
193                 const JSValueRef arguments[], JSValueRef* exception) 
194         {
195
196                 LogInfo("<<<");
197                 LogDebug("arumentConunt:" << argumentCount);
198
199                 JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));
200                 if (priv)
201                 {
202                         AceSecurityStatus status = MESSAGING_CHECK_ACCESS(
203                                 MessagingExportedNames[MESSAGING_FUNCTION_API_CREATE_MESSAGE]);
204                         TIZEN_SYNC_ACCESS_HANDLER(status, context, exception);
205                                 
206                         try {
207                                 ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context);
208                                 JSContextRef l_globalContext = converter->toJSGlobalContext(thisObject);
209                                 Validator check(context, exception);
210
211                                 IMessagingServicePtr imessagingService = priv->getObject();                             //get MessagingService.
212                                 JSValueRef objMsg = NULL;
213                                 
214                                 MessageType msgType = (MessageType)imessagingService->getType();
215                                 LogInfo("msgType :" << msgType);
216         
217                                 if (msgType == EMAIL)
218                                 {
219                                         EmailAccountInfo account = imessagingService->getCurrentEmailAccount();
220                                         LogDebug("Account Address:" << &account);
221                                         objMsg = JSMessage::createJSObject(l_globalContext, account, msgType);          //make message JSValueRef.
222                                 }
223                                 else
224                                 {
225                                         objMsg = JSMessage::createJSObject(l_globalContext, msgType);           //make message JSValueRef.
226                                 }
227
228                                 //set Properties
229                                 if ( argumentCount == 1)
230                                 {
231                                         IMessagePtr msg = converter->toIMessage(objMsg) ;
232
233                                         if (!msg)
234                                                 ThrowMsg(WrtDeviceApis::Commons::PlatformException,"platform exception");
235
236                                         LogDebug ("##### msg type is " << msg->getId());
237                                                                                 
238                                         const ScopedJSStringRef subjectStr(JSStringCreateWithUTF8CString("subject"));
239                                         const ScopedJSStringRef toStr(JSStringCreateWithUTF8CString("to"));
240                                         const ScopedJSStringRef ccStr(JSStringCreateWithUTF8CString("cc"));
241                                         const ScopedJSStringRef bccStr(JSStringCreateWithUTF8CString("bcc"));
242                                         const ScopedJSStringRef plainBodyStr(JSStringCreateWithUTF8CString("plainBody"));
243                                         const ScopedJSStringRef htmlBodyStr(JSStringCreateWithUTF8CString("htmlBody"));
244                                         const ScopedJSStringRef priorityStr(JSStringCreateWithUTF8CString("isHighPriority"));
245
246                                         JSObjectRef arg = converter->toJSObjectRef(arguments[0]);
247                                         JSValueRef subjectData = JSObjectGetProperty(l_globalContext, arg, subjectStr.get(), NULL);
248                                         JSValueRef toData = JSObjectGetProperty(l_globalContext, arg, toStr.get(), NULL);
249                                         JSValueRef ccData = JSObjectGetProperty(l_globalContext, arg, ccStr.get(), NULL);
250                                         JSValueRef bccData = JSObjectGetProperty(l_globalContext, arg, bccStr.get(), NULL);
251                                         JSValueRef plainBodyData = JSObjectGetProperty(l_globalContext, arg, plainBodyStr.get(), NULL);
252                                         JSValueRef htmlBodyData = JSObjectGetProperty(l_globalContext, arg, htmlBodyStr.get(), NULL);
253                                         JSValueRef priorityData = JSObjectGetProperty(l_globalContext, arg, priorityStr.get(), NULL);   
254
255                                         //subject
256                                          if (!JSValueIsUndefined(l_globalContext, subjectData) ) 
257                                          {
258                                                 LogDebug ( " Subject : " << converter->toString(subjectData) );                                         
259                                                 std::string subject = converter->toString(subjectData);
260                                                  switch (msgType) 
261                                                  {
262                                                 case MMS:
263                                                 {
264                                                     IMmsPtr mms = MessageFactory::convertToMms(msg);
265                                                     mms->setSubject(subject);
266                                                     break;
267                                                 }
268                                                 case EMAIL:
269                                                 {
270                                                     IEmailPtr email = MessageFactory::convertToEmail(msg);
271                                                     email->setSubject(subject);
272                                                     break;
273                                                 }
274                                                   default:
275                                                   {
276                                                     LogError("message not supported");
277                                                     //Throw(WrtDeviceApis::Commons::UnsupportedException);
278                                                     //break;
279                                                   }
280                                                 }
281                                          }
282                                         //to
283                                         if (!JSValueIsUndefined(l_globalContext, toData) )
284                                         {
285                                                 Recipients to = converter->toRecipients(toData);
286                                                 LogDebug("setting to field, size=" << to.getRecipientSize());
287                                                 msg->setToRecipients(to);
288                                         }
289                                         //cc
290                                         if (msgType == EMAIL )
291                                         {
292                                                 IEmailPtr email = MessageFactory::convertToEmail(msg);
293                                                 if (!JSValueIsUndefined(l_globalContext, ccData))
294                                                 {
295                                                         Recipients cc = converter->toRecipients(ccData);
296                                                 email->setCcRecipients(cc);
297                                                 }
298
299                                                 if (!JSValueIsUndefined(l_globalContext, bccData))
300                                                 {
301                                                         Recipients bcc = converter->toRecipients(bccData);
302                                                 email->setBccRecipients(bcc);
303                                                 }
304
305                                                 if (!JSValueIsUndefined(l_globalContext, htmlBodyData))
306                                                 {
307                                                         std::string body = converter->toString(htmlBodyData);
308                                                         LogDebug("html body : " << body);
309                                                         email->setHtmlBody(body);
310                                                 }
311
312                                                 if (!JSValueIsUndefined(l_globalContext, priorityData))
313                                                 {
314                                                         email->setPriority(converter->toMessagePriority(priorityData));
315                                                 }
316                                                 
317                                         }
318
319                                         if (!JSValueIsUndefined(l_globalContext, plainBodyData) )
320                                         {
321                                                 std::string body = converter->toString(plainBodyData);
322                                                 LogDebug("plain body  : " << body);
323                                                 msg->setBody(body);
324                                         }
325                         
326                                 }
327                                 return objMsg;
328                                                                 
329                         }
330                         Catch(WrtDeviceApis::Commons::InvalidArgumentException) {
331                         return JSTizenExceptionFactory::postException(context, exception, 
332                                         JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);    
333                         }
334                         Catch(WrtDeviceApis::Commons::ConversionException) {
335                         return JSTizenExceptionFactory::postException(context, exception, 
336                                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);        
337                         }
338
339 //                      LogInfo(">>>");
340 //                      return JSValueMakeUndefined(context);
341                 }
342                 else
343                 {
344                         LogDebug(" Private Object is NULL ");
345                         return JSTizenExceptionFactory::postException(context, exception, 
346                                         JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND);
347                 }
348
349         }
350
351 JSValueRef JSMessagingService::sendMessage(JSContextRef context,
352         JSObjectRef function,
353         JSObjectRef thisObject,
354         size_t argumentCount,
355         const JSValueRef arguments[],
356         JSValueRef* exception)
357 {
358     LogDebug("entered");
359
360     //check permission.
361     AceSecurityStatus status = MESSAGING_CHECK_ACCESS(
362                 MessagingExportedNames[MESSAGING_FUNCTION_API_SEND_MESSAGE]);
363         TIZEN_SYNC_ACCESS_HANDLER(status, context, exception);
364
365     JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));
366
367     if (!priv) {
368         LogError("Null pointer");
369         return JSTizenExceptionFactory::postException(context, exception, 
370                            JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);         
371     }
372
373     JSContextRef globalContext = priv->getContext();
374     LogInfo(">>> argument count : " << argumentCount);
375
376     if (argumentCount < 1) {
377                 return JSTizenExceptionFactory::postException(context, exception, 
378                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
379     }
380
381     WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext);
382     WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr recipientCallbackManager;
383
384     callbackManager->setObject(thisObject);
385
386     ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context);   
387
388 Try {
389                 //argu 1. Message ( mandatory )
390                 if (!JSValueIsObject(context, arguments[0])  || JSIsArrayValue(context, arguments[0]))
391                 {
392                         LogDebug("arguments is invaild");
393                         ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception");
394                 }
395                 
396                 IMessagePtr msg = converter->toIMessage(arguments[0]);
397                 
398                 //argu 2. Success callback (optional)
399                 if ( argumentCount > 1)
400                 {
401                         if ( JSValueIsObject(context, arguments[1]) || Validator(context).isCallback(arguments[1]))
402                         {
403                                 MessageSendCallback callbacks = converter->toMessageSendCallback(arguments[1]);                 
404                                                         
405                                 if (!(JSValueIsUndefined(context, callbacks.onSuccess) || JSValueIsNull(context, callbacks.onSuccess)) )
406                                 {
407                                         callbackManager->setOnSuccess( converter->toFunctionOrNull(callbacks.onSuccess) );
408                                 }
409                                 else
410                                 {
411                                         callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1]));
412                                 }
413                         }
414                         else
415                         {       
416                                 ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception");
417                         }
418                 }
419                 //argu 3. error callback (optional & nullable)
420                 if ( argumentCount > 2)
421                 {
422                         if ( Validator(context).isCallback(arguments[2]))
423                                 callbackManager->setOnError(arguments[2]);
424                         else if(Validator(context).isNullOrUndefined(arguments[2]))
425                                 callbackManager->setOnError(NULL);
426                         else
427                                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
428                 }
429            //create PrivateData
430         EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager, recipientCallbackManager) );
431
432         //EventSendMessagePtr event(new EventSendMessage());
433          EventMessagingServicePtr event(new EventMessagingService());
434
435         IMessagingServicePtr imessagingService = priv->getObject();
436         
437         event->opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_SEND_MESSAGE);
438         event->setEventType(MESSAGING_SERVICE_EVENT_TYPE_SEND_MESSAGE);
439         event->m_message = msg;
440         imessagingService->setMessageToOpId( event->opId, event->m_message);
441         event->store = true;            //always store message in sendbox after send , email Type.
442         event->m_messagingService = imessagingService;
443         event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData>(privateData));
444         event->setForAsynchronousCall(&MessagingController::getInstance());
445      
446         ReqReceiverMessageSingleton::Instance().sendMessage(event);     //send message
447         MessageAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, globalContext);
448 #if 0 //Pending Operation.
449         DPL::SharedPtr<IExternEventCanceler<EventMessagingService> > eventCanceller =
450                 DPL::StaticPointerCast<IExternEventCanceler<EventMessagingService> >(imessagingService);
451
452         IJSExtCancelPendingOperationPrivateObject<EventMessagingService> *gcPendingOperation =
453                 new IJSExtCancelPendingOperationPrivateObject<EventMessagingService>(event, eventCanceller);
454
455         return JSObjectMake(globalContext, JSPendingOperation::getClassRef(), gcPendingOperation);
456 #endif                  
457         //return converter->toJSValueRef(event->opId);
458
459         return JSValueMakeUndefined(context);
460     }
461     Catch(WrtDeviceApis::Commons::ConversionException) {
462                 return JSTizenExceptionFactory::postException(context, exception, 
463                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);        
464     }
465     Catch(WrtDeviceApis::Commons::NullPointerException) {
466                 return JSTizenExceptionFactory::postException(context, exception, 
467                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);        
468     }
469     Catch(WrtDeviceApis::Commons::InvalidArgumentException) {
470                 return JSTizenExceptionFactory::postException(context, exception, 
471                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);        
472     }
473
474 //    return JSValueMakeNull(context);
475 }
476
477 JSValueRef JSMessagingService::loadMessageBody(JSContextRef context,
478         JSObjectRef function,
479         JSObjectRef thisObject,
480         size_t argumentCount,
481         const JSValueRef arguments[],
482         JSValueRef* exception)
483 {
484     LogDebug("entered");
485
486         //check permission.
487         AceSecurityStatus status = MESSAGING_CHECK_ACCESS(
488                 MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_BODY]);
489                 TIZEN_SYNC_ACCESS_HANDLER(status, context, exception);
490
491     JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));
492
493     if (!priv) {
494         LogError("Null pointer");
495                 return JSTizenExceptionFactory::postException(context, exception, 
496                    JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);
497     }
498
499     JSContextRef globalContext = priv->getContext();            //create global Context
500     LogInfo(">>> argument count : " << argumentCount);
501
502         if (argumentCount < 2) {
503                 return JSTizenExceptionFactory::postException(context, exception, 
504                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
505         }
506
507         Validator check(context, exception);    //create check
508
509         WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext);
510         callbackManager->setObject(thisObject);
511         
512         ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter
513
514         Try {
515                         //argu 1. message (mandatory)
516                         if (!JSValueIsObject(context, arguments[0]) || JSIsArrayValue(context, arguments[0]))
517                         {
518                                 ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception");
519                         }
520                         //argu 2. success callback
521                         if ( Validator(context).isCallback(arguments[1]))
522                         {
523                                 callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1]));
524                         }
525                         else
526                         {
527                                 ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception");
528                         }
529                         
530                         //argu 3. error callback (optional & nullable)
531                         if ( argumentCount > 2)
532                         {
533                                 if ( check.isCallback(arguments[2]))
534                                         callbackManager->setOnError(arguments[2]);
535                                 else if(check.isNullOrUndefined(arguments[2]))
536                                         callbackManager->setOnError(NULL);
537                                 else
538                                         Throw(WrtDeviceApis::Commons::InvalidArgumentException);
539                         }
540                         else
541                         {
542                                 callbackManager->setOnError(NULL);
543                         }
544                 }
545                 Catch(WrtDeviceApis::Commons::ConversionException) {
546                         return JSTizenExceptionFactory::postException(context, exception, 
547                                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
548                 }
549                 Catch(WrtDeviceApis::Commons::InvalidArgumentException) {
550                         return JSTizenExceptionFactory::postException(context, exception, 
551                                                                 JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
552                 }
553                 Catch(WrtDeviceApis::Commons::PlatformException) {
554                         return JSTizenExceptionFactory::postException(context, exception, 
555                                                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN);
556                 }
557
558         Try {
559                         IMessagePtr msg = converter->toIMessage(arguments[0]);
560                          LogInfo(" checked toIMessages " );             
561                         //create event
562                         EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) );
563                         EventMessagingServicePtr event(new EventMessagingService());     
564                         event->m_message = msg;
565
566                         if ( event->m_message )
567                         {       
568                                 int msgType = event->m_message->getMessageType();
569                                 
570                                 if (msgType == EMAIL)
571                                 {
572                                         IEmailPtr email = MessageFactory::convertToEmail(event->m_message);
573                                         if (email && email->isBodyDownloaded() > 0)
574                                         {
575                                                 callbackManager->callOnSuccess(converter->toJSValueRef(msg));
576                                                 return JSValueMakeNull(context);
577                                         }
578                                 }
579                                 else
580                                 {
581                                         callbackManager->callOnSuccess(converter->toJSValueRef(msg));
582                                                 return JSValueMakeNull(context);
583                                 }
584
585                                 privateData->setMessageJSValueRef(arguments[0]);        //set Message JSValueRef.
586                         }
587                         LogInfo(" Checked Message Type " );
588                         
589                         IMessagingServicePtr imessagingService = priv->getObject();
590                         int opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_DOWNLOAD_BODY);
591                         LogDebug("Operation ID is = " << opId);
592
593                         event->opId = opId;
594                         imessagingService->setMessageToOpId(opId, event->m_message);
595                         event->setEventType(MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_BODY);
596                         event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData>(privateData));
597                         event->setForAsynchronousCall(&MessagingController::getInstance());
598
599                         ReqReceiverMessageSingleton::Instance().loadMessageBody(event); //load message Body
600                         MessageAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, globalContext);
601 #if 0
602                         DPL::SharedPtr<IExternEventCanceler<EventMessagingService> > eventCanceller =
603                                 DPL::StaticPointerCast<IExternEventCanceler<EventMessagingService> >(imessagingService);
604
605                         IJSExtCancelPendingOperationPrivateObject<EventMessagingService> *gcPendingOperation =
606                                 new IJSExtCancelPendingOperationPrivateObject<EventMessagingService>(event, eventCanceller);
607
608                         return JSObjectMake(globalContext, JSPendingOperation::getClassRef(), gcPendingOperation);
609 #endif
610                         //return converter->toJSValueRef(event->opId);
611                         return JSValueMakeUndefined(context);
612         }
613         Catch(WrtDeviceApis::Commons::NullPointerException) {
614                 callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
615                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT));
616                 return JSValueMakeNull(context);
617         }
618         Catch(WrtDeviceApis::Commons::ConversionException) {
619                 callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
620                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT));
621                 return JSValueMakeNull(context);
622         }
623         Catch(WrtDeviceApis::Commons::Exception) {
624                 callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
625                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN));
626                 return JSValueMakeNull(context);
627         }
628
629 //      return JSValueMakeNull(context);
630
631 }
632
633 JSValueRef JSMessagingService::loadMessageAttachment(JSContextRef context,
634         JSObjectRef function,
635         JSObjectRef thisObject,
636         size_t argumentCount,
637         const JSValueRef arguments[],
638         JSValueRef* exception)
639 {
640         LogDebug("entered");
641
642         //check permission.
643         AceSecurityStatus status = MESSAGING_CHECK_ACCESS(
644                 MessagingExportedNames[MESSAGING_FUNCTION_API_LOAD_MESSAGE_ATTACHMENT]);
645                 TIZEN_SYNC_ACCESS_HANDLER(status, context, exception);
646
647         JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));
648
649         if (!priv) {
650                 LogError("Private Object is Null pointer");
651                 return JSTizenExceptionFactory::postException(context, exception, 
652                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);
653         }
654         
655         JSContextRef globalContext = priv->getContext();                //create global Context
656         LogInfo(">>> argument count : " << argumentCount);
657
658         if (argumentCount < 2) {
659                 return JSTizenExceptionFactory::postException(context, exception, 
660                                 JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
661         }
662
663         Validator check(context, exception);    //create check
664
665         WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext);
666         callbackManager->setObject(thisObject);
667         ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter
668
669         Try {
670
671                 //argu 1. Attachment (mandatory)
672                 if (!JSValueIsObject(context, arguments[0]) || JSIsArrayValue(context, arguments[0]))
673                 {
674                         ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception");
675                 }
676                                 
677                 //argu 2. success callback
678                 if ( check.isCallback(arguments[1]))
679                         callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1]));
680                 else
681                         ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception");
682
683                 //argu 3. error callback (optional & nullable)
684                 if ( argumentCount > 2)
685                 {
686                         if ( check.isCallback(arguments[2]))
687                                 callbackManager->setOnError(arguments[2]);
688                         else if(check.isNullOrUndefined(arguments[2]))
689                                 callbackManager->setOnError(NULL);
690                         else
691                                 Throw(WrtDeviceApis::Commons::InvalidArgumentException);
692                 }
693                 else{
694                         callbackManager->setOnError(NULL);
695                 }
696
697         }
698         Catch(WrtDeviceApis::Commons::ConversionException) {
699                         return JSTizenExceptionFactory::postException(context, exception, 
700                                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
701         }
702         Catch(WrtDeviceApis::Commons::InvalidArgumentException) {
703                         return JSTizenExceptionFactory::postException(context, exception, 
704                                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
705         }
706         Catch(WrtDeviceApis::Commons::Exception) {
707                         return JSTizenExceptionFactory::postException(context, exception, 
708                                         JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN);
709         }
710
711
712         EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) );
713
714         if (!privateData)
715                 return JSTizenExceptionFactory::postException(context, exception,
716                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN);
717
718         Try {
719                 IAttachmentPtr iAttchmentPtr = converter->toIAttachment(arguments[0]);
720                 LogInfo("iAttchmentPtr->getDownloaded() : " << iAttchmentPtr->getDownloaded());
721                 if(iAttchmentPtr->getDownloaded() > 0)
722                 {
723                         callbackManager->callOnSuccess(converter->toJSValueRef(iAttchmentPtr));
724                         return JSValueMakeNull(context);
725                 }
726
727                 EventMessagingServicePtr event(new EventMessagingService());     //create event
728                 event->setEventType(MESSAGING_SERVICE_EVENT_TYPE_LOAD_MESSAGE_ATTACHMENT);
729                 event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData>(privateData));
730                 event->setForAsynchronousCall(&MessagingController::getInstance());
731
732                 event->m_attachment = iAttchmentPtr;
733                 event->m_message = event->m_attachment->getMessage();
734
735                 privateData->setMessageJSValueRef(arguments[0]); //set attachment JSValueRef.
736
737                 IMessagingServicePtr imessagingService = priv->getObject();
738                 if (imessagingService)
739                 {
740                         int opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_DOWNLOAD_ATTACHMENT);
741                         LogDebug("Operation ID is = " << opId);
742
743                         event->opId = opId;
744                         imessagingService->setMessageToOpId(opId, event->m_message);
745
746                         //JSValueRef pendingOperation = WrtDeviceApis::CommonsJavaScript::makePendingOperation(globalContext, event);   //create pendingOperation.
747                         ReqReceiverMessageSingleton::Instance().loadMessageAttachment(event);   //load message Body
748                         MessageAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, globalContext);
749 #if 0
750                         DPL::SharedPtr<IExternEventCanceler<EventMessagingService> > eventCanceller =
751                         DPL::StaticPointerCast<IExternEventCanceler<EventMessagingService> >(imessagingService);
752
753                         IJSExtCancelPendingOperationPrivateObject<EventMessagingService> *gcPendingOperation =
754                                         new IJSExtCancelPendingOperationPrivateObject<EventMessagingService>(event, eventCanceller);
755
756                         return JSObjectMake(globalContext, JSPendingOperation::getClassRef(), gcPendingOperation);
757 #endif
758                         //return converter->toJSValueRef(event->opId);
759                         return JSValueMakeUndefined(context);
760
761                 }
762                 else
763                 {
764                         return JSTizenExceptionFactory::postException(context, exception,
765                                         JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND);
766                 }
767
768         }
769         Catch(WrtDeviceApis::Commons::NullPointerException) {
770                 callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,
771                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT));
772                 return JSValueMakeNull(context);
773         }
774         Catch(WrtDeviceApis::Commons::Exception) {
775                 callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,
776                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN));
777                 return JSValueMakeNull(context);
778         }
779 //      return JSValueMakeUndefined(context);
780 }
781
782 JSValueRef JSMessagingService::sync(JSContextRef context, JSObjectRef function, JSObjectRef thisObject,
783                         size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
784 {
785
786         LogDebug("entered");
787
788         //check permission.
789         AceSecurityStatus status = MESSAGING_CHECK_ACCESS(
790                 MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC]);
791         TIZEN_SYNC_ACCESS_HANDLER(status, context, exception);
792
793         JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));
794
795         if (priv) {
796
797                 JSContextRef globalContext = priv->getContext();                //get global Context
798
799                 LogInfo(">>> argument count : " << argumentCount);
800
801 //              if (argumentCount < 2 ) {
802 //                      return JSTizenExceptionFactory::postException(context, exception, 
803 //                              JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
804 //              }
805
806                 Validator check(context, exception);    //check context
807
808                 WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext);
809                 callbackManager->setObject(thisObject);
810                 ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter
811
812                 IMessagingServicePtr imessagingService = priv->getObject();                             //get MessagingService.
813
814                 MessageType msgType = (MessageType)imessagingService->getType();
815                 LogInfo("msgType :" << msgType);
816
817
818                         
819                 Try {
820
821                         int limit = -1; //sync limit
822                         //argu 1. success  callback ( nullable )
823                         if (argumentCount > 0)
824                         {
825                                 if ( check.isCallback(arguments[0]))
826                                 {
827                                         callbackManager->setOnSuccess(arguments[0]);
828                                 }
829                                 else if(check.isNullOrUndefined(arguments[0]))
830                                 {
831                                         callbackManager->setOnSuccess(NULL);
832                                 }
833                                 else
834                                 {
835                                         Throw(WrtDeviceApis::Commons::ConversionException);
836                                 }
837                         }
838                         else{
839                                         callbackManager->setOnSuccess(NULL);
840                         }
841                         //argu 2. error callback ( nullable )
842                         if (argumentCount > 1)
843                         {
844
845                                 if ( check.isCallback(arguments[1]))
846                                         callbackManager->setOnError(arguments[1]);
847                                 else if(check.isNullOrUndefined(arguments[1]))
848                                         callbackManager->setOnError(NULL);
849                                 else
850                                         Throw(WrtDeviceApis::Commons::ConversionException);
851                         }
852                         else{
853                                         callbackManager->setOnError(NULL);
854                         }
855                         //argu 3. limit ( optional )
856                         if(argumentCount > 2)
857                         {
858                                 if (!Validator(context).isNullOrUndefined(arguments[2]))
859                                 {
860                                         limit = converter->toInt(arguments[2]);
861                                 }
862                         }
863
864                         EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) );
865                         EventMessagingServicePtr event(new EventMessagingService());     //create event         
866
867                         LogDebug("limit : " << limit);
868
869                         event->opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_SYNC);
870                         event->m_sync_account_id = imessagingService->getAccountID() ;
871                         event->m_sync_limit = limit;
872                         event->m_messagingService = imessagingService;
873                         imessagingService->setEventToOpId(event->opId, event);
874
875                         event->setEventType(MESSAGING_SERVICE_EVENT_TYPE_SYNC);
876                         event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData>(privateData));
877                         event->setForAsynchronousCall(&MessagingController::getInstance());
878
879                         ReqReceiverMessageSingleton::Instance().sync(event);    //load message Body
880                         MessageAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, globalContext);
881 #if 0
882                                 DPL::SharedPtr<IExternEventCanceler<EventMessagingService> > eventCanceller =
883                                         DPL::StaticPointerCast<IExternEventCanceler<EventMessagingService> >(imessagingService);
884                          
885                                 IJSExtCancelPendingOperationPrivateObject<EventMessagingService> *gcPendingOperation =
886                                          new IJSExtCancelPendingOperationPrivateObject<EventMessagingService>(event, eventCanceller);
887
888                                 return JSObjectMake(globalContext, JSPendingOperation::getClassRef(), gcPendingOperation);
889 #endif          
890                         return converter->toJSValueRef(event->opId);
891                         
892                 }
893                 Catch(WrtDeviceApis::Commons::ConversionException) {
894                         LogError(">>> TypeMismatchException");
895                         return JSTizenExceptionFactory::postException(context, exception, 
896                                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
897                 }
898                 Catch(WrtDeviceApis::Commons::NullPointerException) {
899                         LogError(">>> TypeMismatchException");
900                         return JSTizenExceptionFactory::postException(context, exception, 
901                                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
902                 }
903                 Catch(WrtDeviceApis::Commons::InvalidArgumentException) {
904                         callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
905                                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT));
906                 }
907                 Catch(WrtDeviceApis::Commons::PlatformException) {
908                         callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
909                                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN));
910                 }
911         
912         }
913         else
914         {               
915                 LogError("Null pointer");
916                 return JSTizenExceptionFactory::postException(context, exception, 
917                    JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);
918         }
919
920         return JSValueMakeNull(context);
921
922 }
923
924
925 JSValueRef JSMessagingService::syncFolder(JSContextRef context, JSObjectRef function, JSObjectRef thisObject,
926                         size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
927 {
928         LogDebug("entered");
929
930         //check permission
931         AceSecurityStatus status = MESSAGING_CHECK_ACCESS(
932                 MessagingExportedNames[MESSAGING_FUNCTION_API_SYNC_FOLDER]);
933         TIZEN_SYNC_ACCESS_HANDLER(status, context, exception);
934
935         JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));
936
937         if (priv) {
938                 JSContextRef globalContext = priv->getContext();                //get global Context
939
940                 LogInfo(">>> argument count : " << argumentCount);
941
942                 if (argumentCount < 1) {
943                         return JSTizenExceptionFactory::postException(context, exception, 
944                                 JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
945                 }
946
947                 Validator check(context, exception);    //check context
948
949                 WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = JSCallbackManager::createObject(globalContext);
950                 callbackManager->setObject(thisObject);
951                 ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(globalContext); //create converter
952
953                 IMessagingServicePtr imessagingService = priv->getObject();                     //get MessagingService.
954
955                 MessageType msgType = (MessageType)imessagingService->getType();
956                 LogInfo("msgType :" << msgType);
957
958                 Try {
959
960                         int limit = -1;
961                         //argu 1. Folder (mandatory)
962                         if (!JSValueIsObject(context, arguments[0]) || JSIsArrayValue(context, arguments[0]))
963                         {
964                                 Throw(WrtDeviceApis::Commons::ConversionException);
965                         }
966                         IMessageFolderPtr folder = converter->toIMessageFolder(arguments[0]);           
967                         LogInfo("check :");
968                         //argu 2. success callback.
969                         if ( argumentCount > 1)
970                         {
971                                 if (Validator(context).isCallback(arguments[1]))
972                                         callbackManager->setOnSuccess(converter->toFunctionOrNull(arguments[1]));
973                                 else if(check.isNullOrUndefined(arguments[1]))
974                                         callbackManager->setOnSuccess(NULL);
975                                 else
976                                         Throw(WrtDeviceApis::Commons::ConversionException);
977                         }
978                         else{
979                                         callbackManager->setOnSuccess(NULL);
980                         }
981                         //argu 3. error callback (optional & nullable)
982                         if ( argumentCount > 2)
983                         {
984                                 if ( check.isCallback(arguments[2]))
985                                         callbackManager->setOnError(arguments[2]);
986                                 else if(check.isNullOrUndefined(arguments[2]))
987                                         callbackManager->setOnError(NULL);
988                                 else
989                                         Throw(WrtDeviceApis::Commons::ConversionException);
990                         }
991                         else{
992                                         callbackManager->setOnError(NULL);
993                         }
994                         //argu 4. limit ( optional )
995                         if(argumentCount > 3)
996                         {
997                                 if (!Validator(context).isNullOrUndefined(arguments[3]))
998                                 {
999                                         limit = converter->toInt(arguments[3]);
1000                                 }
1001                         }
1002                         
1003                         EventMessagingServicePtr event(new EventMessagingService());     //create event                         
1004                         EventMessagingServicePrivateDataPtr privateData( new EventMessagingServicePrivateData(callbackManager) );
1005                                 
1006                                 if ( folder )
1007                                 {
1008                                     event->m_folder_name = folder->getPath();           //it will be changed to the folder ptr
1009                                     event->m_sync_folder_id = folder->getId();          //it will be changed to the folder ptr
1010                                 }
1011
1012                                 LogDebug("limit : " << limit);
1013                                 LogDebug("folderName : " << event->m_folder_name);
1014                                 event->opId = imessagingService->createOpId(MESSAGING_SERVICE_OP_SYNC_FOLDER);
1015                                 event ->m_sync_account_id = imessagingService->getAccountID() ;
1016                                 event ->m_sync_limit = limit;
1017                                 event->m_messagingService = imessagingService;
1018                                 imessagingService->setEventToOpId(event->opId, event);
1019
1020                                 event->setEventType(MESSAGING_SERVICE_EVENT_TYPE_SYNC_FOLDER);
1021                                 event->setPrivateData(DPL::StaticPointerCast<WrtDeviceApis::Commons::IEventPrivateData>(privateData));
1022                                 event->setForAsynchronousCall(&MessagingController::getInstance());
1023
1024                                 ReqReceiverMessageSingleton::Instance().syncFolder(event);      //load message Body
1025                                 MessageAsyncCallbackManagerSingleton::Instance().registerCallbackManager(callbackManager, globalContext);
1026
1027 #if 0
1028                                 DPL::SharedPtr<IExternEventCanceler<EventMessagingService> > eventCanceller =
1029                                         DPL::StaticPointerCast<IExternEventCanceler<EventMessagingService> >(imessagingService);
1030                                 
1031                                 IJSExtCancelPendingOperationPrivateObject<EventMessagingService> *gcPendingOperation =
1032                                         new IJSExtCancelPendingOperationPrivateObject<EventMessagingService>(event, eventCanceller);
1033                                 
1034                                 return JSObjectMake(globalContext, JSPendingOperation::getClassRef(), gcPendingOperation);
1035 #endif          
1036                                 return converter->toJSValueRef(event->opId);
1037                 }
1038                 Catch(WrtDeviceApis::Commons::UnsupportedException) {
1039                         return JSTizenExceptionFactory::postException(context, exception, 
1040                                         JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED);
1041                 }
1042                 Catch(WrtDeviceApis::Commons::ConversionException) {
1043                         return JSTizenExceptionFactory::postException(context, exception, 
1044                                         JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
1045                 }
1046                 Catch(WrtDeviceApis::Commons::NullPointerException) {
1047                         callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
1048                                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT));
1049                         return JSValueMakeNull(context);
1050                 }
1051                 Catch(WrtDeviceApis::Commons::InvalidArgumentException) {
1052                         callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
1053                                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT));
1054                         return JSValueMakeNull(context);
1055                 }
1056                 Catch(WrtDeviceApis::Commons::PlatformException) {
1057                         callbackManager->callOnError(JSTizenExceptionFactory::makeErrorObject(context,          
1058                                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN));
1059                 }
1060                 
1061         }
1062         else
1063         {
1064                 LogError("Null pointer");
1065                 return JSTizenExceptionFactory::postException(context, exception, 
1066                    JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);
1067         }
1068
1069         return JSValueMakeNull(context);
1070
1071
1072 }
1073
1074 JSValueRef JSMessagingService::cancelOperation(JSContextRef context, JSObjectRef function, JSObjectRef thisObject,
1075                         size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
1076 {
1077         LogDebug("entered");
1078
1079         JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));    //get private object
1080
1081         if (priv)
1082         {
1083                 IMessagingServicePtr imessagingService = priv->getObject();
1084                 Try
1085                 {
1086                         LogInfo(">>> argument count : " << argumentCount);
1087
1088                         if ( argumentCount == 1 && !Validator(context).isCallback(arguments[0]))
1089                         {
1090                                 ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context);
1091                                 MessageType msgType = (MessageType)imessagingService->getType();
1092                                 LogInfo("msgType :" << msgType);
1093
1094                                 int opId = converter->toLong( arguments[0] );   //Fetch operation ID
1095                                 int handle = imessagingService->getHandleFromOpId(opId);
1096                                 if ( handle < 0 )
1097                                 {
1098                                         ThrowMsg(WrtDeviceApis::Commons::NotFoundException,"Operation ID Not found");
1099                                 }
1100                                 
1101                                 int opType = imessagingService->getOpTypeFromOpId(opId);
1102                                 LogInfo("operation ID :" << opId << " operation Type : "  << opType);                   
1103
1104                                 if ( opType == MESSAGING_SERVICE_OP_SEND_MESSAGE)
1105                                 {       
1106                                         IMessagePtr msg = imessagingService->getMessageFromOpId(opId);
1107                                         if (msg)
1108                                         {
1109                                                 LogDebug("Call Cancel Function");
1110                                                 msg->sendCancel(handle);
1111                                                 imessagingService->deleteOpId(opId);
1112                                         }
1113                                 }
1114                                 else
1115                                 {       //for email.
1116                                         if (msgType == EMAIL)
1117                                         {       
1118                                                 IMessagePtr msg = imessagingService->getMessageFromOpId(opId);
1119                                                 IEmailPtr email = MessageFactory::convertToEmail(msg);
1120                                                         
1121                                                 if ( opType == MESSAGING_SERVICE_OP_DOWNLOAD_BODY )
1122                                                 {       
1123                                                         LogDebug("Cancel Download Body , handle = " << handle);
1124                                                         email->downloadBodyCancel(handle);
1125                                                 }
1126                                                 else if ( opType == MESSAGING_SERVICE_OP_DOWNLOAD_ATTACHMENT)
1127                                                 {
1128                                                         LogDebug("Cancel Download Attachment , handle = " << handle);
1129                                                         email->downloadAttachmentCancel(handle);
1130                                                 }
1131                                                 else if (  opType == MESSAGING_SERVICE_OP_SYNC )
1132                                                 {       
1133                                                         LogDebug("Cancel Sync , handle = " << handle);
1134                                                         imessagingService->syncCancel(handle);
1135                                                 }
1136                                                 else if ( opType == MESSAGING_SERVICE_OP_SYNC_FOLDER )
1137                                                 {
1138                                                         LogDebug("Cancel Sync Folder, handle = " << handle);
1139                                                         imessagingService->syncFolderCancel(handle);
1140                                                 }
1141                                                 imessagingService->deleteOpId(opId);
1142                                         }
1143                                         else
1144                                         {
1145                                                 ThrowMsg(WrtDeviceApis::Commons::UnsupportedException, "Operation Type is mismatched");
1146                                         }
1147                                 }
1148                                 
1149                         }
1150                         else
1151                         {
1152                                 ThrowMsg(WrtDeviceApis::Commons::InvalidArgumentException,"invalid argument exception");
1153                         }
1154
1155                 }
1156                 Catch (WrtDeviceApis::Commons::InvalidArgumentException){
1157                         LogError("Exception: " << _rethrown_exception.GetMessage());
1158                         return JSTizenExceptionFactory::postException(context, exception, 
1159                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);                                            
1160                 }
1161                 Catch (WrtDeviceApis::Commons::NotFoundException){
1162                         LogError("Exception: " << _rethrown_exception.GetMessage());
1163                         return JSTizenExceptionFactory::postException(context, exception, 
1164                                 JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND);                                                
1165                 }
1166                 Catch (WrtDeviceApis::Commons::UnsupportedException){
1167                         LogError("Exception: " << _rethrown_exception.GetMessage());
1168                         return JSTizenExceptionFactory::postException(context, exception, 
1169                                 JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED);                                                
1170                 } 
1171                 Catch (WrtDeviceApis::Commons::Exception){
1172                         LogError("Exception: " << _rethrown_exception.GetMessage());
1173                         return JSTizenExceptionFactory::postException(context, exception, 
1174                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN);                    
1175                 }
1176                 
1177         }
1178         else
1179         {       
1180                 LogDebug(" Private Object is NULL ");
1181                 return JSTizenExceptionFactory::postException(context, exception, 
1182                                         JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND);
1183         }
1184
1185         LogDebug(">>>");
1186         return JSValueMakeUndefined(context);
1187 }
1188
1189 JSValueRef JSMessagingService::stopSync(JSContextRef context, JSObjectRef function, JSObjectRef thisObject,
1190                         size_t argumentCount, const JSValueRef arguments[], JSValueRef* exception)
1191 {
1192         LogDebug("entered");
1193
1194         JSMessagingServicePriv* priv = static_cast<JSMessagingServicePriv*>(JSObjectGetPrivate(thisObject));    //get private object
1195
1196         if (priv)
1197         {
1198                 IMessagingServicePtr imessagingService = priv->getObject();
1199                 Try
1200                 {
1201                         LogInfo(">>> argument count : " << argumentCount);
1202
1203                         if ( argumentCount < 1 )
1204                         {
1205                                 return JSTizenExceptionFactory::postException(context, exception, 
1206                                                 JSTizenException::TYPE_MISMATCH_ERROR, JSMESSAGING_EXCEPTION_MSG_TYPE_MISMATCH);
1207                         }
1208
1209                                 ConverterMessageFactory::ConverterType converter = ConverterMessageFactory::getConverter(context);
1210                                 MessageType msgType = (MessageType)imessagingService->getType();
1211                                 LogInfo("msgType :" << msgType);
1212
1213                                 int opId = converter->toLong( arguments[0]);    //Fetch operation ID
1214                                 int handle = imessagingService->getHandleFromOpId(opId);
1215                                 if ( handle < 0 )
1216                                 {
1217                                         ThrowMsg(WrtDeviceApis::Commons::NotFoundException,"Operation ID Not found");
1218                                 }
1219                                 
1220                                 int opType = imessagingService->getOpTypeFromOpId(opId);
1221                                 LogInfo("operation ID :" << opId << " operation Type : "  << opType);
1222
1223                                 if (msgType == EMAIL)
1224                                 {                       
1225                                         if (  opType == MESSAGING_SERVICE_OP_SYNC )
1226                                         {       
1227                                                 LogDebug("Cancel Sync , handle = " << handle);
1228                                                 imessagingService->syncCancel(handle);
1229                                         }
1230                                         else if ( opType == MESSAGING_SERVICE_OP_SYNC_FOLDER )
1231                                         {
1232                                                 LogDebug("Cancel Sync Folder, handle = " << handle);
1233                                                 imessagingService->syncFolderCancel(handle);
1234                                         }
1235
1236                                         //call error callback.
1237                                         EventMessagingServicePtr event = imessagingService->getEventFromOpId(opId);
1238                                         if (event)
1239                                         {
1240                                                 LogDebug("get callback Manager");
1241                                                 EventMessagingServicePrivateDataPtr privateData = 
1242                                                         DPL::StaticPointerCast<EventMessagingServicePrivateData>(event->getPrivateData());
1243         
1244                                                 WrtDeviceApis::CommonsJavaScript::JSCallbackManagerPtr callbackManager = privateData->getCallbackManager();             //get callback manager
1245                                                 JSContextRef globalContext = callbackManager->getContext();
1246                                                 if (callbackManager)
1247                                                 {
1248                                                         LogDebug("call error callback.");
1249                                                         callbackManager->callOnError(JSDOMExceptionFactory::AbortException.make(globalContext, JSMESSAGING_EXCEPTION_MSG_ABORT_ERROR));
1250                                                 }
1251                                         }
1252
1253                                         imessagingService->deleteOpId(opId);
1254
1255                                 }
1256                                 else
1257                                 {
1258                                         ThrowMsg(WrtDeviceApis::Commons::UnsupportedException, "Operation Type is mismatched");
1259                                 }
1260                                 
1261
1262                 }
1263                 Catch (WrtDeviceApis::Commons::InvalidArgumentException){
1264                         LogError("Exception: " << _rethrown_exception.GetMessage());
1265                         return JSTizenExceptionFactory::postException(context, exception, 
1266                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);                                            
1267                 }
1268                 Catch (WrtDeviceApis::Commons::NotFoundException){
1269                         LogError("Exception: " << _rethrown_exception.GetMessage());
1270                         return JSTizenExceptionFactory::postException(context, exception, 
1271                                 JSTizenException::INVALID_VALUES_ERROR, JSMESSAGING_EXCEPTION_MSG_INVALID_ARGUMENT);
1272                 }
1273                 Catch (WrtDeviceApis::Commons::UnsupportedException){
1274                         LogError("Exception: " << _rethrown_exception.GetMessage());
1275                         return JSTizenExceptionFactory::postException(context, exception, 
1276                                 JSTizenException::NOT_SUPPORTED_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_SUPPORTED);                                                
1277                 } 
1278                 Catch (WrtDeviceApis::Commons::Exception){
1279                         LogError("Exception: " << _rethrown_exception.GetMessage());
1280                         return JSTizenExceptionFactory::postException(context, exception, 
1281                                 JSTizenException::UNKNOWN_ERROR, JSMESSAGING_EXCEPTION_MSG_UNKNOWN);                    
1282                 }
1283                 
1284         }
1285         else
1286         {       
1287                 LogDebug(" Private Object is NULL ");
1288                 return JSTizenExceptionFactory::postException(context, exception, 
1289                                         JSTizenException::NOT_FOUND_ERROR, JSMESSAGING_EXCEPTION_MSG_NOT_FOUND);
1290         }
1291
1292         LogDebug(">>>");
1293         return JSValueMakeUndefined(context);
1294 }
1295
1296
1297 }
1298 }
1299