summaryrefslogtreecommitdiff
path: root/qt4/TelepathyQt4/profile.cpp
blob: 153f602ba62a6c26ba65bff9db701a44066a8a04 (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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2010 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 <TelepathyQt4/Profile>

#include "TelepathyQt4/debug-internal.h"

#include <TelepathyQt4/ManagerFile>
#include <TelepathyQt4/Utils>
#include <TelepathyQt4/ProtocolInfo>
#include <TelepathyQt4/ProtocolParameter>

#include <QFile>
#include <QFileInfo>
#include <QStringList>
#include <QXmlAttributes>
#include <QXmlDefaultHandler>
#include <QXmlInputSource>
#include <QXmlSimpleReader>

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT Profile::Private
{
    Private();

    void setServiceName(const QString &serviceName);
    void setFileName(const QString &fileName);

    void lookupProfile();
    bool parse(QFile *file);
    void invalidate();

    struct Data
    {
        Data();

        void clear();

        QString type;
        QString provider;
        QString name;
        QString iconName;
        QString cmName;
        QString protocolName;
        Profile::ParameterList parameters;
        bool allowOtherPresences;
        Profile::PresenceList presences;
        RequestableChannelClassSpecList unsupportedChannelClassSpecs;
    };

    class XmlHandler;

    QString serviceName;
    bool valid;
    bool fake;
    bool allowNonIMType;
    Data data;
};

Profile::Private::Data::Data()
    : allowOtherPresences(false)
{
}

void Profile::Private::Data::clear()
{
    type = QString();
    provider = QString();
    name = QString();
    iconName = QString();
    protocolName = QString();
    parameters = Profile::ParameterList();
    allowOtherPresences = false;
    presences = Profile::PresenceList();
    unsupportedChannelClassSpecs = RequestableChannelClassSpecList();
}


class TELEPATHY_QT4_NO_EXPORT Profile::Private::XmlHandler :
                public QXmlDefaultHandler
{
public:
    XmlHandler(const QString &serviceName, bool allowNonIMType, Profile::Private::Data *outputData);

    bool startElement(const QString &namespaceURI, const QString &localName,
            const QString &qName, const QXmlAttributes &attributes);
    bool endElement(const QString &namespaceURI, const QString &localName,
            const QString &qName);
    bool characters(const QString &str);
    bool fatalError(const QXmlParseException &exception);
    QString errorString() const;

private:
    bool attributeValueAsBoolean(const QXmlAttributes &attributes,
            const QString &qName);

    QString mServiceName;
    bool allowNonIMType;
    Profile::Private::Data *mData;
    QStack<QString> mElements;
    QString mCurrentText;
    Profile::Parameter mCurrentParameter;
    RequestableChannelClass mCurrentCC;
    QString mCurrentPropertyName;
    QString mCurrentPropertyType;
    QString mErrorString;
    bool mMetServiceTag;

    static const QString xmlNs;

    static const QString elemService;
    static const QString elemName;
    static const QString elemParams;
    static const QString elemParam;
    static const QString elemPresences;
    static const QString elemPresence;
    static const QString elemUnsupportedCCs;
    static const QString elemCC;
    static const QString elemProperty;

    static const QString elemAttrId;
    static const QString elemAttrName;
    static const QString elemAttrType;
    static const QString elemAttrProvider;
    static const QString elemAttrManager;
    static const QString elemAttrProtocol;
    static const QString elemAttrIcon;
    static const QString elemAttrLabel;
    static const QString elemAttrMandatory;
    static const QString elemAttrAllowOthers;
    static const QString elemAttrMessage;
    static const QString elemAttrDisabled;
};

const QString Profile::Private::XmlHandler::xmlNs = QLatin1String("http://telepathy.freedesktop.org/wiki/service-profile-v1");

const QString Profile::Private::XmlHandler::elemService = QLatin1String("service");
const QString Profile::Private::XmlHandler::elemName = QLatin1String("name");
const QString Profile::Private::XmlHandler::elemParams = QLatin1String("parameters");
const QString Profile::Private::XmlHandler::elemParam = QLatin1String("parameter");
const QString Profile::Private::XmlHandler::elemPresences = QLatin1String("presences");
const QString Profile::Private::XmlHandler::elemPresence = QLatin1String("presence");
const QString Profile::Private::XmlHandler::elemUnsupportedCCs = QLatin1String("unsupported-channel-classes");
const QString Profile::Private::XmlHandler::elemCC = QLatin1String("channel-class");
const QString Profile::Private::XmlHandler::elemProperty = QLatin1String("property");

const QString Profile::Private::XmlHandler::elemAttrId = QLatin1String("id");
const QString Profile::Private::XmlHandler::elemAttrName = QLatin1String("name");
const QString Profile::Private::XmlHandler::elemAttrType = QLatin1String("type");
const QString Profile::Private::XmlHandler::elemAttrProvider = QLatin1String("provider");
const QString Profile::Private::XmlHandler::elemAttrManager = QLatin1String("manager");
const QString Profile::Private::XmlHandler::elemAttrProtocol = QLatin1String("protocol");
const QString Profile::Private::XmlHandler::elemAttrLabel = QLatin1String("label");
const QString Profile::Private::XmlHandler::elemAttrMandatory = QLatin1String("mandatory");
const QString Profile::Private::XmlHandler::elemAttrAllowOthers = QLatin1String("allow-others");
const QString Profile::Private::XmlHandler::elemAttrIcon = QLatin1String("icon");
const QString Profile::Private::XmlHandler::elemAttrMessage = QLatin1String("message");
const QString Profile::Private::XmlHandler::elemAttrDisabled = QLatin1String("disabled");

Profile::Private::XmlHandler::XmlHandler(const QString &serviceName,
        bool allowNonIMType,
        Profile::Private::Data *outputData)
    : mServiceName(serviceName),
      allowNonIMType(allowNonIMType),
      mData(outputData),
      mMetServiceTag(false)
{
}

bool Profile::Private::XmlHandler::startElement(const QString &namespaceURI,
        const QString &localName, const QString &qName,
        const QXmlAttributes &attributes)
{
    if (!mMetServiceTag && qName != elemService) {
        mErrorString = QLatin1String("the file is not a profile file");
        return false;
    }

    if (namespaceURI != xmlNs) {
        // ignore all elements with unknown xmlns
        debug() << "Ignoring unknown xmlns" << namespaceURI;
        return true;
    }

#define CHECK_ELEMENT_IS_CHILD_OF(parentElement) \
    if (mElements.top() != parentElement) { \
        mErrorString = QString(QLatin1String("element '%1' is not a " \
                    "child of element '%2'")) \
            .arg(qName) \
            .arg(parentElement); \
        return false; \
    }
#define CHECK_ELEMENT_ATTRIBUTES_COUNT(value) \
    if (attributes.count() != value) { \
        mErrorString = QString(QLatin1String("element '%1' contains more " \
                    "than %2 attributes")) \
            .arg(qName) \
            .arg(value); \
        return false; \
    }
#define CHECK_ELEMENT_HAS_ATTRIBUTE(attribute) \
    if (attributes.index(attribute) == -1) { \
        mErrorString = QString(QLatin1String("mandatory attribute '%1' " \
                    "missing on element '%2'")) \
            .arg(attribute) \
            .arg(qName); \
        return false; \
    }
#define CHECK_ELEMENT_ATTRIBUTES(allowedAttrs) \
    for (int i = 0; i < attributes.count(); ++i) { \
        bool valid = false; \
        QString attrName = attributes.qName(i); \
        foreach (const QString &allowedAttr, allowedAttrs) { \
            if (attrName == allowedAttr) { \
                valid = true; \
                break; \
            } \
        } \
        if (!valid) { \
            mErrorString = QString(QLatin1String("invalid attribute '%1' on " \
                        "element '%2'")) \
                .arg(attrName) \
                .arg(qName); \
            return false; \
        } \
    }

    if (qName == elemService) {
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrId);
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrType);
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrManager);
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrProtocol);

        QStringList allowedAttrs = QStringList() <<
            elemAttrId << elemAttrType << elemAttrManager <<
            elemAttrProtocol << elemAttrProvider << elemAttrIcon;
        CHECK_ELEMENT_ATTRIBUTES(allowedAttrs);

        if (attributes.value(elemAttrId) != mServiceName) {
            mErrorString = QString(QLatin1String("the '%1' attribute of the "
                        "element '%2' does not match the file name"))
                .arg(elemAttrId)
                .arg(elemService);
            return false;
        }

        mMetServiceTag = true;
        mData->type = attributes.value(elemAttrType);
        if (mData->type != QLatin1String("IM") && !allowNonIMType) {
            mErrorString = QString(QLatin1String("unknown value of element "
                        "'type': %1"))
                .arg(mCurrentText);
            return false;
        }
        mData->provider = attributes.value(elemAttrProvider);
        mData->cmName = attributes.value(elemAttrManager);
        mData->protocolName = attributes.value(elemAttrProtocol);
        mData->iconName = attributes.value(elemAttrIcon);
    } else if (qName == elemParams) {
        CHECK_ELEMENT_IS_CHILD_OF(elemService);
        CHECK_ELEMENT_ATTRIBUTES_COUNT(0);
    } else if (qName == elemParam) {
        CHECK_ELEMENT_IS_CHILD_OF(elemParams);
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrName);
        QStringList allowedAttrs = QStringList() << elemAttrName <<
            elemAttrType << elemAttrMandatory << elemAttrLabel;
        CHECK_ELEMENT_ATTRIBUTES(allowedAttrs);

        QString paramType = attributes.value(elemAttrType);
        if (paramType.isEmpty()) {
            paramType = QLatin1String("s");
        }
        mCurrentParameter.setName(attributes.value(elemAttrName));
        mCurrentParameter.setDBusSignature(QDBusSignature(paramType));
        mCurrentParameter.setLabel(attributes.value(elemAttrLabel));
        mCurrentParameter.setMandatory(attributeValueAsBoolean(attributes,
                    elemAttrMandatory));
    } else if (qName == elemPresences) {
        CHECK_ELEMENT_IS_CHILD_OF(elemService);
        QStringList allowedAttrs = QStringList() << elemAttrAllowOthers;
        CHECK_ELEMENT_ATTRIBUTES(allowedAttrs);

        mData->allowOtherPresences = attributeValueAsBoolean(attributes,
                elemAttrAllowOthers);
    } else if (qName == elemPresence) {
        CHECK_ELEMENT_IS_CHILD_OF(elemPresences);
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrId);
        QStringList allowedAttrs = QStringList() << elemAttrId <<
            elemAttrLabel << elemAttrIcon << elemAttrMessage <<
            elemAttrDisabled;
        CHECK_ELEMENT_ATTRIBUTES(allowedAttrs);

        mData->presences.append(Profile::Presence(
                    attributes.value(elemAttrId),
                    attributes.value(elemAttrLabel),
                    attributes.value(elemAttrIcon),
                    attributes.value(elemAttrMessage),
                    attributeValueAsBoolean(attributes, elemAttrDisabled)));
    } else if (qName == elemUnsupportedCCs) {
        CHECK_ELEMENT_IS_CHILD_OF(elemService);
        CHECK_ELEMENT_ATTRIBUTES_COUNT(0);
    } else if (qName == elemCC) {
        CHECK_ELEMENT_IS_CHILD_OF(elemUnsupportedCCs);
        CHECK_ELEMENT_ATTRIBUTES_COUNT(0);
    } else if (qName == elemProperty) {
        CHECK_ELEMENT_IS_CHILD_OF(elemCC);
        CHECK_ELEMENT_ATTRIBUTES_COUNT(2);
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrName);
        CHECK_ELEMENT_HAS_ATTRIBUTE(elemAttrType);

        mCurrentPropertyName = attributes.value(elemAttrName);
        mCurrentPropertyType = attributes.value(elemAttrType);
    } else {
        if (qName != elemName) {
            Tp::warning() << "Ignoring unknown element" << qName;
        } else {
            // check if we are inside <service>
            CHECK_ELEMENT_IS_CHILD_OF(elemService);
            // no element here supports attributes
            CHECK_ELEMENT_ATTRIBUTES_COUNT(0);
        }
    }

