summaryrefslogtreecommitdiffstats
path: root/src/messaging/qmessageservice_win.cpp
blob: ac8bd159f00d0f00bc488e37e851ce7bd6c873c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmessageservice.h"
#include "winhelpers_p.h"
#include "qmessagemanager.h"
#include "qmessageid_p.h"
#include "qmessagefolderid_p.h"
#include "qmessageaccountid_p.h"
#include "qmessage_p.h"
#include "qmessagestore_p_p.h"
#include "qmessagecontentcontainer_p.h"
#include "qmessagecontentcontainerid_p.h"
#include <QDebug>
#include <QThread>
#include <QTimer>
#include <mapix.h>
#include <objbase.h>
#include <mapiutil.h>
#include <qmobilityglobal.h>
#ifdef _WIN32_WCE
#include <cemapi.h>
#endif

using namespace QtMobility::WinHelpers;

QTM_BEGIN_NAMESPACE

static const unsigned long SmsCharLimit = 160;

class QMessageServicePrivate : public QObject
{
    Q_OBJECT

    Q_DECLARE_PUBLIC(QMessageService)

public:
    QMessageServicePrivate(QMessageService* parent);
    ~QMessageServicePrivate();

    bool send(const QMessage& message, bool showComposer = false);
    bool show(const QMessageId& id);
#ifdef _WIN32_WCE
    bool isPartiallyDownloaded(const QMessageId& id, bool considerAttachments = false);
    bool markForDownload(const QMessageId& id, bool includeAttachments = false);
    bool synchronize(const QMessageAccountId& id);
    bool registerUpdates(const QMessageId& id);
    void unregisterUpdates();
    bool retrieveBody(const QMessage& partialMessage);
#endif

    void setFinished(bool successful);

public slots:
    void completed();
    void reportMatchingIds();
    void reportMessagesCounted();

#ifdef _WIN32_WCE
    void messageUpdated(const QMessageId& id);
#endif

signals:
    void stateChanged(QMessageService::State);
    void messagesFound(const QMessageIdList&);
    void messagesCounted(int);
    void progressChanged(uint, uint);

public:
    QMessageService* q_ptr;
    QMessageManager _manager;
    bool _active;
    QMessageManager::Error _error;
    QMessageIdList _candidateIds;
    int _count;
    QMessageService::State _state;
    QMessageId m_bodyDownloadTarget;
    QMessageManager::NotificationFilterId m_bodyDownloadFilterId;
    bool m_registeredUpdates;
    QThread *m_queryThread;
    QList<QThread*> m_obsoleteThreads;
};

namespace {

class QueryThread : public QThread
{
    Q_OBJECT

    QMessageServicePrivate *_parent;
    QMessageFilter _filter;
    QString _body;
    QMessageDataComparator::MatchFlags _matchFlags;
    QMessageSortOrder _ordering;
    uint _limit;
    uint _offset;

    // Ensure that the main thread has instantiated the store before we access it from another thread:
    QMessageManager _manager;

public:
    QueryThread(QMessageServicePrivate *parent, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset);
    void run();

signals:
    void completed();
};

QueryThread::QueryThread(QMessageServicePrivate *parent, const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset)
: QThread(),
    _parent(parent),
    _filter(filter),
    _body(body),
    _matchFlags(matchFlags),
    _ordering(sortOrder),
    _limit(limit),
    _offset(offset)
{
}

void QueryThread::run()
{
    // Ensure that this thread has initialized MAPI
    WinHelpers::MapiInitializationToken token(WinHelpers::initializeMapi());

    _parent->_candidateIds = _manager.queryMessages(_filter, _body, _matchFlags, _ordering, _limit, _offset);
    _parent->_error = _manager.error();
    emit completed();
}

}

void QMessageServicePrivate::completed()
{
    _active = false;
    _state = QMessageService::FinishedState;
    emit stateChanged(_state);
}

void QMessageServicePrivate::reportMatchingIds()
{
    if (_error == QMessageManager::NoError) {
        emit messagesFound(_candidateIds);
    }

    completed();
}

void QMessageServicePrivate::reportMessagesCounted()
{
    if (_error == QMessageManager::NoError) {
        emit messagesCounted(_candidateIds.count());
    }
    completed();
}

