⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 maincpp.cpp

📁 funambol windows mobile plugin source code, the source code is taken from the funambol site
💻 CPP
📖 第 1 页 / 共 2 页
字号:
        if (ret == 0) {
            config.save();
        }
        else if (ret > 299 && ret < 599) {
            // try to discover if there are sources that are ok...
            SyncSource* s = NULL;
            for (int i = 0; (s = s_array[i]) != NULL; i++) {
                SyncSourceReport* sr = s->getReport();
                if (sr->checkState()) {
                    //SyncSourceConfig& sc = s->getConfig();
                    //ClientSettings cs(APPLICATION_URI);
                    //cs.saveSyncSourceConfig(sc);
                    config.saveSyncSourceConfig(s->getConfig().getName());
                }
                else{
                    //this is to check if there's a problem with the email account
                    //if the email account on the server is not set we find it and
                    //trasform the error code from 506 to 588 so we can catch this
                    //error in uidlg.cpp and popup the right allert message to the
                    //user
                    const char* errorToCheck = "Error Setting Preliminary Info: Error getting Account information " ;
                    if( sr->getLastErrorCode() == 506 &&\
                        strcmp(sr->getLastErrorMsg(),errorToCheck) == 0 &&\
                        strcmp(sr->getSourceName(), "mail") == 0){
                            ret = 588;
                    }
                }
            }
        }

        // check source states and signal them to UI
        SyncSource* s = NULL;
        int sourceID = -1;
        for (int i = 0; (s = s_array[i]) != NULL; i++) {
            SyncSourceReport* sr = s->getReport();
            if(strcmp(sr->getSourceName(),CONTACTS_NAME_A) ==0)
                sourceID = SOURCE_CONTACTS;
            if(strcmp(sr->getSourceName(),APPOINTMENTS_NAME_A) ==0)
                sourceID = SOURCE_CALENDAR;
            if(strcmp(sr->getSourceName(),TASKS_NAME_A) ==0)
                sourceID = SOURCE_TASKS;
            if(strcmp(sr->getSourceName(),FILES_NAME_A) ==0)
                sourceID = SOURCE_BRIEFCASE;
            if(strcmp(sr->getSourceName(),MAILS_NAME_A) ==0)
                sourceID = SOURCE_MAIL;
            if(strcmp(sr->getSourceName(),NOTES_NAME_A) ==0)
                sourceID = SOURCE_NOTES;

            if (sr->checkState())
                SendMessage(HwndFunctions::getWindowHandle(), ID_MYMSG_SOURCE_STATE, sourceID, SYNCSOURCE_STATE_OK);
            else
                SendMessage(HwndFunctions::getWindowHandle(), ID_MYMSG_SOURCE_STATE, sourceID, SYNCSOURCE_STATE_NOT_SYNCED);
        }


        if (mailSource.getIsMailInOutbox() && ret == 0) {
             LOG.debug("performSync: there are mails in outbox");
        }

        if (mailSource.getIsMailInInbox()) {
            LOG.info("performSync: new mail in inbox.");
            /*
            // temporary removed default funambol sound. Use the usual
            // set in the ppc
            LOG.info("performSync: new mail in inbox, playing sound.");
            wstring s(path);
            s += TEXT("\\newmessage.wav");

            if (!PlaySound(s.c_str(), NULL, SND_SYNC | SND_NOSTOP)) {
                LOG.info("Could not play sound: %s", s.c_str());
                MessageBeep(MB_ICONASTERISK);
            }
            */
        }

        if (mailSource.getFailedSendMailInOutbox()) {
            LOG.error("performSync: there was an error sending an email, alerting the user.");
            wstring message = getMailUnsent(mailSource);
            MessageBox(NULL, message.c_str(), TEXT("Alert"),
                    MB_OK | MB_ICONINFORMATION | MB_SETFOREGROUND);
        }

        LOG.debug("Sync ended multiple sources.");
    }
    return ret;
}

/*
 * Entry point to kickoff the synchronization process, both specifying the
 * sources or not. The default is to make all the configured sources.
 *
 * @param path    : the install path of the SyncClient PIM application on
 *                  the device
 * @param sources : NULL terminated array of strings containing the source
 *                  name of the sources to synchronize
 * @param ids :     NULL terminated array of strings containing the id of the mail
 *                  that must be synched with a INCLUSIVE filter. Note that this parameter
 *                  could be valorized only when there is only a source and this source is mail
 *
 * To avoid a server bug and send every time the capabilities to the server
 * in order to receive the NumberOfChanges tag
 * RESET the hashDevInfo flag in the registry
 */