#undef CHECK_ELEMENT_IS_CHILD_OF
#undef CHECK_ELEMENT_ATTRIBUTES_COUNT
#undef CHECK_ELEMENT_HAS_ATTRIBUTE
#undef CHECK_ELEMENT_ATTRIBUTES

    mElements.push(qName);
    mCurrentText.clear();
    return true;
}

bool Profile::Private::XmlHandler::endElement(const QString &namespaceURI,
        const QString &localName, const QString &qName)
{
    if (namespaceURI != xmlNs) {
        // ignore all elements with unknown xmlns
        debug() << "Ignoring unknown xmlns" << namespaceURI;
        return true;
    } else if (qName == elemName) {
        mData->name = mCurrentText;
    } else if (qName == elemParam) {
        mCurrentParameter.setValue(ManagerFile::parseValueWithDBusSignature(mCurrentText,
                    mCurrentParameter.dbusSignature().signature()));
        mData->parameters.append(Profile::Parameter(mCurrentParameter));
    } else if (qName == elemCC) {
        mData->unsupportedChannelClassSpecs.append(RequestableChannelClassSpec(mCurrentCC));
        mCurrentCC.fixedProperties.clear();
    } else if (qName == elemProperty) {
        mCurrentCC.fixedProperties[mCurrentPropertyName] =
            ManagerFile::parseValueWithDBusSignature(mCurrentText,
                    mCurrentPropertyType);
    }

    mElements.pop();
    return true;
}

