windowscontactbackend.cpp 14 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/***************************************************************************
 * Copyright (C) 2015 by Savoir-Faire Linux                                *
 * Author: Edric Ladent Milaret <edric.ladent-milaret@savoirfairelinux.com>*
 *                                                                         *
 * This program is free software; you can redistribute it and/or modify    *
 * it under the terms of the GNU General Public License as published by    *
 * the Free Software Foundation; either version 3 of the License, or       *
 * (at your option) any later version.                                     *
 *                                                                         *
 * This program 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 General Public License for more details.                            *
 *                                                                         *
 * You should have received a copy of the GNU General Public License       *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.   *
 **************************************************************************/

#include "windowscontactbackend.h"

21 22 23 24 25 26 27
#include <QtXml>

#include "personmodel.h"
#include "categorizedcontactmodel.h"

#include "utils.h"

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
WindowsContactEditor::WindowsContactEditor(CollectionMediator<Person> *m
                                           , WindowsContactBackend *parent)
    : CollectionEditor<Person>(m),collection_(parent)
{

}

WindowsContactEditor::~WindowsContactEditor()
{

}

bool
WindowsContactEditor::save(const Person *item)
{
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
    QFile file(QStandardPaths::writableLocation
               (QStandardPaths::HomeLocation) + "/Contacts/"
               + item->formattedName() + ".contact");
    if (!file.open(QIODevice::ReadWrite)) {
        file.close();
        qDebug() << "Cannot open contact file";
        return false;
    }

    QDomDocument doc;
    doc.setContent(&file);

    auto root = doc.elementsByTagName("c:contact").at(0);
    auto nodes = doc.elementsByTagName("c:PhoneNumberCollection");

    //if PhoneNumberCollection already exists
    QVector<QString> nodeNumberVector;
    if (nodes.length()) {
        auto phoneNumberCollection = nodes.at(0);
        auto phoneNumbers = doc.elementsByTagName("c:Number");
        auto virtualPhoneNumber = item->phoneNumbers();
        for (int i = 0; i < phoneNumbers.length(); i++) {
            auto node = phoneNumbers.at(i).toElement();
            nodeNumberVector.append(node.text());
        }
        for (auto elem : virtualPhoneNumber) {
            if (not nodeNumberVector.contains(elem->uri())) {
                auto phoneNumber = doc.createElement("c:PhoneNumber");
                phoneNumberCollection.appendChild(phoneNumber);
                phoneNumber.setAttribute("c:ElementID", Utils::GenGUID());
                auto numberNode = doc.createElement("c:Number");
                phoneNumber.appendChild(numberNode);
                auto numberValue = doc.createTextNode(elem->uri());
                numberNode.appendChild(numberValue);
            }
        }
    } else {
        auto phoneNumberCollection = doc.createElement("c:PhoneNumberCollection");
        root.appendChild(phoneNumberCollection);
        auto phoneNumber = doc.createElement("c:PhoneNumber");
        phoneNumberCollection.appendChild(phoneNumber);
        phoneNumber.setAttribute("c:ElementID", Utils::GenGUID());
        auto numberNode = doc.createElement("c:Number");
        phoneNumber.appendChild(numberNode);
        auto numberValue = doc.createTextNode(item->phoneNumbers().at(0)->uri());
        numberNode.appendChild(numberValue);
    }
    file.resize(0);
    file.write(doc.toByteArray());
    file.close();
    return true;
94 95 96 97 98
}

bool
WindowsContactEditor::remove(const Person *item)
{
99 100 101
    items_.removeOne(const_cast<Person*>(item));
    mediator()->removeItem(item);
    return true;
102 103 104 105 106 107 108 109 110 111
}

bool
WindowsContactEditor::edit(Person *item)
{
    Q_UNUSED(item)
    return false;
}

bool
112
WindowsContactEditor::addNew(Person *item)
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
    QDomDocument doc;
    QFile file(QStandardPaths::writableLocation
               (QStandardPaths::HomeLocation) + "/Contacts/"
               + item->formattedName()+".contact");
    if (file.exists())
        return false;
    if (!file.open(QIODevice::ReadWrite)) {
        file.close();
        qDebug() << "Cannot create contact file";
        return false;
    }
    doc.appendChild(
                doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""));

    //Create root
    auto root = doc.createElement("c:contact");
    root.setAttribute("c:Version", "1");
    root.setAttribute("xmlns:c", "http://schemas.microsoft.com/Contact");
    root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    root.setAttribute("xmlns:MSP2P","http://schemas.microsoft.com/Contact/Extended/MSP2P");
    doc.appendChild(root);

    auto date = Utils::GetISODate();

    //Create creation date
    auto creationDateNode = doc.createElement("c:CreationDate");
    auto creationDateValue = doc.createTextNode(date);
    creationDateNode.appendChild(creationDateValue);
    root.appendChild(creationDateNode);

    //Create extended node
    auto extendedNode = doc.createElement("c:Extended");
    extendedNode.setAttribute("xsi:nil", "true");
    root.appendChild(extendedNode);

    //Create contactID collection
    auto contactIDCol = doc.createElement("c:ContactIDCollection");
    root.appendChild(contactIDCol);
    auto contactID = doc.createElement("c:ContactID");
    contactID.setAttribute("c:ElementID", Utils::GenGUID());
    auto contactValue = doc.createElement("c:Value");
    auto value = doc.createTextNode(item->uid());
    contactValue.appendChild(value);
    contactID.appendChild(contactValue);
    contactIDCol.appendChild(contactID);

    //Create NameCollection
    auto nameCollection = doc.createElement("c:NameCollection");
    root.appendChild(nameCollection);
    auto name = doc.createElement("c:Name");
    nameCollection.appendChild(name);
    name.setAttribute("c:ElementID", Utils::GenGUID());
    auto formattedName = doc.createElement("c:FormattedName");
    name.appendChild(formattedName);
    auto formattedNameValue = doc.createTextNode(item->formattedName());
    formattedName.appendChild(formattedNameValue);

    //Create PhoneNumberCollection
    auto phoneNumberCollection = doc.createElement("c:PhoneNumberCollection");
    root.appendChild(phoneNumberCollection);
    auto phoneNumber = doc.createElement("c:PhoneNumber");
    phoneNumberCollection.appendChild(phoneNumber);
    phoneNumber.setAttribute("c:ElementID", Utils::GenGUID());
    auto numberNode = doc.createElement("c:Number");
    phoneNumber.appendChild(numberNode);
    auto numberValue = doc.createTextNode(item->phoneNumbers().at(0)->uri());
    numberNode.appendChild(numberValue);

    //Write to file
    file.write(doc.toByteArray());
    file.close();

    //Add it to the collection
    addExisting(item);

    return true;
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
}

bool
WindowsContactEditor::addExisting(const Person *item)
{
    items_ << const_cast<Person*>(item);
    mediator()->addItem(item);
    return true;
}

QVector<Person*>
WindowsContactEditor::items() const
{
    return items_;
}

WindowsContactBackend::WindowsContactBackend(CollectionMediator<Person>* mediator,
                                             CollectionInterface* parent)
    : CollectionInterface(new WindowsContactEditor(mediator,this), parent)
209
    , mediator_(mediator), watcher_(new QFileSystemWatcher())
210 211 212 213 214 215 216 217 218 219 220 221 222
{

}

WindowsContactBackend::~WindowsContactBackend()
{

}

bool
WindowsContactBackend::load()
{
    QtConcurrent::run(this, &WindowsContactBackend::loadRun);
223 224
    watcher_->addPath(QStandardPaths::writableLocation
                      (QStandardPaths::HomeLocation) + "/Contacts");
225 226 227 228 229
//FIXME: Temporary disabling watch on the dir because of double add
//    QObject::connect(watcher_, &QFileSystemWatcher::directoryChanged, [=](QString path) {
//        Q_UNUSED(path)
//        QtConcurrent::run(this, &WindowsContactBackend::loadRun);
//    });
230 231 232 233 234 235 236 237 238
    return true;
}

bool
WindowsContactBackend::loadRun()
{
    QDir contactDir(QStandardPaths::writableLocation
                    (QStandardPaths::HomeLocation) + "/Contacts");
    QStringList filesList = contactDir.entryList(QStringList("*.contact"));
239
    auto ret = true;
240
    for(auto contactFileName : filesList) {
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
        if (not getPersonFromContactFile(contactDir, contactFileName))
            ret = false;
    }
    return ret;
}

