void ConnectionState::getBestConnection(MojString& connectionType, MojString& ipAddress)
{
	if (ConnectionState::m_connState->m_wifiConnected)
	{
		connectionType.assign("wifi");
		ipAddress = ConnectionState::m_connState->m_wifiIpAddress;
	}
	else
	{
		connectionType.assign("wan");
		ipAddress = ConnectionState::m_connState->m_wanIpAddress;
	}
}
Ejemplo n.º 2
0
MojErr MojDbIndex::addBuiltinProps()
{
    LOG_TRACE("Entering function %s", __FUNCTION__);

	MojString idStr;
	MojErr err = idStr.assign(MojDb::IdKey);
	MojErrCheck(err);
	if (m_propNames.find(idStr) == MojInvalidSize) {
		MojObject idProp;
		err = idProp.put(NameKey, idStr);
		MojErrCheck(err);
		err = addProp(idProp);
		MojErrCheck(err);
	}
	if (m_includeDeleted && m_propNames.front() != MojDb::DelKey) {
		MojObject delProp;
		err = delProp.putString(NameKey, MojDb::DelKey);
		MojErrCheck(err);
		err = delProp.putBool(DefaultKey, false);
		MojErrCheck(err);
		err = addProp(delProp, true);
		MojErrCheck(err);
		MojAssert(m_propNames.front() == MojDb::DelKey);
	}
	m_idIndex = m_propNames.find(idStr);
	MojAssert(m_idIndex != MojInvalidSize);
	m_idIndex++; // account for prefix

	return MojErrNone;
}
Ejemplo n.º 3
0
MojErr MojDbIndexTest::assertContainsText(TestIndex& ti, MojObject id, const MojChar* str)
{
	MojString strObj;
	MojErr err = strObj.assign(str);
	MojErrCheck(err);
	MojRefCountedPtr<MojDbTextCollator> collator(new MojDbTextCollator);
	MojAllocCheck(collator.get());
	err = collator->init(_T("en_US"), MojDbCollationPrimary);
	MojTestErrCheck(err);
	MojDbKey key;
	err = collator->sortKey(strObj, key);
	MojTestErrCheck(err);

	MojObjectWriter writer;
	err = id.visit(writer);
	MojTestErrCheck(err);
	const MojByte* idData = NULL;
	MojSize idSize = 0;
	err = writer.buf().data(idData, idSize);
	MojTestErrCheck(err);
	err = key.byteVec().append(idData, idData + idSize);
	MojTestErrCheck(err);
	err = assertContains(ti, id, key);
	MojTestErrCheck(err);

	return MojErrNone;
}
Ejemplo n.º 4
0
MojErr MojDbQuotaTest::testEnforce(MojDb& db)
{
	// set quota size to current usage
	MojInt64 quotaUsage1 = 0;
	MojErr err = getQuotaUsage(db, _T("com.foo.bar"), quotaUsage1);
	MojTestErrCheck(err);
	MojObject obj;
	err = obj.putString(_T("owner"), _T("com.foo.bar"));
	MojErrCheck(err);
	err = obj.putInt(_T("size"), quotaUsage1);
	MojErrCheck(err);
	err = db.putQuotas(&obj, &obj + 1);
	MojErrCheck(err);
	err = put(db, MojTestKind1Objects[3]);
	MojTestErrExpected(err, MojErrDbQuotaExceeded);
	// make sure we can delete the kind
	MojString kindStr;
	err = kindStr.assign(_T("Test:1"));
	MojTestErrCheck(err);
	bool found = false;
	err = db.delKind(kindStr, found);
	MojTestErrCheck(err);
	MojTestAssert(found);

	return MojErrNone;
}
Ejemplo n.º 5
0
MojErr MojDbPermissionTest::testKindPermissions(MojDb& db)
{
	MojObject kind;
	MojErr err = kind.fromJson(MojTestKind1);
	MojTestErrCheck(err);

	// new kind, mismatched owner and caller
	MojDbReq req(false);
	err = req.domain(_T("com.bar"));
	MojTestErrCheck(err);
	err = db.putKind(kind, MojDb::FlagNone, req);
	MojTestErrExpected(err, MojErrDbPermissionDenied);
	// new kind, matched owner and caller
	err = req.domain(_T("com.foo"));
	MojTestErrCheck(err);
	err = db.putKind(kind, MojDb::FlagNone, req);
	MojTestErrCheck(err);
	// existing kind, matched owner and caller
	err = db.putKind(kind, MojDb::FlagNone, req);
	MojTestErrCheck(err);
	// existing kind, mismatched owner and caller
	err = req.domain(_T("com.bar"));
	MojTestErrCheck(err);
	err = db.putKind(kind, MojDb::FlagNone, req);
	MojTestErrExpected(err, MojErrDbPermissionDenied);
	// delKind, mismatched owner and caller
	MojString id;
	err = id.assign(_T("PermissionTest:1"));
	MojTestErrCheck(err);
	bool found = false;
	err = db.delKind(id, found, MojDb::FlagNone, req);
	MojTestErrExpected(err, MojErrDbPermissionDenied);

	return MojErrNone;
}
Ejemplo n.º 6
0
MojErr MojDbQuery::createClause(WhereMap& map, const MojChar* propName, CompOp op, MojObject val, MojDbCollationStrength coll)
{
	// construct the clause
	MojErr err = MojErrNone;
	WhereClause clause;
	switch (op) {
	case OpLessThan:
	case OpLessThanEq:
		// less-than ops define upper bound
		err = clause.setUpper(op, val, coll);
		MojErrCheck(err);
		break;
	default:
		// everything else is stored as lower bound
		err = clause.setLower(op, val, coll);
		MojErrCheck(err);
		break;
	}
	// add clause to map
	MojString str;
	err = str.assign(propName);
	MojErrCheck(err);
	err = map.put(str, clause);
	MojErrCheck(err);

	return MojErrNone;
}
MojErr ContainerManager::InfoToJson(MojObject& rep) const
{
	MojObject containers(MojObject::TypeArray);

	std::for_each(m_containers.begin(), m_containers.end(),
		boost::bind(&ResourceContainer::PushJson,
			boost::bind(&ContainerMap::value_type::second, _1),
			boost::ref(containers)));

	MojErr err = rep.put(_T("containers"), containers);
	MojErrCheck(err);

	MojObject entityMap(MojObject::TypeArray);
	for (EntityContainerMap::const_iterator iter = m_entityContainers.begin();
		iter != m_entityContainers.end(); ++iter) {
		MojObject mapping(MojObject::TypeObject);

		MojString containerName;
		err = containerName.assign(iter->second->GetName().c_str());
		MojErrCheck(err);

		err = mapping.put(iter->first->GetName().c_str(), containerName);
		MojErrCheck(err);

		err = entityMap.push(mapping);
		MojErrCheck(err);
	}

	err = rep.put(_T("entityMap"), entityMap);
	MojErrCheck(err);

	return MojErrNone;
}
Ejemplo n.º 8
0
MojErr MojService::CategoryHandler::addMethod(const MojChar* methodName, Callback callback, bool pub, const MojChar* schemaJson)
{
	MojAssert(methodName && callback);

	MojString str;
	MojErr err = str.assign(methodName);
	MojErrCheck(err);
	MojRefCountedPtr<MojSchema> schema;
	if (schemaJson) {
		MojObject schemaObj;
		err = schemaObj.fromJson(schemaJson);
		MojErrCheck(err);

		// add implicit $activity property
		MojObject properties;
		schemaObj.get(MojSchema::PropertiesKey, properties);
		MojObject activityProp;
		err = activityProp.putBool(MojSchema::OptionalKey, true);
		MojErrCheck(err);
		err = properties.put(_T("$activity"), activityProp);
		MojErrCheck(err);
		err = schemaObj.put(MojSchema::PropertiesKey, properties);
		MojErrCheck(err);

		schema.reset(new MojSchema);
		MojAllocCheck(schema.get());
		err = schema->fromObject(schemaObj);
		MojErrCheck(err);
	}
	MojAssert(!m_callbackMap.contains(str));
	err = m_callbackMap.put(str, CallbackInfo(callback, schema.get(), pub));
	MojErrCheck(err);

	return MojErrNone;
}
Ejemplo n.º 9
0
MojErr MojDbTextTokenizerTest::check(const MojChar* text, const MojChar* tokens)
{
	// tokenize string
	MojString textStr;
	MojErr err = textStr.assign(text);
	MojTestErrCheck(err);
	MojSet<MojDbKey> set;
	MojRefCountedPtr<MojDbTextTokenizer> tokenizer(new MojDbTextTokenizer);
	MojAllocCheck(tokenizer.get());
	err = tokenizer->init(_T("en_US"));
	MojTestErrCheck(err);
	err = tokenizer->tokenize(textStr, NULL, set);
	MojTestErrCheck(err);
	// check that tokens match
	MojObject obj;
	err = obj.fromJson(tokens);
	MojTestErrCheck(err);
	MojSize objSize = obj.size();
	MojSize setSize = set.size();
	MojTestAssert(objSize == setSize);
	for (MojObject::ConstArrayIterator i = obj.arrayBegin(); i != obj.arrayEnd(); ++i) {
		MojDbKey key;
		err = key.assign(*i);
		MojTestErrCheck(err);
		MojTestAssert(set.contains(key));
	}
	return MojErrNone;
}
Ejemplo n.º 10
0
MojErr MojDb::updateLocale(const MojChar* locale, MojDbReqRef req)
{
	MojAssert(locale);
	MojLogTrace(s_log);

	MojErr err = beginReq(req, true);
	MojErrCheck(err);
	MojString oldLocale;
	err = getLocale(oldLocale, req);
	MojErrCheck(err);
	MojString newLocale;
	err = newLocale.assign(locale);
	MojErrCheck(err);
	MojErr updateErr = err = updateLocaleImpl(oldLocale, newLocale, req);
	MojErrCatchAll(err) {
		err = req->abort();
		MojErrCheck(err);
		err = m_kindEngine.close();
		MojErrCheck(err);
		MojDbReq openReq;
		err = beginReq(openReq, true);
		MojErrCheck(err);
		err = m_kindEngine.open(this, openReq);
		MojErrCheck(err);
		err = openReq.end();
		MojErrCheck(err);
		MojErrThrow(updateErr);
	}
	return MojErrNone;
}
Ejemplo n.º 11
0
TEST_F(QuotaTest, enforce)
{
    MojObject obj;

    // put quota
    MojAssertNoErr( obj.fromJson(_T("{\"owner\":\"com.foo.bar\",\"size\":1000}")) );
    MojAssertNoErr( db.putQuotas(&obj, &obj + 1) );

    // make kind2 inherit from kind1
    MojAssertNoErr( obj.fromJson(MojTestKind2Str3) );
    MojExpectNoErr( db.putKind(obj) );

    //// end of prerequisites form prev tests

    // set quota size to current usage
    MojInt64 quotaUsage1 = 0;
    EXPECT_NO_FATAL_FAILURE( getQuotaUsage(db, _T("com.foo.bar"), quotaUsage1) );
    MojAssertNoErr( obj.putString(_T("owner"), _T("com.foo.bar")) );
    MojAssertNoErr( obj.putInt(_T("size"), quotaUsage1) );
    MojExpectNoErr( db.putQuotas(&obj, &obj + 1) );

    MojAssertNoErr( obj.fromJson(MojTestKind1Objects[3]) );
    EXPECT_EQ( MojErrDbQuotaExceeded, db.put(obj) );

    // Try to delete the kind
    MojString kindStr;
    MojAssertNoErr( kindStr.assign(_T("Test:1")) );
    bool found = false;
    EXPECT_EQ( MojErrDbKindHasSubKinds, db.delKind(kindStr, found) )
        << "The delete should be failure, because it contain sub kind \"Test2:1\"";
    EXPECT_FALSE( found );
}
Ejemplo n.º 12
0
MojErr MojDbQuotaEngine::informQuotaSubscribers(const MojString& kindId)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);

    MojErr err;
    MojInt64 sizeOut;
    MojInt64 usageOut;
    MojDbKind* kind = NULL;
    MojString owner;

    err = owner.assign("");
    MojErrCheck(err);

    if(m_db->kindEngine()->isExist(kindId.data(), kind))
        owner = kind->owner();

    if((kind == NULL) || owner.empty())
        return MojErrNone;

    //ignore if quota not exist
    QuotaMap::ConstIterator iter = m_quotas.find(owner.data());
    if (iter == m_quotas.end())
        return MojErrNone;

    err = quotaUsage(owner.data(), sizeOut, usageOut);
    MojErrCheck(err);
    err = m_db->getQuotaAlert().notifySubscriber(owner.data(), usageOut, sizeOut);
    MojErrCheck(err);

    return MojErrNone;
}
Ejemplo n.º 13
0
MojErr MojDbQuotaTest::testEnforce(MojDb& db)
{
	// set quota size to current usage
	MojInt64 quotaUsage1 = 0;
	MojErr err = getQuotaUsage(db, _T("com.foo.bar"), quotaUsage1);
	MojTestErrCheck(err);
	MojObject obj;
	err = obj.putString(_T("owner"), _T("com.foo.bar"));
	MojErrCheck(err);
	err = obj.putInt(_T("size"), quotaUsage1);
	MojErrCheck(err);
	err = db.putQuotas(&obj, &obj + 1);
	MojErrCheck(err);
	err = put(db, MojTestKind1Objects[3]);
	MojTestErrExpected(err, MojErrDbQuotaExceeded);
	// Try to delete the kind
	MojString kindStr;
	err = kindStr.assign(_T("Test:1"));
	MojTestErrCheck(err);
	bool found = false;
	err = db.delKind(kindStr, found);

    //The delete should be failure, because it contain sub kind "Test2:1"
    MojTestErrExpected(err,MojErrDbKindHasSubKinds); 
    MojTestAssert(!found); 

	return MojErrNone;
}
Ejemplo n.º 14
0
void SmtpSendMailCommand::UpdateSendStatus()
{
	try {
	
		MojObject sendStatus;
		MojObject visible;
		MojErr err;

		bool update = false;

		if (m_error.errorCode == 0) {

			MojLogInfo(m_log, "updating send status to SENT successfully");
			err = sendStatus.put(EmailSchema::SendStatus::SENT, true);
			ErrorToException(err);
			err = visible.put(EmailSchema::Flags::VISIBLE, false);
			ErrorToException(err);
			update = true;

		} else if (m_error.errorOnEmail) {

			MojLogInfo(m_log, "updating send status on email to indicate error");
		
			MojString str;
			str.assign(m_error.errorText.c_str());
			err = sendStatus.put(EmailSchema::SendStatus::LAST_ERROR, str); 
			ErrorToException(err);
			// FIXME: Should we store an actual error code?
			err = sendStatus.put(EmailSchema::SendStatus::FATAL_ERROR, true);
			ErrorToException(err);
			update = true;

		} 
		// account errors are not handled in sent status: message
		// status will not be changed in those cases.
	
		if (update) {
	
			MojString idJson;
			m_emailId.toJson(idJson);
			MojLogInfo(m_log, "updating send status for email %s", idJson.data());
			m_session.GetDatabaseInterface().UpdateSendStatus(m_updateSendStatusSlot, m_emailId, sendStatus, visible);

		} else {
			
			// Finish up now
			Done();
		}
	} catch (std::exception & e) {
		// Error updating status, just give up.
		MojLogInfo(m_log, "Exception %s hit trying to update send status, bailing", e.what());
		Done();
	} catch (...) {
		// Error updating status, just give up.
		MojLogInfo(m_log, "Unknown exception hit trying to update send status, bailing");
		Done();
	}
}
Ejemplo n.º 15
0
MojErr MojObjectTest::putTest(MojObject& obj)
{
    MojString str;
    MojObject obj2;
    MojObject array1;
    MojObject str2;
    MojObject bool2(false);
    MojObject int2(-260000000000LL);
    MojObject MojDecimal2(MojDecimal(2.34));

    MojErr err = str.assign(_T("howdy"));
    MojTestErrCheck(err);
    str2 = str;

    err = obj2.put(_T("nested"), str);
    MojTestErrCheck(err);
    err = obj.put(_T("object"), obj2);
    MojTestErrCheck(err);
    err = obj.put(_T("string"), str2);
    MojTestErrCheck(err);
    err = obj.put(_T("bool1"), true);
    MojTestErrCheck(err);
    err = obj.put(_T("bool2"), bool2);
    MojTestErrCheck(err);
    err = obj.put(_T("int1"), 50);
    MojTestErrCheck(err);
    err = obj.put(_T("int2"), int2);
    MojTestErrCheck(err);
    err = obj.put(_T("MojDecimal1"), MojDecimal(0.1));
    MojTestErrCheck(err);
    err = obj.put(_T("MojDecimal2"), MojDecimal2);
    MojTestErrCheck(err);
    err = obj.put(_T("null"), MojObject(MojObject::TypeNull));
    MojTestErrCheck(err);
    // array
    err = array1.push(MojObject(MojObject::TypeObject));
    MojTestErrCheck(err);
    err = array1.push(MojObject(MojObject::TypeArray));
    MojTestErrCheck(err);
    err = array1.push(str2);
    MojTestErrCheck(err);
    err = array1.push(true);
    MojTestErrCheck(err);
    err = array1.setAt(3, false);
    MojTestErrCheck(err);
    err = array1.push(MojDecimal(3, 140000));
    MojTestErrCheck(err);
    err = array1.push(100);
    MojTestErrCheck(err);
    err = array1.push(MojObject(MojObject::TypeNull));
    MojTestErrCheck(err);
    err = array1.setAt(7, 4);
    MojTestErrCheck(err);
    err = obj.put(_T("array"), array1);
    MojTestErrCheck(err);

    return MojErrNone;
}
Ejemplo n.º 16
0
MojErr MojDbQuery::select(const MojChar* propName)
{
	MojString str;
	MojErr err = str.assign(propName);
	MojErrCheck(err);
	err = m_selectProps.put(str);
	MojErrCheck(err);

	return MojErrNone;
}
Ejemplo n.º 17
0
void AuthYahooCommand::RunImpl()
{
	MojLogTrace(m_log);
	// HACK: Hard-code partner ID and fetch of NDUID
	m_partnerId.assign("mblclt11");
	
	char id[256];
	memset(id, '\0', 256);
	
	// Read nduid, if available, otherwise make a fake one and try to record it.
	FILE * nduid = fopen("/proc/nduid", "r");
	if (!nduid) {
		nduid = fopen("yahooCachedFakeDeviceId", "r");
		if (!nduid) {
			snprintf(id, 255, "FEED0BEEF479121481533145%016llX", timeMillis());
			nduid = fopen("yahooCachedFakeDeviceId", "w");
			if (nduid) {
				fputs(id, nduid);
				fclose(nduid);
				nduid = NULL;
			}
		}
	}
	
	if (nduid) {
		if (fgets(id, 255, nduid) == NULL)
			id[0] = '\0';
		
		fclose(nduid);
		nduid = NULL;

		if (strlen(id) > 0 && id[strlen(id)-1] == '\n')
			id[strlen(id)-1] = '\0';
	}
	
	m_deviceId.assign(id);

	MojLogInfo(m_log, "Temp: partnerId=%s deviceId=%s", m_partnerId.data(), m_deviceId.data());

	MojObject accountId = m_session.GetAccount()->GetAccountId();

	MojObject params;
	MojErr err = params.put("accountId", accountId);
	ErrorToException(err);

	MojString token;
	token.assign(m_session.GetAccount()->GetYahooToken().c_str());
	err = params.put("securityToken", token);
	ErrorToException(err);

	MojLogInfo(m_log, "Looking up yahoo cookies for account %s", AsJsonString(accountId).c_str());
	// TODO: Should send the request with SmtpClient instead.
	err = m_session.CreateRequest()->send(m_getYahooCookiesSlot, "com.palm.yahoo","fetchcookies", params);
	ErrorToException(err);
}
Ejemplo n.º 18
0
/*
 * Initialize from an incoming libPurple callback parameters
 *
 * payload form: (Sprint)
 * { "serviceName": "gmail", "username": "******", "usernameFrom": "*****@*****.**", "messageText": "<body>test reply to phone<\/body>" }
 * { "serviceName": "aol", "username": "******", "usernameFrom": "palm", "messageText": "test incoming message" }
 *
 *
 */
MojErr IMMessage::initFromCallback(const char* serviceName, const char* username, const char* usernameFrom, const char* message) {

	MojErr err;

	// unescape, strip html
	//    #/tmp/testsanitize "<a>foo</a>"
	//    sanitized: &lt;a&gt;foo&lt;/a&gt;
	//    unsanitized: <a>foo</a>
	//    removed: foo

	// first unescape since gtalk sends everything escaped
	// message is const char* - need a char* version
	char *unescapedMessage = unsanitizeHtml((char*)message);

	// now remove offending html
	// char * sanitizeHtml(const char *input, char **except, bool remove);
	//     remove set to true if you want the the tags to actually be removed vs just "escaped".
	//     except is an array of char* containing tags to ignore when sanitizing. The
	//          last element must be a null. You need to include both beginning and ending
	//          tag if you want both removed (i.e. "b", "/b", "i", "/i")
	char *sanitizedMessage = sanitizeHtml(unescapedMessage, (char**)IMMessage::trustedTags, true);

	// can't keep this log...
	//MojLogInfo(IMServiceApp::s_log, _T("original message: %s, unescaped message: %s, sanitized message: %s"), message, unescapedMessage, sanitizedMessage);

	err = msgText.assign(sanitizedMessage);
	MojErrCheck(err);
	// cleanup
	free(unescapedMessage);
	free(sanitizedMessage);

	// remove blanks and convert to lowercase
	// for AOL, this is screen name with no "@aol.com"...
	MojString formattedUserName;
	err = formattedUserName.assign(usernameFrom);
	MojErrCheck(err);
	err = unformatFromAddress(formattedUserName, fromAddress);
	MojErrCheck(err);

	err = toAddress.assign(username);
	MojErrCheck(err);
	err = msgType.assign(serviceName);
	MojErrCheck(err);

	// set time stamp to current time - seconds since 1/1/1970
	// for some reason multiplying a time_t by 1000 doesn't work - you have to convert to a long first...
	//deviceTimestamp = time (NULL) * 1000;
	MojInt64 sec = time (NULL);
	deviceTimestamp = sec * 1000;
	// server timestamp is new Date().getTime()
	serverTimestamp = sec * 1000;

	return MojErrNone;
}
Ejemplo n.º 19
0
void SaveEmailCommand::CreateNextCacheObject()
{
	MojErr err;
	
	for(; m_partsIt != m_partsArray.arrayEnd(); ++m_partsIt) {
		MojObject& part = *m_partsIt;
		
		bool hasContent;
		MojString content;
		err = part.get("content", content, hasContent);
		ErrorToException(err);
		
		if(hasContent) {
			MojString cacheType;
			cacheType.assign("email");
			
			bool hasDisplayName;
			MojString displayName;
			err = part.get("displayName", displayName, hasDisplayName);
			ErrorToException(err);
			
			MojString cacheFileName;
			
			if(hasDisplayName && displayName.length() > 0) {
				cacheFileName.assign(displayName);
			} else {
				// FIXME only for HTML parts
				cacheFileName.assign("body.html");
			}
			
			MojLogDebug(m_log, "creating a file cache entry");
			m_client.GetFileCacheClient().InsertCacheObject(m_fileCacheInsertedSlot, cacheType, cacheFileName, content.length(), EMAIL_FILECACHE_COST, EMAIL_NO_LIFE_TIME);
			
			// Exit method and wait for response
			return;
		}
	}
	
	// If this is the last part with content, persist to database now
	PersistToDatabase();
}
Ejemplo n.º 20
0
MojErr MojLunaService::addCategory(const MojChar* name, CategoryHandler* handler)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);
	MojAssert(name && handler);
	MojAssertMutexUnlocked(m_mutex);
	MojThreadGuard guard(m_mutex);

	// create array of LSMethods
	MethodVec pubMethods;
	MethodVec privMethods;
	const CategoryHandler::CallbackMap& callbacks = handler->callbacks();
	for (CategoryHandler::CallbackMap::ConstIterator i = callbacks.begin();
		 i != callbacks.end();
		 i++) {
			LSMethod m = {i.key(), &handleRequest};

			MethodVec& methods = i->m_pub ? pubMethods : privMethods;
			MojErr err = methods.push(m);
			MojErrCheck(err);
	}
    LSMethod nullMethod = {NULL, NULL};
    MojErr err = pubMethods.push(nullMethod);
    MojErrCheck(err);
    err = privMethods.push(nullMethod);
    MojErrCheck(err);

    // create category object to hang on to method array
	MojRefCountedPtr<LunaCategory> cat(new LunaCategory(this, handler, pubMethods, privMethods));
	MojAllocCheck(cat.get());
	LSMethod* pubLsMethods = const_cast<LSMethod*>(cat->m_pubMethods.begin());
	LSMethod* privLsMethods = const_cast<LSMethod*>(cat->m_privMethods.begin());

	MojLunaErr lserr;
    bool retVal;
    if (m_service) {
    	retVal = LSPalmServiceRegisterCategory(m_service, name, pubLsMethods, privLsMethods, NULL, cat.get(), lserr);
    	MojLsErrCheck(retVal, lserr);
    } else {
    	MojAssert(m_handle);
    	retVal = LSRegisterCategory(m_handle, name, privLsMethods, NULL, NULL, lserr);
    	MojLsErrCheck(retVal, lserr);
        retVal = LSCategorySetData(m_handle, name, cat.get(), lserr);
        MojLsErrCheck(retVal, lserr);
    }

	MojString categoryStr;
	err = categoryStr.assign(name);
	MojErrCheck(err);
	err = m_categories.put(categoryStr, cat);
	MojErrCheck(err);

	return MojErrNone;
}
Ejemplo n.º 21
0
MojErr MojDbQuotaEngine::kindUsage(const MojChar* kindId, MojInt64& usageOut, MojDbStorageTxn* txn)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);

	MojString kindStr;
	MojErr err = kindStr.assign(kindId);
	MojErrCheck(err);
	MojRefCountedPtr<MojDbStorageItem> item;
	err = getUsage(kindStr, txn, false, usageOut, item);
	MojErrCheck(err);

	return MojErrNone;
}
Ejemplo n.º 22
0
MojErr MojLunaService::createRequest(MojRefCountedPtr<MojServiceRequest>& reqOut, bool onPublic, const char *proxyRequester)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);

	MojString proxyRequesterString;
	MojErr err = proxyRequesterString.assign(proxyRequester);
	MojErrCheck(err);

	reqOut.reset(new MojLunaRequest(this, onPublic, proxyRequesterString));
	MojAllocCheck(reqOut.get());

	return MojErrNone;
}
Ejemplo n.º 23
0
MojErr MojDbQuotaEngine::kindUsage(const MojChar* kindId, MojInt64& usageOut, MojDbStorageTxn* txn)
{
	MojLogTrace(s_log);

	MojString kindStr;
	MojErr err = kindStr.assign(kindId);
	MojErrCheck(err);
	MojRefCountedPtr<MojDbStorageItem> item;
	err = getUsage(kindStr, txn, false, usageOut, item);
	MojErrCheck(err);

	return MojErrNone;
}
Ejemplo n.º 24
0
MojErr MojLogEngine::loggerNames(StringSet& setOut)
{
	setOut.clear();
	MojThreadGuard guard(m_mutex);
	for (LoggerList::ConstIterator i = m_loggers.begin(); i != m_loggers.end(); ++i) {
		MojString name;
		MojErr err = name.assign((*i)->name());
		MojErrCheck(err);
		err = setOut.put(name);
		MojErrCheck(err);
	}
	return MojErrNone;
}
Ejemplo n.º 25
0
/*
 * Initialize from an incoming libPurple callback parameters
 *
 * payload form: (Sprint)
 * { "serviceName": "gmail", "username": "******", "usernameFrom": "*****@*****.**", "messageText": "<body>test reply to phone<\/body>" }
 * { "serviceName": "aol", "username": "******", "usernameFrom": "palm", "messageText": "test incoming message" }
 *
 *
 */
MojErr IMMessage::initFromCallback(const char* serviceName, const char* username, const char* usernameFrom, const char* message) {

	MojErr err;

	// unescape, strip html
	//    #/tmp/testsanitize "<a>foo</a>"
	//    sanitized: &lt;a&gt;foo&lt;/a&gt;
	//    unsanitized: <a>foo</a>
	//    removed: foo

    char* unescapedMessage = purple_unescape_html(message);
    char* sanitizedMessage = purple_markup_strip_html(unescapedMessage);
    g_free(unescapedMessage);

    msgText.assign("");

    // Inefficient but working solution.
    // TODO: Implement proper sanitization (that just keeps br, u, l and i)
    for (char* ptr = sanitizedMessage; *ptr; ++ptr)
        if (*ptr == '\n')
            msgText.append("<br>");
        else
            msgText.append(*ptr);

    err = msgText.assign(sanitizedMessage);
    g_free(sanitizedMessage);
	MojErrCheck(err);

	// remove blanks and convert to lowercase
	// for AOL, this is screen name with no "@aol.com"...
	MojString formattedUserName;
	err = formattedUserName.assign(usernameFrom);
	MojErrCheck(err);
	err = unformatFromAddress(formattedUserName, fromAddress);
	MojErrCheck(err);

	err = toAddress.assign(username);
	MojErrCheck(err);
	err = msgType.assign(serviceName);
	MojErrCheck(err);

	// set time stamp to current time - seconds since 1/1/1970
	// for some reason multiplying a time_t by 1000 doesn't work - you have to convert to a long first...
	//deviceTimestamp = time (NULL) * 1000;
	MojInt64 sec = time (NULL);
	deviceTimestamp = sec * 1000;
	// server timestamp is new Date().getTime()
	serverTimestamp = sec * 1000;

	return MojErrNone;
}
Ejemplo n.º 26
0
/*
 * Load preferences for account we are logging in to
 *
 */
