void EmailAdapter::ParseRecipients(const MojObject& recipients, Email& email)
{
	MojErr err;
	
	EmailAddressListPtr to_list(new EmailAddressList);
	EmailAddressListPtr cc_list(new EmailAddressList);
	EmailAddressListPtr bcc_list(new EmailAddressList);
	
	MojObject::ConstArrayIterator it = recipients.arrayBegin();

	for (; it != recipients.arrayEnd(); ++it) {
		const MojObject& recipient = *it;

		MojString type;
		err = recipient.getRequired(Part::TYPE, type);
		ErrorToException(err);
		
		EmailAddressPtr addr = ParseAddress(recipient);

		if(type.compareCaseless("to") == 0)
			to_list->push_back(addr);
		else if(type.compareCaseless("cc") == 0)
			cc_list->push_back(addr);
		else if(type.compareCaseless("bcc") == 0)
			bcc_list->push_back(addr);
		else // not a valid recipient type
			throw MailException("invalid recipient type", __FILE__, __LINE__);
	}
	
	email.SetTo(to_list);
	email.SetCc(cc_list);
	email.SetBcc(bcc_list);
}
bool MojoCompareMatcher::Match(const MojObject& response)
{
	MojLogTrace(s_log);

	if (response.contains(m_key)) {
		MojObject value;
		MojString valueString;
		response.get(m_key, value);
		value.stringValue(valueString);
		if (value != m_value) {
			MojString oldValueString;
			m_value.stringValue(oldValueString);

			MojLogInfo(s_log, _T("Compare Matcher: Comparison key \"%s\" "
				"value changed from \"%s\" to \"%s\".  Firing."), m_key.data(),
				oldValueString.data(), valueString.data());

			return true;
		} else {
			MojLogInfo(s_log, _T("Compare Matcher: Comparison key \"%s\" "
				"value \"%s\" unchanged."), m_key.data(), valueString.data());
		}
	} else {
		MojLogInfo(s_log, _T("Compare Matcher: Comparison key (%s) not "
			"present."), m_key.data());
	}

	return false;
}
void SmtpSendMailCommand::RunImpl()
{
	try {
		if (m_session.HasError()) {
			if (m_session.GetError().errorOnEmail) {
				// this doesn't make any sense, but if we don't mark the mail as bad, someone
				// is going to loop...
				m_error = m_session.GetError();
				MojLogInfo(m_log, "SendMail dying off, marking mail as bad ...");
				UpdateSendStatus();
			} else {
				MojLogInfo(m_log, "SendMail dying off, due to session error state ...");
				m_doneSignal.fire(m_session.GetError());
				Complete();
			}
			return;
		}

		MojString json;
		m_emailId.toJson(json);
		MojLogInfo(m_log, "running sendMail id=%s", json.data());
	
		GetEmail();

	} catch (const std::exception& e) {
		HandleException(e, __func__, __FILE__, __LINE__);
	} catch (...) {
		HandleUnknownException();
	}
}
MojoNewWhereMatcher::MatchResult MojoNewWhereMatcher::CheckProperty(
	const MojObject& key, const MojObject& response, const MojObject& op,
	const MojObject& val, MatchMode mode) const
{
	if (key.type() == MojObject::TypeString) {
		MojString keyStr;
		MojErr err = key.stringValue(keyStr);
		if (err) {
			throw std::runtime_error("Failed to convert property lookup key "
				"to string");
		}

		MojObject propVal;
		bool found = response.get(keyStr.data(), propVal);
		if (!found) {
			return NoProperty;
		}

		return CheckMatch(propVal, op, val);

	} else if (key.type() == MojObject::TypeArray) {
		return CheckProperty(key, key.arrayBegin(), response, op, val, mode);
	} else {
		throw std::runtime_error("Key specified was neither a string or "
			"array of strings");
	}
}
Exemple #5
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 );
}
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;
}
MojString getTestDir()
{
	MojString dir;
	MojErr err = dir.format("/tmp/mojodb-test-dir-%d", getpid());
	assert( err == MojErrNone );
	return dir;
}
void SmtpSyncOutboxCommand::StartSync()
{
	if (m_clear) {
		MojLogInfo(m_log, "Clearing account before running sync");
		m_client.GetSession()->ClearAccount();
	}

	MojString folderIdJson;
	m_folderId.toJson(folderIdJson);
	MojLogInfo(m_log, "syncing outbox %s", folderIdJson.data());

	m_error.clear();

	// Set up error code that will be logged on account if we fall over without managing to elsewise
	// report an error code -- just in case.
	m_error.errorCode = MailError::INTERNAL_ERROR;
	m_error.errorOnAccount = true;
	m_error.errorOnEmail = false;
	m_error.internalError = "Unknown error in smtp outbox processing";
	m_error.errorText = "";

	// FIXME: Shouldn't this be done before we reply to the sync
	// message, or adopt the activity, or something? There's a
	// lot of hysteresis in sleep, so this is unlikely to be
	// critical, it just feels wrong to do this this late,
	// without overlapping it over anything else.
	m_client.GetPowerManager().StayAwake(true, "smtp outbox sync");

	CheckNetworkConnectivity();
}
/*
 * Save the new incoming IM message to the DB
 *
 * @return MojErr if error - caller will log it
 */
MojErr IncomingIMHandler::saveNewIMMessage(MojRefCountedPtr<IMMessage> IMMessage) {

	MojErr err;

	// The message we are handling
	m_IMMessage = IMMessage;

	// save it
	MojObject dbObject;
	err = m_IMMessage->createDBObject(dbObject);
	MojErrCheck(err);

	//add our kind to the object
	//luna://com.palm.db/put '{"objects":[{"_kind":"com.palm.test:1","foo":1,"bar":1000}]}'
	err = dbObject.putString(_T("_kind"), PALM_DB_IMMESSAGE_KIND);
	MojErrCheck(err);

	// log it - OK to show body in debug log
	MojString json;
	err = dbObject.toJson(json);
	MojErrCheck(err);
	MojLogDebug(IMServiceApp::s_log, _T("saving message to db: %s"), json.data());
	MojLogInfo(IMServiceApp::s_log, _T("saving message to db"));

	// save it
	// the save generates a call to the save result handler
	err = m_dbClient.put(this->m_IMSaveMessageSlot, dbObject);
	MojErrCheck(err);

	return MojErrNone;
}
MojErr MojDbPerfCreateTest::run()
{
	MojErr err = file.open(CreateTestFileName, MOJ_O_RDWR | MOJ_O_CREAT | MOJ_O_TRUNC, MOJ_S_IRUSR | MOJ_S_IWUSR);

	MojString buf;
	err = buf.format("MojoDb Create Performance Test,,,,,\n\nOperation,Kind,Total Time,Time Per Iteration,Time Per Object\n");
	MojTestErrCheck(err);
	err = fileWrite(file, buf);
	MojTestErrCheck(err);

	err = testCreate();
	MojTestErrCheck(err);
	allTestsTime += totalTestTime;

	err = MojPrintF("\n\n TOTAL TEST TIME: %llu nanoseconds. | %10.3f seconds.\n\n", totalTestTime, totalTestTime / 1000000000.0f);
	MojTestErrCheck(err);
	err = MojPrintF("\n-------\n");
	MojTestErrCheck(err);

	err = buf.format("\n\nTOTAL TEST TIME,,%llu,,,", totalTestTime);
	MojTestErrCheck(err);
	err = fileWrite(file, buf);
	MojTestErrCheck(err);

	err = file.close();
	MojTestErrCheck(err);

	return MojErrNone;
}
bool MojoCompareMatcher::Match(const MojObject& response)
{
	LOG_AM_TRACE("Entering function %s", __FUNCTION__);

	if (response.contains(m_key)) {
		MojObject value;
		MojString valueString;
		response.get(m_key, value);
		value.stringValue(valueString);
		if (value != m_value) {
			MojString oldValueString;
			m_value.stringValue(oldValueString);

			LOG_AM_DEBUG("Compare Matcher: Comparison key \"%s\" value changed from \"%s\" to \"%s\".  Firing.", 
				m_key.data(),
				oldValueString.data(), valueString.data());

			return true;
		} else {
			LOG_AM_DEBUG("Compare Matcher: Comparison key \"%s\" value \"%s\" unchanged.",
				m_key.data(), valueString.data());
		}
	} else {
		LOG_AM_DEBUG("Compare Matcher: Comparison key (%s) not present.",
			m_key.data());
	}

	return false;
}
Exemple #12
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;
}
void NetworkStatusMonitor::CreateActivity()
{
	ActivityBuilder ab;

	static MojInt64 uniqueId = 0;

	string serviceName = m_busClient.GetServiceName();

	// FIXME
	if(serviceName.empty()) {
		throw MailException("no service name", __FILE__, __LINE__);
	}

	MojString name;
	MojErr err = name.format("%s network status check - %lld", serviceName.c_str(), ++uniqueId);
	ErrorToException(err);

	ab.SetName(name.data());
	ab.SetDescription("Monitors network status");
	ab.SetExplicit(false);
	ab.SetPersist(false);
	ab.SetForeground(true);
	ab.SetRequiresInternet(true);

	m_activity = Activity::PrepareNewActivity(ab, true, true);
	m_activity->SetSlots(m_activityUpdateSlot, m_activityErrorSlot);
	m_activity->Create(m_busClient);
}
/*
 * New incoming IM message
 */
bool IMServiceHandler::incomingIM(const char* serviceName, const char* username, const char* usernameFrom, const char* message)
{

	MojLogTrace(IMServiceApp::s_log);

	// log the parameters
	// don't log the message text
	MojLogInfo (IMServiceApp::s_log, _T("incomingIM - IM received. serviceName: %s username: %s usernameFrom: %s"), serviceName, username, usernameFrom);

	// no error - process the IM
	MojRefCountedPtr<IMMessage> imMessage(new IMMessage);

	// set the message fields based on the incoming parameters
	MojErr err = imMessage->initFromCallback(serviceName, username, usernameFrom, message);

	if (!err) {
		// handle the message
		MojRefCountedPtr<IncomingIMHandler> incomingIMHandler(new IncomingIMHandler(m_service));
		err = incomingIMHandler->saveNewIMMessage(imMessage);
	}
	if (err) {
		MojString error;
		MojErrToString(err, error);
		MojLogError(IMServiceApp::s_log, _T("incomingIM failed: %d - %s"), err, error.data());
		MojErrCheck(err);
		return false;
	}

	return true;
}
MojErr PopBusDispatcher::CredentialsChanged(MojServiceMessage* msg, MojObject& payload)
{
	// cancel shut down if it is in shut down state
	CancelShutdown();

	MojLogTrace(s_log);

	MojString json;
	MojErr err = payload.toJson(json);
	ErrorToException(err);
	MojLogInfo(s_log, "PopBusDispatcher::CredentialsChanged: payload=%s", json.data());

	MojObject accountId;
	err = payload.getRequired("accountId", accountId);
	ErrorToException(err);

	try {
		ClientPtr client = GetOrCreateClient(accountId);
		// Calling UpdateAccount will force a folder sync.
		client->UpdateAccount(payload, true);
	} catch (const std::exception& e) {
		MojErrThrowMsg(MojErrInternal, "%s", e.what());
	}

	return msg->replySuccess();
}
Exemple #16
0
std::string BusClient::appConfDir(const MojString& appId, PackageType type, PackageLocation location)
{
	MojLogTrace(m_log);
	std::string confPath;

	switch (location) {
	case System:
		confPath = "/";
		break;
	case ThirdParty:
		confPath = BASE_CRYPTOFS;
		break;
	}

	confPath += BASE_PALM_OFFSET;

	switch (type) {
	case Application:
		confPath += APPS_DIR;
		break;
	case Service:
		confPath += SERVICES_DIR;
		break;
	}
	confPath.append(appId.begin(), appId.end());
	if (access(confPath.c_str(), R_OK) != 0) {
		m_wrongAplication = true;
	}

	return confPath + CONF_SUBDIR;
}
MojErr PopBusDispatcher::AccountCreator::CreatePopAccountResponse(MojObject& response, MojErr err)
{
	MojLogInfo(m_log, "AccountCreator::CreatePopAccountResponse");

	MojLogTrace(m_log);
	if (err)
		return m_msg->replyError(err);

	MojString json;
	err = response.toJson(json);
	MojLogInfo(m_log, "%s", json.data());

	// put the id we have just gotten into the payload we send to smtp account
	MojObject resultArray;
	err = response.getRequired("results", resultArray);
	ErrorToException(err);
	MojObject result;
	resultArray.at(0, result);
	MojObject mailAccountId;
	err = result.getRequired("id", mailAccountId);
	ErrorToException(err);
	err = m_payload.put("mailAccountId", mailAccountId);
	ErrorToException(err);

	MojObject accountId;
	err = m_payload.getRequired("accountId", accountId);
	ErrorToException(err);

	ClientPtr client = m_dispatcher.GetOrCreateClient(accountId);
	client->SendRequest(m_smtpAccountCreatedSlot, "com.palm.smtp", "accountCreated", m_payload);

	return MojErrNone;
}
Exemple #18
0
static MojErr getTypes(MojObject typesArray, BusClient::ScanTypes &bitmask)
{
	MojObject::ConstArrayIterator it = typesArray.arrayBegin();
	if (it == NULL)
		MojErrThrowMsg(MojErrInvalidMsg, "'types' not an array");

	for (MojObject::ConstArrayIterator ni = typesArray.arrayEnd(); it != ni; it++) {
		const MojObject& element = *it;
		MojString type;
		MojErr err;

		err = element.stringValue(type);
		MojErrCheck(err);

		if (type == "dbkinds")
			bitmask |= BusClient::DBKINDS;
		else if (type == "dbpermissions")
			bitmask |= BusClient::DBPERMISSIONS;
		else if (type == "filecache")
			bitmask |= BusClient::FILECACHE;
		else if (type == "activities")
			bitmask |= BusClient::ACTIVITIES;
		else
			MojErrThrowMsg(MojErrInvalidMsg, "unrecognized type '%s'", type.data());
	}

	return MojErrNone;
}
void SmtpActivityFactory::BuildOutboxWatch(ActivityBuilder& ab, const MojObject& accountId, const MojObject& folderId)
{
	ActivityBuilder actBuilder;

	MojString name;

	name.format(OUTBOX_WATCH_ACTIVITY_FMT, AsJsonString(accountId).c_str());

	ab.SetName(name);
	ab.SetDescription("Watches SMTP outbox for new emails");
	ab.SetPersist(true);
	ab.SetExplicit(true);
	ab.SetRequiresInternet(false); // don't trigger until we also have connectivity
	ab.SetImmediate(true, ActivityBuilder::PRIORITY_LOW);

	// Callback
	MojObject callbackParams;
	MojErr err = callbackParams.put("accountId", accountId);
	ErrorToException(err);
	err = callbackParams.put("folderId", folderId);
	ErrorToException(err);

	ab.SetCallback(OUTBOX_BUS_METHOD, callbackParams);
	ab.SetMetadata(callbackParams);
}
Exemple #20
0
MojErr MojDbPerfUpdateTest::testMerge(MojDb& db)
{
	MojString buf;
	MojErr err = buf.format("\nUPDATE VIA MERGE,,,,,\n");
	MojTestErrCheck(err);
	err = fileWrite(file, buf);
	MojTestErrCheck(err);

	err = updateObjsViaMerge(db, MojPerfSmKindId, &MojDbPerfTest::createSmallObj);
	MojTestErrCheck(err);
	err = updateObjsViaMerge(db, MojPerfMedKindId, &MojDbPerfTest::createMedObj);
	MojTestErrCheck(err);
	err = updateObjsViaMerge(db, MojPerfLgKindId, &MojDbPerfTest::createLargeObj);
	MojTestErrCheck(err);
	err = updateObjsViaMerge(db, MojPerfMedNestedKindId, &MojDbPerfTest::createMedNestedObj);
	MojTestErrCheck(err);
	err = updateObjsViaMerge(db, MojPerfLgNestedKindId, &MojDbPerfTest::createLargeNestedObj);
	MojTestErrCheck(err);
	err = updateObjsViaMerge(db, MojPerfMedArrayKindId, &MojDbPerfTest::createMedArrayObj);
	MojTestErrCheck(err);
	err = updateObjsViaMerge(db, MojPerfLgArrayKindId, &MojDbPerfTest::createLargeArrayObj);
	MojTestErrCheck(err);

	return MojErrNone;
}
MojoNewWhereMatcher::MatchResult MojoNewWhereMatcher::CheckProperty(
	const MojObject& keyArray, MojObject::ConstArrayIterator keyIter,
	const MojObject& response, const MojObject& op, const MojObject& val,
	MatchMode mode) const
{
	MojObject onion = response;
	for (; keyIter != keyArray.arrayEnd(); ++keyIter) {
		if (onion.type() == MojObject::TypeArray) {
			return CheckProperty(keyArray, keyIter, onion, onion.arrayBegin(),
				op, val, mode);
		} else if (onion.type() == MojObject::TypeObject) {
			MojString keyStr;
			MojErr err = (*keyIter).stringValue(keyStr);
			if (err) {
				throw std::runtime_error("Failed to convert property lookup "
					"key to string");
			}

			MojObject next;
			if (!onion.get(keyStr.data(), next)) {
				return NoProperty;
			}

			onion = next;
		} else {
			return NoProperty;
		}
	}

	return CheckMatch(onion, op, val);

}
Exemple #22
0
MojErr MojDbPerfUpdateTest::testUpdateKind(MojDb& db)
{
	MojString buf;
	MojErr err = buf.format("\nUPDATE KIND,,,,,\n");
	MojTestErrCheck(err);
	err = fileWrite(file, buf);
	MojTestErrCheck(err);

	err = updateKind(db, MojPerfSmKindId, MojPerfSmKindStr, MojPerfSmKindExtraIndex, &MojDbPerfTest::createSmallObj);
	MojTestErrCheck(err);
	err = updateKind(db, MojPerfMedKindId, MojPerfMedKindStr, MojPerfMedKindExtraIndex, &MojDbPerfTest::createMedObj);
	MojTestErrCheck(err);
	err = updateKind(db, MojPerfLgKindId, MojPerfLgKindStr, MojPerfLgKindExtraIndex, &MojDbPerfTest::createLargeObj);
	MojTestErrCheck(err);
	err = updateKind(db, MojPerfMedNestedKindId, MojPerfMedNestedKindStr, MojPerfMedNestedKindExtraIndex, &MojDbPerfTest::createMedNestedObj);
	MojTestErrCheck(err);
	err = updateKind(db, MojPerfLgNestedKindId, MojPerfLgNestedKindStr, MojPerfLgNestedKindExtraIndex, &MojDbPerfTest::createLargeNestedObj);
	MojTestErrCheck(err);
	err = updateKind(db, MojPerfMedArrayKindId, MojPerfMedArrayKindStr, MojPerfMedArrayKindExtraIndex, &MojDbPerfTest::createMedArrayObj);
	MojTestErrCheck(err);
	err = updateKind(db, MojPerfLgArrayKindId, MojPerfLgArrayKindStr, MojPerfLgArrayKindExtraIndex, &MojDbPerfTest::createLargeArrayObj);
	MojTestErrCheck(err);

	return MojErrNone;
}
void ImapAccountAdapter::ParseLoginConfig(const MojObject& config, ImapLoginSettings& login)
{
	MojErr err;

	// Optional username; overrides account username if available
	bool hasServerUsername = false;
	MojString serverUsername;
	err = config.get(ImapAccountAdapter::USERNAME, serverUsername, hasServerUsername);
	ErrorToException(err);
	if(hasServerUsername) {
		login.SetUsername(serverUsername.data());
	}

	MojString hostname;
	err = config.getRequired(ImapAccountAdapter::HOSTNAME, hostname);
	ErrorToException(err);
	login.SetHostname(hostname.data());

	int port;
	err = config.getRequired(ImapAccountAdapter::PORT, port);
	ErrorToException(err);
	login.SetPort(port);

	MojString encryptionStr;
	err = config.getRequired(ImapAccountAdapter::ENCRYPTION, encryptionStr);
	ErrorToException(err);
	login.SetEncryption(GetEncryptionType(encryptionStr));
}
void MojoDatabase::GetSentEmails(Signal::SlotRef slot, const MojObject& outboxFolderId, MojInt32 limit)
{
	MojErr err;

	MojDbQuery query;
	err = query.from(EmailSchema::Kind::EMAIL);
	ErrorToException(err);

	err = query.where(EmailSchema::FOLDER_ID, MojDbQuery::OpEq, outboxFolderId);
	ErrorToException(err);

	MojString sendStatus;
	err = sendStatus.format("%s.%s",EmailSchema::SEND_STATUS, EmailSchema::SendStatus::SENT);
	ErrorToException(err);
	err = query.where(sendStatus.data(), MojDbQuery::OpEq, true);
	ErrorToException(err);

	// Set limit
	if(limit > 0) {
		query.limit(limit);
	}

	slot.cancel(); // cancel existing slot in case we're in a callback
	err = m_dbClient.find(slot, query);
	ErrorToException(err);
}
void SyncAccountCommand::RunImpl()
{
	try {
		if (!m_client.GetAccount().get()) {
			MojString err;
			err.format("Account is not loaded for '%s'", AsJsonString(
					m_client.GetAccountId()).c_str());
			throw MailException(err.data(), __FILE__, __LINE__);
		}

		m_account = m_client.GetAccount();
		if(m_account->HasPassword()) {
			m_accountId = m_account->GetAccountId();
			MojObject inboxFolderId = m_account->GetInboxFolderId();

			MojLogInfo(m_log, "Creating command to sync inbox emails");

			MojErr err = m_payload.put(EmailSchema::FOLDER_ID, inboxFolderId);
			ErrorToException(err);

			m_client.SyncFolder(m_payload);
		} else {
			MojLogInfo(m_log, "No password!  Sync aborted!");
		}

		Complete();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("Unknown exception", __FILE__, __LINE__));
	}
}
Exemple #26
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;
}
MojErr AccountFinderCommand::GetPasswordResponse(MojObject& response, MojErr err)
{
	CommandTraceFunction();

	try {
		// check the result first
		ErrorToException(err);

		MojObject credentials;
		// Credentials object can be missing if the POP account is restored from
		// backup.  Checking for its existence before using it will prevent exception
		// to be thrown.
		bool exists = response.get("credentials", credentials);
		if (exists) {
			MojString password;
			err = credentials.getRequired("password", password);
			ErrorToException(err);

			m_account->SetPassword(password.data());
		} else {
			MojLogInfo(m_log, "The credentials of POP account '%s' are missing", AsJsonString(m_accountId).c_str());
		}

		// get the transport object
		GetPopAccount();
	} catch (const std::exception& ex) {
		Failure(ex);
	} catch (...) {
		Failure(MailException("unknown exception", __FILE__, __LINE__));
	}

	return MojErrNone;
}
MojErr PopBusDispatcher::ParseEmlMessage(MojServiceMessage* msg, MojObject& payload)
{
	MojLogInfo(s_log, "PopBusDispatcher::ParseEmlMessage");

	// cancel shut down if it is in shut down state
	CancelShutdown();

	try {

		MojString filePath;
		MojErr err = payload.getRequired("filePath", filePath);
		ErrorToException(err);

		MojLogDebug(s_log, "filePath:%s", filePath.data());
		if (filePath.empty()) {
			msg->replyError(MojErrInvalidArg, "Invalid query string");
		} else {
			new ParseEmlHandler(this, m_bClient, m_tasks, msg, filePath.data());
		}

		return MojErrNone;
	} catch (const std::exception& e) {
		MojErrThrowMsg(MojErrInternal, "%s", e.what());
	}

}
/*
 * Result of query for buddy with given username and serviceName
 *
 * If the buddy is found, we can send no matter what. If buddy is not found, we need to check if this service allows sending IM messages
 * to non buddies (gtalk does not allow this, aol does)
 */
MojErr SendOneMessageHandler::findBuddyResult(MojObject& result, MojErr findErr)
{

	if (findErr) {

		MojString error;
		MojErrToString(findErr, error);
		MojLogError(IMServiceApp::s_log, _T("findBuddyResult: error %d - %s"), findErr, error.data());
		// not much we can do here...
		failMessage(ERROR_SEND_GENERIC_ERROR);

	} else {

		// log the results
		MojString mojStringJson;
		result.toJson(mojStringJson);
		MojLogDebug(IMServiceApp::s_log, _T("findBuddyResult result: %s"), mojStringJson.data());

		// "results" in result
		MojObject results;
		result.get(_T("results"), results);

		// check to see if array is empty - there should really always be 0 or 1 item here
		if (!results.empty()){

			// buddy is on the list - send to the transport
			MojLogInfo(IMServiceApp::s_log, _T("findBuddyResult - user is on buddy list. No need to check account template."));
			sendToTransport();
		}
		else {
			MojLogInfo(IMServiceApp::s_log, _T("findBuddyResult - no buddy found. Need to check account template if this is allowed"));

			// check palm://com.palm.service.accounts/listAccountTemplates {"capability":"MESSAGING"} to get a list of account templates that support messaging.
			// If the account template includes "chatWithNonBuddies":false, it should fail to send.
			MojLogInfo(IMServiceApp::s_log, "Issuing listAccountTemplates request to com.palm.service.accounts");

			// parameters: {“capability”:”MESSAGING”}
			MojObject params;
			params.putString("capability", "MESSAGING");

			// Get a request object from the service
			MojRefCountedPtr<MojServiceRequest> req;
			MojErr err = m_service->createRequest(req);

			if (!err) {
				err = req->send(m_listAccountSlot, "com.palm.service.accounts", "listAccountTemplates", params);
			}

			if (err) {
				MojString error;
				MojErrToString(err, error);
				MojLogError(IMServiceApp::s_log, _T("findBuddyResult failed to send request to accounts: error %d - %s"), err, error.data());
				// not much we can do here...don't leave message still pending
				failMessage(ERROR_SEND_GENERIC_ERROR);
			}
		}
	}

	return MojErrNone;
}
Exemple #30
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;
}