#ifdef _WIN32_WCE
void QMessageServicePrivate::messageUpdated(const QMessageId& id)
{
    if (id == m_bodyDownloadTarget) {
        bool isBodyDownloaded = !isPartiallyDownloaded(id);
        if (isBodyDownloaded) {
            unregisterUpdates();

            completed();
        }
    }
}

#endif

QMessageServicePrivate::QMessageServicePrivate(QMessageService* parent)
    :q_ptr(parent),
     _active(false),
     _state(QMessageService::InactiveState),
     m_registeredUpdates(false),
     m_queryThread(0)
{
}

QMessageServicePrivate::~QMessageServicePrivate()
{
    qDeleteAll(m_obsoleteThreads);
    delete m_queryThread;
    _manager.unregisterNotificationFilter(m_bodyDownloadFilterId);
}

static Lptstr createMCFRecipients(QMessageAddress::Type filterAddressType, const QMessageAddressList& addressList)
{
    QStringList temp;

    foreach(const QMessageAddress& a, addressList)
    {
        if(a.type() == filterAddressType)
            temp.append(a.addressee());
    }

    return temp.isEmpty() ? Lptstr(0) : LptstrFromQString(temp.join(";"));
}

bool QMessageServicePrivate::send(const QMessage& message, bool showComposer)
{
    //check message type

    if(message.type() == QMessage::AnyType || message.type() == QMessage::NoType)
    {
        qWarning() << "Unsupported message type for sending/composition";
        _error = QMessageManager::ConstraintFailure;
        return false;
    }

    //check account

    QMessageAccountId accountId = message.parentAccountId();

    if(!accountId.isValid())
    {
        accountId = QMessageAccount::defaultAccount(message.type());
        if(!accountId.isValid())
        {
            qWarning() << "Invalid account for sending/composition";
            _error = QMessageManager::InvalidId;
            return false;
        }
    }

    //check account/message type compatibility

    QMessageAccount account(accountId);
    if(!(account.messageTypes() & message.type()))
    {
        qWarning() << "Message type unsupported by account";
        _error = QMessageManager::ConstraintFailure;
        return false;
    }

#ifdef _WIN32_WCE
    if(showComposer)
    {
        MAILCOMPOSEFIELDS mcf;
        memset(&mcf,0,sizeof(mcf));

        Lptstr accountName = LptstrFromQString(QMessageAccount(accountId).name());
        Lptstr to;
        Lptstr cc;
        Lptstr bcc;
        Lptstr subject;
        Lptstr attachments;
        Lptstr bodyText;

        //account

        mcf.pszAccount = accountName;
        mcf.dwFlags = MCF_ACCOUNT_IS_NAME;

        if(message.type() == QMessage::Email)
        {
            //recipients

            to = createMCFRecipients(QMessageAddress::Email, message.to());
            cc = createMCFRecipients(QMessageAddress::Email, message.cc());
            bcc = createMCFRecipients(QMessageAddress::Email, message.bcc());
            mcf.pszTo = to;
            mcf.pszCc = cc;
            mcf.pszBcc = bcc;

            //subject

            subject = LptstrFromQString(message.subject());
            mcf.pszSubject = subject;

            //body

            QMessageContentContainerId bodyId = message.bodyId();
            if(bodyId.isValid())
            {
                const QMessageContentContainer& bodyContainer = message.find(bodyId);
                bodyText = LptstrFromQString(bodyContainer.textContent());
                mcf.pszBody = bodyText;
            }

            //attachments

            if(message.status() & QMessage::HasAttachments)
            {
                QStringList attachmentList;

                foreach(const QMessageContentContainerId& id, message.attachmentIds())
                {
                    const QMessageContentContainer& attachmentContainer = message.find(id);
                    attachmentList.append(QMessageContentContainerPrivate::attachmentFilename(attachmentContainer));
                }

                mcf.cAttachments = attachmentList.count();
                QChar nullChar(0);
                attachments = LptstrFromQString(attachmentList.join(nullChar));
                mcf.pszAttachments = attachments;
            }
        }
        else if(message.type() == QMessage::Sms)
        {
            //recipients

            to = createMCFRecipients(QMessageAddress::Phone, message.to());
            mcf.pszTo = to;

            //body

            QMessageContentContainerId bodyId = message.bodyId();
            if(bodyId.isValid())
            {
                const QMessageContentContainer& bodyContainer = message.find(bodyId);
                QString textContent = bodyContainer.textContent();
                if(textContent.length() > SmsCharLimit)
                {
                    textContent.truncate(SmsCharLimit);
                    qWarning() << "SMS messages may not exceed " << SmsCharLimit << " characters. Body trucated.";
                }
                bodyText = LptstrFromQString(textContent);
                mcf.pszBody = bodyText;
            }
        }

       mcf.cbSize = sizeof(mcf);

       if(FAILED(MailComposeMessage(&mcf)))
       {
           _error = QMessageManager::FrameworkFault;
           qWarning() << "MailComposeMessage failed";
           return false;
       }
    }
    else
    {
#endif

    //check recipients
    QMessageAddressList recipients = message.to() + message.bcc() + message.cc();
    if(recipients.isEmpty() && !showComposer)
    {
        qWarning() << "Message must have recipients for sending";
        _error = QMessageManager::ConstraintFailure;
        return false;
    }

    MapiSessionPtr mapiSession(MapiSession::createSession(&_error));
    if (_error != QMessageManager::NoError)
    {
        qWarning() << "Could not create MAPI session for sending";
        return false;
    }

    QMessage outgoing(message);

    //ensure the message is marked read otherwise MapiForm displays the message as incoming
    outgoing.setStatus(QMessage::Read,true);

    //set default account if unset
    if(!outgoing.parentAccountId().isValid())
        outgoing.setParentAccountId(accountId);

    MapiStorePtr mapiStore = mapiSession->findStore(&_error, outgoing.parentAccountId(),false);

    if(mapiStore.isNull() || _error != QMessageManager::NoError)
    {
        qWarning() << "Unable to retrieve MAPI store for account";
        return false;
    }

    //try first to create message in outbox for store, failing that attempt draft

    MapiFolderPtr mapiFolder = mapiStore->findFolder(&_error,QMessage::OutboxFolder);

    if( mapiFolder.isNull() || _error != QMessageManager::NoError ) {
        qWarning() << "Unable to retrieve outbox MAPI folder for sending, attempting drafts...";
        mapiFolder = mapiStore->findFolder(&_error,QMessage::DraftsFolder);
        if(mapiFolder.isNull() || _error != QMessageManager::NoError) {
            qWarning() << "Unable to retrieve drafts MAPI folder for sending";
            return false;
        }
    }

    IMessage* mapiMessage = mapiFolder->createMessage(&_error, outgoing, mapiSession, DontSavePropertyChanges);

    if(!mapiMessage || _error != QMessageManager::NoError)
    {
        qWarning() << "Unable to create MAPI message from source";
        mapiRelease(mapiMessage);
        return false;
    }

#ifndef _WIN32_WCE
    if(showComposer)
    {
        MapiForm* mapiForm = new MapiForm(mapiStore->store(),mapiSession->session(),mapiFolder->folder(),mapiMessage);
        bool result = mapiForm->show();
        mapiRelease(mapiForm);

        if(!result)
        {
            qWarning() << "MapiForm::Show failed";
            _error = QMessageManager::FrameworkFault;
            return false;
        }
    }
    else
#endif
    {
        if(FAILED(mapiMessage->SubmitMessage(0)))
        {
            qWarning() << "MAPI SubmitMessage failed.";
            _error = QMessageManager::FrameworkFault;
            mapiRelease(mapiMessage);
            return false;
        }
    }

#ifdef _WIN32_WCE
    }
#endif

    return true;
}

