summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/plugin/src/filtering/cntsymbiansrvconnection.cpp
blob: a479fee17f9ce3171303035bdf814c1898ea6e53 (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
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//system includes
#include <e32base.h>
#include <s32mem.h>
#include <qcontact.h>
#include <qcontactname.h>
#include <qcontactorganization.h>

//user includes
#include "cntsymbiansrvconnection.h"
#include "cntsymbiantransformerror.h"

// Constants
// To be removed. Should be defined in a header file

#define KCntOpenDataBase 100 // = KCapabilityReadUserData

_LIT(KCntServerExe,"CNTSRV.EXE");   // Name of the exe for the Contacts server.
_LIT(KCntServerName,"CNTSRV");  // Name used to connect a session 
                                // to the Contacts server.

/** Maximum number of asynchronous IPC calls. */
const TInt KAsyncMessageSlots=6;

/* Contacts server version number. */ 
const TInt KCntServerMajorVersionNumber=1;
const TInt KCntServerMinorVersionNumber=1;
const TInt KCntServerBuildVersionNumber=1;

const TInt KGranularityRank = 8; //2^8 = 256 bytes
const TInt KDefaultPackagerSize = 3514; //Observed Techview Golden template size.

/*!
 * The constructor
 */
CntSymbianSrvConnection::CntSymbianSrvConnection(QContactManagerEngine* manager) :
    m_manager(manager),
    m_buffer(0),
    m_bufPtr(0,0,0),
    m_isInitialized(false)
{
}

/*!
 * Destructor 
 */
CntSymbianSrvConnection::~CntSymbianSrvConnection()
{
    delete m_buffer;
    RHandleBase::Close();
}

/*!
 * Query the SQL database
 * 
 * \a sqlQuery An SQL query
 * \a error On return, contains the possible error.
 * \return the list of matched contact ids
 */
QList<QContactLocalId> CntSymbianSrvConnection::searchContacts(const QString& sqlQuery, 
                                                       QContactManager::Error* error)
{
    QList<QContactLocalId> list;
    TPtrC queryPtr(reinterpret_cast<const TUint16*>(sqlQuery.utf16()));
    TRAPD(err, list = searchContactIdsL(queryPtr, CntSymbianSrvConnection::CntSearchResultList));
    CntSymbianTransformError::transformError(err, error);
    return list;
}

/*!
 * Fetches list of matched contact ids with phonenumber fields
 * SELECT contact_id, extra_value FROM comm_addr
 * WHERE value = [value string] AND type = [type value];
 * 
 * \a sqlQuery An SQL query
 * \a error On return, contains the possible error.
 * \return the list of matched contact ids and values
 */
QList<QPair<QContactLocalId, QString> > CntSymbianSrvConnection::searchPhoneNumbers(const QString& sqlQuery, 
                                              QContactManager::Error* error)
{
    QList<QPair<QContactLocalId, QString> > list;
    TPtrC queryPtr(reinterpret_cast<const TUint16*>(sqlQuery.utf16()));
    TRAPD(err, list = searchPhoneNumbersL(queryPtr, CntSymbianSrvConnection::CntSearchResultList));
    CntSymbianTransformError::transformError(err, error);
    return list;
}

/*!
 * Query the SQL database
 * 
 * \a sqlQuery An SQL query
 * a QueryType query type
 * \a error On return, contains the possible error.
 * \return the list of matched contact ids
 */
QList<QContactLocalId> CntSymbianSrvConnection::searchOnServer(const QString& sqlQuery,
                                                                QueryType aQueryType,
                                                                QContactManager::Error* error)
{
    QList<QContactLocalId> list;
    TPtrC queryPtr(reinterpret_cast<const TUint16*>(sqlQuery.utf16()));
    TRAPD(err, list = searchContactIdsL(queryPtr, aQueryType));
        CntSymbianTransformError::transformError(err, error);
    return list;
}
/*!
 * Fetches all contact names from the database. If there are more than 3000 contacts,
 * only the first (by id) 3000 contacts will be fetched due to RAM restrictions.
 * 
 * \a error On return, contains the possible error.
 * \return the list of contact names (stored in QContact objects)
 */
QList<QContact> CntSymbianSrvConnection::searchAllContactNames(QContactManager::Error* error)
{
    QList<QContact> list;
    TRAPD(err, list = searchContactNamesL(_L("SELECT contact_id, first_name, last_name, company_name FROM contact WHERE (type_flags>>24)<=1")));
    CntSymbianTransformError::transformError(err, error);
    return list;
}

/*!
 * Query the SQL database
 * 
 * \a id Id of the contact whose name to search
 * \a error On return, contains the possible error.
 * \return the list of matched contact ids
 */
QContact CntSymbianSrvConnection::searchContactName(QContactLocalId id, 
                                                    QContactManager::Error* error)
{
    QList<QContact> list;

    // Fetch results from the server
    TBuf<100> sqlQuery;
    sqlQuery.Format(_L("SELECT contact_id, first_name, last_name, company_name FROM contact WHERE contact_id = %d"), id);
    TRAPD(err, list = searchContactNamesL(sqlQuery));
    CntSymbianTransformError::transformError(err, error);
    
    if (list.size() == 0) {
        *error = QContactManager::DoesNotExistError;
        return QContact();
    }

    return list.at(0);
}

/*!
 * The leaving function that queries the SQL database
 * 
 * \a aSqlQuery An SQL query
 * \return the list of matched contact ids
 */
QList<QContactLocalId> CntSymbianSrvConnection::searchContactIdsL(const TDesC& aSqlQuery, QueryType aQueryType)
{
    readContactsToBufferL(aSqlQuery, aQueryType);

    RBufReadStream readStream;
    QList<QContactLocalId> list;
    TInt item;
    
    readStream.Open(*m_buffer);
    while ((item = readStream.ReadInt32L()) != 0) {
        list << item;
    }

    return list;
}

/*!
 * The leaving function that queries the SQL database
 * 
 * \a aSqlQuery An SQL query
 * \return the list of matched contact ids and phonenumber values
 */
QList<QPair<QContactLocalId, QString> > CntSymbianSrvConnection::searchPhoneNumbersL(const TDesC& aSqlQuery, QueryType aQueryType)
{
    readContactsToBufferL(aSqlQuery, aQueryType);

    RBufReadStream readStream;
    QList<QPair<QContactLocalId, QString> > list;
    TInt item;
    TBuf<256> extraValue;
    
    readStream.Open(*m_buffer);
    while ((item = readStream.ReadInt32L()) != 0) {
        readStream >> extraValue;
        QContactLocalId id = item;
        list.append(qMakePair(id,QString::fromUtf16(extraValue.Ptr(), extraValue.Length())));
    }

    return list;
}

/*!
 * The leaving function that queries the SQL database
 * 
 * \a aSqlQuery An SQL query
 * \return the list of matched contact ids
 */
QList<QContact> CntSymbianSrvConnection::searchContactNamesL(const TDesC& aSqlQuery)
{
    readContactsToBufferL(aSqlQuery, CntSymbianSrvConnection::CntSearchResultList);

    RBufReadStream readStream;
    QList<QContact> contacts;
    TInt id;
    TBuf<256> firstName;
    TBuf<256> lastName;
    TBuf<256> company;

    readStream.Open(*m_buffer);
    while ((id = readStream.ReadInt32L()) != 0) {
        readStream >> firstName;
        readStream >> lastName;
        readStream >> company;

        QContact contact, tempContact;

        QContactName name;
        name.setFirstName(QString::fromUtf16(firstName.Ptr(), firstName.Length()));
        name.setLastName(QString::fromUtf16(lastName.Ptr(), lastName.Length()));
        tempContact.saveDetail(&name);

        QContactOrganization organization;
        organization.setName(QString::fromUtf16(company.Ptr(), company.Length()));
        tempContact.saveDetail(&organization);

        QContactManager::Error error(QContactManager::NoError);
        QString label = m_manager->synthesizedDisplayLabel(tempContact, &error);
        if (error != QContactManager::NoError) {
            continue;
        }
        tempContact.clearDetails();

        m_manager->setContactDisplayLabel(&contact, label);

        QContactId contactId;
        contactId.setLocalId(id);
        contactId.setManagerUri(m_manager->managerUri());
        contact.setId(contactId);

        contacts << contact;
    }

    return contacts;
}

    
/*!
 * The leaving function that queries the SQL database
 * 
 * \a id database id of the contact
 * \return the list of matched contact names
 */
void CntSymbianSrvConnection::readContactsToBufferL(const TDesC& sqlQuery, QueryType aQueryType)
{
    // Initialize connection if it is not initialized yet.
    if (!m_isInitialized) {
        ConnectSrvL();
        OpenDatabaseL();
        m_isInitialized = true;
    }

    TIpcArgs args;
    args.Set(0, &GetReceivingBufferL());
    args.Set(1, &sqlQuery);
    TInt newBuffSize = SendReceive(aQueryType, args);
    User::LeaveIfError(newBuffSize);
    if (newBuffSize > 0) {
        args.Set(0, &GetReceivingBufferL(newBuffSize));
        args.Set(1, &sqlQuery);
        User::LeaveIfError(SendReceive(aQueryType, args));
    }
}

    
/*!
 * Connect to / create a cntsrv server session
 */
void CntSymbianSrvConnection::ConnectSrvL()
{
    // Assume the server is already running and attempt to create a session
    // with a maximum of KAsyncMessageSlots message slots.
    TInt err = CreateSession(KCntServerName,Version(),KAsyncMessageSlots);
    
    // Server is not running
    if(err == KErrNotFound) {
        // Use the RProcess API to start the server.
        RProcess server;
        User::LeaveIfError(server.Create(KCntServerExe,KNullDesC));
        
        //Enforce server to be at system default priority EPriorityForeground
        server.SetPriority(EPriorityForeground);
        
        // Synchronize with the server.
        TRequestStatus reqStatus;
        server.Rendezvous(reqStatus);
        server.Resume();
        
        // Server will call the reciprocal static synchronization call.
        User::WaitForRequest(reqStatus);
        server.Close();
        User::LeaveIfError(reqStatus.Int());
        
        // Create the server session.
        User::LeaveIfError(CreateSession(KCntServerName,Version(),KAsyncMessageSlots));
    } else {
        User::LeaveIfError(err);
    }
    
    // Create IPC buffer
    m_buffer = CBufFlat::NewL(1 << KGranularityRank);
    m_maxBufferSize = KDefaultPackagerSize;
            
}

/*!
 * Open database
 */
void CntSymbianSrvConnection::OpenDatabaseL()
{
    TIpcArgs args;
    args.Set(0, &KNullDesC);
    User::LeaveIfError(SendReceive(KCntOpenDataBase, args));
}

/*!
 * Version of cntsrv
 */
TVersion CntSymbianSrvConnection::Version() const
{
    return(TVersion(KCntServerMajorVersionNumber,
                    KCntServerMinorVersionNumber,
                    KCntServerBuildVersionNumber));
}

/*!
 * Get the buffer reference to be used for IPC
 * 
 * \a size size of the receiving buffer
 * \return a reference to the beginning of the buffer
 */
TDes8& CntSymbianSrvConnection::GetReceivingBufferL(int size)
{
    if(size > m_buffer->Size()) {
        // Find next divisable by granularity size value.
        (size >>= KGranularityRank)++;
        m_maxBufferSize = size <<= 8;
        m_buffer->ResizeL(m_maxBufferSize);
    
    } else if(!size && m_buffer->Size() < m_maxBufferSize) {
        // Use the stored default size.
        m_buffer->ResizeL(m_maxBufferSize);
    }
    // The location of the whole buffer may have changed, because reallocation
    // may have taken place. Update both buffer pointers.
    m_bufPtr.Set(m_buffer->Ptr(0));
    return m_bufPtr;
}