File: pending-captchas.cpp

package info (click to toggle)
telepathy-qt 0.9.1-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 38,764 kB
  • sloc: cpp: 59,914; xml: 34,543; ansic: 21,194; python: 3,370; sh: 118; makefile: 20
file content (387 lines) | stat: -rw-r--r-- 13,520 bytes parent folder | download | duplicates (5)
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
/**
 * This file is part of TelepathyQt
 *
 * @copyright Copyright (C) 2012 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2012 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt/PendingCaptchas>

#include "TelepathyQt/debug-internal.h"

#include "TelepathyQt/_gen/pending-captchas.moc.hpp"

#include <TelepathyQt/Captcha>
#include <TelepathyQt/captcha-authentication-internal.h>

namespace Tp
{

struct TP_QT_NO_EXPORT PendingCaptchas::Private
{
    Private(PendingCaptchas *parent);
    ~Private();

    CaptchaAuthentication::ChallengeType stringToChallengeType(const QString &string) const;
    void appendCaptchaResult(const QString &mimeType, const QString &label,
            const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id);

    // Public object
    PendingCaptchas *parent;

    CaptchaAuthentication::ChallengeTypes preferredTypes;
    QStringList preferredMimeTypes;

    bool multipleRequired;
    QList<Captcha> captchas;
    int captchasLeft;

    CaptchaAuthenticationPtr captchaAuthentication;
    ChannelPtr channel;
};

PendingCaptchas::Private::Private(PendingCaptchas *parent)
    : parent(parent)
{

}

PendingCaptchas::Private::~Private()
{
}

CaptchaAuthentication::ChallengeType PendingCaptchas::Private::stringToChallengeType(const QString &string) const
{
    if (string == QLatin1String("audio_recog")) {
        return CaptchaAuthentication::AudioRecognitionChallenge;
    } else if (string == QLatin1String("ocr")) {
        return CaptchaAuthentication::OCRChallenge;
    } else if (string == QLatin1String("picture_q")) {
        return CaptchaAuthentication::PictureQuestionChallenge;
    } else if (string == QLatin1String("picture_recog")) {
        return CaptchaAuthentication::PictureRecognitionChallenge;
    } else if (string == QLatin1String("qa")) {
        return CaptchaAuthentication::TextQuestionChallenge;
    } else if (string == QLatin1String("speech_q")) {
        return CaptchaAuthentication::SpeechQuestionChallenge;
    } else if (string == QLatin1String("speech_recog")) {
        return CaptchaAuthentication::SpeechRecognitionChallenge;
    } else if (string == QLatin1String("video_q")) {
        return CaptchaAuthentication::VideoQuestionChallenge;
    } else if (string == QLatin1String("video_recog")) {
        return CaptchaAuthentication::VideoRecognitionChallenge;
    }

    // Not really making sense...
    return CaptchaAuthentication::UnknownChallenge;
}

void PendingCaptchas::Private::appendCaptchaResult(const QString &mimeType, const QString &label,
        const QByteArray &data, CaptchaAuthentication::ChallengeType type, uint id)
{
    // Add to the list
    Captcha captchaItem(mimeType, label, data, type, id);

    captchas.append(captchaItem);

    --captchasLeft;

    if (!captchasLeft) {
        parent->setFinished();
    }
}

/**
 * \class PendingCaptchas
 * \ingroup client
 * \headerfile TelepathyQt/pending-captchas.h <TelepathyQt/PendingCaptchas>
 *
 * \brief The PendingCaptchas class represents an asynchronous
 * operation for retrieving a captcha challenge from a connection manager.
 *
 * See \ref async_model
 */

PendingCaptchas::PendingCaptchas(
        const QDBusPendingCall &call,
        const QStringList &preferredMimeTypes,
        CaptchaAuthentication::ChallengeTypes preferredTypes,
        const CaptchaAuthenticationPtr &captchaAuthentication)
    : PendingOperation(captchaAuthentication),
      mPriv(new Private(this))
{
    mPriv->captchaAuthentication = captchaAuthentication;
    mPriv->channel = captchaAuthentication->channel();
    mPriv->preferredMimeTypes = preferredMimeTypes;
    mPriv->preferredTypes = preferredTypes;

    /* keep track of channel invalidation */
    connect(mPriv->channel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));

    connect(new QDBusPendingCallWatcher(call),
            SIGNAL(finished(QDBusPendingCallWatcher*)),
            this,
            SLOT(onGetCaptchasWatcherFinished(QDBusPendingCallWatcher*)));
}