bool QMessageServicePrivate::show(const QMessageId& messageId)
{
    if(!messageId.isValid())
    {
        _error = QMessageManager::InvalidId;
        qWarning() << "Invalid QMessageId";
        return false;
    }

#ifdef _WIN32_WCE
    MapiEntryId entryId = QMessageIdPrivate::entryId(messageId);
    LPENTRYID entryIdPtr(reinterpret_cast<LPENTRYID>(const_cast<char*>(entryId.data())));
    if(FAILED(MailDisplayMessage(entryIdPtr,entryId.length())))
    {
        qWarning() << "MailDisplayMessage failed";
        _error = QMessageManager::FrameworkFault;
        return false;
    }
    return true;

#else

    MapiSessionPtr mapiSession(MapiSession::createSession(&_error));
    if (_error != QMessageManager::NoError)
    {
        qWarning() << "Could not create MAPI seesion";
        return false;
    }

    MapiEntryId entryId = QMessageIdPrivate::entryId(messageId);
    MapiRecordKey folderRecordKey = QMessageIdPrivate::folderRecordKey(messageId);
    MapiRecordKey storeRecordKey = QMessageIdPrivate::storeRecordKey(messageId);

    MapiStorePtr mapiStore = mapiSession->findStore(&_error,QMessageAccountIdPrivate::from(storeRecordKey));

    if(mapiStore.isNull() || _error != QMessageManager::NoError)
    {
        qWarning() << "Unable to retrieve MAPI store for account";
        return false;
    }

    MapiFolderPtr mapiFolder = mapiStore->openFolderWithKey(&_error,folderRecordKey);

    if( mapiFolder.isNull() || _error != QMessageManager::NoError ) {
        qWarning() << "Unable to retrieve MAPI folder for message";
        return false;
    }

    IMessage* mapiMessage = mapiFolder->openMessage(&_error,entryId);

    if(!mapiMessage || _error != QMessageManager::NoError)
    {
        qWarning() << "Unable to retrieve MAPI message";
        mapiRelease(mapiMessage);
        return false;
    }

    MapiForm* mapiForm = new MapiForm(mapiStore->store(),mapiSession->session(),mapiFolder->folder(),mapiMessage);
    bool result = mapiForm->show();
    mapiRelease(mapiForm);

    if(!result)
    {
        qWarning() << "MapiForm::show failed.";
        _error = QMessageManager::FrameworkFault;
        return false;
    }

    mapiRelease(mapiMessage);

    return result;

#endif
}

#ifdef _WIN32_WCE

bool QMessageServicePrivate::isPartiallyDownloaded(const QMessageId& id, bool considerAttachments)
{
    if(!id.isValid())
    {
        _error = QMessageManager::InvalidId;
        qWarning() << "Invalid QMessageId";
        return false;
    }

    MapiSessionPtr mapiSession(MapiSession::createSession(&_error));

    if (_error != QMessageManager::NoError)
    {
        qWarning() << "Could not create MAPI session";
        return false;
    }

    MapiStorePtr mapiStore = mapiSession->openStore(&_error,QMessageIdPrivate::storeRecordKey(id));

    if(mapiStore.isNull() || _error != QMessageManager::NoError) {
        qWarning() << "Unable to retrieve MAPI store for account";
        return false;
    }

    IMessage* message = mapiStore->openMessage(&_error,QMessageIdPrivate::entryId(id));

    ULONG status = 0;
    if(!getMapiProperty(message,PR_MSG_STATUS,&status)) {
        qWarning() << "Unable to get MAPI message status flags";
        _error = QMessageManager::FrameworkFault;
        return false;
    }
    else
    {
        mapiRelease(message);
        bool bodyNotDownloaded = (status & MSGSTATUS_HEADERONLY) || (status & MSGSTATUS_PARTIAL);
        bool attachmentsNotDownloaded = (status & MSGSTATUS_PENDING_ATTACHMENTS);
        return considerAttachments ? bodyNotDownloaded && attachmentsNotDownloaded : bodyNotDownloaded;
    }
}