bool
WindowsContactBackend::getPersonFromContactFile(const QDir& contactDir,
                                                const QString &contactFileName)
{
    QString contactFilePath
            (contactDir.absolutePath() + "/" +  contactFileName);
    QFile contactFile(contactFilePath);
    if (contactFile.open(QIODevice::ReadOnly)) {
        QXmlStreamReader reader;
        Person *p = new Person(this);
        QVector<ContactMethod*> contactMethod;
        reader.setDevice(&contactFile);
        while (!reader.atEnd()) {
            reader.readNext();
            if (reader.isStartElement()) {
                QString name = reader.name().toString();
                if (name == "FormattedName")
                    p->setFormattedName(reader.readElementText());
                else if (name == "NickName")
                    p->setNickName(reader.readElementText());
                else if (name == "GivenName")
                    p->setFirstName(reader.readElementText());
                else if (name == "FamilyName")
                    p->setFamilyName(reader.readElementText());
                else if (name == "Company")
                    p->setOrganization(reader.readElementText());
                else if (name == "Department")
                    p->setDepartment(reader.readElementText());
                else if (name == "Number") {
                    QString number = reader.readElementText();
                    if (not number.isEmpty()) {
                        ContactMethod *contact =
                                PhoneDirectoryModel::instance()->getNumber(number,p);
                        contactMethod.append(contact);
281
                    }
282 283
                } else if (name == "ContactID") {
                    while (reader.name().toString() != "Value")
284
                        reader.readNext();
285 286 287 288 289 290 291 292 293 294 295
                    p->setUid(reader.readElementText().toUtf8());
                }
                else if (name == "Photo") {
                    //FIXME: It seems to be possible to have multiple photo...
                    reader.readNext();
                    if (reader.name().toString() == "Url") {
                        QString photoValue = reader.readElementText();
                        QImage photo;
                        photo.load(photoValue);
                        p->setPhoto(photo.scaled(sizePhoto_,sizePhoto_, Qt::KeepAspectRatio,
                                                 Qt::SmoothTransformation));
296
                    }
297 298 299 300 301 302 303 304 305 306 307 308 309 310
                }
                else if (name == "EmailAddress") {
                    QString address;
                    bool isPreferred = false;
                    reader.readNext();
                    while (reader.name().toString() != "EmailAddress"
                           && !reader.atEnd()) {
                        if (reader.isStartElement()) {
                            QString tag = reader.name().toString();
                            if (tag == "Address")
                                address = reader.readElementText();
                            else if (tag == "Label")
                                if (reader.readElementText() == "Preferred")
                                    isPreferred = true;
311
                        }
312
                        reader.readNext();
313
                    }
314 315
                    if (isPreferred)
                        p->setPreferredEmail(address);
316 317
                }
            }
318 319 320 321 322 323 324 325
        }
        if (reader.hasError()) {
            qDebug() << reader.errorString();
            contactFile.close();
            return false;
        } else {
            Person* existing = PersonModel::instance()->getPersonByUid(p->uid());
            if (existing) {
326
                if (contactMethod.size() > 0)
327 328 329 330 331 332 333 334 335 336 337 338 339
                    existing->setContactMethods ( contactMethod   );
                existing->setNickName       ( p->nickName()       );
                existing->setFirstName      ( p->firstName()      );
                existing->setFamilyName     ( p->secondName()     );
                existing->setFormattedName  ( p->formattedName()  );
                existing->setOrganization   ( p->organization()   );
                existing->setPreferredEmail ( p->preferredEmail() );
                existing->setGroup          ( p->group()          );
                existing->setDepartment     ( p->department()     );
                existing->setPhoto          ( p->photo()          );
                delete p;
            } else {
                p->setContactMethods(contactMethod);
340 341
                editor<Person>()->addExisting(p);
            }
342
            return true;
343
        }
344 345 346
    } else {
        qDebug() << "Error Opening contact file : " << contactFileName;
        return false;
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
    }
}

bool
WindowsContactBackend::reload()
{
    return false;
}

bool
WindowsContactBackend::clear()
{
    return false;
}

QString
WindowsContactBackend::name() const
{
    return "Windows Contact Backend";
}

QString
WindowsContactBackend::category() const
{
    return "Contacts";
}

bool
WindowsContactBackend::isEnabled() const
{
    return true;
}

QByteArray
WindowsContactBackend::id() const
{
    return "wincb";
}

FlagPack<CollectionInterface::SupportedFeatures> WindowsContactBackend::supportedFeatures() const
{
    return (
                CollectionInterface::SupportedFeatures::NONE |
390 391 392 393
                CollectionInterface::SupportedFeatures::LOAD |
                CollectionInterface::SupportedFeatures::SAVE |
                CollectionInterface::SupportedFeatures::REMOVE |
                CollectionInterface::SupportedFeatures::ADD);
394 395
}