DWORD WINAPI synchronize (
                const wchar_t* path,
                const wchar_t** sources,
                const wchar_t** ids,
                const char* mode)
{
    LOG.reset();
    int ret = 0;

    HwndFunctions::getWindowHandle();

    SyncItemListenerClient* itemListener = new SyncItemListenerClient();
    SyncListenerClient* syncListener = new SyncListenerClient();
    syncSourceListener  = new SyncSourceListenerClient();
    SyncStatusListenerClient* sstl = new SyncStatusListenerClient();
    TransportListenerClient* tl = new TransportListenerClient();

    setSyncItemListener(itemListener);
    setSyncListener(syncListener);
    setSyncSourceListener(syncSourceListener);
    setSyncStatusListener(sstl);
    setTransportListener(tl);
    
    //ClientSettings cs(APPLICATION_URI);
    ClientSettings::getInstance();

    string logTitle = ClientSettings::getInstance()->getAccessConfig().getUserAgent();
    logTitle += " Log";
    LOG.reset(logTitle.c_str());

    LOG.info("DeviceID: %s", ClientSettings::getInstance()->getDeviceConfig().getDevID());
    LOG.info("IP address: %s", ClientSettings::getInstance()->getIp().c_str());

    // Get the sources to sync
    const wchar_t** srcList = sources ? sources : defaultSources;
    vector<const wchar_t*> activeList = getActiveSources(*(ClientSettings::getInstance()), srcList);
    // Start the sync
    ret = performSync(*(ClientSettings::getInstance()), path, activeList, ids, mode);

    if (ret == -20) {
        LOG.debug("The user stops the sync to avoid slow sync of PIM");
        return ret;
    }

    if (ret == -10) {
        LOG.debug("Mail not set to be synched");
        LOG.debug("No source to sync");
        return -10;
    }

    // release listeners
    if(itemListener)
        { delete itemListener; itemListener=NULL; }
    if(syncListener)
        { delete syncListener; syncListener=NULL; }
    if(syncSourceListener)
        { delete syncSourceListener; syncSourceListener=NULL; }
    if(itemListener)
        { delete itemListener; itemListener=NULL; }
    if(itemListener)
        { delete itemListener; itemListener=NULL; }

    LOG.debug("Synchronize is returning: %d.", ret);
    return ret;
}


/*
 * NOTE: USED ONLY TEMPORANEALLY TO GET A MAIL PARAMETER THAT MUST
 * BE FIXED IN A PROPER WAY
 */
static TCHAR* getMailMaxMsgSize() {
    HKEY key = NULL;
    DWORD res;
    long err = 0;
    TCHAR *p = TEXT("mailMaxMsgSize");
    ULONG dim = 0;
    TCHAR *buf = NULL;

    RegCreateKeyEx(
            HKEY_LOCAL_MACHINE,
            TEXT("\\Software\\") ROOT_CONTEXT_W TEXT("\\spds\\sources\\mails"),
            0,
            NULL,
            REG_OPTION_NON_VOLATILE,
            KEY_ALL_ACCESS,
            NULL,
            &key,
            &res
            );

    if (key == 0) {
        lastErrorCode = ERR_INVALID_CONTEXT;
        sprintf(lastErrorMsg, "Invalid context path: %s", "Software/" ROOT_CONTEXT "/spds/sources/mails");
        goto finally;
    }

    // Get value length
    err = RegQueryValueEx(
            key,
            p,
            NULL,
            NULL,  // we currently support only strings
            NULL,
            &dim
            );

    if (err == ERROR_SUCCESS) {
        if (dim > 0) {
            buf = new TCHAR[dim + 1];

            err = RegQueryValueEx(
                    key,
                    p,
                    NULL,
                    NULL,  // we currently support only strings
                    (UCHAR*)buf,
                    &dim
                    );
        }
    }
    //else MessageBox(NULL,  T("Error"), T("getConfigParameter"), MB_OK);

    if (!buf)
        buf = wstrdup(TEXT(""));

finally:

    if (key != 0) {
        RegCloseKey(key);
    }

    return buf;
}


/*
* return code -10: no source to sync
*/

DWORD checkStartSync() {

    DWORD pid = 0;
    // Try to create the mutex
    HANDLE hMutex = CreateMutex(NULL, TRUE, TEXT("FunSyncInProgress") );
    if(hMutex){
        DWORD err = GetLastError();
        if(GetLastError() == ERROR_ALREADY_EXISTS){
            pid = getProcessPid( TEXT("startsync.exe") );
        }
        CloseHandle( hMutex );
    }
    return pid;

}