bool QMessageServicePrivate::markForDownload(const QMessageId& id, bool includeAttachments)
{
    if(!id.isValid())
    {
        _error = QMessageManager::InvalidId;
        qWarning() << "Invalid QMessageId";
        return false;
    }

    MapiSessionPtr mapiSession(MapiSession::createSession(&_error));

    if (_error != QMessageManager::NoError)
    {
        qWarning() << "Could not create MAPI session";
        return false;
    }

    MapiStorePtr mapiStore = mapiSession->openStore(&_error,QMessageIdPrivate::storeRecordKey(id));

    if(mapiStore.isNull() || _error != QMessageManager::NoError)
    {
        qWarning() << "Unable to retrieve MAPI store for message account";
        return false;
    }

    IMessage* message = mapiStore->openMessage(&_error,QMessageIdPrivate::entryId(id));

    ULONG status = 0;

    if(!getMapiProperty(message,PR_MSG_STATUS,&status))
    {
        qWarning() << "Unable to get MAPI message status flags";
        _error = QMessageManager::FrameworkFault;
        return false;
    }
    else
    {
        //mark the message to download on the next sync

        status |= MSGSTATUS_REMOTE_DOWNLOAD;
        if(includeAttachments)
            status |= MSGSTATUS_REMOTE_DOWNLOAD_ATTACH;

        if(!setMapiProperty(message, PR_MSG_STATUS, status))
        {
            qWarning() << "Could not mark the MAPI message for download!";
            _error = QMessageManager::FrameworkFault;
            return false;
        }

        mapiRelease(message);

        //TODO investigate possibility of interacting with mapi transport directly
        /*
        QString transportName = mapiStore->transportName();
        if(transportName.isEmpty())
        {
            qWarning() << "Could not get transport name for mapi store";
            return false;
        }
        */
    }
    return true;
}

bool QMessageServicePrivate::synchronize(const QMessageAccountId& id)
{
    if(!id.isValid())
    {
        qWarning() << "Cannot synchronize invalid QMessageAccountId";
        _error = QMessageManager::InvalidId;
        return false;
    }

    QMessageAccount account(id);
    if(FAILED(MailSyncMessages(LptstrFromQString(account.name()),MCF_ACCOUNT_IS_NAME | MCF_RUN_IN_BACKGROUND)))
    {
        qWarning() << "MailSyncMessages failed for account: " << account.name();
        _error = QMessageManager::FrameworkFault;
        return false;
    }
    return true;
}

bool QMessageServicePrivate::registerUpdates(const QMessageId& id)
{
    if(!id.isValid())
    {
        qWarning() << "Cannot register for update notifications on invalid QMessageId";
        _error = QMessageManager::InvalidId;
        return false;
    }

    if(!m_registeredUpdates)
    {
        connect(&_manager, SIGNAL(messageUpdated(const QMessageId&, const QMessageManager::NotificationFilterIdSet&)),this,SLOT(messageUpdated(const QMessageId&)));
        m_bodyDownloadFilterId = _manager.registerNotificationFilter(QMessageFilter::byId(id));
        m_bodyDownloadTarget = id;
        m_registeredUpdates = true;
    }
    return m_registeredUpdates;
}

void QMessageServicePrivate::unregisterUpdates()
{
    disconnect(&_manager, SIGNAL(messageUpdated(const QMessageId&, const QMessageManager::NotificationFilterIdSet&)),this,SLOT(messageUpdated(const QMessageId&)));
    _manager.unregisterNotificationFilter(m_bodyDownloadFilterId);
    m_bodyDownloadFilterId = 0;
    m_registeredUpdates = false;
}

bool QMessageServicePrivate::retrieveBody(const QMessage& partialMessage)
{
    if(partialMessage.type() != QMessage::Email)
    {
        qWarning() << "Cannot retrieve body for non-email message type";
        _error = QMessageManager::ConstraintFailure;
        return false;
    }

    if(isPartiallyDownloaded(partialMessage.id()))
    {
        //only valid for Email
        if(markForDownload(partialMessage.id(),true))
            if(registerUpdates(partialMessage.id()))
                if(!synchronize(partialMessage.parentAccountId()))
                    unregisterUpdates();
    }
    else QTimer::singleShot(0,this,SLOT(completed()));

    return (_error == QMessageManager::NoError);
}

#endif

void QMessageServicePrivate::setFinished(bool successful)
{
    if (!successful && (_error == QMessageManager::NoError)) {
        _error = QMessageManager::RequestIncomplete;
    }

    completed();
}

QMessageService::QMessageService(QObject *parent)
    : QObject(parent),
    d_ptr(new QMessageServicePrivate(this))
{
    connect(d_ptr, SIGNAL(stateChanged(QMessageService::State)),
        this, SIGNAL(stateChanged(QMessageService::State)));
    connect(d_ptr, SIGNAL(messagesFound(const QMessageIdList&)),
        this, SIGNAL(messagesFound(const QMessageIdList&)));
    connect(d_ptr, SIGNAL(messagesCounted(int)),
        this, SIGNAL(messagesCounted(int)));
    connect(d_ptr, SIGNAL(progressChanged(uint, uint)),
        this, SIGNAL(progressChanged(uint, uint)));
}

