VCardUtils.cpp 10.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
/**************************************************************************
* Copyright (C) 2016 by Savoir-faire Linux                                *
* Author: Jger Nicolas <nicolas.jager@savoirfairelinux.com>              *
* Author: Traczyk Andreas <traczyk.andreas@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 <pch.h>

#include <direct.h>

23 24
#include "lodepng.h"

25
using namespace RingClientUWP;
26
using namespace ViewModel;
27 28 29 30 31 32 33 34 35 36 37 38 39 40
using namespace VCardUtils;

using namespace Windows::UI::Core;

std::string
getBetweenTokens(   const std::string& str,
                    const char* token1,
                    const char* token2 = nullptr)
{
    std::size_t start = token1 ? (str.find(token1) + strlen(token1)) : 0;
    std::size_t length = token2 ? (str.find(token2) - 1 - start) : std::string::npos;
    return str.substr(start, length);
}

41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
std::map<std::string, std::string>
VCardUtils::parseContactRequestPayload(const std::string& payload)
{
    std::map<std::string, std::string> map;

    std::stringstream _payload(payload);
    std::string _line;

    while (std::getline(_payload, _line)) {
        auto msgPos = _line.find(Symbols::END_TOKEN);
        if (msgPos != std::string::npos) {
            if (std::getline(_payload, _line))
                map["MESSAGE"].append(_line);
            break;
        }
        map["VCARD"].append(_line).append("\n");
    }

    return map;
}

62 63
VCard::VCard(Contact^ owner, String^ accountId)
    : m_Owner(owner), m_accountId(Utils::toString(accountId))
64 65 66 67 68 69
{}

int
VCard::receiveChunk(const std::string& args, const std::string& payload)
{
    MSG_("receive VCARD chunk");
70 71
    static int partsReceived = 0;
    static std::vector<std::string> parts;
72 73 74 75 76

    int32_t _id = stoi( getBetweenTokens(args, Symbols::ID_TOKEN, Symbols::PART_TOKEN) );
    uint32_t _part = stoi( getBetweenTokens(args, Symbols::PART_TOKEN, Symbols::OF_TOKEN) );
    uint32_t _of = stoi( getBetweenTokens(args, Symbols::OF_TOKEN) );

77 78
    if (parts.empty())
        parts.resize(_of);
79

80 81 82
    if (parts[_part - 1].empty()) {
        parts[_part - 1].assign(payload);
        partsReceived++;
83

84 85 86 87
        if (partsReceived == _of) {
            m_data.clear();
            for (const auto& part : parts) {
                m_data.append(part);
atraczyk's avatar
atraczyk committed
88
            }
89

90 91
            partsReceived = 0;
            parts.clear();
92

93 94 95 96
            completeReception();
            MSG_("VCARD_COMPLETE");
            return VCARD_COMPLETE;
        }
97
    }
98

99 100 101
    return VCARD_INCOMPLETE;
}

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
std::string
getVCardValue(std::string data, std::string key)
{
    std::string value;
    std::stringstream _data(data);
    std::string _line;
    while (std::getline(_data, _line)) {
        if (_line.find(key) != std::string::npos) {
            value = _line.substr(key.length());
            break;
        }
    }
    value.erase(std::remove(value.begin(), value.end(), '\r'), value.end());
    return value;
}

118 119 120 121 122 123 124 125
int
VCard::parseFromString()
{
    std::stringstream _data(m_data);
    std::string _line;

    m_mParts.clear();

126 127
    m_mParts[Property::UID] = getVCardValue(m_data, "UID:");
    if (m_mParts[Property::UID].empty())
128
        m_mParts[Property::UID] = Utils::genID(0LL, 9999999999999LL);
129 130 131 132
    MSG_(m_mParts[Property::UID]);

    m_mParts[Property::FN] = getVCardValue(m_data, "FN:");
    MSG_(m_mParts[Property::FN]);
133 134

    while (std::getline(_data, _line)) {
135
        if (_line.find("PHOTO;") != std::string::npos)
136
            break;
137
    }
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

    while (std::getline(_data, _line)) {
        if (_line.find("PHOTO;") != std::string::npos)
            break;
    }

    size_t pos = _line.find("PNG:");
    if (pos == std::string::npos) {
        pos = _line.find("JPEG:");
        if (pos != std::string::npos)
            m_mParts[Property::PHOTO].append(_line.substr(pos + 5));
    }
    else
        m_mParts[Property::PHOTO].append(_line.substr(pos + 4));

    return 1;
154 155
}

156 157 158
void
VCard::completeReception()
{
159 160 161 162 163 164 165 166
    if (parseFromString()) {
        saveToFile();
        decodeBase64ToPNGFile();
    }
    else {
        return;
    }

167 168 169
    if (!m_mParts[Property::FN].empty())
        m_Owner->_displayName = Utils::toPlatformString(m_mParts[Property::FN]);
    m_Owner->_vcardUID = Utils::toPlatformString(m_mParts[Property::UID]);
170 171
    if (auto contactListModel =  AccountsViewModel::instance->getContactListModel(m_accountId))
        contactListModel->saveContactsToFile();
172 173
    RingD::instance->raiseVCardUpdated(m_Owner);
    SmartPanelItemsViewModel::instance->update({ "_avatarImage" });
174 175
}

176 177 178 179
void
VCard::send(std::string callID, const char* vCardFile)
{
    int i = 0;
180
    const int chunkSize = 1024;
181 182 183 184 185 186 187 188
    std::string vCard;
    if (vCardFile) {
        std::ifstream file(vCardFile);
        vCard.assign(( std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    }
    else
        vCard = asString();
    int total = vCard.size() / chunkSize + (vCard.size() % chunkSize ? 1 : 0);
atraczyk's avatar
atraczyk committed
189
    std::string idkey = Utils::genID(0LL, 99999999LL);
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
    while ( vCard.size() ) {
        std::map<std::string, std::string> chunk;
        std::stringstream key;
        key << PROFILE_VCF
            << ";id=" << idkey
            << ",part=" << std::to_string(i + 1)
            << ",of=" << std::to_string(total);
        chunk[key.str()] = vCard.substr(0, chunkSize);
        vCard = vCard.erase(0, chunkSize);
        ++i;
        sendChunk(callID, chunk);
    }
}

void
VCard::sendChunk(std::string callID, std::map<std::string, std::string> chunk)
{
    MSG_("sending chunk...");
    for(auto i : chunk)
        MSG_("key:" + i.first + "\nvalue:" + i.second);
    RingD::instance->sendSIPTextMessageVCF(callID, chunk);
}

std::string
VCard::asString()
{
    std::stringstream ret;

    ret << Symbols::BEGIN_TOKEN     << Symbols::END_LINE_TOKEN;

    ret << Property::VERSION        << Symbols::SEPERATOR2      << "3.0"
        << Symbols::END_LINE_TOKEN;

    ret << Property::UID            << Symbols::SEPERATOR2      << m_mParts[Property::UID]
        << Symbols::END_LINE_TOKEN;

atraczyk's avatar
atraczyk committed
226
    ret << Property::FN             << Symbols::SEPERATOR2      << m_mParts[Property::FN]
227 228 229 230 231 232 233 234 235 236 237 238 239 240
        << Symbols::END_LINE_TOKEN;

    ret << Property::PHOTO          << Symbols::SEPERATOR1      << Symbols::PHOTO_ENC
        << Symbols::SEPERATOR1      << Symbols::PHOTO_TYPE      << Symbols::SEPERATOR2
        << m_mParts[Property::PHOTO]                            << Symbols::END_LINE_TOKEN;

    ret << Symbols::END_TOKEN;

    return std::string(ret.str());
}

void
VCard::decodeBase64ToPNGFile()
{
241 242 243
    if (!m_mParts[Property::PHOTO].size())
        return;

244 245 246 247
    size_t padding = m_mParts[Property::PHOTO].size() % 4;
    if (padding)
        m_mParts[Property::PHOTO].append(padding, 0);

248 249 250 251 252 253 254 255 256 257
    std::vector<uint8_t> decodedData = Utils::base64::decode(m_mParts[Property::PHOTO]);

    std::vector<uint8_t> image;
    unsigned width, height;
    unsigned err = lodepng::decode(image, width, height, decodedData);
    if (err) {
        MSG_("decoded PNG data corrupt - aborting save to file");
        return;
    }

258 259 260 261 262 263 264 265 266
    std::string vcardDir(RingD::instance->getLocalFolder() + ".vcards\\");
    std::string pngFile(m_mParts[Property::UID] + ".png");
    MSG_("Saving PNG (" + m_mParts[Property::UID] + ") to " + pngFile + "...");
    if (_mkdir(vcardDir.c_str())) {
        std::ofstream file(vcardDir + pngFile, std::ios::out | std::ios::trunc | std::ios::binary);
        if (file.is_open()) {
            for (auto i : decodedData)
                file << i;
            file.close();
267
            //RingClientUWP::ResourceMananger::instance->preloadImage(Utils::toPlatformString(vcardDir + pngFile));
atraczyk's avatar
atraczyk committed
268 269
            m_Owner->_avatarImage = Utils::toPlatformString(vcardDir + pngFile);
            MSG_("Done decoding and saving VCard Photo to PNG");
270 271 272 273 274 275 276 277 278 279 280 281 282
        }
    }
}

void
VCard::encodePNGToBase64()
{
    std::string vcardDir(RingD::instance->getLocalFolder() + ".vcards\\");
    std::string pngFile(m_mParts[Property::UID] + ".png");
    std::basic_ifstream<uint8_t> file(vcardDir + pngFile, std::ios::in | std::ios::binary);
    if (file.is_open()) {
        auto eos = std::istreambuf_iterator<uint8_t>();
        auto data = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(file), eos);
283
        m_mParts[Property::PHOTO] = Utils::base64::encode(data);
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
        file.close();
        MSG_("Done encoding PNG to b64");
    }
}

int
VCard::saveToFile()
{
    std::string vcardDir(RingD::instance->getLocalFolder() + ".vcards\\");
    std::string vcardFile(m_mParts[Property::UID] + ".vcard");
    MSG_("Saving VCard (" + m_mParts[Property::UID] + ") to " + vcardFile + "...");
    if (_mkdir(vcardDir.c_str())) {
        std::ofstream file(vcardDir + vcardFile, std::ios::out | std::ios::trunc);
        if (file.is_open()) {
            file << asString();
            file.close();
            MSG_("Done Saving VCard");
            return 1;
        }
    }
    return 0;
}

void
VCard::setData(std::map<std::string, std::string> data)
{
    m_mParts = data;
311
}
312 313 314 315 316 317 318 319 320 321

void
VCard::setData(const std::string& data)
{
    m_data = data;
}

std::string
VCard::getPart(const std::string& part)
{
322 323 324 325 326 327 328 329
    std::string p;
    try {
        p = m_mParts.at(part);
    }
    catch (std::exception& e) {
        MSG_(e.what());
    }
    return p;
330
}