bool Profile::Private::XmlHandler::characters(const QString &str)
{
    mCurrentText += str;
    return true;
}

bool Profile::Private::XmlHandler::fatalError(
        const QXmlParseException &exception)
{
    mErrorString = QString(QLatin1String("parse error at line %1, column %2: "
                "%3"))
        .arg(exception.lineNumber())
        .arg(exception.columnNumber())
        .arg(exception.message());
    return false;
}

QString Profile::Private::XmlHandler::errorString() const
{
    return mErrorString;
}

bool Profile::Private::XmlHandler::attributeValueAsBoolean(
        const QXmlAttributes &attributes, const QString &qName)
{
    QString tmpStr = attributes.value(qName);
    if (tmpStr == QLatin1String("1") ||
        tmpStr == QLatin1String("true")) {
        return true;
    } else {
        return false;
    }
}


Profile::Private::Private()
    : valid(false),
      fake(false),
      allowNonIMType(false)
{
}

void Profile::Private::setServiceName(const QString &serviceName_)
{
    invalidate();

    allowNonIMType = false;
    serviceName = serviceName_;
    lookupProfile();
}

void Profile::Private::setFileName(const QString &fileName)
{
    invalidate();

    allowNonIMType = true;
    QFileInfo fi(fileName);
    serviceName = fi.baseName();

    debug() << "Loading profile file" << fileName;

    QFile file(fileName);
    if (!file.exists()) {
        warning() << QString(QLatin1String("Error parsing profile file %1: file does not exist"))
            .arg(file.fileName());
        return;
    }

    if (!file.open(QFile::ReadOnly)) {
        warning() << QString(QLatin1String("Error parsing profile file %1: "
                    "cannot open file for readonly access"))
            .arg(file.fileName());
        return;
    }

    if (parse(&file)) {
        debug() << "Profile file" << fileName << "loaded successfully";
    }
}

