void ActivityBuilderFactory::BuildScheduledSync(ActivityBuilder &builder, int intervalMins)
{
	// activity to setup watch
	MojString name;
	GetScheduledSyncActivityName(name);

	// description of watch
	MojString desc;
	GetScheduledSyncActivityDesc(desc);

	// sync interval in seconds
	int intervalSecs = MinsToSecs(intervalMins);

	builder.SetName(name.data());
	builder.SetDescription(desc.data());
	builder.SetPersist(true);
	builder.SetExplicit(true);
	builder.SetRequiresInternet(false);
	builder.SetSyncInterval(0, intervalSecs);
	builder.SetImmediate(true, "low");

	// setup parameters (to be sent when trigger is called)
	MojObject params;
	MojErr err = params.put(PopAccountAdapter::ACCOUNT_ID, m_accountId);
	ErrorToException(err);
	builder.SetCallback(SCHEDULED_SYNC_CALLBACK, params);

	// put accountId in metadata
	MojObject metadata;
	err = metadata.put("accountId", m_accountId);
	ErrorToException(err);
	builder.SetMetadata(metadata);
}
void ActivityBuilderFactory::BuildDeleteEmailsWatch(ActivityBuilder& builder)
{
	MojString name;
	GetDeleteEmailsActivityName(name);

	MojString desc;
	GetDeleteEmailsActivityDesc(desc);

	builder.SetName(name.data());
	builder.SetDescription(desc.data());
	builder.SetPersist(true);
	builder.SetExplicit(true);
	builder.SetImmediate(true, "low");

	// setup trigger
	MojDbQuery trigger;
	MojErr err = trigger.from(PopEmailAdapter::POP_EMAIL_KIND);
	ErrorToException(err);
	err = trigger.where("_del", MojDbQuery::OpEq, true);
	ErrorToException(err);
	builder.SetDatabaseWatchTrigger(trigger);

	// setup parameters (to be sent when trigger is called)
	MojObject params;
	err = params.put(PopFolderAdapter::ACCOUNT_ID, m_accountId);
	ErrorToException(err);
	builder.SetCallback(DELETE_EMAILS_CALLBACK, params);

	// put accountId in metadata
	MojObject metadata;
	err = metadata.put(PopFolderAdapter::ACCOUNT_ID, m_accountId);
	ErrorToException(err);
	builder.SetMetadata(metadata);
}
void ActivityBuilderFactory::BuildAccountPrefsWatch(ActivityBuilder& builder, MojObject& accountRev)
{
	MojString name;
	GetAccountPrefsWatchActivityName(name);

	MojString desc;
	GetAccountPrefsWatchActivityDesc(desc);

	builder.SetName(name.data());
	builder.SetDescription(desc.data());
	builder.SetPersist(true);
	builder.SetExplicit(true);
	builder.SetImmediate(true, "low");

	MojDbQuery trigger;
	MojErr err = trigger.from(PopAccountAdapter::POP_ACCOUNT_KIND);
	ErrorToException(err);
	err = trigger.where(PopAccountAdapter::ACCOUNT_ID, MojDbQuery::OpEq, m_accountId);
	ErrorToException(err);
	err = trigger.where("_revPop", MojDbQuery::OpGreaterThan, accountRev);
	ErrorToException(err);
	builder.SetDatabaseWatchTrigger(trigger);

	MojObject params;
	err = params.put(PopAccountAdapter::ACCOUNT_ID, m_accountId);
	ErrorToException(err);
	builder.SetCallback(ACCOUNT_PREFS_WATCH_CALLBACK, params);

	MojObject metadata;
	err = metadata.put(PopAccountAdapter::ACCOUNT_ID, m_accountId);
	ErrorToException(err);
	builder.SetMetadata(metadata);
}
Exemple #4
0
void BusClient::ScheduleShutdown()
{
	MojLogTrace(m_log);
	// Reply to the "run" message now that we're done
	if (m_launchedAsService && m_msg.get()) {
		const Configurator::ConfigCollection& ok = Configurator::ConfigureOk();
		const Configurator::ConfigCollection& failed = Configurator::ConfigureFailure();

		if (m_wrongAplication) {
			MojString response;
			response.appendFormat("Aplication or service doesn't exist");
			m_wrongAplication = false;
			m_msg->replyError(MojErrInternal, response.data());

		} else if (!failed.empty()) {
			MojString response;
			response.appendFormat("Partial configuration - %zu ok, %zu failed", ok.size(), failed.size());
			m_msg->replyError(MojErrInternal, response.data());
		} else {
			MojObject response;
			response.putInt("configured", ok.size());
			m_msg->replySuccess(response);
		}
		m_msg.reset();
	}

	if (!m_pending.empty()) {
		MojLogDebug(m_log, "%d pending service calls to handle remaining", m_pending.size());

		// still more pending work
		m_configuratorsCompleted = 0;
		m_configurators.clear();
		Configurator::ResetConfigStats();

		const PendingWork &pending = m_pending.back();
		(pending.instance->*(pending.callback))(pending.msg.get(), pending.payload);

		m_pending.pop_back();
		return;
	}

	MojLogDebug(m_log, "No more pending service calls to handle - scheduling shutdown");

	// Schedule an event to shutdown once the stack is unwound.
	if (m_timerTimeout == 0) {
		// this is to work around around a race condition where the LSCall is delivered
		// after we shutdown causing us to start back up - give some time for the LSCall
		// to get delivered.  NOV-114626.  This needs a proper fix within ls2 (can't be
		// worked around anywhere else).
		m_timerTimeout = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, /* timer priority */
		    500, /* timeout in ms */
		    &BusClient::ShutdownCallback, // callback
		    this, /* callback data */
		    NULL /*destroy notify callback*/
		);
	}
	//g_idle_add(&BusClient::ShutdownCallback, this);

	m_shuttingDown = true;
}
/*
 * 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;
}
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;
}
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());
	}

}
void PopBusDispatcher::GetAccountFromTransportObject(boost::shared_ptr<PopAccount>& account, MojObject& payload, MojObject& transportObj)
{
	MojString username;
	MojErr err = transportObj.getRequired("username", username);
	ErrorToException(err);
	account->SetUsername(username.data());

	MojString password;
	err = payload.getRequired("password", password);
	ErrorToException(err);
	account->SetPassword(password.data());

	MojString server;
	err = transportObj.getRequired("server", server);
	ErrorToException(err);
	account->SetHostName(server.data());

	int port;
	err = transportObj.getRequired("port", port);
	ErrorToException(err);
	account->SetPort(port);

	MojString encryption;
	err = transportObj.getRequired("encryption", encryption);
	ErrorToException(err);
	account->SetEncryption(encryption.data());
}
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));
}
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;
}
Exemple #11
0
MojErr MojDbKind::update(MojObject* newObj, const MojObject* oldObj, MojDbOp op, MojDbReq& req, bool checkSchema)
{
	MojLogTrace(s_log);

	MojErr err = checkPermission(op, req);
	MojErrCheck(err);
	err = req.curKind(this);
	MojErrCheck(err);

#if defined(TESTDBKIND)
	MojString s;
	MojErr e2;
	
	if (oldObj) {
		e2 = oldObj->toJson(s);
		MojLogInfo(s_log, _T("Kind_Update_OldObj: %s ;\n"), s.data());
	}
	if (newObj) {
		e2 = newObj->toJson(s);
		MojLogInfo(s_log, _T("Kind_Update_NewObj: %s ;\n"), s.data());
	}
#endif
	if (newObj) {
		// add the _backup property if not set
		if (m_backup && !newObj->contains(MojDb::SyncKey)) {
			err = newObj->putBool(MojDb::SyncKey, true);
			MojErrCheck(err);
		}

		// TEMPORARY!!! This should be done in pre-update to also check parent kinds
        	// warning message comes from preUpdate
		if(checkSchema)
		{
		   
		   MojSchema::Result res;
		   err = m_schema.validate(*newObj, res);
		   MojErrCheck(err);
		   if (!res.valid())
		   {
		      MojErrThrowMsg(MojErrSchemaValidation, _T("schema validation failed for kind '%s': %s"),
		                     m_id.data(), res.msg().data());
		   }
		}
        
	}

	// update revSets and validate schema
	err = preUpdate(newObj, oldObj, req);
	MojErrCheck(err);
	// update indexes
	MojVector<MojDbKind*> kindVec;
	MojInt32 idxcount = 0;
	err = updateIndexes(newObj, oldObj, req, op, kindVec, idxcount);
	MojLogInfo(s_log, _T("Kind_UpdateIndexes_End: %s; supers = %zu; indexcount = %zu; updated = %d \n"), this->id().data(), 
				m_supers.size(), m_indexes.size(), idxcount);

	MojErrCheck(err);

	return MojErrNone;
}
Exemple #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;
}
// TODO: Need to use ActivitySet for activity handling.
SmtpAccountDisableCommand::SmtpAccountDisableCommand(SmtpClient& client, const MojRefCountedPtr<MojServiceMessage> msg, const MojObject& accountId)
: SmtpCommand(client),
  m_client(client),
  m_accountId(accountId),
  m_deleteOutboxWatchResponseSlot(this, &SmtpAccountDisableCommand::DeleteOutboxWatchResponse),
  m_deleteAccountWatchResponseSlot(this, &SmtpAccountDisableCommand::DeleteAccountWatchResponse),
  m_msg(msg)
{
	MojString d;
	m_accountId.stringValue(d);
	m_outboxWatchActivityName.format(OUTBOX_WATCH_ACTIVITY_FMT, d.data());
	m_accountWatchActivityName.format(ACCOUNT_WATCH_ACTIVITY_FMT, d.data());
}
MojErr SmtpAccountDisableCommand::DeleteAccountWatchResponse(MojObject& response, MojErr err)
{
	MojLogInfo(m_log, "SmtpAccountDisable replying");

	try {
		if(err) {
			if(err == ENOENT) {
				MojLogWarning(m_log, "account watch activity doesn't exist");
			} else {
				ResponseToException(response, err);
			}
		}

		m_msg->replySuccess();
		Complete();
	} catch (const std::exception& e) {
		m_msg->replyError(err, e.what());
		Failure(e);
	} catch (...) {
		MojString error;
		error.format("uncaught exception in %s", __PRETTY_FUNCTION__);
		m_msg->replyError(MojErrInternal, error.data());
		Failure(MailException("unknown exception in cancelling activities response", __FILE__, __LINE__));
	}
	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;
}
/*
 * 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;
}
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__));
	}
}
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);

}
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");
	}
}
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);
}
Exemple #21
0
void BusClient::Unconfigure(const MojString &appId, PackageType type, PackageLocation location, ScanTypes bitmask)
{
	std::string confPath = appConfDir(appId, type, location);

	ScanDir(appId, Configurator::RemoveConfiguration, confPath, bitmask, PackageTypeToConfigType(type));
	MojLogDebug(m_log, "Removal of %s finished", appId.data());
}
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();
}
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();
}
MojErr SmtpAccountDisableCommand::DeleteOutboxWatchResponse(MojObject& response, MojErr err)
{
	MojLogInfo(m_log, "SmtpAccountDisable removing outbox watch");

	try {
		if(err) {
			if(err == ENOENT) {
				MojLogWarning(m_log, "outbox watch activity doesn't exist");
			} else {
				ResponseToException(response, err);
			}
		}

		MojObject payload;
		payload.put("activityName", m_accountWatchActivityName);

		m_client.SendRequest(m_deleteAccountWatchResponseSlot, "com.palm.activitymanager", "cancel", payload);
	} catch (const std::exception& e) {
		m_msg->replyError(err, e.what());
		Failure(e);
	} catch (...) {
		MojString error;
		error.format("uncaught exception in %s", __PRETTY_FUNCTION__);
		m_msg->replyError(MojErrInternal, error.data());
		Failure(MailException("unknown exception in cancelling activities response", __FILE__, __LINE__));
	}

	return MojErrNone;
}
Exemple #25
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;
}
/**
 * is kind exist?
 */
MojErr MojDbShardManagerTest::verifyKindExistance (MojString kindId, MojDb& db)
{
    bool foundOurKind = false;
    MojString str; //for debug

    //kinds map
    MojDbKindEngine::KindMap& map = db.kindEngine()->kindMap();

    for (MojDbKindEngine::KindMap::ConstIterator it = map.begin();
         it != map.end();
         ++it)
    {
        str = it.key();
        if(kindId == str)
        {
            foundOurKind = true;
            break;
        }
    }

    if (!foundOurKind)
        MojErrThrowMsg(MojErrDbKindNotRegistered, "Kind %s not found in kindMap", kindId.data());

    return MojErrNone;
}
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();
	}
}
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;
}
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);
}
/*
 * 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;
}