/*
* To get the complete mail id. The AdviseSink of the syncml transport returns an array of /id1, /id2
* But the complete id mapped with the server is I/id1, S/id2. So to ask the right mail is necessary to retrieve
* the complete id that is stored in the files containing the cached situation
*/
static wchar_t* findMailIdInFile(const wchar_t* fileName, const wchar_t* partialID) {

    wchar_t* idComplete = NULL;
    wchar_t line[512];
    FILE* f = _wfopen(fileName, TEXT("r"));

    if (f == NULL)
        return NULL;

    while(fgetws(line, 511, f) != NULL) {

        if (wcsstr(line, partialID ) != NULL) {
            if (idComplete = getElementContent(line, TEXT("id"), 0))
                break;

        }
    }
    fclose(f);
    return idComplete;
}

static wchar_t* completeMailId(const wchar_t* path, const wchar_t* partialID) {

    bool isLast = false;
    wchar_t fileName[255];
    wchar_t* idComplete = NULL;

    WIN32_FIND_DATA FileData;
    wchar_t filter[255];
    wsprintf(filter, TEXT("%s\\mails_*"), path);
    HANDLE hFind = FindFirstFile(filter, &FileData);

    if (hFind == INVALID_HANDLE_VALUE) {
        LOG.debug("No mails_ file found.");
        return NULL;
    }

    while (!isLast) {
        wsprintf(fileName, TEXT("%s\\%s"), path, FileData.cFileName);
        idComplete = findMailIdInFile(fileName, partialID);

        if (idComplete) { // id completed found
            break;
        } else {
            if (!FindNextFile(hFind, &FileData))
                isLast = TRUE;
        }
    }

    FindClose(hFind);
    return idComplete;

}

/*
* Return the number of email that are not sent in outbox folder
* When the connector will send the messate cause for every item
* we can get the message too
*/

static wstring getMailUnsent(MailSyncSource& mailSource) {

    wstring messageToRet;
    SyncSourceReport* rep = mailSource.getReport();
    int res = rep->getItemReportFailedCount(SERVER, COMMAND_ADD);
    int number = 0, i = 0;
    BOOL found = FALSE;
    for (i = 0; i < res; i++) {
        ItemReport* r = rep->getItemReport(SERVER, COMMAND_ADD, i);
        if (wcsstr(r->getId(), L"O/") != 0 && (r->getStatus() == 500 || r->getStatus() == 418 || r->getStatus() == 419)) {
            found = TRUE;
            if (r->getStatusMessage()) {
                LOG.debug("The outbox mail (id: %S) cannot be sent. Server says: %S", r->getId(), r->getStatusMessage());
                messageToRet = r->getStatusMessage();
                if (messageToRet.length() > 130) {
                    messageToRet = messageToRet.substr(0,130);
                    messageToRet.append(L"...");
                }

            }
            number++;
        }
    }

    if (!found) {
        res = rep->getItemReportFailedCount(SERVER, COMMAND_REPLACE);
        for (i = 0; i < res; i++) {
            ItemReport* r = rep->getItemReport(SERVER, COMMAND_REPLACE, i);
            if (wcscmp(r->getId(), L"O/") != 0 && (r->getStatus() == 500 || r->getStatus() == 418 || r->getStatus() == 419)) {
                if (r->getStatusMessage()) {
                    LOG.debug("The outbox mail (id: %S) cannot be sent. Server says: %S", r->getId(), r->getStatusMessage());
                    messageToRet = r->getStatusMessage();
                    if (messageToRet.length() > 130) {
                        messageToRet = messageToRet.substr(0,130);
                        messageToRet.append(L"...");
                    }
                }
                number++;
            }
        }

    }

    if (number == 1) {
        /*
        * Added extension to the name if there isn't one
        */
        wstring msg(messageToRet);
        std::transform(messageToRet.begin(), messageToRet.end(), msg.begin(), tolower);

        if (messageToRet == L"" || (msg.find(L"error sending") == wstring::npos &&
                                    msg.find(L"error adding") == wstring::npos)
                                ||  msg.find(L"com.funambol") != wstring::npos ) {
            messageToRet = ONE_OUT_MESSAGE_NOT_SENT;
        } else {
            messageToRet.insert(0, OUT_MESSAGE_NOT_SENT);
        }
    } else {
        messageToRet = MORE_OUT_MESSAGE_NOT_SENT;
    }

    return messageToRet;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -