RhoConnectClient is used for synchronization with RhoConnect applications.
In order to use this API you must include the following extension in your build.yml
extensions: ["rhoconnect-client"]
Be sure to review the JavaScript API Usage guide for important information about using this API in JavaScript
Be sure to review the Ruby API Usage guide for important information about using this API in Ruby
Add the object notification by passing in an object ID.
Parameters
Source name for object notification.
Object ID to get notifications.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.addObjectNotify(STRING sourceName, STRING object)
Rho::RhoConnectClient.addObjectNotify(STRING sourceName, STRING object)
Removes callback for object notifications.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.cleanObjectNotify()
Rho::RhoConnectClient.cleanObjectNotify()
Clears the sync notification for a given source.
Parameters
Source name to clear notification. Use ‘*’ to clear notification for all models.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.clearNotification(STRING sourceName)
Rho::RhoConnectClient.clearNotification(STRING sourceName)
Start the RhoConnectClient sync process.
Parameters
Set to true to show status popup.
Parameters to be passed to server.
Sync only sources that have local changes.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.doSync(BOOLEAN showStatusPopup, STRING queryParams, BOOLEAN syncOnlyChangedSources)
Rho::RhoConnectClient.doSync(BOOLEAN showStatusPopup, STRING queryParams, BOOLEAN syncOnlyChangedSources)
Start RhoConnectClient sync process for a given source name.
Parameters
Source name.
Set to true to show status popup.
Parameters to be passed to server.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.doSyncSource(STRING sourceName, BOOLEAN showStatusPopup, STRING queryParams)
Rho::RhoConnectClient.doSyncSource(STRING sourceName, BOOLEAN showStatusPopup, STRING queryParams)
Enable or disable the show status popup.
Parameters
Enable the status popup.
Disable the status popup.
Synchronous Return:
Method Access:
Rho::RhoConnectClient.enable_status_popup(BOOLEAN true_or_false)
Returns the current sync page size for the RhoConnectClient.
Synchronous Return:
Page size for the RhoConnectClient.
Method Access:
Rho::RhoConnectClient.get_pagesize()
Returns the current username of the RhoConnectClient session.
Synchronous Return:
Username of current user if logged in, last logged in user if not logged in.
Method Access:
Rho::RhoConnectClient.get_user_name()
Returns true if the RhoConnectClient currently has a user session, false if not.
Synchronous Return:
True if have logged in user session, false if not.
Method Access:
Rho.RhoConnectClient.isLoggedIn()
Rho::RhoConnectClient.isLoggedIn()
Returns true if sync is currently in progress.
Synchronous Return:
True if sync has started but not finished yet, false otherwise.
Method Access:
Rho.RhoConnectClient.isSyncing()
Rho::RhoConnectClient.isSyncing()
Authenticates the user with RhoConnect. The callback will be executed when it is finished.
Parameters
Login name.
Password.
Async Callback Returning Parameters: INTEGER
Synchronous Return:
Method Access:
Rho.RhoConnectClient.login(STRING login, STRING password, CallBackHandler callback)
Rho::RhoConnectClient.login(STRING login, STRING password, CallBackHandler callback)
Logout the user from the RhoConnect server. This removes the local user session.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.logout()
Rho::RhoConnectClient.logout()
Perform an action on a record upon a sync create-error. The :recreate
action will write the records to the local DB and schedule them to be pushed to the back-end again at the next sync. For example, if a create-error occurred because something was missing but it is mandatory for validation. You can use the :recreate flag after catching the error in order resend a fixed record. The :delete
action will permanently delete a record on the local DB and will never be synced with the back-end. This might be used in cases where a time-stamp is vital and upon error, a new record must be generated before syncing.
Parameters
The ORM model name. This is necessary for RhoConnect to know the model on which the action is to be performed.
An array of one or more object IDs. These IDs are the IDs of the objects that failed to create.
Action to be performed on the objects specified in the objects array.
Remove the object from the local DB and do not retry creation of the record on the back-end.
Push this object to the server again at the next sync.
Synchronous Return:
Method Access:
Rho::RhoConnectClient.on_sync_create_error(STRING source_name, ARRAY objects, SYMBOL action)
Decide whether or not to retry deletion of a record upon a sync delete-error. In case you would like to retry for example, if the network your device is on is not completely reliable, you may opt to retry a few times before reporting that the delete failed. To retry a delete specify the :retry
action with this method. For example: RhoConnectClient.on_sync_delete_error('Product', object, :retry)
Parameters
The name of the source on the RhoConnect server.
An hash of one or more error objects. Structure of the objects
hash is { id => { ‘attributes’ => { attribute => value }}}
Action to be performed on the error object(s).
Push delete object operation to server again at next sync.
Synchronous Return:
Method Access:
Rho::RhoConnectClient.on_sync_delete_error(STRING source_name, HASH objects, SYMBOL action)
Perform an action on a record upon a sync update-error. The :retry
action is similar to the :recreate
action in the on_sync_create_error
method. The :rollback
action will roll back changes that are not accepted by the back-end. The record that will be rolled back to is the record(s) provided in the rollback_objects parameter. We recommend that the previous state of the record be saved in some way (preferably local such as cache) so that it can be provided upon update-error.
Parameters
The ORM model name. This is necessary for RhoConnect to know the model on which the action is to be performed.
A hash of one or more error objects. The structure of the objects
hash is { id => { ‘attributes’ => { attribute => value }}}
Action to be performed on the objects specified in the objects hash.
Push the update object operation to server again at next sync.
Write the rollback_objects
to client database.
A hash of the attributes for the objects before a failed update and send by the server. Must be specified for :rollback action. Structure of the rollback_objects
hash is { id => { ‘attributes’ => { attribute => value }}}
Synchronous Return:
Method Access:
Rho::RhoConnectClient.on_sync_update_error(STRING source_name, HASH objects, SYMBOL action, HASH rollback_objects)
If you have a large dataset in your backend service, you don’t have to synchronize everything with the RhoConnectClient. Instead you can filter the synchronized dataset using the RhoConnectClient’s search function. Provide callback, which will be executed after search is completed.
(Not currently supported in JavaScript.)
Parameters
Hash of arguments passed to search.
Array of source names to be included in search result.
Default is ‘search’
Hash of key-value pairs to be included in search result.
Maximum number of results to be returned.
If true and there are local changes, client sync will be triggered before search.
Async Callback Returning Parameters: OBJECT
Resulting status of search. ‘ok’ of completed successfully, ‘error’ otherwise.
Search_params originally provided for the search call. Typically you want to forward the original search_params to your view that displays the results so you can perform the same query locally. Please see examples section.
Synchronous Return:
Will return value only if threadedMode set to false. Otherwise search results returned in callback.
: this method also supports async callbacks - check the Callback tab for callback return parameters.Method Access:
Rho::RhoConnectClient.search(HASH args, CallBackHandler callback)
The RhoConnectClient system uses notifications to provide information about the sync process to a Rhodes application. Notifications can be setup once for the duration of runtime or each time a sync is triggered. Once a sync is processing for a model, notifications are called with parameters containing sync process state. Your application can use this information to display different wait pages, progress bars, etc. setNotification will set notification for a model.
Parameters
Source name for which notification will be enabled. Use ‘*’ to set notification for all models.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.setNotification(STRING sourceName, CallBackHandler callback)
Rho::RhoConnectClient.setNotification(STRING sourceName, CallBackHandler callback)
The RhoConnectClient can send a notification when a specific object on the current page has been modified. This is useful if you have frequently-changing data like feeds or time-lines in your application and want them to update without the user taking any action.
Parameters
Async Callback Returning Parameters: OBJECT
Array of created objects.
Array of updated objects.
Array of deleted objects.
Synchronous Return:
Method Access:
Rho.RhoConnectClient.setObjectNotification(CallBackHandler callback)
Rho::RhoConnectClient.setObjectNotification(CallBackHandler callback)
Set the synchronization page size for the RhoConnectClient.
Parameters
Size of the RhoConnectClient synchronization page.
Synchronous Return:
Method Access:
Rho::RhoConnectClient.set_pagesize(INTEGER size)
Updates the RhoConnectClient poll interval.
Parameters
Number of seconds for the poll interval. 0 disables polling-based synchronization (you may still use push-based-synchronization).
Synchronous Return:
Method Access:
Rho::RhoConnectClient.set_pollinterval(INTEGER interval)
Enable or disable verification of RhoConnect SSL certificates.
Parameters
Enable verification of RhoConnect SSL certificates.
Disable verification of RhoConnect SSL certificates.
Synchronous Return:
Method Access:
Rho::RhoConnectClient.set_ssl_verify_peer(BOOLEAN true_or_false)
Sets the RhoConnect server address and stores it in rhoconfig.txt. This will modify the URL set before running the app.
Parameters
The URL for the RhoConnect server.
Synchronous Return:
Method Access:
Rho::RhoConnectClient.set_syncserver(STRING server_url)
Stops any sync operations currently in progress.
There is a high potential of database corruption if this method is used during a sync. Do not do this unless you are planning on resetting your DB afterward. |
Synchronous Return:
Method Access:
Rho.RhoConnectClient.stopSync()
Rho::RhoConnectClient.stopSync()
Set 0 to force bulk sync on next synchronization cycle. After sync is complete, bulksyncState will be set to 1.
(Not currently supported in JavaScript.)
Default: 1
Property Access:
Rho::RhoConnectClient.bulksyncState
Page size for RhoConnectClient. Default size is 2000.
Property Access:
Rho.RhoConnectClient.pageSize
Rho::RhoConnectClient.pageSize
Sync poll interval in seconds. Setting this to 0 will disable polling-based sync. Sync process will be triggered automatically according to this setting.
Default: 60
Property Access:
Rho.RhoConnectClient.pollInterval
Rho::RhoConnectClient.pollInterval
Enable or disable show status pop-up.
Default: true
Property Access:
Rho.RhoConnectClient.showStatusPopup
Rho::RhoConnectClient.showStatusPopup
Enable or disable verification of RhoConnect ssl certificates, true by default.
Default: true
Property Access:
Rho.RhoConnectClient.sslVerifyPeer
Rho::RhoConnectClient.sslVerifyPeer
Sync server URL.
Property Access:
Rho.RhoConnectClient.syncServer
Rho::RhoConnectClient.syncServer
Current username of the RhoConnectClient session if isLoggedIn is true, otherwise returns the last logged in username.
Property Access:
Rho.RhoConnectClient.userName
Rho::RhoConnectClient.userName
In your controller call login.
Rho.RhoConnectClient.login('john','password',function(result){ loginCallback(result); });
RhoConnectClient.login( @params['login'], @params['password'], url_for(:action => :login_callback) )
When RhoConnectClient.login completes, the callback declared is executed and receives parameters including success or failure and error messages (if any).
// Error codes: // ERR_NONE = 0 // ERR_NETWORK = 1 // ERR_REMOTESERVER = 2 // ERR_RUNTIME = 3 // ERR_UNEXPECTEDSERVERRESPONSE = 4 // ERR_DIFFDOMAINSINSYNCSRC = 5 // ERR_NOSERVERRESPONSE = 6 // ERR_CLIENTISNOTLOGGEDIN = 7 // ERR_CUSTOMSYNCSERVER = 8 // ERR_UNATHORIZED = 9 function loginCallback(result) { var errorCode = parseInt(result.error_code); var errorMessage = result.error_message; if(errorCode === 0 { // process success } else { // process error with errorMessage } }
# Error codes: # ERR_NONE = 0 # ERR_NETWORK = 1 # ERR_REMOTESERVER = 2 # ERR_RUNTIME = 3 # ERR_UNEXPECTEDSERVERRESPONSE = 4 # ERR_DIFFDOMAINSINSYNCSRC = 5 # ERR_NOSERVERRESPONSE = 6 # ERR_CLIENTISNOTLOGGEDIN = 7 # ERR_CUSTOMSYNCSERVER = 8 # ERR_UNATHORIZED = 9 def login_callback error_code = @params['error_code'].to_i if error_code == Rho::RhoError::ERR_NONE # run sync if we were successful WebView.navigate Rho::RhoConfig.options_path RhoConnectClient.doSync else if error_code == Rho::RhoError::ERR_CUSTOMSYNCSERVER @msg = @params['error_message'] end if not @msg or @msg.length == 0 @msg = Rho::RhoError.new(error_code).message end WebView.navigate( url_for(:action => :login, :query => {:msg => @msg}) ) end end
First, assign a sync notification for the Account model:
function syncNotify(params) { // handle notifications... } Rho.RhoConnectClient.setNotification('Account', syncNotify);
RhoConnectClient.setNotification( 'Account', url_for(:action => :sync_notify), "sync_complete=true" )
Which is the same as:
function syncNotify() { // handle notifications... } Account.setNotification(syncNotify);
Account.setNotification( url_for(:action => :sync_notify), "sync_complete=true" )
You can also set a notification for all models:
function syncNotify(params) { // handle notifications... } Rho.RhoConnectClient.setNotification('*', syncNotify);
RhoConnectClient.setNotification( '*', url_for(:action => :sync_notify), "sync_complete=true" )
To use object notifications, first set the notification callback in application.rb#initialize.
class AppApplication < Rho::RhoApplication def initialize super RhoConnectClient.setObjectNotification( url_for( :controller => "Product", :action => :sync_object_notify ) ) end end
Next, in your controller action that displays the object(s), add the object notification by passing in a record or collection of records:
function syncObjectNotified(params) { // handle notifications... } var product = Product.find('first'); Rho.RhoConnectClient.addObjectNotify('Product', product.id);
class ProductController < Rho::RhoController # GET /Product def index @product = Product.find(:first) RhoConnectClient.addObjectNotify('Product', @product.id) render end # ... def sync_object_notified # process notification data ... # refresh the current page WebView.refresh # or call System.execute_js to update part of the page end end
Here we will set a notification and log an error code 1 or ERR_NETWORK:
function syncNotify(result) { var errorCode = parseInt(result.error_code); var errorMessage = result.error_message; if(errorCode === 1) { console.log("We received a network error: " + errorMessage); return; } } Rho.RhoConnectClient.setNotification('*', syncNotify);
RhoConnectClient.setNotification( '*', url_for(:action => :sync_notify), "sync_complete=true" ) # In your controller: def sync_notify error_code = @params['error_code'].to_i error_message = @params['error_message'] if error_code == Rho::RhoError::ERR_NETWORK puts "We received a network error: " + error_message end end
First, call search from your controller action:
def search page = @params['page'] || 0 page_size = @params['page_size'] || 10 RhoConnectClient.search( { 'Contact', :from => 'search', :search_params => { :FirstName => @params['FirstName'], :LastName => @params['LastName'], :Company => @params['Company'] }, :offset => page * page_size, :max_results => page_size } url_for(:action => :search_callback) ) render :action => :search_wait end
The search_params
will be forwarded to your callback so you can update the view with the results:
def search_callback status = @params["status"] if (status and status == "ok") WebView.navigate( url_for( :action => :show_page, :query => @params['search_params'] ) ) else render :action => :search_error end end def show_page @contacts = Contact.find( :all, :conditions => { { :func => 'LOWER', :name => 'FirstName', :op => 'LIKE' } => @params[:FirstName], { :func => 'LOWER', :name=>'LastName', :op=>'LIKE' } => @params[:LastName], { :func=>'LOWER', :name=>'Company', :op=>'LIKE' } => @params[:Company], }, :op => 'OR', :select => ['FirstName','LastName', 'Company'], :per_page => page_size, :offset => page * page_size ) render :action => :show_page end
When the notification is called, it will receive a variable called @params, just like a normal Rhodes controller action.
These parameters are included in all notifications.
In the following sections we cover the different status values and parameters available with each status.
bulk_status – The state of the bulk sync process:
partition – Current bulk sync partition.
Each error contains a ‘message’ key with the error message.
Ruby Example:
@params["server_errors"]["query-error"]["message"] #=> "Error connecting to backend server: http://rhostore.herokuapp.com"
JavaScript Example:
params.server_errors["query-error"].message //=> "Error connecting to backend server: http://rhostore.herokuapp.com"
“create-error” is a unique situation that needs to be handled in your sync callback. See RhoConnectClient.on_sync_create_error()
for more details.
This status returns only when the sync run is complete (all partitions are done synchronizing).
This is present if a FixedSchema model has changed during the current sync run. A new bulk sync run should be triggered (by setting bulksyncState) and the user should be alerted in the UI.
On iOS, if the application is backgrounded, it will be suspended. This also means if a current sync is in progress, it will immediately terminate. To prevent this behavior, set ‘finish_sync_in_background’ to ‘1’ in rhoconfig.txt. When set to ‘1’, the RhoConnectClient will attempt to finish synchronization before the application fully suspends.