MojErr IMServiceHandler::loadpreferences(MojServiceMessage* serviceMsg, const MojObject payload)
{
	//Sleep for 3 secondas to ensure DB is updated
	sleep(3);
	
	//Load server and port
	MojString errorText;
	bool found = false;
	bool result = true;
	MojString templateId;
	MojString UserName;

	//Get templateId
	MojErr err = payload.get(_T("templateId"), templateId, found);
	if (!found) {
		errorText.assign(_T("Missing templateId in payload."));
		result = false;
	}
	//Get server name
	err = payload.get(_T("UserName"), UserName, found);
	if (!found) {
		errorText.assign(_T("Missing UserName in payload."));
		result = false;
	}
	
	if (!result) {
		serviceMsg->replyError(err, errorText);
		return MojErrNone;
	}
	
	//Load the prefs
	LoadAccountPreferences (templateId, UserName);
	
	//Return success
	serviceMsg->replySuccess();
	return MojErrNone;
}
Ejemplo n.º 27
0
MojErr MojDbTestStorageEngine::setNextError(const MojChar* methodName, MojErr err)
{
	if (err == MojErrNone) {
		bool found;
		MojErr errDel = m_errMap.del(methodName, found);
		MojErrCheck(errDel);
	} else {
		MojString str;
		str.assign(methodName);
		MojErr errPut = m_errMap.put(str, err);
		MojErrCheck(errPut);
	}

	return MojErrNone;
}
Ejemplo n.º 28
0
MojErr MojDbLevelDatabase::open(const MojChar* dbName, MojDbLevelEngine* eng, bool& createdOut, MojDbStorageTxn* txn)
{
    LOG_TRACE("Entering function %s", __FUNCTION__);
    MojAssert(dbName && eng);
    MojAssert(!txn || txn->isValid());

    // save eng, name and file
    createdOut = false;
    m_engine = eng;
    MojErr err = m_name.assign(dbName);
    MojErrCheck(err);
    const MojString& engPath = eng->path();
    if (engPath.empty()) {
        err = m_file.assign(dbName);
        MojErrCheck(err);
    } else {
        err = m_file.format(_T("%s/%s"), engPath.data(), dbName);
        MojErrCheck(err);
    }

    // create and open db
    leveldb::Status status = leveldb::DB::Open(MojDbLevelEngine::getOpenOptions(), m_file.data(), &m_db);

    if (status.IsCorruption()) {    // database corrupted
        // try restore database
        // AHTUNG! After restore database can lost some data!
        status = leveldb::RepairDB(m_file.data(), MojDbLevelEngine::getOpenOptions());
        MojLdbErrCheck(status, _T("db corrupted"));
        status = leveldb::DB::Open(MojDbLevelEngine::getOpenOptions(), m_file.data(), &m_db);  // database restored, re-open
    }

    MojLdbErrCheck(status, _T("db_create"));
    MojAssert(m_db);

    // set up prop-vec for primary key queries
    MojString idStr;
    err = idStr.assign(MojDb::IdKey);
    MojErrCheck(err);
    err = m_primaryProps.push(idStr);
    MojErrCheck(err);

    //keep a reference to this database
    err = eng->addDatabase(this);
    MojErrCheck(err);

    return MojErrNone;
}
Ejemplo n.º 29
0
void SmtpSyncOutboxCommand::CheckErrorCodes()
{
	CommandTraceFunction();
	try {
		
		if (m_error.IsLockoutError()) {
			if (m_force) {
				MojLogInfo(m_log, "Account locked out due to error (code=%d,internal=%s), but continuing due to force.",
					m_error.errorCode,
					m_error.internalError.c_str());
			} else {
				MojLogInfo(m_log, "Account locked out due to error (code=%d,internal=%s), completing sync early.",
					m_error.errorCode,
					m_error.internalError.c_str());
				SmtpSyncOutboxCommand::CompleteAndUpdateActivities();
				return;
			}
		}
		
		if (m_error.errorCode) {
			// Reset error code before we continue -- if the
			// account still has trouble, we'll put the error
			// back before we're done.
			
			// clear our state
			m_error.clear();
			
			MojString text;
			text.assign("");
			// clear the db state
			m_client.GetDatabaseInterface().UpdateAccountErrorStatus(m_resetErrorSlot, m_accountId, 0, text);
			return;
		} else {
			// clear entire error state
			m_error.clear();
		}
		
		GetOutboxEmails();
	
	} catch (std::exception & e) {
		HandleException(e, __func__);
	} catch (...) {
		HandleException(__func__);
	}
}
Ejemplo n.º 30
0
MojErr MojDbServiceHandler::open()
{
	MojLogTrace(s_log);

	MojErr err = addMethods(s_pubMethods, true);
	MojErrCheck(err);
	err = addMethods(s_privMethods, false);
	MojErrCheck(err);

	for (const Method* method = s_batchMethods; method->m_name != NULL; method++) {
		MojString methodStr;
		err = methodStr.assign(method->m_name);
		MojErrCheck(err);
		err = m_batchCallbacks.put(methodStr, (DbCallback) method->m_callback);
		MojErrCheck(err);
	}
	return MojErrNone;
}