QMessageService::~QMessageService()
{
    delete d_ptr;
    d_ptr = 0;
}

bool QMessageService::queryMessages(const QMessageFilter &filter, const QMessageSortOrder &sortOrder, uint limit, uint offset)
{
    return queryMessages(filter, QString(), QMessageDataComparator::MatchFlags(), sortOrder, limit, offset);
}

bool QMessageService::queryMessages(const QMessageFilter &filter, const QString &body, QMessageDataComparator::MatchFlags matchFlags, const QMessageSortOrder &sortOrder, uint limit, uint offset)
{
    if (d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }


    d_ptr->_active = true;
    d_ptr->_error = QMessageManager::NoError;
    d_ptr->_state = QMessageService::ActiveState;
    emit stateChanged(d_ptr->_state);

#if 0
    d_ptr->_candidateIds = d_ptr->_manager.queryMessages(filter, body, matchFlags, sortOrder, limit, offset);
    d_ptr->_error = d_ptr->_manager.error();
    QTimer::singleShot(0,d_ptr,SLOT(reportMatchingIds()));
#else
    // Perform the query in another thread to keep the UI thread free
    QueryThread *query = new QueryThread(d_ptr, filter, body, matchFlags, sortOrder, limit, offset);
    connect(query, SIGNAL(completed()), d_ptr, SLOT(reportMatchingIds()), Qt::QueuedConnection);
    query->start();

    if (d_ptr->m_queryThread) {
        // Don't delete the previous thread object immediately
        if (!d_ptr->m_obsoleteThreads.isEmpty()) {
            qDeleteAll(d_ptr->m_obsoleteThreads);
            d_ptr->m_obsoleteThreads.clear();
        }
        d_ptr->m_obsoleteThreads.append(d_ptr->m_queryThread);
    }
    d_ptr->m_queryThread = query;
#endif
    return true;
}

bool QMessageService::countMessages(const QMessageFilter &filter)
{
    if (d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }
    d_ptr->_active = true;
    d_ptr->_error = QMessageManager::NoError;
    d_ptr->_state = QMessageService::ActiveState;
    emit stateChanged(d_ptr->_state);

    // Perform the query in another thread to keep the UI thread free
    QueryThread *query = new QueryThread(d_ptr, filter, QString(), QMessageDataComparator::MatchFlags(), QMessageSortOrder(), 0, 0);
    connect(query, SIGNAL(completed()), d_ptr, SLOT(reportMessagesCounted()), Qt::QueuedConnection);
    query->start();

    if (d_ptr->m_queryThread) {
        // Don't delete the previous thread object immediately
        if (!d_ptr->m_obsoleteThreads.isEmpty()) {
            qDeleteAll(d_ptr->m_obsoleteThreads);
        }
        d_ptr->m_obsoleteThreads.append(d_ptr->m_queryThread);
    }
    d_ptr->m_queryThread = query;

    return true;
}

bool QMessageService::send(QMessage &message)
{
    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

    d_ptr->_active = true;
    d_ptr->_state = QMessageService::ActiveState;
    d_ptr->_error = QMessageManager::NoError;
    emit stateChanged(d_ptr->_state);

    bool result = d_ptr->send(message);
    d_ptr->setFinished(result);

    return result;
}

bool QMessageService::compose(const QMessage &message)
{
    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

    d_ptr->_active = true;
    d_ptr->_state = QMessageService::ActiveState;
    d_ptr->_error = QMessageManager::NoError;
    emit stateChanged(d_ptr->_state);

    bool result = d_ptr->send(message,true);
    d_ptr->setFinished(result);

    return result;
}

bool QMessageService::retrieveHeader(const QMessageId& id)
{
    Q_UNUSED(id);

    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

	if(!id.isValid())
	{
		qWarning() << "Invalid QMessageId";
		d_ptr->_error = QMessageManager::InvalidId;
		d_ptr->setFinished(true);
		return false;
	}

    d_ptr->_error = QMessageManager::NoError;
    d_ptr->setFinished(true);

    return true;
}

bool QMessageService::retrieveBody(const QMessageId& id)
{
    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

#ifdef _WIN32_WCE

    d_ptr->_active = true;
    d_ptr->_state = ActiveState;
    d_ptr->_error = QMessageManager::NoError;
    emit stateChanged(d_ptr->_state);

    if(!id.isValid())
    {
        qWarning() << "Invalid QMessageId";
        d_ptr->_error = QMessageManager::InvalidId;
    }

    QMessage message;

    if(d_ptr->_error == QMessageManager::NoError)
    {
        message = QMessage(id);
        d_ptr->_error = QMessageManager().error();
    }


    if(d_ptr->_error == QMessageManager::NoError)
        d_ptr->retrieveBody(message);

    //emit failure immediately
    if (d_ptr->_error != QMessageManager::NoError) {
        d_ptr->setFinished(false);
        return false;
    }

    return true;

#else
    Q_UNUSED(id);

    d_ptr->_error = QMessageManager::NotYetImplemented;
    d_ptr->setFinished(false);
    return false;
#endif
}

bool QMessageService::retrieve(const QMessageId& messageId, const QMessageContentContainerId& id)
{

    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

#ifdef _WIN32_WCE

    d_ptr->_active = true;
    d_ptr->_state = ActiveState;
    d_ptr->_error = QMessageManager::NoError;
    emit stateChanged(d_ptr->_state);

    if(!messageId.isValid())
    {
        qWarning() << "Invalid QMessageId";
        d_ptr->_error = QMessageManager::InvalidId;
    }

    QMessage message;

    if(d_ptr->_error == QMessageManager::NoError)
    {
        message = QMessage(messageId);
        d_ptr->_error = d_ptr->_manager.error();
    }

    if(d_ptr->_error == QMessageManager::NoError)
    {
        bool isBodyContainer = message.bodyId() == id;
        if(isBodyContainer)
            d_ptr->retrieveBody(message);
        //TODO downloading attachment programatically possible?
    }

    //emit failure immediately
    if (d_ptr->_error != QMessageManager::NoError) {
        d_ptr->setFinished(false);
        return false;
    }

    return true;

#else
    Q_UNUSED(messageId)
    Q_UNUSED(id)

    d_ptr->_error = QMessageManager::NotYetImplemented;
    d_ptr->setFinished(false);
#endif

    return false;
}

bool QMessageService::show(const QMessageId& id)
{
    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

    d_ptr->_active = true;
    d_ptr->_state = ActiveState;
    d_ptr->_error = QMessageManager::NoError;
    emit stateChanged(d_ptr->_state);

    bool result = d_ptr->show(id);
    d_ptr->setFinished(result);

    return result;
}

bool QMessageService::exportUpdates(const QMessageAccountId &id)
{
    Q_UNUSED(id);

    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

    d_ptr->_error = QMessageManager::NotYetImplemented;
    d_ptr->setFinished(false);

    return false;
}

bool QMessageService::synchronize(const QMessageAccountId& id)
{
    Q_UNUSED(id);

    if(d_ptr->_active) {
        qWarning() << "Service is currently busy";
        return false;
    }

    d_ptr->_error = QMessageManager::NotYetImplemented;
    d_ptr->setFinished(false);

    return false;
}

QMessageService::State QMessageService::state() const
{
    return d_ptr->_state;
}

void QMessageService::cancel()
{
#ifdef _WIN32_WCE
    if(d_ptr->_active)
    {
        bool awaitingBodyRetrieval(d_ptr->m_bodyDownloadFilterId != 0);

        if(awaitingBodyRetrieval)
        {
            d_ptr->unregisterUpdates();
            d_ptr->_error = QMessageManager::NoError;
            d_ptr->_state = QMessageService::InactiveState;
            d_ptr->_active = false;
            emit stateChanged(d_ptr->_state);
        }
    }
#else
    //NOOP
#endif
}

QMessageManager::Error QMessageService::error() const
{
    return d_ptr->_error;
}

#include <qmessageservice_win.moc>

QTM_END_NAMESPACE