void Profile::Private::lookupProfile()
{
    debug() << "Searching profile for service" << serviceName;

    QStringList searchDirs = Profile::searchDirs();
    bool found = false;
    foreach (const QString searchDir, searchDirs) {
        QString fileName = searchDir + serviceName + QLatin1String(".profile");

        QFile file(fileName);
        if (!file.exists()) {
            continue;
        }

        if (!file.open(QFile::ReadOnly)) {
            continue;
        }

        if (parse(&file)) {
            debug() << "Profile for service" << serviceName << "found:" << fileName;
            found = true;
            break;
        }
    }

    if (!found) {
        debug() << "Cannot find valid profile for service" << serviceName;
    }
}

bool Profile::Private::parse(QFile *file)
{
    invalidate();

    fake = false;
    QFileInfo fi(file->fileName());
    XmlHandler xmlHandler(serviceName, allowNonIMType, &data);

    QXmlSimpleReader xmlReader;
    xmlReader.setContentHandler(&xmlHandler);
    xmlReader.setErrorHandler(&xmlHandler);

    QXmlInputSource xmlInputSource(file);
    if (!xmlReader.parse(xmlInputSource)) {
        warning() << QString(QLatin1String("Error parsing profile file %1: %2"))
            .arg(file->fileName())
            .arg(xmlHandler.errorString());
        invalidate();
        return false;
    }

    valid = true;
    return true;
}