PendingCaptchas::PendingCaptchas(
        const QString& errorName,
        const QString& errorMessage,
        const CaptchaAuthenticationPtr &captchaAuthentication)
    : PendingOperation(captchaAuthentication),
      mPriv(new PendingCaptchas::Private(this))
{
    warning() << "PendingCaptchas created with instant failure";
    setFinishedWithError(errorName, errorMessage);
}

/**
 * Class destructor.
 */
PendingCaptchas::~PendingCaptchas()
{
    delete mPriv;
}

void PendingCaptchas::onChannelInvalidated(Tp::DBusProxy *proxy,
        const QString &errorName, const QString &errorMessage)
{
    Q_UNUSED(proxy);

    if (isFinished()) {
        return;
    }

    warning().nospace() << "PendingCaptchas failed because channel was invalidated with " <<
        errorName << ": " << errorMessage;

    setFinishedWithError(errorName, errorMessage);
}

void PendingCaptchas::onGetCaptchasWatcherFinished(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<Tp::CaptchaInfoList, uint, QString> reply = *watcher;

    if (reply.isError()) {
        debug().nospace() << "PendingDBusCall failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
        watcher->deleteLater();
        return;
    }

    debug() << "Got reply to PendingDBusCall";
    Tp::CaptchaInfoList list = qdbus_cast<Tp::CaptchaInfoList>(reply.argumentAt(0));
    int howManyRequired = reply.argumentAt(1).toUInt();

    // Compute which captchas are required
    QList<QPair<Tp::CaptchaInfo,QString> > finalList;
    foreach (const Tp::CaptchaInfo &info, list) {
        // First of all, mimetype check
        QString mimeType;
        if (info.availableMIMETypes.isEmpty()) {
            // If it's one of the types which might not have a payload, go for it
            CaptchaAuthentication::ChallengeTypes noPayloadChallenges(
                    CaptchaAuthentication::TextQuestionChallenge |
                    CaptchaAuthentication::UnknownChallenge);
            if (mPriv->stringToChallengeType(info.type) & noPayloadChallenges) {
                // Ok, move on
            } else {
                // In this case, there's something wrong
                warning() << "Got a captcha with type " << info.type << " which does not "
                        "expose any available mimetype for its payload. Something might be "
                        "wrong with the connection manager.";
                continue;
            }
        } else if (mPriv->preferredMimeTypes.isEmpty()) {
            // No preference, let's take the first of the list
            mimeType = info.availableMIMETypes.first();
        } else {
            QSet<QString> supportedMimeTypes = info.availableMIMETypes.toSet().intersect(
                    mPriv->preferredMimeTypes.toSet());
            if (supportedMimeTypes.isEmpty()) {
                // Apparently our handler does not support any of this captcha's mimetypes, skip
                continue;
            }

            // Ok, use the first one
            mimeType = *supportedMimeTypes.constBegin();
        }

        // If it's required, easy
        if (info.flags & CaptchaFlagRequired) {
            finalList.append(qMakePair(info, mimeType));
            continue;
        }

        // Otherwise, let's see if the mimetype matches
        if (mPriv->preferredTypes & mPriv->stringToChallengeType(info.type)) {
            finalList.append(qMakePair(info, mimeType));
        }

        if (finalList.size() == howManyRequired) {
            break;
        }
    }

    if (finalList.size() != howManyRequired) {
        warning() << "No captchas available matching the specified preferences";
        setFinishedWithError(TP_QT_ERROR_NOT_AVAILABLE,
                QLatin1String("No captchas matching the handler's request"));
        return;
    }

    // Now, get the infos for all the required captchas in our final list.
    mPriv->captchasLeft = finalList.size();
    mPriv->multipleRequired = howManyRequired > 1 ? true : false;
    for (QList<QPair<Tp::CaptchaInfo,QString> >::const_iterator i = finalList.constBegin();
            i != finalList.constEnd(); ++i) {
        QString mimeType = (*i).second;
        Tp::CaptchaInfo captchaInfo = (*i).first;

        // If the captcha does not have a mimetype, we can add it straight
        if (mimeType.isEmpty()) {
            mPriv->appendCaptchaResult(mimeType, captchaInfo.label, QByteArray(),
                    mPriv->stringToChallengeType(captchaInfo.type), captchaInfo.ID);

            continue;
        }

        QDBusPendingCall call =
        mPriv->channel->interface<Client::ChannelInterfaceCaptchaAuthenticationInterface>()->GetCaptchaData(
                    captchaInfo.ID, mimeType);

        QDBusPendingCallWatcher *dataWatcher = new QDBusPendingCallWatcher(call);
        dataWatcher->setProperty("__Tp_Qt_CaptchaID", captchaInfo.ID);
        dataWatcher->setProperty("__Tp_Qt_CaptchaMimeType", mimeType);
        dataWatcher->setProperty("__Tp_Qt_CaptchaLabel", captchaInfo.label);
        dataWatcher->setProperty("__Tp_Qt_CaptchaType",
                mPriv->stringToChallengeType(captchaInfo.type));

        connect(dataWatcher,
                SIGNAL(finished(QDBusPendingCallWatcher*)),
                this,
                SLOT(onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher*)));
    }

    watcher->deleteLater();
}