void Profile::Private::invalidate()
{
    valid = false;
    data.clear();
}

/**
 * \class Profile
 * \ingroup utils
 * \headerfile TelepathyQt4/profile.h <TelepathyQt4/Profile>
 *
 * \brief The Profile class provides an easy way to read Telepathy profile
 * files according to http://telepathy.freedesktop.org/wiki/service-profile-v1.
 *
 * Note that profiles with xml element <type> different than "IM" are considered
 * invalid.
 */

/**
 * Create a new Profile object used to read .profiles compliant files.
 *
 * \param serviceName The profile service name.
 * \return A ProfilePtr object pointing to the newly created Profile object.
 */
ProfilePtr Profile::createForServiceName(const QString &serviceName)
{
    ProfilePtr profile = ProfilePtr(new Profile());
    profile->setServiceName(serviceName);
    return profile;
}

/**
 * Create a new Profile object used to read .profiles compliant files.
 *
 * \param fileName The profile file name.
 * \return A ProfilePtr object pointing to the newly created Profile object.
 */
ProfilePtr Profile::createForFileName(const QString &fileName)
{
    ProfilePtr profile = ProfilePtr(new Profile());
    profile->setFileName(fileName);
    return profile;
}

/**
 * Construct a new Profile object used to read .profiles compliant files.
 *
 * \param serviceName The profile service name.
 */
Profile::Profile()
    : mPriv(new Private())
{
}

/**
 * Construct a fake profile using the given \a serviceName, \a cmName,
 * \a protocolName and \a protocolInfo.
 *
 *  - isFake() will return \c true
 *  - type() will return "IM"
 *  - provider() will return an empty string
 *  - serviceName() will return \a serviceName
 *  - name() and protocolName() will return \a protocolName
 *  - iconName() will return "im-\a protocolName"
 *  - cmName() will return \a cmName
 *  - parameters() will return a list matching CM default parameters
 *  - presences() will return an empty list and allowOtherPresences will return
 *    \c true, meaning that CM presences should be used
 *  - unsupportedChannelClassSpecs() will return an empty list
 *
 * \param serviceName The service name.
 * \param cmName The connection manager name.
 * \param protocolName The protocol name.
 * \param protocolInfo The protocol info for the protocol \a protocolName.
 */
Profile::Profile(const QString &serviceName, const QString &cmName,
        const QString &protocolName, const ProtocolInfo &protocolInfo)
    : mPriv(new Private())
{
    mPriv->serviceName = serviceName;

    mPriv->data.type = QString(QLatin1String("IM"));
    // provider is empty
    mPriv->data.name = protocolName;
    mPriv->data.iconName = QString(QLatin1String("im-%1")).arg(protocolName);
    mPriv->data.cmName = cmName;
    mPriv->data.protocolName = protocolName;

    foreach (const ProtocolParameter &protocolParam, protocolInfo.parameters()) {
        if (!protocolParam.defaultValue().isNull()) {
            mPriv->data.parameters.append(Profile::Parameter(
                        protocolParam.name(),
                        protocolParam.dbusSignature(),
                        protocolParam.defaultValue(),
                        QString(), // label
                        false));    // mandatory
        }
    }

    // parameters will be the same as CM parameters
    // set allow others to true meaning that the standard CM presences are
    // supported
    mPriv->data.allowOtherPresences = true;
    // presences will be the same as CM presences
    // unsupported channel classes is empty

    mPriv->valid = true;
    mPriv->fake = true;
}

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

/**
 * Return the unique name of the service to which this profile applies.
 *
 * \return The unique name of the service.
 */
QString Profile::serviceName() const
{
    return mPriv->serviceName;
}

/**
 * Return whether this profile is valid.
 *
 * \return \c true if valid, otherwise \c false.
 */
bool Profile::isValid() const
{
    return mPriv->valid;
}

/**
 * Return whether this profile is fake.
 *
 * Fake profiles are profiles created for services not providing a .profile
 * file.
 *
 * \return \c true if fake, otherwise \c false.
 */
bool Profile::isFake() const
{
    return mPriv->fake;
}

/**
 * Return the type of the service to which this profile applies.
 *
 * In general, services of interest of Telepathy should be of type 'IM'.
 * Other service types exist but are unlikely to affect Telepathy in any way.
 *
 * \return The type of the service.
 */
QString Profile::type() const
{
    return mPriv->data.type;
}

/**
 * Return the name of the vendor/organisation/provider who actually runs the
 * service to which this profile applies.
 *
 * \return The provider of the service.
 */
QString Profile::provider() const
{
    return mPriv->data.provider;
}

/**
 * Return the human-readable name for the service to which this profile applies.
 *
 * \return The Human-readable name of the service.
 */
QString Profile::name() const
{
    return mPriv->data.name;
}

/**
 * Return the base name of the icon for the service to which this profile
 * applies.
 *
 * \return The base name of the icon for the service.
 */
QString Profile::iconName() const
{
    return mPriv->data.iconName;
}

/**
 * Return the connection manager name for the service to which this profile
 * applies.
 *
 * \return The connection manager name for the service.
 */
QString Profile::cmName() const
{
    return mPriv->data.cmName;
}

/**
 * Return the protocol name for the service to which this profile applies.
 *
 * \return The protocol name for the service.
 */
QString Profile::protocolName() const
{
    return mPriv->data.protocolName;
}

/**
 * Return a list of parameters defined for the service to which this profile
 * applies.
 *
 * \return A list of Profile::Parameter.
 */
Profile::ParameterList Profile::parameters() const
{
    return mPriv->data.parameters;
}

/**
 * Return whether this profile defines the parameter named \a name.
 *
 * \return \c true if parameter is defined, otherwise \c false.
 */
bool Profile::hasParameter(const QString &name) const
{
    foreach (const Parameter &parameter, mPriv->data.parameters) {
        if (parameter.name() == name) {
            return true;
        }
    }
    return false;
}

/**
 * Return the parameter for a given \a name.
 *
 * \return A Profile::Parameter.
 */
Profile::Parameter Profile::parameter(const QString &name) const
{
    foreach (const Parameter &parameter, mPriv->data.parameters) {
        if (parameter.name() == name) {
            return parameter;
        }
    }
    return Profile::Parameter();
}

/**
 * Return whether the standard CM presences not defined in presences() are
 * supported.
 *
 * \return \c true if standard CM presences are supported, otherwise \c false.
 */
bool Profile::allowOtherPresences() const
{
    return mPriv->data.allowOtherPresences;
}

/**
 * Return a list of presences defined for the service to which this profile
 * applies.
 *
 * \return A list of Profile::Presence.
 */
Profile::PresenceList Profile::presences() const
{
    return mPriv->data.presences;
}

/**
 * Return whether this profile defines the presence with id \a id.
 *
 * \return \c true if presence is defined, otherwise \c false.
 */
bool Profile::hasPresence(const QString &id) const
{
    foreach (const Presence &presence, mPriv->data.presences) {
        if (presence.id() == id) {
            return true;
        }
    }
    return false;
}

/**
 * Return the presence for a given \a id.
 *
 * \return A Profile::Presence.
 */
Profile::Presence Profile::presence(const QString &id) const
{
    foreach (const Presence &presence, mPriv->data.presences) {
        if (presence.id() == id) {
            return presence;
        }
    }
    return Profile::Presence();
}

/**
 * A list of channel classes not supported by the service to which this profile
 * applies.
 *
 * \return A list of RequestableChannelClassSpec.
 */
RequestableChannelClassSpecList Profile::unsupportedChannelClassSpecs() const
{
    return mPriv->data.unsupportedChannelClassSpecs;
}

void Profile::setServiceName(const QString &serviceName)
{
    mPriv->setServiceName(serviceName);
}

void Profile::setFileName(const QString &fileName)
{
    mPriv->setFileName(fileName);
}

QStringList Profile::searchDirs()
{
    QStringList ret;

    QString xdgDataHome = QString::fromLocal8Bit(qgetenv("XDG_DATA_HOME"));
    if (xdgDataHome.isEmpty()) {
        ret << QDir::homePath() + QLatin1String("/.local/share/data/telepathy/profiles/");
    } else {
        ret << xdgDataHome + QLatin1String("/telepathy/profiles/");
    }

    QString xdgDataDirsEnv = QString::fromLocal8Bit(qgetenv("XDG_DATA_DIRS"));
    if (xdgDataDirsEnv.isEmpty()) {
        ret << QLatin1String("/usr/local/share/telepathy/profiles/");
        ret << QLatin1String("/usr/share/telepathy/profiles/");
    } else {
        QStringList xdgDataDirs = xdgDataDirsEnv.split(QLatin1Char(':'));
        foreach (const QString xdgDataDir, xdgDataDirs) {
            ret << xdgDataDir + QLatin1String("/telepathy/profiles/");
        }
    }

    return ret;
}


struct TELEPATHY_QT4_NO_EXPORT Profile::Parameter::Private
{
    QString name;
    QDBusSignature dbusSignature;
    QVariant value;
    QString label;
    bool mandatory;
};

/**
 * \class Profile::Parameter
 * \ingroup utils
 * \headerfile TelepathyQt4/profile.h <TelepathyQt4/Profile>
 *
 * \brief The Profile::Parameter class represents a parameter defined in
 * .profile files.
 */

/**
 * Construct a new Profile::Parameter object.
 */
Profile::Parameter::Parameter()
    : mPriv(new Private)
{
    mPriv->mandatory = false;
}

/**
 * Construct a new Profile::Parameter object that is a copy of \a other.
 */
Profile::Parameter::Parameter(const Parameter &other)
    : mPriv(new Private)
{
    mPriv->name = other.mPriv->name;
    mPriv->dbusSignature = other.mPriv->dbusSignature;
    mPriv->value = other.mPriv->value;
    mPriv->label = other.mPriv->label;
    mPriv->mandatory = other.mPriv->mandatory;
}

/**
 * Construct a new Profile::Parameter object.
 *
 * \param name The parameter name.
 * \param dbusSignature The parameter D-Bus signature.
 * \param value The parameter value.
 * \param label The parameter label.
 * \param mandatory Whether this parameter is mandatory.
 */
Profile::Parameter::Parameter(const QString &name,
        const QDBusSignature &dbusSignature,
        const QVariant &value,
        const QString &label,
        bool mandatory)
    : mPriv(new Private)
{
    mPriv->name = name;
    mPriv->dbusSignature = dbusSignature;
    mPriv->value = value;
    mPriv->label = label;
    mPriv->mandatory = mandatory;
}

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

/**
 * Return the name of this parameter.
 *
 * \return The name of this parameter.
 */
QString Profile::Parameter::name() const
{
    return mPriv->name;
}

void Profile::Parameter::setName(const QString &name)
{
    mPriv->name = name;
}

/**
 * Return the D-Bus signature of this parameter.
 *
 * \return The D-Bus signature of this parameter.
 */
QDBusSignature Profile::Parameter::dbusSignature() const
{
    return mPriv->dbusSignature;
}

void Profile::Parameter::setDBusSignature(const QDBusSignature &dbusSignature)
{
    mPriv->dbusSignature = dbusSignature;
}

/**
 * Return the QVariant::Type of this parameter, constructed using
 * dbusSignature().
 *
 * \return The QVariant::Type of this parameter.
 */
QVariant::Type Profile::Parameter::type() const
{
    return ManagerFile::variantTypeFromDBusSignature(mPriv->dbusSignature.signature());
}

/**
 * Return the value of this parameter.
 *
 * If mandatory() returns \c true, the value must not be modified and should be
 * used as is when creating accounts for this profile.
 *
 * \return The value of this parameter.
 */
QVariant Profile::Parameter::value() const
{
    return mPriv->value;
}

void Profile::Parameter::setValue(const QVariant &value)
{
    mPriv->value = value;
}

/**
 * Return the human-readable label of this parameter.
 *
 * \return The human-readable label of this parameter.
 */
QString Profile::Parameter::label() const
{
    return mPriv->label;
}

void Profile::Parameter::setLabel(const QString &label)
{
    mPriv->label = label;
}

/**
 * Return whether this parameter is mandatory, or whether the value returned by
 * value() should be used as is when creating accounts for this profile.
 *
 * \return \c true if mandatory, otherwise \c false.
 */
bool Profile::Parameter::isMandatory() const
{
    return mPriv->mandatory;
}

void Profile::Parameter::setMandatory(bool mandatory)
{
    mPriv->mandatory = mandatory;
}

Profile::Parameter &Profile::Parameter::operator=(const Profile::Parameter &other)
{
    mPriv->name = other.mPriv->name;
    mPriv->dbusSignature = other.mPriv->dbusSignature;
    mPriv->value = other.mPriv->value;
    mPriv->label = other.mPriv->label;
    mPriv->mandatory = other.mPriv->mandatory;
    return *this;
}


struct TELEPATHY_QT4_NO_EXPORT Profile::Presence::Private
{
    QString id;
    QString label;
    QString iconName;
    QString message;
    bool disabled;
};

/**
 * \class Profile::Presence
 * \ingroup utils
 * \headerfile TelepathyQt4/profile.h <TelepathyQt4/Profile>
 *
 * \brief The Profile::Presence class represents a presence defined in
 * .profile files.
 */

/**
 * Construct a new Profile::Presence object.
 */
Profile::Presence::Presence()
    : mPriv(new Private)
{
    mPriv->disabled = false;
}

/**
 * Construct a new Profile::Presence object that is a copy of \a other.
 */
Profile::Presence::Presence(const Presence &other)
    : mPriv(new Private)
{
    mPriv->id = other.mPriv->id;
    mPriv->label = other.mPriv->label;
    mPriv->iconName = other.mPriv->iconName;
    mPriv->message = other.mPriv->message;
    mPriv->disabled = other.mPriv->disabled;
}

/**
 * Construct a new Profile::Presence object.
 *
 * \param id The presence id.
 * \param label The presence label.
 * \param iconName The presence icon name.
 * \param message The presence message.
 * \param disabled Whether this presence is supported.
 */
Profile::Presence::Presence(const QString &id,
        const QString &label,
        const QString &iconName,
        const QString &message,
        bool disabled)
    : mPriv(new Private)
{
    mPriv->id = id;
    mPriv->label = label;
    mPriv->iconName = iconName;
    mPriv->message = message;
    mPriv->disabled = disabled;
}

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

/**
 * Return the Telepathy presence id for this presence.
 *
 * \return The Telepathy presence id for this presence.
 */
QString Profile::Presence::id() const
{
    return mPriv->id;
}

void Profile::Presence::setId(const QString &id)
{
    mPriv->id = id;
}

/**
 * Return the label that should be used for this presence.
 *
 * \return The label for this presence.
 */
QString Profile::Presence::label() const
{
    return mPriv->label;
}

void Profile::Presence::setLabel(const QString &label)
{
    mPriv->label = label;
}

/**
 * Return the icon name of this presence.
 *
 * \return The icon name of this presence.
 */
QString Profile::Presence::iconName() const
{
    return mPriv->iconName;
}

void Profile::Presence::setIconName(const QString &iconName)
{
    mPriv->iconName = iconName;
}

/**
 * Return whether user-defined text-message can be attached to this presence.
 *
 * \return \c true if user-defined text-message can be attached to this presence, \c false
 *         otherwise.
 */
bool Profile::Presence::canHaveStatusMessage() const
{
    if (mPriv->message == QLatin1String("1") ||
        mPriv->message == QLatin1String("true")) {
        return true;
    }

    return false;
}

/**
 * \deprecated Use canHaveStatusMessage() instead.
 */
QString Profile::Presence::message() const
{
    return mPriv->message;
}

void Profile::Presence::setMessage(const QString &message)
{
    mPriv->message = message;
}

/**
 * Return whether this presence is supported for the service to which this
 * profile applies.
 *
 * \return \c true if supported, otherwise \c false.
 */
bool Profile::Presence::isDisabled() const
{
    return mPriv->disabled;
}

void Profile::Presence::setDisabled(bool disabled)
{
    mPriv->disabled = disabled;
}

Profile::Presence &Profile::Presence::operator=(const Profile::Presence &other)
{
    mPriv->id = other.mPriv->id;
    mPriv->label = other.mPriv->label;
    mPriv->iconName = other.mPriv->iconName;
    mPriv->message = other.mPriv->message;
    mPriv->disabled = other.mPriv->disabled;
    return *this;
}

} // Tp