void PendingCaptchas::onGetCaptchaDataWatcherFinished(QDBusPendingCallWatcher *watcher)
{
    QDBusPendingReply<QByteArray> reply = *watcher;

    if (reply.isError()) {
        debug().nospace() << "PendingDBusCall failed: " <<
            reply.error().name() << ": " << reply.error().message();
        setFinishedWithError(reply.error());
        watcher->deleteLater();
        return;
    }

    debug() << "Got reply to PendingDBusCall";

    // Add to the list
    mPriv->appendCaptchaResult(watcher->property("__Tp_Qt_CaptchaMimeType").toString(),
            watcher->property("__Tp_Qt_CaptchaLabel").toString(),
            reply.value(), static_cast<CaptchaAuthentication::ChallengeType>(
                watcher->property("__Tp_Qt_CaptchaType").toUInt()),
            watcher->property("__Tp_Qt_CaptchaID").toUInt());

    watcher->deleteLater();
}

/**
 * Return the main captcha of the request. This captcha is guaranteed to be compatible
 * with any constraint specified in CaptchaAuthentication::requestCaptchas().
 *
 * This is a convenience method which should be used when requiresMultipleCaptchas()
 * is false - otherwise, you should use captchaList.
 *
 * The returned Captcha can be answered through CaptchaAuthentication::answer() by
 * using its id.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return The main captcha for the pending request.
 * \sa captchaList()
 *     CaptchaAuthentication::requestCaptchas()
 *     requiresMultipleCaptchas()
 *     CaptchaAuthentication::answer()
 */
Captcha PendingCaptchas::captcha() const
{
    if (!isFinished()) {
        return Captcha();
    }

    return mPriv->captchas.first();
}

/**
 * Return all the captchas of the request. These captchas are guaranteed to be compatible
 * with any constraint specified in CaptchaAuthentication::requestCaptchas().
 *
 * If requiresMultipleCaptchas() is false, you probably want to use the convenience method
 * captcha() instead.
 *
 * The returned Captchas can be answered through CaptchaAuthentication::answer() by
 * using their ids.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return All the captchas for the pending request.
 * \sa captcha()
 *     CaptchaAuthentication::requestCaptchas()
 *     requiresMultipleCaptchas()
 *     CaptchaAuthentication::answer()
 */
QList<Captcha> PendingCaptchas::captchaList() const
{
    if (!isFinished()) {
        return QList<Captcha>();
    }

    return mPriv->captchas;
}

/**
 * Return whether this request requires more than one captcha to be answered or not.
 *
 * This method should always be checked before answering to find out what the
 * connection manager expects. Depending on the result, you might want to use the
 * result from captcha() if just a single answer is required, or from captchaList()
 * otherwise.
 *
 * This method will return a meaningful value only if the operation was completed
 * successfully.
 *
 * \return The main captcha for the pending request.
 * \sa captcha()
 *     captchaList()
 */
bool PendingCaptchas::requiresMultipleCaptchas() const
{
    return mPriv->multipleRequired;
}

}