summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorArkadiusz Pietraszek <a.pietraszek@partner.samsung.com>2019-07-22 14:48:41 +0200
committerArkadiusz Pietraszek <a.pietraszek@partner.samsung.com>2019-07-23 09:26:25 +0200
commit7ec46fc74b6e8fee6c88db108df4f0debc1cf9d1 (patch)
tree513277be38915199b3cf2a663d252f3708d2afd1
parentadc48d91bf07894699c61e9fff5bcff915337480 (diff)
parent6fad652f2873bd7a45548fe0c00b2222aa7bcd4b (diff)
downloadwebapi-plugins-7ec46fc74b6e8fee6c88db108df4f0debc1cf9d1.tar.gz
webapi-plugins-7ec46fc74b6e8fee6c88db108df4f0debc1cf9d1.tar.bz2
webapi-plugins-7ec46fc74b6e8fee6c88db108df4f0debc1cf9d1.zip
Merge branch 'tizen_4.0' into tizen_5.0
Change-Id: Id7abc98f999b2bfb8dc0b49692f688f1b4c9ee9f
-rwxr-xr-xsrc/account/account_api.js286
-rwxr-xr-xsrc/alarm/alarm_api.js264
-rwxr-xr-xsrc/application/application_api.js2264
-rwxr-xr-xsrc/archive/archive_api.js415
-rwxr-xr-xsrc/badge/badge_api.js186
-rwxr-xr-xsrc/bluetooth/bluetooth_api.js2607
-rwxr-xr-xsrc/bookmark/bookmark_api.js576
-rwxr-xr-xsrc/calendar/js/calendar.js1152
-rwxr-xr-xsrc/calendar/js/calendar_alarm.js110
-rwxr-xr-xsrc/calendar/js/calendar_attendee.js280
-rw-r--r--src/calendar/js/calendar_item.js1338
-rwxr-xr-xsrc/calendar/js/calendar_manager.js266
-rwxr-xr-xsrc/calendar/js/calendar_recurrence_rule.js280
-rwxr-xr-xsrc/calendar/js/common.js378
-rwxr-xr-xsrc/callhistory/callhistory_api.js184
-rwxr-xr-xsrc/contact/js/address_book.js1218
-rwxr-xr-xsrc/contact/js/common.js131
-rwxr-xr-xsrc/contact/js/contact.js1116
-rwxr-xr-xsrc/contact/js/contact_data_structures.js1550
-rwxr-xr-xsrc/contact/js/contact_manager.js943
-rwxr-xr-xsrc/contact/js/person.js406
-rwxr-xr-xsrc/content/js/common.js59
-rwxr-xr-xsrc/content/js/datatypes.js1290
-rwxr-xr-xsrc/content/js/manager.js852
-rwxr-xr-xsrc/content/js/playlist.js523
-rwxr-xr-xsrc/datacontrol/datacontrol_api.js990
-rwxr-xr-xsrc/download/download_api.js493
-rw-r--r--src/exif/exif_api.js982
-rwxr-xr-xsrc/feedback/feedback_api.js153
-rwxr-xr-xsrc/filesystem/js/base64.js42
-rw-r--r--src/filesystem/js/common.js681
-rw-r--r--src/filesystem/js/file.js1901
-rw-r--r--src/filesystem/js/file_handle.js1251
-rw-r--r--src/filesystem/js/file_stream.js516
-rw-r--r--src/filesystem/js/file_system_manager.js1250
-rwxr-xr-xsrc/humanactivitymonitor/humanactivitymonitor_api.js1462
-rw-r--r--src/inputdevice/inputdevice_api.js321
-rw-r--r--src/iotcon/iotcon_api.js2288
-rwxr-xr-xsrc/keymanager/keymanager_api.js294
-rwxr-xr-xsrc/mediacontroller/mediacontroller_api.js1387
-rwxr-xr-xsrc/mediakey/mediakey_api.js17
-rwxr-xr-xsrc/messageport/messageport_api.js475
-rwxr-xr-xsrc/messaging/messaging_api.js1644
-rw-r--r--src/networkbearerselection/networkbearerselection_api.js160
-rw-r--r--src/nfc/nfc_api.js2523
-rw-r--r--src/notification/notification_api.js1990
-rw-r--r--src/package/package_api.js421
-rw-r--r--src/playerutil/playerutil_api.js51
-rwxr-xr-xsrc/power/power_api.js261
-rw-r--r--src/ppm/ppm_api.js120
-rw-r--r--src/preference/preference_api.js235
-rw-r--r--src/push/push_api.js419
-rw-r--r--src/radio/radio_api.js288
-rw-r--r--src/secureelement/secureelement_api.js227
-rwxr-xr-xsrc/sensor/sensor_api.js771
-rw-r--r--src/sound/sound_api.js299
-rw-r--r--src/systeminfo/systeminfo_api.js1621
-rw-r--r--src/systemsetting/systemsetting_api.js26
-rw-r--r--src/time/time_api.js1240
-rw-r--r--src/tizen/tizen_api.js676
-rwxr-xr-xsrc/tvinputdevice/tvinputdevice_api.js716
-rw-r--r--src/utils/utils_api.js1738
-rwxr-xr-xsrc/voicecontrol/voicecontrol_api.js324
-rw-r--r--src/websetting/websetting_api.js100
-rw-r--r--src/widgetservice/widgetservice_api.js781
65 files changed, 26246 insertions, 23562 deletions
diff --git a/src/account/account_api.js b/src/account/account_api.js
index 3f9a31b9..db4eb6f3 100755
--- a/src/account/account_api.js
+++ b/src/account/account_api.js
@@ -13,26 +13,24 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var validator_ = xwalk.utils.validator;
var types_ = validator_.Types;
var T_ = xwalk.utils.type;
var native_ = new xwalk.utils.NativeManager(extension);
var privUtils_ = xwalk.utils;
-
function InternalValues_(data) {
if (!(this instanceof InternalValues_)) {
return new InternalValues_(data);
}
- for(var key in data) {
+ for (var key in data) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
}
}
-
function AccountProvider(data) {
var internal_ = [];
if (data) {
@@ -41,119 +39,146 @@ function AccountProvider(data) {
Object.freeze(internal_);
Object.defineProperties(this, {
- applicationId: { enumerable: true, writable: false, value: data.applicationId },
- displayName: { enumerable: true, writable: false, value: data.displayName },
- iconUri: { enumerable: true, writable: false, value: data.iconUri },
- smallIconUri: { enumerable: true, writable: false, value: data.smallIconUri },
- capabilities: { enumerable: true,
- set: function() {},
- get: function() { return internal_; }
- },
- isMultipleAccountSupported: { enumerable: true, writable: false, value: data.isMultipleAccountSupported },
+ applicationId: { enumerable: true, writable: false, value: data.applicationId },
+ displayName: { enumerable: true, writable: false, value: data.displayName },
+ iconUri: { enumerable: true, writable: false, value: data.iconUri },
+ smallIconUri: { enumerable: true, writable: false, value: data.smallIconUri },
+ capabilities: {
+ enumerable: true,
+ set: function() {},
+ get: function() {
+ return internal_;
+ }
+ },
+ isMultipleAccountSupported: {
+ enumerable: true,
+ writable: false,
+ value: data.isMultipleAccountSupported
+ }
});
}
-
function Account() {
validator_.isConstructorCall(this, tizen.Account);
var args = validator_.validateArgs(arguments, [
{ name: 'provider', type: types_.PLATFORM_OBJECT, values: AccountProvider },
- { name: 'accountInitDict', type: types_.DICTIONARY, optional: true, nullable: true }
+ {
+ name: 'accountInitDict',
+ type: types_.DICTIONARY,
+ optional: true,
+ nullable: true
+ }
]);
var _internal = { id: null };
Object.defineProperties(this, {
- id: { enumerable: true,
- set: function (value) { if (value instanceof InternalValues_) _internal.id = value.id; },
- get: function () { return _internal.id; }
+ id: {
+ enumerable: true,
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.id = value.id;
+ },
+ get: function() {
+ return _internal.id;
+ }
+ },
+ userName: {
+ enumerable: true,
+ writable: true,
+ value: args.accountInitDict ? args.accountInitDict.userName : null
+ },
+ iconUri: {
+ enumerable: true,
+ writable: true,
+ value: args.accountInitDict ? args.accountInitDict.iconUri : null
},
- userName: { enumerable: true, writable: true,
- value: (args.accountInitDict ? args.accountInitDict.userName : null) },
- iconUri: { enumerable: true, writable: true,
- value: (args.accountInitDict ? args.accountInitDict.iconUri : null) },
- provider: { enumerable: true, writable: false, value: args.provider }
+ provider: { enumerable: true, writable: false, value: args.provider }
});
}
-
Account.prototype.setExtendedData = function() {
var args = validator_.validateArgs(arguments, [
{ name: 'key', type: types_.STRING },
{ name: 'value', type: types_.STRING }
]);
- if( this.id === null ) {
- throw new WebAPIException( WebAPIException.NOT_FOUND_ERR, "Account ID was not initialized." );
+ if (this.id === null) {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Account ID was not initialized.'
+ );
}
- var result = native_.callSync('Account_setExtendedData',
- {
- accountId: this.id,
- key: args.key,
- value: args.value
- }
- );
+ var result = native_.callSync('Account_setExtendedData', {
+ accountId: this.id,
+ key: args.key,
+ value: args.value
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
};
-
Account.prototype.getExtendedData = function() {
if (T_.isFunction(arguments[0]) || arguments.length > 1) {
var args = validator_.validateArgs(arguments, [
{
- name : 'successCallback',
- type : types_.FUNCTION
+ name: 'successCallback',
+ type: types_.FUNCTION
},
{
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
- if( this.id === null ) {
- throw new WebAPIException( WebAPIException.NOT_FOUND_ERR, "Account ID was not initialized." );
+ if (this.id === null) {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Account ID was not initialized.'
+ );
}
- var result = native_.call('Account_getExtendedData', { accountId: this.id },
+ var result = native_.call(
+ 'Account_getExtendedData',
+ { accountId: this.id },
function(result) {
- if (native_.isFailure(result)) {
- if(!T_.isNullOrUndefined(args.errorCallback)) {
- args.errorCallback(native_.getErrorObject(result));
- }
- } else {
- var data = native_.getResultObject(result);
- for (var i = 0; i < data.length; ++i) {
- Object.freeze(data[i]);
+ if (native_.isFailure(result)) {
+ if (!T_.isNullOrUndefined(args.errorCallback)) {
+ args.errorCallback(native_.getErrorObject(result));
+ }
+ } else {
+ var data = native_.getResultObject(result);
+ for (var i = 0; i < data.length; ++i) {
+ Object.freeze(data[i]);
+ }
+ args.successCallback(native_.getResultObject(result));
}
- args.successCallback(native_.getResultObject(result));
- }
}
);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
} else {
var args = validator_.validateArgs(arguments, [
{ name: 'key', type: types_.STRING }
]);
- if( this.id === null ) {
- throw new WebAPIException( WebAPIException.NOT_FOUND_ERR, "Account ID was not initialized." );
+ if (this.id === null) {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Account ID was not initialized.'
+ );
}
- var result = native_.callSync('Account_getExtendedDataSync',
- {
- accountId: this.id,
- key: args.key
- }
- );
+ var result = native_.callSync('Account_getExtendedDataSync', {
+ accountId: this.id,
+ key: args.key
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
@@ -161,7 +186,6 @@ Account.prototype.getExtendedData = function() {
}
};
-
function AccountFromResult(result) {
var provider = new AccountProvider(result.provider);
var account = new Account(provider, result.accountInitDict);
@@ -169,34 +193,29 @@ function AccountFromResult(result) {
return account;
}
-
function AccountManager() {}
-
AccountManager.prototype.add = function() {
var args = validator_.validateArgs(arguments, [
{ name: 'account', type: types_.PLATFORM_OBJECT, values: Account }
]);
- var result = native_.callSync('AccountManager_add',
- {
- userName: args.account.userName,
- iconUri: args.account.iconUri,
- applicationId: args.account.provider.applicationId
- }
- );
+ var result = native_.callSync('AccountManager_add', {
+ userName: args.account.userName,
+ iconUri: args.account.iconUri,
+ applicationId: args.account.provider.applicationId
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
} else {
args.account.id = new InternalValues_({ id: native_.getResultObject(result) });
}
-}
-
+};
AccountManager.prototype.remove = function() {
var args = validator_.validateArgs(arguments, [
- { name: 'accountId', type: types_.UNSIGNED_LONG}
+ { name: 'accountId', type: types_.UNSIGNED_LONG }
]);
var result = native_.callSync('AccountManager_remove', { accountId: args.accountId });
@@ -204,37 +223,32 @@ AccountManager.prototype.remove = function() {
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
-}
-
+};
AccountManager.prototype.update = function() {
var args = validator_.validateArgs(arguments, [
{ name: 'account', type: types_.PLATFORM_OBJECT, values: Account }
]);
- var result = native_.callSync('AccountManager_update',
- {
- accountId: args.account.id,
- userName: args.account.userName,
- iconUri: args.account.iconUri
- }
- );
+ var result = native_.callSync('AccountManager_update', {
+ accountId: args.account.id,
+ userName: args.account.userName,
+ iconUri: args.account.iconUri
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
-}
-
+};
AccountManager.prototype.getAccount = function() {
var args = validator_.validateArgs(arguments, [
{ name: 'accountId', type: types_.UNSIGNED_LONG }
]);
- var result = native_.callSync(
- 'AccountManager_getAccount',
- { accountId: args.accountId }
- );
+ var result = native_.callSync('AccountManager_getAccount', {
+ accountId: args.accountId
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
@@ -247,23 +261,28 @@ AccountManager.prototype.getAccount = function() {
} else {
return null;
}
-}
-
+};
AccountManager.prototype.getAccounts = function() {
var args = validator_.validateArgs(arguments, [
- { name: 'successCallback', type: types_.FUNCTION, optional: false, nullable: false },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ },
{ name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
{ name: 'applicationId', type: types_.STRING, optional: true, nullable: true }
]);
- var result = native_.call('AccountManager_getAccounts',
+ var result = native_.call(
+ 'AccountManager_getAccounts',
{
applicationId: args.applicationId
},
function(result) {
if (native_.isFailure(result)) {
- if(!T_.isNullOrUndefined(args.errorCallback)) {
+ if (!T_.isNullOrUndefined(args.errorCallback)) {
args.errorCallback(native_.getErrorObject(result));
}
} else {
@@ -277,21 +296,19 @@ AccountManager.prototype.getAccounts = function() {
}
);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-}
-
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+};
AccountManager.prototype.getProvider = function() {
var args = validator_.validateArgs(arguments, [
{ name: 'applicationId', type: types_.STRING }
]);
- var result = native_.callSync(
- 'AccountManager_getProvider',
- { applicationId: args.applicationId }
- );
+ var result = native_.callSync('AccountManager_getProvider', {
+ applicationId: args.applicationId
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
@@ -306,21 +323,26 @@ AccountManager.prototype.getProvider = function() {
}
};
-
AccountManager.prototype.getProviders = function() {
var args = validator_.validateArgs(arguments, [
- { name: 'successCallback', type: types_.FUNCTION, optional: false, nullable: false },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ },
{ name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
{ name: 'capability', type: types_.STRING, optional: true, nullable: true }
]);
- var result = native_.call( 'AccountManager_getProviders',
+ var result = native_.call(
+ 'AccountManager_getProviders',
{
capability: args.capability
},
function(result) {
if (native_.isFailure(result)) {
- if(!T_.isNullOrUndefined(args.errorCallback)) {
+ if (!T_.isNullOrUndefined(args.errorCallback)) {
args.errorCallback(native_.getErrorObject(result));
}
} else {
@@ -335,35 +357,33 @@ AccountManager.prototype.getProviders = function() {
);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
-}
-
+};
var ACCOUNT_LISTENER = 'ACCOUNT_CHANGED';
-
function AccountListeners() {
var that = this;
- this.appCallback = function (event) {
+ this.appCallback = function(event) {
if (!T_.isEmptyObject(that.instances)) {
var param;
switch (event.action) {
- case 'onadded':
- param = AccountFromResult(native_.getResultObject(event));
- break;
+ case 'onadded':
+ param = AccountFromResult(native_.getResultObject(event));
+ break;
- case 'onremoved':
- param = native_.getResultObject(event);
- break;
+ case 'onremoved':
+ param = native_.getResultObject(event);
+ break;
- case 'onupdated':
- param = AccountFromResult(native_.getResultObject(event));
- break;
+ case 'onupdated':
+ param = AccountFromResult(native_.getResultObject(event));
+ break;
- default:
- privUtils_.log('Unknown event: ' + event.action);
- break;
+ default:
+ privUtils_.log('Unknown event: ' + event.action);
+ break;
}
var callback;
@@ -379,11 +399,9 @@ function AccountListeners() {
};
}
-
AccountListeners.prototype.instances = {};
AccountListeners.prototype.nextID = 0;
-
AccountListeners.prototype.addListener = function(callback) {
var id = ++this.nextID;
@@ -400,7 +418,6 @@ AccountListeners.prototype.addListener = function(callback) {
return id;
};
-
AccountListeners.prototype.removeListener = function(accountListenerId) {
delete this.instances[accountListenerId];
if (T_.isEmptyObject(this.instances)) {
@@ -414,19 +431,20 @@ AccountListeners.prototype.removeListener = function(accountListenerId) {
}
};
-
var _accountListeners = new AccountListeners();
-
AccountManager.prototype.addAccountListener = function() {
var args = validator_.validateArgs(arguments, [
- { name: 'callback', type: types_.LISTENER, values: ['onadded', 'onremoved', 'onupdated'] }
+ {
+ name: 'callback',
+ type: types_.LISTENER,
+ values: ['onadded', 'onremoved', 'onupdated']
+ }
]);
//checking privilege is done in C++ layer through _accountListeners.addListener()
return _accountListeners.addListener(args.callback);
-}
-
+};
AccountManager.prototype.removeAccountListener = function() {
var args = validator_.validateArgs(arguments, [
@@ -435,7 +453,7 @@ AccountManager.prototype.removeAccountListener = function() {
//checking privilege is done in C++ layer through _accountListeners.removeListener()
_accountListeners.removeListener(args.accountListenerId);
-}
+};
tizen.Account = Account;
diff --git a/src/alarm/alarm_api.js b/src/alarm/alarm_api.js
index 089f6a3f..98b4c7be 100755
--- a/src/alarm/alarm_api.js
+++ b/src/alarm/alarm_api.js
@@ -23,12 +23,12 @@ var native = new xwalk.utils.NativeManager(extension);
var isAlarmAbsolutePeriodDeprecated = true;
-var AlarmManager = function () {
+var AlarmManager = function() {
Object.defineProperties(this, {
- PERIOD_MINUTE: { value: 60, writable: false, enumerable: true},
- PERIOD_HOUR: { value: 3600, writable: false, enumerable: true},
- PERIOD_DAY: { value: 86400, writable: false, enumerable: true},
- PERIOD_WEEK: { value: 604800, writable: false, enumerable: true},
+ PERIOD_MINUTE: { value: 60, writable: false, enumerable: true },
+ PERIOD_HOUR: { value: 3600, writable: false, enumerable: true },
+ PERIOD_DAY: { value: 86400, writable: false, enumerable: true },
+ PERIOD_WEEK: { value: 604800, writable: false, enumerable: true }
});
};
@@ -51,7 +51,7 @@ function InternalData_(data) {
return new InternalData_(data);
}
- for(var key in data) {
+ for (var key in data) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
@@ -61,7 +61,7 @@ function InternalData_(data) {
function UpdateInternalData_(internal, data) {
var values = InternalData_(data);
- for(var key in data) {
+ for (var key in data) {
if (values.hasOwnProperty(key) && internal.hasOwnProperty(key)) {
internal[key] = values;
}
@@ -83,27 +83,28 @@ LogManager.prototype.disallow = function() {
var _warningLogs = new LogManager();
//class AlarmManager ////////////////////////////////////////////////////
-AlarmManager.prototype.add = function () {
+AlarmManager.prototype.add = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'alarm',
- type : AV.Types.PLATFORM_OBJECT,
- values : [tizen.AlarmRelative, tizen.AlarmAbsolute]
+ name: 'alarm',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: [tizen.AlarmRelative, tizen.AlarmAbsolute]
},
{
- name : 'applicationId',
- type : AV.Types.STRING,
+ name: 'applicationId',
+ type: AV.Types.STRING
},
{
- name : 'appControl',
- type : AV.Types.PLATFORM_OBJECT,
- values : tizen.ApplicationControl,
- optional : true,
- nullable : true
- },
+ name: 'appControl',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: tizen.ApplicationControl,
+ optional: true,
+ nullable: true
+ }
]);
- var type = null, seconds = 0;
+ var type = null,
+ seconds = 0;
if (args.alarm instanceof tizen.AlarmRelative) {
type = 'AlarmRelative';
} else if (args.alarm instanceof tizen.AlarmAbsolute) {
@@ -134,17 +135,20 @@ AlarmManager.prototype.add = function () {
AlarmManager.prototype.addAlarmNotification = function() {
var args = AV.validateMethod(arguments, [
- {
- name: 'alarm',
- type: AV.Types.PLATFORM_OBJECT,
- values: [tizen.AlarmRelative, tizen.AlarmAbsolute]
- }, {
- name: 'notification',
- type: AV.Types.PLATFORM_OBJECT,
- values: [tizen.StatusNotification, tizen.UserNotification]
- }]);
-
- var type = null, milliseconds = 0;
+ {
+ name: 'alarm',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: [tizen.AlarmRelative, tizen.AlarmAbsolute]
+ },
+ {
+ name: 'notification',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: [tizen.StatusNotification, tizen.UserNotification]
+ }
+ ]);
+
+ var type = null,
+ milliseconds = 0;
if (args.alarm instanceof tizen.AlarmRelative) {
type = 'AlarmRelative';
} else if (args.alarm instanceof tizen.AlarmAbsolute) {
@@ -160,35 +164,34 @@ AlarmManager.prototype.addAlarmNotification = function() {
callArgs.isPeriodSet = !T.isNullOrUndefined(args.alarm.period);
//add marker for UserNotification implementation
- callArgs.newImpl = (callArgs.notification instanceof tizen.UserNotification);
+ callArgs.newImpl = callArgs.notification instanceof tizen.UserNotification;
var result = native.callSync('AlarmManager_addAlarmNotification', callArgs);
if (native.isFailure(result)) {
throw native.getErrorObject(result);
- }
- else {
+ } else {
_edit.allow();
UpdateInternalData_(args.alarm, native.getResultObject(result));
_edit.disallow();
}
};
-AlarmManager.prototype.remove = function () {
+AlarmManager.prototype.remove = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'id',
- type : AV.Types.STRING,
+ name: 'id',
+ type: AV.Types.STRING
}
]);
- var result = native.callSync('AlarmManager_remove', {id: Number(args.id)});
+ var result = native.callSync('AlarmManager_remove', { id: Number(args.id) });
if (native.isFailure(result)) {
throw native.getErrorObject(result);
}
};
-AlarmManager.prototype.removeAll = function () {
+AlarmManager.prototype.removeAll = function() {
var result = native.callSync('AlarmManager_removeAll', {});
if (native.isFailure(result)) {
@@ -196,15 +199,15 @@ AlarmManager.prototype.removeAll = function () {
}
};
-AlarmManager.prototype.get = function () {
+AlarmManager.prototype.get = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'id',
- type : AV.Types.STRING,
+ name: 'id',
+ type: AV.Types.STRING
}
]);
- var result = native.callSync('AlarmManager_get', {id: Number(args.id)});
+ var result = native.callSync('AlarmManager_get', { id: Number(args.id) });
if (native.isFailure(result)) {
throw native.getErrorObject(result);
@@ -214,10 +217,20 @@ AlarmManager.prototype.get = function () {
var alarm;
_warningLogs.disallow();
if ('AlarmRelative' === result.type) {
- alarm = new tizen.AlarmRelative(result.delay, result.period, InternalData_(result));
+ alarm = new tizen.AlarmRelative(
+ result.delay,
+ result.period,
+ InternalData_(result)
+ );
} else {
- var date = new Date(result.year, result.month, result.day,
- result.hour, result.min, result.sec);
+ var date = new Date(
+ result.year,
+ result.month,
+ result.day,
+ result.hour,
+ result.min,
+ result.sec
+ );
alarm = new tizen.AlarmAbsolute(date, result.second, InternalData_(result));
}
@@ -227,46 +240,53 @@ AlarmManager.prototype.get = function () {
};
function _prepareAppControl(noti) {
- if (!noti || !noti.actions || !noti.actions.appControl) {
- privUtils_.log("Do nothing - appControl is NOT present");
- return;
- }
- if (!T.isNullOrUndefined(noti.actions.appControl.operation)) {
- noti.actions.appControl = new tizen.ApplicationControl(
- noti.actions.appControl.operation,
- noti.actions.appControl.uri,
- noti.actions.appControl.mime,
- noti.actions.appControl.category,
- noti.actions.appControl.data,
- noti.actions.appControl.launchMode);
- }
+ if (!noti || !noti.actions || !noti.actions.appControl) {
+ privUtils_.log('Do nothing - appControl is NOT present');
+ return;
+ }
+ if (!T.isNullOrUndefined(noti.actions.appControl.operation)) {
+ noti.actions.appControl = new tizen.ApplicationControl(
+ noti.actions.appControl.operation,
+ noti.actions.appControl.uri,
+ noti.actions.appControl.mime,
+ noti.actions.appControl.category,
+ noti.actions.appControl.data,
+ noti.actions.appControl.launchMode
+ );
+ }
}
function _prepareDetailInfo(noti) {
- if (!noti || !noti.textContents || !noti.textContents.detailInfo) {
- console.log("Do nothing - detailInfo is NOT present");
- return;
- }
- var detailInfo = noti.textContents.detailInfo;
- if (T.isArray(detailInfo)) {
- var _d = [];
- for (var i = 0; i < detailInfo.length; ++i) {
- _d.push(new tizen.NotificationDetailInfo(detailInfo[i].mainText,
- detailInfo[i].subText || null));
+ if (!noti || !noti.textContents || !noti.textContents.detailInfo) {
+ console.log('Do nothing - detailInfo is NOT present');
+ return;
+ }
+ var detailInfo = noti.textContents.detailInfo;
+ if (T.isArray(detailInfo)) {
+ var _d = [];
+ for (var i = 0; i < detailInfo.length; ++i) {
+ _d.push(
+ new tizen.NotificationDetailInfo(
+ detailInfo[i].mainText,
+ detailInfo[i].subText || null
+ )
+ );
+ }
+ noti.textContents.detailInfo = _d;
}
- noti.textContents.detailInfo = _d;
- }
}
-AlarmManager.prototype.getAlarmNotification = function () {
+AlarmManager.prototype.getAlarmNotification = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'id',
- type : AV.Types.STRING,
+ name: 'id',
+ type: AV.Types.STRING
}
]);
- var result = native.callSync('AlarmManager_getAlarmNotification', {id: Number(args.id)});
+ var result = native.callSync('AlarmManager_getAlarmNotification', {
+ id: Number(args.id)
+ });
if (native.isFailure(result)) {
throw native.getErrorObject(result);
@@ -278,7 +298,7 @@ AlarmManager.prototype.getAlarmNotification = function () {
}
};
-AlarmManager.prototype.getAll = function () {
+AlarmManager.prototype.getAll = function() {
var result = native.callSync('AlarmManager_getAll', {});
if (native.isFailure(result)) {
@@ -287,12 +307,11 @@ AlarmManager.prototype.getAll = function () {
var data = native.getResultObject(result);
var md = [];
_warningLogs.disallow();
- data.forEach(function (i) {
- if ('AlarmRelative'=== i.type) {
+ data.forEach(function(i) {
+ if ('AlarmRelative' === i.type) {
md.push(new tizen.AlarmRelative(i.delay, i.period, InternalData_(i)));
} else {
- var date = new Date(i.year, i.month, i.day,
- i.hour, i.min, i.sec);
+ var date = new Date(i.year, i.month, i.day, i.hour, i.min, i.sec);
md.push(new tizen.AlarmAbsolute(date, i.second, InternalData_(i)));
}
});
@@ -310,13 +329,15 @@ function Alarm(id) {
}
var _internal = {
- 'id' : m_id
+ id: m_id
};
Object.defineProperties(this, {
id: {
- get: function () {return _internal.id;},
- set: function (value) {
+ get: function() {
+ return _internal.id;
+ },
+ set: function(value) {
if (value instanceof InternalData_) {
_internal.id = value.id;
}
@@ -335,7 +356,7 @@ tizen.AlarmRelative = function(delay, period, internal) {
var m_delay = Converter.toLong(delay);
if (arguments.length >= 2) {
- if(!T.isNullOrUndefined(period)){
+ if (!T.isNullOrUndefined(period)) {
m_period = Converter.toLong(period, true);
}
}
@@ -372,8 +393,10 @@ tizen.AlarmRelative.prototype = new Alarm();
tizen.AlarmRelative.prototype.constructor = tizen.AlarmRelative;
-tizen.AlarmRelative.prototype.getRemainingSeconds = function () {
- var result = native.callSync('AlarmRelative_getRemainingSeconds', {id: Number(this.id)});
+tizen.AlarmRelative.prototype.getRemainingSeconds = function() {
+ var result = native.callSync('AlarmRelative_getRemainingSeconds', {
+ id: Number(this.id)
+ });
if (native.isFailure(result)) {
throw native.getErrorObject(result);
@@ -408,19 +431,24 @@ function makeDateConst(obj) {
tizen.AlarmAbsolute = function(date, second, internal) {
AV.validateConstructorCall(this, tizen.AlarmAbsolute);
- var m_period = null, m_daysOfWeek = [], m_date;
+ var m_period = null,
+ m_daysOfWeek = [],
+ m_date;
if (T.isDate(date)) {
m_date = date;
if (arguments.length >= 2) {
- if(T.isArray(second)){
+ if (T.isArray(second)) {
m_daysOfWeek = second;
} else {
- if(!T.isNullOrUndefined(second)){
+ if (!T.isNullOrUndefined(second)) {
m_period = Converter.toLong(second);
- if(_warningLogs.enableLog && isAlarmAbsolutePeriodDeprecated){
- privUtils_.warn("This Constructor is deprecated since Tizen 4.0." +
- " Please consider using other constructors or other type of an alarm.");
+ if (_warningLogs.enableLog && isAlarmAbsolutePeriodDeprecated) {
+ privUtils_.warn(
+ 'This Constructor is deprecated since Tizen 4.0.' +
+ ' Please consider using other constructors or other ' +
+ 'type of an alarm.'
+ );
}
}
}
@@ -445,16 +473,22 @@ tizen.AlarmAbsolute = function(date, second, internal) {
},
period: {
get: function() {
- if(_warningLogs.enableLog && isAlarmAbsolutePeriodDeprecated){
- privUtils_.warn('Since Tizen 4.0 constructor AlarmAbsolute(Date date, long period) ' +
- 'is deprecated, thus period attribute should not be used.');
+ if (_warningLogs.enableLog && isAlarmAbsolutePeriodDeprecated) {
+ privUtils_.warn(
+ 'Since Tizen 4.0 constructor AlarmAbsolute(Date date, ' +
+ 'long period) is deprecated, thus period attribute ' +
+ 'should not be used.'
+ );
}
return m_period;
},
set: function(v) {
- if(_warningLogs.enableLog && isAlarmAbsolutePeriodDeprecated){
- privUtils_.warn('Since Tizen 4.0 constructor AlarmAbsolute(Date date, long period) ' +
- 'is deprecated, thus period attribute should not be used.');
+ if (_warningLogs.enableLog && isAlarmAbsolutePeriodDeprecated) {
+ privUtils_.warn(
+ 'Since Tizen 4.0 constructor AlarmAbsolute(Date date, ' +
+ 'long period) is deprecated, thus period attribute ' +
+ 'should not be used.'
+ );
}
if (_edit.canEdit && v) {
@@ -481,8 +515,10 @@ tizen.AlarmAbsolute.prototype = new Alarm();
tizen.AlarmAbsolute.prototype.constructor = tizen.AlarmAbsolute;
-tizen.AlarmAbsolute.prototype.getNextScheduledDate = function () {
- var result = native.callSync('AlarmAbsolute_getNextScheduledDate', {id: Number(this.id)});
+tizen.AlarmAbsolute.prototype.getNextScheduledDate = function() {
+ var result = native.callSync('AlarmAbsolute_getNextScheduledDate', {
+ id: Number(this.id)
+ });
if (native.isFailure(result)) {
throw native.getErrorObject(result);
@@ -501,19 +537,19 @@ tizen.AlarmAbsolute.prototype.getNextScheduledDate = function () {
var ProfileAlarm = (function() {
var m_profile = null;
function ProfileAlarm() {
- if (m_profile == null) {
- m_profile = privUtils_.checkProfile();
- }
- Object.defineProperties(this, {
- profile: {
- get: function() {
- return m_profile;
- },
- set: function() {},
- enumerable: true
- }
- })
- };
+ if (m_profile == null) {
+ m_profile = privUtils_.checkProfile();
+ }
+ Object.defineProperties(this, {
+ profile: {
+ get: function() {
+ return m_profile;
+ },
+ set: function() {},
+ enumerable: true
+ }
+ });
+ }
var instance;
return {
@@ -525,7 +561,7 @@ var ProfileAlarm = (function() {
}
return instance;
}
- };
+ };
})();
var _profile = ProfileAlarm.getInstance().profile;
diff --git a/src/application/application_api.js b/src/application/application_api.js
index 3b53fc11..8855b06b 100755
--- a/src/application/application_api.js
+++ b/src/application/application_api.js
@@ -22,13 +22,13 @@ var privUtils_ = xwalk.utils;
var native = new xwalk.utils.NativeManager(extension);
var ApplicationControlLaunchMode = {
- SINGLE: 'SINGLE',
- GROUP: 'GROUP'
+ SINGLE: 'SINGLE',
+ GROUP: 'GROUP'
};
var ApplicationUsageMode = {
- RECENTLY: 'RECENTLY',
- FREQUENTLY: 'FREQUENTLY'
+ RECENTLY: 'RECENTLY',
+ FREQUENTLY: 'FREQUENTLY'
};
// TODO: Please uncomment below lines when system events is ready
@@ -64,1364 +64,1416 @@ var ApplicationUsageMode = {
// helper functions ////////////////////////////////////////////////////
function _createApplicationControlData(object) {
- var ret;
- if (!T.isNullOrUndefined(object)) {
- ret = new tizen.ApplicationControlData(object.key, object.value);
- }
- return ret;
+ var ret;
+ if (!T.isNullOrUndefined(object)) {
+ ret = new tizen.ApplicationControlData(object.key, object.value);
+ }
+ return ret;
}
function _createApplicationControlDataArray(object) {
- var ret = [];
- if (!T.isNullOrUndefined(object) && T.isArray(object)) {
- object.forEach(function (o) {
- var data = _createApplicationControlData(o);
- if (!T.isNullOrUndefined(data)) {
- ret.push(data);
- }
- });
- }
- return ret;
+ var ret = [];
+ if (!T.isNullOrUndefined(object) && T.isArray(object)) {
+ object.forEach(function(o) {
+ var data = _createApplicationControlData(o);
+ if (!T.isNullOrUndefined(data)) {
+ ret.push(data);
+ }
+ });
+ }
+ return ret;
}
function _createApplicationControl(object) {
- var ret;
- if (!T.isNullOrUndefined(object)) {
- ret = new tizen.ApplicationControl(object.operation,
- object.uri,
- object.mime,
- object.category,
- _createApplicationControlDataArray(object.data));
- }
- return ret;
+ var ret;
+ if (!T.isNullOrUndefined(object)) {
+ ret = new tizen.ApplicationControl(
+ object.operation,
+ object.uri,
+ object.mime,
+ object.category,
+ _createApplicationControlDataArray(object.data)
+ );
+ }
+ return ret;
}
function _createApplicationInformationArray(object) {
- var ret = [];
- if (!T.isNullOrUndefined(object) && T.isArray(object)) {
- object.forEach(function (o) {
- var data = new ApplicationInformation(o);
- if (!T.isNullOrUndefined(data)) {
- ret.push(data);
- }
- });
- }
- return ret;
+ var ret = [];
+ if (!T.isNullOrUndefined(object) && T.isArray(object)) {
+ object.forEach(function(o) {
+ var data = new ApplicationInformation(o);
+ if (!T.isNullOrUndefined(data)) {
+ ret.push(data);
+ }
+ });
+ }
+ return ret;
}
// class ApplicationManager ////////////////////////////////////////////////////
-var ApplicationManager = function() {
-};
+var ApplicationManager = function() {};
ApplicationManager.prototype.getCurrentApplication = function() {
- var result = native.callSync('ApplicationManager_getCurrentApplication', {});
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- return new Application(native.getResultObject(result));
- }
-};
+ var result = native.callSync('ApplicationManager_getCurrentApplication', {});
-ApplicationManager.prototype.kill = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'contextId',
- type : AV.Types.STRING
- },
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
-
- var callback = function(result) {
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ throw native.getErrorObject(result);
} else {
- native.callIfPossible(args.successCallback);
+ return new Application(native.getResultObject(result));
}
- };
+};
- var result = native.call('ApplicationManager_kill', {contextId: args.contextId}, callback);
+ApplicationManager.prototype.kill = function() {
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'contextId',
+ type: AV.Types.STRING
+ },
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
-};
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ };
+
+ var result = native.call(
+ 'ApplicationManager_kill',
+ { contextId: args.contextId },
+ callback
+ );
-ApplicationManager.prototype.launch = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'id',
- type : AV.Types.STRING
- },
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
-
- var callback = function(result) {
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- native.callIfPossible(args.successCallback);
+ throw native.getErrorObject(result);
}
- };
+};
+
+ApplicationManager.prototype.launch = function() {
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'id',
+ type: AV.Types.STRING
+ },
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ };
- var result = native.call('ApplicationManager_launch', {id: args.id}, callback);
+ var result = native.call('ApplicationManager_launch', { id: args.id }, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
ApplicationManager.prototype.launchAppControl = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'appControl',
- type : AV.Types.PLATFORM_OBJECT,
- values : tizen.ApplicationControl
- },
- {
- name : 'id',
- type : AV.Types.STRING,
- optional : true,
- nullable : true
- },
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- },
- {
- name : 'replyCallback',
- type : AV.Types.LISTENER,
- values : ['onsuccess', 'onfailure'],
- optional : true,
- nullable : true
- }
- ]);
-
- var replyCallbackId = 'ApplicationControlDataArrayReplyCallback_' + new Date().valueOf();
- var registeredReplyCallback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.replyCallback.onfailure);
- } else {
- native.callIfPossible(args.replyCallback.onsuccess,
- _createApplicationControlDataArray(result.data));
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'appControl',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: tizen.ApplicationControl
+ },
+ {
+ name: 'id',
+ type: AV.Types.STRING,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'replyCallback',
+ type: AV.Types.LISTENER,
+ values: ['onsuccess', 'onfailure'],
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var replyCallbackId =
+ 'ApplicationControlDataArrayReplyCallback_' + new Date().valueOf();
+ var registeredReplyCallback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.replyCallback.onfailure);
+ } else {
+ native.callIfPossible(
+ args.replyCallback.onsuccess,
+ _createApplicationControlDataArray(result.data)
+ );
+ }
+ native.removeListener(replyCallbackId, registeredReplyCallback);
+ };
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ native.removeListener(replyCallbackId, registeredReplyCallback);
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ };
+
+ var callArgs = {};
+ callArgs.appControl = args.appControl;
+ if (args.has.id) {
+ callArgs.id = args.id;
}
- native.removeListener(replyCallbackId, registeredReplyCallback);
- };
+ if (args.has.replyCallback && args.replyCallback) {
+ callArgs.replyCallback = replyCallbackId;
+ native.addListener(replyCallbackId, registeredReplyCallback);
+ }
+
+ var result = native.call('ApplicationManager_launchAppControl', callArgs, callback);
- var callback = function(result) {
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- native.removeListener(replyCallbackId, registeredReplyCallback);
- } else {
- native.callIfPossible(args.successCallback);
+ throw native.getErrorObject(result);
}
- };
+};
- var callArgs = {};
- callArgs.appControl = args.appControl;
- if (args.has.id) {
- callArgs.id = args.id;
- }
- if (args.has.replyCallback && args.replyCallback) {
- callArgs.replyCallback = replyCallbackId;
- native.addListener(replyCallbackId, registeredReplyCallback);
- }
+ApplicationManager.prototype.findAppControl = function() {
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'appControl',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: tizen.ApplicationControl
+ },
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var result = native.call('ApplicationManager_launchAppControl', callArgs, callback);
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var r = native.getResultObject(result);
+ args.successCallback(
+ _createApplicationInformationArray(r.informationArray),
+ _createApplicationControl(r.appControl)
+ );
+ }
+ };
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
-};
+ var callArgs = { appControl: args.appControl };
+ var result = native.call('ApplicationManager_findAppControl', callArgs, callback);
-ApplicationManager.prototype.findAppControl = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'appControl',
- type : AV.Types.PLATFORM_OBJECT,
- values : tizen.ApplicationControl
- },
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
-
- var callback = function(result) {
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var r = native.getResultObject(result);
- args.successCallback(_createApplicationInformationArray(r.informationArray),
- _createApplicationControl(r.appControl));
+ throw native.getErrorObject(result);
}
- };
-
- var callArgs = {appControl: args.appControl};
- var result = native.call('ApplicationManager_findAppControl', callArgs, callback);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
};
ApplicationManager.prototype.getAppsContext = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
-
- var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var contexts = native.getResultObject(result).contexts;
- var c = [];
- contexts.forEach(function (i) {
- c.push(new ApplicationContext(i));
- });
- args.successCallback(c);
- }
- };
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var contexts = native.getResultObject(result).contexts;
+ var c = [];
+ contexts.forEach(function(i) {
+ c.push(new ApplicationContext(i));
+ });
+ args.successCallback(c);
+ }
+ };
- var result = native.call('ApplicationManager_getAppsContext', {}, callback);
+ var result = native.call('ApplicationManager_getAppsContext', {}, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
ApplicationManager.prototype.getAppContext = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'contextId',
- type : AV.Types.STRING,
- optional : true,
- nullable : true
- }
- ]);
-
- var callArgs = {};
-
- if (args.has.contextId) {
- callArgs.contextId = args.contextId;
- }
-
- var result = native.callSync('ApplicationManager_getAppContext', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- return new ApplicationContext(native.getResultObject(result));
- }
-};
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'contextId',
+ type: AV.Types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+
+ if (args.has.contextId) {
+ callArgs.contextId = args.contextId;
+ }
+
+ var result = native.callSync('ApplicationManager_getAppContext', callArgs);
-ApplicationManager.prototype.getAppsInfo = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
-
- var callback = function(result) {
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ throw native.getErrorObject(result);
} else {
- args.successCallback(_createApplicationInformationArray(
- native.getResultObject(result).informationArray)
- );
+ return new ApplicationContext(native.getResultObject(result));
}
- };
+};
+
+ApplicationManager.prototype.getAppsInfo = function() {
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ args.successCallback(
+ _createApplicationInformationArray(
+ native.getResultObject(result).informationArray
+ )
+ );
+ }
+ };
- var result = native.call('ApplicationManager_getAppsInfo', {}, callback);
+ var result = native.call('ApplicationManager_getAppsInfo', {}, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
ApplicationManager.prototype.getAppInfo = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'id',
- type : AV.Types.STRING,
- optional : true,
- nullable : true
- }
- ]);
-
- var callArgs = {};
-
- if (args.has.id) {
- callArgs.id = args.id;
- }
-
- var result = native.callSync('ApplicationManager_getAppInfo', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- return new ApplicationInformation(native.getResultObject(result));
- }
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'id',
+ type: AV.Types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+
+ if (args.has.id) {
+ callArgs.id = args.id;
+ }
+
+ var result = native.callSync('ApplicationManager_getAppInfo', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ return new ApplicationInformation(native.getResultObject(result));
+ }
};
ApplicationManager.prototype.getAppCerts = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'id',
- type : AV.Types.STRING,
- optional : true,
- nullable : true
- }
- ]);
-
- var callArgs = {};
-
- if (args.has.id) {
- callArgs.id = args.id;
- }
-
- var result = native.callSync('ApplicationManager_getAppCerts', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var certificates = native.getResultObject(result);
- var c = [];
- certificates.forEach(function (i) {
- c.push(new ApplicationCertificate(i));
- });
- return c;
- }
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'id',
+ type: AV.Types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+
+ if (args.has.id) {
+ callArgs.id = args.id;
+ }
+
+ var result = native.callSync('ApplicationManager_getAppCerts', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var certificates = native.getResultObject(result);
+ var c = [];
+ certificates.forEach(function(i) {
+ c.push(new ApplicationCertificate(i));
+ });
+ return c;
+ }
};
ApplicationManager.prototype.getAppSharedURI = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'id',
- type : AV.Types.STRING,
- optional : true,
- nullable : true
- }
- ]);
-
- var callArgs = {};
-
- if (args.has.id) {
- callArgs.id = args.id;
- }
-
- var result = native.callSync('ApplicationManager_getAppSharedURI', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- return native.getResultObject(result);
- }
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'id',
+ type: AV.Types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+
+ if (args.has.id) {
+ callArgs.id = args.id;
+ }
+
+ var result = native.callSync('ApplicationManager_getAppSharedURI', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ return native.getResultObject(result);
+ }
};
ApplicationManager.prototype.getAppMetaData = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'id',
- type : AV.Types.STRING,
- optional : true,
- nullable : true
- }
- ]);
-
- var callArgs = {};
-
- if (args.has.id) {
- callArgs.id = args.id;
- }
-
- var result = native.callSync('ApplicationManager_getAppMetaData', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var metaData = native.getResultObject(result);
- var md = [];
- metaData.forEach(function (i) {
- md.push(new ApplicationMetaData(i));
- });
- return md;
- }
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'id',
+ type: AV.Types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+
+ if (args.has.id) {
+ callArgs.id = args.id;
+ }
+
+ var result = native.callSync('ApplicationManager_getAppMetaData', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var metaData = native.getResultObject(result);
+ var md = [];
+ metaData.forEach(function(i) {
+ md.push(new ApplicationMetaData(i));
+ });
+ return md;
+ }
};
ApplicationManager.prototype.getBatteryUsageInfo = function() {
- var args = AV.validateMethod(arguments, [
- {
- name: 'successCallback',
- type: AV.Types.FUNCTION
- },
- {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'days',
- type: AV.Types.LONG,
- optional: true,
- nullable: true
- },
- {
- name: 'limit',
- type: AV.Types.LONG,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = {};
-
- if (!T.isNullOrUndefined(args.days)) {
- callArgs.days = args.days;
- }
-
- if (!T.isNullOrUndefined(args.limit)) {
- callArgs.limit = args.limit;
- }
-
- var callback = function(result) {
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'days',
+ type: AV.Types.LONG,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'limit',
+ type: AV.Types.LONG,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+
+ if (!T.isNullOrUndefined(args.days)) {
+ callArgs.days = args.days;
+ }
+
+ if (!T.isNullOrUndefined(args.limit)) {
+ callArgs.limit = args.limit;
+ }
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var resultArray = [];
+ data.forEach(function(i) {
+ resultArray.push(new ApplicationBatteryUsage(i));
+ });
+ args.successCallback(resultArray);
+ }
+ };
+
+ var result = native.call(
+ 'ApplicationManager_getBatteryUsageInfo',
+ callArgs,
+ callback
+ );
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var resultArray = [];
- data.forEach(function (i) {
- resultArray.push(new ApplicationBatteryUsage(i));
- });
- args.successCallback(resultArray);
- }
- };
-
- var result = native.call('ApplicationManager_getBatteryUsageInfo', callArgs, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ throw native.getErrorObject(result);
+ }
};
ApplicationManager.prototype.getAppsUsageInfo = function() {
- var args = AV.validateMethod(arguments, [
- {
- name: 'successCallback',
- type: AV.Types.FUNCTION
- },
- {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'mode',
- type: AV.Types.ENUM,
- values: T.getValues(ApplicationUsageMode),
- optional: true,
- nullable: true
- },
- {
- name: 'filter',
- type: AV.Types.DICTIONARY,
- optional: true,
- nullable: true
- },
- {
- name: 'limit',
- type: AV.Types.LONG,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = {};
-
- if (!T.isNullOrUndefined(args.mode)) {
- callArgs.mode = args.mode;
- }
-
- if (!T.isNullOrUndefined(args.filter) && typeof args.filter !== 'object') {
- setTimeout(function() {
- native.callIfPossible(args.errorCallback,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'filter must be an object.'));
- }, 0);
- return;
- }
-
- callArgs.filter = {};
- if (!T.isNullOrUndefined(args.filter)) {
- var filter = args.filter;
- if (!T.isNullOrUndefined(filter.timeSpan)) {
- callArgs.filter.timeSpan = Converter.toLong(filter.timeSpan);
- } else {
- if (!T.isNullOrUndefined(filter.startTime)) {
- if (filter.startTime instanceof Date) {
- callArgs.filter.startTime = filter.startTime.getTime() / 1000;
- } else {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'startTime given with invalid type.');
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'mode',
+ type: AV.Types.ENUM,
+ values: T.getValues(ApplicationUsageMode),
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'filter',
+ type: AV.Types.DICTIONARY,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'limit',
+ type: AV.Types.LONG,
+ optional: true,
+ nullable: true
}
- }
+ ]);
- if (!T.isNullOrUndefined(filter.endTime)) {
- if (filter.endTime instanceof Date) {
- callArgs.filter.endTime = filter.endTime.getTime() / 1000;
+ var callArgs = {};
+
+ if (!T.isNullOrUndefined(args.mode)) {
+ callArgs.mode = args.mode;
+ }
+
+ if (!T.isNullOrUndefined(args.filter) && typeof args.filter !== 'object') {
+ setTimeout(function() {
+ native.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'filter must be an object.'
+ )
+ );
+ }, 0);
+ return;
+ }
+
+ callArgs.filter = {};
+ if (!T.isNullOrUndefined(args.filter)) {
+ var filter = args.filter;
+ if (!T.isNullOrUndefined(filter.timeSpan)) {
+ callArgs.filter.timeSpan = Converter.toLong(filter.timeSpan);
} else {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'endTime given with invalid type.');
+ if (!T.isNullOrUndefined(filter.startTime)) {
+ if (filter.startTime instanceof Date) {
+ callArgs.filter.startTime = filter.startTime.getTime() / 1000;
+ } else {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'startTime given with invalid type.'
+ );
+ }
+ }
+
+ if (!T.isNullOrUndefined(filter.endTime)) {
+ if (filter.endTime instanceof Date) {
+ callArgs.filter.endTime = filter.endTime.getTime() / 1000;
+ } else {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'endTime given with invalid type.'
+ );
+ }
+ }
}
- }
}
- }
- if (!T.isNullOrUndefined(args.limit)) {
- callArgs.limit = args.limit;
- }
+ if (!T.isNullOrUndefined(args.limit)) {
+ callArgs.limit = args.limit;
+ }
- var callback = function(result) {
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var resultArray = [];
+ data.forEach(function(i) {
+ resultArray.push(new ApplicationUsage(i));
+ });
+ args.successCallback(resultArray);
+ }
+ };
+
+ var result = native.call('ApplicationManager_getAppsUsageInfo', callArgs, callback);
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var resultArray = [];
- data.forEach(function(i) {
- resultArray.push(new ApplicationUsage(i));
- });
- args.successCallback(resultArray);
- }
- };
-
- var result = native.call('ApplicationManager_getAppsUsageInfo', callArgs, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ throw native.getErrorObject(result);
+ }
};
function ListenerManager(native, listenerName) {
- this.listeners = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
-};
+ this.listeners = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
+}
ListenerManager.prototype.onListenerCalled = function(msg) {
- var d = null;
+ var d = null;
- switch (msg.action) {
- case 'oninstalled':
- case 'onupdated':
- d = new ApplicationInformation(msg.data);
- break;
+ switch (msg.action) {
+ case 'oninstalled':
+ case 'onupdated':
+ d = new ApplicationInformation(msg.data);
+ break;
- case 'onuninstalled':
- d = msg.data;
- break;
+ case 'onuninstalled':
+ d = msg.data;
+ break;
- default:
- privUtils_.log('Unknown mode: ' + msg.action);
- return;
- }
+ default:
+ privUtils_.log('Unknown mode: ' + msg.action);
+ return;
+ }
- for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId) && this.listeners[watchId][msg.action]) {
- this.listeners[watchId][msg.action](d);
+ for (var watchId in this.listeners) {
+ if (
+ this.listeners.hasOwnProperty(watchId) &&
+ this.listeners[watchId][msg.action]
+ ) {
+ this.listeners[watchId][msg.action](d);
+ }
}
- }
};
ListenerManager.prototype.addListener = function(callback) {
- privUtils_.log('ListenerManager.prototype.addListener');
- var id = this.nextId;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- var result = this.native.callSync('ApplicationManager_addAppInfoEventListener');
- if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
+ privUtils_.log('ListenerManager.prototype.addListener');
+ var id = this.nextId;
+ if (!this.nativeSet) {
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ var result = this.native.callSync('ApplicationManager_addAppInfoEventListener');
+ if (this.native.isFailure(result)) {
+ throw this.native.getErrorObject(result);
+ }
+ this.nativeSet = true;
}
- this.nativeSet = true;
- }
- this.listeners[id] = callback;
- ++this.nextId;
+ this.listeners[id] = callback;
+ ++this.nextId;
- return id;
+ return id;
};
ListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- } else {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Specified listener does not exist');
- }
-
- if (this.nativeSet && T.isEmptyObject(this.listeners)) {
- this.native.callSync('ApplicationManager_removeAppInfoEventListener');
- this.native.removeListener(this.listenerName);
- this.nativeSet = false;
- }
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ } else {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Specified listener does not exist'
+ );
+ }
+
+ if (this.nativeSet && T.isEmptyObject(this.listeners)) {
+ this.native.callSync('ApplicationManager_removeAppInfoEventListener');
+ this.native.removeListener(this.listenerName);
+ this.nativeSet = false;
+ }
};
var APPLICATION_EVENT_LISTENER = 'ApplicationEventListener';
var applicationEventListener = new ListenerManager(native, APPLICATION_EVENT_LISTENER);
ApplicationManager.prototype.addAppInfoEventListener = function() {
- privUtils_.warn('DEPRECATION WARNING: addAppInfoEventListener() is deprecated and will be removed from next release. '
- + 'Use tizen.package.setPackageInfoEventListener() instead.');
-
- var args = AV.validateMethod(arguments, [
- {
- name : 'eventCallback',
- type : AV.Types.LISTENER,
- values : ['oninstalled', 'onupdated', 'onuninstalled']
- }
- ]);
-
- return applicationEventListener.addListener(args.eventCallback);
+ privUtils_.warn(
+ 'DEPRECATION WARNING: addAppInfoEventListener() is deprecated and will ' +
+ 'be removed from next release. ' +
+ 'Use tizen.package.setPackageInfoEventListener() instead.'
+ );
+
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'eventCallback',
+ type: AV.Types.LISTENER,
+ values: ['oninstalled', 'onupdated', 'onuninstalled']
+ }
+ ]);
+
+ return applicationEventListener.addListener(args.eventCallback);
};
ApplicationManager.prototype.removeAppInfoEventListener = function() {
- privUtils_.warn('DEPRECATION WARNING: removeAppInfoEventListener() is deprecated and will be removed from next release. '
- + 'Use tizen.package.unsetPackageInfoEventListener() instead.');
-
- var args = AV.validateMethod(arguments, [
- {
- name : 'watchId',
- type : AV.Types.LONG
- }
- ]);
+ privUtils_.warn(
+ 'DEPRECATION WARNING: removeAppInfoEventListener() is deprecated and will ' +
+ 'be removed from next release. ' +
+ 'Use tizen.package.unsetPackageInfoEventListener() instead.'
+ );
+
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'watchId',
+ type: AV.Types.LONG
+ }
+ ]);
- applicationEventListener.removeListener(args.watchId);
+ applicationEventListener.removeListener(args.watchId);
};
function StatusListenerManager(native, listenerName) {
- this.listeners = {};
- this.listenersCount = 0;
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
-};
+ this.listeners = {};
+ this.listenersCount = 0;
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
+}
StatusListenerManager.prototype.onListenerCalled = function(msg) {
- var statusType = msg.statusType;
- var app_id = msg.appId;
-
- for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId)) {
- var listener = this.listeners[watchId];
- if (!listener.appId || listener.appId === app_id) {
- listener.callback(app_id, statusType);
- }
+ var statusType = msg.statusType;
+ var app_id = msg.appId;
+
+ for (var watchId in this.listeners) {
+ if (this.listeners.hasOwnProperty(watchId)) {
+ var listener = this.listeners[watchId];
+ if (!listener.appId || listener.appId === app_id) {
+ listener.callback(app_id, statusType);
+ }
+ }
}
- }
};
StatusListenerManager.prototype.addListener = function(callback, appId) {
- if (!this.nativeSet) {
- var result = this.native.callSync('ApplicationManager_addAppStatusChangeListener');
- if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
- }
+ if (!this.nativeSet) {
+ var result = this.native.callSync(
+ 'ApplicationManager_addAppStatusChangeListener'
+ );
+ if (this.native.isFailure(result)) {
+ throw this.native.getErrorObject(result);
+ }
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- this.nativeSet = true;
- }
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ this.nativeSet = true;
+ }
- var listener = {
- 'callback' : callback,
- 'appId' : appId
- };
+ var listener = {
+ callback: callback,
+ appId: appId
+ };
- var id = this.nextId++;
- this.listeners[id] = listener;
- this.listenersCount++;
+ var id = this.nextId++;
+ this.listeners[id] = listener;
+ this.listenersCount++;
- return id;
+ return id;
};
StatusListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- if (this.listenersCount > 1) {
- delete this.listeners[watchId];
- this.listenersCount--;
- return;
- }
+ if (this.listeners.hasOwnProperty(watchId)) {
+ if (this.listenersCount > 1) {
+ delete this.listeners[watchId];
+ this.listenersCount--;
+ return;
+ }
- if (this.nativeSet) {
- var result = this.native.callSync('ApplicationManager_removeStatusChangeListener');
- if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
- }
+ if (this.nativeSet) {
+ var result = this.native.callSync(
+ 'ApplicationManager_removeStatusChangeListener'
+ );
+ if (this.native.isFailure(result)) {
+ throw this.native.getErrorObject(result);
+ }
- delete this.listeners[watchId];
- this.listenersCount--;
+ delete this.listeners[watchId];
+ this.listenersCount--;
- this.native.removeListener(this.listenerName);
- this.nativeSet = false;
+ this.native.removeListener(this.listenerName);
+ this.nativeSet = false;
+ }
}
- }
};
var APP_STATUS_CHANGE_LISTENER = 'AppStatusChangeListener';
-var appStatusChangeListener = new StatusListenerManager(native, APP_STATUS_CHANGE_LISTENER);
+var appStatusChangeListener = new StatusListenerManager(
+ native,
+ APP_STATUS_CHANGE_LISTENER
+);
ApplicationManager.prototype.addAppStatusChangeListener = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'statusChangeListener',
- type : AV.Types.FUNCTION,
- },
- {
- name : 'appId',
- type : AV.Types.STRING,
- optional : true,
- nullable : true
- }
- ]);
-
- if (args.appId !== undefined && args.appId !== null && !args.appId.length) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Application id is empty');
- }
-
- return appStatusChangeListener.addListener(args.statusChangeListener, args.appId);
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'statusChangeListener',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'appId',
+ type: AV.Types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (args.appId !== undefined && args.appId !== null && !args.appId.length) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Application id is empty'
+ );
+ }
+
+ return appStatusChangeListener.addListener(args.statusChangeListener, args.appId);
};
ApplicationManager.prototype.removeAppStatusChangeListener = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'watchId',
- type : AV.Types.LONG
- }
- ]);
-
- appStatusChangeListener.removeListener(args.watchId);
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'watchId',
+ type: AV.Types.LONG
+ }
+ ]);
+
+ appStatusChangeListener.removeListener(args.watchId);
};
// class Application ////////////////////////////////////////////////////
function Application(data) {
- Object.defineProperties(this, {
- appInfo : {
- value : new ApplicationInformation(data.appInfo),
- writable : false,
- enumerable : true
- },
- contextId : {
- value : Converter.toString(data.contextId),
- writable : false,
- enumerable : true
- }
- });
+ Object.defineProperties(this, {
+ appInfo: {
+ value: new ApplicationInformation(data.appInfo),
+ writable: false,
+ enumerable: true
+ },
+ contextId: {
+ value: Converter.toString(data.contextId),
+ writable: false,
+ enumerable: true
+ }
+ });
}
Application.prototype.exit = function() {
- native.sendRuntimeMessage('tizen://exit');
+ native.sendRuntimeMessage('tizen://exit');
};
Application.prototype.hide = function() {
- native.sendRuntimeMessage('tizen://hide');
+ native.sendRuntimeMessage('tizen://hide');
};
Application.prototype.getRequestedAppControl = function() {
- var result = native.callSync('Application_getRequestedAppControl', {});
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- result = native.getResultObject(result);
- if (result) {
- return new RequestedApplicationControl(result);
+ var result = native.callSync('Application_getRequestedAppControl', {});
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
} else {
- return null;
+ result = native.getResultObject(result);
+ if (result) {
+ return new RequestedApplicationControl(result);
+ } else {
+ return null;
+ }
}
- }
};
function _checkEventName(name) {
- var name = name || '';
- if (!(/^([a-zA-Z_]){1}([a-zA-Z0-9_]){0,126}$/.test(name))) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid event name');
- }
+ var name = name || '';
+ if (!/^([a-zA-Z_]){1}([a-zA-Z0-9_]){0,126}$/.test(name)) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid event name'
+ );
+ }
}
function _checkAppId(appId) {
- if (!(/^([a-zA-Z0-9]){10}([.]){1}([a-zA-Z0-9_]){1,52}$/.test(appId))) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid appId');
- }
+ if (!/^([a-zA-Z0-9]){10}([.]){1}([a-zA-Z0-9_]){1,52}$/.test(appId)) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid appId');
+ }
}
var event_listeners_ = {};
var watchId_ = 0;
function nextWatchId() {
- return ++watchId_;
+ return ++watchId_;
}
Application.prototype.addEventListener = function(event, callback) {
- var args = AV.validateArgs(arguments, [
- {name: 'event', type: AV.Types.DICTIONARY},
- {name: 'callback', type: AV.Types.FUNCTION}
- ]);
+ var args = AV.validateArgs(arguments, [
+ { name: 'event', type: AV.Types.DICTIONARY },
+ { name: 'callback', type: AV.Types.FUNCTION }
+ ]);
- var data = {};
+ var data = {};
-// TODO: Please uncomment below lines when system events is ready
-// if (Object.keys(SystemEvent).indexOf(args.event.name) > -1) {
-// data.name = 'tizen.system.event.' + args.event.name.toLowerCase();
-// } else {
+ // TODO: Please uncomment below lines when system events is ready
+ // if (Object.keys(SystemEvent).indexOf(args.event.name) > -1) {
+ // data.name = 'tizen.system.event.' + args.event.name.toLowerCase();
+ // } else {
_checkEventName(args.event.name);
_checkAppId(args.event.appId);
// the 'event.' prefix is required by platform
data.name = 'event.' + args.event.appId + '.' + args.event.name;
-// }
-
- var watchId = nextWatchId();
- data.listenerId = data.name;
- event_listeners_[data.name] = !T.isObject(event_listeners_[data.name])
- ? {} : event_listeners_[data.name];
-
- if (!Object.keys(event_listeners_[data.name]).length) {
- native.addListener(data.name, function(msg) {
- var eventName = msg.name;
- var parsedName = eventName.split('.');
- var eventInfo = {};
- if (parsedName.length < 3) {
- privUtils_.log('Invalid event name returned' + eventName);
- }
- for (var id in event_listeners_[eventName]) {
- if (event_listeners_[eventName].hasOwnProperty(id)) {
- if (msg.data) {
- eventInfo.appId = parsedName[1];
- eventInfo.name = parsedName[2];
- event_listeners_[eventName][id](eventInfo, msg.data);
- } else {
- delete msg.name;
- msg.type = parsedName[2]; //TODO: type should come from native site
- eventInfo.name = parsedName[2].toUpperCase();
- event_listeners_[eventName][id](eventInfo, msg);
- }
+ // }
+
+ var watchId = nextWatchId();
+ data.listenerId = data.name;
+ event_listeners_[data.name] = !T.isObject(event_listeners_[data.name])
+ ? {}
+ : event_listeners_[data.name];
+
+ if (!Object.keys(event_listeners_[data.name]).length) {
+ native.addListener(data.name, function(msg) {
+ var eventName = msg.name;
+ var parsedName = eventName.split('.');
+ var eventInfo = {};
+ if (parsedName.length < 3) {
+ privUtils_.log('Invalid event name returned' + eventName);
+ }
+ for (var id in event_listeners_[eventName]) {
+ if (event_listeners_[eventName].hasOwnProperty(id)) {
+ if (msg.data) {
+ eventInfo.appId = parsedName[1];
+ eventInfo.name = parsedName[2];
+ event_listeners_[eventName][id](eventInfo, msg.data);
+ } else {
+ delete msg.name;
+ msg.type = parsedName[2];
+ //TODO: type should come from native site
+ eventInfo.name = parsedName[2].toUpperCase();
+ event_listeners_[eventName][id](eventInfo, msg);
+ }
+ }
+ }
+ });
+
+ var result = native.callSync('Application_addEventListener', data);
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
}
- }
- });
-
- var result = native.callSync('Application_addEventListener', data);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
}
- }
- event_listeners_[data.name][watchId] = args.callback;
- return watchId;
+ event_listeners_[data.name][watchId] = args.callback;
+ return watchId;
};
function getEventNameById(watchId) {
- var eventName;
- for (var event in event_listeners_) {
- if (event_listeners_.hasOwnProperty(event)) {
- for (var id in event_listeners_[event]) {
- if (event_listeners_[event].hasOwnProperty(id) && Converter.toLong(id) === watchId) {
- eventName = event;
+ var eventName;
+ for (var event in event_listeners_) {
+ if (event_listeners_.hasOwnProperty(event)) {
+ for (var id in event_listeners_[event]) {
+ if (
+ event_listeners_[event].hasOwnProperty(id) &&
+ Converter.toLong(id) === watchId
+ ) {
+ eventName = event;
+ }
+ }
}
- }
}
- }
- return eventName;
+ return eventName;
}
Application.prototype.removeEventListener = function(watchId) {
- var args = AV.validateArgs(arguments, [
- {name: 'watchId', type: AV.Types.LONG}
- ]);
+ var args = AV.validateArgs(arguments, [{ name: 'watchId', type: AV.Types.LONG }]);
- var eventName = getEventNameById(args.watchId);
+ var eventName = getEventNameById(args.watchId);
- if (!eventName) {
- return;
- }
+ if (!eventName) {
+ return;
+ }
- delete event_listeners_[eventName][args.watchId];
+ delete event_listeners_[eventName][args.watchId];
- if (!Object.keys(event_listeners_[eventName]).length) {
- native.removeListener(eventName);
- var result = native.callSync('Application_removeEventListener', {name: eventName});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ if (!Object.keys(event_listeners_[eventName]).length) {
+ native.removeListener(eventName);
+ var result = native.callSync('Application_removeEventListener', {
+ name: eventName
+ });
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
}
- }
};
Application.prototype.broadcastEvent = function(event, data) {
- var args = AV.validateMethod(arguments, [
- {name: 'event', type: AV.Types.DICTIONARY},
- {name: 'data', type: AV.Types.DICTIONARY}
- ]);
+ var args = AV.validateMethod(arguments, [
+ { name: 'event', type: AV.Types.DICTIONARY },
+ { name: 'data', type: AV.Types.DICTIONARY }
+ ]);
- _checkEventName(args.event.name);
+ _checkEventName(args.event.name);
- var nativeData = {
- name: 'event.' + this.appInfo.id + '.' + args.event.name,
- data: args.data
- };
+ var nativeData = {
+ name: 'event.' + this.appInfo.id + '.' + args.event.name,
+ data: args.data
+ };
- var result = native.callSync('Application_broadcastEvent', nativeData);
+ var result = native.callSync('Application_broadcastEvent', nativeData);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
Application.prototype.broadcastTrustedEvent = function(event, data) {
- var args = AV.validateMethod(arguments, [
- {name: 'event', type: AV.Types.DICTIONARY},
- {name: 'data', type: AV.Types.DICTIONARY}
- ]);
+ var args = AV.validateMethod(arguments, [
+ { name: 'event', type: AV.Types.DICTIONARY },
+ { name: 'data', type: AV.Types.DICTIONARY }
+ ]);
- _checkEventName(args.event.name);
+ _checkEventName(args.event.name);
- var nativeData = {
- name: 'event.' + this.appInfo.id + '.' + args.event.name,
- data: args.data
- };
+ var nativeData = {
+ name: 'event.' + this.appInfo.id + '.' + args.event.name,
+ data: args.data
+ };
- var result = native.callSync('Application_broadcastTrustedEvent', nativeData);
+ var result = native.callSync('Application_broadcastTrustedEvent', nativeData);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
// class ApplicationInformation ////////////////////////////////////////////////////
function ApplicationInformation(data) {
- var size = undefined;
-
- function sizeGetter() {
- if (undefined === size) {
- var callArgs = { packageId : this.packageId }; // jshint ignore:line
- var result = native.callSync('ApplicationInformation_getSize', callArgs);
+ var size = undefined;
+
+ function sizeGetter() {
+ if (undefined === size) {
+ var callArgs = { packageId: this.packageId }; // jshint ignore:line
+ var result = native.callSync('ApplicationInformation_getSize', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ size = native.getResultObject(result).size;
+ }
+ }
+ return size;
+ }
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- size = native.getResultObject(result).size;
- }
- }
- return size;
- }
-
- Object.defineProperties(this, {
- id : {
- value : data.id,
- writable : false,
- enumerable : true
- },
- name : {
- value : data.name,
- writable : false,
- enumerable : true
- },
- iconPath : {
- value : data.iconPath,
- writable : false,
- enumerable : true
- },
- version : {
- value : data.version,
- writable : false,
- enumerable : true
- },
- show : {
- value : data.show,
- writable : false,
- enumerable : true
- },
- categories : {
- value : data.categories,
- writable : false,
- enumerable : true
- },
- installDate : {
- value : new Date(data.installDate),
- writable : false,
- enumerable : true
- },
- size : {
- enumerable : true,
- set : function() {
- },
- get : sizeGetter
- },
- packageId : {
- value : data.packageId,
- writable : false,
- enumerable : true
- }
- });
+ Object.defineProperties(this, {
+ id: {
+ value: data.id,
+ writable: false,
+ enumerable: true
+ },
+ name: {
+ value: data.name,
+ writable: false,
+ enumerable: true
+ },
+ iconPath: {
+ value: data.iconPath,
+ writable: false,
+ enumerable: true
+ },
+ version: {
+ value: data.version,
+ writable: false,
+ enumerable: true
+ },
+ show: {
+ value: data.show,
+ writable: false,
+ enumerable: true
+ },
+ categories: {
+ value: data.categories,
+ writable: false,
+ enumerable: true
+ },
+ installDate: {
+ value: new Date(data.installDate),
+ writable: false,
+ enumerable: true
+ },
+ size: {
+ enumerable: true,
+ set: function() {},
+ get: sizeGetter
+ },
+ packageId: {
+ value: data.packageId,
+ writable: false,
+ enumerable: true
+ }
+ });
}
// class ApplicationContext ////////////////////////////////////////////////////
function ApplicationContext(data) {
- Object.defineProperties(this, {
- id : {value: data.id, writable: false, enumerable: true},
- appId : {value: data.appId, writable: false, enumerable: true}
- });
+ Object.defineProperties(this, {
+ id: { value: data.id, writable: false, enumerable: true },
+ appId: { value: data.appId, writable: false, enumerable: true }
+ });
}
// class ApplicationControlData ////////////////////////////////////////////////////
tizen.ApplicationControlData = function(k, v) {
- AV.validateConstructorCall(this, tizen.ApplicationControlData);
-
- var valid = (arguments.length >= 2) && T.isArray(v);
-
- var key;
- function keySetter(k) {
- key = Converter.toString(k);
- }
- if (valid) {
- keySetter(k);
- }
-
- var value;
- function valueSetter(v) {
- if (T.isArray(v)) {
- value = [];
- for (var i = 0; i < v.length; ++i) {
- value.push(Converter.toString(v[i]));
- }
- }
- }
- if (valid) {
- valueSetter(v);
- }
-
- Object.defineProperties(this, {
- key : {
- enumerable : true,
- set : keySetter,
- get : function() {
- return key;
- }
- },
- value : {
- enumerable : true,
- set : valueSetter,
- get : function() {
- return value;
- }
- }
- });
-}
+ AV.validateConstructorCall(this, tizen.ApplicationControlData);
+
+ var valid = arguments.length >= 2 && T.isArray(v);
+
+ var key;
+ function keySetter(k) {
+ key = Converter.toString(k);
+ }
+ if (valid) {
+ keySetter(k);
+ }
+
+ var value;
+ function valueSetter(v) {
+ if (T.isArray(v)) {
+ value = [];
+ for (var i = 0; i < v.length; ++i) {
+ value.push(Converter.toString(v[i]));
+ }
+ }
+ }
+ if (valid) {
+ valueSetter(v);
+ }
+
+ Object.defineProperties(this, {
+ key: {
+ enumerable: true,
+ set: keySetter,
+ get: function() {
+ return key;
+ }
+ },
+ value: {
+ enumerable: true,
+ set: valueSetter,
+ get: function() {
+ return value;
+ }
+ }
+ });
+};
// class ApplicationControl ////////////////////////////////////////////////////
tizen.ApplicationControl = function(o, u, m, c, d, mode) {
- AV.validateConstructorCall(this, tizen.ApplicationControl);
-
- var valid = (arguments.length >= 1);
-
- var operation;
- function operationSetter(o) {
- operation = Converter.toString(o);
- }
- if (valid) {
- operationSetter(o);
- }
-
- var uri;
- function uriSetter(u) {
- if (T.isNull(u)) {
- uri = u;
- } else {
- uri = Converter.toString(u);
+ AV.validateConstructorCall(this, tizen.ApplicationControl);
+
+ var valid = arguments.length >= 1;
+
+ var operation;
+ function operationSetter(o) {
+ operation = Converter.toString(o);
+ }
+ if (valid) {
+ operationSetter(o);
}
- }
- if (valid) {
- uriSetter(T.isUndefined(u) ? null : u);
- }
- var mime;
- function mimeSetter(m) {
- if (T.isNull(m)) {
- mime = m;
- } else {
- mime = Converter.toString(m);
+ var uri;
+ function uriSetter(u) {
+ if (T.isNull(u)) {
+ uri = u;
+ } else {
+ uri = Converter.toString(u);
+ }
+ }
+ if (valid) {
+ uriSetter(T.isUndefined(u) ? null : u);
}
- }
- if (valid) {
- mimeSetter(T.isUndefined(m) ? null : m);
- }
- var category;
- function categorySetter(c) {
- if (T.isNull(c)) {
- category = c;
- } else {
- category = Converter.toString(c);
- }
- }
- if (valid) {
- categorySetter(T.isUndefined(c) ? null : c);
- }
-
- var data;
- function dataSetter(d) {
- if (T.isArray(d)) {
- for (var i = 0; i < d.length; ++i) {
- if (!(d[i] instanceof tizen.ApplicationControlData)) {
- return;
+ var mime;
+ function mimeSetter(m) {
+ if (T.isNull(m)) {
+ mime = m;
+ } else {
+ mime = Converter.toString(m);
}
- }
- data = d;
- }
- }
- if (valid) {
- dataSetter(T.isNullOrUndefined(d) ? [] : d);
- }
-
- var launchMode;
- function launchModeSetter(mode) {
- if (ApplicationControlLaunchMode[mode]) {
- launchMode = ApplicationControlLaunchMode[mode];
- }
- }
- if (valid) {
- if (T.isNullOrUndefined(mode) || !ApplicationControlLaunchMode[mode]) {
- launchMode = ApplicationControlLaunchMode['SINGLE'];
- } else {
- launchModeSetter(mode);
- }
- }
-
- Object.defineProperties(this, {
- operation : {
- enumerable : true,
- set : operationSetter,
- get : function() {
- return operation;
- }
- },
- uri : {
- enumerable : true,
- set : uriSetter,
- get : function() {
- return uri;
- }
- },
- mime : {
- enumerable : true,
- set : mimeSetter,
- get : function() {
- return mime;
- }
- },
- category : {
- enumerable : true,
- set : categorySetter,
- get : function() {
- return category;
- }
- },
- data : {
- enumerable : true,
- set : dataSetter,
- get : function() {
- return data;
- }
- },
- launchMode : {
- enumerable : true,
- set : launchModeSetter,
- get : function() {
- return launchMode;
- }
- }
- });
-}
+ }
+ if (valid) {
+ mimeSetter(T.isUndefined(m) ? null : m);
+ }
+
+ var category;
+ function categorySetter(c) {
+ if (T.isNull(c)) {
+ category = c;
+ } else {
+ category = Converter.toString(c);
+ }
+ }
+ if (valid) {
+ categorySetter(T.isUndefined(c) ? null : c);
+ }
+
+ var data;
+ function dataSetter(d) {
+ if (T.isArray(d)) {
+ for (var i = 0; i < d.length; ++i) {
+ if (!(d[i] instanceof tizen.ApplicationControlData)) {
+ return;
+ }
+ }
+ data = d;
+ }
+ }
+ if (valid) {
+ dataSetter(T.isNullOrUndefined(d) ? [] : d);
+ }
+
+ var launchMode;
+ function launchModeSetter(mode) {
+ if (ApplicationControlLaunchMode[mode]) {
+ launchMode = ApplicationControlLaunchMode[mode];
+ }
+ }
+ if (valid) {
+ if (T.isNullOrUndefined(mode) || !ApplicationControlLaunchMode[mode]) {
+ launchMode = ApplicationControlLaunchMode['SINGLE'];
+ } else {
+ launchModeSetter(mode);
+ }
+ }
+
+ Object.defineProperties(this, {
+ operation: {
+ enumerable: true,
+ set: operationSetter,
+ get: function() {
+ return operation;
+ }
+ },
+ uri: {
+ enumerable: true,
+ set: uriSetter,
+ get: function() {
+ return uri;
+ }
+ },
+ mime: {
+ enumerable: true,
+ set: mimeSetter,
+ get: function() {
+ return mime;
+ }
+ },
+ category: {
+ enumerable: true,
+ set: categorySetter,
+ get: function() {
+ return category;
+ }
+ },
+ data: {
+ enumerable: true,
+ set: dataSetter,
+ get: function() {
+ return data;
+ }
+ },
+ launchMode: {
+ enumerable: true,
+ set: launchModeSetter,
+ get: function() {
+ return launchMode;
+ }
+ }
+ });
+};
// class RequestedApplicationControl ////////////////////////////////////////////////////
function RequestedApplicationControl(data) {
- Object.defineProperties(this, {
- appControl : {
- value: _createApplicationControl(data.appControl),
- writable: false,
- enumerable: true
- },
- callerAppId : {
- value: data.callerAppId,
- writable: false,
- enumerable: true
- }
- });
+ Object.defineProperties(this, {
+ appControl: {
+ value: _createApplicationControl(data.appControl),
+ writable: false,
+ enumerable: true
+ },
+ callerAppId: {
+ value: data.callerAppId,
+ writable: false,
+ enumerable: true
+ }
+ });
}
RequestedApplicationControl.prototype.replyResult = function() {
- var args = AV.validateMethod(arguments, [
- {
- name : 'data',
- type : AV.Types.ARRAY,
- values : tizen.ApplicationControlData,
- optional: true,
- nullable: true
- }
- ]);
-
-
- var callArgs = {};
-
- if (args.has.data) {
- callArgs.data = args.data;
- } else {
- callArgs.data = [];
- }
-
- var result = native.callSync('RequestedApplicationControl_replyResult', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'data',
+ type: AV.Types.ARRAY,
+ values: tizen.ApplicationControlData,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+
+ if (args.has.data) {
+ callArgs.data = args.data;
+ } else {
+ callArgs.data = [];
+ }
+
+ var result = native.callSync('RequestedApplicationControl_replyResult', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
RequestedApplicationControl.prototype.replyFailure = function() {
- var result = native.callSync('RequestedApplicationControl_replyFailure', {});
+ var result = native.callSync('RequestedApplicationControl_replyFailure', {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
// class ApplicationCertificate ////////////////////////////////////////////////////
function ApplicationCertificate(data) {
- Object.defineProperties(this, {
- type : {
- value : data.type,
- writable : false,
- enumerable : true
- },
- value : {
- value : data.value,
- writable : false,
- enumerable : true
- }
- });
+ Object.defineProperties(this, {
+ type: {
+ value: data.type,
+ writable: false,
+ enumerable: true
+ },
+ value: {
+ value: data.value,
+ writable: false,
+ enumerable: true
+ }
+ });
}
// class ApplicationMetaData ///////////////////////////////////////////////////////
function ApplicationMetaData(data) {
- Object.defineProperties(this, {
- key : {
- value : data.key,
- writable : false,
- enumerable : true
- },
- value : {
- value : data.value,
- writable : false,
- enumerable : true
- }
- });
+ Object.defineProperties(this, {
+ key: {
+ value: data.key,
+ writable: false,
+ enumerable: true
+ },
+ value: {
+ value: data.value,
+ writable: false,
+ enumerable: true
+ }
+ });
}
//class ApplicationBatteryUsage ////////////////////////////////////////////////////
function ApplicationBatteryUsage(data) {
- Object.defineProperties(this, {
- appId : {
- value : data.appId,
- writable : false,
- enumerable : true
- },
- batteryUsage : {
- value : data.batteryUsage,
- writable : false,
- enumerable : true
- }
- });
+ Object.defineProperties(this, {
+ appId: {
+ value: data.appId,
+ writable: false,
+ enumerable: true
+ },
+ batteryUsage: {
+ value: data.batteryUsage,
+ writable: false,
+ enumerable: true
+ }
+ });
}
//class ApplicationUsage ////////////////////////////////////////////////////////
function ApplicationUsage(data) {
- Object.defineProperties(this, {
- appId : {
- value : data.appId,
- writable : false,
- enumerable : true
- },
- totalCount : {
- value : data.totalCount,
- writable : false,
- enumerable : true
- },
- totalDuration : {
- value : data.totalDuration,
- writable : false,
- enumerable : true
- },
- lastTime : {
- value : new Date(data.lastTime * 1000),
- writable : false,
- enumerable : true
- }
- });
+ Object.defineProperties(this, {
+ appId: {
+ value: data.appId,
+ writable: false,
+ enumerable: true
+ },
+ totalCount: {
+ value: data.totalCount,
+ writable: false,
+ enumerable: true
+ },
+ totalDuration: {
+ value: data.totalDuration,
+ writable: false,
+ enumerable: true
+ },
+ lastTime: {
+ value: new Date(data.lastTime * 1000),
+ writable: false,
+ enumerable: true
+ }
+ });
}
// exports ////////////////////////////////////////////////////
diff --git a/src/archive/archive_api.js b/src/archive/archive_api.js
index 41a8caac..61c2b993 100755
--- a/src/archive/archive_api.js
+++ b/src/archive/archive_api.js
@@ -13,13 +13,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var validator_ = xwalk.utils.validator;
var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
var privUtils_ = xwalk.utils;
-function CommonFS() {};
+function CommonFS() {}
CommonFS.cacheVirtualToReal = {};
CommonFS.isCacheReady = false;
@@ -37,7 +37,10 @@ function _initializeCache() {
var result = native_.callSync('Archive_fetchStorages', {});
if (native_.isFailure(result)) {
- privUtils_.log("Exception while getting widget paths was thrown: " + native_.getErrorObject(result).message);
+ privUtils_.log(
+ 'Exception while getting widget paths was thrown: ' +
+ native_.getErrorObject(result).message
+ );
return;
}
@@ -50,11 +53,14 @@ function _initializeCache() {
CommonFS.isCacheReady = true;
if (!CommonFS.listenerRegistered) {
try {
- tizen.filesystem.addStorageStateChangeListener(clearCache);
- CommonFS.listenerRegistered = true;
+ tizen.filesystem.addStorageStateChangeListener(clearCache);
+ CommonFS.listenerRegistered = true;
} catch (e) {
- privUtils_.log('Failed to register storage change listener, '
- + 'storage information may be corrupted: ' + e.message);
+ privUtils_.log(
+ 'Failed to register storage change listener, ' +
+ 'storage information may be corrupted: ' +
+ e.message
+ );
}
}
}
@@ -62,15 +68,20 @@ function _initializeCache() {
_initializeCache();
CommonFS.toRealPath = function(aPath) {
- var _fileRealPath = '', _uriPrefix = 'file://', i;
+ var _fileRealPath = '',
+ _uriPrefix = 'file://',
+ i;
if (aPath.indexOf(_uriPrefix) === 0) {
_fileRealPath = aPath.substr(_uriPrefix.length);
} else if (aPath[0] != '/') {
// virtual path$
_initializeCache();
var _pathTokens = aPath.split('/');
- if (this.cacheVirtualToReal[_pathTokens[0]]
- && (this.cacheVirtualToReal[_pathTokens[0]].state === undefined || this.cacheVirtualToReal[_pathTokens[0]].state === 'MOUNTED')) {
+ if (
+ this.cacheVirtualToReal[_pathTokens[0]] &&
+ (this.cacheVirtualToReal[_pathTokens[0]].state === undefined ||
+ this.cacheVirtualToReal[_pathTokens[0]].state === 'MOUNTED')
+ ) {
_fileRealPath = this.cacheVirtualToReal[_pathTokens[0]].path;
for (i = 1; i < _pathTokens.length; ++i) {
_fileRealPath += '/' + _pathTokens[i];
@@ -81,15 +92,15 @@ CommonFS.toRealPath = function(aPath) {
} else {
_fileRealPath = aPath;
}
- privUtils_.log("REAL PATH:" + _fileRealPath);
- if (_fileRealPath === "undefined" || _fileRealPath === "null") {
+ privUtils_.log('REAL PATH:' + _fileRealPath);
+ if (_fileRealPath === 'undefined' || _fileRealPath === 'null') {
throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
return _fileRealPath;
};
CommonFS.isVirtualPath = function(aPath) {
- var root = aPath.split("/")[0];
+ var root = aPath.split('/')[0];
_initializeCache();
return this.cacheVirtualToReal[root] != undefined;
};
@@ -97,19 +108,19 @@ CommonFS.isVirtualPath = function(aPath) {
/**
* Returns new unique opId
*/
-var getNextOpId = (function () {
+var getNextOpId = (function() {
var opId = 0,
- incOpId = function () {
+ incOpId = function() {
return opId++;
};
return incOpId;
-}());
+})();
var Property = {
- W: 1 << 0, // WRITABLE
- E: 1 << 1, // ENUMERABLE
- C: 1 << 2 // CONFIGURABLE
-}
+ W: 1 << 0, // WRITABLE
+ E: 1 << 1, // ENUMERABLE
+ C: 1 << 2 // CONFIGURABLE
+};
/**
* Example usage:
@@ -136,22 +147,27 @@ function propertyFactory_(that, name, value, flags, options) {
if (options === null || typeof options !== 'object') {
options = {};
}
- if (!(options.get) && !(options.set)) {
+ if (!options.get && !options.set) {
options.value = value;
}
- if ((flags & Property.W) != 0) { options.writable = true; }
- if ((flags & Property.E) != 0) { options.enumerable = true; }
- if ((flags & Property.C) != 0) { options.configurable = true; }
- Object.defineProperty(
- that,
- name,
- options
- );
+ if ((flags & Property.W) != 0) {
+ options.writable = true;
+ }
+ if ((flags & Property.E) != 0) {
+ options.enumerable = true;
+ }
+ if ((flags & Property.C) != 0) {
+ options.configurable = true;
+ }
+ Object.defineProperty(that, name, options);
}
-function checkMode(mode, access)
-{ if(access.indexOf(mode) == -1) {
- throw new WebAPIException(WebAPIException.INVALID_ACCESS_ERR, 'Not allowed operation');
+function checkMode(mode, access) {
+ if (access.indexOf(mode) == -1) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_ACCESS_ERR,
+ 'Not allowed operation'
+ );
}
}
@@ -160,10 +176,10 @@ function checkMode(mode, access)
* @enum {string}
*/
var ArchiveCompressionLevel = {
- STORE: "STORE",
- FAST: "FAST",
- NORMAL: "NORMAL",
- BEST: "BEST"
+ STORE: 'STORE',
+ FAST: 'FAST',
+ NORMAL: 'NORMAL',
+ BEST: 'BEST'
};
var onprogressCallbacks = {};
@@ -175,7 +191,10 @@ var ArchiveFileProgressCallback = function(msg) {
}
var result = native_.getResultObject(msg);
- if ('onprogress' === result.action && onprogressCallbacks.hasOwnProperty(result.opId)) {
+ if (
+ 'onprogress' === result.action &&
+ onprogressCallbacks.hasOwnProperty(result.opId)
+ ) {
onprogressCallbacks[result.opId](result.opId, result.value, result.filename);
}
};
@@ -183,7 +202,8 @@ var ArchiveFileProgressCallback = function(msg) {
native_.addListener(ARCHIVE_ONPROGRESS_CALLBACK, ArchiveFileProgressCallback);
/**
- * The ArchiveFileEntry interface provides access to ArchiveFile member information and file data.
+ * The ArchiveFileEntry interface provides access to ArchiveFile member information
+ * and file data.
* This constructor is for internal use only.
* It should be prohibited to call this constructor by user.
*/
@@ -196,43 +216,78 @@ function ArchiveFileEntry(data, priv) {
throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
- propertyFactory_(this, 'name', data.name || "", Property.E);
- propertyFactory_(this, 'size', data.size || 0, Property.E);
- propertyFactory_(this, 'compressedSize', data.compressedSize || 0, Property.E);
- propertyFactory_(this, 'modified', new Date(data.modified * 1000) || null , Property.E);
+ propertyFactory_(this, 'name', data.name || '', Property.E);
+ propertyFactory_(this, 'size', data.size || 0, Property.E);
+ propertyFactory_(this, 'compressedSize', data.compressedSize || 0, Property.E);
+ propertyFactory_(
+ this,
+ 'modified',
+ new Date(data.modified * 1000) || null,
+ Property.E
+ );
function getHandle() {
- if(priv.handle)
- return priv.handle;
- else throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'Archive is not opened');
+ if (priv.handle) return priv.handle;
+ else
+ throw new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Archive is not opened'
+ );
}
/**
* Extracts ArchiveFileEntry to the given location.
*/
- this.extract = function () {
+ this.extract = function() {
var args = validator_.validateArgs(arguments, [
- { name: "destinationDirectory", type: types_.FILE_REFERENCE },
- { name: "onsuccess", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "onerror", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "onprogress", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "stripName", type: types_.STRING, optional: true, nullable: true },
- { name: "overwrite", type: types_.BOOLEAN, optional: true, nullable: true }
- ]),
- opId = getNextOpId();
+ { name: 'destinationDirectory', type: types_.FILE_REFERENCE },
+ {
+ name: 'onsuccess',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'onerror',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'onprogress',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'stripName',
+ type: types_.STRING,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'overwrite',
+ type: types_.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]),
+ opId = getNextOpId();
if (!CommonFS.isVirtualPath(args.destinationDirectory)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- "Destination directory should be virtual path or file.");
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Destination directory should be virtual path or file.'
+ );
}
var callArgs = {
- destinationDirectory : CommonFS.toRealPath(args.destinationDirectory),
- stripName : args.stripName || null,
- overwrite : args.overwrite || null,
- opId : opId,
- handle : getHandle(),
- name : this.name
+ destinationDirectory: CommonFS.toRealPath(args.destinationDirectory),
+ stripName: args.stripName || null,
+ overwrite: args.overwrite || null,
+ opId: opId,
+ handle: getHandle(),
+ name: this.name
};
var callback = function(result) {
@@ -258,9 +313,9 @@ function ArchiveFileEntry(data, priv) {
};
}
-
/**
- * The ArchiveManager interface provides methods for global operations related to ArchiveFile.
+ * The ArchiveManager interface provides methods for global operations related to
+ * ArchiveFile.
*/
/**
@@ -277,51 +332,80 @@ function ArchiveFile(data) {
throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
- propertyFactory_(this, 'mode' , data.mode || "r", Property.E);
- propertyFactory_(this, 'decompressedSize', data.decompressedSize || 0, Property.E);
+ propertyFactory_(this, 'mode', data.mode || 'r', Property.E);
+ propertyFactory_(this, 'decompressedSize', data.decompressedSize || 0, Property.E);
- var priv ={ handle: data.handle };
+ var priv = { handle: data.handle };
function getHandle() {
- if(priv.handle)
- return priv.handle;
- else throw new WebAPIException(WebAPIException.INVALID_STATE_ERR, 'ArchiveFile closed - operation not permitted');
+ if (priv.handle) return priv.handle;
+ else
+ throw new WebAPIException(
+ WebAPIException.INVALID_STATE_ERR,
+ 'ArchiveFile closed - operation not permitted'
+ );
}
/**
* Adds a new member file to ArchiveFile.
*/
- this.add = function () {
+ this.add = function() {
var args = validator_.validateArgs(arguments, [
- { name: "sourceFile", type: types_.FILE_REFERENCE },
- { name: "onsuccess", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "onerror", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "onprogress", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "options", type: types_.DICTIONARY, optional: true, nullable: true }
- ]),
- opId = getNextOpId();
+ { name: 'sourceFile', type: types_.FILE_REFERENCE },
+ {
+ name: 'onsuccess',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'onerror',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'onprogress',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'options',
+ type: types_.DICTIONARY,
+ optional: true,
+ nullable: true
+ }
+ ]),
+ opId = getNextOpId();
if (!CommonFS.isVirtualPath(args.sourceFile)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- "sourceFile should be virtual path or file.");
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'sourceFile should be virtual path or file.'
+ );
}
- var optionsAttributes = ["destination", "stripSourceDirectory", "compressionLevel"],
+ var optionsAttributes = [
+ 'destination',
+ 'stripSourceDirectory',
+ 'compressionLevel'
+ ],
options = args.options || {};
- for(var i in optionsAttributes) {
+ for (var i in optionsAttributes) {
if (!options[optionsAttributes[i]]) {
options[optionsAttributes[i]] = null;
}
}
- checkMode(this.mode, ["w","rw", "a"]);
+ checkMode(this.mode, ['w', 'rw', 'a']);
var callArgs = {
- sourceFile : CommonFS.toRealPath(args.sourceFile),
- options : options,
- opId : opId,
- handle : getHandle()
+ sourceFile: CommonFS.toRealPath(args.sourceFile),
+ options: options,
+ opId: opId,
+ handle: getHandle()
};
var callback = function(result) {
@@ -348,28 +432,50 @@ function ArchiveFile(data) {
/**
* Extracts every file from this ArchiveFile to a given directory.
*/
- this.extractAll = function () {
+ this.extractAll = function() {
var args = validator_.validateArgs(arguments, [
- { name: "destinationDirectory", type: types_.FILE_REFERENCE },
- { name: "onsuccess", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "onerror", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "onprogress", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "overwrite", type: types_.BOOLEAN, optional: true, nullable: true }
- ]),
- opId = getNextOpId();
+ { name: 'destinationDirectory', type: types_.FILE_REFERENCE },
+ {
+ name: 'onsuccess',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'onerror',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'onprogress',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'overwrite',
+ type: types_.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]),
+ opId = getNextOpId();
if (!CommonFS.isVirtualPath(args.destinationDirectory)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- "destinationDirectory should be virtual path or file.");
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'destinationDirectory should be virtual path or file.'
+ );
}
- checkMode(this.mode, ["r","rw"]);
+ checkMode(this.mode, ['r', 'rw']);
var callArgs = {
- destinationDirectory : CommonFS.toRealPath(args.destinationDirectory),
- overwrite : args.overwrite || null,
- opId : opId,
- handle : getHandle()
+ destinationDirectory: CommonFS.toRealPath(args.destinationDirectory),
+ overwrite: args.overwrite || null,
+ opId: opId,
+ handle: getHandle()
};
var callback = function(result) {
@@ -396,18 +502,18 @@ function ArchiveFile(data) {
/**
* Retrieves information about the member files in ArchiveFile.
*/
- this.getEntries = function () {
+ this.getEntries = function() {
var args = validator_.validateArgs(arguments, [
- { name: "onsuccess", type: types_.FUNCTION },
- { name: "onerror", type: types_.FUNCTION, optional: true, nullable: true }
- ]),
- opId = getNextOpId();
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]),
+ opId = getNextOpId();
- checkMode(this.mode, ["r","rw"]);
+ checkMode(this.mode, ['r', 'rw']);
var callArgs = {
- opId : opId,
- handle : getHandle()
+ opId: opId,
+ handle: getHandle()
};
var callback = function(result) {
@@ -416,11 +522,11 @@ function ArchiveFile(data) {
} else {
var entries = [];
var ret = native_.getResultObject(result);
- ret.forEach(function (e) {
+ ret.forEach(function(e) {
entries.push(new ArchiveFileEntry(e, priv));
});
args.onsuccess(entries);
- }
+ }
};
var result = native_.call('ArchiveFile_getEntries', callArgs, callback);
@@ -432,29 +538,32 @@ function ArchiveFile(data) {
};
/**
- * Retrieves information about ArchiveFileEntry with the specified name in ArchiveFile.
+ * Retrieves information about ArchiveFileEntry with the specified name in
+ * ArchiveFile.
*/
- this.getEntryByName = function () {
+ this.getEntryByName = function() {
var args = validator_.validateArgs(arguments, [
- { name: "name", type: types_.STRING },
- { name: "onsuccess", type: types_.FUNCTION },
- { name: "onerror", type: types_.FUNCTION, optional: true, nullable: true }
- ]),
- opId = getNextOpId();
+ { name: 'name', type: types_.STRING },
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]),
+ opId = getNextOpId();
- checkMode(this.mode, ["r","rw"]);
+ checkMode(this.mode, ['r', 'rw']);
var callArgs = {
- name : args.name,
- opId : opId,
- handle : getHandle()
+ name: args.name,
+ opId: opId,
+ handle: getHandle()
};
var callback = function(result) {
if (native_.isFailure(result)) {
native_.callIfPossible(args.onerror, native_.getErrorObject(result));
} else {
- args.onsuccess(new ArchiveFileEntry(native_.getResultObject(result), priv));
+ args.onsuccess(
+ new ArchiveFileEntry(native_.getResultObject(result), priv)
+ );
}
};
@@ -469,11 +578,11 @@ function ArchiveFile(data) {
/**
* Closes the ArchiveFile.
*/
- this.close = function () {
+ this.close = function() {
var handle = priv.handle;
- if(priv.handle) {
+ if (priv.handle) {
delete priv.handle;
- var result = native_.callSync('ArchiveFile_close', {'handle': handle});
+ var result = native_.callSync('ArchiveFile_close', { handle: handle });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
@@ -482,45 +591,45 @@ function ArchiveFile(data) {
};
}
-
-var ArchiveManager = function () {
-};
+var ArchiveManager = function() {};
/**
- * Opens the archive file. After this operation, it is possible to add or get files to and from the archive.
+ * Opens the archive file. After this operation, it is possible to add or get files
+ * to and from the archive.
*/
-ArchiveManager.prototype.open = function () {
+ArchiveManager.prototype.open = function() {
var args = validator_.validateArgs(arguments, [
- { name: "file", type: types_.FILE_REFERENCE },
- { name: "mode", type: types_.ENUM, values: ["r", "rw", "w", "a"] },
- { name: "onsuccess", type: types_.FUNCTION },
- { name: "onerror", type: types_.FUNCTION, optional: true, nullable: true },
- { name: "options", type: types_.DICTIONARY, optional: true, nullable: true }
- ]),
- opId = getNextOpId();
-
- var optionsAttributes = ["overwrite"],
+ { name: 'file', type: types_.FILE_REFERENCE },
+ { name: 'mode', type: types_.ENUM, values: ['r', 'rw', 'w', 'a'] },
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'options', type: types_.DICTIONARY, optional: true, nullable: true }
+ ]),
+ opId = getNextOpId();
+
+ var optionsAttributes = ['overwrite'],
options = args.options || {};
- for(var i in optionsAttributes) {
+ for (var i in optionsAttributes) {
if (!options[optionsAttributes[i]]) {
options[optionsAttributes[i]] = null;
}
}
if (!CommonFS.isVirtualPath(args.file)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- "file should be virtual path or file.");
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'file should be virtual path or file.'
+ );
}
var callArgs = {
- file : CommonFS.toRealPath(args.file),
- mode : args.mode,
- options : options,
- opId : opId,
+ file: CommonFS.toRealPath(args.file),
+ mode: args.mode,
+ options: options,
+ opId: opId
};
-
var callback = function(result) {
if (native_.isFailure(result)) {
native_.callIfPossible(args.onerror, native_.getErrorObject(result));
@@ -540,12 +649,10 @@ ArchiveManager.prototype.open = function () {
/**
* Cancels an operation with the given identifier.
*/
-ArchiveManager.prototype.abort = function () {
- var args = validator_.validateArgs(arguments, [
- { name: "opId", type: types_.LONG }
- ]);
+ArchiveManager.prototype.abort = function() {
+ var args = validator_.validateArgs(arguments, [{ name: 'opId', type: types_.LONG }]);
- var result = native_.callSync('ArchiveManager_abort', {opId: args.opId});
+ var result = native_.callSync('ArchiveManager_abort', { opId: args.opId });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
diff --git a/src/badge/badge_api.js b/src/badge/badge_api.js
index dcd666b8..f26311cb 100755
--- a/src/badge/badge_api.js
+++ b/src/badge/badge_api.js
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
//maximum value of badge as found in old plugin implementation
var MAX_BADGE_COUNT = 999;
@@ -27,143 +27,141 @@ var _badgeListenerRegistered = false;
var _badgeCallbackMap = {};
var _currentWatchId = 1;
var _getNextWatchId = function() {
- return _currentWatchId++;
+ return _currentWatchId++;
};
var _badgeChangeListener = function(result) {
- if (result.appId && result.count && _badgeCallbackMap.hasOwnProperty(result.appId)) {
- for (var functionToCall in _badgeCallbackMap[result.appId]) {
- native_.callIfPossible(_badgeCallbackMap[result.appId][functionToCall],
- result.appId, converter_.toLong(result.count));
+ if (result.appId && result.count && _badgeCallbackMap.hasOwnProperty(result.appId)) {
+ for (var functionToCall in _badgeCallbackMap[result.appId]) {
+ native_.callIfPossible(
+ _badgeCallbackMap[result.appId][functionToCall],
+ result.appId,
+ converter_.toLong(result.count)
+ );
+ }
}
- }
};
-
-
/**
* This class provides functions to request and release badge resource.
* @constructor
*/
function BadgeManager() {
- Object.defineProperties(this, {
- 'maxBadgeCount': { value: MAX_BADGE_COUNT, emumerable: true, writable: false}
- });
+ Object.defineProperties(this, {
+ maxBadgeCount: { value: MAX_BADGE_COUNT, emumerable: true, writable: false }
+ });
}
-
/**
* Sets the badge count for the designated application.
*/
BadgeManager.prototype.setBadgeCount = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'appId', type: types_.STRING},
- {name: 'count', type: types_.LONG}
- ]);
-
- if (args.count < 0) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Count parameter is negative!');
- }
-
- var ret = native_.callSync('BadgeManager_setBadgeCount', {
- appId: args.appId,
- count: args.count
- });
-
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
-};
+ var args = validator_.validateArgs(arguments, [
+ { name: 'appId', type: types_.STRING },
+ { name: 'count', type: types_.LONG }
+ ]);
+
+ if (args.count < 0) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Count parameter is negative!'
+ );
+ }
+ var ret = native_.callSync('BadgeManager_setBadgeCount', {
+ appId: args.appId,
+ count: args.count
+ });
+
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
+};
/**
* Gets the badge count for the designated application.
* @return {number} long Count of the badge
*/
BadgeManager.prototype.getBadgeCount = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'appId', type: types_.STRING}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'appId', type: types_.STRING }
+ ]);
- var ret = native_.callSync('BadgeManager_getBadgeCount', {
- appId: args.appId
- });
+ var ret = native_.callSync('BadgeManager_getBadgeCount', {
+ appId: args.appId
+ });
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
- return parseInt(native_.getResultObject(ret));
+ return parseInt(native_.getResultObject(ret));
};
-
/**
* Gets the badge count for the designated application.
*/
BadgeManager.prototype.addChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'appIdList',
- type: types_.ARRAY,
- values: types_.STRING,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: false,
- nullable: false
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'appIdList',
+ type: types_.ARRAY,
+ values: types_.STRING,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ var result = native_.callSync('BadgeManager_addChangeListener', args);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ if (!_badgeListenerRegistered) {
+ _badgeListenerRegistered = true;
+ native_.addListener('BadgeChangeListener', _badgeChangeListener);
}
- ]);
-
- var result = native_.callSync('BadgeManager_addChangeListener', args);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- if (!_badgeListenerRegistered) {
- _badgeListenerRegistered = true;
- native_.addListener('BadgeChangeListener', _badgeChangeListener);
- }
- for (var i = 0; i < args.appIdList.length; i++) {
- if (!_badgeCallbackMap.hasOwnProperty(args.appIdList[i])) {
- _badgeCallbackMap[args.appIdList[i]] = [];
+ for (var i = 0; i < args.appIdList.length; i++) {
+ if (!_badgeCallbackMap.hasOwnProperty(args.appIdList[i])) {
+ _badgeCallbackMap[args.appIdList[i]] = [];
+ }
+ _badgeCallbackMap[args.appIdList[i]].push(args.successCallback);
}
- _badgeCallbackMap[args.appIdList[i]].push(args.successCallback);
- }
- return;
+ return;
};
-
/**
* Gets the badge count for the designated application.
*/
BadgeManager.prototype.removeChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'appIdList',
- type: types_.ARRAY,
- values: types_.STRING,
- optional: false,
- nullable: false
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'appIdList',
+ type: types_.ARRAY,
+ values: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ for (var i = 0; i < args.appIdList.length; i++) {
+ if (_badgeCallbackMap.hasOwnProperty(args.appIdList[i]))
+ delete _badgeCallbackMap[args.appIdList[i]];
}
- ]);
-
- for (var i = 0; i < args.appIdList.length; i++) {
- if (_badgeCallbackMap.hasOwnProperty(args.appIdList[i]))
- delete _badgeCallbackMap[args.appIdList[i]];
- }
- if (Type.isEmptyObject(_badgeCallbackMap)) {
- native_.removeListener('BadgeChangeListener', _badgeChangeListener);
- _badgeListenerRegistered = false;
- }
+ if (Type.isEmptyObject(_badgeCallbackMap)) {
+ native_.removeListener('BadgeChangeListener', _badgeChangeListener);
+ _badgeListenerRegistered = false;
+ }
- var result = native_.callSync('BadgeManager_removeChangeListener', args);
- if (native_.isFailure(result))
- throw native_.getErrorObject(result);
+ var result = native_.callSync('BadgeManager_removeChangeListener', args);
+ if (native_.isFailure(result)) throw native_.getErrorObject(result);
};
exports = new BadgeManager();
diff --git a/src/bluetooth/bluetooth_api.js b/src/bluetooth/bluetooth_api.js
index 9fb4266e..c229e6cc 100755
--- a/src/bluetooth/bluetooth_api.js
+++ b/src/bluetooth/bluetooth_api.js
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var T = xwalk.utils.type;
var Converter = xwalk.utils.converter;
var AV = xwalk.utils.validator;
@@ -24,377 +24,394 @@ var native = new xwalk.utils.NativeManager(extension);
// class BluetoothClassDeviceMajor /////////////////////////////////////////
var BluetoothClassDeviceMajor = function() {
Object.defineProperties(this, {
- MISC: {value: 0x00, writable: false, enumerable: true},
- COMPUTER: {value: 0x01, writable: false, enumerable: true},
- PHONE: {value: 0x02, writable: false, enumerable: true},
- NETWORK: {value: 0x03, writable: false, enumerable: true},
- AUDIO_VIDEO: {value: 0x04, writable: false, enumerable: true},
- PERIPHERAL: {value: 0x05, writable: false, enumerable: true},
- IMAGING: {value: 0x06, writable: false, enumerable: true},
- WEARABLE: {value: 0x07, writable: false, enumerable: true},
- TOY: {value: 0x08, writable: false, enumerable: true},
- HEALTH: {value: 0x09, writable: false, enumerable: true},
- UNCATEGORIZED: {value: 0x1F, writable: false, enumerable: true}
+ MISC: { value: 0x00, writable: false, enumerable: true },
+ COMPUTER: { value: 0x01, writable: false, enumerable: true },
+ PHONE: { value: 0x02, writable: false, enumerable: true },
+ NETWORK: { value: 0x03, writable: false, enumerable: true },
+ AUDIO_VIDEO: { value: 0x04, writable: false, enumerable: true },
+ PERIPHERAL: { value: 0x05, writable: false, enumerable: true },
+ IMAGING: { value: 0x06, writable: false, enumerable: true },
+ WEARABLE: { value: 0x07, writable: false, enumerable: true },
+ TOY: { value: 0x08, writable: false, enumerable: true },
+ HEALTH: { value: 0x09, writable: false, enumerable: true },
+ UNCATEGORIZED: { value: 0x1f, writable: false, enumerable: true }
});
};
// class BluetoothClassDeviceMinor /////////////////////////////////////////
var BluetoothClassDeviceMinor = function() {
Object.defineProperties(this, {
- COMPUTER_UNCATEGORIZED: {value: 0x00, writable: false, enumerable: true},
- COMPUTER_DESKTOP: {value: 0x01, writable: false, enumerable: true},
- COMPUTER_SERVER: {value: 0x02, writable: false, enumerable: true},
- COMPUTER_LAPTOP: {value: 0x03, writable: false, enumerable: true},
- COMPUTER_HANDHELD_PC_OR_PDA: {value: 0x04, writable: false, enumerable: true},
- COMPUTER_PALM_PC_OR_PDA: {value: 0x05, writable: false, enumerable: true},
- COMPUTER_WEARABLE: {value: 0x06, writable: false, enumerable: true},
-
- PHONE_UNCATEGORIZED: {value: 0x00, writable: false, enumerable: true},
- PHONE_CELLULAR: {value: 0x01, writable: false, enumerable: true},
- PHONE_CORDLESS: {value: 0x02, writable: false, enumerable: true},
- PHONE_SMARTPHONE: {value: 0x03, writable: false, enumerable: true},
- PHONE_MODEM_OR_GATEWAY: {value: 0x04, writable: false, enumerable: true},
- PHONE_ISDN: {value: 0x05, writable: false, enumerable: true},
-
- AV_UNRECOGNIZED: {value: 0x00, writable: false, enumerable: true},
- AV_WEARABLE_HEADSET: {value: 0x01, writable: false, enumerable: true},
- AV_HANDSFREE: {value: 0x02, writable: false, enumerable: true},
- AV_MICROPHONE: {value: 0x04, writable: false, enumerable: true},
- AV_LOUDSPEAKER: {value: 0x05, writable: false, enumerable: true},
- AV_HEADPHONES: {value: 0x06, writable: false, enumerable: true},
- AV_PORTABLE_AUDIO: {value: 0x07, writable: false, enumerable: true},
- AV_CAR_AUDIO: {value: 0x08, writable: false, enumerable: true},
- AV_SETTOP_BOX: {value: 0x09, writable: false, enumerable: true},
- AV_HIFI: {value: 0x0A, writable: false, enumerable: true},
- AV_VCR: {value: 0x0B, writable: false, enumerable: true},
- AV_VIDEO_CAMERA: {value: 0x0C, writable: false, enumerable: true},
- AV_CAMCORDER: {value: 0x0D, writable: false, enumerable: true},
- AV_MONITOR: {value: 0x0E, writable: false, enumerable: true},
- AV_DISPLAY_AND_LOUDSPEAKER: {value: 0x0F, writable: false, enumerable: true},
- AV_VIDEO_CONFERENCING: {value: 0x10, writable: false, enumerable: true},
- AV_GAMING_TOY: {value: 0x12, writable: false, enumerable: true},
-
- PERIPHERAL_UNCATEGORIZED: {value: 0x00, writable: false, enumerable: true},
- PERIPHERAL_KEYBOARD: {value: 0x10, writable: false, enumerable: true},
- PERIPHERAL_POINTING_DEVICE: {value: 0x20, writable: false, enumerable: true},
+ COMPUTER_UNCATEGORIZED: { value: 0x00, writable: false, enumerable: true },
+ COMPUTER_DESKTOP: { value: 0x01, writable: false, enumerable: true },
+ COMPUTER_SERVER: { value: 0x02, writable: false, enumerable: true },
+ COMPUTER_LAPTOP: { value: 0x03, writable: false, enumerable: true },
+ COMPUTER_HANDHELD_PC_OR_PDA: { value: 0x04, writable: false, enumerable: true },
+ COMPUTER_PALM_PC_OR_PDA: { value: 0x05, writable: false, enumerable: true },
+ COMPUTER_WEARABLE: { value: 0x06, writable: false, enumerable: true },
+
+ PHONE_UNCATEGORIZED: { value: 0x00, writable: false, enumerable: true },
+ PHONE_CELLULAR: { value: 0x01, writable: false, enumerable: true },
+ PHONE_CORDLESS: { value: 0x02, writable: false, enumerable: true },
+ PHONE_SMARTPHONE: { value: 0x03, writable: false, enumerable: true },
+ PHONE_MODEM_OR_GATEWAY: { value: 0x04, writable: false, enumerable: true },
+ PHONE_ISDN: { value: 0x05, writable: false, enumerable: true },
+
+ AV_UNRECOGNIZED: { value: 0x00, writable: false, enumerable: true },
+ AV_WEARABLE_HEADSET: { value: 0x01, writable: false, enumerable: true },
+ AV_HANDSFREE: { value: 0x02, writable: false, enumerable: true },
+ AV_MICROPHONE: { value: 0x04, writable: false, enumerable: true },
+ AV_LOUDSPEAKER: { value: 0x05, writable: false, enumerable: true },
+ AV_HEADPHONES: { value: 0x06, writable: false, enumerable: true },
+ AV_PORTABLE_AUDIO: { value: 0x07, writable: false, enumerable: true },
+ AV_CAR_AUDIO: { value: 0x08, writable: false, enumerable: true },
+ AV_SETTOP_BOX: { value: 0x09, writable: false, enumerable: true },
+ AV_HIFI: { value: 0x0a, writable: false, enumerable: true },
+ AV_VCR: { value: 0x0b, writable: false, enumerable: true },
+ AV_VIDEO_CAMERA: { value: 0x0c, writable: false, enumerable: true },
+ AV_CAMCORDER: { value: 0x0d, writable: false, enumerable: true },
+ AV_MONITOR: { value: 0x0e, writable: false, enumerable: true },
+ AV_DISPLAY_AND_LOUDSPEAKER: { value: 0x0f, writable: false, enumerable: true },
+ AV_VIDEO_CONFERENCING: { value: 0x10, writable: false, enumerable: true },
+ AV_GAMING_TOY: { value: 0x12, writable: false, enumerable: true },
+
+ PERIPHERAL_UNCATEGORIZED: { value: 0x00, writable: false, enumerable: true },
+ PERIPHERAL_KEYBOARD: { value: 0x10, writable: false, enumerable: true },
+ PERIPHERAL_POINTING_DEVICE: { value: 0x20, writable: false, enumerable: true },
PERIPHERAL_KEYBOARD_AND_POINTING_DEVICE: {
value: 0x30,
writable: false,
enumerable: true
},
- PERIPHERAL_JOYSTICK: {value: 0x01, writable: false, enumerable: true},
- PERIPHERAL_GAMEPAD: {value: 0x02, writable: false, enumerable: true},
- PERIPHERAL_REMOTE_CONTROL: {value: 0x03, writable: false, enumerable: true},
- PERIPHERAL_SENSING_DEVICE: {value: 0x04, writable: false, enumerable: true},
- PERIPHERAL_DEGITIZER_TABLET: {value: 0x05, writable: false, enumerable: true},
- PERIPHERAL_CARD_READER: {value: 0x06, writable: false, enumerable: true},
- PERIPHERAL_DIGITAL_PEN: {value: 0x07, writable: false, enumerable: true},
- PERIPHERAL_HANDHELD_SCANNER: {value: 0x08, writable: false, enumerable: true},
- PERIPHERAL_HANDHELD_INPUT_DEVICE: {value: 0x09, writable: false, enumerable: true},
-
- IMAGING_UNCATEGORIZED: {value: 0x00, writable: false, enumerable: true},
- IMAGING_DISPLAY: {value: 0x04, writable: false, enumerable: true},
- IMAGING_CAMERA: {value: 0x08, writable: false, enumerable: true},
- IMAGING_SCANNER: {value: 0x10, writable: false, enumerable: true},
- IMAGING_PRINTER: {value: 0x20, writable: false, enumerable: true},
-
- WEARABLE_WRITST_WATCH: {value: 0x01, writable: false, enumerable: true},
- WEARABLE_PAGER: {value: 0x02, writable: false, enumerable: true},
- WEARABLE_JACKET: {value: 0x03, writable: false, enumerable: true},
- WEARABLE_HELMET: {value: 0x04, writable: false, enumerable: true},
- WEARABLE_GLASSES: {value: 0x05, writable: false, enumerable: true},
-
- TOY_ROBOT: {value: 0x01, writable: false, enumerable: true},
- TOY_VEHICLE: {value: 0x02, writable: false, enumerable: true},
- TOY_DOLL: {value: 0x03, writable: false, enumerable: true},
- TOY_CONTROLLER: {value: 0x04, writable: false, enumerable: true},
- TOY_GAME: {value: 0x05, writable: false, enumerable: true},
-
- HEALTH_UNDEFINED: {value: 0x00, writable: false, enumerable: true},
- HEALTH_BLOOD_PRESSURE_MONITOR: {value: 0x01, writable: false, enumerable: true},
- HEALTH_THERMOMETER: {value: 0x02, writable: false, enumerable: true},
- HEALTH_WEIGHING_SCALE: {value: 0x03, writable: false, enumerable: true},
- HEALTH_GLUCOSE_METER: {value: 0x04, writable: false, enumerable: true},
- HEALTH_PULSE_OXIMETER: {value: 0x05, writable: false, enumerable: true},
- HEALTH_PULSE_RATE_MONITOR: {value: 0x06, writable: false, enumerable: true},
- HEALTH_DATA_DISPLAY: {value: 0x07, writable: false, enumerable: true},
- HEALTH_STEP_COUNTER: {value: 0x08, writable: false, enumerable: true},
- HEALTH_BODY_COMPOSITION_ANALYZER: {value: 0x09, writable: false, enumerable: true},
- HEALTH_PEAK_FLOW_MONITOR: {value: 0x0A, writable: false, enumerable: true},
- HEALTH_MEDICATION_MONITOR: {value: 0x0B, writable: false, enumerable: true},
- HEALTH_KNEE_PROSTHESIS: {value: 0x0C, writable: false, enumerable: true},
- HEALTH_ANKLE_PROSTHESIS: {value: 0x0D, writable: false, enumerable: true}
+ PERIPHERAL_JOYSTICK: { value: 0x01, writable: false, enumerable: true },
+ PERIPHERAL_GAMEPAD: { value: 0x02, writable: false, enumerable: true },
+ PERIPHERAL_REMOTE_CONTROL: { value: 0x03, writable: false, enumerable: true },
+ PERIPHERAL_SENSING_DEVICE: { value: 0x04, writable: false, enumerable: true },
+ PERIPHERAL_DEGITIZER_TABLET: { value: 0x05, writable: false, enumerable: true },
+ PERIPHERAL_CARD_READER: { value: 0x06, writable: false, enumerable: true },
+ PERIPHERAL_DIGITAL_PEN: { value: 0x07, writable: false, enumerable: true },
+ PERIPHERAL_HANDHELD_SCANNER: { value: 0x08, writable: false, enumerable: true },
+ PERIPHERAL_HANDHELD_INPUT_DEVICE: {
+ value: 0x09,
+ writable: false,
+ enumerable: true
+ },
+
+ IMAGING_UNCATEGORIZED: { value: 0x00, writable: false, enumerable: true },
+ IMAGING_DISPLAY: { value: 0x04, writable: false, enumerable: true },
+ IMAGING_CAMERA: { value: 0x08, writable: false, enumerable: true },
+ IMAGING_SCANNER: { value: 0x10, writable: false, enumerable: true },
+ IMAGING_PRINTER: { value: 0x20, writable: false, enumerable: true },
+
+ WEARABLE_WRITST_WATCH: { value: 0x01, writable: false, enumerable: true },
+ WEARABLE_PAGER: { value: 0x02, writable: false, enumerable: true },
+ WEARABLE_JACKET: { value: 0x03, writable: false, enumerable: true },
+ WEARABLE_HELMET: { value: 0x04, writable: false, enumerable: true },
+ WEARABLE_GLASSES: { value: 0x05, writable: false, enumerable: true },
+
+ TOY_ROBOT: { value: 0x01, writable: false, enumerable: true },
+ TOY_VEHICLE: { value: 0x02, writable: false, enumerable: true },
+ TOY_DOLL: { value: 0x03, writable: false, enumerable: true },
+ TOY_CONTROLLER: { value: 0x04, writable: false, enumerable: true },
+ TOY_GAME: { value: 0x05, writable: false, enumerable: true },
+
+ HEALTH_UNDEFINED: { value: 0x00, writable: false, enumerable: true },
+ HEALTH_BLOOD_PRESSURE_MONITOR: { value: 0x01, writable: false, enumerable: true },
+ HEALTH_THERMOMETER: { value: 0x02, writable: false, enumerable: true },
+ HEALTH_WEIGHING_SCALE: { value: 0x03, writable: false, enumerable: true },
+ HEALTH_GLUCOSE_METER: { value: 0x04, writable: false, enumerable: true },
+ HEALTH_PULSE_OXIMETER: { value: 0x05, writable: false, enumerable: true },
+ HEALTH_PULSE_RATE_MONITOR: { value: 0x06, writable: false, enumerable: true },
+ HEALTH_DATA_DISPLAY: { value: 0x07, writable: false, enumerable: true },
+ HEALTH_STEP_COUNTER: { value: 0x08, writable: false, enumerable: true },
+ HEALTH_BODY_COMPOSITION_ANALYZER: {
+ value: 0x09,
+ writable: false,
+ enumerable: true
+ },
+ HEALTH_PEAK_FLOW_MONITOR: { value: 0x0a, writable: false, enumerable: true },
+ HEALTH_MEDICATION_MONITOR: { value: 0x0b, writable: false, enumerable: true },
+ HEALTH_KNEE_PROSTHESIS: { value: 0x0c, writable: false, enumerable: true },
+ HEALTH_ANKLE_PROSTHESIS: { value: 0x0d, writable: false, enumerable: true }
});
};
// class BluetoothClassDeviceService ///////////////////////////////////////
var BluetoothClassDeviceService = function() {
Object.defineProperties(this, {
- LIMITED_DISCOVERABILITY: {value: 0x0001, writable: false, enumerable: true},
- POSITIONING: {value: 0x0008, writable: false, enumerable: true},
- NETWORKING: {value: 0x0010, writable: false, enumerable: true},
- RENDERING: {value: 0x0020, writable: false, enumerable: true},
- CAPTURING: {value: 0x0040, writable: false, enumerable: true},
- OBJECT_TRANSFER: {value: 0x0080, writable: false, enumerable: true},
- AUDIO: {value: 0x0100, writable: false, enumerable: true},
- TELEPHONY: {value: 0x0200, writable: false, enumerable: true},
- INFORMATION: {value: 0x0400, writable: false, enumerable: true}
+ LIMITED_DISCOVERABILITY: { value: 0x0001, writable: false, enumerable: true },
+ POSITIONING: { value: 0x0008, writable: false, enumerable: true },
+ NETWORKING: { value: 0x0010, writable: false, enumerable: true },
+ RENDERING: { value: 0x0020, writable: false, enumerable: true },
+ CAPTURING: { value: 0x0040, writable: false, enumerable: true },
+ OBJECT_TRANSFER: { value: 0x0080, writable: false, enumerable: true },
+ AUDIO: { value: 0x0100, writable: false, enumerable: true },
+ TELEPHONY: { value: 0x0200, writable: false, enumerable: true },
+ INFORMATION: { value: 0x0400, writable: false, enumerable: true }
});
};
-//class tizen.BluetoothLEServiceData ////////////////////////////////////////////////////
+//class tizen.BluetoothLEServiceData //////////////////////////
tizen.BluetoothLEServiceData = function(d) {
- AV.isConstructorCall(this, tizen.BluetoothLEServiceData);
- var uuid_ = '';
- var data_ = '';
-
- Object.defineProperties(this, {
- uuid: {
- enumerable: true,
- get: function() {
- return uuid_;
- },
- set: function(v) {
- uuid_ = Converter.toString(v);
- }
- },
- data: {
- enumerable: true,
- get: function() {
- return data_;
- },
- set: function(v) {
- data_ = Converter.toString(v);
- }
- }
- });
-
- if (arguments.length >= 2) { // public constructor
- this.uuid = arguments[0];
- this.data = arguments[1];
- } else if (d && T.isObject(d)) { // internal constructor
- this.uuid = d.uuid;
- this.data = d.data;
- } else {
- uuid_ = undefined;
- data_ = undefined;
- }
-};
-
-//class BluetoothLEAdvertiseData ////////////////////////////////////////////////////
-tizen.BluetoothLEAdvertiseData = function(dict) {
- AV.isConstructorCall(this, tizen.BluetoothLEAdvertiseData);
- var includeName_ = false;
- var uuids_ = null;
- var solicitationuuids_ = null;
- var appearance_ = null;
- var includeTxPowerLevel_ = false;
- var serviceData_ = null;
- var manufacturerData_ = null;
-
- Object.defineProperties(this, {
- includeName: {
- enumerable: true,
- get: function() {
- return includeName_;
- },
- set: function(v) {
- includeName_ = Converter.toBoolean(v, true);
- }
- },
- uuids: {
- enumerable: true,
- get: function() {
- return uuids_;
- },
- set: function(v) {
- if (T.isNull(v)) {
- uuids_ = v;
- } else if (T.isArray(v)) {
- for (var i = 0; i < v.length; ++i) {
- if (!T.isString(v[i])) {
- v[i] = Converter.toString(v[i]);
+ AV.isConstructorCall(this, tizen.BluetoothLEServiceData);
+ var uuid_ = '';
+ var data_ = '';
+
+ Object.defineProperties(this, {
+ uuid: {
+ enumerable: true,
+ get: function() {
+ return uuid_;
+ },
+ set: function(v) {
+ uuid_ = Converter.toString(v);
+ }
+ },
+ data: {
+ enumerable: true,
+ get: function() {
+ return data_;
+ },
+ set: function(v) {
+ data_ = Converter.toString(v);
}
- }
- uuids_ = v;
}
- }
- },
- solicitationuuids: {
- enumerable: true,
- get: function() {
- return solicitationuuids_;
- },
- set: function(v) {
- if (T.isNull(v)) {
- solicitationuuids_ = v;
- } else if (T.isArray(v)) {
- for (var i = 0; i < v.length; ++i) {
- if (!T.isString(v[i])) {
- v[i] = Converter.toString(v[i]);
+ });
+
+ if (arguments.length >= 2) {
+ // public constructor
+ this.uuid = arguments[0];
+ this.data = arguments[1];
+ } else if (d && T.isObject(d)) {
+ // internal constructor
+ this.uuid = d.uuid;
+ this.data = d.data;
+ } else {
+ uuid_ = undefined;
+ data_ = undefined;
+ }
+};
+
+//class BluetoothLEAdvertiseData //////////////////////////
+tizen.BluetoothLEAdvertiseData = function(dict) {
+ AV.isConstructorCall(this, tizen.BluetoothLEAdvertiseData);
+ var includeName_ = false;
+ var uuids_ = null;
+ var solicitationuuids_ = null;
+ var appearance_ = null;
+ var includeTxPowerLevel_ = false;
+ var serviceData_ = null;
+ var manufacturerData_ = null;
+
+ Object.defineProperties(this, {
+ includeName: {
+ enumerable: true,
+ get: function() {
+ return includeName_;
+ },
+ set: function(v) {
+ includeName_ = Converter.toBoolean(v, true);
+ }
+ },
+ uuids: {
+ enumerable: true,
+ get: function() {
+ return uuids_;
+ },
+ set: function(v) {
+ if (T.isNull(v)) {
+ uuids_ = v;
+ } else if (T.isArray(v)) {
+ for (var i = 0; i < v.length; ++i) {
+ if (!T.isString(v[i])) {
+ v[i] = Converter.toString(v[i]);
+ }
+ }
+ uuids_ = v;
+ }
+ }
+ },
+ solicitationuuids: {
+ enumerable: true,
+ get: function() {
+ return solicitationuuids_;
+ },
+ set: function(v) {
+ if (T.isNull(v)) {
+ solicitationuuids_ = v;
+ } else if (T.isArray(v)) {
+ for (var i = 0; i < v.length; ++i) {
+ if (!T.isString(v[i])) {
+ v[i] = Converter.toString(v[i]);
+ }
+ }
+ solicitationuuids_ = v;
+ }
+ }
+ },
+ appearance: {
+ enumerable: true,
+ get: function() {
+ return appearance_;
+ },
+ set: function(v) {
+ appearance_ = Converter.toUnsignedLong(v, true);
+ }
+ },
+ includeTxPowerLevel: {
+ enumerable: true,
+ get: function() {
+ return includeTxPowerLevel_;
+ },
+ set: function(v) {
+ includeTxPowerLevel_ = Converter.toBoolean(v, true);
+ }
+ },
+ serviceData: {
+ enumerable: true,
+ get: function() {
+ return serviceData_;
+ },
+ set: function(v) {
+ if (T.isNull(v) || v instanceof tizen.BluetoothLEServiceData) {
+ serviceData_ = v;
+ }
+ }
+ },
+ manufacturerData: {
+ enumerable: true,
+ get: function() {
+ return manufacturerData_;
+ },
+ set: function(v) {
+ if (T.isNull(v) || v instanceof tizen.BluetoothLEManufacturerData) {
+ manufacturerData_ = v;
+ }
}
- }
- solicitationuuids_ = v;
}
- }
- },
- appearance: {
- enumerable: true,
- get: function() {
- return appearance_;
- },
- set: function(v) {
- appearance_ = Converter.toUnsignedLong(v, true);
- }
- },
- includeTxPowerLevel: {
- enumerable: true,
- get: function() {
- return includeTxPowerLevel_;
- },
- set: function(v) {
- includeTxPowerLevel_ = Converter.toBoolean(v, true);
- }
- },
- serviceData: {
- enumerable: true,
- get: function() {
- return serviceData_;
- },
- set: function(v) {
- if (T.isNull(v) || (v instanceof tizen.BluetoothLEServiceData)) {
- serviceData_ = v;
- }
- }
- },
- manufacturerData: {
- enumerable: true,
- get: function() {
- return manufacturerData_;
- },
- set: function(v) {
- if (T.isNull(v) || (v instanceof tizen.BluetoothLEManufacturerData)) {
- manufacturerData_ = v;
+ });
+
+ if (T.isObject(dict)) {
+ var o = {};
+
+ // includeName
+ if (T.isNull(dict.includeName) || T.isBoolean(dict.includeName)) {
+ o.includeName = dict.includeName;
+ } else if (!T.isUndefined(dict.includeName)) {
+ return;
}
- }
- }
- });
- if (T.isObject(dict)) {
- var o = {};
+ // uuids
+ if (T.isNull(dict.uuids)) {
+ o.uuids = dict.uuids;
+ } else if (T.isArray(dict.uuids)) {
+ for (var i = 0; i < dict.uuids.length; ++i) {
+ if (!T.isString(dict.uuids[i])) {
+ return;
+ }
+ }
+ o.uuids = dict.uuids;
+ } else if (!T.isUndefined(dict.uuids)) {
+ return;
+ }
+
+ // solicitationuuids
+ if (T.isNull(dict.solicitationuuids)) {
+ o.solicitationuuids = dict.solicitationuuids;
+ } else if (T.isArray(dict.solicitationuuids)) {
+ for (var i = 0; i < dict.solicitationuuids.length; ++i) {
+ if (!T.isString(dict.solicitationuuids[i])) {
+ return;
+ }
+ }
+ o.solicitationuuids = dict.solicitationuuids;
+ } else if (!T.isUndefined(dict.solicitationuuids)) {
+ return;
+ }
- // includeName
- if (T.isNull(dict.includeName) || T.isBoolean(dict.includeName)) {
- o.includeName = dict.includeName;
- } else if (!T.isUndefined(dict.includeName)) {
- return;
- }
+ // appearance
+ if (T.isNull(dict.appearance) || T.isNumber(dict.appearance)) {
+ o.appearance = dict.appearance;
+ } else if (!T.isUndefined(dict.appearance)) {
+ return;
+ }
- // uuids
- if (T.isNull(dict.uuids)) {
- o.uuids = dict.uuids;
- } else if (T.isArray(dict.uuids)) {
- for (var i = 0; i < dict.uuids.length; ++i) {
- if (!T.isString(dict.uuids[i])) {
- return;
+ // includeTxPowerLevel
+ if (T.isNull(dict.includeTxPowerLevel) || T.isBoolean(dict.includeTxPowerLevel)) {
+ o.includeTxPowerLevel = dict.includeTxPowerLevel;
+ } else if (!T.isUndefined(dict.includeTxPowerLevel)) {
+ return;
}
- }
- o.uuids = dict.uuids;
- } else if (!T.isUndefined(dict.uuids)) {
- return;
- }
- // solicitationuuids
- if (T.isNull(dict.solicitationuuids)) {
- o.solicitationuuids = dict.solicitationuuids;
- } else if (T.isArray(dict.solicitationuuids)) {
- for (var i = 0; i < dict.solicitationuuids.length; ++i) {
- if (!T.isString(dict.solicitationuuids[i])) {
- return;
+ // serviceData
+ if (
+ T.isNull(dict.serviceData) ||
+ dict.serviceData instanceof tizen.BluetoothLEServiceData
+ ) {
+ o.serviceData = dict.serviceData;
+ } else if (!T.isUndefined(dict.serviceData)) {
+ return;
}
- }
- o.solicitationuuids = dict.solicitationuuids;
- } else if (!T.isUndefined(dict.solicitationuuids)) {
- return;
- }
- // appearance
- if (T.isNull(dict.appearance) || T.isNumber(dict.appearance)) {
- o.appearance = dict.appearance;
- } else if (!T.isUndefined(dict.appearance)) {
- return;
- }
+ // manufacturerData
+ if (
+ T.isNull(dict.manufacturerData) ||
+ dict.manufacturerData instanceof tizen.BluetoothLEManufacturerData
+ ) {
+ o.manufacturerData = dict.manufacturerData;
+ } else if (!T.isUndefined(dict.manufacturerData)) {
+ return;
+ }
- // includeTxPowerLevel
- if (T.isNull(dict.includeTxPowerLevel) || T.isBoolean(dict.includeTxPowerLevel)) {
- o.includeTxPowerLevel = dict.includeTxPowerLevel;
- } else if (!T.isUndefined(dict.includeTxPowerLevel)) {
- return;
+ for (var prop in o) {
+ if (o.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
+ this[prop] = o[prop];
+ }
+ }
}
+};
- // serviceData
- if (T.isNull(dict.serviceData) || dict.serviceData instanceof tizen.BluetoothLEServiceData) {
- o.serviceData = dict.serviceData;
- } else if (!T.isUndefined(dict.serviceData)) {
- return;
- }
+//class tizen.BluetoothLEManufacturerData //////////////////////////
+tizen.BluetoothLEManufacturerData = function(d) {
+ AV.isConstructorCall(this, tizen.BluetoothLEManufacturerData);
+ var id_ = '';
+ var data_ = '';
- // manufacturerData
- if (T.isNull(dict.manufacturerData) ||
- (dict.manufacturerData instanceof tizen.BluetoothLEManufacturerData)) {
- o.manufacturerData = dict.manufacturerData;
- } else if (!T.isUndefined(dict.manufacturerData)) {
- return;
- }
+ Object.defineProperties(this, {
+ id: {
+ enumerable: true,
+ get: function() {
+ return id_;
+ },
+ set: function(v) {
+ id_ = Converter.toString(v);
+ }
+ },
+ data: {
+ enumerable: true,
+ get: function() {
+ return data_;
+ },
+ set: function(v) {
+ data_ = Converter.toString(v);
+ }
+ }
+ });
- for (var prop in o) {
- if (o.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
- this[prop] = o[prop];
- }
+ if (arguments.length >= 2) {
+ // public constructor
+ this.id = arguments[0];
+ this.data = arguments[1];
+ } else if (d && T.isObject(d)) {
+ // internal constructor
+ this.id = d.id;
+ this.data = d.data;
+ } else {
+ id_ = undefined;
+ data_ = undefined;
}
- }
};
-//class tizen.BluetoothLEManufacturerData ////////////////////////////////////////////////////
-tizen.BluetoothLEManufacturerData = function(d) {
- AV.isConstructorCall(this, tizen.BluetoothLEManufacturerData);
- var id_ = '';
- var data_ = '';
-
- Object.defineProperties(this, {
- id: {
- enumerable: true,
- get: function() {
- return id_;
- },
- set: function(v) {
- id_ = Converter.toString(v);
- }
- },
- data: {
- enumerable: true,
- get: function() {
- return data_;
- },
- set: function(v) {
- data_ = Converter.toString(v);
- }
- }
- });
-
- if (arguments.length >= 2) { // public constructor
- this.id = arguments[0];
- this.data = arguments[1];
- } else if (d && T.isObject(d)) { // internal constructor
- this.id = d.id;
- this.data = d.data;
- } else {
- id_ = undefined;
- data_ = undefined;
- }
-};
-
-// class BluetoothClass ////////////////////////////////////////////////////
+// class BluetoothClass //////////////////////////
var BluetoothClass = function(data) {
var services = [];
if (data) {
@@ -402,46 +419,52 @@ var BluetoothClass = function(data) {
}
Object.defineProperties(this, {
- major : {value: data.major, writable: false, enumerable: true},
- minor : {value: data.minor, writable: false, enumerable: true},
- services : {
+ major: { value: data.major, writable: false, enumerable: true },
+ minor: { value: data.minor, writable: false, enumerable: true },
+ services: {
enumerable: true,
- set : function(){},
- get : function(){ return services.slice(); }
+ set: function() {},
+ get: function() {
+ return services.slice();
+ }
}
});
};
var BluetoothClass_hasService = function() {
- privUtils_.log('Entered BluetoothClass.hasService()');
- privUtils_.checkPrivilegeAccess4Ver("2.4", Privilege.BLUETOOTH, Privilege.BLUETOOTH_GAP);
+ privUtils_.log('Entered BluetoothClass.hasService()');
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.4',
+ Privilege.BLUETOOTH,
+ Privilege.BLUETOOTH_GAP
+ );
- var args = AV.validateMethod(arguments, [
- {
- name : 'service',
- type : AV.Types.UNSIGNED_LONG
- }
- ]);
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'service',
+ type: AV.Types.UNSIGNED_LONG
+ }
+ ]);
- var size = this.services.length;
- for (var i = 0; i < size; i++) {
- if (this.services[i] === args.service) {
- return true;
- }
- }
- return false;
+ var size = this.services.length;
+ for (var i = 0; i < size; i++) {
+ if (this.services[i] === args.service) {
+ return true;
+ }
+ }
+ return false;
};
BluetoothClass.prototype.hasService = function() {
return BluetoothClass_hasService.apply(this, arguments);
};
-// class BluetoothSocket ////////////////////////////////////////////////////
+// class BluetoothSocket //////////////////////////
var _BLUETOOTH_SOCKET_STATE_CLOSED = 'CLOSED';
function BluetoothSocketListeners() {
var that = this;
- this.socketCallback = function (data) {
+ this.socketCallback = function(data) {
var event = data;
var socket = that.sockets[event.id];
@@ -450,7 +473,9 @@ function BluetoothSocketListeners() {
// no more events
that.removeListener(event.id);
// change state
- Object.defineProperty(socket, 'state', {value : _BLUETOOTH_SOCKET_STATE_CLOSED});
+ Object.defineProperty(socket, 'state', {
+ value: _BLUETOOTH_SOCKET_STATE_CLOSED
+ });
}
var callback = socket[event.event];
@@ -485,12 +510,21 @@ var _bluetoothSocketListeners = new BluetoothSocketListeners();
var BluetoothSocket = function(data) {
Object.defineProperties(this, {
- uuid : {value: data.uuid, writable: false, enumerable: true},
- state : {value: data.state, writable: false, enumerable: true, configurable: true},
- peer : {value: new BluetoothDevice(data.peer), writable: false, enumerable: true},
- onmessage : {value: null, writable: true, enumerable: true},
- onclose : {value: null, writable: true, enumerable: true},
- _id : {value: data.id, writable: false, enumerable: false}
+ uuid: { value: data.uuid, writable: false, enumerable: true },
+ state: {
+ value: data.state,
+ writable: false,
+ enumerable: true,
+ configurable: true
+ },
+ peer: {
+ value: new BluetoothDevice(data.peer),
+ writable: false,
+ enumerable: true
+ },
+ onmessage: { value: null, writable: true, enumerable: true },
+ onclose: { value: null, writable: true, enumerable: true },
+ _id: { value: data.id, writable: false, enumerable: false }
});
_bluetoothSocketListeners.addListener(this);
@@ -501,15 +535,15 @@ BluetoothSocket.prototype.writeData = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'data',
- type : AV.Types.ARRAY,
- values : AV.Types.BYTE
+ name: 'data',
+ type: AV.Types.ARRAY,
+ values: AV.Types.BYTE
}
]);
var callArgs = {
- id : this._id,
- data : args.data
+ id: this._id,
+ data: args.data
};
var result = native.callSync('BluetoothSocket_writeData', callArgs);
@@ -525,7 +559,7 @@ BluetoothSocket.prototype.readData = function() {
privUtils_.log('Entered BluetoothSocket.readData()');
var callArgs = {
- id : this._id
+ id: this._id
};
var result = native.callSync('BluetoothSocket_readData', callArgs);
@@ -542,7 +576,7 @@ BluetoothSocket.prototype.close = function() {
if (_BLUETOOTH_SOCKET_STATE_CLOSED !== this.state) {
var callArgs = {
- id : this._id
+ id: this._id
};
var result = native.callSync('BluetoothSocket_close', callArgs);
@@ -552,80 +586,94 @@ BluetoothSocket.prototype.close = function() {
}
// change state
- Object.defineProperty(this, 'state', { value : _BLUETOOTH_SOCKET_STATE_CLOSED });
+ Object.defineProperty(this, 'state', { value: _BLUETOOTH_SOCKET_STATE_CLOSED });
}
};
-//class BluetoothLEDevice ////////////////////////////////////////////////////
+//class BluetoothLEDevice //////////////////////////
var BluetoothLEDevice = function(data) {
- var address = "", name = null, txpowerlevel = null, appearance = null, uuids = null,
- solicitationuuids = null, serviceData = null, manufacturerData = null, rssi = null;
+ var address = '',
+ name = null,
+ txpowerlevel = null,
+ appearance = null,
+ uuids = null,
+ solicitationuuids = null,
+ serviceData = null,
+ manufacturerData = null,
+ rssi = null;
if (data) {
- address = data.address;
- name = data.name || null;
- txpowerlevel = data.txpowerlevel || null;
- appearance = data.appearance || null;
- uuids = data.uuids || null;
- solicitationuuids = data.solicitationuuids || null;
- if (data.serviceData) {
- data.serviceData.forEach(function(d) {
- serviceData.push(new tizen.BluetoothLEServiceData(d));
- });
- }
- if (data.manufacturerData) {
- manufacturerData = new tizen.BluetoothLEManufacturerData(data.manufacturerData);
- }
- if (data.rssi) {
- rssi = data.rssi;
- }
+ address = data.address;
+ name = data.name || null;
+ txpowerlevel = data.txpowerlevel || null;
+ appearance = data.appearance || null;
+ uuids = data.uuids || null;
+ solicitationuuids = data.solicitationuuids || null;
+ if (data.serviceData) {
+ data.serviceData.forEach(function(d) {
+ serviceData.push(new tizen.BluetoothLEServiceData(d));
+ });
+ }
+ if (data.manufacturerData) {
+ manufacturerData = new tizen.BluetoothLEManufacturerData(
+ data.manufacturerData
+ );
+ }
+ if (data.rssi) {
+ rssi = data.rssi;
+ }
}
Object.defineProperties(this, {
- address : {value: address, writable: false, enumerable: true},
- name : {value: name, writable: false, enumerable: true},
- txpowerlevel : {value: txpowerlevel, writable: false, enumerable: true},
- appearance : {value: appearance, writable: false, enumerable: true},
- uuids : {
+ address: { value: address, writable: false, enumerable: true },
+ name: { value: name, writable: false, enumerable: true },
+ txpowerlevel: { value: txpowerlevel, writable: false, enumerable: true },
+ appearance: { value: appearance, writable: false, enumerable: true },
+ uuids: {
enumerable: true,
- set : function(){},
- get : function(){
- var service_uuids = uuids ? uuids.slice() : null;
- return service_uuids;
+ set: function() {},
+ get: function() {
+ var service_uuids = uuids ? uuids.slice() : null;
+ return service_uuids;
}
},
- solicitationuuids : {
+ solicitationuuids: {
enumerable: true,
- set : function(){},
- get : function(){ return solicitationuuids ? solicitationuuids.slice() : null; }
+ set: function() {},
+ get: function() {
+ return solicitationuuids ? solicitationuuids.slice() : null;
+ }
},
- serviceData : {
+ serviceData: {
enumerable: true,
- set : function(){},
- get : function(){ return serviceData ? serviceData.slice() : null; }
+ set: function() {},
+ get: function() {
+ return serviceData ? serviceData.slice() : null;
+ }
},
- manufacturerData : {
+ manufacturerData: {
value: manufacturerData,
writable: false,
- enumerable: true},
- rssi : {value: rssi, writable: false, enumerable: true}
+ enumerable: true
+ },
+ rssi: { value: rssi, writable: false, enumerable: true }
});
};
BluetoothLEDevice.prototype.connect = function() {
privUtils_.log('Entered BluetoothLEDevice.connect()');
var args = AV.validateMethod(arguments, [
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
@@ -637,26 +685,30 @@ BluetoothLEDevice.prototype.connect = function() {
}
};
// Errors are handled by error callback
- var result = native.call('BluetoothLEDevice_connect', {address : this.address}, callback);
+ var result = native.call(
+ 'BluetoothLEDevice_connect',
+ { address: this.address },
+ callback
+ );
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
BluetoothLEDevice.prototype.disconnect = function() {
privUtils_.log('Entered BluetoothLEDevice.disconnect()');
var args = AV.validateMethod(arguments, [
- {
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
- },
- {
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callback = function(result) {
@@ -667,7 +719,11 @@ BluetoothLEDevice.prototype.disconnect = function() {
}
};
- var result = native.call('BluetoothLEDevice_disconnect', {address : this.address}, callback);
+ var result = native.call(
+ 'BluetoothLEDevice_disconnect',
+ { address: this.address },
+ callback
+ );
if (native.isFailure(result)) {
throw native.getErrorObject(result);
}
@@ -683,8 +739,8 @@ BluetoothLEDevice.prototype.getService = function() {
]);
var callArgs = {
- uuid : args.uuid,
- address : this.address
+ uuid: args.uuid,
+ address: this.address
};
var result = native.callSync('BluetoothLEDevice_getService', callArgs);
@@ -696,19 +752,19 @@ BluetoothLEDevice.prototype.getService = function() {
};
BluetoothLEDevice.prototype.getServiceAllUuids = function() {
- privUtils_.log('Entered BluetoothLEDevice.getServiceAllUuids()');
+ privUtils_.log('Entered BluetoothLEDevice.getServiceAllUuids()');
- var callArgs = {
- address : this.address
- };
+ var callArgs = {
+ address: this.address
+ };
- var result = native.callSync('BluetoothLEDevice_getServiceAllUuids', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var uuids = native.getResultObject(result);
- return uuids;
- }
+ var result = native.callSync('BluetoothLEDevice_getServiceAllUuids', callArgs);
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var uuids = native.getResultObject(result);
+ return uuids;
+ }
};
BluetoothLEDevice.prototype.addConnectStateChangeListener = function() {
@@ -727,7 +783,7 @@ BluetoothLEDevice.prototype.addConnectStateChangeListener = function() {
if (event.address === that.address && args.listener[event.action]) {
args.listener[event.action](that);
}
- }
+ };
var watchId = _bleConnectChangeListener.addListener(func);
@@ -747,7 +803,7 @@ BluetoothLEDevice.prototype.removeConnectStateChangeListener = function() {
_bleConnectChangeListener.removeListener(args.watchID);
};
-// class BluetoothDevice ////////////////////////////////////////////////////
+// class BluetoothDevice //////////////////////////
var BluetoothDevice = function(data) {
var self = this;
function _getter(field) {
@@ -783,30 +839,34 @@ var BluetoothDevice = function(data) {
}
Object.defineProperties(this, {
- name : {value: data.name, writable: false, enumerable: true},
- address : {value: data.address, writable: false, enumerable: true},
- deviceClass : {value: new BluetoothClass(data.deviceClass),
+ name: { value: data.name, writable: false, enumerable: true },
+ address: { value: data.address, writable: false, enumerable: true },
+ deviceClass: {
+ value: new BluetoothClass(data.deviceClass),
writable: false,
- enumerable: true},
- isBonded : {
+ enumerable: true
+ },
+ isBonded: {
enumerable: true,
- set : function(){},
- get : isBondedGetter
+ set: function() {},
+ get: isBondedGetter
},
- isTrusted : {
+ isTrusted: {
enumerable: true,
- set : function(){},
- get : isTrustedGetter
+ set: function() {},
+ get: isTrustedGetter
},
- isConnected : {
+ isConnected: {
enumerable: true,
- set : function(){},
- get : isConnectedGetter
+ set: function() {},
+ get: isConnectedGetter
},
- uuids : {
+ uuids: {
enumerable: true,
- set : function(){},
- get : function(){ return uuids.slice(); }
+ set: function() {},
+ get: function() {
+ return uuids.slice();
+ }
}
});
};
@@ -816,24 +876,24 @@ BluetoothDevice.prototype.connectToServiceByUUID = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'uuid',
- type : AV.Types.STRING
+ name: 'uuid',
+ type: AV.Types.STRING
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- address : this.address,
- uuid : args.uuid
+ address: this.address,
+ uuid: args.uuid
};
var callback = function(result) {
if (native.isFailure(result)) {
@@ -843,16 +903,20 @@ BluetoothDevice.prototype.connectToServiceByUUID = function() {
}
};
- var result = native.call('BluetoothDevice_connectToServiceByUUID', callArgs, callback);
+ var result = native.call(
+ 'BluetoothDevice_connectToServiceByUUID',
+ callArgs,
+ callback
+ );
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-// class BluetoothServiceHandler ////////////////////////////////////////////////////
+// class BluetoothServiceHandler //////////////////////////
function BluetoothServiceListeners() {
var that = this;
- this.serviceCallback = function (data) {
+ this.serviceCallback = function(data) {
var e = data;
var service = that.services[e.uuid];
var result = new BluetoothSocket(e);
@@ -887,10 +951,12 @@ var _bluetoothServiceListeners = new BluetoothServiceListeners();
var BluetoothServiceHandler = function(data) {
function isConnectedGetter() {
var callArgs = {
- uuid : this.uuid
+ uuid: this.uuid
};
- var result = native.callSync('BluetoothAdapter_isServiceConnected', { uuid : this.uuid });
+ var result = native.callSync('BluetoothAdapter_isServiceConnected', {
+ uuid: this.uuid
+ });
if (native.isFailure(result)) {
return false;
@@ -900,14 +966,14 @@ var BluetoothServiceHandler = function(data) {
}
Object.defineProperties(this, {
- uuid : {value: data.uuid, writable: false, enumerable: true},
- name : {value: data.name, writable: false, enumerable: true},
- isConnected : {
+ uuid: { value: data.uuid, writable: false, enumerable: true },
+ name: { value: data.name, writable: false, enumerable: true },
+ isConnected: {
enumerable: true,
- set : function(){},
- get : isConnectedGetter
+ set: function() {},
+ get: isConnectedGetter
},
- onconnect : {value: null, writable: true, enumerable: true}
+ onconnect: { value: null, writable: true, enumerable: true }
});
_bluetoothServiceListeners.addListener(this);
@@ -917,21 +983,21 @@ BluetoothServiceHandler.prototype.unregister = function() {
privUtils_.log('Entered BluetoothServiceHandler.unregister()');
var args = AV.validateMethod(arguments, [
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- uuid : this.uuid
+ uuid: this.uuid
};
var callback = function(result) {
@@ -944,16 +1010,16 @@ BluetoothServiceHandler.prototype.unregister = function() {
var result = native.call('BluetoothServiceHandler_unregister', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
_bluetoothServiceListeners.removeListener(this.uuid);
};
-// class BluetoothHealthApplication ////////////////////////////////////////////////////
+// class BluetoothHealthApplication //////////////////////////
function BluetoothHealthApplicationListeners() {
var that = this;
- this.appCallback = function (data) {
+ this.appCallback = function(data) {
var event = data;
var app = that.apps[event.id];
@@ -1000,10 +1066,10 @@ var _bluetoothHealthApplicationListeners = new BluetoothHealthApplicationListene
var BluetoothHealthApplication = function(data) {
Object.defineProperties(this, {
- dataType : {value: data.dataType, writable: false, enumerable: true},
- name : {value: data.name, writable: false, enumerable: true},
- onconnect : {value: null, writable: true, enumerable: true},
- _id : {value: data._id, writable: false, enumerable: false}
+ dataType: { value: data.dataType, writable: false, enumerable: true },
+ name: { value: data.name, writable: false, enumerable: true },
+ onconnect: { value: null, writable: true, enumerable: true },
+ _id: { value: data._id, writable: false, enumerable: false }
});
_bluetoothHealthApplicationListeners.addListener(this);
@@ -1013,20 +1079,20 @@ BluetoothHealthApplication.prototype.unregister = function() {
privUtils_.log('Entered BluetoothHealthApplication.unregister()');
var args = AV.validateMethod(arguments, [
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
- var callArgs = {id : this._id};
+ var callArgs = { id: this._id };
var callback = function(result) {
if (native.isFailure(result)) {
@@ -1038,26 +1104,26 @@ BluetoothHealthApplication.prototype.unregister = function() {
var result = native.call('BluetoothHealthApplication_unregister', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
_bluetoothHealthApplicationListeners.removeListener(this._id);
};
-// class BluetoothProfileHandler ////////////////////////////////////////////////////
+// class BluetoothProfileHandler //////////////////////////
var _BluetoothProfileType = {
- HEALTH : 'HEALTH'
+ HEALTH: 'HEALTH'
};
var BluetoothProfileHandler = function(data) {
if (data) {
Object.defineProperties(this, {
- profileType : {value: data.profileType, writable: false, enumerable: true}
+ profileType: { value: data.profileType, writable: false, enumerable: true }
});
}
};
-// class BluetoothHealthProfileHandler ////////////////////////////////////////////////////
+// class BluetoothHealthProfileHandler //////////////////////////
var BluetoothHealthProfileHandler = function(data) {
BluetoothProfileHandler.call(this, data);
};
@@ -1071,41 +1137,47 @@ BluetoothHealthProfileHandler.prototype.registerSinkApplication = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'dataType',
- type : AV.Types.LONG // there's no short type
+ name: 'dataType',
+ type: AV.Types.LONG // there's no short type
},
{
- name : 'name',
- type : AV.Types.STRING
+ name: 'name',
+ type: AV.Types.STRING
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- dataType : args.dataType,
- name : args.name
+ dataType: args.dataType,
+ name: args.name
};
var callback = function(result) {
if (native.isFailure(result)) {
native.callIfPossible(args.errorCallback, native.getErrorObject(result));
} else {
- args.successCallback(new BluetoothHealthApplication(native.getResultObject(result)));
+ args.successCallback(
+ new BluetoothHealthApplication(native.getResultObject(result))
+ );
}
};
- var result = native.call('BluetoothHealthProfileHandler_registerSinkApp', callArgs, callback);
+ var result = native.call(
+ 'BluetoothHealthProfileHandler_registerSinkApp',
+ callArgs,
+ callback
+ );
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -1114,30 +1186,30 @@ BluetoothHealthProfileHandler.prototype.connectToSource = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'peer',
- type : AV.Types.PLATFORM_OBJECT,
- values : BluetoothDevice
+ name: 'peer',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: BluetoothDevice
},
{
- name : 'application',
- type : AV.Types.PLATFORM_OBJECT,
- values : BluetoothHealthApplication
+ name: 'application',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: BluetoothHealthApplication
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- address : args.peer.address,
- appId : args.application._id
+ address: args.peer.address,
+ appId: args.application._id
};
var callback = function(result) {
@@ -1151,28 +1223,33 @@ BluetoothHealthProfileHandler.prototype.connectToSource = function() {
}
};
- var result = native.call('BluetoothHealthProfileHandler_connectToSource', callArgs, callback);
+ var result = native.call(
+ 'BluetoothHealthProfileHandler_connectToSource',
+ callArgs,
+ callback
+ );
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-// class BluetoothHealthChannel ////////////////////////////////////////////////////
+// class BluetoothHealthChannel //////////////////////////
var BluetoothHealthChannel = function(data) {
Object.defineProperties(this, {
- peer : {value: data.peer, writable: false, enumerable: true},
- channelType : {value: data.channelType, writable: false, enumerable: true},
- application : {
+ peer: { value: data.peer, writable: false, enumerable: true },
+ channelType: { value: data.channelType, writable: false, enumerable: true },
+ application: {
value: _bluetoothHealthApplicationListeners.apps[data.appId],
writable: false,
enumerable: true
},
- isConnected : {
+ isConnected: {
value: data.isConnected,
writable: false,
enumerable: true,
- configurable: true},
- _id : {value: data._id, writable: false, enumerable: false}
+ configurable: true
+ },
+ _id: { value: data._id, writable: false, enumerable: false }
});
};
@@ -1181,8 +1258,8 @@ BluetoothHealthChannel.prototype.close = function() {
if (this.isConnected) {
var callArgs = {
- channel : this._id,
- address : this.peer.address
+ channel: this._id,
+ address: this.peer.address
};
var result = native.callSync('BluetoothHealthChannel_close', callArgs);
@@ -1191,7 +1268,7 @@ BluetoothHealthChannel.prototype.close = function() {
throw native.getErrorObject(result);
}
- Object.defineProperty(this, 'isConnected', { value : false });
+ Object.defineProperty(this, 'isConnected', { value: false });
}
};
@@ -1199,15 +1276,15 @@ BluetoothHealthChannel.prototype.sendData = function() {
privUtils_.log('Entered BluetoothHealthChannel.sendData()');
var args = AV.validateMethod(arguments, [
{
- name : 'data',
- type : AV.Types.ARRAY,
- values : AV.Types.BYTE
+ name: 'data',
+ type: AV.Types.ARRAY,
+ values: AV.Types.BYTE
}
]);
var callArgs = {
- channel : this._id,
- data : args.data
+ channel: this._id,
+ data: args.data
};
var result = native.callSync('BluetoothHealthChannel_sendData', callArgs);
@@ -1245,257 +1322,283 @@ function _BluetoothHealthChannelChangeCallback(event) {
}
var BluetoothHealthChannel_setListener = function() {
- privUtils_.log('Entered BluetoothHealthChannel.setListener()');
- privUtils_.checkPrivilegeAccess4Ver("2.4", Privilege.BLUETOOTH, Privilege.BLUETOOTH_HEALTH);
- var args = AV.validateMethod(arguments, [
- {
- name : 'changeCallback',
- type : AV.Types.LISTENER,
- values : ['onmessage', 'onclose']
- }
- ]);
+ privUtils_.log('Entered BluetoothHealthChannel.setListener()');
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.4',
+ Privilege.BLUETOOTH,
+ Privilege.BLUETOOTH_HEALTH
+ );
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'changeCallback',
+ type: AV.Types.LISTENER,
+ values: ['onmessage', 'onclose']
+ }
+ ]);
- if (T.isEmptyObject(_healthListeners)) {
- native.addListener('BluetoothHealthChannelChangeCallback',
- _BluetoothHealthChannelChangeCallback);
- }
- _healthListeners[this._id] = args.changeCallback;
+ if (T.isEmptyObject(_healthListeners)) {
+ native.addListener(
+ 'BluetoothHealthChannelChangeCallback',
+ _BluetoothHealthChannelChangeCallback
+ );
+ }
+ _healthListeners[this._id] = args.changeCallback;
};
-
BluetoothHealthChannel.prototype.setListener = function() {
BluetoothHealthChannel_setListener.apply(this, arguments);
};
-var BluetoothHealthChannel_unsetListener = function() {
- privUtils_.log('Entered BluetoothHealthChannel.unsetListener ()');
- if (T.isEmptyObject(_healthListeners)) {
- privUtils_.checkPrivilegeAccess4Ver("2.4", Privilege.BLUETOOTH, Privilege.BLUETOOTH_HEALTH);
- }
+var BluetoothHealthChannel_unsetListener = function() {
+ privUtils_.log('Entered BluetoothHealthChannel.unsetListener ()');
+ if (T.isEmptyObject(_healthListeners)) {
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.4',
+ Privilege.BLUETOOTH,
+ Privilege.BLUETOOTH_HEALTH
+ );
+ }
- delete _healthListeners[this._id];
+ delete _healthListeners[this._id];
- if (T.isEmptyObject(_healthListeners)) {
- native.removeListener('BluetoothHealthChannelChangeCallback',
- _BluetoothHealthChannelChangeCallback);
- }
+ if (T.isEmptyObject(_healthListeners)) {
+ native.removeListener(
+ 'BluetoothHealthChannelChangeCallback',
+ _BluetoothHealthChannelChangeCallback
+ );
+ }
};
-BluetoothHealthChannel.prototype.unsetListener = function() {
- BluetoothHealthChannel_unsetListener.apply(this, arguments);
+BluetoothHealthChannel.prototype.unsetListener = function() {
+ BluetoothHealthChannel_unsetListener.apply(this, arguments);
};
-
/**
* Creates a manager for specified listener event.
*
* @param {string} name - name of the listener this manager handles
- * @param {function} callback - function to be invoked when event specified by the name fires.
- * This function should return false if the callback doesn't want
- * to handle the event anymore, true otherwise.
+ * @param {function} callback - function to be invoked when event specified by the name
+ * fires.
+ * This function should return false if the callback
+ * doesn't want to handle the event anymore, true otherwise.
* This function should have following signature:
* bool callback(event, successCallback, errorCallback);
*
* @return {object} object which allows to add or remove callbacks for specified listener
*/
function _singleListenerBuilder(name, callback) {
- var listenerName = name;
- var successCallback;
- var errorCallback;
- var callbackFunction = callback;
- var listenerRegistered = false;
+ var listenerName = name;
+ var successCallback;
+ var errorCallback;
+ var callbackFunction = callback;
+ var listenerRegistered = false;
- function innerCallback(event) {
- if (!callbackFunction(event, successCallback, errorCallback)) {
- removeListener();
+ function innerCallback(event) {
+ if (!callbackFunction(event, successCallback, errorCallback)) {
+ removeListener();
+ }
}
- }
- function addListener(s, e) {
- successCallback = s;
- errorCallback = e;
+ function addListener(s, e) {
+ successCallback = s;
+ errorCallback = e;
- if (!listenerRegistered) {
- native.addListener(listenerName, innerCallback);
- listenerRegistered = true;
+ if (!listenerRegistered) {
+ native.addListener(listenerName, innerCallback);
+ listenerRegistered = true;
+ }
}
- }
- function removeListener() {
- if (listenerRegistered) {
- native.removeListener(listenerName, innerCallback);
- listenerRegistered = false;
- }
+ function removeListener() {
+ if (listenerRegistered) {
+ native.removeListener(listenerName, innerCallback);
+ listenerRegistered = false;
+ }
- successCallback = undefined;
- errorCallback = undefined;
- }
+ successCallback = undefined;
+ errorCallback = undefined;
+ }
- return {
- addListener: addListener,
- removeListener: removeListener
- };
+ return {
+ addListener: addListener,
+ removeListener: removeListener
+ };
}
-var _bleScanListener = _singleListenerBuilder('BluetoothLEScanCallback',
- function(event, successCallback, errorCallback) {
-
- var d;
- var ret = true;
+var _bleScanListener = _singleListenerBuilder('BluetoothLEScanCallback', function(
+ event,
+ successCallback,
+ errorCallback
+) {
+ var d;
+ var ret = true;
- switch (event.action) {
+ switch (event.action) {
case 'onsuccess':
- d = new BluetoothLEDevice(event.data);
- break;
+ d = new BluetoothLEDevice(event.data);
+ break;
case 'onerror':
- if (errorCallback) {
- errorCallback(native.getErrorObject(event));
- }
- return ret;
+ if (errorCallback) {
+ errorCallback(native.getErrorObject(event));
+ }
+ return ret;
default:
- privUtils_.log('Unknown mode: ' + event.action);
- return ret;
- }
- if (successCallback) {
- successCallback(d);
- }
-
- return ret;
+ privUtils_.log('Unknown mode: ' + event.action);
+ return ret;
+ }
+ if (successCallback) {
+ successCallback(d);
+ }
+
+ return ret;
});
-var _bleAdvertiseListener = _singleListenerBuilder('BluetoothLEAdvertiseCallback',
+var _bleAdvertiseListener = _singleListenerBuilder(
+ 'BluetoothLEAdvertiseCallback',
function(event, successCallback, errorCallback) {
- var d;
- var ret = true;
-
- switch (event.action) {
- case 'onstate':
- if (successCallback) {
- successCallback(native.getResultObject(event));
- if (native.getResultObject(event) == 'STOPPED') {
- _bleAdvertiseListener.removeListener();
- }
- }
- return ret;
+ var d;
+ var ret = true;
+
+ switch (event.action) {
+ case 'onstate':
+ if (successCallback) {
+ successCallback(native.getResultObject(event));
+ if (native.getResultObject(event) == 'STOPPED') {
+ _bleAdvertiseListener.removeListener();
+ }
+ }
+ return ret;
- case 'onerror':
- if (errorCallback) {
- errorCallback(native.getErrorObject(event));
- }
- return ret;
+ case 'onerror':
+ if (errorCallback) {
+ errorCallback(native.getErrorObject(event));
+ }
+ return ret;
- default:
- privUtils_.log('Unknown mode: ' + event.action);
- return ret;
- }
-});
+ default:
+ privUtils_.log('Unknown mode: ' + event.action);
+ return ret;
+ }
+ }
+);
-//class BluetoothLEAdapter ////////////////////////////////////////////////////
-var BluetoothLEAdapter = function() {
-};
+//class BluetoothLEAdapter //////////////////////////
+var BluetoothLEAdapter = function() {};
BluetoothLEAdapter.prototype.startScan = function() {
- privUtils_.log('Entered BluetoothLEAdapter.startScan()');
- var args = AV.validateMethod(arguments, [{
- name: 'successCallback',
- type: AV.Types.FUNCTION
- }, {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }]);
+ privUtils_.log('Entered BluetoothLEAdapter.startScan()');
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var result = native.callSync('BluetoothLEAdapter_startScan', {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var result = native.callSync('BluetoothLEAdapter_startScan', {});
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
- _bleScanListener.addListener(args.successCallback, args.errorCallback);
+ _bleScanListener.addListener(args.successCallback, args.errorCallback);
};
BluetoothLEAdapter.prototype.stopScan = function() {
- privUtils_.log('Entered BluetoothLEAdapter.stopScan()');
+ privUtils_.log('Entered BluetoothLEAdapter.stopScan()');
- _bleScanListener.removeListener();
+ _bleScanListener.removeListener();
- var result = native.callSync('BluetoothLEAdapter_stopScan', {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var result = native.callSync('BluetoothLEAdapter_stopScan', {});
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
var _BluetoothAdvertisePacketType = {
- ADVERTISE: 'ADVERTISE',
- SCAN_RESPONSE: 'SCAN_RESPONSE'
+ ADVERTISE: 'ADVERTISE',
+ SCAN_RESPONSE: 'SCAN_RESPONSE'
};
var _BluetoothAdvertisingMode = {
- BALANCED: 'BALANCED',
- LOW_LATENCY: 'LOW_LATENCY',
- LOW_ENERGY: 'LOW_ENERGY'
+ BALANCED: 'BALANCED',
+ LOW_LATENCY: 'LOW_LATENCY',
+ LOW_ENERGY: 'LOW_ENERGY'
};
BluetoothLEAdapter.prototype.startAdvertise = function() {
- privUtils_.log('Entered BluetoothLEAdapter.startAdvertise()');
- var args = AV.validateMethod(arguments, [{
- name: 'advertiseData',
- type: AV.Types.PLATFORM_OBJECT,
- values: tizen.BluetoothLEAdvertiseData
- }, {
- name: 'packetType',
- type: AV.Types.ENUM,
- values: T.getValues(_BluetoothAdvertisePacketType)
- }, {
- name: 'successCallback',
- type: AV.Types.FUNCTION
- }, {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }, {
- name: 'mode',
- type: AV.Types.ENUM,
- values: T.getValues(_BluetoothAdvertisingMode),
- optional: true,
- nullable: true
- }, {
- name: 'connectable',
- type: AV.Types.BOOLEAN,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = {
- advertiseData: args.advertiseData,
- packetType: args.packetType,
- mode: T.isNullOrUndefined(args.mode) ? _BluetoothAdvertisingMode.BALANCED : args.mode,
- connectable: T.isNullOrUndefined(args.connectable) ? true : args.connectable
- };
-
- var result = native.callSync('BluetoothLEAdapter_startAdvertise', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
-
- _bleAdvertiseListener.addListener(args.successCallback, args.errorCallback);
+ privUtils_.log('Entered BluetoothLEAdapter.startAdvertise()');
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'advertiseData',
+ type: AV.Types.PLATFORM_OBJECT,
+ values: tizen.BluetoothLEAdvertiseData
+ },
+ {
+ name: 'packetType',
+ type: AV.Types.ENUM,
+ values: T.getValues(_BluetoothAdvertisePacketType)
+ },
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'mode',
+ type: AV.Types.ENUM,
+ values: T.getValues(_BluetoothAdvertisingMode),
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'connectable',
+ type: AV.Types.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {
+ advertiseData: args.advertiseData,
+ packetType: args.packetType,
+ mode: T.isNullOrUndefined(args.mode)
+ ? _BluetoothAdvertisingMode.BALANCED
+ : args.mode,
+ connectable: T.isNullOrUndefined(args.connectable) ? true : args.connectable
+ };
+
+ var result = native.callSync('BluetoothLEAdapter_startAdvertise', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
+
+ _bleAdvertiseListener.addListener(args.successCallback, args.errorCallback);
};
BluetoothLEAdapter.prototype.stopAdvertise = function() {
- privUtils_.log('Entered BluetoothLEAdapter.stopAdvertise()');
+ privUtils_.log('Entered BluetoothLEAdapter.stopAdvertise()');
- var result = native.callSync('BluetoothLEAdapter_stopAdvertise', {});
+ var result = native.callSync('BluetoothLEAdapter_stopAdvertise', {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
-//class BluetoothGATTService ////////////////////////////////////////////////////
+//class BluetoothGATTService //////////////////////////
var BluetoothGATTService = function(data, address) {
var handle_ = data.handle;
var uuid_ = data.uuid;
@@ -1503,8 +1606,10 @@ var BluetoothGATTService = function(data, address) {
var address_ = address || data.address;
function servicesGetter() {
var services = [];
- var result = native.callSync('BluetoothGATTService_getServices',
- {handle: handle_, address : address_});
+ var result = native.callSync('BluetoothGATTService_getServices', {
+ handle: handle_,
+ address: address_
+ });
if (native.isSuccess(result)) {
var resultObject = native.getResultObject(result);
resultObject.forEach(function(s) {
@@ -1515,8 +1620,11 @@ var BluetoothGATTService = function(data, address) {
}
function characteristicsGetter() {
var characteristics = [];
- var result = native.callSync('BluetoothGATTService_getCharacteristics',
- {handle: handle_, uuid: uuid_, address : address_});
+ var result = native.callSync('BluetoothGATTService_getCharacteristics', {
+ handle: handle_,
+ uuid: uuid_,
+ address: address_
+ });
if (native.isSuccess(result)) {
var resultObject = native.getResultObject(result);
resultObject.forEach(function(c) {
@@ -1526,9 +1634,13 @@ var BluetoothGATTService = function(data, address) {
return characteristics;
}
Object.defineProperties(this, {
- uuid : {value: uuid_, writable: false, enumerable: true},
- services : {enumerable: true, set : function() {}, get : servicesGetter},
- characteristics : {enumerable: true, set : function() {}, get : characteristicsGetter}
+ uuid: { value: uuid_, writable: false, enumerable: true },
+ services: { enumerable: true, set: function() {}, get: servicesGetter },
+ characteristics: {
+ enumerable: true,
+ set: function() {},
+ get: characteristicsGetter
+ }
});
};
@@ -1541,219 +1653,232 @@ var toByteArray = function(array) {
return d;
};
-//class BluetoothGATTCharacteristic ////////////////////////////////////////////////////
+//class BluetoothGATTCharacteristic //////////////////////////
var BluetoothGATTCharacteristic = function(data, address) {
- var handle_ = data.handle;
- var descriptors_ = [];
- var isBroadcast_ = false;
- var hasExtendedProperties_ = false;
- var isNotify_ = false;
- var isIndication_ = false;
- var isReadable_ = false;
- var isSignedWrite_ = false;
- var isWritable_ = false;
- var isWriteNoResponse_ = false;
- //address_ is needed to control if device is still connected
- var address_ = address;
-
- if (T.isObject(data)) {
- data.descriptors.forEach(function(dd) {
- descriptors_.push(new BluetoothGATTDescriptor(dd, address_));
- });
- isBroadcast_ = data.isBroadcast;
- hasExtendedProperties_ = data.hasExtendedProperties;
- isNotify_ = data.isNotify;
- isIndication_ = data.isIndication;
- isReadable_ = data.isReadable;
- isSignedWrite_ = data.isSignedWrite;
- isWritable_ = data.isWritable;
- isWriteNoResponse_ = data.isWriteNoResponse;
- }
-
- Object.defineProperties(this, {
- descriptors: {
- enumerable: true,
- get: function() {
- return descriptors_.slice();
- },
- set: function() {
- }
- },
- isBroadcast: {
- enumerable: true,
- get: function() {
- return isBroadcast_;
- },
- set: function() {
- }
- },
- hasExtendedProperties: {
- enumerable: true,
- get: function() {
- return hasExtendedProperties_;
- },
- set: function() {
- }
- },
- isNotify: {
- enumerable: true,
- get: function() {
- return isNotify_;
- },
- set: function() {
- }
- },
- isIndication: {
- enumerable: true,
- get: function() {
- return isIndication_;
- },
- set: function() {
- }
- },
- isReadable: {
- enumerable: true,
- get: function() {
- return isReadable_;
- },
- set: function() {
- }
- },
- isSignedWrite: {
- enumerable: true,
- get: function() {
- return isSignedWrite_;
- },
- set: function() {
- }
- },
- isWritable: {
- enumerable: true,
- get: function() {
- return isWritable_;
- },
- set: function() {
- }
- },
- isWriteNoResponse: {
- enumerable: true,
- get: function() {
- return isWriteNoResponse_;
- },
- set: function() {
- }
- }
- });
-
- this.readValue = function() {
- privUtils_.log('Entered BluetoothGATTCharacteristic.readValue()');
- var args = AV.validateMethod(arguments, [{
- name: 'successCallback',
- type: AV.Types.FUNCTION
- }, {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var d = toByteArray(native.getResultObject(result));
- args.successCallback(d);
+ var handle_ = data.handle;
+ var descriptors_ = [];
+ var isBroadcast_ = false;
+ var hasExtendedProperties_ = false;
+ var isNotify_ = false;
+ var isIndication_ = false;
+ var isReadable_ = false;
+ var isSignedWrite_ = false;
+ var isWritable_ = false;
+ var isWriteNoResponse_ = false;
+ //address_ is needed to control if device is still connected
+ var address_ = address;
+
+ if (T.isObject(data)) {
+ data.descriptors.forEach(function(dd) {
+ descriptors_.push(new BluetoothGATTDescriptor(dd, address_));
+ });
+ isBroadcast_ = data.isBroadcast;
+ hasExtendedProperties_ = data.hasExtendedProperties;
+ isNotify_ = data.isNotify;
+ isIndication_ = data.isIndication;
+ isReadable_ = data.isReadable;
+ isSignedWrite_ = data.isSignedWrite;
+ isWritable_ = data.isWritable;
+ isWriteNoResponse_ = data.isWriteNoResponse;
+ }
+
+ Object.defineProperties(this, {
+ descriptors: {
+ enumerable: true,
+ get: function() {
+ return descriptors_.slice();
+ },
+ set: function() {}
+ },
+ isBroadcast: {
+ enumerable: true,
+ get: function() {
+ return isBroadcast_;
+ },
+ set: function() {}
+ },
+ hasExtendedProperties: {
+ enumerable: true,
+ get: function() {
+ return hasExtendedProperties_;
+ },
+ set: function() {}
+ },
+ isNotify: {
+ enumerable: true,
+ get: function() {
+ return isNotify_;
+ },
+ set: function() {}
+ },
+ isIndication: {
+ enumerable: true,
+ get: function() {
+ return isIndication_;
+ },
+ set: function() {}
+ },
+ isReadable: {
+ enumerable: true,
+ get: function() {
+ return isReadable_;
+ },
+ set: function() {}
+ },
+ isSignedWrite: {
+ enumerable: true,
+ get: function() {
+ return isSignedWrite_;
+ },
+ set: function() {}
+ },
+ isWritable: {
+ enumerable: true,
+ get: function() {
+ return isWritable_;
+ },
+ set: function() {}
+ },
+ isWriteNoResponse: {
+ enumerable: true,
+ get: function() {
+ return isWriteNoResponse_;
+ },
+ set: function() {}
}
- };
+ });
- var callArgs = {handle : handle_, address : address_};
+ this.readValue = function() {
+ privUtils_.log('Entered BluetoothGATTCharacteristic.readValue()');
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var d = toByteArray(native.getResultObject(result));
+ args.successCallback(d);
+ }
+ };
- var result = native.call('BluetoothGATT_readValue', callArgs, callback);
+ var callArgs = { handle: handle_, address: address_ };
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
- };
+ var result = native.call('BluetoothGATT_readValue', callArgs, callback);
- this.writeValue = function() {
- privUtils_.log('Entered BluetoothGATTCharacteristic.writeValue()');
- var args = AV.validateMethod(arguments, [{
- name: 'value',
- type: AV.Types.ARRAY,
- values: AV.Types.BYTE
- }, {
- name: 'successCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }, {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callback = function(result) {
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- native.callIfPossible(args.successCallback);
+ throw native.getErrorObject(result);
}
- };
+ };
- var callArgs = { handle : handle_, value: toByteArray(args.value), address : address_ };
+ this.writeValue = function() {
+ privUtils_.log('Entered BluetoothGATTCharacteristic.writeValue()');
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'value',
+ type: AV.Types.ARRAY,
+ values: AV.Types.BYTE
+ },
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var result = native.call('BluetoothGATT_writeValue', callArgs, callback);
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ };
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var callArgs = {
+ handle: handle_,
+ value: toByteArray(args.value),
+ address: address_
+ };
+
+ var result = native.call('BluetoothGATT_writeValue', callArgs, callback);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
var addValueChangeListener = function() {
- privUtils_.log('Entered BluetoothGATTCharacteristic.addValueChangeListener()');
- privUtils_.checkPrivilegeAccess4Ver("2.4", Privilege.BLUETOOTH, Privilege.BLUETOOTH_ADMIN);
- var args = AV.validateMethod(arguments, [{
- name: 'callback',
- type: AV.Types.FUNCTION
- }]);
+ privUtils_.log('Entered BluetoothGATTCharacteristic.addValueChangeListener()');
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.4',
+ Privilege.BLUETOOTH,
+ Privilege.BLUETOOTH_ADMIN
+ );
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'callback',
+ type: AV.Types.FUNCTION
+ }
+ ]);
- var callArgs = { handle: handle_, address : address_ };
+ var callArgs = { handle: handle_, address: address_ };
- var callback = function(event) {
- if (event.handle === handle_) {
- args.callback(toByteArray(native.getResultObject(event)));
- }
- };
+ var callback = function(event) {
+ if (event.handle === handle_) {
+ args.callback(toByteArray(native.getResultObject(event)));
+ }
+ };
- return _bluetoothGATTCharacteristicListener.addListener(callback, callArgs);
+ return _bluetoothGATTCharacteristicListener.addListener(callback, callArgs);
};
this.addValueChangeListener = function() {
- return addValueChangeListener.apply(this, arguments);
+ return addValueChangeListener.apply(this, arguments);
};
this.removeValueChangeListener = function() {
- privUtils_.log('Entered BluetoothGATTCharacteristic.removeValueChangeListener()');
+ privUtils_.log('Entered BluetoothGATTCharacteristic.removeValueChangeListener()');
- var args = AV.validateMethod(arguments, [{
- name: 'watchID',
- type: AV.Types.LONG
- }]);
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'watchID',
+ type: AV.Types.LONG
+ }
+ ]);
- var callArgs = { handle: handle_, address : address_ };
+ var callArgs = { handle: handle_, address: address_ };
- return _bluetoothGATTCharacteristicListener.removeListener(args.watchID, callArgs);
+ return _bluetoothGATTCharacteristicListener.removeListener(
+ args.watchID,
+ callArgs
+ );
};
};
-
/**
* Creates a manager for specified listener event. Manager handles multiple
* registered listeners
*
* @param {string} name - name of the listener this manager handles
- * @param {function} callback - function to be invoked when event specified by the name fires.
+ * @param {function} callback - function to be invoked when event specified by the name
+ * fires.
* This function should have following signature:
* void callback(listener, event);
* @param {string} addListenerId - optional parameter. If specified, this native
@@ -1763,81 +1888,91 @@ var BluetoothGATTCharacteristic = function(data, address) {
* method will be called synchronously when
* listener is removed.
* @param {bool} repeatNativeCall - optional parameter. If specified, the addListenerId
- * and removeListenerId methods will be called synchronously
- * each time listener is added/removed. Otherwise they are
- * going to be called just once: when first listener is added
- * and last listener is removed.
+ * and removeListenerId methods will be called
+ * synchronously each time listener is added/removed.
+ * Otherwise they are going to be called just once: when
+ * first listener is added and last listener is removed.
*
* @return {object} object which allows to add or remove callbacks for specified listener
*/
-function _multipleListenerBuilder(name, callback, addListenerId, removeListenerId, repeatNativeCall) {
- var listenerName = name;
- var addId = addListenerId;
- var removeId = removeListenerId;
- var callbackFunction = callback;
- var listeners = {};
- var nextId = 1;
- var jsListenerRegistered = false;
- var nativeListenerRegistered = false;
- var repeatNativeListenerCall = repeatNativeCall;
-
- function innerCallback(event) {
- for (var watchId in listeners) {
- if (listeners.hasOwnProperty(watchId)) {
- callbackFunction(listeners[watchId], event);
- }
- }
- }
-
- function addListener(callback, args) {
- var id = ++nextId;
-
- if (addId && (!nativeListenerRegistered || repeatNativeListenerCall)) {
- var result = native.callSync(addId, args || {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
- nativeListenerRegistered = true;
+function _multipleListenerBuilder(
+ name,
+ callback,
+ addListenerId,
+ removeListenerId,
+ repeatNativeCall
+) {
+ var listenerName = name;
+ var addId = addListenerId;
+ var removeId = removeListenerId;
+ var callbackFunction = callback;
+ var listeners = {};
+ var nextId = 1;
+ var jsListenerRegistered = false;
+ var nativeListenerRegistered = false;
+ var repeatNativeListenerCall = repeatNativeCall;
+
+ function innerCallback(event) {
+ for (var watchId in listeners) {
+ if (listeners.hasOwnProperty(watchId)) {
+ callbackFunction(listeners[watchId], event);
+ }
+ }
}
- if (!jsListenerRegistered) {
- native.addListener(listenerName, innerCallback);
- jsListenerRegistered = true;
- }
+ function addListener(callback, args) {
+ var id = ++nextId;
- listeners[id] = callback;
- return id;
- }
+ if (addId && (!nativeListenerRegistered || repeatNativeListenerCall)) {
+ var result = native.callSync(addId, args || {});
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
+ nativeListenerRegistered = true;
+ }
- function removeListener(watchId, args) {
- if (listeners.hasOwnProperty(watchId)) {
- delete listeners[watchId];
- }
+ if (!jsListenerRegistered) {
+ native.addListener(listenerName, innerCallback);
+ jsListenerRegistered = true;
+ }
- if (removeId && ((nativeListenerRegistered && T.isEmptyObject(listeners)) || repeatNativeListenerCall)) {
- var result = native.callSync(removeId, args || {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
- nativeListenerRegistered = false;
+ listeners[id] = callback;
+ return id;
}
- if (jsListenerRegistered && T.isEmptyObject(listeners)) {
- native.removeListener(listenerName, innerCallback);
- jsListenerRegistered = false;
+ function removeListener(watchId, args) {
+ if (listeners.hasOwnProperty(watchId)) {
+ delete listeners[watchId];
+ }
+
+ if (
+ removeId &&
+ ((nativeListenerRegistered && T.isEmptyObject(listeners)) ||
+ repeatNativeListenerCall)
+ ) {
+ var result = native.callSync(removeId, args || {});
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
+ nativeListenerRegistered = false;
+ }
+
+ if (jsListenerRegistered && T.isEmptyObject(listeners)) {
+ native.removeListener(listenerName, innerCallback);
+ jsListenerRegistered = false;
+ }
}
- }
- return {
- addListener: addListener,
- removeListener: removeListener
- };
+ return {
+ addListener: addListener,
+ removeListener: removeListener
+ };
}
var _bluetoothGATTCharacteristicListener = _multipleListenerBuilder(
'BluetoothGATTCharacteristicValueChangeListener',
function(listener, event) {
- listener(event);
+ listener(event);
},
'BluetoothGATTCharacteristic_addValueChangeListener',
'BluetoothGATTCharacteristic_removeValueChangeListener',
@@ -1853,81 +1988,90 @@ var _bleConnectChangeListener = _multipleListenerBuilder(
'BluetoothLEDevice_removeConnectStateChangeListener'
);
-//class BluetoothGATTDescriptor ////////////////////////////////////////////////////
+//class BluetoothGATTDescriptor //////////////////////////
var BluetoothGATTDescriptor = function(data, address) {
- var handle_ = data.handle;
- //address_ is needed to control if device is still connected
- var address_ = address;
-
- this.readValue = function() {
- privUtils_.log('Entered BluetoothGATTDescriptor.readValue()');
- var args = AV.validateMethod(arguments, [{
- name: 'successCallback',
- type: AV.Types.FUNCTION
- }, {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var d = toByteArray(native.getResultObject(result));
- args.successCallback(d);
- }
- };
-
- var callArgs = {handle : handle_, address : address_};
+ var handle_ = data.handle;
+ //address_ is needed to control if device is still connected
+ var address_ = address;
+
+ this.readValue = function() {
+ privUtils_.log('Entered BluetoothGATTDescriptor.readValue()');
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var d = toByteArray(native.getResultObject(result));
+ args.successCallback(d);
+ }
+ };
- var result = native.call('BluetoothGATT_readValue', callArgs, callback);
+ var callArgs = { handle: handle_, address: address_ };
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
- };
-
- this.writeValue = function() {
- privUtils_.log('Entered BluetoothGATTDescriptor.writeValue()');
- var args = AV.validateMethod(arguments, [{
- name: 'value',
- type: AV.Types.ARRAY,
- values: AV.Types.BYTE
- }, {
- name: 'successCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }, {
- name: 'errorCallback',
- type: AV.Types.FUNCTION,
- optional: true,
- nullable: true
- }]);
+ var result = native.call('BluetoothGATT_readValue', callArgs, callback);
- var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- native.callIfPossible(args.successCallback);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
- var callArgs = { handle : handle_, value: toByteArray(args.value), address : address_ };
+ this.writeValue = function() {
+ privUtils_.log('Entered BluetoothGATTDescriptor.writeValue()');
+ var args = AV.validateMethod(arguments, [
+ {
+ name: 'value',
+ type: AV.Types.ARRAY,
+ values: AV.Types.BYTE
+ },
+ {
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var result = native.call('BluetoothGATT_writeValue', callArgs, callback);
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ };
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
- };
-};
+ var callArgs = {
+ handle: handle_,
+ value: toByteArray(args.value),
+ address: address_
+ };
+ var result = native.call('BluetoothGATT_writeValue', callArgs, callback);
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
+ };
+};
-// class BluetoothAdapter ////////////////////////////////////////////////////
+// class BluetoothAdapter //////////////////////////
var BluetoothAdapter = function() {
function nameGetter() {
var result = native.callSync('BluetoothAdapter_getName', {});
@@ -1970,25 +2114,25 @@ var BluetoothAdapter = function() {
}
Object.defineProperties(this, {
- name : {
+ name: {
enumerable: true,
- set : function(){},
- get : nameGetter
+ set: function() {},
+ get: nameGetter
},
- address : {
+ address: {
enumerable: true,
- set : function(){},
- get : addressGetter
+ set: function() {},
+ get: addressGetter
},
- powered : {
+ powered: {
enumerable: true,
- set : function(){},
- get : poweredGetter
+ set: function() {},
+ get: poweredGetter
},
- visible : {
+ visible: {
enumerable: true,
- set : function(){},
- get : visibleGetter
+ set: function() {},
+ get: visibleGetter
}
});
};
@@ -1997,25 +2141,25 @@ BluetoothAdapter.prototype.setName = function() {
privUtils_.log('Entered BluetoothAdapter.setName()');
var args = AV.validateMethod(arguments, [
{
- name : 'name',
- type : AV.Types.STRING
+ name: 'name',
+ type: AV.Types.STRING
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- name : args.name
+ name: args.name
};
var callback = function(result) {
@@ -2028,36 +2172,39 @@ BluetoothAdapter.prototype.setName = function() {
var result = native.call('BluetoothAdapter_setName', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
BluetoothAdapter.prototype.setPowered = function() {
privUtils_.log('Entered BluetoothAdapter.setPowered()');
- privUtils_.warn('DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. '
- + 'Let the user turn on/off Bluetooth through the Settings application instead.');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: setPowered() is deprecated and will be removed from ' +
+ 'next release. Let the user turn on/off Bluetooth through the Settings ' +
+ 'application instead.'
+ );
var args = AV.validateMethod(arguments, [
{
- name : 'powered',
- type : AV.Types.BOOLEAN
+ name: 'powered',
+ type: AV.Types.BOOLEAN
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- powered : args.powered
+ powered: args.powered
};
var callback = function(result) {
@@ -2070,44 +2217,46 @@ BluetoothAdapter.prototype.setPowered = function() {
var result = native.call('BluetoothAdapter_setPowered', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-
// This method is deprecated since Tizen 2.3 and will be removed in Tizen 3.0.
BluetoothAdapter.prototype.setVisible = function() {
privUtils_.log('Entered BluetoothAdapter.setVisible()');
- privUtils_.warn('DEPRECATION WARNING: setVisible() is deprecated and will be removed from next release. '
- + 'Let the user change the Bluetooth visibility through the Settings application instead.');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: setVisible() is deprecated and will be removed from ' +
+ 'next release. Let the user change the Bluetooth visibility through the ' +
+ 'Settings application instead.'
+ );
var args = AV.validateMethod(arguments, [
{
- name : 'visible',
- type : AV.Types.BOOLEAN
+ name: 'visible',
+ type: AV.Types.BOOLEAN
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'timeout',
- type : AV.Types.UNSIGNED_LONG,
- optional : true,
- nullable : true
+ name: 'timeout',
+ type: AV.Types.UNSIGNED_LONG,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- visible : args.visible,
+ visible: args.visible
};
if (args.visible === true) {
@@ -2128,7 +2277,7 @@ BluetoothAdapter.prototype.setVisible = function() {
var result = native.call('BluetoothAdapter_setVisible', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -2167,14 +2316,17 @@ BluetoothAdapter.prototype.setChangeListener = function() {
privUtils_.log('Entered BluetoothAdapter.setChangeListener()');
var args = AV.validateMethod(arguments, [
{
- name : 'changeCallback',
- type : AV.Types.LISTENER,
- values : ['onstatechanged', 'onnamechanged', 'onvisibilitychanged']
+ name: 'changeCallback',
+ type: AV.Types.LISTENER,
+ values: ['onstatechanged', 'onnamechanged', 'onvisibilitychanged']
}
]);
if (T.isNullOrUndefined(_listener)) {
- native.addListener('BluetoothAdapterChangeCallback', _BluetoothAdapterChangeCallback);
+ native.addListener(
+ 'BluetoothAdapterChangeCallback',
+ _BluetoothAdapterChangeCallback
+ );
}
_listener = args.changeCallback;
};
@@ -2182,7 +2334,10 @@ BluetoothAdapter.prototype.setChangeListener = function() {
BluetoothAdapter.prototype.unsetChangeListener = function() {
privUtils_.log('Entered BluetoothAdapter.unsetChangeListener()');
if (!T.isNullOrUndefined(_listener)) {
- native.removeListener('BluetoothAdapterChangeCallback', _BluetoothAdapterChangeCallback);
+ native.removeListener(
+ 'BluetoothAdapterChangeCallback',
+ _BluetoothAdapterChangeCallback
+ );
_listener = undefined;
}
};
@@ -2209,15 +2364,19 @@ function _BluetoothDiscoverDevicesSuccessCallback(event) {
case 'onfinished':
var result = e.data;
d = [];
- result.forEach(function (data) {
+ result.forEach(function(data) {
d.push(new BluetoothDevice(data));
});
//remove listeners after discovering
- native.removeListener('BluetoothDiscoverDevicesSuccessCallback',
- _BluetoothDiscoverDevicesSuccessCallback);
- native.removeListener('BluetoothDiscoverDevicesErrorCallback',
- _BluetoothDiscoverDevicesErrorCallback);
+ native.removeListener(
+ 'BluetoothDiscoverDevicesSuccessCallback',
+ _BluetoothDiscoverDevicesSuccessCallback
+ );
+ native.removeListener(
+ 'BluetoothDiscoverDevicesErrorCallback',
+ _BluetoothDiscoverDevicesErrorCallback
+ );
break;
default:
@@ -2241,32 +2400,40 @@ BluetoothAdapter.prototype.discoverDevices = function() {
privUtils_.log('Entered BluetoothAdapter.discoverDevices()');
var args = AV.validateMethod(arguments, [
{
- name : 'successCallback',
- type : AV.Types.LISTENER,
- values : ['onstarted', 'ondevicefound', 'ondevicedisappeared', 'onfinished']
+ name: 'successCallback',
+ type: AV.Types.LISTENER,
+ values: ['onstarted', 'ondevicefound', 'ondevicedisappeared', 'onfinished']
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
_discoverDevicesSuccessCallback = args.successCallback;
_discoverDevicesErrorCallback = args.errorCallback;
- native.addListener('BluetoothDiscoverDevicesSuccessCallback',
- _BluetoothDiscoverDevicesSuccessCallback);
- native.addListener('BluetoothDiscoverDevicesErrorCallback',
- _BluetoothDiscoverDevicesErrorCallback);
+ native.addListener(
+ 'BluetoothDiscoverDevicesSuccessCallback',
+ _BluetoothDiscoverDevicesSuccessCallback
+ );
+ native.addListener(
+ 'BluetoothDiscoverDevicesErrorCallback',
+ _BluetoothDiscoverDevicesErrorCallback
+ );
var result = native.callSync('BluetoothAdapter_discoverDevices', {});
if (native.isFailure(result)) {
- native.removeListener('BluetoothDiscoverDevicesSuccessCallback',
- _BluetoothDiscoverDevicesSuccessCallback);
- native.removeListener('BluetoothDiscoverDevicesErrorCallback',
- _BluetoothDiscoverDevicesErrorCallback);
+ native.removeListener(
+ 'BluetoothDiscoverDevicesSuccessCallback',
+ _BluetoothDiscoverDevicesSuccessCallback
+ );
+ native.removeListener(
+ 'BluetoothDiscoverDevicesErrorCallback',
+ _BluetoothDiscoverDevicesErrorCallback
+ );
throw native.getErrorObject(result);
}
};
@@ -2275,16 +2442,16 @@ BluetoothAdapter.prototype.stopDiscovery = function() {
privUtils_.log('Entered BluetoothAdapter.stopDiscovery()');
var args = AV.validateMethod(arguments, [
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
@@ -2298,7 +2465,7 @@ BluetoothAdapter.prototype.stopDiscovery = function() {
var result = native.call('BluetoothAdapter_stopDiscovery', {}, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -2306,14 +2473,14 @@ BluetoothAdapter.prototype.getKnownDevices = function() {
privUtils_.log('Entered BluetoothAdapter.getKnownDevices()');
var args = AV.validateMethod(arguments, [
{
- name : 'successCallback',
- type : AV.Types.FUNCTION
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
@@ -2323,7 +2490,7 @@ BluetoothAdapter.prototype.getKnownDevices = function() {
} else {
var r = native.getResultObject(result).devices;
var devices = [];
- r.forEach(function (data) {
+ r.forEach(function(data) {
devices.push(new BluetoothDevice(data));
});
args.successCallback(devices);
@@ -2332,7 +2499,7 @@ BluetoothAdapter.prototype.getKnownDevices = function() {
var result = native.call('BluetoothAdapter_getKnownDevices', {}, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -2340,18 +2507,18 @@ BluetoothAdapter.prototype.getDevice = function() {
privUtils_.log('Entered BluetoothAdapter.getDevice()');
var args = AV.validateMethod(arguments, [
{
- name : 'address',
- type : AV.Types.STRING
+ name: 'address',
+ type: AV.Types.STRING
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
@@ -2363,9 +2530,13 @@ BluetoothAdapter.prototype.getDevice = function() {
}
};
- var result = native.call('BluetoothAdapter_getDevice', {address : args.address}, callback);
+ var result = native.call(
+ 'BluetoothAdapter_getDevice',
+ { address: args.address },
+ callback
+ );
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -2373,25 +2544,25 @@ BluetoothAdapter.prototype.createBonding = function() {
privUtils_.log('Entered BluetoothAdapter.createBonding()');
var args = AV.validateMethod(arguments, [
{
- name : 'address',
- type : AV.Types.STRING
+ name: 'address',
+ type: AV.Types.STRING
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : false,
- nullable : false
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: false,
+ nullable: false
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- address : args.address
+ address: args.address
};
var callback = function(result) {
@@ -2404,7 +2575,7 @@ BluetoothAdapter.prototype.createBonding = function() {
var result = native.call('BluetoothAdapter_createBonding', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -2412,25 +2583,25 @@ BluetoothAdapter.prototype.destroyBonding = function() {
privUtils_.log('Entered BluetoothAdapter.destroyBonding()');
var args = AV.validateMethod(arguments, [
{
- name : 'address',
- type : AV.Types.STRING
+ name: 'address',
+ type: AV.Types.STRING
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- address : args.address
+ address: args.address
};
var callback = function(result) {
@@ -2443,7 +2614,7 @@ BluetoothAdapter.prototype.destroyBonding = function() {
var result = native.call('BluetoothAdapter_destroyBonding', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -2451,28 +2622,28 @@ BluetoothAdapter.prototype.registerRFCOMMServiceByUUID = function() {
privUtils_.log('Entered BluetoothAdapter.registerRFCOMMServiceByUUID()');
var args = AV.validateMethod(arguments, [
{
- name : 'uuid',
- type : AV.Types.STRING
+ name: 'uuid',
+ type: AV.Types.STRING
},
{
- name : 'name',
- type : AV.Types.STRING
+ name: 'name',
+ type: AV.Types.STRING
},
{
- name : 'successCallback',
- type : AV.Types.FUNCTION,
+ name: 'successCallback',
+ type: AV.Types.FUNCTION
},
{
- name : 'errorCallback',
- type : AV.Types.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: AV.Types.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
var callArgs = {
- uuid : args.uuid,
- name : args.name
+ uuid: args.uuid,
+ name: args.name
};
var callback = function(result) {
@@ -2485,9 +2656,13 @@ BluetoothAdapter.prototype.registerRFCOMMServiceByUUID = function() {
}
};
- var result = native.call('BluetoothAdapter_registerRFCOMMServiceByUUID', callArgs, callback);
+ var result = native.call(
+ 'BluetoothAdapter_registerRFCOMMServiceByUUID',
+ callArgs,
+ callback
+ );
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
@@ -2496,13 +2671,13 @@ BluetoothAdapter.prototype.getBluetoothProfileHandler = function() {
var args = AV.validateMethod(arguments, [
{
- name : 'profileType',
- type : AV.Types.ENUM,
- values : T.getValues(_BluetoothProfileType)
+ name: 'profileType',
+ type: AV.Types.ENUM,
+ values: T.getValues(_BluetoothProfileType)
}
]);
- var callArgs = {profileType : args.profileType};
+ var callArgs = { profileType: args.profileType };
var result = native.callSync('BluetoothAdapter_getBluetoothProfileHandler', callArgs);
@@ -2514,25 +2689,28 @@ BluetoothAdapter.prototype.getBluetoothProfileHandler = function() {
return new BluetoothHealthProfileHandler(callArgs);
default:
- throw new WebAPIException('NotSupportedError', 'Profile ' + args.profileType + ' is not supported.');
+ throw new WebAPIException(
+ 'NotSupportedError',
+ 'Profile ' + args.profileType + ' is not supported.'
+ );
}
}
};
-// class BluetoothManager ////////////////////////////////////////////////////
+// class BluetoothManager //////////////////////////
var BluetoothManager = function() {
Object.defineProperties(this, {
- deviceMajor : {
+ deviceMajor: {
value: new BluetoothClassDeviceMajor(),
writable: false,
enumerable: true
},
- deviceMinor : {
+ deviceMinor: {
value: new BluetoothClassDeviceMinor(),
writable: false,
enumerable: true
},
- deviceService : {
+ deviceService: {
value: new BluetoothClassDeviceService(),
writable: false,
enumerable: true
@@ -2541,26 +2719,33 @@ var BluetoothManager = function() {
};
var BluetoothManager_getDefaultAdapter = function() {
- privUtils_.checkPrivilegeAccess4Ver("2.4", Privilege.BLUETOOTH, Privilege.BLUETOOTH_GAP);
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.4',
+ Privilege.BLUETOOTH,
+ Privilege.BLUETOOTH_GAP
+ );
- return new BluetoothAdapter();
+ return new BluetoothAdapter();
};
-
BluetoothManager.prototype.getDefaultAdapter = function() {
privUtils_.log('Entered BluetoothManager.getDefaultAdapter()');
return BluetoothManager_getDefaultAdapter();
};
var BluetoothManager_getLEAdapter = function() {
- privUtils_.checkPrivilegeAccess4Ver("2.4", Privilege.BLUETOOTH, Privilege.BLUETOOTH_ADMIN);
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.4',
+ Privilege.BLUETOOTH,
+ Privilege.BLUETOOTH_ADMIN
+ );
- return new BluetoothLEAdapter();
+ return new BluetoothLEAdapter();
};
BluetoothManager.prototype.getLEAdapter = function() {
privUtils_.log('Entered BluetoothManager.getLEAdapter()');
return BluetoothManager_getLEAdapter();
};
-// exports ///////////////////////////////////////////////////////////////////
+// exports /////////////////////////////////////////
exports = new BluetoothManager();
diff --git a/src/bookmark/bookmark_api.js b/src/bookmark/bookmark_api.js
index 7ccf8a14..2470b6cd 100755
--- a/src/bookmark/bookmark_api.js
+++ b/src/bookmark/bookmark_api.js
@@ -19,15 +19,15 @@ var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
function EditManager() {
- this.canEdit = false;
+ this.canEdit = false;
}
EditManager.prototype.allow = function() {
- this.canEdit = true;
+ this.canEdit = true;
};
EditManager.prototype.disallow = function() {
- this.canEdit = false;
+ this.canEdit = false;
};
var _edit = new EditManager();
@@ -35,343 +35,333 @@ var _edit = new EditManager();
function BookmarkManager() {}
BookmarkManager.prototype.get = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'parentFolder',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.BookmarkFolder, tizen.BookmarkItem],
- optional: true,
- nullable: true
- },
- {
- name: 'recursive',
- type: types_.BOOLEAN,
- optional: true,
- nullable: true
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'parentFolder',
+ type: types_.PLATFORM_OBJECT,
+ values: [tizen.BookmarkFolder, tizen.BookmarkItem],
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'recursive',
+ type: types_.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]);
+ var result;
+
+ if (arguments.length === 0 || args.parentFolder === null) {
+ result = provider.getFolderItems(provider.getRootId(), args.recursive);
+ if (!result) throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ return result;
}
- ]);
- var result;
+ if (args.parentFolder.id === null || args.parentFolder.id === 0)
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- if (arguments.length === 0 || args.parentFolder === null) {
- result = provider.getFolderItems(provider.getRootId(), args.recursive);
- if (!result)
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ result = provider.getFolderItems(args.parentFolder.id, args.recursive);
+ if (!result) throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
return result;
- }
- if (args.parentFolder.id === null || args.parentFolder.id === 0)
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
-
- result = provider.getFolderItems(args.parentFolder.id, args.recursive);
- if (!result)
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- return result;
};
BookmarkManager.prototype.add = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'bookmark',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.BookmarkFolder, tizen.BookmarkItem],
- optional: false,
- nullable: false
- },
- {
- name: 'parentFolder',
- type: types_.PLATFORM_OBJECT,
- values: tizen.BookmarkFolder,
- optional: true,
- nullable: true
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'bookmark',
+ type: types_.PLATFORM_OBJECT,
+ values: [tizen.BookmarkFolder, tizen.BookmarkItem],
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'parentFolder',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.BookmarkFolder,
+ optional: true,
+ nullable: true
+ }
+ ]);
+ if (arguments.length == 1 || args.parentFolder === null) {
+ if (args.bookmark.id) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ provider.addToFolder(args.bookmark, provider.getRootId());
+ return;
}
- ]);
- if (arguments.length == 1 || args.parentFolder === null) {
- if (args.bookmark.id) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ if (!args.parentFolder.id) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
}
- provider.addToFolder(args.bookmark, provider.getRootId());
- return;
- }
- if (!args.parentFolder.id) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- }
-
- provider.addToFolder(args.bookmark, args.parentFolder.id);
+ provider.addToFolder(args.bookmark, args.parentFolder.id);
};
BookmarkManager.prototype.remove = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'bookmark',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.BookmarkFolder, tizen.BookmarkItem],
- optional: true,
- nullable: true
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'bookmark',
+ type: types_.PLATFORM_OBJECT,
+ values: [tizen.BookmarkFolder, tizen.BookmarkItem],
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (!arguments.length || args.bookmark === null) {
+ var result = native_.callSync('Bookmark_removeAll');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ return;
}
- ]);
- if (!arguments.length || args.bookmark === null) {
- var result = native_.callSync('Bookmark_removeAll');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (!args.bookmark.id) {
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
}
- return;
- }
-
- if (!args.bookmark.id) {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
- }
-
- var result = native_.isFailure(native_.callSync('Bookmark_remove', {id: args.bookmark.id}));
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.isFailure(
+ native_.callSync('Bookmark_remove', { id: args.bookmark.id })
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- _edit.allow();
- args.bookmark.id = null;
- args.bookmark.parent = undefined;
- _edit.disallow();
+ _edit.allow();
+ args.bookmark.id = null;
+ args.bookmark.parent = undefined;
+ _edit.disallow();
};
function BookmarkProvider() {}
BookmarkProvider.prototype.addToFolder = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'bookmark',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.BookmarkFolder, tizen.BookmarkItem],
- optional: true,
- nullable: true
- },
- {
- name: 'parentId',
- type: types_.DOUBLE,
- optional: false,
- nullable: false}
- ]);
- var ret = native_.callSync('Bookmark_add',
- {
- title: args.bookmark.title,
- url: String(args.bookmark.url),
- parentId: args.parentId,
- type: args.bookmark instanceof tizen.BookmarkFolder ? 1 : 0
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'bookmark',
+ type: types_.PLATFORM_OBJECT,
+ values: [tizen.BookmarkFolder, tizen.BookmarkItem],
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'parentId',
+ type: types_.DOUBLE,
+ optional: false,
+ nullable: false
+ }
+ ]);
+ var ret = native_.callSync('Bookmark_add', {
+ title: args.bookmark.title,
+ url: String(args.bookmark.url),
+ parentId: args.parentId,
+ type: args.bookmark instanceof tizen.BookmarkFolder ? 1 : 0
+ });
+
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
}
- );
-
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
- var ret_id = native_.getResultObject(ret);
- _edit.allow();
- args.bookmark.id = ret_id;
- args.bookmark.parent = this.getFolder(args.parentId);
- _edit.disallow();
+ var ret_id = native_.getResultObject(ret);
+ _edit.allow();
+ args.bookmark.id = ret_id;
+ args.bookmark.parent = this.getFolder(args.parentId);
+ _edit.disallow();
};
BookmarkProvider.prototype.getFolder = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'id',
- type: types_.DOUBLE,
- optional: false,
- nullable: false
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.DOUBLE,
+ optional: false,
+ nullable: false
+ }
+ ]);
+ if (arguments.length === 0 || args.id <= 0) return null;
+ if (args.id == this.getRootId()) return null;
+
+ var ret = native_.callSync('Bookmark_get', {
+ id: args.id,
+ shouldGetItems: 0
+ });
+
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
}
- ]);
- if (arguments.length === 0 || args.id <= 0)
- return null;
- if (args.id == this.getRootId())
- return null;
-
- var ret = native_.callSync('Bookmark_get', {
- id: args.id,
- shouldGetItems: 0
- });
-
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
-
- var folder = native_.getResultObject(ret);
- if (folder === undefined || folder === null) {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
- }
-
- var obj = new tizen.BookmarkFolder(folder[0].title);
- obj.id = folder[0].id;
- obj.parent = this.getFolder(folder[0].parentId);
- return obj;
-};
-BookmarkProvider.prototype.getFolderItems = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'id',
- type: types_.DOUBLE,
- optional: false,
- nullable: false
- },
- {
- name: 'recursive',
- type: types_.BOOLEAN,
- optional: true,
- nullable: true
+ var folder = native_.getResultObject(ret);
+ if (folder === undefined || folder === null) {
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
}
- ]);
- var ret = native_.callSync('Bookmark_get', {
- id: Number(args.id),
- shouldGetItems: 1
- });
+ var obj = new tizen.BookmarkFolder(folder[0].title);
+ obj.id = folder[0].id;
+ obj.parent = this.getFolder(folder[0].parentId);
+ return obj;
+};
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
+BookmarkProvider.prototype.getFolderItems = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.DOUBLE,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'recursive',
+ type: types_.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var ret = native_.callSync('Bookmark_get', {
+ id: Number(args.id),
+ shouldGetItems: 1
+ });
+
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
- var folder = native_.getResultObject(ret);
- if (folder === undefined) {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
- }
+ var folder = native_.getResultObject(ret);
+ if (folder === undefined) {
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
+ }
- var item;
- var obj;
- var result = [];
- var len = folder.length;
+ var item;
+ var obj;
+ var result = [];
+ var len = folder.length;
- for (var i = 0; item = folder[i], i < len; i++) {
- if (Number(item.type) === 0)
- obj = new tizen.BookmarkItem(item.title, item.url);
- else
- obj = new tizen.BookmarkFolder(item.title);
+ for (var i = 0; (item = folder[i]), i < len; i++) {
+ if (Number(item.type) === 0) obj = new tizen.BookmarkItem(item.title, item.url);
+ else obj = new tizen.BookmarkFolder(item.title);
- _edit.allow();
- obj.id = item.id;
- obj.parent = this.getFolder(item.parentId);
- _edit.disallow();
- result.push(obj);
+ _edit.allow();
+ obj.id = item.id;
+ obj.parent = this.getFolder(item.parentId);
+ _edit.disallow();
+ result.push(obj);
- if (args.recursive && Number(item.type) !== 0)
- result = result.concat(this.getFolderItems(item.id, true));
- }
- return result;
+ if (args.recursive && Number(item.type) !== 0)
+ result = result.concat(this.getFolderItems(item.id, true));
+ }
+ return result;
};
BookmarkProvider.prototype.getRootId = function() {
- var ret = native_.callSync('Bookmark_getRootId');
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
- var rootId = native_.getResultObject(ret);
- return Number(rootId);
+ var ret = native_.callSync('Bookmark_getRootId');
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
+ var rootId = native_.getResultObject(ret);
+ return Number(rootId);
};
var provider = new BookmarkProvider();
tizen.BookmarkItem = function() {
- validator_.isConstructorCall(this, tizen.BookmarkItem);
- var args = validator_.validateArgs(arguments, [
- {
- name: 'title',
- type: types_.STRING,
- optional: false
- },
- {
- name: 'url',
- type: types_.STRING,
- optional: false
- }
- ]);
- var parent_;
- var id_ = null;
-
- Object.defineProperties(this, {
- parent: {
- get: function() {
- return parent_;
- },
- set: function(new_parent) {
- if (_edit.canEdit)
- parent_ = new_parent;
- },
- enumerable: true,
- nullable: true
- },
- title: {
- get: function() {
- return args.title;
- },
- enumerable: true,
- nullable: false
- },
- url: {
- get: function() {
- if (args.url === "undefined")
- args.url = undefined;
- return args.url;
- },
- enumerable: true,
- nullable: false
- },
- id: {
- get: function() {
- return id_;
- },
- set: function(new_id) {
- if (_edit.canEdit)
- id_ = new_id;
- },
- enumerable: false,
- nullable: true
- }
- });
+ validator_.isConstructorCall(this, tizen.BookmarkItem);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'title',
+ type: types_.STRING,
+ optional: false
+ },
+ {
+ name: 'url',
+ type: types_.STRING,
+ optional: false
+ }
+ ]);
+ var parent_;
+ var id_ = null;
+
+ Object.defineProperties(this, {
+ parent: {
+ get: function() {
+ return parent_;
+ },
+ set: function(new_parent) {
+ if (_edit.canEdit) parent_ = new_parent;
+ },
+ enumerable: true,
+ nullable: true
+ },
+ title: {
+ get: function() {
+ return args.title;
+ },
+ enumerable: true,
+ nullable: false
+ },
+ url: {
+ get: function() {
+ if (args.url === 'undefined') args.url = undefined;
+ return args.url;
+ },
+ enumerable: true,
+ nullable: false
+ },
+ id: {
+ get: function() {
+ return id_;
+ },
+ set: function(new_id) {
+ if (_edit.canEdit) id_ = new_id;
+ },
+ enumerable: false,
+ nullable: true
+ }
+ });
};
tizen.BookmarkFolder = function() {
- validator_.isConstructorCall(this, tizen.BookmarkFolder);
- var args = validator_.validateArgs(arguments, [
- {
- name: 'title',
- type: types_.STRING,
- optional: false,
- nullable: false
- }
- ]);
-
- var parent_;
- var id_ = null;
-
- Object.defineProperties(this, {
- parent: {
- get: function() {
- return parent_;
- },
- set: function(new_parent) {
- if (_edit.canEdit)
- parent_ = new_parent;
- },
- enumerable: true,
- nullable: true
- },
- title: {
- get: function() {
- return args.title;
- },
- enumerable: true,
- nullable: false
- },
- id: {
- get: function() {
- return id_;
- },
- set: function(new_id) {
- if (_edit.canEdit)
- id_ = new_id;
- },
- enumerable: false,
- nullable: true
- }
- });
+ validator_.isConstructorCall(this, tizen.BookmarkFolder);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'title',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ var parent_;
+ var id_ = null;
+
+ Object.defineProperties(this, {
+ parent: {
+ get: function() {
+ return parent_;
+ },
+ set: function(new_parent) {
+ if (_edit.canEdit) parent_ = new_parent;
+ },
+ enumerable: true,
+ nullable: true
+ },
+ title: {
+ get: function() {
+ return args.title;
+ },
+ enumerable: true,
+ nullable: false
+ },
+ id: {
+ get: function() {
+ return id_;
+ },
+ set: function(new_id) {
+ if (_edit.canEdit) id_ = new_id;
+ },
+ enumerable: false,
+ nullable: true
+ }
+ });
};
exports = new BookmarkManager();
diff --git a/src/calendar/js/calendar.js b/src/calendar/js/calendar.js
index af6ecdcb..0aede5ee 100755
--- a/src/calendar/js/calendar.js
+++ b/src/calendar/js/calendar.js
@@ -15,498 +15,549 @@
*/
var _global = window || global || {};
-
+
var CalendarType = {
- EVENT: 'EVENT',
- TASK: 'TASK'
+ EVENT: 'EVENT',
+ TASK: 'TASK'
};
/**
* For internal use only.
*/
var InternalCalendar = function(data) {
- Object.defineProperties(this, {
- accountId: {
- value: -1,
- writable: true,
- enumerable: true
- },
- id: {
- value: null,
- writable: true,
- enumerable: true
- },
- name: {
- value: null,
- writable: true,
- enumerable: true
- },
- type: {
- value: '',
- writable: true,
- enumerable: true
- },
- isUnified: {
- value: false,
- writable: true,
- enumerable: true
- }
- });
+ Object.defineProperties(this, {
+ accountId: {
+ value: -1,
+ writable: true,
+ enumerable: true
+ },
+ id: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ name: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ type: {
+ value: '',
+ writable: true,
+ enumerable: true
+ },
+ isUnified: {
+ value: false,
+ writable: true,
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
-
// class Calendar
var Calendar = function(accountId, name, type) {
- var _data;
+ var _data;
- validator_.isConstructorCall(this, Calendar);
+ validator_.isConstructorCall(this, Calendar);
- if (arguments[0] instanceof InternalCalendar) {
- _data = arguments[0];
- } else {
- var _accountId = converter_.toLong(accountId);
- var _name = converter_.toString(name);
- var _type = converter_.toString(type);
-
- if (arguments.length < 3) {
- _data = new InternalCalendar();
+ if (arguments[0] instanceof InternalCalendar) {
+ _data = arguments[0];
} else {
- _data = new InternalCalendar({
+ var _accountId = converter_.toLong(accountId);
+ var _name = converter_.toString(name);
+ var _type = converter_.toString(type);
+
+ if (arguments.length < 3) {
+ _data = new InternalCalendar();
+ } else {
+ _data = new InternalCalendar({
accountId: _accountId,
name: _name,
type: _type
- });
- }
- }
-
- Object.defineProperties(this, {
- accountId: {
- value: converter_.toLong(_data.accountId),
- writable: false,
- enumerable: true
- },
- id: {
- get: function() {
- return converter_.toString(_data.id, true);
- },
- set: function(v) {
- if (v instanceof InternalCalendar) {
- _data.id = v.id;
+ });
}
- },
- enumerable: true
- },
- name: {
- value: _data.name,
- writable: false,
- enumerable: true
- },
- type: {
- value: _data.type,
- writable: false,
- enumerable: false
- },
- isUnified: {
- value: _data.isUnified,
- writable: false,
- enumerable: false
}
- });
+
+ Object.defineProperties(this, {
+ accountId: {
+ value: converter_.toLong(_data.accountId),
+ writable: false,
+ enumerable: true
+ },
+ id: {
+ get: function() {
+ return converter_.toString(_data.id, true);
+ },
+ set: function(v) {
+ if (v instanceof InternalCalendar) {
+ _data.id = v.id;
+ }
+ },
+ enumerable: true
+ },
+ name: {
+ value: _data.name,
+ writable: false,
+ enumerable: true
+ },
+ type: {
+ value: _data.type,
+ writable: false,
+ enumerable: false
+ },
+ isUnified: {
+ value: _data.isUnified,
+ writable: false,
+ enumerable: false
+ }
+ });
};
Calendar.prototype.get = function(id) {
- var args;
- if (this.type === CalendarType.TASK) {
- if (!parseInt(id) || parseInt(id) <= 0) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ var args;
+ if (this.type === CalendarType.TASK) {
+ if (!parseInt(id) || parseInt(id) <= 0) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
+ args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.STRING
+ }
+ ]);
+ } else {
+ args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.CalendarEventId
+ }
+ ]);
}
- args = validator_.validateArgs(arguments, [{
- name: 'id',
- type: types_.STRING
- }]);
- } else {
- args = validator_.validateArgs(arguments, [{
- name: 'id',
- type: types_.PLATFORM_OBJECT,
- values: tizen.CalendarEventId
- }]);
- }
-
- var result = native_.callSync('Calendar_get', {
- calendarId: this.id,
- id: args.id
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- _edit.allow();
- var item;
- var _item = native_.getResultObject(result);
-
- if (this.type === CalendarType.TASK) {
- item = new CalendarTask(_itemConverter.toTizenObject(_item, _item.isAllDay));
- } else {
- item = new CalendarEvent(_itemConverter.toTizenObject(_item, _item.isAllDay));
- }
- _edit.disallow();
-
- return item;
+
+ var result = native_.callSync('Calendar_get', {
+ calendarId: this.id,
+ id: args.id
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ _edit.allow();
+ var item;
+ var _item = native_.getResultObject(result);
+
+ if (this.type === CalendarType.TASK) {
+ item = new CalendarTask(_itemConverter.toTizenObject(_item, _item.isAllDay));
+ } else {
+ item = new CalendarEvent(_itemConverter.toTizenObject(_item, _item.isAllDay));
+ }
+ _edit.disallow();
+
+ return item;
};
Calendar.prototype.add = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'item',
- type: types_.PLATFORM_OBJECT,
- values: [CalendarEvent, CalendarTask]
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'item',
+ type: types_.PLATFORM_OBJECT,
+ values: [CalendarEvent, CalendarTask]
+ }
+ ]);
+
+ if (
+ (this.type === CalendarType.EVENT && !(args.item instanceof CalendarEvent)) ||
+ (this.type === CalendarType.TASK && !(args.item instanceof CalendarTask))
+ ) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Invalid item type.'
+ );
}
- ]);
- if ((this.type === CalendarType.EVENT && !(args.item instanceof CalendarEvent)) ||
- (this.type === CalendarType.TASK && !(args.item instanceof CalendarTask))) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Invalid item type.');
- }
+ var tmp = _itemConverter.fromTizenObject(args.item);
+ tmp.calendarId = this.id;
- var tmp = _itemConverter.fromTizenObject(args.item);
- tmp.calendarId = this.id;
-
- var result = native_.callSync('Calendar_add', {
- item: tmp,
- type: this.type
- });
+ var result = native_.callSync('Calendar_add', {
+ item: tmp,
+ type: this.type
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var _id = native_.getResultObject(result);
+ var _id = native_.getResultObject(result);
- _edit.allow();
- args.item.calendarId = this.id;
+ _edit.allow();
+ args.item.calendarId = this.id;
- switch (this.type) {
+ switch (this.type) {
case CalendarType.EVENT:
- args.item.id = new CalendarEventId(_id.uid, _id.rid);
- break;
+ args.item.id = new CalendarEventId(_id.uid, _id.rid);
+ break;
case CalendarType.TASK:
- args.item.id = _id.uid;
- break;
- }
- _edit.disallow();
+ args.item.id = _id.uid;
+ break;
+ }
+ _edit.disallow();
};
Calendar.prototype.addBatch = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'items',
- type: types_.ARRAY,
- values: (this.type === CalendarType.EVENT)
- ? tizen.CalendarEvent : tizen.CalendarTask
- }, {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }, {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'items',
+ type: types_.ARRAY,
+ values:
+ this.type === CalendarType.EVENT
+ ? tizen.CalendarEvent
+ : tizen.CalendarTask
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- _edit.allow();
- var _ids = native_.getResultObject(result);
- for (var i = 0; i < args.items.length; i++) {
- args.items[i].calendarId = this.id;
- switch (this.type) {
- case CalendarType.EVENT:
- args.items[i].id = new CalendarEventId(_ids[i].uid, _ids[i].rid);
- break;
- case CalendarType.TASK:
- args.items[i].id = _ids[i].uid;
- break;
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ _edit.allow();
+ var _ids = native_.getResultObject(result);
+ for (var i = 0; i < args.items.length; i++) {
+ args.items[i].calendarId = this.id;
+ switch (this.type) {
+ case CalendarType.EVENT:
+ args.items[i].id = new CalendarEventId(_ids[i].uid, _ids[i].rid);
+ break;
+ case CalendarType.TASK:
+ args.items[i].id = _ids[i].uid;
+ break;
+ }
+ }
+ _edit.disallow();
+ native_.callIfPossible(args.successCallback, args.items);
}
- }
- _edit.disallow();
- native_.callIfPossible(args.successCallback, args.items);
+ }.bind(this);
+
+ var tmp = [];
+ var tmpItem;
+ for (var i = 0; i < args.items.length; i++) {
+ if (
+ (this.type === CalendarType.EVENT &&
+ !(args.items[i] instanceof CalendarEvent)) ||
+ (this.type === CalendarType.TASK && !(args.items[i] instanceof CalendarTask))
+ ) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Invalid item type.'
+ );
+ }
+ tmpItem = _itemConverter.fromTizenObject(args.items[i]);
+ tmpItem.calendarId = this.id;
+ tmp.push(tmpItem);
}
- }.bind(this);
-
- var tmp = [];
- var tmpItem;
- for (var i = 0; i < args.items.length; i++) {
- if ((this.type === CalendarType.EVENT && !(args.items[i] instanceof CalendarEvent)) ||
- (this.type === CalendarType.TASK && !(args.items[i] instanceof CalendarTask))) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Invalid item type.');
+
+ var result = native_.call(
+ 'Calendar_addBatch',
+ {
+ type: this.type,
+ items: tmp
+ },
+ callback
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- tmpItem = _itemConverter.fromTizenObject(args.items[i]);
- tmpItem.calendarId = this.id;
- tmp.push(tmpItem);
- }
-
- var result = native_.call('Calendar_addBatch', {
- type: this.type,
- items: tmp
- }, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
Calendar.prototype.update = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'item',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.CalendarEvent, tizen.CalendarTask]
- },
- {
- name: 'updateAllInstances',
- type: types_.BOOLEAN,
- optional: true,
- nullable: true
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'item',
+ type: types_.PLATFORM_OBJECT,
+ values: [tizen.CalendarEvent, tizen.CalendarTask]
+ },
+ {
+ name: 'updateAllInstances',
+ type: types_.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (
+ (this.type === CalendarType.EVENT && !(args.item instanceof CalendarEvent)) ||
+ (this.type === CalendarType.TASK && !(args.item instanceof CalendarTask))
+ ) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Invalid item type.'
+ );
}
- ]);
-
- if ((this.type === CalendarType.EVENT && !(args.item instanceof CalendarEvent)) ||
- (this.type === CalendarType.TASK && !(args.item instanceof CalendarTask))) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Invalid item type.');
- }
- var tmp = _itemConverter.fromTizenObject(args.item);
- tmp.calendarId = this.id;
+ var tmp = _itemConverter.fromTizenObject(args.item);
+ tmp.calendarId = this.id;
- var result = native_.callSync('Calendar_update', {
- item: tmp,
- type: this.type,
- updateAllInstances: (args.has.updateAllInstances)
+ var result = native_.callSync('Calendar_update', {
+ item: tmp,
+ type: this.type,
+ updateAllInstances: args.has.updateAllInstances
? converter_.toBoolean(args.updateAllInstances, true)
: true
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ });
- var _item = native_.getResultObject(result);
- _edit.allow();
- for (var prop in _item) {
- if (args.item.hasOwnProperty(prop)) {
- args.item[prop] = _item[prop];
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- }
- _edit.disallow();
+ var _item = native_.getResultObject(result);
+ _edit.allow();
+ for (var prop in _item) {
+ if (args.item.hasOwnProperty(prop)) {
+ args.item[prop] = _item[prop];
+ }
+ }
+ _edit.disallow();
};
Calendar.prototype.updateBatch = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'items',
- type: types_.ARRAY,
- values: (this.type === CalendarType.EVENT)
- ? tizen.CalendarEvent : tizen.CalendarTask
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'updateAllInstances',
- type: types_.BOOLEAN,
- optional: true,
- nullable: true
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'items',
+ type: types_.ARRAY,
+ values:
+ this.type === CalendarType.EVENT
+ ? tizen.CalendarEvent
+ : tizen.CalendarTask
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'updateAllInstances',
+ type: types_.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var calendarType = this.type;
+ var calendarType = this.type;
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+
+ native_.callIfPossible(args.successCallback);
+ }.bind(this);
+
+ var tmp = [];
+ var tmpItem;
+ for (var i = 0; i < args.items.length; i++) {
+ if (
+ (calendarType === CalendarType.EVENT &&
+ !(args.items[i] instanceof CalendarEvent)) ||
+ (calendarType === CalendarType.TASK &&
+ !(args.items[i] instanceof CalendarTask))
+ ) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Invalid item type.'
+ );
+ }
+ tmpItem = _itemConverter.fromTizenObject(args.items[i]);
+ tmp.push(tmpItem);
}
- native_.callIfPossible(args.successCallback);
- }.bind(this);
+ var result = native_.call(
+ 'Calendar_updateBatch',
+ {
+ type: this.type,
+ items: tmp,
+ updateAllInstances: args.has.updateAllInstances
+ ? converter_.toBoolean(args.updateAllInstances, true)
+ : true
+ },
+ callback
+ );
- var tmp = [];
- var tmpItem;
- for (var i = 0; i < args.items.length; i++) {
- if ((calendarType === CalendarType.EVENT && !(args.items[i] instanceof CalendarEvent)) ||
- (calendarType === CalendarType.TASK && !(args.items[i] instanceof CalendarTask))) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Invalid item type.');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- tmpItem = _itemConverter.fromTizenObject(args.items[i]);
- tmp.push(tmpItem);
- }
-
- var result = native_.call('Calendar_updateBatch', {
- type: this.type,
- items: tmp,
- updateAllInstances: (args.has.updateAllInstances)
- ? converter_.toBoolean(args.updateAllInstances, true)
- : true
- }, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
Calendar.prototype.remove = function(id) {
- var args;
- if (this.type === CalendarType.TASK) {
- if (!parseInt(id) || parseInt(id) <= 0) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ var args;
+ if (this.type === CalendarType.TASK) {
+ if (!parseInt(id) || parseInt(id) <= 0) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
+ args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.STRING
+ }
+ ]);
+ } else {
+ args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.CalendarEventId
+ }
+ ]);
}
- args = validator_.validateArgs(arguments, [{
- name: 'id',
- type: types_.STRING
- }]);
- } else {
- args = validator_.validateArgs(arguments, [{
- name: 'id',
- type: types_.PLATFORM_OBJECT,
- values: tizen.CalendarEventId
- }]);
- }
-
- var result = native_.callSync('Calendar_remove', {
- type: this.type,
- id: args.id
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
-Calendar.prototype.removeBatch = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'ids',
- type: types_.ARRAY,
- values: (this.type === CalendarType.EVENT)
- ? tizen.CalendarEventId : undefined
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ var result = native_.callSync('Calendar_remove', {
+ type: this.type,
+ id: args.id
+ });
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback);
+ throw native_.getErrorObject(result);
}
- };
+};
+
+Calendar.prototype.removeBatch = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'ids',
+ type: types_.ARRAY,
+ values: this.type === CalendarType.EVENT ? tizen.CalendarEventId : undefined
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback);
+ }
+ };
- var result = native_.call('Calendar_removeBatch', {
- type: this.type,
- ids: args.ids
- }, callback);
+ var result = native_.call(
+ 'Calendar_removeBatch',
+ {
+ type: this.type,
+ ids: args.ids
+ },
+ callback
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
Calendar.prototype.find = function(successCallback, errorCallback, filter, sortMode) {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: types_.FUNCTION
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'filter',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter],
- optional: true,
- nullable: true
- },
- {
- name: 'sortMode',
- type: types_.PLATFORM_OBJECT,
- values: tizen.SortMode,
- optional: true,
- nullable: true
- }
- ]);
- args.filter = utils_.repackFilter(args.filter);
- var calendarType = this.type;
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'filter',
+ type: types_.PLATFORM_OBJECT,
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ],
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'sortMode',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.SortMode,
+ optional: true,
+ nullable: true
+ }
+ ]);
+ args.filter = utils_.repackFilter(args.filter);
+ var calendarType = this.type;
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var _items = native_.getResultObject(result);
- var c = [];
- _edit.allow();
- _items.forEach(function(i) {
- if (calendarType === CalendarType.TASK) {
- c.push(new CalendarTask(_itemConverter.toTizenObject(i, i.isAllDay)));
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
} else {
- c.push(new CalendarEvent(_itemConverter.toTizenObject(i, i.isAllDay)));
+ var _items = native_.getResultObject(result);
+ var c = [];
+ _edit.allow();
+ _items.forEach(function(i) {
+ if (calendarType === CalendarType.TASK) {
+ c.push(new CalendarTask(_itemConverter.toTizenObject(i, i.isAllDay)));
+ } else {
+ c.push(
+ new CalendarEvent(_itemConverter.toTizenObject(i, i.isAllDay))
+ );
+ }
+ });
+ _edit.disallow();
+ args.successCallback(c);
}
- });
- _edit.disallow();
- args.successCallback(c);
+ };
+ var result = native_.call(
+ 'Calendar_find',
+ {
+ calendarId: this.id,
+ filter: args.filter,
+ sortMode: args.sortMode || null
+ },
+ callback
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- };
- var result = native_.call('Calendar_find', {
- calendarId: this.id,
- filter: args.filter,
- sortMode: args.sortMode || null
- }, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
var _listeners = {};
@@ -515,175 +566,190 @@ var _nativeListeners = {};
var _nextId = 0;
function _CalendarEventChangeCallback(event) {
- _CalendarChangeCallback('EVENT', event);
+ _CalendarChangeCallback('EVENT', event);
}
function _CalendarTaskChangeCallback(event) {
- _CalendarChangeCallback('TASK', event);
+ _CalendarChangeCallback('TASK', event);
}
function _CalendarChangeCallback(type, event) {
- var invokeListeners = function(listeners, callbackName, items) {
- var result = [];
- _edit.allow();
- for (var i = 0, length = items.length; i < length; i++) {
- var item;
-
- if (callbackName === 'onitemsremoved') {
- if (type === 'EVENT') {
- item = new CalendarEventId(items[i].id, null);
- } else {
- item = converter_.toString(items[i].id);
- }
- } else {
- item = _itemConverter.toTizenObject(items[i], items[i].isAllDay);
- if (type === 'EVENT') {
- item = new CalendarEvent(item);
- } else {
- item = new CalendarTask(item);
+ var invokeListeners = function(listeners, callbackName, items) {
+ var result = [];
+ _edit.allow();
+ for (var i = 0, length = items.length; i < length; i++) {
+ var item;
+
+ if (callbackName === 'onitemsremoved') {
+ if (type === 'EVENT') {
+ item = new CalendarEventId(items[i].id, null);
+ } else {
+ item = converter_.toString(items[i].id);
+ }
+ } else {
+ item = _itemConverter.toTizenObject(items[i], items[i].isAllDay);
+ if (type === 'EVENT') {
+ item = new CalendarEvent(item);
+ } else {
+ item = new CalendarTask(item);
+ }
+ }
+
+ result.push(item);
}
- }
+ _edit.disallow();
- result.push(item);
- }
- _edit.disallow();
+ for (var watchId in listeners) {
+ if (listeners.hasOwnProperty(watchId)) {
+ native_.callIfPossible(listeners[watchId][callbackName], result);
+ }
+ }
+ }.bind(this);
- for (var watchId in listeners) {
- if (listeners.hasOwnProperty(watchId)) {
- native_.callIfPossible(listeners[watchId][callbackName], result);
- }
- }
- }.bind(this);
+ var groupItemsByCalendar = function(items) {
+ var grouped = {};
- var groupItemsByCalendar = function(items) {
- var grouped = {};
+ for (var i = 0, length = items.length; i < length; i++) {
+ var item = items[i];
- for (var i = 0, length = items.length; i < length; i++) {
- var item = items[i];
+ // skip item if we are not listening on this calendarId
+ if (!_listeners.hasOwnProperty(item.calendarId)) {
+ continue;
+ }
- // skip item if we are not listening on this calendarId
- if (!_listeners.hasOwnProperty(item.calendarId)) {
- continue;
- }
+ if (!grouped.hasOwnProperty(item.calendarId)) {
+ grouped[item.calendarId] = [];
+ }
+ grouped[item.calendarId].push(item);
+ }
- if (!grouped.hasOwnProperty(item.calendarId)) {
- grouped[item.calendarId] = [];
- }
- grouped[item.calendarId].push(item);
+ return grouped;
+ }.bind(this);
+
+ var actions = ['added', 'updated', 'removed'];
+ for (var i = 0; i < actions.length; i++) {
+ var action = actions[i];
+ var callback = 'onitems' + action;
+
+ if (
+ event.hasOwnProperty(action) &&
+ type_.isArray(event[action]) &&
+ event[action].length
+ ) {
+ // invoke listeners for unified calendars
+ if (_listeners.hasOwnProperty(type)) {
+ invokeListeners(_listeners[type], callback, event[action]);
+ }
+
+ var groupedItems = groupItemsByCalendar(event[action]);
+ for (var calendarId in groupedItems) {
+ if (groupedItems.hasOwnProperty(calendarId)) {
+ invokeListeners(
+ _listeners[calendarId],
+ callback,
+ groupedItems[calendarId]
+ );
+ }
+ }
+ }
}
+}
- return grouped;
- }.bind(this);
-
- var actions = ['added', 'updated', 'removed'];
- for (var i = 0; i < actions.length; i++) {
- var action = actions[i];
- var callback = 'onitems' + action;
-
- if (event.hasOwnProperty(action) && type_.isArray(event[action]) && event[action].length) {
+Calendar.prototype.addChangeListener = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.LISTENER,
+ values: ['onitemsadded', 'onitemsupdated', 'onitemsremoved']
+ }
+ ]);
- // invoke listeners for unified calendars
- if (_listeners.hasOwnProperty(type)) {
- invokeListeners(_listeners[type], callback, event[action]);
- }
+ var listenerId = 'CalendarChangeCallback_' + this.type;
- var groupedItems = groupItemsByCalendar(event[action]);
- for (var calendarId in groupedItems) {
- if (groupedItems.hasOwnProperty(calendarId)) {
- invokeListeners(_listeners[calendarId], callback, groupedItems[calendarId]);
+ if (!_nativeListeners.hasOwnProperty(listenerId)) {
+ var result = native_.callSync('Calendar_addChangeListener', {
+ type: this.type,
+ listenerId: listenerId
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- }
- }
- }
-}
-Calendar.prototype.addChangeListener = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'successCallback',
- type: types_.LISTENER,
- values: ['onitemsadded', 'onitemsupdated', 'onitemsremoved']
- }]);
-
- var listenerId = 'CalendarChangeCallback_' + this.type;
-
- if (!_nativeListeners.hasOwnProperty(listenerId)) {
- var result = native_.callSync('Calendar_addChangeListener', {
- type: this.type,
- listenerId: listenerId
- });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ native_.addListener(
+ listenerId,
+ this.type === 'EVENT'
+ ? _CalendarEventChangeCallback
+ : _CalendarTaskChangeCallback
+ );
+ _nativeListeners[listenerId] = this.type;
}
- native_.addListener(listenerId, (this.type === 'EVENT')
- ? _CalendarEventChangeCallback
- : _CalendarTaskChangeCallback);
- _nativeListeners[listenerId] = this.type;
- }
-
- // we can't use id in case of unified calendar - which is null for both calendar types
- var calendarId = (this.isUnified) ? this.type : this.id;
- if (!_listeners.hasOwnProperty(calendarId)) {
- _listeners[calendarId] = {};
- }
+ // we can't use id in case of unified calendar - which is null for both calendar types
+ var calendarId = this.isUnified ? this.type : this.id;
+ if (!_listeners.hasOwnProperty(calendarId)) {
+ _listeners[calendarId] = {};
+ }
- var watchId = ++_nextId;
- _listeners[calendarId][watchId] = args.successCallback;
+ var watchId = ++_nextId;
+ _listeners[calendarId][watchId] = args.successCallback;
- return watchId;
+ return watchId;
};
var Calendar_removeChangeListener = function() {
- if (type_.isEmptyObject(_listeners)) {
- utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
- }
- var args = validator_.validateArgs(arguments, [
- {
- name: 'watchId',
- type: types_.LONG
+ if (type_.isEmptyObject(_listeners)) {
+ utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
}
- ]);
-
- var watchId = converter_.toString(args.watchId);
- var calendarId = (this.isUnified) ? this.type : this.id;
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'watchId',
+ type: types_.LONG
+ }
+ ]);
- if (!_listeners[calendarId] || !_listeners[calendarId][watchId]) {
- return;
- }
+ var watchId = converter_.toString(args.watchId);
+ var calendarId = this.isUnified ? this.type : this.id;
- delete _listeners[calendarId][watchId];
+ if (!_listeners[calendarId] || !_listeners[calendarId][watchId]) {
+ return;
+ }
- if (type_.isEmptyObject(_listeners[calendarId])) {
- delete _listeners[calendarId];
- }
+ delete _listeners[calendarId][watchId];
- if (type_.isEmptyObject(_listeners)) {
+ if (type_.isEmptyObject(_listeners[calendarId])) {
+ delete _listeners[calendarId];
+ }
- var result;
- // @todo consider listener unregister when we are not listening on this.type of calendar
- var fail = false;
- for (var listenerId in _nativeListeners) {
- if (_nativeListeners.hasOwnProperty(listenerId)) {
- result = native_.callSync('Calendar_removeChangeListener', {
- type: _nativeListeners[listenerId]
- });
- if (native_.isFailure(result)) {
- fail = native_.getErrorObject(result);
+ if (type_.isEmptyObject(_listeners)) {
+ var result;
+ // @todo consider listener unregister when we are not listening on
+ // this.type of calendar
+ var fail = false;
+ for (var listenerId in _nativeListeners) {
+ if (_nativeListeners.hasOwnProperty(listenerId)) {
+ result = native_.callSync('Calendar_removeChangeListener', {
+ type: _nativeListeners[listenerId]
+ });
+ if (native_.isFailure(result)) {
+ fail = native_.getErrorObject(result);
+ }
+ native_.removeListener(
+ listenerId,
+ this.type === 'EVENT'
+ ? _CalendarEventChangeCallback
+ : _CalendarTaskChangeCallback
+ );
+
+ delete _nativeListeners[listenerId];
+ }
}
- native_.removeListener(listenerId, (this.type === 'EVENT')
- ? _CalendarEventChangeCallback
- : _CalendarTaskChangeCallback);
- delete _nativeListeners[listenerId];
- }
- }
-
- if (fail) {
- throw fail;
+ if (fail) {
+ throw fail;
+ }
}
- }
};
Calendar.prototype.removeChangeListener = function() {
- Calendar_removeChangeListener.apply(this, arguments);
+ Calendar_removeChangeListener.apply(this, arguments);
};
tizen.Calendar = Calendar;
diff --git a/src/calendar/js/calendar_alarm.js b/src/calendar/js/calendar_alarm.js
index 6976ac5a..3755560e 100755
--- a/src/calendar/js/calendar_alarm.js
+++ b/src/calendar/js/calendar_alarm.js
@@ -13,70 +13,72 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var AlarmMethod = {
- SOUND: 'SOUND',
- DISPLAY: 'DISPLAY'
+ SOUND: 'SOUND',
+ DISPLAY: 'DISPLAY'
};
var privUtils_ = xwalk.utils;
var CalendarAlarm = function(time, method, description) {
- validator_.isConstructorCall(this, CalendarAlarm);
+ validator_.isConstructorCall(this, CalendarAlarm);
- var _absoluteDate = time instanceof tizen.TZDate && !this.before ? time : null;
- var _before = time instanceof tizen.TimeDuration && !this.absoluteDate ? time : null;
- var _description = (description) ? converter_.toString(description, true) : '';
- var _method;
+ var _absoluteDate = time instanceof tizen.TZDate && !this.before ? time : null;
+ var _before = time instanceof tizen.TimeDuration && !this.absoluteDate ? time : null;
+ var _description = description ? converter_.toString(description, true) : '';
+ var _method;
- try {
- _method = converter_.toEnum(method, Object.keys(AlarmMethod), false);
- } catch (e) {
- privUtils_.warn('Failed to convert method: "' + method + '" to enum AlarmMethod.');
- _method = method;
- }
+ try {
+ _method = converter_.toEnum(method, Object.keys(AlarmMethod), false);
+ } catch (e) {
+ privUtils_.warn(
+ 'Failed to convert method: "' + method + '" to enum AlarmMethod.'
+ );
+ _method = method;
+ }
- Object.defineProperties(this, {
- absoluteDate: {
- get: function() {
- return _absoluteDate;
- },
- set: function(v) {
- _absoluteDate = v instanceof tizen.TZDate && !_before ? v : null;
- },
- enumerable: true
- },
- before: {
- get: function() {
- return _before;
- },
- set: function(v) {
- _before = v instanceof tizen.TimeDuration && !_absoluteDate ? v : null;
- },
- enumerable: true
- },
- method: {
- get: function() {
- return _method;
- },
- set: function(v) {
- if (v === null) {
- return;
+ Object.defineProperties(this, {
+ absoluteDate: {
+ get: function() {
+ return _absoluteDate;
+ },
+ set: function(v) {
+ _absoluteDate = v instanceof tizen.TZDate && !_before ? v : null;
+ },
+ enumerable: true
+ },
+ before: {
+ get: function() {
+ return _before;
+ },
+ set: function(v) {
+ _before = v instanceof tizen.TimeDuration && !_absoluteDate ? v : null;
+ },
+ enumerable: true
+ },
+ method: {
+ get: function() {
+ return _method;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _method = converter_.toEnum(v, Object.keys(AlarmMethod), false);
+ },
+ enumerable: true
+ },
+ description: {
+ get: function() {
+ return _description;
+ },
+ set: function(v) {
+ _description = converter_.toString(v, true);
+ },
+ enumerable: true
}
- _method = converter_.toEnum(v, Object.keys(AlarmMethod), false);
- },
- enumerable: true
- },
- description: {
- get: function() {
- return _description;
- },
- set: function(v) {
- _description = converter_.toString(v, true);
- },
- enumerable: true
- }
- });
+ });
};
tizen.CalendarAlarm = CalendarAlarm;
diff --git a/src/calendar/js/calendar_attendee.js b/src/calendar/js/calendar_attendee.js
index 0db4f551..bb24760f 100755
--- a/src/calendar/js/calendar_attendee.js
+++ b/src/calendar/js/calendar_attendee.js
@@ -15,168 +15,168 @@
*/
var _global = window || global || {};
-
+
var AttendeeType = {
- INDIVIDUAL: 'INDIVIDUAL',
- GROUP: 'GROUP',
- RESOURCE: 'RESOURCE',
- ROOM: 'ROOM',
- UNKNOWN: 'UNKNOWN'
+ INDIVIDUAL: 'INDIVIDUAL',
+ GROUP: 'GROUP',
+ RESOURCE: 'RESOURCE',
+ ROOM: 'ROOM',
+ UNKNOWN: 'UNKNOWN'
};
var AttendeeStatus = {
- PENDING: 'PENDING',
- ACCEPTED: 'ACCEPTED',
- DECLINED: 'DECLINED',
- TENTATIVE: 'TENTATIVE',
- DELEGATED: 'DELEGATED',
- COMPLETED: 'COMPLETED',
- IN_PROCESS: 'IN_PROCESS'
+ PENDING: 'PENDING',
+ ACCEPTED: 'ACCEPTED',
+ DECLINED: 'DECLINED',
+ TENTATIVE: 'TENTATIVE',
+ DELEGATED: 'DELEGATED',
+ COMPLETED: 'COMPLETED',
+ IN_PROCESS: 'IN_PROCESS'
};
var AttendeeRole = {
- REQ_PARTICIPANT: 'REQ_PARTICIPANT',
- OPT_PARTICIPANT: 'OPT_PARTICIPANT',
- NON_PARTICIPANT: 'NON_PARTICIPANT',
- CHAIR: 'CHAIR'
+ REQ_PARTICIPANT: 'REQ_PARTICIPANT',
+ OPT_PARTICIPANT: 'OPT_PARTICIPANT',
+ NON_PARTICIPANT: 'NON_PARTICIPANT',
+ CHAIR: 'CHAIR'
};
var CalendarAttendeeInit = function(data) {
- var _name = null;
- var _role = 'REQ_PARTICIPANT';
- var _status = 'PENDING';
- var _RSVP = false;
- var _type = 'INDIVIDUAL';
- var _group = null;
- var _delegatorURI = null;
- var _delegateURI = null;
- var _contactRef = null;
+ var _name = null;
+ var _role = 'REQ_PARTICIPANT';
+ var _status = 'PENDING';
+ var _RSVP = false;
+ var _type = 'INDIVIDUAL';
+ var _group = null;
+ var _delegatorURI = null;
+ var _delegateURI = null;
+ var _contactRef = null;
- Object.defineProperties(this, {
- name: {
- get: function() {
- return _name;
- },
- set: function(v) {
- _name = converter_.toString(v, true);
- },
- enumerable: true
- },
- role: {
- get: function() {
- return _role;
- },
- set: function(v) {
- if (v === null) {
- return;
- }
- _role = converter_.toEnum(v, Object.keys(AttendeeRole), false);
- },
- enumerable: true
- },
- status: {
- get: function() {
- return _status;
- },
- set: function(v) {
- if (v === null) {
- return;
- }
- _status = converter_.toEnum(v, Object.keys(AttendeeStatus), false);
- },
- enumerable: true
- },
- RSVP: {
- get: function() {
- return _RSVP;
- },
- set: function(v) {
- _RSVP = converter_.toBoolean(v);
- },
- enumerable: true
- },
- type: {
- get: function() {
- return _type;
- },
- set: function(v) {
- if (v === null) {
- return;
+ Object.defineProperties(this, {
+ name: {
+ get: function() {
+ return _name;
+ },
+ set: function(v) {
+ _name = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ role: {
+ get: function() {
+ return _role;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _role = converter_.toEnum(v, Object.keys(AttendeeRole), false);
+ },
+ enumerable: true
+ },
+ status: {
+ get: function() {
+ return _status;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _status = converter_.toEnum(v, Object.keys(AttendeeStatus), false);
+ },
+ enumerable: true
+ },
+ RSVP: {
+ get: function() {
+ return _RSVP;
+ },
+ set: function(v) {
+ _RSVP = converter_.toBoolean(v);
+ },
+ enumerable: true
+ },
+ type: {
+ get: function() {
+ return _type;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _type = converter_.toEnum(v, Object.keys(AttendeeType), false);
+ },
+ enumerable: true
+ },
+ group: {
+ get: function() {
+ return _group;
+ },
+ set: function(v) {
+ _group = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ delegatorURI: {
+ get: function() {
+ return _delegatorURI;
+ },
+ set: function(v) {
+ _delegatorURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ delegateURI: {
+ get: function() {
+ return _delegateURI;
+ },
+ set: function(v) {
+ _delegateURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ contactRef: {
+ get: function() {
+ return _contactRef;
+ },
+ set: function(v) {
+ _contactRef = v instanceof tizen.ContactRef ? v : _contactRef;
+ },
+ enumerable: true
}
- _type = converter_.toEnum(v, Object.keys(AttendeeType), false);
- },
- enumerable: true
- },
- group: {
- get: function() {
- return _group;
- },
- set: function(v) {
- _group = converter_.toString(v, true);
- },
- enumerable: true
- },
- delegatorURI: {
- get: function() {
- return _delegatorURI;
- },
- set: function(v) {
- _delegatorURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- delegateURI: {
- get: function() {
- return _delegateURI;
- },
- set: function(v) {
- _delegateURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- contactRef: {
- get: function() {
- return _contactRef;
- },
- set: function(v) {
- _contactRef = v instanceof tizen.ContactRef ? v : _contactRef;
- },
- enumerable: true
- }
- });
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
var CalendarAttendee = function(uri, attendeeInitDict) {
- validator_.isConstructorCall(this, CalendarAttendee);
+ validator_.isConstructorCall(this, CalendarAttendee);
- CalendarAttendeeInit.call(this, attendeeInitDict);
+ CalendarAttendeeInit.call(this, attendeeInitDict);
- var _uri = null;
+ var _uri = null;
- Object.defineProperties(this, {
- uri: {
- get: function() {
- return _uri;
- },
- set: function(v) {
- if (v === null) {
- return;
+ Object.defineProperties(this, {
+ uri: {
+ get: function() {
+ return _uri;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _uri = converter_.toString(v, true);
+ },
+ enumerable: true
}
- _uri = converter_.toString(v, true);
- },
- enumerable: true
- }
- });
+ });
- this.uri = uri;
+ this.uri = uri;
};
CalendarAttendee.prototype = new CalendarAttendeeInit();
diff --git a/src/calendar/js/calendar_item.js b/src/calendar/js/calendar_item.js
index 4b6c0d4d..8f2ad6ea 100644
--- a/src/calendar/js/calendar_item.js
+++ b/src/calendar/js/calendar_item.js
@@ -17,746 +17,788 @@
var _global = window || global || {};
var CalendarTextFormat = {
- ICALENDAR_20: 'ICALENDAR_20',
- VCALENDAR_10: 'VCALENDAR_10'
+ ICALENDAR_20: 'ICALENDAR_20',
+ VCALENDAR_10: 'VCALENDAR_10'
};
var CalendarItemVisibility = {
- PUBLIC: 'PUBLIC', //default
- PRIVATE: 'PRIVATE',
- CONFIDENTIAL: 'CONFIDENTIAL'
+ PUBLIC: 'PUBLIC', //default
+ PRIVATE: 'PRIVATE',
+ CONFIDENTIAL: 'CONFIDENTIAL'
};
var CalendarItemPriority = {
- HIGH: 'HIGH',
- MEDIUM: 'MEDIUM',
- LOW: 'LOW',
- NONE: 'NONE' //default
+ HIGH: 'HIGH',
+ MEDIUM: 'MEDIUM',
+ LOW: 'LOW',
+ NONE: 'NONE' //default
};
var CalendarItemStatus = {
- TENTATIVE: 'TENTATIVE',
- CONFIRMED: 'CONFIRMED',
- CANCELLED: 'CANCELLED',
- NONE: 'NONE', //default for both CalendarEvent and CalendarTask
- NEEDS_ACTION: 'NEEDS_ACTION',
- IN_PROCESS: 'IN_PROCESS',
- COMPLETED: 'COMPLETED'
+ TENTATIVE: 'TENTATIVE',
+ CONFIRMED: 'CONFIRMED',
+ CANCELLED: 'CANCELLED',
+ NONE: 'NONE', //default for both CalendarEvent and CalendarTask
+ NEEDS_ACTION: 'NEEDS_ACTION',
+ IN_PROCESS: 'IN_PROCESS',
+ COMPLETED: 'COMPLETED'
};
var EventAvailability = {
- BUSY: 'BUSY', //default for CalendarEvent
- FREE: 'FREE',
- BUSY_UNAVAILABLE: 'BUSY_UNAVAILABLE',
- BUSY_TENTATIVE: 'BUSY_TENTATIVE'
+ BUSY: 'BUSY', //default for CalendarEvent
+ FREE: 'FREE',
+ BUSY_UNAVAILABLE: 'BUSY_UNAVAILABLE',
+ BUSY_TENTATIVE: 'BUSY_TENTATIVE'
};
var CalendarEventId = function(uid, rid) {
- validator_.isConstructorCall(this, CalendarEventId);
-
- var _uid = null;
-
- Object.defineProperties(this, {
- uid: {
- get: function() {
- return _uid;
- },
- set: function(v) {
- if (v === null) {
- return;
+ validator_.isConstructorCall(this, CalendarEventId);
+
+ var _uid = null;
+
+ Object.defineProperties(this, {
+ uid: {
+ get: function() {
+ return _uid;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _uid = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ rid: {
+ value: rid ? converter_.toString(rid, true) : null,
+ writable: true,
+ enumerable: true
}
- _uid = converter_.toString(v, true);
- },
- enumerable: true
- },
- rid: {
- value: (rid) ? converter_.toString(rid, true) : null,
- writable: true,
- enumerable: true
- }
- });
+ });
- this.uid = uid;
+ this.uid = uid;
};
// class CalendarItem
var CalendarItem = function(data) {
- var _id = null;
- var _calendarId = null;
- var _lastModificationDate = null;
- var _description = '';
- var _summary = '';
- var _isAllDay = false;
- var _startDate = null;
- var _duration = null;
- var _location = '';
- var _geolocation = null;
- var _organizer = '';
- var _visibility = CalendarItemVisibility.PUBLIC;
- var _status = CalendarItemStatus.NONE;
- var _priority = CalendarItemPriority.NONE;
- var _alarms = [];
- var _categories = [];
- var _attendees = [];
-
- function _validateAlarms(v) {
- var valid = false;
-
- if (type_.isArray(v)) {
- for (var i = 0; i < v.length; i++) {
- if (!(v[i] instanceof tizen.CalendarAlarm)) {
- return false;
+ var _id = null;
+ var _calendarId = null;
+ var _lastModificationDate = null;
+ var _description = '';
+ var _summary = '';
+ var _isAllDay = false;
+ var _startDate = null;
+ var _duration = null;
+ var _location = '';
+ var _geolocation = null;
+ var _organizer = '';
+ var _visibility = CalendarItemVisibility.PUBLIC;
+ var _status = CalendarItemStatus.NONE;
+ var _priority = CalendarItemPriority.NONE;
+ var _alarms = [];
+ var _categories = [];
+ var _attendees = [];
+
+ function _validateAlarms(v) {
+ var valid = false;
+
+ if (type_.isArray(v)) {
+ for (var i = 0; i < v.length; i++) {
+ if (!(v[i] instanceof tizen.CalendarAlarm)) {
+ return false;
+ }
+ }
+ valid = true;
}
- }
- valid = true;
+ return valid;
}
- return valid;
- }
- function _validateAttendees(v) {
- var valid = false;
+ function _validateAttendees(v) {
+ var valid = false;
- if (type_.isArray(v)) {
- for (var i = 0; i < v.length; i++) {
- if (!(v[i] instanceof tizen.CalendarAttendee)) {
- return false;
+ if (type_.isArray(v)) {
+ for (var i = 0; i < v.length; i++) {
+ if (!(v[i] instanceof tizen.CalendarAttendee)) {
+ return false;
+ }
+ }
+ valid = true;
}
- }
- valid = true;
+ return valid;
}
- return valid;
- }
- function _validateCategories(v) {
- var valid = false;
+ function _validateCategories(v) {
+ var valid = false;
- if (type_.isArray(v)) {
- for (var i = 0; i < v.length; i++) {
- if (!(type_.isString(v[i]))) {
- return false;
+ if (type_.isArray(v)) {
+ for (var i = 0; i < v.length; i++) {
+ if (!type_.isString(v[i])) {
+ return false;
+ }
+ }
+ valid = true;
}
- }
- valid = true;
+ return valid;
}
- return valid;
- }
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return _id;
- },
- set: function(v) {
- if (_edit.canEdit) {
- if (v instanceof _global.Object) {
- _id = new CalendarEventId(v.uid, v.rid);
- } else {
- _id = converter_.toString(v, true);
- }
- }
- },
- enumerable: true
- },
- calendarId: {
- get: function() {
- return _calendarId;
- },
- set: function(v) {
- if (_edit.canEdit) {
- _calendarId = v;
- }
- },
- enumerable: true
- },
- lastModificationDate: {
- get: function() {
- return _lastModificationDate;
- },
- set: function(v) {
- if (_edit.canEdit) {
- _lastModificationDate = v instanceof tizen.TZDate ? v :
- tizen.time.getCurrentDateTime();
- }
- },
- enumerable: true
- },
- description: {
- get: function() {
- return _description;
- },
- set: function(v) {
- _description = v ? converter_.toString(v, true) : _description;
- },
- enumerable: true
- },
- summary: {
- get: function() {
- return _summary;
- },
- set: function(v) {
- _summary = v ? converter_.toString(v, true) : _summary;
- },
- enumerable: true
- },
- isAllDay: {
- get: function() {
- return _isAllDay;
- },
- set: function(v) {
- _isAllDay = converter_.toBoolean(v);
- },
- enumerable: true
- },
- startDate: {
- get: function() {
- return _startDate;
- },
- set: function(v) {
- _startDate = v instanceof tizen.TZDate ? v : _startDate;
- this.duration = _duration;
- },
- enumerable: true
- },
- duration: {
- get: function() {
- return _duration;
- },
- set: function(v) {
- // set duration as dueDate or endDate
- var _startDate = this.startDate ?
- this.startDate : tizen.time.getCurrentDateTime();
- if (this instanceof tizen.CalendarEvent) {
- this.endDate = v instanceof tizen.TimeDuration ?
- _startDate.addDuration(v) : this.endDate;
- } else {
- this.dueDate = v instanceof tizen.TimeDuration ?
- _startDate.addDuration(v) : this.dueDate;
- }
- _duration = v instanceof tizen.TimeDuration ? v : null;
- //@todo Fix UTC, UTC expect duration value but according to documentation:
- // ... the implementation may not save the duration itself,
- // rather convert it to the corresponding endDate/dueDate attribute and save it.
- // For example, if you set the startDate and the duration attributes and save the item,
- // you may see that the duration is null while endDate/dueDate is non-null
- // after retrieving it because the implementation has calculated the endDate/dueDate
- // based on the duration and the startDate then saved it, not the duration.
- },
- enumerable: true
- },
- location: {
- get: function() {
- return _location;
- },
- set: function(v) {
- _location = v ? converter_.toString(v) : _location;
- },
- enumerable: true
- },
- geolocation: {
- get: function() {
- return _geolocation;
- },
- set: function(v) {
- _geolocation = v instanceof tizen.SimpleCoordinates ? v : _geolocation;
- },
- enumerable: true
- },
- organizer: {
- get: function() {
- return _organizer;
- },
- set: function(v) {
- _organizer = v ? converter_.toString(v) : _organizer;
- },
- enumerable: true
- },
- visibility: {
- get: function() {
- return _visibility;
- },
- set: function(v) {
- _visibility = v ? converter_.toEnum(v, Object.keys(CalendarItemVisibility), false) :
- _visibility;
- },
- enumerable: true
- },
- status: {
- get: function() {
- return _status;
- },
- set: function(v) {
- if (v === null) {
- return;
- }
- if (this instanceof tizen.CalendarEvent) {
- _status = v ? converter_.toEnum(v, Object.keys(CalendarItemStatus).slice(0, 4), false) :
- CalendarItemStatus.NONE;
- } else {
- _status = v ? converter_.toEnum(v, Object.keys(CalendarItemStatus).slice(2), false) :
- CalendarItemStatus.NONE;
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return _id;
+ },
+ set: function(v) {
+ if (_edit.canEdit) {
+ if (v instanceof _global.Object) {
+ _id = new CalendarEventId(v.uid, v.rid);
+ } else {
+ _id = converter_.toString(v, true);
+ }
+ }
+ },
+ enumerable: true
+ },
+ calendarId: {
+ get: function() {
+ return _calendarId;
+ },
+ set: function(v) {
+ if (_edit.canEdit) {
+ _calendarId = v;
+ }
+ },
+ enumerable: true
+ },
+ lastModificationDate: {
+ get: function() {
+ return _lastModificationDate;
+ },
+ set: function(v) {
+ if (_edit.canEdit) {
+ _lastModificationDate =
+ v instanceof tizen.TZDate ? v : tizen.time.getCurrentDateTime();
+ }
+ },
+ enumerable: true
+ },
+ description: {
+ get: function() {
+ return _description;
+ },
+ set: function(v) {
+ _description = v ? converter_.toString(v, true) : _description;
+ },
+ enumerable: true
+ },
+ summary: {
+ get: function() {
+ return _summary;
+ },
+ set: function(v) {
+ _summary = v ? converter_.toString(v, true) : _summary;
+ },
+ enumerable: true
+ },
+ isAllDay: {
+ get: function() {
+ return _isAllDay;
+ },
+ set: function(v) {
+ _isAllDay = converter_.toBoolean(v);
+ },
+ enumerable: true
+ },
+ startDate: {
+ get: function() {
+ return _startDate;
+ },
+ set: function(v) {
+ _startDate = v instanceof tizen.TZDate ? v : _startDate;
+ this.duration = _duration;
+ },
+ enumerable: true
+ },
+ duration: {
+ get: function() {
+ return _duration;
+ },
+ set: function(v) {
+ // set duration as dueDate or endDate
+ var _startDate = this.startDate
+ ? this.startDate
+ : tizen.time.getCurrentDateTime();
+ if (this instanceof tizen.CalendarEvent) {
+ this.endDate =
+ v instanceof tizen.TimeDuration
+ ? _startDate.addDuration(v)
+ : this.endDate;
+ } else {
+ this.dueDate =
+ v instanceof tizen.TimeDuration
+ ? _startDate.addDuration(v)
+ : this.dueDate;
+ }
+ _duration = v instanceof tizen.TimeDuration ? v : null;
+ //@todo Fix UTC, UTC expect duration value but according to
+ // documentation:
+ // ... the implementation may not save the duration itself,
+ // rather convert it to the corresponding endDate/dueDate attribute and
+ // save it. For example, if you set the startDate and the duration
+ // attributes and save the item, you may see that the duration is null
+ // while endDate/dueDate is non-null after retrieving it because the
+ // implementation has calculated the endDate/dueDate based on the
+ // duration and the startDate then saved it, not the duration.
+ },
+ enumerable: true
+ },
+ location: {
+ get: function() {
+ return _location;
+ },
+ set: function(v) {
+ _location = v ? converter_.toString(v) : _location;
+ },
+ enumerable: true
+ },
+ geolocation: {
+ get: function() {
+ return _geolocation;
+ },
+ set: function(v) {
+ _geolocation = v instanceof tizen.SimpleCoordinates ? v : _geolocation;
+ },
+ enumerable: true
+ },
+ organizer: {
+ get: function() {
+ return _organizer;
+ },
+ set: function(v) {
+ _organizer = v ? converter_.toString(v) : _organizer;
+ },
+ enumerable: true
+ },
+ visibility: {
+ get: function() {
+ return _visibility;
+ },
+ set: function(v) {
+ _visibility = v
+ ? converter_.toEnum(v, Object.keys(CalendarItemVisibility), false)
+ : _visibility;
+ },
+ enumerable: true
+ },
+ status: {
+ get: function() {
+ return _status;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ if (this instanceof tizen.CalendarEvent) {
+ _status = v
+ ? converter_.toEnum(
+ v,
+ Object.keys(CalendarItemStatus).slice(0, 4),
+ false
+ )
+ : CalendarItemStatus.NONE;
+ } else {
+ _status = v
+ ? converter_.toEnum(
+ v,
+ Object.keys(CalendarItemStatus).slice(2),
+ false
+ )
+ : CalendarItemStatus.NONE;
+ }
+ },
+ enumerable: true
+ },
+ priority: {
+ get: function() {
+ return _priority;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _priority = v
+ ? converter_.toEnum(v, Object.keys(CalendarItemPriority), false)
+ : _status;
+ },
+ enumerable: true
+ },
+ alarms: {
+ get: function() {
+ return _alarms;
+ },
+ set: function(v) {
+ _alarms = _validateAlarms(v) ? v : _alarms;
+ },
+ enumerable: true
+ },
+ categories: {
+ get: function() {
+ return _categories;
+ },
+ set: function(v) {
+ _categories = _validateCategories(v) ? v : _categories;
+ },
+ enumerable: true
+ },
+ attendees: {
+ get: function() {
+ return _attendees;
+ },
+ set: function(v) {
+ _attendees = _validateAttendees(v) ? v : _attendees;
+ },
+ enumerable: true
}
- },
- enumerable: true
- },
- priority: {
- get: function() {
- return _priority;
- },
- set: function(v) {
- if (v === null) {
- return;
+ });
+
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
}
- _priority = v ? converter_.toEnum(v, Object.keys(CalendarItemPriority), false) :
- _status;
- },
- enumerable: true
- },
- alarms: {
- get: function() {
- return _alarms;
- },
- set: function(v) {
- _alarms = _validateAlarms(v) ? v : _alarms;
- },
- enumerable: true
- },
- categories: {
- get: function() {
- return _categories;
- },
- set: function(v) {
- _categories = _validateCategories(v) ? v : _categories;
- },
- enumerable: true
- },
- attendees: {
- get: function() {
- return _attendees;
- },
- set: function(v) {
- _attendees = _validateAttendees(v) ? v : _attendees;
- },
- enumerable: true
}
- });
+};
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+var CalendarItem_convertToString = function() {
+ utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'format',
+ type: types_.ENUM,
+ values: Object.keys(CalendarTextFormat)
+ }
+ ]);
+
+ var _checkNumber = function(n) {
+ return n < 10 ? '0' + n : n;
+ };
+
+ var _timeFormat = function(d) {
+ return (
+ ';TZID=' +
+ d.getTimezone() +
+ ':' +
+ d.getFullYear() +
+ _checkNumber(d.getMonth()) +
+ _checkNumber(d.getDate()) +
+ 'T' +
+ _checkNumber(d.getHours()) +
+ _checkNumber(d.getMinutes()) +
+ _checkNumber(d.getSeconds() + 'Z')
+ );
+ };
+
+ var _this = this;
+ var _dtStart = '';
+
+ if (_this.startDate) {
+ _dtStart = _timeFormat(_this.startDate);
+ } else {
+ _dtStart = _timeFormat(tizen.time.getCurrentDateTime());
}
- }
-};
+ var _dtEnd = _dtStart;
-var CalendarItem_convertToString = function() {
- utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
- var args = validator_.validateArgs(arguments, [
- {
- name: 'format',
- type: types_.ENUM,
- values: Object.keys(CalendarTextFormat)
+ if (_this.endDate) {
+ _dtEnd = _timeFormat(_this.endDate);
+ } else if (_this.dueDate) {
+ _dtEnd = _timeFormat(_this.dueDate);
}
- ]);
-
- var _checkNumber = function(n) {
- return n < 10 ? '0' + n : n;
- };
-
- var _timeFormat = function(d) {
- return ';TZID=' + d.getTimezone() +
- ':' + d.getFullYear() + _checkNumber(d.getMonth()) + _checkNumber(d.getDate()) +
- 'T' + _checkNumber(d.getHours()) + _checkNumber(d.getMinutes()) +
- _checkNumber(d.getSeconds() + 'Z');
- };
-
- var _this = this;
- var _dtStart = '';
-
- if (_this.startDate) {
- _dtStart = _timeFormat(_this.startDate);
- } else {
- _dtStart = _timeFormat(tizen.time.getCurrentDateTime());
- }
-
- var _dtEnd = _dtStart;
-
- if (_this.endDate) {
- _dtEnd = _timeFormat(_this.endDate);
- } else if (_this.dueDate) {
- _dtEnd = _timeFormat(_this.dueDate);
- }
-
- var _description = _this.description.length ? ':' + _this.description : '';
- var _location = _this.location.length ? ':' + _this.location : '';
- var _organizer = _this.organizer.length ? ';CN=' + _this.organizer : '';
- var _priority = _this.priority.length ? ':' + _this.priority : '';
- var _summary = _this.summary.length ? ':' + _this.summary : '';
- var _categories = _this.categories.length ? ':' + _this.categories.join(', ') : '';
- var _visibility = _this.visibility;
- var _status = _this.status;
- var _version = args.format === CalendarTextFormat.ICALENDAR_20 ? ':2.0' : ':1.0';
-
- var vEven = [
- 'BEGIN:VCALENDAR',
- 'VERSION' + _version,
- 'BEGIN:VEVENT',
- 'CLASS:' + _visibility,
- 'TRANSP:OPAQUE',
- 'DTSTART' + _dtStart,
- 'DESCRIPTION' + _description,
- 'LOCATION' + _location,
- 'ORGANIZER' + _organizer,
- 'PRIORITY' + _priority,
- 'SUMMARY' + _summary,
- 'DTEND' + _dtEnd,
- 'CATEGORIES' + _categories,
- 'END:VEVENT',
- 'END:VCALENDAR'
- ].join('\n');
-
- var vTodo = [
- 'BEGIN:VCALENDAR',
- 'VERSION' + _version,
- 'BEGIN:VTODO',
- 'SUMMARY' + _summary,
- 'DUE' + _dtEnd,
- 'STATUS' + _status,
- 'END:VTODO',
- 'END:VCALENDAR'
- ].join('\n');
-
- if (this instanceof tizen.CalendarTask) {
- return vTodo;
- } else {
- return vEven;
- }
+ var _description = _this.description.length ? ':' + _this.description : '';
+ var _location = _this.location.length ? ':' + _this.location : '';
+ var _organizer = _this.organizer.length ? ';CN=' + _this.organizer : '';
+ var _priority = _this.priority.length ? ':' + _this.priority : '';
+ var _summary = _this.summary.length ? ':' + _this.summary : '';
+ var _categories = _this.categories.length ? ':' + _this.categories.join(', ') : '';
+ var _visibility = _this.visibility;
+ var _status = _this.status;
+ var _version = args.format === CalendarTextFormat.ICALENDAR_20 ? ':2.0' : ':1.0';
+
+ var vEven = [
+ 'BEGIN:VCALENDAR',
+ 'VERSION' + _version,
+ 'BEGIN:VEVENT',
+ 'CLASS:' + _visibility,
+ 'TRANSP:OPAQUE',
+ 'DTSTART' + _dtStart,
+ 'DESCRIPTION' + _description,
+ 'LOCATION' + _location,
+ 'ORGANIZER' + _organizer,
+ 'PRIORITY' + _priority,
+ 'SUMMARY' + _summary,
+ 'DTEND' + _dtEnd,
+ 'CATEGORIES' + _categories,
+ 'END:VEVENT',
+ 'END:VCALENDAR'
+ ].join('\n');
+
+ var vTodo = [
+ 'BEGIN:VCALENDAR',
+ 'VERSION' + _version,
+ 'BEGIN:VTODO',
+ 'SUMMARY' + _summary,
+ 'DUE' + _dtEnd,
+ 'STATUS' + _status,
+ 'END:VTODO',
+ 'END:VCALENDAR'
+ ].join('\n');
+
+ if (this instanceof tizen.CalendarTask) {
+ return vTodo;
+ } else {
+ return vEven;
+ }
};
CalendarItem.prototype.convertToString = function() {
- return CalendarItem_convertToString.apply(this, arguments);
-}
+ return CalendarItem_convertToString.apply(this, arguments);
+};
var CalendarItem_clone = function() {
- utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
- var tmp = _itemConverter.toTizenObject(_itemConverter.fromTizenObject(this));
+ utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
+ var tmp = _itemConverter.toTizenObject(_itemConverter.fromTizenObject(this));
- tmp.id = null;
+ tmp.id = null;
- return this instanceof tizen.CalendarEvent ? new tizen.CalendarEvent(tmp) :
- new tizen.CalendarTask(tmp);
+ return this instanceof tizen.CalendarEvent
+ ? new tizen.CalendarEvent(tmp)
+ : new tizen.CalendarTask(tmp);
};
CalendarItem.prototype.clone = function() {
- return CalendarItem_clone.apply(this, arguments);
+ return CalendarItem_clone.apply(this, arguments);
};
function _convertFromStringToItem(str) {
- if (str.indexOf('VCALENDAR') === -1) {
- return;
- }
-
- var _startDate = null;
- var _description = '';
- var _location = null;
- var _organizer = null;
- var _priority = null;
- var _summary = null;
- var _categories = [];
- var _visibility = null;
- var _status = null;
- var _endDate = null;
- var _dueDate = null;
- var sep;
-
- if (str.indexOf('\r\n') > -1) {
- sep = '\r\n';
- } else if (str.indexOf('\n') > -1) {
- sep = '\n';
- } else {
- return;
- }
-
- function _convertTime(v) {
- var y = parseInt(v.substring(0, 4) , 10);
- var m = parseInt(v.substring(4, 6) , 10);
- var d = parseInt(v.substring(6, 8) , 10);
- var h = parseInt(v.substring(9, 11) , 10);
- var n = parseInt(v.substring(11, 13) , 10);
- var s = parseInt(v.substring(13, 15) , 10);
-
- return new tizen.TZDate(y, m, d, h, n, s);
- }
-
- var arr = str.split(sep);
-
- for (var i = 0; i < arr.length; i++) {
- if (arr[i].indexOf('SUMMARY') > -1) {
- _summary = arr[i].split(':')[1];
- } else if (arr[i].indexOf('CATEGORIES') > -1) {
- var c = arr[i].split(':')[1];
- _categories = c.split(',');
- } else if (arr[i].indexOf('ORGANIZER') > -1) {
- _organizer = arr[i].split('=')[1];
- } else if (arr[i].indexOf('DESCRIPTION') > -1) {
- _description = arr[i].split(':')[1];
- } else if (arr[i].indexOf('CLASS') > -1) {
- _visibility = arr[i].split(':')[1];
- } else if (arr[i].indexOf('LOCATION') > -1) {
- _location = arr[i].split(':')[1];
- } else if (arr[i].indexOf('PRIORITY') > -1) {
- _priority = arr[i].split(':')[1];
- } else if (arr[i].indexOf('STATUS') > -1) {
- _status = arr[i].split(':')[1];
- } else if (arr[i].indexOf('DTSTART') > -1) {
- _startDate = _convertTime(arr[i].split(':')[1]);
- } else if (arr[i].indexOf('DTEND') > -1) {
- _endDate = _convertTime(arr[i].split(':')[1]);
- } else if (arr[i].indexOf('DUE') > -1) {
- _dueDate = _convertTime(arr[i].split(':')[1]);
+ if (str.indexOf('VCALENDAR') === -1) {
+ return;
+ }
+
+ var _startDate = null;
+ var _description = '';
+ var _location = null;
+ var _organizer = null;
+ var _priority = null;
+ var _summary = null;
+ var _categories = [];
+ var _visibility = null;
+ var _status = null;
+ var _endDate = null;
+ var _dueDate = null;
+ var sep;
+
+ if (str.indexOf('\r\n') > -1) {
+ sep = '\r\n';
+ } else if (str.indexOf('\n') > -1) {
+ sep = '\n';
+ } else {
+ return;
+ }
+
+ function _convertTime(v) {
+ var y = parseInt(v.substring(0, 4), 10);
+ var m = parseInt(v.substring(4, 6), 10);
+ var d = parseInt(v.substring(6, 8), 10);
+ var h = parseInt(v.substring(9, 11), 10);
+ var n = parseInt(v.substring(11, 13), 10);
+ var s = parseInt(v.substring(13, 15), 10);
+
+ return new tizen.TZDate(y, m, d, h, n, s);
}
- }
-
- return {
- visibility: _visibility,
- startDate: _startDate,
- description: _description,
- location: _location,
- organizer: _organizer,
- priority: _priority,
- summary: _summary,
- status: _status,
- categories: _categories,
- endDate: _endDate,
- dueDate: _dueDate
- };
+ var arr = str.split(sep);
+
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i].indexOf('SUMMARY') > -1) {
+ _summary = arr[i].split(':')[1];
+ } else if (arr[i].indexOf('CATEGORIES') > -1) {
+ var c = arr[i].split(':')[1];
+ _categories = c.split(',');
+ } else if (arr[i].indexOf('ORGANIZER') > -1) {
+ _organizer = arr[i].split('=')[1];
+ } else if (arr[i].indexOf('DESCRIPTION') > -1) {
+ _description = arr[i].split(':')[1];
+ } else if (arr[i].indexOf('CLASS') > -1) {
+ _visibility = arr[i].split(':')[1];
+ } else if (arr[i].indexOf('LOCATION') > -1) {
+ _location = arr[i].split(':')[1];
+ } else if (arr[i].indexOf('PRIORITY') > -1) {
+ _priority = arr[i].split(':')[1];
+ } else if (arr[i].indexOf('STATUS') > -1) {
+ _status = arr[i].split(':')[1];
+ } else if (arr[i].indexOf('DTSTART') > -1) {
+ _startDate = _convertTime(arr[i].split(':')[1]);
+ } else if (arr[i].indexOf('DTEND') > -1) {
+ _endDate = _convertTime(arr[i].split(':')[1]);
+ } else if (arr[i].indexOf('DUE') > -1) {
+ _dueDate = _convertTime(arr[i].split(':')[1]);
+ }
+ }
+
+ return {
+ visibility: _visibility,
+ startDate: _startDate,
+ description: _description,
+ location: _location,
+ organizer: _organizer,
+ priority: _priority,
+ summary: _summary,
+ status: _status,
+ categories: _categories,
+ endDate: _endDate,
+ dueDate: _dueDate
+ };
}
var CalendarTaskInit = function(data) {
- CalendarItem.call(this, {
- status: CalendarItemStatus.NONE
- });
-
- var _dueDate = null;
- var _completedDate = null;
- var _progress = 0;
-
- Object.defineProperties(this, {
- dueDate: {
- get: function() {
- return _dueDate;
- },
- set: function(v) {
- if (!v instanceof tizen.TZDate && this.startDate) {
- v = this.startDate;
+ CalendarItem.call(this, {
+ status: CalendarItemStatus.NONE
+ });
+
+ var _dueDate = null;
+ var _completedDate = null;
+ var _progress = 0;
+
+ Object.defineProperties(this, {
+ dueDate: {
+ get: function() {
+ return _dueDate;
+ },
+ set: function(v) {
+ if (!v instanceof tizen.TZDate && this.startDate) {
+ v = this.startDate;
+ }
+
+ _dueDate = v instanceof tizen.TZDate ? v : _dueDate;
+ },
+ enumerable: true
+ },
+ completedDate: {
+ get: function() {
+ return _completedDate;
+ },
+ set: function(v) {
+ _completedDate = v instanceof tizen.TZDate ? v : _completedDate;
+ },
+ enumerable: true
+ },
+ progress: {
+ get: function() {
+ return _progress;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _progress = type_.isNumber(v) && (v >= 0 || v <= 100) ? v : _progress;
+ },
+ enumerable: true
}
+ });
- _dueDate = v instanceof tizen.TZDate ? v : _dueDate;
- },
- enumerable: true
- },
- completedDate: {
- get: function() {
- return _completedDate;
- },
- set: function(v) {
- _completedDate = v instanceof tizen.TZDate ? v : _completedDate;
- },
- enumerable: true
- },
- progress: {
- get: function() {
- return _progress;
- },
- set: function(v) {
- if (v === null) {
- return;
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
}
- _progress = (type_.isNumber(v) && (v >= 0 || v <= 100)) ? v : _progress;
- },
- enumerable: true
}
- });
-
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
- }
- }
};
var CalendarTask = function(taskInitDict, format) {
- validator_.isConstructorCall(this, CalendarTask);
+ validator_.isConstructorCall(this, CalendarTask);
- if (type_.isString(taskInitDict) && Object.keys(CalendarTextFormat).indexOf(format) > -1) {
- CalendarTaskInit.call(this, _convertFromStringToItem(taskInitDict));
- } else {
- CalendarTaskInit.call(this, taskInitDict);
- }
+ if (
+ type_.isString(taskInitDict) &&
+ Object.keys(CalendarTextFormat).indexOf(format) > -1
+ ) {
+ CalendarTaskInit.call(this, _convertFromStringToItem(taskInitDict));
+ } else {
+ CalendarTaskInit.call(this, taskInitDict);
+ }
};
CalendarTask.prototype = new CalendarItem();
CalendarTask.prototype.constructor = CalendarTask;
-
var CalendarEventInit = function(data) {
- CalendarItem.call(this, {
- status: CalendarItemStatus.NONE
- });
-
- var _isDetached = false;
- var _endDate = null;
- var _availability = EventAvailability.BUSY;
- var _recurrenceRule = null;
-
- var _validateReccurence = function(v) {
- if (_isDetached && v !== null) {
- throw new WebAPIException(WebAPIException.NOT_SUPPORTED_ERR,
- 'Recurrence can\'t be set because event is detached');
- }
+ CalendarItem.call(this, {
+ status: CalendarItemStatus.NONE
+ });
+
+ var _isDetached = false;
+ var _endDate = null;
+ var _availability = EventAvailability.BUSY;
+ var _recurrenceRule = null;
+
+ var _validateReccurence = function(v) {
+ if (_isDetached && v !== null) {
+ throw new WebAPIException(
+ WebAPIException.NOT_SUPPORTED_ERR,
+ 'Recurrence can\'t be set because event is detached'
+ );
+ }
- if (v === null || v instanceof tizen.CalendarRecurrenceRule) {
- return v;
- } else {
- return _recurrenceRule;
- }
- };
-
- Object.defineProperties(this, {
- isDetached: {
- get: function() {
- return _isDetached;
- },
- set: function(v) {
- if (_edit.canEdit) {
- _isDetached = v;
+ if (v === null || v instanceof tizen.CalendarRecurrenceRule) {
+ return v;
+ } else {
+ return _recurrenceRule;
}
- },
- enumerable: true
- },
- endDate: {
- get: function() {
- return _endDate;
- },
- set: function(v) {
- if (!v instanceof tizen.TZDate && this.startDate) {
- v = this.startDate;
+ };
+
+ Object.defineProperties(this, {
+ isDetached: {
+ get: function() {
+ return _isDetached;
+ },
+ set: function(v) {
+ if (_edit.canEdit) {
+ _isDetached = v;
+ }
+ },
+ enumerable: true
+ },
+ endDate: {
+ get: function() {
+ return _endDate;
+ },
+ set: function(v) {
+ if (!v instanceof tizen.TZDate && this.startDate) {
+ v = this.startDate;
+ }
+
+ _endDate = v instanceof tizen.TZDate ? v : _endDate;
+ },
+ enumerable: true
+ },
+ availability: {
+ get: function() {
+ return _availability;
+ },
+ set: function(v) {
+ _availability =
+ Object.keys(EventAvailability).indexOf(v) > -1 ? v : _availability;
+ },
+ enumerable: true
+ },
+ recurrenceRule: {
+ get: function() {
+ return _recurrenceRule;
+ },
+ set: function(v) {
+ _recurrenceRule = _validateReccurence(v);
+ },
+ enumerable: true
}
+ });
- _endDate = v instanceof tizen.TZDate ? v : _endDate;
- },
- enumerable: true
- },
- availability: {
- get: function() {
- return _availability;
- },
- set: function(v) {
- _availability = Object.keys(EventAvailability).indexOf(v) > -1 ? v :
- _availability;
- },
- enumerable: true
- },
- recurrenceRule: {
- get: function() {
- return _recurrenceRule;
- },
- set: function(v) {
- _recurrenceRule = _validateReccurence(v);
- },
- enumerable: true
- }
- });
-
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
var CalendarEvent = function(eventInitDict, format) {
- validator_.isConstructorCall(this, CalendarEvent);
+ validator_.isConstructorCall(this, CalendarEvent);
- if (type_.isString(eventInitDict) && Object.keys(CalendarTextFormat).indexOf(format) > -1) {
- CalendarEventInit.call(this, _convertFromStringToItem(eventInitDict));
- } else {
- CalendarEventInit.call(this, eventInitDict);
- }
+ if (
+ type_.isString(eventInitDict) &&
+ Object.keys(CalendarTextFormat).indexOf(format) > -1
+ ) {
+ CalendarEventInit.call(this, _convertFromStringToItem(eventInitDict));
+ } else {
+ CalendarEventInit.call(this, eventInitDict);
+ }
};
CalendarEvent.prototype = new CalendarItem();
CalendarEvent.prototype.constructor = CalendarEvent;
-var CalendarEvent_expandRecurrence = function(startDate, endDate, successCallback, errorCallback) {
- utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
- if (arguments.length < 3) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
- if (!(startDate instanceof tizen.TZDate)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
- if (!(endDate instanceof tizen.TZDate)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
- if (typeof successCallback !== 'function') {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
- if (errorCallback) {
- if (typeof errorCallback !== 'function') {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+var CalendarEvent_expandRecurrence = function(
+ startDate,
+ endDate,
+ successCallback,
+ errorCallback
+) {
+ utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
+ if (arguments.length < 3) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
- }
- if (!(this.recurrenceRule instanceof tizen.CalendarRecurrenceRule)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'The event is not recurring.');
- }
-
- var args = validator_.validateArgs(arguments, [
- {
- name: 'startDate',
- type: types_.PLATFORM_OBJECT,
- values: tizen.TZDate
- },
- {
- name: 'endDate',
- type: types_.PLATFORM_OBJECT,
- values: tizen.TZDate
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
+ if (!(startDate instanceof tizen.TZDate)) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
- ]);
-
- // invoke callbacks in "next tick"
- setTimeout(function() {
- var result = _recurrenceManager.get(this, startDate, endDate);
-
- if (result instanceof Array) {
- args.successCallback(result);
- } else if (args.errorCallback) {
- args.errorCallback(result);
+ if (!(endDate instanceof tizen.TZDate)) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
- }.bind(this), 1);
+ if (typeof successCallback !== 'function') {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
+ if (errorCallback) {
+ if (typeof errorCallback !== 'function') {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
+ }
+ if (!(this.recurrenceRule instanceof tizen.CalendarRecurrenceRule)) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'The event is not recurring.'
+ );
+ }
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'startDate',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.TZDate
+ },
+ {
+ name: 'endDate',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.TZDate
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ // invoke callbacks in "next tick"
+ setTimeout(
+ function() {
+ var result = _recurrenceManager.get(this, startDate, endDate);
+
+ if (result instanceof Array) {
+ args.successCallback(result);
+ } else if (args.errorCallback) {
+ args.errorCallback(result);
+ }
+ }.bind(this),
+ 1
+ );
};
CalendarEvent.prototype.expandRecurrence = function() {
- CalendarEvent_expandRecurrence.apply(this, arguments);
+ CalendarEvent_expandRecurrence.apply(this, arguments);
};
tizen.CalendarEventId = CalendarEventId;
diff --git a/src/calendar/js/calendar_manager.js b/src/calendar/js/calendar_manager.js
index 9f5bcca2..960a0323 100755
--- a/src/calendar/js/calendar_manager.js
+++ b/src/calendar/js/calendar_manager.js
@@ -19,167 +19,175 @@ var CalendarManager = function() {};
// IDs defined in C-API calendar_types2.h
var DefaultCalendarId = {
- EVENT: 1, // DEFAULT_EVENT_CALENDAR_BOOK_ID
- TASK: 2 // DEFAULT_TODO_CALENDAR_BOOK_ID
+ EVENT: 1, // DEFAULT_EVENT_CALENDAR_BOOK_ID
+ TASK: 2 // DEFAULT_TODO_CALENDAR_BOOK_ID
};
CalendarManager.prototype.getCalendars = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: Object.keys(CalendarType)
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = {
- type: args.type
- };
-
- var callback = function(result) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(CalendarType)
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {
+ type: args.type
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var calendars = native_.getResultObject(result);
+ var c = [];
+ calendars.forEach(function(i) {
+ c.push(new Calendar(new InternalCalendar(i)));
+ });
+ args.successCallback(c);
+ }
+ };
+
+ var result = native_.call('CalendarManager_getCalendars', callArgs, callback);
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var calendars = native_.getResultObject(result);
- var c = [];
- calendars.forEach(function(i) {
- c.push(new Calendar(new InternalCalendar(i)));
- });
- args.successCallback(c);
+ throw native_.getErrorObject(result);
}
- };
-
- var result = native_.call('CalendarManager_getCalendars', callArgs, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
var CalendarManager_getUnifiedCalendar = function() {
- utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: Object.keys(CalendarType)
- }]);
-
- return new Calendar(new InternalCalendar({
- type: args.type,
- isUnified: true
- }));
+ utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(CalendarType)
+ }
+ ]);
+
+ return new Calendar(
+ new InternalCalendar({
+ type: args.type,
+ isUnified: true
+ })
+ );
};
CalendarManager.prototype.getUnifiedCalendar = function() {
- return CalendarManager_getUnifiedCalendar.apply(this, arguments);
+ return CalendarManager_getUnifiedCalendar.apply(this, arguments);
};
var CalendarManager_getDefaultCalendar = function() {
- utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: Object.keys(CalendarType)
- }
- ]);
-
- return this.getCalendar(args.type, DefaultCalendarId[args.type]);
+ utils_.checkPrivilegeAccess(privilege_.CALENDAR_READ);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(CalendarType)
+ }
+ ]);
+
+ return this.getCalendar(args.type, DefaultCalendarId[args.type]);
};
CalendarManager.prototype.getDefaultCalendar = function() {
- return CalendarManager_getDefaultCalendar.apply(this, arguments);
+ return CalendarManager_getDefaultCalendar.apply(this, arguments);
};
var CalendarManagerGetCalendar = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: Object.keys(CalendarType)
- },
- {
- name: 'id',
- type: types_.STRING
- }
- ]);
-
- if (isNaN(Number(args.id))) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'Calendar not found');
- }
-
- var callArgs = {
- type: args.type,
- id: args.id
- };
-
- var result = native_.callSync('CalendarManager_getCalendar', callArgs);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- return new Calendar(new InternalCalendar(native_.getResultObject(result)));
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(CalendarType)
+ },
+ {
+ name: 'id',
+ type: types_.STRING
+ }
+ ]);
+
+ if (isNaN(Number(args.id))) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Calendar not found');
+ }
+
+ var callArgs = {
+ type: args.type,
+ id: args.id
+ };
+
+ var result = native_.callSync('CalendarManager_getCalendar', callArgs);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ return new Calendar(new InternalCalendar(native_.getResultObject(result)));
};
CalendarManager.prototype.getCalendar = function() {
- return CalendarManagerGetCalendar.apply(this, arguments);
+ return CalendarManagerGetCalendar.apply(this, arguments);
};
CalendarManager.prototype.addCalendar = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'calendar',
+ type: types_.PLATFORM_OBJECT,
+ values: Calendar
+ }
+ ]);
+
+ var callArgs = {
+ name: args.calendar.name,
+ accountId: args.calendar.accountId,
+ type: args.calendar.type
+ };
+
+ var result = native_.callSync('CalendarManager_addCalendar', callArgs);
- var args = validator_.validateArgs(arguments, [{
- name: 'calendar',
- type: types_.PLATFORM_OBJECT,
- values: Calendar
- }]);
-
- var callArgs = {
- name: args.calendar.name,
- accountId: args.calendar.accountId,
- type: args.calendar.type
- };
-
- var result = native_.callSync('CalendarManager_addCalendar', callArgs);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- args.calendar.id = new InternalCalendar({
- id: native_.getResultObject(result).id
- });
+ args.calendar.id = new InternalCalendar({
+ id: native_.getResultObject(result).id
+ });
};
CalendarManager.prototype.removeCalendar = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(CalendarType)
+ },
+ {
+ name: 'id',
+ type: types_.STRING
+ }
+ ]);
+
+ var callArgs = {
+ type: args.type,
+ id: args.id
+ };
+
+ var result = native_.callSync('CalendarManager_removeCalendar', callArgs);
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: Object.keys(CalendarType)
- },
- {
- name: 'id',
- type: types_.STRING
- }
- ]);
-
- var callArgs = {
- type: args.type,
- id: args.id
- };
-
- var result = native_.callSync('CalendarManager_removeCalendar', callArgs);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
exports = new CalendarManager();
diff --git a/src/calendar/js/calendar_recurrence_rule.js b/src/calendar/js/calendar_recurrence_rule.js
index b13ebffc..b6c38865 100755
--- a/src/calendar/js/calendar_recurrence_rule.js
+++ b/src/calendar/js/calendar_recurrence_rule.js
@@ -17,167 +17,171 @@
var _global = window || global || {};
var RecurrenceRuleFrequency = {
- DAILY: 'DAILY',
- WEEKLY: 'WEEKLY',
- MONTHLY: 'MONTHLY',
- YEARLY: 'YEARLY'
+ DAILY: 'DAILY',
+ WEEKLY: 'WEEKLY',
+ MONTHLY: 'MONTHLY',
+ YEARLY: 'YEARLY'
};
var ByDayValue = {
- MO: 'MO',
- TU: 'TU',
- WE: 'WE',
- TH: 'TH',
- FR: 'FR',
- SA: 'SA',
- SU: 'SU'
+ MO: 'MO',
+ TU: 'TU',
+ WE: 'WE',
+ TH: 'TH',
+ FR: 'FR',
+ SA: 'SA',
+ SU: 'SU'
};
var CalendarRecurrenceRuleInit = function(data) {
- var _interval = 1;
- var _untilDate = null;
- var _daysOfTheWeek = [];
- var _occurrenceCount = -1;
- var _setPositions = [];
- var _exceptions = [];
-
- function _validateDaysOfTheWeek(v) {
- if (type_.isArray(v)) {
- var allowedValues = Object.keys(ByDayValue);
- for (var i = 0; i < v.length; ++i) {
- if (allowedValues.indexOf(v[i]) < 0) {
- return false;
+ var _interval = 1;
+ var _untilDate = null;
+ var _daysOfTheWeek = [];
+ var _occurrenceCount = -1;
+ var _setPositions = [];
+ var _exceptions = [];
+
+ function _validateDaysOfTheWeek(v) {
+ if (type_.isArray(v)) {
+ var allowedValues = Object.keys(ByDayValue);
+ for (var i = 0; i < v.length; ++i) {
+ if (allowedValues.indexOf(v[i]) < 0) {
+ return false;
+ }
+ }
+ return true;
}
- }
- return true;
- }
-
- return false;
- }
- function _validateSetPositions(v) {
- var valid = false;
+ return false;
+ }
- if (type_.isArray(v)) {
- for (var i = 0; i < v.length; i++) {
- v[i] = parseInt(v[i]);
- if (isNaN(v[i]) || (v[i] < -366 || v[i] > 366 || v[i] === 0)) {
- return false;
+ function _validateSetPositions(v) {
+ var valid = false;
+
+ if (type_.isArray(v)) {
+ for (var i = 0; i < v.length; i++) {
+ v[i] = parseInt(v[i]);
+ if (isNaN(v[i]) || (v[i] < -366 || v[i] > 366 || v[i] === 0)) {
+ return false;
+ }
+ }
+ valid = true;
}
- }
- valid = true;
+ return valid;
}
- return valid;
- }
- function _validateExceptions(v) {
- var valid = false;
+ function _validateExceptions(v) {
+ var valid = false;
- if (type_.isArray(v)) {
- for (var i = 0; i < v.length; i++) {
- if (!(v[i] instanceof tizen.TZDate)) {
- return false;
+ if (type_.isArray(v)) {
+ for (var i = 0; i < v.length; i++) {
+ if (!(v[i] instanceof tizen.TZDate)) {
+ return false;
+ }
+ }
+ valid = true;
}
- }
- valid = true;
+ return valid;
}
- return valid;
- }
-
- Object.defineProperties(this, {
- interval: {
- get: function() {
- return _interval;
- },
- set: function(v) {
- _interval = (type_.isNumber(v) && v > 0) ? v : _interval;
- },
- enumerable: true
- },
- untilDate: {
- get: function() {
- return _untilDate;
- },
- set: function(v) {
- if (v instanceof tizen.TZDate) {
- _untilDate = v;
- }
- },
- enumerable: true
- },
- occurrenceCount: {
- get: function() {
- return _occurrenceCount;
- },
- set: function(v) {
- if (type_.isNumber(v) && v >= -1) {
- _occurrenceCount = v;
+
+ Object.defineProperties(this, {
+ interval: {
+ get: function() {
+ return _interval;
+ },
+ set: function(v) {
+ _interval = type_.isNumber(v) && v > 0 ? v : _interval;
+ },
+ enumerable: true
+ },
+ untilDate: {
+ get: function() {
+ return _untilDate;
+ },
+ set: function(v) {
+ if (v instanceof tizen.TZDate) {
+ _untilDate = v;
+ }
+ },
+ enumerable: true
+ },
+ occurrenceCount: {
+ get: function() {
+ return _occurrenceCount;
+ },
+ set: function(v) {
+ if (type_.isNumber(v) && v >= -1) {
+ _occurrenceCount = v;
+ }
+ },
+ enumerable: true
+ },
+ daysOfTheWeek: {
+ get: function() {
+ return _daysOfTheWeek;
+ },
+ set: function(v) {
+ _daysOfTheWeek = _validateDaysOfTheWeek(v) ? v : _daysOfTheWeek;
+ },
+ enumerable: true
+ },
+ setPositions: {
+ get: function() {
+ return _setPositions;
+ },
+ set: function(v) {
+ _setPositions = _validateSetPositions(v) ? v : _setPositions;
+ },
+ enumerable: true
+ },
+ exceptions: {
+ get: function() {
+ return _exceptions;
+ },
+ set: function(v) {
+ _exceptions = _validateExceptions(v) ? v : _exceptions;
+ },
+ enumerable: true
}
- },
- enumerable: true
- },
- daysOfTheWeek: {
- get: function() {
- return _daysOfTheWeek;
- },
- set: function(v) {
- _daysOfTheWeek = _validateDaysOfTheWeek(v) ? v : _daysOfTheWeek;
- },
- enumerable: true
- },
- setPositions: {
- get: function() {
- return _setPositions;
- },
- set: function(v) {
- _setPositions = _validateSetPositions(v) ? v : _setPositions;
- },
- enumerable: true
- },
- exceptions: {
- get: function() {
- return _exceptions;
- },
- set: function(v) {
- _exceptions = _validateExceptions(v) ? v : _exceptions;
- },
- enumerable: true
- }
- });
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
var CalendarRecurrenceRule = function(frequency, ruleInitDict) {
- validator_.isConstructorCall(this, CalendarRecurrenceRule);
-
- CalendarRecurrenceRuleInit.call(this, ruleInitDict);
-
- var _frequency = null;
-
- Object.defineProperties(this, {
- frequency: {
- get: function() {
- return _frequency;
- },
- set: function(v) {
- if (v === null) {
- return;
+ validator_.isConstructorCall(this, CalendarRecurrenceRule);
+
+ CalendarRecurrenceRuleInit.call(this, ruleInitDict);
+
+ var _frequency = null;
+
+ Object.defineProperties(this, {
+ frequency: {
+ get: function() {
+ return _frequency;
+ },
+ set: function(v) {
+ if (v === null) {
+ return;
+ }
+ _frequency = converter_.toEnum(
+ v,
+ Object.keys(RecurrenceRuleFrequency),
+ false
+ );
+ },
+ enumerable: true
}
- _frequency = converter_.toEnum(v, Object.keys(RecurrenceRuleFrequency), false);
- },
- enumerable: true
- }
- });
+ });
- // @todo fix UTC, according to documentation frequency is not optional
- this.frequency = (!frequency) ? 'DAILY' : frequency;
+ // @todo fix UTC, according to documentation frequency is not optional
+ this.frequency = !frequency ? 'DAILY' : frequency;
};
CalendarRecurrenceRule.prototype = new CalendarRecurrenceRuleInit();
diff --git a/src/calendar/js/common.js b/src/calendar/js/common.js
index cc7427e8..1a8633fa 100755
--- a/src/calendar/js/common.js
+++ b/src/calendar/js/common.js
@@ -26,15 +26,15 @@ var types_ = validator_.Types;
var native_ = new utils_.NativeManager(extension);
var EditManager = function() {
- this.canEdit = false;
+ this.canEdit = false;
};
EditManager.prototype.allow = function() {
- this.canEdit = true;
+ this.canEdit = true;
};
EditManager.prototype.disallow = function() {
- this.canEdit = false;
+ this.canEdit = false;
};
var _edit = new EditManager();
@@ -42,224 +42,242 @@ var _edit = new EditManager();
var ItemConverter = function() {};
ItemConverter.prototype.toTizenObject = function(item) {
- var tmp = {};
- for (var prop in item) {
- if (prop === 'startDate' ||
+ var tmp = {};
+ for (var prop in item) {
+ if (
+ prop === 'startDate' ||
prop === 'endDate' ||
prop === 'dueDate' ||
prop === 'completedDate' ||
- prop === 'lastModificationDate') {
- tmp[prop] = dateConverter_.toTZDate(item[prop], item.isAllDay);
- } else {
- tmp[prop] = item[prop];
- }
- }
-
- var alarms = [];
- var alarm, time;
- for (var i = 0; i < tmp.alarms.length; i++) {
- alarm = tmp.alarms[i];
- if (alarm.absoluteDate) {
- time = dateConverter_.toTZDate(alarm.absoluteDate, tmp.isAllDay);
- } else if (alarm.before) {
- time = new tizen.TimeDuration(alarm.before.length, alarm.before.unit);
+ prop === 'lastModificationDate'
+ ) {
+ tmp[prop] = dateConverter_.toTZDate(item[prop], item.isAllDay);
+ } else {
+ tmp[prop] = item[prop];
+ }
}
- alarms.push(new tizen.CalendarAlarm(time, alarm.method, alarm.description));
- }
- tmp.alarms = alarms;
-
- var attendees = [];
- for (var i = 0; i < tmp.attendees.length; i++) {
- if (tmp.attendees[i].contactRef) {
- var contactRef = new tizen.ContactRef(tmp.attendees[i].contactRef.addressBookId,
- tmp.attendees[i].contactRef.contactId);
- tmp.attendees[i].contactRef = contactRef;
+
+ var alarms = [];
+ var alarm, time;
+ for (var i = 0; i < tmp.alarms.length; i++) {
+ alarm = tmp.alarms[i];
+ if (alarm.absoluteDate) {
+ time = dateConverter_.toTZDate(alarm.absoluteDate, tmp.isAllDay);
+ } else if (alarm.before) {
+ time = new tizen.TimeDuration(alarm.before.length, alarm.before.unit);
+ }
+ alarms.push(new tizen.CalendarAlarm(time, alarm.method, alarm.description));
}
- if (tmp.attendees[i].uri) {
- attendees.push(new tizen.CalendarAttendee(tmp.attendees[i].uri, tmp.attendees[i]));
+ tmp.alarms = alarms;
+
+ var attendees = [];
+ for (var i = 0; i < tmp.attendees.length; i++) {
+ if (tmp.attendees[i].contactRef) {
+ var contactRef = new tizen.ContactRef(
+ tmp.attendees[i].contactRef.addressBookId,
+ tmp.attendees[i].contactRef.contactId
+ );
+ tmp.attendees[i].contactRef = contactRef;
+ }
+ if (tmp.attendees[i].uri) {
+ attendees.push(
+ new tizen.CalendarAttendee(tmp.attendees[i].uri, tmp.attendees[i])
+ );
+ }
}
- }
- tmp.attendees = attendees;
-
- var untilDate;
- var exceptions = [];
- if (tmp.recurrenceRule) {
- untilDate = dateConverter_.toTZDate(tmp.recurrenceRule.untilDate, tmp.isAllDay);
- tmp.recurrenceRule.untilDate = untilDate;
+ tmp.attendees = attendees;
+
+ var untilDate;
+ var exceptions = [];
+ if (tmp.recurrenceRule) {
+ untilDate = dateConverter_.toTZDate(tmp.recurrenceRule.untilDate, tmp.isAllDay);
+ tmp.recurrenceRule.untilDate = untilDate;
+
+ for (var i = 0; i < tmp.recurrenceRule.exceptions.length; i++) {
+ exceptions.push(
+ dateConverter_.toTZDate(tmp.recurrenceRule.exceptions[i], tmp.isAllDay)
+ );
+ }
+ tmp.recurrenceRule.exceptions = exceptions;
- for (var i = 0; i < tmp.recurrenceRule.exceptions.length; i++) {
- exceptions.push(dateConverter_.toTZDate(tmp.recurrenceRule.exceptions[i], tmp.isAllDay));
+ var recurrenceRule = new tizen.CalendarRecurrenceRule(
+ tmp.recurrenceRule.frequency,
+ tmp.recurrenceRule
+ );
+ tmp.recurrenceRule = recurrenceRule;
}
- tmp.recurrenceRule.exceptions = exceptions;
-
- var recurrenceRule = new tizen.CalendarRecurrenceRule(tmp.recurrenceRule.frequency, tmp.recurrenceRule);
- tmp.recurrenceRule = recurrenceRule;
- }
- if (tmp.duration) {
- var duration = new tizen.TimeDuration(tmp.duration.length, tmp.duration.unit);
- tmp.duration = duration;
- }
+ if (tmp.duration) {
+ var duration = new tizen.TimeDuration(tmp.duration.length, tmp.duration.unit);
+ tmp.duration = duration;
+ }
- if (tmp.geolocation) {
- var geolocation = new tizen.SimpleCoordinates(tmp.geolocation.latitude, tmp.geolocation.longitude);
- tmp.geolocation = geolocation;
- }
+ if (tmp.geolocation) {
+ var geolocation = new tizen.SimpleCoordinates(
+ tmp.geolocation.latitude,
+ tmp.geolocation.longitude
+ );
+ tmp.geolocation = geolocation;
+ }
- return tmp;
+ return tmp;
};
ItemConverter.prototype.fromTizenObject = function(item) {
- var tmp = {};
- for (var prop in item) {
- if (item[prop] instanceof tizen.TZDate) {
- tmp[prop] = dateConverter_.fromTZDate(item[prop]);
- } else if (item[prop] instanceof Array) {
- tmp[prop] = [];
- for (var i = 0, length = item[prop].length; i < length; i++) {
- if (item[prop][i] instanceof _global.Object) {
- tmp[prop][i] = {};
- for (var p in item[prop][i]) {
- if (item[prop][i][p] instanceof tizen.TZDate) {
- tmp[prop][i][p] = dateConverter_.fromTZDate(item[prop][i][p]);
- } else {
- tmp[prop][i][p] = item[prop][i][p];
+ var tmp = {};
+ for (var prop in item) {
+ if (item[prop] instanceof tizen.TZDate) {
+ tmp[prop] = dateConverter_.fromTZDate(item[prop]);
+ } else if (item[prop] instanceof Array) {
+ tmp[prop] = [];
+ for (var i = 0, length = item[prop].length; i < length; i++) {
+ if (item[prop][i] instanceof _global.Object) {
+ tmp[prop][i] = {};
+ for (var p in item[prop][i]) {
+ if (item[prop][i][p] instanceof tizen.TZDate) {
+ tmp[prop][i][p] = dateConverter_.fromTZDate(item[prop][i][p]);
+ } else {
+ tmp[prop][i][p] = item[prop][i][p];
+ }
+ }
+ } else {
+ tmp[prop] = item[prop];
+ }
+ }
+ } else if (item[prop] instanceof _global.Object) {
+ tmp[prop] = {};
+ for (var p in item[prop]) {
+ if (item[prop][p] instanceof tizen.TZDate) {
+ tmp[prop][p] = dateConverter_.fromTZDate(item[prop][p]);
+ } else if (item[prop][p] instanceof Array) {
+ tmp[prop][p] = [];
+ for (var j = 0, l = item[prop][p].length; j < l; j++) {
+ tmp[prop][p].push(dateConverter_.fromTZDate(item[prop][p][j]));
+ }
+ } else {
+ tmp[prop][p] = item[prop][p];
+ }
}
- }
- } else {
- tmp[prop] = item[prop];
- }
- }
- } else if (item[prop] instanceof _global.Object) {
- tmp[prop] = {};
- for (var p in item[prop]) {
- if (item[prop][p] instanceof tizen.TZDate) {
- tmp[prop][p] = dateConverter_.fromTZDate(item[prop][p]);
- } else if (item[prop][p] instanceof Array) {
- tmp[prop][p] = [];
- for (var j = 0, l = item[prop][p].length; j < l; j++) {
- tmp[prop][p].push(dateConverter_.fromTZDate(item[prop][p][j]));
- }
} else {
- tmp[prop][p] = item[prop][p];
+ tmp[prop] = item[prop];
}
- }
- } else {
- tmp[prop] = item[prop];
}
- }
- return tmp;
+ return tmp;
};
var _itemConverter = new ItemConverter();
function _daysInYear(y) {
- if ((y % 4 === 0 && y % 100) || y % 400 === 0) {
- return 366;
- }
- return 365;
+ if ((y % 4 === 0 && y % 100) || y % 400 === 0) {
+ return 366;
+ }
+ return 365;
}
function _daysInMonth(m, y) {
- switch (m) {
- case 1 :
- return _daysInYear(y) === 366 ? 29 : 28;
- case 3 :
- case 5 :
- case 8 :
- case 10 :
- return 30;
- default :
- return 31;
- }
+ switch (m) {
+ case 1:
+ return _daysInYear(y) === 366 ? 29 : 28;
+ case 3:
+ case 5:
+ case 8:
+ case 10:
+ return 30;
+ default:
+ return 31;
+ }
}
var RecurrenceManager = function() {};
RecurrenceManager.prototype.get = function(event, startDate, endDate) {
- var events = [];
- var frequency = event.recurrenceRule.frequency;
- var interval = event.recurrenceRule.interval;
- var untilDate = event.recurrenceRule.untilDate;
- var occurrenceCount = event.recurrenceRule.occurrenceCount;
- var exceptions = event.recurrenceRule.exceptions;
- var isDetached = event.isDetached;
- var startEvent = event.startDate;
- var startDate = startDate;
- var endDate = endDate;
-
- if (isDetached) {
- return 'The event is detached.';
- }
-
- if (startEvent.laterThan(startDate)) {
- startDate = startEvent;
- }
-
- if (untilDate) {
- endDate = untilDate.laterThan(endDate) ? endDate : untilDate;
- }
-
- var timeDifference = endDate.difference(startDate);
- var daysDifference = timeDifference.length;
-
- function checkDays(date) {
- switch (frequency) {
- case 'DAILY' :
- return 1;
- case 'WEEKLY' :
- return 7;
- case 'MONTHLY' :
- return _daysInMonth(date.getMonth(), date.getFullYear());
- case 'YEARLY' :
- return _daysInYear(date.getFullYear());
+ var events = [];
+ var frequency = event.recurrenceRule.frequency;
+ var interval = event.recurrenceRule.interval;
+ var untilDate = event.recurrenceRule.untilDate;
+ var occurrenceCount = event.recurrenceRule.occurrenceCount;
+ var exceptions = event.recurrenceRule.exceptions;
+ var isDetached = event.isDetached;
+ var startEvent = event.startDate;
+ var startDate = startDate;
+ var endDate = endDate;
+
+ if (isDetached) {
+ return 'The event is detached.';
}
- }
- function checkException(date) {
- for (var j = 0; j < exceptions.length; j++) {
- if (exceptions[j].equalsTo(date)) {
- return true;
- }
+ if (startEvent.laterThan(startDate)) {
+ startDate = startEvent;
}
- return false;
- }
-
- var dates = [];
- var date = startDate;
- var push = true;
- var _interval = occurrenceCount >= 0 ? occurrenceCount :
- (daysDifference + 1) / checkDays(startDate);
-
- for (var i = 0; i < _interval; ++i) {
- if (exceptions) {
- checkException(date) ? push = false : null;
+
+ if (untilDate) {
+ endDate = untilDate.laterThan(endDate) ? endDate : untilDate;
}
- if (push) {
- if (endDate.laterThan(date) || endDate.equalsTo(date)) {
- dates.push(date);
- }
+ var timeDifference = endDate.difference(startDate);
+ var daysDifference = timeDifference.length;
+
+ function checkDays(date) {
+ switch (frequency) {
+ case 'DAILY':
+ return 1;
+ case 'WEEKLY':
+ return 7;
+ case 'MONTHLY':
+ return _daysInMonth(date.getMonth(), date.getFullYear());
+ case 'YEARLY':
+ return _daysInYear(date.getFullYear());
+ }
}
- date = date.addDuration(new tizen.TimeDuration((checkDays(date) * interval), 'DAYS'));
- }
-
- var tmp;
- for (var i = 0; i < dates.length; i++) {
- tmp = event.clone();
- _edit.allow();
- tmp.startDate = dates[i];
- if (event.id instanceof tizen.CalendarEventId) {
- tmp.id = new tizen.CalendarEventId(event.id.uid, +new Date());
- tmp.isDetached = true;
+
+ function checkException(date) {
+ for (var j = 0; j < exceptions.length; j++) {
+ if (exceptions[j].equalsTo(date)) {
+ return true;
+ }
+ }
+ return false;
}
- _edit.disallow();
- events.push(tmp);
- }
+ var dates = [];
+ var date = startDate;
+ var push = true;
+ var _interval =
+ occurrenceCount >= 0
+ ? occurrenceCount
+ : (daysDifference + 1) / checkDays(startDate);
+
+ for (var i = 0; i < _interval; ++i) {
+ if (exceptions) {
+ checkException(date) ? (push = false) : null;
+ }
+
+ if (push) {
+ if (endDate.laterThan(date) || endDate.equalsTo(date)) {
+ dates.push(date);
+ }
+ }
+ date = date.addDuration(
+ new tizen.TimeDuration(checkDays(date) * interval, 'DAYS')
+ );
+ }
+
+ var tmp;
+ for (var i = 0; i < dates.length; i++) {
+ tmp = event.clone();
+ _edit.allow();
+ tmp.startDate = dates[i];
+ if (event.id instanceof tizen.CalendarEventId) {
+ tmp.id = new tizen.CalendarEventId(event.id.uid, +new Date());
+ tmp.isDetached = true;
+ }
+ _edit.disallow();
+
+ events.push(tmp);
+ }
- return events;
+ return events;
};
var _recurrenceManager = new RecurrenceManager();
diff --git a/src/callhistory/callhistory_api.js b/src/callhistory/callhistory_api.js
index e2ed279c..f930b972 100755
--- a/src/callhistory/callhistory_api.js
+++ b/src/callhistory/callhistory_api.js
@@ -26,22 +26,22 @@ function _createCallHistoryEntries(e) {
var entries_array = [];
var entries = e.data;
- entries.forEach(function (data) {
+ entries.forEach(function(data) {
entries_array.push(new CallHistoryEntry(data));
});
return entries_array;
-};
+}
function _getUidFromCallHistoryEntry(entries) {
var uid = [];
- entries.forEach(function (data) {
+ entries.forEach(function(data) {
uid.push(data.uid);
});
return uid;
-};
+}
function ListenerManager(native, listenerName) {
this.listeners = {};
@@ -49,7 +49,7 @@ function ListenerManager(native, listenerName) {
this.nativeSet = false;
this.native = native;
this.listenerName = listenerName;
-};
+}
ListenerManager.prototype.onListenerCalled = function(msg) {
var d = undefined;
@@ -69,7 +69,10 @@ ListenerManager.prototype.onListenerCalled = function(msg) {
}
for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId) && this.listeners[watchId][msg.action]) {
+ if (
+ this.listeners.hasOwnProperty(watchId) &&
+ this.listeners[watchId][msg.action]
+ ) {
this.listeners[watchId][msg.action](d);
}
}
@@ -78,8 +81,8 @@ ListenerManager.prototype.onListenerCalled = function(msg) {
ListenerManager.prototype.addListener = function(callback) {
var id = this.nextId;
if (!this.nativeSet) {
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- this.nativeSet = true;
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ this.nativeSet = true;
}
this.listeners[id] = callback;
++this.nextId;
@@ -97,50 +100,54 @@ ListenerManager.prototype.removeListener = function(watchId) {
};
var CALL_HISTORY_CHANGE_LISTENER = 'CallHistoryChangeCallback';
-var callHistoryChangeListener = new ListenerManager(native_, CALL_HISTORY_CHANGE_LISTENER);
+var callHistoryChangeListener = new ListenerManager(
+ native_,
+ CALL_HISTORY_CHANGE_LISTENER
+);
-function CallHistory() {
-};
+function CallHistory() {}
CallHistory.prototype.find = function() {
var args = validator_.validateArgs(arguments, [
{
- name : 'successCallback',
- type : types_.FUNCTION,
+ name: 'successCallback',
+ type: types_.FUNCTION
},
{
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'filter',
- type : types_.PLATFORM_OBJECT,
- optional : true,
- nullable : true,
- values : [tizen.AttributeFilter,
- tizen.AttributeRangeFilter,
- tizen.CompositeFilter]
+ name: 'filter',
+ type: types_.PLATFORM_OBJECT,
+ optional: true,
+ nullable: true,
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ]
},
{
- name : 'sortMode',
- type : types_.PLATFORM_OBJECT,
- optional : true,
- nullable : true,
- values : tizen.SortMode
+ name: 'sortMode',
+ type: types_.PLATFORM_OBJECT,
+ optional: true,
+ nullable: true,
+ values: tizen.SortMode
},
{
- name : 'limit',
- type : types_.UNSIGNED_LONG,
- optional : true,
- nullable : true
+ name: 'limit',
+ type: types_.UNSIGNED_LONG,
+ optional: true,
+ nullable: true
},
{
- name : 'offset',
- type : types_.UNSIGNED_LONG,
- optional : true,
- nullable : true
+ name: 'offset',
+ type: types_.UNSIGNED_LONG,
+ optional: true,
+ nullable: true
}
]);
@@ -161,16 +168,16 @@ CallHistory.prototype.find = function() {
var result = native_.call('CallHistory_find', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
CallHistory.prototype.remove = function() {
var args = validator_.validateArgs(arguments, [
{
- name : 'entry',
- type : types_.PLATFORM_OBJECT,
- values : CallHistoryEntry
+ name: 'entry',
+ type: types_.PLATFORM_OBJECT,
+ values: CallHistoryEntry
}
]);
@@ -179,7 +186,7 @@ CallHistory.prototype.remove = function() {
var result = native_.callSync('CallHistory_remove', callArgs);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
return;
@@ -188,21 +195,21 @@ CallHistory.prototype.remove = function() {
CallHistory.prototype.removeBatch = function() {
var args = validator_.validateArgs(arguments, [
{
- name : 'entries',
- type : types_.ARRAY,
- values : CallHistoryEntry
+ name: 'entries',
+ type: types_.ARRAY,
+ values: CallHistoryEntry
},
{
- name : 'successCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
@@ -220,23 +227,23 @@ CallHistory.prototype.removeBatch = function() {
var result = native_.call('CallHistory_removeBatch', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
CallHistory.prototype.removeAll = function() {
var args = validator_.validateArgs(arguments, [
{
- name : 'successCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
},
{
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
@@ -250,23 +257,23 @@ CallHistory.prototype.removeAll = function() {
var result = native_.call('CallHistory_removeAll', {}, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
CallHistory.prototype.addChangeListener = function() {
var args = validator_.validateArgs(arguments, [
{
- name : 'eventCallback',
- type : types_.LISTENER,
- values : ['onadded', 'onchanged', 'onremoved']
+ name: 'eventCallback',
+ type: types_.LISTENER,
+ values: ['onadded', 'onchanged', 'onremoved']
}
]);
if (T_.isEmptyObject(callHistoryChangeListener.listeners)) {
var result = native_.callSync('CallHistory_addChangeListener');
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
}
@@ -280,8 +287,8 @@ function removeChangeListener() {
var args = validator_.validateArgs(arguments, [
{
- name : 'watchId',
- type : types_.LONG
+ name: 'watchId',
+ type: types_.LONG
}
]);
@@ -290,13 +297,13 @@ function removeChangeListener() {
if (T_.isEmptyObject(callHistoryChangeListener.listeners)) {
var result = native_.callSync('CallHistory_removeChangeListener');
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
}
-};
+}
CallHistory.prototype.removeChangeListener = function() {
- removeChangeListener.apply(this, arguments);
+ removeChangeListener.apply(this, arguments);
};
function RemoteParty(data) {
@@ -312,12 +319,14 @@ function RemoteParty(data) {
enumerable: true
}
});
-};
+}
function CallHistoryEntry(data) {
function directionSetter(val) {
if (direction === 'MISSEDNEW' && val === 'MISSED') {
- var result = native_.callSync('CallHistory_setMissedDirection', {uid : this.uid});
+ var result = native_.callSync('CallHistory_setMissedDirection', {
+ uid: this.uid
+ });
if (native_.isSuccess(result)) {
direction = 'MISSED';
}
@@ -326,7 +335,7 @@ function CallHistoryEntry(data) {
function createRemoteParties(parties) {
var parties_array = [];
- parties.forEach(function (data) {
+ parties.forEach(function(data) {
parties_array.push(new RemoteParty(data));
});
return parties_array;
@@ -338,35 +347,38 @@ function CallHistoryEntry(data) {
}
Object.defineProperties(this, {
- uid: {value: converter_.toString(data.uid), writable: false, enumerable: true},
- type: {value: data.type, writable: false, enumerable: true},
- features : {
+ uid: { value: converter_.toString(data.uid), writable: false, enumerable: true },
+ type: { value: data.type, writable: false, enumerable: true },
+ features: {
value: data.features ? data.features : null,
writable: false,
enumerable: true
},
- remoteParties : {
- value : createRemoteParties(data.remoteParties),
+ remoteParties: {
+ value: createRemoteParties(data.remoteParties),
writable: false,
enumerable: true
},
- startTime: {value: new Date(Number(data.startTime) * 1000),
+ startTime: {
+ value: new Date(Number(data.startTime) * 1000),
writable: false,
enumerable: true
},
- duration: {value: data.duration, writable: false, enumerable: true},
+ duration: { value: data.duration, writable: false, enumerable: true },
direction: {
enumerable: true,
- set : directionSetter,
- get : function() { return direction; }
+ set: directionSetter,
+ get: function() {
+ return direction;
+ }
},
callingParty: {
value: data.callingParty ? data.callingParty : null,
writable: false,
enumerable: true
- },
+ }
});
-};
+}
// Exports
exports = new CallHistory();
diff --git a/src/contact/js/address_book.js b/src/contact/js/address_book.js
index b99dbb15..e8f45fd3 100755
--- a/src/contact/js/address_book.js
+++ b/src/contact/js/address_book.js
@@ -21,702 +21,760 @@ var _contactListenerRegistered = false;
var _contactCallbackMap = {};
var _filterById = function(array, id) {
- var ret = [];
- for (var i = 0; i < array.length; ++i) {
- if (array[i].addressBookId === id) {
- ret.push(_promote(array[i], Contact));
+ var ret = [];
+ for (var i = 0; i < array.length; ++i) {
+ if (array[i].addressBookId === id) {
+ ret.push(_promote(array[i], Contact));
+ }
}
- }
- return ret;
+ return ret;
};
var _contactChangeListener = function(result) {
- var unifiedId = UNIFIED_ADDRESSBOOK_ID;
- var watchId;
- var callback, i;
-
- // Unified address book case
- if (_contactCallbackMap.hasOwnProperty(unifiedId)) {
- for (watchId in _contactCallbackMap[unifiedId]) {
- if (_contactCallbackMap[unifiedId].hasOwnProperty(watchId)) {
- callback = _contactCallbackMap[unifiedId][watchId].successCallback;
- if (result.added.length) {
- native_.callIfPossible(callback.oncontactsadded, _promote(result.added, Contact));
- }
- if (result.updated.length) {
- native_.callIfPossible(callback.oncontactsupdated, _promote(result.updated, Contact));
+ var unifiedId = UNIFIED_ADDRESSBOOK_ID;
+ var watchId;
+ var callback, i;
+
+ // Unified address book case
+ if (_contactCallbackMap.hasOwnProperty(unifiedId)) {
+ for (watchId in _contactCallbackMap[unifiedId]) {
+ if (_contactCallbackMap[unifiedId].hasOwnProperty(watchId)) {
+ callback = _contactCallbackMap[unifiedId][watchId].successCallback;
+ if (result.added.length) {
+ native_.callIfPossible(
+ callback.oncontactsadded,
+ _promote(result.added, Contact)
+ );
+ }
+ if (result.updated.length) {
+ native_.callIfPossible(
+ callback.oncontactsupdated,
+ _promote(result.updated, Contact)
+ );
+ }
+ if (result.removed.length) {
+ var allRemoved = [];
+ for (i = 0; i < result.removed.length; ++i) {
+ allRemoved.push(result.removed[i].id);
+ }
+ native_.callIfPossible(callback.oncontactsremoved, result.allRemoved);
+ }
+ }
}
- if (result.removed.length) {
- var allRemoved = [];
- for (i = 0; i < result.removed.length; ++i) {
- allRemoved.push(result.removed[i].id);
- }
- native_.callIfPossible(callback.oncontactsremoved, result.allRemoved);
- }
- }
}
- }
-
- for (var callbackAddressbookId in _contactCallbackMap) {
- if (callbackAddressbookId !== UNIFIED_ADDRESSBOOK_ID &&
- _contactCallbackMap.hasOwnProperty(callbackAddressbookId)) {
-
- var filteredAdded = [];
- var filteredUpdated = [];
- var filteredRemoved = [];
-
- if (result.added.length) {
- filteredAdded = _filterById(result.added, callbackAddressbookId);
- }
- if (result.updated.length) {
- filteredUpdated = _filterById(result.updated, callbackAddressbookId);
- }
- if (result.removed.length) {
- for (i = 0; i < result.removed.length; ++i) {
- if (result.removed[i].addressBookId === callbackAddressbookId) {
- filteredRemoved.push(result.removed[i].id);
- }
- }
- }
-
- for (watchId in _contactCallbackMap[callbackAddressbookId]) {
- if (_contactCallbackMap[callbackAddressbookId].hasOwnProperty(watchId)) {
- callback = _contactCallbackMap[callbackAddressbookId][watchId].successCallback;
- if (filteredAdded.length) {
- native_.callIfPossible(callback.oncontactsadded, filteredAdded);
- }
- if (filteredUpdated.length) {
- native_.callIfPossible(callback.oncontactsupdated, filteredUpdated);
- }
- if (filteredRemoved.length) {
- native_.callIfPossible(callback.oncontactsremoved, filteredRemoved);
- }
+
+ for (var callbackAddressbookId in _contactCallbackMap) {
+ if (
+ callbackAddressbookId !== UNIFIED_ADDRESSBOOK_ID &&
+ _contactCallbackMap.hasOwnProperty(callbackAddressbookId)
+ ) {
+ var filteredAdded = [];
+ var filteredUpdated = [];
+ var filteredRemoved = [];
+
+ if (result.added.length) {
+ filteredAdded = _filterById(result.added, callbackAddressbookId);
+ }
+ if (result.updated.length) {
+ filteredUpdated = _filterById(result.updated, callbackAddressbookId);
+ }
+ if (result.removed.length) {
+ for (i = 0; i < result.removed.length; ++i) {
+ if (result.removed[i].addressBookId === callbackAddressbookId) {
+ filteredRemoved.push(result.removed[i].id);
+ }
+ }
+ }
+
+ for (watchId in _contactCallbackMap[callbackAddressbookId]) {
+ if (_contactCallbackMap[callbackAddressbookId].hasOwnProperty(watchId)) {
+ callback =
+ _contactCallbackMap[callbackAddressbookId][watchId]
+ .successCallback;
+ if (filteredAdded.length) {
+ native_.callIfPossible(callback.oncontactsadded, filteredAdded);
+ }
+ if (filteredUpdated.length) {
+ native_.callIfPossible(
+ callback.oncontactsupdated,
+ filteredUpdated
+ );
+ }
+ if (filteredRemoved.length) {
+ native_.callIfPossible(
+ callback.oncontactsremoved,
+ filteredRemoved
+ );
+ }
+ }
+ }
}
- }
}
- }
};
var AddressBook = function(accountId, name) {
- validator_.isConstructorCall(this, AddressBook);
-
- var id_ = null;
- var name_ = '';
- var readOnly_ = false;
- var accountId_ = null;
-
- if (type_.isNumber(accountId)) {
- accountId_ = accountId;
- }
- if (type_.isString(name)) {
- name_ = name;
- }
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return id_;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- id_ = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- accountId: {
- get: function() {
- return accountId_;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- accountId_ = converter_.toLong(v, true);
- }
- },
- enumerable: true
- },
- name: {
- get: function() {
- return name_;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- name_ = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- readOnly: {
- get: function() {
- return readOnly_;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- readOnly_ = converter_.toBoolean(v, false);
- }
- },
- enumerable: true
+ validator_.isConstructorCall(this, AddressBook);
+
+ var id_ = null;
+ var name_ = '';
+ var readOnly_ = false;
+ var accountId_ = null;
+
+ if (type_.isNumber(accountId)) {
+ accountId_ = accountId;
+ }
+ if (type_.isString(name)) {
+ name_ = name;
}
- });
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return id_;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ id_ = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ accountId: {
+ get: function() {
+ return accountId_;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ accountId_ = converter_.toLong(v, true);
+ }
+ },
+ enumerable: true
+ },
+ name: {
+ get: function() {
+ return name_;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ name_ = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ readOnly: {
+ get: function() {
+ return readOnly_;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ readOnly_ = converter_.toBoolean(v, false);
+ }
+ },
+ enumerable: true
+ }
+ });
};
function _prepareContact(data) {
- return _editGuard.run(function() {
- var contact = new Contact(data);
-
- if (contact.name instanceof ContactName) {
- contact.name.displayName = '';
- if (type_.isString(contact.name.firstName)) {
- contact.name.displayName = contact.name.firstName;
- if (type_.isString(contact.name.lastName)) {
- contact.name.displayName += ' ' + contact.name.lastName;
+ return _editGuard.run(function() {
+ var contact = new Contact(data);
+
+ if (contact.name instanceof ContactName) {
+ contact.name.displayName = '';
+ if (type_.isString(contact.name.firstName)) {
+ contact.name.displayName = contact.name.firstName;
+ if (type_.isString(contact.name.lastName)) {
+ contact.name.displayName += ' ' + contact.name.lastName;
+ }
+ } else if (
+ type_.isArray(contact.name.nicknames) &&
+ type_.isString(contact.name.nicknames[0])
+ ) {
+ contact.name.displayName = contact.name.nicknames[0];
+ } else if (type_.isString(contact.name.nicknames)) {
+ contact.name.displayName = contact.name.nicknames;
+ }
}
- } else if (type_.isArray(contact.name.nicknames) &&
- type_.isString(contact.name.nicknames[0])) {
- contact.name.displayName = contact.name.nicknames[0];
- } else if (type_.isString(contact.name.nicknames)) {
- contact.name.displayName = contact.name.nicknames;
- }
- }
- return contact;
- });
+ return contact;
+ });
}
AddressBook.prototype.get = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'id',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.id)) !== args.id) {
- // TCT: AddressBook_get_id_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('AddressBook_get', {
- id: args.id
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- return _prepareContact(native_.getResultObject(result));
-};
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
-AddressBook.prototype.add = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'contact',
- type: types_.PLATFORM_OBJECT,
- values: Contact,
- optional: false,
- nullable: false
- }
- ]);
-
- var result = native_.callSync('AddressBook_add', {
- addressBookId: this.id,
- contact: _toJsonObject(args.contact)
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- var _updatedContact = native_.getResultObject(result);
- _editGuard.run(function() {
- for (var prop in _updatedContact) {
- if (args.contact.hasOwnProperty(prop)) {
- args.contact[prop] = _updatedContact[prop];
- }
+ if (String(converter_.toLong(args.id)) !== args.id) {
+ // TCT: AddressBook_get_id_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- if (args.contact.name instanceof ContactName) {
- args.contact.name.displayName = '';
- if (type_.isString(args.contact.name.firstName)) {
- args.contact.name.displayName = args.contact.name.firstName;
- if (type_.isString(args.contact.name.lastName)) {
- args.contact.name.displayName += ' ' + args.contact.name.lastName;
- }
- } else if (type_.isArray(args.contact.name.nicknames) &&
- type_.isString(args.contact.name.nicknames[0])) {
- args.contact.name.displayName = args.contact.name.nicknames[0];
- } else if (type_.isString(args.contact.name.nicknames)) {
- args.contact.name.displayName = args.contact.name.nicknames;
- }
+ var result = native_.callSync('AddressBook_get', {
+ id: args.id
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- });
+
+ return _prepareContact(native_.getResultObject(result));
};
-AddressBook.prototype.addBatch = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'contacts',
- type: types_.ARRAY,
- value: Contact,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
+AddressBook.prototype.add = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'contact',
+ type: types_.PLATFORM_OBJECT,
+ values: Contact,
+ optional: false,
+ nullable: false
+ }
+ ]);
- ]);
+ var result = native_.callSync('AddressBook_add', {
+ addressBookId: this.id,
+ contact: _toJsonObject(args.contact)
+ });
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
+ var _updatedContact = native_.getResultObject(result);
_editGuard.run(function() {
- var _result = native_.getResultObject(result);
- for (var i = 0; i < _result.length; ++i) {
- for (var prop in _result[i]) {
- if (args.contacts[i].hasOwnProperty(prop)) {
- args.contacts[i][prop] = _result[i][prop];
- }
+ for (var prop in _updatedContact) {
+ if (args.contact.hasOwnProperty(prop)) {
+ args.contact[prop] = _updatedContact[prop];
+ }
+ }
+
+ if (args.contact.name instanceof ContactName) {
+ args.contact.name.displayName = '';
+ if (type_.isString(args.contact.name.firstName)) {
+ args.contact.name.displayName = args.contact.name.firstName;
+ if (type_.isString(args.contact.name.lastName)) {
+ args.contact.name.displayName += ' ' + args.contact.name.lastName;
+ }
+ } else if (
+ type_.isArray(args.contact.name.nicknames) &&
+ type_.isString(args.contact.name.nicknames[0])
+ ) {
+ args.contact.name.displayName = args.contact.name.nicknames[0];
+ } else if (type_.isString(args.contact.name.nicknames)) {
+ args.contact.name.displayName = args.contact.name.nicknames;
+ }
}
- }
});
+};
- native_.callIfPossible(args.successCallback, args.contacts);
- };
+AddressBook.prototype.addBatch = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'contacts',
+ type: types_.ARRAY,
+ value: Contact,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var result = native_.call('AddressBook_addBatch', {
- addressBookId: this.id,
- batchArgs: _toJsonObject(args.contacts)
- }, callback);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ _editGuard.run(function() {
+ var _result = native_.getResultObject(result);
+ for (var i = 0; i < _result.length; ++i) {
+ for (var prop in _result[i]) {
+ if (args.contacts[i].hasOwnProperty(prop)) {
+ args.contacts[i][prop] = _result[i][prop];
+ }
+ }
+ }
+ });
+
+ native_.callIfPossible(args.successCallback, args.contacts);
+ };
+
+ var result = native_.call(
+ 'AddressBook_addBatch',
+ {
+ addressBookId: this.id,
+ batchArgs: _toJsonObject(args.contacts)
+ },
+ callback
+ );
-AddressBook.prototype.update = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'contact',
- type: types_.PLATFORM_OBJECT,
- values: Contact,
- optional: false,
- nullable: false
- }
- ]);
-
- if (args.contact.addressBookId !== this.id && UNIFIED_ADDRESSBOOK_ID !== this.id) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('AddressBook_update', {
- contact: _toJsonObject(args.contact)
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- var _updatedContact = native_.getResultObject(result);
- _editGuard.run(function() {
- for (var prop in _updatedContact) {
- if (args.contact.hasOwnProperty(prop)) {
- args.contact[prop] = _updatedContact[prop];
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- });
};
-AddressBook.prototype.updateBatch = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'contacts',
- type: types_.ARRAY,
- values: Contact,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
+AddressBook.prototype.update = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'contact',
+ type: types_.PLATFORM_OBJECT,
+ values: Contact,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (args.contact.addressBookId !== this.id && UNIFIED_ADDRESSBOOK_ID !== this.id) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- ]);
- var callback = function(result) {
+ var result = native_.callSync('AddressBook_update', {
+ contact: _toJsonObject(args.contact)
+ });
+
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
+ var _updatedContact = native_.getResultObject(result);
_editGuard.run(function() {
- var _result = native_.getResultObject(result);
- for (var i = 0; i < _result.length; ++i) {
- for (var prop in _result[i].result) {
- if (args.contacts[i].hasOwnProperty(prop)) {
- args.contacts[i][prop] = _result[i].result[prop];
- }
+ for (var prop in _updatedContact) {
+ if (args.contact.hasOwnProperty(prop)) {
+ args.contact[prop] = _updatedContact[prop];
+ }
}
- }
});
+};
- native_.callIfPossible(args.successCallback);
- };
+AddressBook.prototype.updateBatch = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'contacts',
+ type: types_.ARRAY,
+ values: Contact,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var thatId = this.id;
- args.contacts.forEach(function(c) {
- if (c.addressBookId !== thatId && UNIFIED_ADDRESSBOOK_ID !== thatId) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Contact is not saved in database'));
- }, 0);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
- return;
- }
- });
+ _editGuard.run(function() {
+ var _result = native_.getResultObject(result);
+ for (var i = 0; i < _result.length; ++i) {
+ for (var prop in _result[i].result) {
+ if (args.contacts[i].hasOwnProperty(prop)) {
+ args.contacts[i][prop] = _result[i].result[prop];
+ }
+ }
+ }
+ });
+
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var thatId = this.id;
+ args.contacts.forEach(function(c) {
+ if (c.addressBookId !== thatId && UNIFIED_ADDRESSBOOK_ID !== thatId) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Contact is not saved in database'
+ )
+ );
+ }, 0);
+
+ return;
+ }
+ });
- var result = native_.call('AddressBook_updateBatch', {
- batchArgs: _toJsonObject(args.contacts)
- }, callback);
+ var result = native_.call(
+ 'AddressBook_updateBatch',
+ {
+ batchArgs: _toJsonObject(args.contacts)
+ },
+ callback
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
AddressBook.prototype.remove = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'id',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.id)) !== args.id) {
- // TCT: AddressBook_remove_id_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('AddressBook_remove', {
- id: args.id
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'id',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
-AddressBook.prototype.removeBatch = function(ids, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'ids',
- type: types_.ARRAY,
- values: types_.STRING,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
+ if (String(converter_.toLong(args.id)) !== args.id) {
+ // TCT: AddressBook_remove_id_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- ]);
- var callback = function(result) {
+ var result = native_.callSync('AddressBook_remove', {
+ id: args.id
+ });
+
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
+};
- native_.callIfPossible(args.successCallback);
- };
+AddressBook.prototype.removeBatch = function(ids, successCallback, errorCallback) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'ids',
+ type: types_.ARRAY,
+ values: types_.STRING,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var result = native_.call('AddressBook_removeBatch', {
- batchArgs: args.ids
- }, callback);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ native_.callIfPossible(args.successCallback);
+ };
-AddressBook.prototype.find = function(successCallback, errorCallback, filter, sortMode) {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: false,
- nullable: false
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'filter',
- type: types_.PLATFORM_OBJECT,
- values: [
- tizen.AttributeFilter,
- tizen.AttributeRangeFilter,
- tizen.CompositeFilter
- ],
- optional: true,
- nullable: true
- },
- {
- name: 'sortMode',
- type: types_.PLATFORM_OBJECT,
- values: tizen.SortMode,
- optional: true,
- nullable: true
- }
- ]);
+ var result = native_.call(
+ 'AddressBook_removeBatch',
+ {
+ batchArgs: args.ids
+ },
+ callback
+ );
- var self = this;
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
+};
- var _contacts = [];
- var _result = native_.getResultObject(result);
- _result.forEach(function(data) {
- var contact = _prepareContact(data);
- _contacts.push(contact);
- });
+AddressBook.prototype.find = function(successCallback, errorCallback, filter, sortMode) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'filter',
+ type: types_.PLATFORM_OBJECT,
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ],
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'sortMode',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.SortMode,
+ optional: true,
+ nullable: true
+ }
+ ]);
- native_.callIfPossible(successCallback, _contacts);
- };
+ var self = this;
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(errorCallback, native_.getErrorObject(result));
+ return;
+ }
- var result = native_.call('AddressBook_find', {
- addressBookId: this.id,
- filter: utils_.repackFilter(filter),
- sortMode: sortMode
- }, callback);
+ var _contacts = [];
+ var _result = native_.getResultObject(result);
+ _result.forEach(function(data) {
+ var contact = _prepareContact(data);
+ _contacts.push(contact);
+ });
+
+ native_.callIfPossible(successCallback, _contacts);
+ };
+
+ var result = native_.call(
+ 'AddressBook_find',
+ {
+ addressBookId: this.id,
+ filter: utils_.repackFilter(filter),
+ sortMode: sortMode
+ },
+ callback
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
AddressBook.prototype.addChangeListener = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'successCallback',
- type: types_.LISTENER,
- values: ['oncontactsadded', 'oncontactsupdated', 'oncontactsremoved'],
- optional: false,
- nullable: false
- }, {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- // always on first registration checking privileges is done
- if (type_.isEmptyObject(_contactCallbackMap)) {
- var result = native_.callSync('AddressBook_startListening', {});
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.LISTENER,
+ values: ['oncontactsadded', 'oncontactsupdated', 'oncontactsremoved'],
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ // always on first registration checking privileges is done
+ if (type_.isEmptyObject(_contactCallbackMap)) {
+ var result = native_.callSync('AddressBook_startListening', {});
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- if (!_contactListenerRegistered) {
- native_.addListener('ContactChangeListener', _contactChangeListener);
- _contactListenerRegistered = true;
- }
+ if (!_contactListenerRegistered) {
+ native_.addListener('ContactChangeListener', _contactChangeListener);
+ _contactListenerRegistered = true;
+ }
- if (!_contactCallbackMap.hasOwnProperty(this.id)) {
- _contactCallbackMap[this.id] = {};
- }
+ if (!_contactCallbackMap.hasOwnProperty(this.id)) {
+ _contactCallbackMap[this.id] = {};
+ }
- var currentWatchId = _getNextWatchId();
+ var currentWatchId = _getNextWatchId();
- _contactCallbackMap[this.id][currentWatchId] = {
- successCallback: args.successCallback,
- errorCallback: args.errorCallback
- };
+ _contactCallbackMap[this.id][currentWatchId] = {
+ successCallback: args.successCallback,
+ errorCallback: args.errorCallback
+ };
- return currentWatchId;
+ return currentWatchId;
};
var AddressBook_removeChangeListener = function(watchId) {
- if (type_.isEmptyObject(_contactCallbackMap)) {
- utils_.checkPrivilegeAccess(privilege_.CONTACT_READ);
- }
- var args = validator_.validateArgs(arguments, [
- {
- name: 'watchId',
- type: types_.LONG,
- optional: false,
- nullable: false
+ if (type_.isEmptyObject(_contactCallbackMap)) {
+ utils_.checkPrivilegeAccess(privilege_.CONTACT_READ);
}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'watchId',
+ type: types_.LONG,
+ optional: false,
+ nullable: false
+ }
+ ]);
- if (args.watchId <= 0) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Wrong watch id');
- }
+ if (args.watchId <= 0) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Wrong watch id');
+ }
- if (!_contactCallbackMap.hasOwnProperty(this.id) ||
- !_contactCallbackMap[this.id].hasOwnProperty(args.watchId)) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'watch id not found for this address book');
- }
+ if (
+ !_contactCallbackMap.hasOwnProperty(this.id) ||
+ !_contactCallbackMap[this.id].hasOwnProperty(args.watchId)
+ ) {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'watch id not found for this address book'
+ );
+ }
- delete _contactCallbackMap[this.id][args.watchId];
+ delete _contactCallbackMap[this.id][args.watchId];
- if (type_.isEmptyObject(_contactCallbackMap[this.id])) {
- delete _contactCallbackMap[this.id];
- }
+ if (type_.isEmptyObject(_contactCallbackMap[this.id])) {
+ delete _contactCallbackMap[this.id];
+ }
- if (type_.isEmptyObject(_contactCallbackMap)) {
- native_.removeListener('ContactChangeListener', _contactChangeListener);
- _contactListenerRegistered = false;
+ if (type_.isEmptyObject(_contactCallbackMap)) {
+ native_.removeListener('ContactChangeListener', _contactChangeListener);
+ _contactListenerRegistered = false;
- var result = native_.callSync('AddressBook_stopListening', {});
+ var result = native_.callSync('AddressBook_stopListening', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
};
AddressBook.prototype.removeChangeListener = function(watchId) {
- AddressBook_removeChangeListener.apply(this, arguments);
+ AddressBook_removeChangeListener.apply(this, arguments);
};
AddressBook.prototype.getGroup = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'groupId',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.groupId)) !== args.groupId) {
- // TCT: AddressBook_getGroup_groupId_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('AddressBook_getGroup', {
- addressBookId: this.id,
- id: args.groupId
- });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- return _editGuard.run(function() {
- return new ContactGroup(native_.getResultObject(result));
- });
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'groupId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (String(converter_.toLong(args.groupId)) !== args.groupId) {
+ // TCT: AddressBook_getGroup_groupId_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var result = native_.callSync('AddressBook_getGroup', {
+ addressBookId: this.id,
+ id: args.groupId
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ return _editGuard.run(function() {
+ return new ContactGroup(native_.getResultObject(result));
+ });
};
AddressBook.prototype.addGroup = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'group',
- type: types_.PLATFORM_OBJECT,
- values: ContactGroup,
- optional: false,
- nullable: false
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'group',
+ type: types_.PLATFORM_OBJECT,
+ values: ContactGroup,
+ optional: false,
+ nullable: false
+ }
+ ]);
- var result = native_.callSync('AddressBook_addGroup',
- {addressBookId: this.id, group: args.group});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('AddressBook_addGroup', {
+ addressBookId: this.id,
+ group: args.group
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- _editGuard.run(function() {
- result = native_.getResultObject(result);
- args.group.id = result.id;
- args.group.addressBookId = result.addressBookId;
- });
+ _editGuard.run(function() {
+ result = native_.getResultObject(result);
+ args.group.id = result.id;
+ args.group.addressBookId = result.addressBookId;
+ });
};
AddressBook.prototype.updateGroup = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'group',
- type: types_.PLATFORM_OBJECT,
- values: ContactGroup,
- optional: false,
- nullable: false
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'group',
+ type: types_.PLATFORM_OBJECT,
+ values: ContactGroup,
+ optional: false,
+ nullable: false
+ }
+ ]);
- var result = native_.callSync('AddressBook_updateGroup',
- {addressBookId: this.id, group: args.group});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('AddressBook_updateGroup', {
+ addressBookId: this.id,
+ group: args.group
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
AddressBook.prototype.removeGroup = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'groupId',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.groupId)) !== args.groupId) {
- // TCT: AddressBook_removeGroup_groupId_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('AddressBook_removeGroup',
- {addressBookId: this.id, id: args.groupId});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'groupId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (String(converter_.toLong(args.groupId)) !== args.groupId) {
+ // TCT: AddressBook_removeGroup_groupId_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var result = native_.callSync('AddressBook_removeGroup', {
+ addressBookId: this.id,
+ id: args.groupId
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
AddressBook.prototype.getGroups = function() {
- var result = native_.callSync('AddressBook_getGroups', {addressBook: this});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- result = native_.getResultObject(result);
- var _tab = [];
- _editGuard.run(function() {
- result.forEach(function(data) {
- _tab.push(new ContactGroup(data));
+ var result = native_.callSync('AddressBook_getGroups', { addressBook: this });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ result = native_.getResultObject(result);
+ var _tab = [];
+ _editGuard.run(function() {
+ result.forEach(function(data) {
+ _tab.push(new ContactGroup(data));
+ });
});
- });
- return _tab;
+ return _tab;
};
// exports /////////////////////////////////////////////////////////////////
diff --git a/src/contact/js/common.js b/src/contact/js/common.js
index c4d8142a..54883f6f 100755
--- a/src/contact/js/common.js
+++ b/src/contact/js/common.js
@@ -15,7 +15,7 @@
*/
var _global = window || global || {};
-
+
var utils_ = xwalk.utils;
var privilege_ = xwalk.utils.privilege;
var type_ = utils_.type;
@@ -27,78 +27,78 @@ var native_ = new utils_.NativeManager(extension);
var _currentWatchId = 1;
var _getNextWatchId = function() {
- return _currentWatchId++;
+ return _currentWatchId++;
};
// Adjusts properties to have the correct format expected by the native side.
// Currently only translates JS Date
var _toJsonObject = function(obj) {
- var ret;
- if (type_.isDate(obj)) {
- var year = ('0000' + obj.getFullYear()).slice(-4);
- var month = ('00' + (obj.getMonth() + 1)).slice(-2);
- var day = ('00' + obj.getDate()).slice(-2);
- return Number(year + month + day);
- }
- if (type_.isArray(obj)) {
- ret = [];
- for (var i = 0; i < obj.length; ++i) {
- ret[i] = _toJsonObject(obj[i]);
+ var ret;
+ if (type_.isDate(obj)) {
+ var year = ('0000' + obj.getFullYear()).slice(-4);
+ var month = ('00' + (obj.getMonth() + 1)).slice(-2);
+ var day = ('00' + obj.getDate()).slice(-2);
+ return Number(year + month + day);
+ }
+ if (type_.isArray(obj)) {
+ ret = [];
+ for (var i = 0; i < obj.length; ++i) {
+ ret[i] = _toJsonObject(obj[i]);
+ }
+ return ret;
}
- return ret;
- }
- if (obj instanceof _global.Object) {
- ret = {};
- for (var prop in obj) {
- if (obj.hasOwnProperty(prop)) {
- ret[prop] = _toJsonObject(obj[prop]);
- }
+ if (obj instanceof _global.Object) {
+ ret = {};
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
+ ret[prop] = _toJsonObject(obj[prop]);
+ }
+ }
+ return ret;
}
- return ret;
- }
- return obj;
+ return obj;
};
var _fromJsonDate = function(date) {
- date = date + '';
- var year = date.substr(0, 4);
- var month = date.substr(4, 2);
- var day = date.substr(6, 2);
- return new Date(year, month - 1, day);
+ date = date + '';
+ var year = date.substr(0, 4);
+ var month = date.substr(4, 2);
+ var day = date.substr(6, 2);
+ return new Date(year, month - 1, day);
};
var _promote = function(val, type) {
- return _editGuard.run(function() {
- if (type_.isArray(val)) {
- var ret = [];
- for (var i = 0; i < val.length; ++i) {
- ret.push(new type(val[i]));
- }
- return ret;
- }
- return new type(val);
- });
+ return _editGuard.run(function() {
+ if (type_.isArray(val)) {
+ var ret = [];
+ for (var i = 0; i < val.length; ++i) {
+ ret.push(new type(val[i]));
+ }
+ return ret;
+ }
+ return new type(val);
+ });
};
function _checkError(result) {
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
var TypeEnum = ['VCARD_30'];
var PersonUsageTypeEnum = {
- OUTGOING_CALL: 'OUTGOING_CALL',
- OUTGOING_MSG: 'OUTGOING_MSG',
- OUTGOING_EMAIL: 'OUTGOING_EMAIL',
- INCOMING_CALL: 'INCOMING_CALL',
- INCOMING_MSG: 'INCOMING_MSG',
- INCOMING_EMAIL: 'INCOMING_EMAIL',
- MISSED_CALL: 'MISSED_CALL',
- REJECTED_CALL: 'REJECTED_CALL',
- BLOCKED_CALL: 'BLOCKED_CALL',
- BLOCKED_MSG: 'BLOCKED_MSG'
+ OUTGOING_CALL: 'OUTGOING_CALL',
+ OUTGOING_MSG: 'OUTGOING_MSG',
+ OUTGOING_EMAIL: 'OUTGOING_EMAIL',
+ INCOMING_CALL: 'INCOMING_CALL',
+ INCOMING_MSG: 'INCOMING_MSG',
+ INCOMING_EMAIL: 'INCOMING_EMAIL',
+ MISSED_CALL: 'MISSED_CALL',
+ REJECTED_CALL: 'REJECTED_CALL',
+ BLOCKED_CALL: 'BLOCKED_CALL',
+ BLOCKED_MSG: 'BLOCKED_MSG'
};
// Edit Guard //////////////////////////////////////////////////////////////
@@ -106,31 +106,30 @@ var PersonUsageTypeEnum = {
// which tell to edit readonly fields.
var _canEdit = 0;
-var EditGuard = function() {
-};
+var EditGuard = function() {};
EditGuard.prototype.run = function(callback) {
- try {
- this.enable();
- var result = callback();
- this.disable();
- return result;
- } catch (ex) {
- this.disable();
- throw ex;
- }
+ try {
+ this.enable();
+ var result = callback();
+ this.disable();
+ return result;
+ } catch (ex) {
+ this.disable();
+ throw ex;
+ }
};
EditGuard.prototype.enable = function() {
- _canEdit++;
+ _canEdit++;
};
EditGuard.prototype.disable = function() {
- _canEdit--;
+ _canEdit--;
};
EditGuard.prototype.isEditEnabled = function() {
- return _canEdit > 0;
+ return _canEdit > 0;
};
var _editGuard = new EditGuard();
diff --git a/src/contact/js/contact.js b/src/contact/js/contact.js
index af317dee..dcdd7def 100755
--- a/src/contact/js/contact.js
+++ b/src/contact/js/contact.js
@@ -15,630 +15,694 @@
*/
var Contact = function(data) {
- validator_.isConstructorCall(this, Contact);
-
- var _forceEditMode = false;
- if (type_.isString(data)) {
- var result = native_.callSync('ContactManager_importFromVCard', {
- 'contact': data
- });
- _checkError(result);
-
- data = native_.getResultObject(result);
- // These need to be forced to null as a contact created from a vcard is not added
- // to any address book
- data.id = null;
- data.personId = null;
- data.addressBookId = null;
- data.lastUpdate = null;
-
- // Force edit mode so that anonymous objects can be promoted to their correct types.
- _forceEditMode = true;
- } else if (type_.isObject(data) || type_.isFunction(data)) {
- // It's a dictionary
- } else {
- // null or invalid types.
- data = {};
- }
-
- var _id = null;
- var _personId = null;
- var _addressBookId = null;
- var _lastUpdate = null;
- var _isFavorite = false;
- var _name = null;
- var _addresses = [];
- var _photoURI = null;
- var _phoneNumbers = [];
- var _emails = [];
- var _messengers = [];
- var _relationships = [];
- var _extensions = [];
- var _birthday = null;
- var _anniversaries = [];
- var _organizations = [];
- var _notes = [];
- var _urls = [];
- var _ringtoneURI = null;
- var _messageAlertURI = null;
- var _vibrationURI = null;
- var _groupIds = [];
-
- var _sanitizeArray = function(arr, type, previousValue) {
- if (!type_.isArray(arr)) {
- return previousValue;
- }
- for (var i = 0; i < arr.length; ++i) {
- if (type_.isString(type)) {
- arr[i] = converter_.toString(arr[i]);
- } else if (_editGuard.isEditEnabled()) {
- arr[i] = new type(arr[i]);
- } else if (!(arr[i] instanceof type)) {
- return previousValue;
- }
+ validator_.isConstructorCall(this, Contact);
+
+ var _forceEditMode = false;
+ if (type_.isString(data)) {
+ var result = native_.callSync('ContactManager_importFromVCard', {
+ contact: data
+ });
+ _checkError(result);
+
+ data = native_.getResultObject(result);
+ // These need to be forced to null as a contact created from a vcard is not added
+ // to any address book
+ data.id = null;
+ data.personId = null;
+ data.addressBookId = null;
+ data.lastUpdate = null;
+
+ // Force edit mode so that anonymous objects can be promoted to their
+ // correct types.
+ _forceEditMode = true;
+ } else if (type_.isObject(data) || type_.isFunction(data)) {
+ // It's a dictionary
+ } else {
+ // null or invalid types.
+ data = {};
}
- return arr;
- };
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return _id;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _id = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- personId: {
- get: function() {
- return _personId;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _personId = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- addressBookId: {
- get: function() {
- return _addressBookId;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _addressBookId = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- lastUpdated: {
- get: function() {
- return _lastUpdate;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- if (v instanceof Date || v === null) {
- _lastUpdate = v;
- } else if (type_.isString(v)) {
- _lastUpdate = new Date(v);
- } else {
- _lastUpdate = _fromJsonDate(v);
- }
- }
- },
- enumerable: true
- },
- isFavorite: {
- get: function() {
- return _isFavorite;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _isFavorite = converter_.toBoolean(v, false);
+
+ var _id = null;
+ var _personId = null;
+ var _addressBookId = null;
+ var _lastUpdate = null;
+ var _isFavorite = false;
+ var _name = null;
+ var _addresses = [];
+ var _photoURI = null;
+ var _phoneNumbers = [];
+ var _emails = [];
+ var _messengers = [];
+ var _relationships = [];
+ var _extensions = [];
+ var _birthday = null;
+ var _anniversaries = [];
+ var _organizations = [];
+ var _notes = [];
+ var _urls = [];
+ var _ringtoneURI = null;
+ var _messageAlertURI = null;
+ var _vibrationURI = null;
+ var _groupIds = [];
+
+ var _sanitizeArray = function(arr, type, previousValue) {
+ if (!type_.isArray(arr)) {
+ return previousValue;
}
- },
- enumerable: true
- },
- name: {
- get: function() {
- return _name;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _name = new ContactName(v);
- } else {
- _name = (v instanceof ContactName || v === null) ? v : _name;
+ for (var i = 0; i < arr.length; ++i) {
+ if (type_.isString(type)) {
+ arr[i] = converter_.toString(arr[i]);
+ } else if (_editGuard.isEditEnabled()) {
+ arr[i] = new type(arr[i]);
+ } else if (!(arr[i] instanceof type)) {
+ return previousValue;
+ }
}
- },
- enumerable: true
- },
- addresses: {
- get: function() {
- return _addresses;
- },
- set: function(v) {
- _addresses = _sanitizeArray(v, ContactAddress, _addresses);
- },
- enumerable: true
- },
- photoURI: {
- get: function() {
- return _photoURI;
- },
- set: function(v) {
- _photoURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- phoneNumbers: {
- get: function() {
- return _phoneNumbers;
- },
- set: function(v) {
- _phoneNumbers = _sanitizeArray(v, ContactPhoneNumber, _phoneNumbers);
- },
- enumerable: true
- },
- emails: {
- get: function() {
- return _emails;
- },
- set: function(v) {
- _emails = _sanitizeArray(v, ContactEmailAddress, _emails);
- },
- enumerable: true
- },
- messengers: {
- get: function() {
- return _messengers;
- },
- set: function(v) {
- _messengers = _sanitizeArray(v, ContactInstantMessenger, _messengers);
- },
- enumerable: true
- },
- relationships: {
- get: function() {
- return _relationships;
- },
- set: function(v) {
- _relationships = _sanitizeArray(v, ContactRelationship, _relationships);
- },
- enumerable: true
- },
- extensions: {
- get: function() {
- return _extensions;
- },
- set: function(v) {
- _extensions = _sanitizeArray(v, ContactExtension, _extensions);
- },
- enumerable: true
- },
- birthday: {
- get: function() {
- return _birthday;
- },
- set: function(v) {
- if (v instanceof Date || v === null) {
- _birthday = v;
- } else if (type_.isString(v)) {
- _birthday = new Date(v);
- } else if (_editGuard.isEditEnabled()) {
- _birthday = _fromJsonDate(v);
+ return arr;
+ };
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return _id;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _id = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ personId: {
+ get: function() {
+ return _personId;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _personId = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ addressBookId: {
+ get: function() {
+ return _addressBookId;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _addressBookId = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ lastUpdated: {
+ get: function() {
+ return _lastUpdate;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ if (v instanceof Date || v === null) {
+ _lastUpdate = v;
+ } else if (type_.isString(v)) {
+ _lastUpdate = new Date(v);
+ } else {
+ _lastUpdate = _fromJsonDate(v);
+ }
+ }
+ },
+ enumerable: true
+ },
+ isFavorite: {
+ get: function() {
+ return _isFavorite;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _isFavorite = converter_.toBoolean(v, false);
+ }
+ },
+ enumerable: true
+ },
+ name: {
+ get: function() {
+ return _name;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _name = new ContactName(v);
+ } else {
+ _name = v instanceof ContactName || v === null ? v : _name;
+ }
+ },
+ enumerable: true
+ },
+ addresses: {
+ get: function() {
+ return _addresses;
+ },
+ set: function(v) {
+ _addresses = _sanitizeArray(v, ContactAddress, _addresses);
+ },
+ enumerable: true
+ },
+ photoURI: {
+ get: function() {
+ return _photoURI;
+ },
+ set: function(v) {
+ _photoURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ phoneNumbers: {
+ get: function() {
+ return _phoneNumbers;
+ },
+ set: function(v) {
+ _phoneNumbers = _sanitizeArray(v, ContactPhoneNumber, _phoneNumbers);
+ },
+ enumerable: true
+ },
+ emails: {
+ get: function() {
+ return _emails;
+ },
+ set: function(v) {
+ _emails = _sanitizeArray(v, ContactEmailAddress, _emails);
+ },
+ enumerable: true
+ },
+ messengers: {
+ get: function() {
+ return _messengers;
+ },
+ set: function(v) {
+ _messengers = _sanitizeArray(v, ContactInstantMessenger, _messengers);
+ },
+ enumerable: true
+ },
+ relationships: {
+ get: function() {
+ return _relationships;
+ },
+ set: function(v) {
+ _relationships = _sanitizeArray(v, ContactRelationship, _relationships);
+ },
+ enumerable: true
+ },
+ extensions: {
+ get: function() {
+ return _extensions;
+ },
+ set: function(v) {
+ _extensions = _sanitizeArray(v, ContactExtension, _extensions);
+ },
+ enumerable: true
+ },
+ birthday: {
+ get: function() {
+ return _birthday;
+ },
+ set: function(v) {
+ if (v instanceof Date || v === null) {
+ _birthday = v;
+ } else if (type_.isString(v)) {
+ _birthday = new Date(v);
+ } else if (_editGuard.isEditEnabled()) {
+ _birthday = _fromJsonDate(v);
+ }
+ },
+ enumerable: true
+ },
+ anniversaries: {
+ get: function() {
+ return _anniversaries;
+ },
+ set: function(v) {
+ _anniversaries = _sanitizeArray(v, ContactAnniversary, _anniversaries);
+ },
+ enumerable: true
+ },
+ organizations: {
+ get: function() {
+ return _organizations;
+ },
+ set: function(v) {
+ _organizations = _sanitizeArray(v, ContactOrganization, _organizations);
+ },
+ enumerable: true
+ },
+ notes: {
+ get: function() {
+ return _notes;
+ },
+ set: function(v) {
+ _notes = _sanitizeArray(v, '', _notes);
+ },
+ enumerable: true
+ },
+ urls: {
+ get: function() {
+ return _urls;
+ },
+ set: function(v) {
+ _urls = _sanitizeArray(v, ContactWebSite, _urls);
+ },
+ enumerable: true
+ },
+ ringtoneURI: {
+ get: function() {
+ return _ringtoneURI;
+ },
+ set: function(v) {
+ _ringtoneURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ messageAlertURI: {
+ get: function() {
+ return _messageAlertURI;
+ },
+ set: function(v) {
+ _messageAlertURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ vibrationURI: {
+ get: function() {
+ return _vibrationURI;
+ },
+ set: function(v) {
+ _vibrationURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ groupIds: {
+ get: function() {
+ return _groupIds;
+ },
+ set: function(v) {
+ _groupIds = _sanitizeArray(v, '', _groupIds);
+ },
+ enumerable: true
}
- },
- enumerable: true
- },
- anniversaries: {
- get: function() {
- return _anniversaries;
- },
- set: function(v) {
- _anniversaries = _sanitizeArray(v, ContactAnniversary, _anniversaries);
- },
- enumerable: true
- },
- organizations: {
- get: function() {
- return _organizations;
- },
- set: function(v) {
- _organizations = _sanitizeArray(v, ContactOrganization, _organizations);
- },
- enumerable: true
- },
- notes: {
- get: function() {
- return _notes;
- },
- set: function(v) {
- _notes = _sanitizeArray(v, '', _notes);
- },
- enumerable: true
- },
- urls: {
- get: function() {
- return _urls;
- },
- set: function(v) {
- _urls = _sanitizeArray(v, ContactWebSite, _urls);
- },
- enumerable: true
- },
- ringtoneURI: {
- get: function() {
- return _ringtoneURI;
- },
- set: function(v) {
- _ringtoneURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- messageAlertURI: {
- get: function() {
- return _messageAlertURI;
- },
- set: function(v) {
- _messageAlertURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- vibrationURI: {
- get: function() {
- return _vibrationURI;
- },
- set: function(v) {
- _vibrationURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- groupIds: {
- get: function() {
- return _groupIds;
- },
- set: function(v) {
- _groupIds = _sanitizeArray(v, '', _groupIds);
- },
- enumerable: true
- }
- });
-
- var _this = this;
- var _setProperties = function() {
- for (var p in _this) {
- if (data.hasOwnProperty(p)) {
- _this[p] = data[p];
- }
- }
- };
+ });
- if (_forceEditMode) {
- _editGuard.run(_setProperties);
- } else {
- _setProperties();
- }
+ var _this = this;
+ var _setProperties = function() {
+ for (var p in _this) {
+ if (data.hasOwnProperty(p)) {
+ _this[p] = data[p];
+ }
+ }
+ };
+ if (_forceEditMode) {
+ _editGuard.run(_setProperties);
+ } else {
+ _setProperties();
+ }
};
// Auxiliary functions /////////////////////////////////////////////////////
// Convert address from Contact object to string
var _contactAddressToString = function(obj) {
- var str = '';
- if (obj.addresses.length === 0) {
- return '';
- }
- // Sorry for so many if statements, but the IDE makes me do it
- for (var it in obj.addresses) {
- if (!it instanceof ContactAddress) {
- continue;
- }
- str += 'ADR;';
- for (var addType in it.types) {
- if (type_.isString(addType)) {
- str += addType + ',';
- }
+ var str = '';
+ if (obj.addresses.length === 0) {
+ return '';
}
- if (str.charAt(str.length - 1) === ',') {
- str[str.length - 1] = ':';
+ // Sorry for so many if statements, but the IDE makes me do it
+ for (var it in obj.addresses) {
+ if (!it instanceof ContactAddress) {
+ continue;
+ }
+ str += 'ADR;';
+ for (var addType in it.types) {
+ if (type_.isString(addType)) {
+ str += addType + ',';
+ }
+ }
+ if (str.charAt(str.length - 1) === ',') {
+ str[str.length - 1] = ':';
+ }
+ str += ';'; // because of we don't keep Post office addres
+ // which is part of vCard 3.0 standard
+ str += it.additionalInformation + ';';
+ str += it.streetAddress + ';';
+ str += it.city + ';';
+ str += it.region + ';';
+ str += it.postalCode + ';';
+ str += it.country + ';';
+ str += '\n';
}
- str += ';'; // because of we don't keep Post office addres
- // which is part of vCard 3.0 standard
- str += it.additionalInformation + ';';
- str += it.streetAddress + ';';
- str += it.city + ';';
- str += it.region + ';';
- str += it.postalCode + ';';
- str += it.country + ';';
- str += '\n';
- }
- return str;
+ return str;
};
// Convert email address from Contact object to string
var _contactEmailToString = function(obj) {
- if (!type_.isArray(obj.emails) || obj.emails.length === 0) {
- utils_.log('Empty email list');
- return '';
- }
- var str = '';
- for (var mail in obj.emails) {
- if (!mail instanceof ContactEmailAddress || !type_.isArray(mail.types) ||
- mail.types.length === 0) {
- utils_.log('Incorrect email type');
- continue;
- }
- str += 'EMAIL;';
- // set types
- for (var type in mail.types) {
- if (type_.isString(type)) {
- str += type + ',';
- }
+ if (!type_.isArray(obj.emails) || obj.emails.length === 0) {
+ utils_.log('Empty email list');
+ return '';
}
- if (str.charAt(str.length - 1) === ',') {
- str[str.length - 1] = ':';
+ var str = '';
+ for (var mail in obj.emails) {
+ if (
+ !mail instanceof ContactEmailAddress ||
+ !type_.isArray(mail.types) ||
+ mail.types.length === 0
+ ) {
+ utils_.log('Incorrect email type');
+ continue;
+ }
+ str += 'EMAIL;';
+ // set types
+ for (var type in mail.types) {
+ if (type_.isString(type)) {
+ str += type + ',';
+ }
+ }
+ if (str.charAt(str.length - 1) === ',') {
+ str[str.length - 1] = ':';
+ }
+ str += '=' + converter_.toString(mail.email) + '\n';
}
- str += '=' + converter_.toString(mail.email) + '\n';
- }
- return str;
+ return str;
};
// Convert organizations info from Contact object to string
var _contactOrganizationToString = function(obj) {
- if (obj.organizations.length === 0 ||
- !obj.organizations[0] instanceof ContactOrganization) {
- return '';
- }
- var str = '';
- for (var org in obj.organizations) {
- if (!org instanceof ContactOrganization) {
- continue;
+ if (
+ obj.organizations.length === 0 ||
+ !obj.organizations[0] instanceof ContactOrganization
+ ) {
+ return '';
+ }
+ var str = '';
+ for (var org in obj.organizations) {
+ if (!org instanceof ContactOrganization) {
+ continue;
+ }
+ str += 'ORG:';
+ str += org.name + ';' + org.department + ';' + org.title + '\n';
}
- str += 'ORG:';
- str += org.name + ';' + org.department + ';' + org.title + '\n';
- }
- return str;
+ return str;
};
// Convert organizations roles from Contact object to string
var _contactRoleToString = function(obj) {
- if (obj.organizations.length === 0 ||
- !obj.organizations[0] instanceof ContactOrganization) {
- return '';
- }
- var str = '';
- for (var org in obj.organizations) {
- if (!org instanceof ContactOrganization) {
- continue;
+ if (
+ obj.organizations.length === 0 ||
+ !obj.organizations[0] instanceof ContactOrganization
+ ) {
+ return '';
}
- str += 'ROLE:';
- str += org.name + ';' + org.role + '\n';
- }
- return str;
+ var str = '';
+ for (var org in obj.organizations) {
+ if (!org instanceof ContactOrganization) {
+ continue;
+ }
+ str += 'ROLE:';
+ str += org.name + ';' + org.role + '\n';
+ }
+ return str;
};
// Convert phone numbers from Contact object to string
var _contactPhoneNumbersToString = function(obj) {
- if (obj.phoneNumbers.length === 0 || !obj.phoneNumbers[0] instanceof ContactPhoneNumber) {
- return '';
- }
- var str = '';
- for (var phone in obj.phoneNumbers) {
- if (!phone instanceof ContactPhoneNumber) {
- continue;
+ if (
+ obj.phoneNumbers.length === 0 ||
+ !obj.phoneNumbers[0] instanceof ContactPhoneNumber
+ ) {
+ return '';
}
- str += 'TEL';
- for (var type in phone.types) {
- if (type_.isString(type)) {
- str += ';' + type;
- }
+ var str = '';
+ for (var phone in obj.phoneNumbers) {
+ if (!phone instanceof ContactPhoneNumber) {
+ continue;
+ }
+ str += 'TEL';
+ for (var type in phone.types) {
+ if (type_.isString(type)) {
+ str += ';' + type;
+ }
+ }
+ str += ':';
+ str += phone.number + '\n';
}
- str += ':';
- str += phone.number + '\n';
- }
- return str;
+ return str;
};
// Convert urls from Contact object to string
var _contactURLToString = function(obj) {
- if (obj.urls.length === 0 || !obj.urls[0] instanceof ContactWebSite) {
- return '';
- }
- var str = '';
- for (var url in obj.urls) {
- if (url instanceof ContactWebSite) {
- str += 'URL:' + url.url + '\n';
+ if (obj.urls.length === 0 || !obj.urls[0] instanceof ContactWebSite) {
+ return '';
+ }
+ var str = '';
+ for (var url in obj.urls) {
+ if (url instanceof ContactWebSite) {
+ str += 'URL:' + url.url + '\n';
+ }
}
- }
- return str;
+ return str;
};
// Convert anniversaries to string
var _contactAnniversaryToString = function(obj) {
- if (obj.anniversaries.length === 0 || !obj.anniversaries[0] instanceof ContactAnniversary) {
- return '';
- }
- var str = '';
- for (var ann in obj.anniversaries) {
- if (ann instanceof ContactAnniversary) {
- str += 'X-ANNIVERSARY;' + ann.label + ':' + ann.date + ';' + '\n';
+ if (
+ obj.anniversaries.length === 0 ||
+ !obj.anniversaries[0] instanceof ContactAnniversary
+ ) {
+ return '';
}
- }
- return str;
+ var str = '';
+ for (var ann in obj.anniversaries) {
+ if (ann instanceof ContactAnniversary) {
+ str += 'X-ANNIVERSARY;' + ann.label + ':' + ann.date + ';' + '\n';
+ }
+ }
+ return str;
};
// Convert relationships to string
var _contactRelationshipsToString = function(obj) {
- if (obj.relationships.length === 0 ||
- !obj.relationships[0] instanceof ContactRelationship) {
- return '';
- }
- var str = '';
- for (var rel in obj.relationships) {
- if (rel instanceof ContactRelationship) {
- str += 'X-RELATIONSHIP;' + rel.relativeName + ':' + rel.type +
- ':' + rel.label + ';\n';
+ if (
+ obj.relationships.length === 0 ||
+ !obj.relationships[0] instanceof ContactRelationship
+ ) {
+ return '';
+ }
+ var str = '';
+ for (var rel in obj.relationships) {
+ if (rel instanceof ContactRelationship) {
+ str +=
+ 'X-RELATIONSHIP;' +
+ rel.relativeName +
+ ':' +
+ rel.type +
+ ':' +
+ rel.label +
+ ';\n';
+ }
}
- }
- return str;
+ return str;
};
// Convert extension to string
// Format:
// X-EXTENSION:<data1>;<data2>;...;<data12>
var _contactExtensionsToString = function(obj) {
- var str = '';
- var label = null;
-
- if (obj.extensions === null || !type_.isArray(obj.extensions)) {
- return '';
- }
- for (var i = 0; i < obj.extensions.length; i++) {
- if (!obj.extensions[i] instanceof ContactExtension) {
- return '';
- }
- str += 'X-EXTENSION:';
+ var str = '';
+ var label = null;
- if (obj.extensions[i].data1 === null) {
- str += '0';
- } else {
- str += String(obj.extensions[i].data1);
+ if (obj.extensions === null || !type_.isArray(obj.extensions)) {
+ return '';
}
+ for (var i = 0; i < obj.extensions.length; i++) {
+ if (!obj.extensions[i] instanceof ContactExtension) {
+ return '';
+ }
+ str += 'X-EXTENSION:';
- for (var j = 2; j <= 12; j++) {
- str += ';';
- label = 'data' + j;
- if (obj.extensions[i][label] && obj.extensions[i][label].length > 0) {
- str += obj.extensions[i][label];
- }
- }
+ if (obj.extensions[i].data1 === null) {
+ str += '0';
+ } else {
+ str += String(obj.extensions[i].data1);
+ }
+
+ for (var j = 2; j <= 12; j++) {
+ str += ';';
+ label = 'data' + j;
+ if (obj.extensions[i][label] && obj.extensions[i][label].length > 0) {
+ str += obj.extensions[i][label];
+ }
+ }
- str += '\n';
- }
- return str;
+ str += '\n';
+ }
+ return str;
};
// Convert messengers to string
var _contactInstantMessengeToString = function(obj) {
- if (obj.messengers.length === 0 || !obj.messengers[0] instanceof ContactInstantMessenger) {
- return '';
- }
- var str = '';
- for (var messenger in obj.messengers) {
- if (messenger instanceof ContactInstantMessenger) {
- str += 'X-MESSANGER;' + messenger.imAddress + ':' + messenger.type +
- ':' + messenger.label + ';\n';
+ if (
+ obj.messengers.length === 0 ||
+ !obj.messengers[0] instanceof ContactInstantMessenger
+ ) {
+ return '';
+ }
+ var str = '';
+ for (var messenger in obj.messengers) {
+ if (messenger instanceof ContactInstantMessenger) {
+ str +=
+ 'X-MESSANGER;' +
+ messenger.imAddress +
+ ':' +
+ messenger.type +
+ ':' +
+ messenger.label +
+ ';\n';
+ }
}
- }
- return str;
+ return str;
};
// Auxiliary function, allows to parse JSON to Contact
var _JSONToContactType = function(type, obj) {
- var contact = new type();
-
- for (var prop in obj) {
- if (contact.hasOwnProperty(prop)) {
- if (contact[prop] instanceof Date && type_.isNumber(obj[prop])) {
- contact[prop] = new Date(1000 * obj[prop]);
- } else {
- contact[prop] = obj[prop];
- }
+ var contact = new type();
+
+ for (var prop in obj) {
+ if (contact.hasOwnProperty(prop)) {
+ if (contact[prop] instanceof Date && type_.isNumber(obj[prop])) {
+ contact[prop] = new Date(1000 * obj[prop]);
+ } else {
+ contact[prop] = obj[prop];
+ }
+ }
}
- }
- return contact;
+ return contact;
};
// Converts the Contact item to a string format.
Contact.prototype.convertToString = function(format) {
- format = format || TypeEnum[0];
-
- if (!type_.isString(format)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Invalid format');
- }
-
- if (TypeEnum.indexOf(format) < 0) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Invalid format');
- }
+ format = format || TypeEnum[0];
- if (this.id === '') {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Contact ID is empty.');
- }
-
- var str = 'BEGIN:VCARD\nVERSION:3.0\n';
-
- // set contact name
- str += 'N:' + this.name.lastName + ';' + this.name.firstName + ';' +
- this.name.middleName + ';' + this.name.prefix + ';' + this.name.suffix + '\n';
- str += 'FN' + this.name.displayName + '\n';
+ if (!type_.isString(format)) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Invalid format');
+ }
- // set phonetic names
- str += 'X-PHONETIC-FIRST-NAME' + this.name.phoneticFirstName + '\n' +
- 'X-PHONETIC-LAST-NAME' + this.name.phoneticLastName + '\n';
+ if (TypeEnum.indexOf(format) < 0) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Invalid format');
+ }
- // set contact address
- str += _contactAddressToString(this);
+ if (this.id === '') {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Contact ID is empty.'
+ );
+ }
- // set Birthday
- if (this.birthday) {
- str += 'BDAY:' + this.birthday.getYear() + '-' + this.birthday.getMonth() +
- '-' + this.birthday.getDay() + '\n';
- }
+ var str = 'BEGIN:VCARD\nVERSION:3.0\n';
+
+ // set contact name
+ str +=
+ 'N:' +
+ this.name.lastName +
+ ';' +
+ this.name.firstName +
+ ';' +
+ this.name.middleName +
+ ';' +
+ this.name.prefix +
+ ';' +
+ this.name.suffix +
+ '\n';
+ str += 'FN' + this.name.displayName + '\n';
+
+ // set phonetic names
+ str +=
+ 'X-PHONETIC-FIRST-NAME' +
+ this.name.phoneticFirstName +
+ '\n' +
+ 'X-PHONETIC-LAST-NAME' +
+ this.name.phoneticLastName +
+ '\n';
+
+ // set contact address
+ str += _contactAddressToString(this);
+
+ // set Birthday
+ if (this.birthday) {
+ str +=
+ 'BDAY:' +
+ this.birthday.getYear() +
+ '-' +
+ this.birthday.getMonth() +
+ '-' +
+ this.birthday.getDay() +
+ '\n';
+ }
- // set anniversary
- str += _contactAnniversaryToString(this);
+ // set anniversary
+ str += _contactAnniversaryToString(this);
- // set relationship
- str += _contactRelationshipsToString(this);
+ // set relationship
+ str += _contactRelationshipsToString(this);
- // set extension
- str += _contactExtensionsToString(this);
+ // set extension
+ str += _contactExtensionsToString(this);
- // set emails
- str += _contactEmailToString(this);
+ // set emails
+ str += _contactEmailToString(this);
- // set organization data
- str += _contactOrganizationToString(this);
+ // set organization data
+ str += _contactOrganizationToString(this);
- // set role
- str += _contactRoleToString(this);
+ // set role
+ str += _contactRoleToString(this);
- // set phone numbers
- str += _contactPhoneNumbersToString(this);
+ // set phone numbers
+ str += _contactPhoneNumbersToString(this);
- // set user ID
- str += 'UID:' + this.id + '\n';
+ // set user ID
+ str += 'UID:' + this.id + '\n';
- // set isFavorite
- str += 'X-IS-FAVORITE' + this.isFavorite + '\n';
+ // set isFavorite
+ str += 'X-IS-FAVORITE' + this.isFavorite + '\n';
- // set URLs
- str += _contactURLToString(this);
+ // set URLs
+ str += _contactURLToString(this);
- // set messengers
- str += _contactInstantMessengeToString(this);
+ // set messengers
+ str += _contactInstantMessengeToString(this);
- // set last revision
- if (this.lastUpdated) {
- str += 'REV:' + this.lastUpdated.getYear() + '-' + this.lastUpdated.getMonth() +
- '-' + this.lastUpdated.getDay() + 'T' + this.lastUpdated.getHours() + ':' +
- this.lastUpdated.getMinutes() + ':' + this.lastUpdated.getSeconds() + 'Z\n';
- }
+ // set last revision
+ if (this.lastUpdated) {
+ str +=
+ 'REV:' +
+ this.lastUpdated.getYear() +
+ '-' +
+ this.lastUpdated.getMonth() +
+ '-' +
+ this.lastUpdated.getDay() +
+ 'T' +
+ this.lastUpdated.getHours() +
+ ':' +
+ this.lastUpdated.getMinutes() +
+ ':' +
+ this.lastUpdated.getSeconds() +
+ 'Z\n';
+ }
- str += 'END:VCARD\n';
+ str += 'END:VCARD\n';
- return str;
+ return str;
};
// Creates a clone of the Contact object, detached from any address book
Contact.prototype.clone = function() {
- return new Contact(this);
+ return new Contact(this);
};
// exports /////////////////////////////////////////////////////////////////
diff --git a/src/contact/js/contact_data_structures.js b/src/contact/js/contact_data_structures.js
index 4296a496..bd864b7b 100755
--- a/src/contact/js/contact_data_structures.js
+++ b/src/contact/js/contact_data_structures.js
@@ -13,868 +13,880 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
// An enumerator that indicates the types for the relationships.
var ContactRelationshipType = {
- ASSISTANT: 'ASSISTANT',
- BROTHER: 'BROTHER',
- CHILD: 'CHILD',
- DOMESTIC_PARTNER: 'DOMESTIC_PARTNER',
- FATHER: 'FATHER',
- FRIEND: 'FRIEND',
- MANAGER: 'MANAGER',
- MOTHER: 'MOTHER',
- PARENT: 'PARENT',
- PARTNER: 'PARTNER',
- REFERRED_BY: 'REFERRED_BY',
- RELATIVE: 'RELATIVE',
- SISTER: 'SISTER',
- SPOUSE: 'SPOUSE',
- OTHER: 'OTHER',
- CUSTOM: 'CUSTOM'
+ ASSISTANT: 'ASSISTANT',
+ BROTHER: 'BROTHER',
+ CHILD: 'CHILD',
+ DOMESTIC_PARTNER: 'DOMESTIC_PARTNER',
+ FATHER: 'FATHER',
+ FRIEND: 'FRIEND',
+ MANAGER: 'MANAGER',
+ MOTHER: 'MOTHER',
+ PARENT: 'PARENT',
+ PARTNER: 'PARTNER',
+ REFERRED_BY: 'REFERRED_BY',
+ RELATIVE: 'RELATIVE',
+ SISTER: 'SISTER',
+ SPOUSE: 'SPOUSE',
+ OTHER: 'OTHER',
+ CUSTOM: 'CUSTOM'
};
// An enumerator that indicates the types for instant messenger.
var ContactInstantMessengerType = {
- GOOGLE: 'GOOGLE',
- WLM: 'WLM',
- YAHOO: 'YAHOO',
- FACEBOOK: 'FACEBOOK',
- ICQ: 'ICQ',
- AIM: 'AIM',
- QQ: 'QQ',
- JABBER: 'JABBER',
- SKYPE: 'SKYPE',
- IRC: 'IRC',
- OTHER: 'OTHER',
- CUSTOM: 'CUSTOM'
+ GOOGLE: 'GOOGLE',
+ WLM: 'WLM',
+ YAHOO: 'YAHOO',
+ FACEBOOK: 'FACEBOOK',
+ ICQ: 'ICQ',
+ AIM: 'AIM',
+ QQ: 'QQ',
+ JABBER: 'JABBER',
+ SKYPE: 'SKYPE',
+ IRC: 'IRC',
+ OTHER: 'OTHER',
+ CUSTOM: 'CUSTOM'
};
// class ContactRef ////////////////////////////////////////////////////////
var ContactRef = function(data) {
- validator_.isConstructorCall(this, ContactRef);
- var _contactId = '';
- var _addressBookId = '';
- Object.defineProperties(this, {
- addressBookId: {
- get: function() {
- return _addressBookId;
- },
- set: function(v) {
- _addressBookId = converter_.toString(v, false);
- },
- enumerable: true
- },
- contactId: {
- get: function() {
- return _contactId;
- },
- set: function(v) {
- _contactId = converter_.toString(v, false);
- },
- enumerable: true
- }
- });
-
- if (type_.isObject(data)) {
- this.addressBookId = data.addressBookId;
- this.contactId = data.contactId;
- } else {
- try {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'addressBookId',
- type: types_.STRING,
- optional: false,
- nullable: false
- },
- {
- name: 'contactId',
- type: types_.STRING,
- optional: false,
- nullable: false
+ validator_.isConstructorCall(this, ContactRef);
+ var _contactId = '';
+ var _addressBookId = '';
+ Object.defineProperties(this, {
+ addressBookId: {
+ get: function() {
+ return _addressBookId;
+ },
+ set: function(v) {
+ _addressBookId = converter_.toString(v, false);
+ },
+ enumerable: true
+ },
+ contactId: {
+ get: function() {
+ return _contactId;
+ },
+ set: function(v) {
+ _contactId = converter_.toString(v, false);
+ },
+ enumerable: true
+ }
+ });
+
+ if (type_.isObject(data)) {
+ this.addressBookId = data.addressBookId;
+ this.contactId = data.contactId;
+ } else {
+ try {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'addressBookId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'contactId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+ _addressBookId = args.addressBookId;
+ _contactId = args.contactId;
+ } catch (x) {
+ // Constructors shouldn't throw
}
- ]);
- _addressBookId = args.addressBookId;
- _contactId = args.contactId;
- } catch (x) {
- // Constructors shouldn't throw
}
- }
};
// class ContactGroup //////////////////////////////////////////////////
var ContactGroup = function(name, ringtone, photo) {
- validator_.isConstructorCall(this, ContactGroup);
-
- var _id = null;
- var _address = null;
- var _readOnly = false;
- var _name = '';
- var _ringtoneURI = null;
- var _photoURI = null;
-
- if (name && type_.isString(name)) {
- _name = name.length ? name : '';
- }
-
- if (ringtone && type_.isString(ringtone)) {
- _ringtoneURI = ringtone.length ? ringtone : null;
- }
-
- if (photo && type_.isString(photo)) {
- _photoURI = photo.length ? photo : null;
- }
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return _id;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _id = converter_.toString(v, true);
- }
- },
- enumerable: true
- },
- addressBookId: {
- get: function() {
- return _address;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _address = converter_.toString(v, true);
- }
- },
- enumerable: true
- },
- name: {
- get: function() {
- return _name;
- },
- set: function(v) {
- _name = converter_.toString(v, false);
- },
- enumerable: true
- },
- ringtoneURI: {
- get: function() {
- return _ringtoneURI;
- },
- set: function(v) {
- _ringtoneURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- photoURI: {
- get: function() {
- return _photoURI;
- },
- set: function(v) {
- _photoURI = converter_.toString(v, true);
- },
- enumerable: true
- },
- readOnly: {
- get: function() {
- return _readOnly;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _readOnly = converter_.toBoolean(v, false);
- }
- },
- enumerable: true
+ validator_.isConstructorCall(this, ContactGroup);
+
+ var _id = null;
+ var _address = null;
+ var _readOnly = false;
+ var _name = '';
+ var _ringtoneURI = null;
+ var _photoURI = null;
+
+ if (name && type_.isString(name)) {
+ _name = name.length ? name : '';
}
- });
- if (_editGuard.isEditEnabled()) {
- var data = arguments[0];
- if (type_.isObject(data)) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
+ if (ringtone && type_.isString(ringtone)) {
+ _ringtoneURI = ringtone.length ? ringtone : null;
+ }
+
+ if (photo && type_.isString(photo)) {
+ _photoURI = photo.length ? photo : null;
+ }
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return _id;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _id = converter_.toString(v, true);
+ }
+ },
+ enumerable: true
+ },
+ addressBookId: {
+ get: function() {
+ return _address;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _address = converter_.toString(v, true);
+ }
+ },
+ enumerable: true
+ },
+ name: {
+ get: function() {
+ return _name;
+ },
+ set: function(v) {
+ _name = converter_.toString(v, false);
+ },
+ enumerable: true
+ },
+ ringtoneURI: {
+ get: function() {
+ return _ringtoneURI;
+ },
+ set: function(v) {
+ _ringtoneURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ photoURI: {
+ get: function() {
+ return _photoURI;
+ },
+ set: function(v) {
+ _photoURI = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ readOnly: {
+ get: function() {
+ return _readOnly;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _readOnly = converter_.toBoolean(v, false);
+ }
+ },
+ enumerable: true
+ }
+ });
+
+ if (_editGuard.isEditEnabled()) {
+ var data = arguments[0];
+ if (type_.isObject(data)) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
- }
};
// class ContactEmailAddress ///////////////////////////////////////////
var ContactEmailAddress = function(address, types, isDefault) {
- validator_.isConstructorCall(this, ContactEmailAddress);
-
- var _email = '';
- var _label = null;
- var _isDefault = false;
- var _types = ['WORK'];
-
- if (type_.isString(address) && address.indexOf('@') > 0 &&
- address.indexOf('@') !== (address.length - 1)) {
- _email = address;
- }
-
- if (type_.isBoolean(isDefault)) {
- _isDefault = isDefault;
- }
-
- if (type_.isArray(types)) {
- _types = [];
- for (var i = 0; i < types.length; ++i) {
- if (type_.isString(types[i])) {
- _types.push(types[i]);
- }
+ validator_.isConstructorCall(this, ContactEmailAddress);
+
+ var _email = '';
+ var _label = null;
+ var _isDefault = false;
+ var _types = ['WORK'];
+
+ if (
+ type_.isString(address) &&
+ address.indexOf('@') > 0 &&
+ address.indexOf('@') !== address.length - 1
+ ) {
+ _email = address;
}
- } else if (type_.isString(types)) {
- _types = [];
- _types.push(types);
- }
-
- Object.defineProperties(this, {
- email: {
- get: function() {
- return _email;
- },
- set: function(v) {
- if (type_.isString(v) && v.indexOf('@') > 0 &&
- v.indexOf('@') !== (v.length - 1)) {
- _email = v;
- }
- },
- enumerable: true
- },
- isDefault: {
- get: function() {
- return _isDefault;
- },
- set: function(v) {
- _isDefault = converter_.toBoolean(v, false);
- },
- enumerable: true
- },
- types: {
- get: function() {
- return _types;
- },
- set: function(v) {
- if (type_.isArray(v)) {
- _types = [];
- for (var i = 0; i < v.length; ++i) {
- if (type_.isString(v[i])) {
- _types.push(v[i]);
+
+ if (type_.isBoolean(isDefault)) {
+ _isDefault = isDefault;
+ }
+
+ if (type_.isArray(types)) {
+ _types = [];
+ for (var i = 0; i < types.length; ++i) {
+ if (type_.isString(types[i])) {
+ _types.push(types[i]);
}
- }
- } else if (type_.isString(v)) {
- _types = [];
- _types.push(v);
}
- },
- enumerable: true
- },
- label: {
- get: function() {
- return _label;
- },
- set: function(v) {
- _label = converter_.toString(v, true);
- },
- enumerable: true
+ } else if (type_.isString(types)) {
+ _types = [];
+ _types.push(types);
}
- });
- if (_editGuard.isEditEnabled()) {
- for (var prop in arguments[0]) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = arguments[0][prop];
- }
+ Object.defineProperties(this, {
+ email: {
+ get: function() {
+ return _email;
+ },
+ set: function(v) {
+ if (
+ type_.isString(v) &&
+ v.indexOf('@') > 0 &&
+ v.indexOf('@') !== v.length - 1
+ ) {
+ _email = v;
+ }
+ },
+ enumerable: true
+ },
+ isDefault: {
+ get: function() {
+ return _isDefault;
+ },
+ set: function(v) {
+ _isDefault = converter_.toBoolean(v, false);
+ },
+ enumerable: true
+ },
+ types: {
+ get: function() {
+ return _types;
+ },
+ set: function(v) {
+ if (type_.isArray(v)) {
+ _types = [];
+ for (var i = 0; i < v.length; ++i) {
+ if (type_.isString(v[i])) {
+ _types.push(v[i]);
+ }
+ }
+ } else if (type_.isString(v)) {
+ _types = [];
+ _types.push(v);
+ }
+ },
+ enumerable: true
+ },
+ label: {
+ get: function() {
+ return _label;
+ },
+ set: function(v) {
+ _label = converter_.toString(v, true);
+ },
+ enumerable: true
+ }
+ });
+
+ if (_editGuard.isEditEnabled()) {
+ for (var prop in arguments[0]) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = arguments[0][prop];
+ }
+ }
}
- }
};
// class ContactPhoneNumber ////////////////////////////////////////////
var ContactPhoneNumber = function(number, type, isDefault) {
- validator_.isConstructorCall(this, ContactPhoneNumber);
-
- var _isDefault = false;
- var _number = '';
- var _types = ['VOICE'];
+ validator_.isConstructorCall(this, ContactPhoneNumber);
- if (type_.isString(number)) {
- _number = number;
- }
+ var _isDefault = false;
+ var _number = '';
+ var _types = ['VOICE'];
- if (type_.isArray(type)) {
- _types = [];
- for (var i = 0; i < type.length; ++i) {
- _types.push(converter_.toString(type[i], false));
+ if (type_.isString(number)) {
+ _number = number;
}
- } else if (type_.isString(type)) {
- _types = [];
- _types.push(type, false);
- }
-
- if (type_.isBoolean(isDefault)) {
- _isDefault = isDefault;
- }
-
- Object.defineProperties(this, {
- number: {
- get: function() {
- return _number;
- },
- set: function(v) {
- _number = converter_.toString(v, false);
- },
- enumerable: true
- },
- isDefault: {
- get: function() {
- return _isDefault;
- },
- set: function(v) {
- _isDefault = converter_.toBoolean(v, false);
- },
- enumerable: true
- },
- types: {
- get: function() {
- return _types;
- },
- set: function(v) {
- if (type_.isArray(v)) {
- _types = [];
- for (var i = 0; i < v.length; ++i) {
- _types.push(converter_.toString(v[i], false));
- }
- } else if (type_.isString(v)) {
- _types = [];
- _types.push(v, false);
+
+ if (type_.isArray(type)) {
+ _types = [];
+ for (var i = 0; i < type.length; ++i) {
+ _types.push(converter_.toString(type[i], false));
}
- },
- enumerable: true
- },
- label: {
- value: null,
- writable: true,
- enumerable: true
+ } else if (type_.isString(type)) {
+ _types = [];
+ _types.push(type, false);
}
- });
- if (_editGuard.isEditEnabled()) {
- for (var prop in arguments[0]) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = arguments[0][prop];
- }
+ if (type_.isBoolean(isDefault)) {
+ _isDefault = isDefault;
+ }
+
+ Object.defineProperties(this, {
+ number: {
+ get: function() {
+ return _number;
+ },
+ set: function(v) {
+ _number = converter_.toString(v, false);
+ },
+ enumerable: true
+ },
+ isDefault: {
+ get: function() {
+ return _isDefault;
+ },
+ set: function(v) {
+ _isDefault = converter_.toBoolean(v, false);
+ },
+ enumerable: true
+ },
+ types: {
+ get: function() {
+ return _types;
+ },
+ set: function(v) {
+ if (type_.isArray(v)) {
+ _types = [];
+ for (var i = 0; i < v.length; ++i) {
+ _types.push(converter_.toString(v[i], false));
+ }
+ } else if (type_.isString(v)) {
+ _types = [];
+ _types.push(v, false);
+ }
+ },
+ enumerable: true
+ },
+ label: {
+ value: null,
+ writable: true,
+ enumerable: true
+ }
+ });
+
+ if (_editGuard.isEditEnabled()) {
+ for (var prop in arguments[0]) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = arguments[0][prop];
+ }
+ }
}
- }
};
// class ContactAddress ////////////////////////////////////////////////
var ContactAddress = function(data) {
- validator_.isConstructorCall(this, ContactAddress);
-
- var _isDefault = false;
- var _types = ['HOME'];
-
- Object.defineProperties(this, {
- country: {
- value: null,
- writable: true,
- enumerable: true
- },
- region: {
- value: null,
- writable: true,
- enumerable: true
- },
- city: {
- value: null,
- writable: true,
- enumerable: true
- },
- streetAddress: {
- value: null,
- writable: true,
- enumerable: true
- },
- additionalInformation: {
- value: null,
- writable: true,
- enumerable: true
- },
- postalCode: {
- value: null,
- writable: true,
- enumerable: true
- },
- isDefault: {
- get: function() {
- return _isDefault;
- },
- set: function(v) {
- _isDefault = converter_.toBoolean(v, false);
- },
- enumerable: true
- },
- types: {
- get: function() {
- return _types;
- },
- set: function(v) {
- if (type_.isString(v)) {
- _types = [];
- _types.push(v);
- } else if (type_.isArray(v)) {
- _types = [];
- for (var i = 0; i < v.length; ++i) {
- if (type_.isString(v[i])) {
- _types.push(v[i]);
- }
- }
+ validator_.isConstructorCall(this, ContactAddress);
+
+ var _isDefault = false;
+ var _types = ['HOME'];
+
+ Object.defineProperties(this, {
+ country: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ region: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ city: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ streetAddress: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ additionalInformation: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ postalCode: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ isDefault: {
+ get: function() {
+ return _isDefault;
+ },
+ set: function(v) {
+ _isDefault = converter_.toBoolean(v, false);
+ },
+ enumerable: true
+ },
+ types: {
+ get: function() {
+ return _types;
+ },
+ set: function(v) {
+ if (type_.isString(v)) {
+ _types = [];
+ _types.push(v);
+ } else if (type_.isArray(v)) {
+ _types = [];
+ for (var i = 0; i < v.length; ++i) {
+ if (type_.isString(v[i])) {
+ _types.push(v[i]);
+ }
+ }
+ }
+ },
+ enumerable: true
+ },
+ label: {
+ value: null,
+ writable: true,
+ enumerable: true
}
- },
- enumerable: true
- },
- label: {
- value: null,
- writable: true,
- enumerable: true
- }
- });
+ });
- if (type_.isObject(data)) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (type_.isObject(data)) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
// class ContactAnniversary ////////////////////////////////////////////////
var ContactAnniversary = function(anniversary_date, anniversary_label) {
- validator_.isConstructorCall(this, ContactAnniversary);
-
- var _anniversary_date = new Date();
- var _anniversary_label = null;
-
- Object.defineProperties(this, {
- date: {
- get: function() {
- return _anniversary_date;
- },
- set: function(v) {
- _anniversary_date = v instanceof Date ? v : new Date();
- },
- enumerable: true
- },
- label: {
- get: function() {
- return _anniversary_label;
- },
- set: function(v) {
- _anniversary_label = converter_.toString(v, true);
- },
- enumerable: true
- }
- });
-
- if (_editGuard.isEditEnabled()) {
- _anniversary_date = _fromJsonDate(arguments[0].date);
- _anniversary_label = arguments[0].label;
- } else {
- if (type_.isDate(anniversary_date)) {
- _anniversary_date = anniversary_date;
- }
- if (type_.isString(anniversary_label)) {
- _anniversary_label = anniversary_label;
+ validator_.isConstructorCall(this, ContactAnniversary);
+
+ var _anniversary_date = new Date();
+ var _anniversary_label = null;
+
+ Object.defineProperties(this, {
+ date: {
+ get: function() {
+ return _anniversary_date;
+ },
+ set: function(v) {
+ _anniversary_date = v instanceof Date ? v : new Date();
+ },
+ enumerable: true
+ },
+ label: {
+ get: function() {
+ return _anniversary_label;
+ },
+ set: function(v) {
+ _anniversary_label = converter_.toString(v, true);
+ },
+ enumerable: true
+ }
+ });
+
+ if (_editGuard.isEditEnabled()) {
+ _anniversary_date = _fromJsonDate(arguments[0].date);
+ _anniversary_label = arguments[0].label;
+ } else {
+ if (type_.isDate(anniversary_date)) {
+ _anniversary_date = anniversary_date;
+ }
+ if (type_.isString(anniversary_label)) {
+ _anniversary_label = anniversary_label;
+ }
}
- }
};
// class ContactWebSite ////////////////////////////////////////////////////
var ContactWebSite = function(contact_url, contact_type) {
- validator_.isConstructorCall(this, ContactWebSite);
-
- var _url = '';
- var _type = 'HOMEPAGE';
-
- if (type_.isString(contact_url)) {
- _url = contact_url;
- }
- if (type_.isString(contact_type)) {
- _type = contact_type;
- }
-
- Object.defineProperties(this, {
- url: {
- get: function() {
- return _url;
- },
- set: function(v) {
- _url = converter_.toString(v, false);
- },
- enumerable: true
- },
- type: {
- get: function() {
- return _type;
- },
- set: function(v) {
- _type = converter_.toString(v, false);
- },
- enumerable: true
+ validator_.isConstructorCall(this, ContactWebSite);
+
+ var _url = '';
+ var _type = 'HOMEPAGE';
+
+ if (type_.isString(contact_url)) {
+ _url = contact_url;
+ }
+ if (type_.isString(contact_type)) {
+ _type = contact_type;
}
- });
+
+ Object.defineProperties(this, {
+ url: {
+ get: function() {
+ return _url;
+ },
+ set: function(v) {
+ _url = converter_.toString(v, false);
+ },
+ enumerable: true
+ },
+ type: {
+ get: function() {
+ return _type;
+ },
+ set: function(v) {
+ _type = converter_.toString(v, false);
+ },
+ enumerable: true
+ }
+ });
};
// class ContactOrganization ///////////////////////////////////////////////
var ContactOrganization = function(data) {
- validator_.isConstructorCall(this, ContactOrganization);
- Object.defineProperties(this, {
- name: {
- value: null,
- writable: true,
- enumerable: true
- },
- department: {
- value: null,
- writable: true,
- enumerable: true
- },
- title: {
- value: null,
- writable: true,
- enumerable: true
- },
- role: {
- value: null,
- writable: true,
- enumerable: true
- },
- logoURI: {
- value: null,
- writable: true,
- enumerable: true
- }
- });
+ validator_.isConstructorCall(this, ContactOrganization);
+ Object.defineProperties(this, {
+ name: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ department: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ title: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ role: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ logoURI: {
+ value: null,
+ writable: true,
+ enumerable: true
+ }
+ });
- if (type_.isObject(data)) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (type_.isObject(data)) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
// class ContactName ///////////////////////////////////////////////////////
var ContactName = function(data) {
- validator_.isConstructorCall(this, ContactName);
-
- var _displayName = null;
- var _nicknames = [];
-
- Object.defineProperties(this, {
- prefix: {
- value: null,
- writable: true,
- enumerable: true
- },
- suffix: {
- value: null,
- writable: true,
- enumerable: true
- },
- firstName: {
- value: null,
- writable: true,
- enumerable: true
- },
- middleName: {
- value: null,
- writable: true,
- enumerable: true
- },
- lastName: {
- value: null,
- writable: true,
- enumerable: true
- },
- nicknames: {
- get: function() {
- return _nicknames;
- },
- set: function(nicknames) {
- if (type_.isArray(nicknames)) {
- _nicknames = nicknames;
- }
- },
- enumerable: true
- },
- phoneticFirstName: {
- value: null,
- writable: true,
- enumerable: true
- },
- phoneticMiddleName: {
- value: null,
- writable: true,
- enumerable: true
- },
- phoneticLastName: {
- value: null,
- writable: true,
- enumerable: true
- },
- displayName: {
- get: function() {
- return _displayName;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _displayName = converter_.toString(v, true);
+ validator_.isConstructorCall(this, ContactName);
+
+ var _displayName = null;
+ var _nicknames = [];
+
+ Object.defineProperties(this, {
+ prefix: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ suffix: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ firstName: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ middleName: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ lastName: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ nicknames: {
+ get: function() {
+ return _nicknames;
+ },
+ set: function(nicknames) {
+ if (type_.isArray(nicknames)) {
+ _nicknames = nicknames;
+ }
+ },
+ enumerable: true
+ },
+ phoneticFirstName: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ phoneticMiddleName: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ phoneticLastName: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ displayName: {
+ get: function() {
+ return _displayName;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _displayName = converter_.toString(v, true);
+ }
+ },
+ enumerable: true
}
- },
- enumerable: true
- }
- });
+ });
- if (type_.isObject(data)) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (type_.isObject(data)) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
var ContactRelationship = function(relativeName, type) {
- validator_.isConstructorCall(this, ContactRelationship);
-
- var _relativeName = converter_.toString(relativeName, false);
- var _type = type ? converter_.toEnum(type, Object.keys(ContactRelationshipType), false)
- : ContactRelationshipType.OTHER;
- var _label = null;
-
- Object.defineProperties(this, {
- relativeName: {
- get: function () {
- return _relativeName;
- },
- set: function (v) {
- _relativeName = converter_.toString(v, false);
- },
- enumerable: true
- },
- type: {
- get: function () {
- return _type;
- },
- set: function (v) {
- _type = v ? converter_.toEnum(v, Object.keys(ContactRelationshipType), false)
- : _type;
- },
- enumerable: true
- },
- label: {
- get: function () {
- return _label;
- },
- set: function (v) {
- _label = converter_.toString(v, true);
- },
- enumerable: true
- }
- });
+ validator_.isConstructorCall(this, ContactRelationship);
+
+ var _relativeName = converter_.toString(relativeName, false);
+ var _type = type
+ ? converter_.toEnum(type, Object.keys(ContactRelationshipType), false)
+ : ContactRelationshipType.OTHER;
+ var _label = null;
+
+ Object.defineProperties(this, {
+ relativeName: {
+ get: function() {
+ return _relativeName;
+ },
+ set: function(v) {
+ _relativeName = converter_.toString(v, false);
+ },
+ enumerable: true
+ },
+ type: {
+ get: function() {
+ return _type;
+ },
+ set: function(v) {
+ _type = v
+ ? converter_.toEnum(v, Object.keys(ContactRelationshipType), false)
+ : _type;
+ },
+ enumerable: true
+ },
+ label: {
+ get: function() {
+ return _label;
+ },
+ set: function(v) {
+ _label = converter_.toString(v, true);
+ },
+ enumerable: true
+ }
+ });
};
var ContactExtension = function(data) {
- validator_.isConstructorCall(this, ContactExtension);
-
- var _data1 = 0;
- var _data2 = null;
- var _data3 = null;
- var _data4 = null;
- var _data5 = null;
- var _data6 = null;
- var _data7 = null;
- var _data8 = null;
- var _data9 = null;
- var _data10 = null;
- var _data11 = null;
- var _data12 = null;
-
- Object.defineProperties(this, {
- data1: {
- get: function () {
- return _data1;
- },
- set: function (v) {
- _data1 = converter_.toLong(v, false);
- },
- enumerable: true
- },
- data2: {
- get: function () {
- return _data2;
- },
- set: function (v) {
- _data2 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data3: {
- get: function () {
- return _data3;
- },
- set: function (v) {
- _data3 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data4: {
- get: function () {
- return _data4;
- },
- set: function (v) {
- _data4 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data5: {
- get: function () {
- return _data5;
- },
- set: function (v) {
- _data5 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data6: {
- get: function () {
- return _data6;
- },
- set: function (v) {
- _data6 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data7: {
- get: function () {
- return _data7;
- },
- set: function (v) {
- _data7 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data8: {
- get: function () {
- return _data8;
- },
- set: function (v) {
- _data8 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data9: {
- get: function () {
- return _data9;
- },
- set: function (v) {
- _data9 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data10: {
- get: function () {
- return _data10;
- },
- set: function (v) {
- _data10 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data11: {
- get: function () {
- return _data11;
- },
- set: function (v) {
- _data11 = converter_.toString(v, true);
- },
- enumerable: true
- },
- data12: {
- get: function () {
- return _data12;
- },
- set: function (v) {
- _data12 = converter_.toString(v, true);
- },
- enumerable: true
- }
- });
+ validator_.isConstructorCall(this, ContactExtension);
+
+ var _data1 = 0;
+ var _data2 = null;
+ var _data3 = null;
+ var _data4 = null;
+ var _data5 = null;
+ var _data6 = null;
+ var _data7 = null;
+ var _data8 = null;
+ var _data9 = null;
+ var _data10 = null;
+ var _data11 = null;
+ var _data12 = null;
+
+ Object.defineProperties(this, {
+ data1: {
+ get: function() {
+ return _data1;
+ },
+ set: function(v) {
+ _data1 = converter_.toLong(v, false);
+ },
+ enumerable: true
+ },
+ data2: {
+ get: function() {
+ return _data2;
+ },
+ set: function(v) {
+ _data2 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data3: {
+ get: function() {
+ return _data3;
+ },
+ set: function(v) {
+ _data3 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data4: {
+ get: function() {
+ return _data4;
+ },
+ set: function(v) {
+ _data4 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data5: {
+ get: function() {
+ return _data5;
+ },
+ set: function(v) {
+ _data5 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data6: {
+ get: function() {
+ return _data6;
+ },
+ set: function(v) {
+ _data6 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data7: {
+ get: function() {
+ return _data7;
+ },
+ set: function(v) {
+ _data7 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data8: {
+ get: function() {
+ return _data8;
+ },
+ set: function(v) {
+ _data8 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data9: {
+ get: function() {
+ return _data9;
+ },
+ set: function(v) {
+ _data9 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data10: {
+ get: function() {
+ return _data10;
+ },
+ set: function(v) {
+ _data10 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data11: {
+ get: function() {
+ return _data11;
+ },
+ set: function(v) {
+ _data11 = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ data12: {
+ get: function() {
+ return _data12;
+ },
+ set: function(v) {
+ _data12 = converter_.toString(v, true);
+ },
+ enumerable: true
+ }
+ });
- if (type_.isObject(data)) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (type_.isObject(data)) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
var ContactInstantMessenger = function(imAddress, type) {
- validator_.isConstructorCall(this, ContactInstantMessenger);
-
- var _imAddress = '';
- var _type = 'OTHER';
-
- Object.defineProperties(this, {
- imAddress: {
- get: function() {
- return _imAddress;
- },
- set: function(v) {
- if (type_.isNullOrUndefined(v)) {
- return;
- }
- _imAddress = converter_.toString(v, false);
- },
- enumerable: true
- },
- type: {
- get: function() {
- return _type;
- },
- set: function(v) {
- if (type_.isNullOrUndefined(v)) {
- return;
+ validator_.isConstructorCall(this, ContactInstantMessenger);
+
+ var _imAddress = '';
+ var _type = 'OTHER';
+
+ Object.defineProperties(this, {
+ imAddress: {
+ get: function() {
+ return _imAddress;
+ },
+ set: function(v) {
+ if (type_.isNullOrUndefined(v)) {
+ return;
+ }
+ _imAddress = converter_.toString(v, false);
+ },
+ enumerable: true
+ },
+ type: {
+ get: function() {
+ return _type;
+ },
+ set: function(v) {
+ if (type_.isNullOrUndefined(v)) {
+ return;
+ }
+ _type = converter_.toEnum(
+ v,
+ Object.keys(ContactInstantMessengerType),
+ false
+ );
+ },
+ enumerable: true
+ },
+ label: {
+ value: null,
+ writable: true,
+ enumerable: true
}
- _type = converter_.toEnum(v, Object.keys(ContactInstantMessengerType), false);
- },
- enumerable: true
- },
- label: {
- value: null,
- writable: true,
- enumerable: true
- }
- });
+ });
- this.imAddress = imAddress;
- this.type = type;
+ this.imAddress = imAddress;
+ this.type = type;
};
// exports /////////////////////////////////////////////////////////////////
diff --git a/src/contact/js/contact_manager.js b/src/contact/js/contact_manager.js
index 3b526442..78f0a1dd 100755
--- a/src/contact/js/contact_manager.js
+++ b/src/contact/js/contact_manager.js
@@ -17,554 +17,585 @@
var _personListenerRegistered = false;
var _personCallbackMap = {};
var _personChangeListener = function(result) {
- for (var key in _personCallbackMap) {
- if (_personCallbackMap.hasOwnProperty(key)) {
- if (result.added.length) {
- native_.callIfPossible(_personCallbackMap[key].onpersonsadded,
- _promote(result.added, Person));
- }
- if (result.updated.length) {
- native_.callIfPossible(_personCallbackMap[key].onpersonsupdated,
- _promote(result.updated, Person));
- }
- if (result.removed.length) {
- native_.callIfPossible(_personCallbackMap[key].onpersonsremoved,
- result.removed);
- }
+ for (var key in _personCallbackMap) {
+ if (_personCallbackMap.hasOwnProperty(key)) {
+ if (result.added.length) {
+ native_.callIfPossible(
+ _personCallbackMap[key].onpersonsadded,
+ _promote(result.added, Person)
+ );
+ }
+ if (result.updated.length) {
+ native_.callIfPossible(
+ _personCallbackMap[key].onpersonsupdated,
+ _promote(result.updated, Person)
+ );
+ }
+ if (result.removed.length) {
+ native_.callIfPossible(
+ _personCallbackMap[key].onpersonsremoved,
+ result.removed
+ );
+ }
+ }
}
- }
};
-
var ContactManager = function() {};
// Gets the available address books
ContactManager.prototype.getAddressBooks = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: false,
- nullable: false
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var books = native_.getResultObject(result);
- var tmp = [];
-
- books.forEach(function(data) {
- return _editGuard.run(function() {
- var addressBook = new AddressBook(result.accountId, result.name);
- addressBook.id = data.id;
- addressBook.name = data.name;
- addressBook.readOnly = result.readOnly;
-
- tmp.push(addressBook);
- });
- });
-
- native_.callIfPossible(args.successCallback, tmp);
- }
- };
-
- var result = native_.call('ContactManager_getAddressBooks', {}, callback);
-
- _checkError(result);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var books = native_.getResultObject(result);
+ var tmp = [];
+
+ books.forEach(function(data) {
+ return _editGuard.run(function() {
+ var addressBook = new AddressBook(result.accountId, result.name);
+ addressBook.id = data.id;
+ addressBook.name = data.name;
+ addressBook.readOnly = result.readOnly;
+
+ tmp.push(addressBook);
+ });
+ });
+
+ native_.callIfPossible(args.successCallback, tmp);
+ }
+ };
+
+ var result = native_.call('ContactManager_getAddressBooks', {}, callback);
+
+ _checkError(result);
};
// Gets the aggregation of all address books.
var ContactManager_getUnifiedAddressBook = function() {
- utils_.checkPrivilegeAccess(privilege_.CONTACT_READ);
+ utils_.checkPrivilegeAccess(privilege_.CONTACT_READ);
- return _editGuard.run(function() {
- var addressBook = new AddressBook(0, 'Unified address book');
- addressBook.id = UNIFIED_ADDRESSBOOK_ID;
- addressBook.readOnly = false;
+ return _editGuard.run(function() {
+ var addressBook = new AddressBook(0, 'Unified address book');
+ addressBook.id = UNIFIED_ADDRESSBOOK_ID;
+ addressBook.readOnly = false;
- return addressBook;
- });
+ return addressBook;
+ });
};
ContactManager.prototype.getUnifiedAddressBook = function() {
- return ContactManager_getUnifiedAddressBook.apply(this, arguments);
+ return ContactManager_getUnifiedAddressBook.apply(this, arguments);
};
// Gets the default address book.
ContactManager.prototype.getDefaultAddressBook = function() {
- //privileges are checked in getAddressBook function
- return this.getAddressBook(DEFAULT_ADDRESSBOOK_ID);
+ //privileges are checked in getAddressBook function
+ return this.getAddressBook(DEFAULT_ADDRESSBOOK_ID);
};
// Gets the address book with the specified identifier.
ContactManager.prototype.getAddressBook = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'addressBookId',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.addressBookId)) !== args.addressBookId) {
- // TCT: ContactManager_getAddressBook_addressBookId_invalid
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- }
-
- var result = native_.callSync('ContactManager_getAddressBook', {
- addressBookId: args.addressBookId
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- result = native_.getResultObject(result);
-
- return _editGuard.run(function() {
- var addressBook = new AddressBook(result.accountId, result.name);
- addressBook.id = args.addressBookId;
- addressBook.readOnly = result.readOnly;
-
- return addressBook;
- });
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'addressBookId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (String(converter_.toLong(args.addressBookId)) !== args.addressBookId) {
+ // TCT: ContactManager_getAddressBook_addressBookId_invalid
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
+
+ var result = native_.callSync('ContactManager_getAddressBook', {
+ addressBookId: args.addressBookId
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ result = native_.getResultObject(result);
+
+ return _editGuard.run(function() {
+ var addressBook = new AddressBook(result.accountId, result.name);
+ addressBook.id = args.addressBookId;
+ addressBook.readOnly = result.readOnly;
+
+ return addressBook;
+ });
};
ContactManager.prototype.addAddressBook = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'addressBook',
- type: types_.PLATFORM_OBJECT,
- values: tizen.AddressBook,
- optional: false,
- nullable: false
- }]);
-
- var result = native_.callSync('ContactManager_addAddressBook', {
- addressBook: args.addressBook
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- var data = native_.getResultObject(result);
- _editGuard.run(function() {
- for (var prop in data) {
- if (args.addressBook.hasOwnProperty(prop)) {
- args.addressBook[prop] = data[prop];
- }
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'addressBook',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.AddressBook,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ var result = native_.callSync('ContactManager_addAddressBook', {
+ addressBook: args.addressBook
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- });
+
+ var data = native_.getResultObject(result);
+ _editGuard.run(function() {
+ for (var prop in data) {
+ if (args.addressBook.hasOwnProperty(prop)) {
+ args.addressBook[prop] = data[prop];
+ }
+ }
+ });
};
ContactManager.prototype.removeAddressBook = function() {
- // TCT: ContactManager_removeAddressBook_misarg
- if (type_.isNullOrUndefined(arguments[0])) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var args = validator_.validateArgs(arguments, [{
- name: 'addressBookId',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (args.addressBookId === UNIFIED_ADDRESSBOOK_ID) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Unified address book can not be deleted');
- }
-
- if (args.addressBookId === DEFAULT_ADDRESSBOOK_ID) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Default address book can not be deleted');
- }
-
- var result = native_.callSync('ContactManager_removeAddressBook', {
- addressBookId: args.addressBookId
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ // TCT: ContactManager_removeAddressBook_misarg
+ if (type_.isNullOrUndefined(arguments[0])) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'addressBookId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (args.addressBookId === UNIFIED_ADDRESSBOOK_ID) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Unified address book can not be deleted'
+ );
+ }
+
+ if (args.addressBookId === DEFAULT_ADDRESSBOOK_ID) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Default address book can not be deleted'
+ );
+ }
+
+ var result = native_.callSync('ContactManager_removeAddressBook', {
+ addressBookId: args.addressBookId
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
// Gets the person with the specified identifier.
ContactManager.prototype.get = function() {
- // validation
- var args = validator_.validateArgs(arguments, [
- {
- name: 'personId',
- type: types_.STRING,
- optional: false,
- nullable: false
+ // validation
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'personId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (String(converter_.toLong(args.personId)) !== args.personId) {
+ // TCT: ContactManager_get_personId_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- ]);
- if (String(converter_.toLong(args.personId)) !== args.personId) {
- // TCT: ContactManager_get_personId_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
+ var result = native_.callSync('ContactManager_get', {
+ personId: args.personId
+ });
+ _checkError(result);
- var result = native_.callSync('ContactManager_get', {
- personId: args.personId
- });
- _checkError(result);
-
- return _editGuard.run(function() {
- return new Person(native_.getResultObject(result));
- });
+ return _editGuard.run(function() {
+ return new Person(native_.getResultObject(result));
+ });
};
// Updates a person in the address book synchronously.
var ContactManagerUpdate = function() {
- // validation
- var args = validator_.validateArgs(arguments, [{
- name: 'person',
- type: types_.PLATFORM_OBJECT,
- values: Person,
- optional: false,
- nullable: false
- }]);
- var result = native_.callSync('ContactManager_update', { person: args.person });
- _checkError(result);
-
- result = native_.getResultObject(result);
- for (var prop in result) {
- if (args.person.hasOwnProperty(prop)) {
- args.person[prop] = result[prop];
+ // validation
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'person',
+ type: types_.PLATFORM_OBJECT,
+ values: Person,
+ optional: false,
+ nullable: false
+ }
+ ]);
+ var result = native_.callSync('ContactManager_update', { person: args.person });
+ _checkError(result);
+
+ result = native_.getResultObject(result);
+ for (var prop in result) {
+ if (args.person.hasOwnProperty(prop)) {
+ args.person[prop] = result[prop];
+ }
}
- }
};
ContactManager.prototype.update = function() {
- ContactManagerUpdate.apply(this, arguments);
+ ContactManagerUpdate.apply(this, arguments);
};
// Updates several existing persons in the contact DB asynchronously.
ContactManager.prototype.updateBatch = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'persons',
- type: types_.ARRAY,
- values: Person,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
- }
-
- native_.callIfPossible(args.successCallback);
- };
-
- var result = native_.call('ContactManager_updateBatch', {
- addressBook: {},
- batchArgs: _toJsonObject(args.persons)
- }, callback);
-
- _checkError(result);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'persons',
+ type: types_.ARRAY,
+ values: Person,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var result = native_.call(
+ 'ContactManager_updateBatch',
+ {
+ addressBook: {},
+ batchArgs: _toJsonObject(args.persons)
+ },
+ callback
+ );
+
+ _checkError(result);
};
// Removes a person from the contact DB synchronously.
ContactManager.prototype.remove = function() {
- // validation
- var args = validator_.validateArgs(arguments, [{
- name: 'personId',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.personId)) !== args.personId) {
- // TCT: ContactManager_remove_personId_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('ContactManager_remove', {personId: args.personId});
- _checkError(result);
+ // validation
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'personId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (String(converter_.toLong(args.personId)) !== args.personId) {
+ // TCT: ContactManager_remove_personId_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var result = native_.callSync('ContactManager_remove', { personId: args.personId });
+ _checkError(result);
};
// Removes persons from contact DB asynchronously.
ContactManager.prototype.removeBatch = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'personIds',
- type: types_.ARRAY,
- values: types_.STRING,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
- }
-
- native_.callIfPossible(args.successCallback);
- };
-
- var result = native_.call('ContactManager_removeBatch', {
- addressBook: {},
- batchArgs: _toJsonObject(args.personIds)
- }, callback);
-
- _checkError(result);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'personIds',
+ type: types_.ARRAY,
+ values: types_.STRING,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var result = native_.call(
+ 'ContactManager_removeBatch',
+ {
+ addressBook: {},
+ batchArgs: _toJsonObject(args.personIds)
+ },
+ callback
+ );
+
+ _checkError(result);
};
// Gets an array of all Person objects from the contact DB or the ones that match the
// optionally supplied filter.
ContactManager.prototype.find = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: false,
- nullable: false
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'filter',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter,
- tizen.AttributeRangeFilter,
- tizen.CompositeFilter],
- optional: true,
- nullable: true
- },
- {
- name: 'sortMode',
- type: types_.PLATFORM_OBJECT,
- values: tizen.SortMode,
- optional: true,
- nullable: true
- }
- ]);
-
- var data = {
- filter: utils_.repackFilter(args.filter),
- sortMode: args.sortMode
- };
-
- var self = this;
-
- var callback = function(result) {
- if (native_.isSuccess(result)) {
- var _result = native_.getResultObject(result);
- var retval = [];
- for (var i = 0; i < _result.length; ++i) {
- var person = _editGuard.run(function() {
- return new Person(_result[i]);
- });
- retval.push(person);
- }
- args.successCallback(retval);
- } else {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- }
- };
-
- var result = native_.call('ContactManager_find', data, callback);
-
- _checkError(result);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'filter',
+ type: types_.PLATFORM_OBJECT,
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ],
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'sortMode',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.SortMode,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var data = {
+ filter: utils_.repackFilter(args.filter),
+ sortMode: args.sortMode
+ };
+
+ var self = this;
+
+ var callback = function(result) {
+ if (native_.isSuccess(result)) {
+ var _result = native_.getResultObject(result);
+ var retval = [];
+ for (var i = 0; i < _result.length; ++i) {
+ var person = _editGuard.run(function() {
+ return new Person(_result[i]);
+ });
+ retval.push(person);
+ }
+ args.successCallback(retval);
+ } else {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ }
+ };
+
+ var result = native_.call('ContactManager_find', data, callback);
+
+ _checkError(result);
};
ContactManager.prototype.findByUsageCount = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'filter',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter,
- tizen.AttributeRangeFilter],
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: false,
- nullable: false
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'sortModeOrder',
- type: types_.ENUM,
- values: ['ASC', 'DESC'],
- optional: true,
- nullable: true
- },
- {
- name: 'limit',
- type: types_.UNSIGNED_LONG,
- optional: true,
- nullable: true
- },
- {
- name: 'offset',
- type: types_.UNSIGNED_LONG,
- optional: true,
- nullable: true
- }
- ]);
-
- var data = {
- filter: utils_.repackFilter(args.filter),
- sortModeOrder: args.sortModeOrder,
- limit: args.limit,
- offset: args.offset
- };
-
- var self = this;
-
- var callback = function(result) {
- if (native_.isSuccess(result)) {
- var _result = native_.getResultObject(result);
- var retval = [];
- for (var i = 0; i < _result.length; ++i) {
- var person = _editGuard.run(function() {
- return new Person(_result[i]);
- });
- retval.push(person);
- }
- args.successCallback(retval);
- } else {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- }
- };
-
- var result = native_.call('ContactManager_findByUsageCount', data, callback);
-
- _checkError(result);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'filter',
+ type: types_.PLATFORM_OBJECT,
+ values: [tizen.AttributeFilter, tizen.AttributeRangeFilter],
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'sortModeOrder',
+ type: types_.ENUM,
+ values: ['ASC', 'DESC'],
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'limit',
+ type: types_.UNSIGNED_LONG,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'offset',
+ type: types_.UNSIGNED_LONG,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var data = {
+ filter: utils_.repackFilter(args.filter),
+ sortModeOrder: args.sortModeOrder,
+ limit: args.limit,
+ offset: args.offset
+ };
+
+ var self = this;
+
+ var callback = function(result) {
+ if (native_.isSuccess(result)) {
+ var _result = native_.getResultObject(result);
+ var retval = [];
+ for (var i = 0; i < _result.length; ++i) {
+ var person = _editGuard.run(function() {
+ return new Person(_result[i]);
+ });
+ retval.push(person);
+ }
+ args.successCallback(retval);
+ } else {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ }
+ };
+
+ var result = native_.call('ContactManager_findByUsageCount', data, callback);
+
+ _checkError(result);
};
// Subscribes to receive notifications about persons' changes.
ContactManager.prototype.addChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: types_.LISTENER,
- values: ['onpersonsadded', 'onpersonsupdated', 'onpersonsremoved'],
- optional: false,
- nullable: false
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.LISTENER,
+ values: ['onpersonsadded', 'onpersonsupdated', 'onpersonsremoved'],
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (type_.isEmptyObject(_personCallbackMap)) {
+ var result = native_.callSync('ContactManager_startListening', {});
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- ]);
-
- if (type_.isEmptyObject(_personCallbackMap)) {
- var result = native_.callSync('ContactManager_startListening', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (!_personListenerRegistered) {
+ native_.addListener('ContactPersonChangeListener', _personChangeListener);
+ _personListenerRegistered = true;
}
- }
-
- if (!_personListenerRegistered) {
- native_.addListener('ContactPersonChangeListener', _personChangeListener);
- _personListenerRegistered = true;
- }
- var currentWatchId = _getNextWatchId();
+ var currentWatchId = _getNextWatchId();
- _personCallbackMap[currentWatchId] = args.successCallback;
+ _personCallbackMap[currentWatchId] = args.successCallback;
- return currentWatchId;
+ return currentWatchId;
};
// Unsubscribes a persons' changes watch operation.
var ContactManager_removeChangeListener = function() {
- if (type_.isEmptyObject(_personCallbackMap)) {
- utils_.checkPrivilegeAccess(privilege_.CONTACT_READ);
- }
-
- var args = validator_.validateArgs(arguments, [
- {
- name: 'watchId',
- type: types_.LONG,
- optional: false,
- nullable: false
+ if (type_.isEmptyObject(_personCallbackMap)) {
+ utils_.checkPrivilegeAccess(privilege_.CONTACT_READ);
}
- ]);
- // This makes UTC_contact_removeChangeListenerPerson_N_001 pass.
- // watch id's start at 1
- if (args.watchId === 0) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'id is null or undefined');
- }
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'watchId',
+ type: types_.LONG,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ // This makes UTC_contact_removeChangeListenerPerson_N_001 pass.
+ // watch id's start at 1
+ if (args.watchId === 0) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'id is null or undefined'
+ );
+ }
- if (args.watchId < 0) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Negative watch id');
- }
+ if (args.watchId < 0) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Negative watch id'
+ );
+ }
- if (!_personCallbackMap.hasOwnProperty(args.watchId)) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'watch id not found');
- }
+ if (!_personCallbackMap.hasOwnProperty(args.watchId)) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'watch id not found');
+ }
- delete _personCallbackMap[args.watchId];
+ delete _personCallbackMap[args.watchId];
- if (type_.isEmptyObject(_personCallbackMap)) {
- native_.removeListener('ContactPersonChangeListener', _personChangeListener);
- _personListenerRegistered = false;
+ if (type_.isEmptyObject(_personCallbackMap)) {
+ native_.removeListener('ContactPersonChangeListener', _personChangeListener);
+ _personListenerRegistered = false;
- var result = native_.callSync('ContactManager_stopListening', {});
+ var result = native_.callSync('ContactManager_stopListening', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
};
ContactManager.prototype.removeChangeListener = function() {
- ContactManager_removeChangeListener.apply(this, arguments);
+ ContactManager_removeChangeListener.apply(this, arguments);
};
// exports /////////////////////////////////////////////////////////////////
diff --git a/src/contact/js/person.js b/src/contact/js/person.js
index 489bdf65..edcf84ba 100755
--- a/src/contact/js/person.js
+++ b/src/contact/js/person.js
@@ -15,216 +15,232 @@
*/
var Person = function(data) {
- validator_.isConstructorCall(this, Person);
-
- var _id = '';
- var _displayName = '';
- var _contactCount = 0;
- var _hasPhoneNumber = false;
- var _hasEmail = false;
- var _isFavorite = false;
- var _displayContactId = '';
-
- if (data.hasOwnProperty('id') && type_.isString(data.id)) {
- _id = data.id;
- }
- if (data.hasOwnProperty('displayName') && type_.isString(data.displayName)) {
- _displayName = data.displayName;
- }
- if (data.hasOwnProperty('contactCount') && type_.isNumber(data.contactCount)) {
- _contactCount = data.contactCount;
- }
- if (data.hasOwnProperty('hasPhoneNumber') && type_.isBoolean(data.hasPhoneNumber)) {
- _hasPhoneNumber = data.hasPhoneNumber;
- }
- if (data.hasOwnProperty('hasEmail') && type_.isBoolean(data.hasEmail)) {
- _hasEmail = data.hasEmail;
- }
- if (data.hasOwnProperty('displayContactId') && type_.isString(data.displayContactId)) {
- _displayContactId = data.displayContactId;
- }
- if (data.hasOwnProperty('isFavorite') && type_.isBoolean(data.isFavorite)) {
- _isFavorite = data.isFavorite;
- }
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return _id;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _id = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- displayName: {
- get: function() {
- return _displayName;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _displayName = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- contactCount: {
- get: function() {
- return _contactCount;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _contactCount = converter_.toLong(v, false);
- }
- },
- enumerable: true
- },
- hasPhoneNumber: {
- get: function() {
- return _hasPhoneNumber;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _hasPhoneNumber = converter_.toBoolean(v, false);
- }
- },
- enumerable: true
- },
- hasEmail: {
- get: function() {
- return _hasEmail;
- },
- set: function(v) {
- if (_editGuard.isEditEnabled()) {
- _hasEmail = converter_.toBoolean(v, false);
- }
- },
- enumerable: true
- },
-
- isFavorite: {
- get: function() {
- return _isFavorite;
- },
- set: function(v) {
- _isFavorite = converter_.toBoolean(v, false);
- },
- enumerable: true
- },
- photoURI: {
- value: data.hasOwnProperty('photoURI') ? data.photoURI : null,
- writable: false,
- enumerable: true
- },
- ringtoneURI: {
- value: data.hasOwnProperty('ringtoneURI') ? data.ringtoneURI : null,
- writable: true,
- enumerable: true
- },
- displayContactId: {
- get: function() {
- return _displayContactId;
- },
- set: function(v) {
- _displayContactId = converter_.toString(v, false);
- },
- enumerable: true
+ validator_.isConstructorCall(this, Person);
+
+ var _id = '';
+ var _displayName = '';
+ var _contactCount = 0;
+ var _hasPhoneNumber = false;
+ var _hasEmail = false;
+ var _isFavorite = false;
+ var _displayContactId = '';
+
+ if (data.hasOwnProperty('id') && type_.isString(data.id)) {
+ _id = data.id;
+ }
+ if (data.hasOwnProperty('displayName') && type_.isString(data.displayName)) {
+ _displayName = data.displayName;
+ }
+ if (data.hasOwnProperty('contactCount') && type_.isNumber(data.contactCount)) {
+ _contactCount = data.contactCount;
+ }
+ if (data.hasOwnProperty('hasPhoneNumber') && type_.isBoolean(data.hasPhoneNumber)) {
+ _hasPhoneNumber = data.hasPhoneNumber;
}
- });
+ if (data.hasOwnProperty('hasEmail') && type_.isBoolean(data.hasEmail)) {
+ _hasEmail = data.hasEmail;
+ }
+ if (
+ data.hasOwnProperty('displayContactId') &&
+ type_.isString(data.displayContactId)
+ ) {
+ _displayContactId = data.displayContactId;
+ }
+ if (data.hasOwnProperty('isFavorite') && type_.isBoolean(data.isFavorite)) {
+ _isFavorite = data.isFavorite;
+ }
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return _id;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _id = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ displayName: {
+ get: function() {
+ return _displayName;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _displayName = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ contactCount: {
+ get: function() {
+ return _contactCount;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _contactCount = converter_.toLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ hasPhoneNumber: {
+ get: function() {
+ return _hasPhoneNumber;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _hasPhoneNumber = converter_.toBoolean(v, false);
+ }
+ },
+ enumerable: true
+ },
+ hasEmail: {
+ get: function() {
+ return _hasEmail;
+ },
+ set: function(v) {
+ if (_editGuard.isEditEnabled()) {
+ _hasEmail = converter_.toBoolean(v, false);
+ }
+ },
+ enumerable: true
+ },
+
+ isFavorite: {
+ get: function() {
+ return _isFavorite;
+ },
+ set: function(v) {
+ _isFavorite = converter_.toBoolean(v, false);
+ },
+ enumerable: true
+ },
+ photoURI: {
+ value: data.hasOwnProperty('photoURI') ? data.photoURI : null,
+ writable: false,
+ enumerable: true
+ },
+ ringtoneURI: {
+ value: data.hasOwnProperty('ringtoneURI') ? data.ringtoneURI : null,
+ writable: true,
+ enumerable: true
+ },
+ displayContactId: {
+ get: function() {
+ return _displayContactId;
+ },
+ set: function(v) {
+ _displayContactId = converter_.toString(v, false);
+ },
+ enumerable: true
+ }
+ });
};
// Aggregates another person to this person.
Person.prototype.link = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'personId',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.personId)) !== args.personId) {
- // TCT: Person_link_personId_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('Person_link', {
- personId: this.id,
- id: args.personId
- });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var _this = this;
- _editGuard.run(function() {
- _this.contactCount = _this.contactCount + 1;
- });
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'personId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (String(converter_.toLong(args.personId)) !== args.personId) {
+ // TCT: Person_link_personId_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var result = native_.callSync('Person_link', {
+ personId: this.id,
+ id: args.personId
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var _this = this;
+ _editGuard.run(function() {
+ _this.contactCount = _this.contactCount + 1;
+ });
};
// Separates a contact from this person.
Person.prototype.unlink = function(contactId) {
- var args = validator_.validateArgs(arguments, [{
- name: 'contactId',
- type: types_.STRING,
- optional: false,
- nullable: false
- }]);
-
- if (String(converter_.toLong(args.contactId)) !== args.contactId) {
- // TCT: Person_unlink_contactId_invalid
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var result = native_.callSync('Person_unlink', {
- personId: this.id,
- id: args.contactId
- });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var _this = this;
- return _editGuard.run(function() {
- _this.contactCount = _this.contactCount - 1;
- return new Person(native_.getResultObject(result));
- });
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'contactId',
+ type: types_.STRING,
+ optional: false,
+ nullable: false
+ }
+ ]);
+
+ if (String(converter_.toLong(args.contactId)) !== args.contactId) {
+ // TCT: Person_unlink_contactId_invalid
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var result = native_.callSync('Person_unlink', {
+ personId: this.id,
+ id: args.contactId
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var _this = this;
+ return _editGuard.run(function() {
+ _this.contactCount = _this.contactCount - 1;
+ return new Person(native_.getResultObject(result));
+ });
};
// Gets person's usage count
Person.prototype.getUsageCount = function() {
- // validation
- var args = validator_.validateArgs(arguments, [
- {
- name: 'usage_type',
- type: types_.ENUM,
- values: Object.keys(PersonUsageTypeEnum),
- optional: true,
- nullable: true
- }]);
-
- var usage_type = (args.usage_type === undefined ? null : args.usage_type);
-
- var result = native_.callSync('Person_getUsageCount', { personId: this.id, usage_type: usage_type });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var res = native_.getResultObject(result);
- return Number(res.usageCount);
+ // validation
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'usage_type',
+ type: types_.ENUM,
+ values: Object.keys(PersonUsageTypeEnum),
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var usage_type = args.usage_type === undefined ? null : args.usage_type;
+
+ var result = native_.callSync('Person_getUsageCount', {
+ personId: this.id,
+ usage_type: usage_type
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var res = native_.getResultObject(result);
+ return Number(res.usageCount);
};
// Resets a person's usageCount from the contact DB synchronously.
Person.prototype.resetUsageCount = function() {
-// validation
- var args = validator_.validateArgs(arguments, [{
- name: 'usage_type',
- type: types_.ENUM,
- values: Object.keys(PersonUsageTypeEnum),
- optional: true,
- nullable: true
- }]);
-
- var usage_type = (args.usage_type === undefined ? null : args.usage_type);
-
- var result = native_.callSync('Person_resetUsageCount', { personId: this.id, usage_type: usage_type });
- _checkError(result);
+ // validation
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'usage_type',
+ type: types_.ENUM,
+ values: Object.keys(PersonUsageTypeEnum),
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var usage_type = args.usage_type === undefined ? null : args.usage_type;
+
+ var result = native_.callSync('Person_resetUsageCount', {
+ personId: this.id,
+ usage_type: usage_type
+ });
+ _checkError(result);
};
diff --git a/src/content/js/common.js b/src/content/js/common.js
index e60816bb..4c55df55 100755
--- a/src/content/js/common.js
+++ b/src/content/js/common.js
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var utils_ = xwalk.utils;
var type_ = utils_.type;
var converter_ = utils_.converter;
@@ -22,15 +22,15 @@ var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
var EditManager = function() {
- this.isAllowed = false;
+ this.isAllowed = false;
};
EditManager.prototype.allow = function() {
- this.isAllowed = true;
+ this.isAllowed = true;
};
EditManager.prototype.disallow = function() {
- this.isAllowed = false;
+ this.isAllowed = false;
};
var edit_ = new EditManager();
@@ -38,45 +38,48 @@ var edit_ = new EditManager();
var SCHEMA = 'file://';
function createContentObject_(data) {
- var content;
- switch (data.type) {
+ var content;
+ switch (data.type) {
case ContentType.IMAGE:
- content = new ImageContent(data);
- break;
+ content = new ImageContent(data);
+ break;
case ContentType.AUDIO:
content = new AudioContent(data);
- break;
+ break;
case ContentType.VIDEO:
- content = new VideoContent(data);
- break;
+ content = new VideoContent(data);
+ break;
case ContentType.OTHER:
- content = new Content(data);
- break;
+ content = new Content(data);
+ break;
default:
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'Undefined content type');
- }
- // below constructor overwriting is needed because of backward compatibility
- var object = {};
- content.constructor = object.constructor;
- return content;
+ throw new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Undefined content type'
+ );
+ }
+ // below constructor overwriting is needed because of backward compatibility
+ var object = {};
+ content.constructor = object.constructor;
+ return content;
}
function createContentDirObject_(data) {
- return new ContentDirectory(data);
+ return new ContentDirectory(data);
}
function convertUriToPath_(uri) {
- if (0 === uri.indexOf(SCHEMA)) {
- return uri.substring(SCHEMA.length);
- }
+ if (0 === uri.indexOf(SCHEMA)) {
+ return uri.substring(SCHEMA.length);
+ }
- return uri;
+ return uri;
}
function convertPathToUri_(path) {
- if (0 === path.indexOf(SCHEMA)) {
- return path;
- }
+ if (0 === path.indexOf(SCHEMA)) {
+ return path;
+ }
- return SCHEMA + path;
+ return SCHEMA + path;
}
diff --git a/src/content/js/datatypes.js b/src/content/js/datatypes.js
index 1a0bae85..9ddfd0dd 100755
--- a/src/content/js/datatypes.js
+++ b/src/content/js/datatypes.js
@@ -15,697 +15,703 @@
*/
var ContentDirectoryStorageType = {
- INTERNAL: 'INTERNAL',
- EXTERNAL: 'EXTERNAL'
+ INTERNAL: 'INTERNAL',
+ EXTERNAL: 'EXTERNAL'
};
var ContentType = {
- IMAGE: 'IMAGE',
- VIDEO: 'VIDEO',
- AUDIO: 'AUDIO',
- OTHER: 'OTHER'
+ IMAGE: 'IMAGE',
+ VIDEO: 'VIDEO',
+ AUDIO: 'AUDIO',
+ OTHER: 'OTHER'
};
var AudioContentLyricsType = {
- SYNCHRONIZED: 'SYNCHRONIZED',
- UNSYNCHRONIZED: 'UNSYNCHRONIZED'
+ SYNCHRONIZED: 'SYNCHRONIZED',
+ UNSYNCHRONIZED: 'UNSYNCHRONIZED'
};
var ImageContentOrientation = {
- NORMAL: 'NORMAL',
- FLIP_HORIZONTAL: 'FLIP_HORIZONTAL',
- ROTATE_180: 'ROTATE_180',
- FLIP_VERTICAL: 'FLIP_VERTICAL',
- TRANSPOSE: 'TRANSPOSE',
- ROTATE_90: 'ROTATE_90',
- TRANSVERSE: 'TRANSVERSE',
- ROTATE_270: 'ROTATE_270'
+ NORMAL: 'NORMAL',
+ FLIP_HORIZONTAL: 'FLIP_HORIZONTAL',
+ ROTATE_180: 'ROTATE_180',
+ FLIP_VERTICAL: 'FLIP_VERTICAL',
+ TRANSPOSE: 'TRANSPOSE',
+ ROTATE_90: 'ROTATE_90',
+ TRANSVERSE: 'TRANSVERSE',
+ ROTATE_270: 'ROTATE_270'
};
function ContentDirectory(data) {
- var id;
- var directoryURI;
- var title;
- var storageType;
- var modifiedDate = null;
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return id;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- id = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- directoryURI: {
- get: function() {
- return directoryURI;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- directoryURI = convertPathToUri_(converter_.toString(v, false));
- }
- },
- enumerable: true
- },
- title: {
- get: function() {
- return title;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- title = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- storageType: {
- get: function() {
- return storageType;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- storageType = converter_.toEnum(v, Object.keys(ContentDirectoryStorageType), false);
- }
- },
- enumerable: true
- },
- modifiedDate: {
- get: function() {
- return modifiedDate;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- modifiedDate = v > 0 ? new Date(v * 1000) : null;
- }
- },
- enumerable: true
- }
- });
-
- if (type_.isObject(data)) {
- // fill object with data
- edit_.allow();
- for (var key in data) {
- if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
- this[key] = data[key];
- }
+ var id;
+ var directoryURI;
+ var title;
+ var storageType;
+ var modifiedDate = null;
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return id;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ id = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ directoryURI: {
+ get: function() {
+ return directoryURI;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ directoryURI = convertPathToUri_(converter_.toString(v, false));
+ }
+ },
+ enumerable: true
+ },
+ title: {
+ get: function() {
+ return title;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ title = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ storageType: {
+ get: function() {
+ return storageType;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ storageType = converter_.toEnum(
+ v,
+ Object.keys(ContentDirectoryStorageType),
+ false
+ );
+ }
+ },
+ enumerable: true
+ },
+ modifiedDate: {
+ get: function() {
+ return modifiedDate;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ modifiedDate = v > 0 ? new Date(v * 1000) : null;
+ }
+ },
+ enumerable: true
+ }
+ });
+
+ if (type_.isObject(data)) {
+ // fill object with data
+ edit_.allow();
+ for (var key in data) {
+ if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
+ this[key] = data[key];
+ }
+ }
+ edit_.disallow();
}
- edit_.disallow();
- }
}
-
function Content(data) {
- var editableAttributes = ['name', 'rating', 'description', 'isFavorite'];
- var id;
- var name;
- var type;
- var mimeType;
- var title;
- var contentURI;
- var thumbnailURIs = null;
- var releaseDate = null;
- var modifiedDate = null;
- var size;
- var description = null;
- var rating;
- var isFavorite;
-
- Object.defineProperties(this, {
- editableAttributes: {
- value: editableAttributes,
- writable: false,
- enumerable: true
- },
- id: {
- get: function() {
- return id;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- id = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- name: {
- get: function() {
- return name;
- },
- set: function(v) {
- if (!type_.isNull(v)) {
- name = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- type: {
- get: function() {
- return type;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- type = converter_.toEnum(v, Object.keys(ContentType), false);
- }
- },
- enumerable: true
- },
- mimeType: {
- get: function() {
- return mimeType;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- mimeType = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- title: {
- get: function() {
- return title;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- title = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- contentURI: {
- get: function() {
- return contentURI;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- contentURI = convertPathToUri_(v);
- }
- },
- enumerable: true
- },
- thumbnailURIs: {
- get: function() {
- return thumbnailURIs;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- thumbnailURIs = converter_.toArray(v, true);
- }
- },
- enumerable: true
- },
- releaseDate: {
- get: function() {
- return releaseDate;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- releaseDate = v > 0 ? new Date(v * 1000) : null;
- }
- },
- enumerable: true
- },
- modifiedDate: {
- get: function() {
- return modifiedDate;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- modifiedDate = v > 0 ? new Date(v * 1000) : null;
- }
- },
- enumerable: true
- },
- size: {
- get: function() {
- return size;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- size = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- description: {
- get: function() {
- return description;
- },
- set: function(v) {
- description = converter_.toString(v, true);
- },
- enumerable: true
- },
- rating: {
- get: function() {
- return rating;
- },
- set: function(v) {
- if (!type_.isNull(v) && v >= 0 && v <= 10) {
- rating = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- isFavorite: {
- get: function() {
- return isFavorite;
- },
- set: function(v) {
- if (!type_.isNull(v)) {
- isFavorite = converter_.toBoolean(v, false);
- }
- },
- enumerable: true
- }
- });
-
- if (type_.isObject(data)) {
- // fill object with data
- edit_.allow();
- for (var key in data) {
- if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
- this[key] = data[key];
- }
+ var editableAttributes = ['name', 'rating', 'description', 'isFavorite'];
+ var id;
+ var name;
+ var type;
+ var mimeType;
+ var title;
+ var contentURI;
+ var thumbnailURIs = null;
+ var releaseDate = null;
+ var modifiedDate = null;
+ var size;
+ var description = null;
+ var rating;
+ var isFavorite;
+
+ Object.defineProperties(this, {
+ editableAttributes: {
+ value: editableAttributes,
+ writable: false,
+ enumerable: true
+ },
+ id: {
+ get: function() {
+ return id;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ id = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ name: {
+ get: function() {
+ return name;
+ },
+ set: function(v) {
+ if (!type_.isNull(v)) {
+ name = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ type: {
+ get: function() {
+ return type;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ type = converter_.toEnum(v, Object.keys(ContentType), false);
+ }
+ },
+ enumerable: true
+ },
+ mimeType: {
+ get: function() {
+ return mimeType;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ mimeType = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ title: {
+ get: function() {
+ return title;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ title = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ contentURI: {
+ get: function() {
+ return contentURI;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ contentURI = convertPathToUri_(v);
+ }
+ },
+ enumerable: true
+ },
+ thumbnailURIs: {
+ get: function() {
+ return thumbnailURIs;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ thumbnailURIs = converter_.toArray(v, true);
+ }
+ },
+ enumerable: true
+ },
+ releaseDate: {
+ get: function() {
+ return releaseDate;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ releaseDate = v > 0 ? new Date(v * 1000) : null;
+ }
+ },
+ enumerable: true
+ },
+ modifiedDate: {
+ get: function() {
+ return modifiedDate;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ modifiedDate = v > 0 ? new Date(v * 1000) : null;
+ }
+ },
+ enumerable: true
+ },
+ size: {
+ get: function() {
+ return size;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ size = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ description: {
+ get: function() {
+ return description;
+ },
+ set: function(v) {
+ description = converter_.toString(v, true);
+ },
+ enumerable: true
+ },
+ rating: {
+ get: function() {
+ return rating;
+ },
+ set: function(v) {
+ if (!type_.isNull(v) && v >= 0 && v <= 10) {
+ rating = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ isFavorite: {
+ get: function() {
+ return isFavorite;
+ },
+ set: function(v) {
+ if (!type_.isNull(v)) {
+ isFavorite = converter_.toBoolean(v, false);
+ }
+ },
+ enumerable: true
+ }
+ });
+
+ if (type_.isObject(data)) {
+ // fill object with data
+ edit_.allow();
+ for (var key in data) {
+ if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
+ this[key] = data[key];
+ }
+ }
+ edit_.disallow();
}
- edit_.disallow();
- }
}
-
function VideoContent(data) {
- Content.call(this, data);
+ Content.call(this, data);
- var editableAttributes = this.editableAttributes;
- editableAttributes.push('geolocation');
+ var editableAttributes = this.editableAttributes;
+ editableAttributes.push('geolocation');
- var geolocation;
- var album;
- var artists;
- var duration;
- var width;
- var height;
+ var geolocation;
+ var album;
+ var artists;
+ var duration;
+ var width;
+ var height;
Object.defineProperties(this, {
- editableAttributes: {
- value: editableAttributes,
- writable: false,
- enumerable: true
- },
- geolocation: {
- get: function() {
- return geolocation;
- },
- set: function(v) {
- if (!type_.isNull(v)) {
- var latitude = converter_.toDouble(v.latitude, false);
- var longitude = converter_.toDouble(v.longitude, false);
- geolocation = new tizen.SimpleCoordinates(latitude, longitude);
- }
- },
- enumerable: true
- },
- album: {
- get: function() {
- return album;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- album = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- artists: {
- get: function() {
- return artists;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- artists = converter_.toArray(v, true);
- }
- },
- enumerable: true
- },
- duration: {
- get: function() {
- return duration;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- duration = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- width: {
- get: function() {
- return width;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- width = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- height: {
- get: function() {
- return height;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- height = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- }
- });
-
- if (type_.isObject(data)) {
- // fill object with data
- edit_.allow();
- for (var key in data) {
- if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
- this[key] = data[key];
- }
+ editableAttributes: {
+ value: editableAttributes,
+ writable: false,
+ enumerable: true
+ },
+ geolocation: {
+ get: function() {
+ return geolocation;
+ },
+ set: function(v) {
+ if (!type_.isNull(v)) {
+ var latitude = converter_.toDouble(v.latitude, false);
+ var longitude = converter_.toDouble(v.longitude, false);
+ geolocation = new tizen.SimpleCoordinates(latitude, longitude);
+ }
+ },
+ enumerable: true
+ },
+ album: {
+ get: function() {
+ return album;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ album = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ artists: {
+ get: function() {
+ return artists;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ artists = converter_.toArray(v, true);
+ }
+ },
+ enumerable: true
+ },
+ duration: {
+ get: function() {
+ return duration;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ duration = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ width: {
+ get: function() {
+ return width;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ width = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ height: {
+ get: function() {
+ return height;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ height = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ }
+ });
+
+ if (type_.isObject(data)) {
+ // fill object with data
+ edit_.allow();
+ for (var key in data) {
+ if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
+ this[key] = data[key];
+ }
+ }
+ edit_.disallow();
}
- edit_.disallow();
- }
}
VideoContent.prototype = new Content();
VideoContent.prototype.constructor = VideoContent;
-
function AudioContentLyrics(data) {
- var type;
- var timestamps;
- var texts;
-
- Object.defineProperties(this, {
- type: {
- get: function() {
- return type;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- type = converter_.toEnum(v, Object.keys(AudioContentLyricsType), false);
- }
- },
- enumerable: true
- },
- timestamps: {
- get: function() {
- return timestamps;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- timestamps = converter_.toArray(v, true);
- }
- },
- enumerable: true
- },
- texts: {
- get: function() {
- return texts;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- texts = converter_.toArray(v, false);
- }
- },
- enumerable: true
- }
- });
-
- if (type_.isObject(data)) {
- // fill object with data
- edit_.allow();
- for (var key in data) {
- if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
- this[key] = data[key];
- }
+ var type;
+ var timestamps;
+ var texts;
+
+ Object.defineProperties(this, {
+ type: {
+ get: function() {
+ return type;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ type = converter_.toEnum(
+ v,
+ Object.keys(AudioContentLyricsType),
+ false
+ );
+ }
+ },
+ enumerable: true
+ },
+ timestamps: {
+ get: function() {
+ return timestamps;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ timestamps = converter_.toArray(v, true);
+ }
+ },
+ enumerable: true
+ },
+ texts: {
+ get: function() {
+ return texts;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ texts = converter_.toArray(v, false);
+ }
+ },
+ enumerable: true
+ }
+ });
+
+ if (type_.isObject(data)) {
+ // fill object with data
+ edit_.allow();
+ for (var key in data) {
+ if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
+ this[key] = data[key];
+ }
+ }
+ edit_.disallow();
}
- edit_.disallow();
- }
}
-
function AudioContent(data) {
- Content.call(this, data);
-
- var album;
- var genres;
- var artists;
- var composers;
- var lyrics;
- var copyright;
- var bitrate;
- var trackNumber;
- var duration;
-
- var getLyrics = function() {
- var data = {
- contentURI: convertUriToPath_(this.contentURI)
- };
-
- var result = native_.callSync('ContentManager_getLyrics', data);
-
- if (native_.isFailure(result)) {
- utils_.log('Getting lyrics failed for ' + data.contentURI);
- var error_object = native_.getErrorObject(result);
- if (WebAPIException.SECURITY_ERR == error_object.code) {
- throw error_object;
- }
- return;
- }
+ Content.call(this, data);
- return new AudioContentLyrics(native_.getResultObject(result));
- }.bind(this);
-
- Object.defineProperties(this, {
- album: {
- get: function() {
- return album;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- album = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- genres: {
- get: function() {
- return genres;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- genres = converter_.toArray(v, true);
- }
- },
- enumerable: true
- },
- artists: {
- get: function() {
- return artists;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- artists = converter_.toArray(v, true);
- }
- },
- enumerable: true
- },
- composers: {
- get: function() {
- return composers;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- composers = converter_.toArray(v, true);
- }
- },
- enumerable: true
- },
- lyrics: {
- get: function() {
- if (lyrics === undefined) {
- lyrics = getLyrics();
- }
- return lyrics;
- },
- set: function(v) {
- if (edit_.isAllowed && type_.isObject(v)) {
- lyrics = new AudioContentLyrics(v);
- }
- },
- enumerable: true
- },
- copyright: {
- get: function() {
- return copyright;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- copyright = converter_.toString(v, false);
- }
- },
- enumerable: true
- },
- bitrate: {
- get: function() {
- return bitrate;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- bitrate = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- trackNumber: {
- get: function() {
- return trackNumber;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- trackNumber = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- duration: {
- get: function() {
- return duration;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- duration = converter_.toUnsignedLong(v, false);
+ var album;
+ var genres;
+ var artists;
+ var composers;
+ var lyrics;
+ var copyright;
+ var bitrate;
+ var trackNumber;
+ var duration;
+
+ var getLyrics = function() {
+ var data = {
+ contentURI: convertUriToPath_(this.contentURI)
+ };
+
+ var result = native_.callSync('ContentManager_getLyrics', data);
+
+ if (native_.isFailure(result)) {
+ utils_.log('Getting lyrics failed for ' + data.contentURI);
+ var error_object = native_.getErrorObject(result);
+ if (WebAPIException.SECURITY_ERR == error_object.code) {
+ throw error_object;
+ }
+ return;
}
- },
- enumerable: true
- }
- });
-
- if (type_.isObject(data)) {
- // fill object with data
- edit_.allow();
- for (var key in data) {
- if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
- this[key] = data[key];
- }
+
+ return new AudioContentLyrics(native_.getResultObject(result));
+ }.bind(this);
+
+ Object.defineProperties(this, {
+ album: {
+ get: function() {
+ return album;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ album = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ genres: {
+ get: function() {
+ return genres;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ genres = converter_.toArray(v, true);
+ }
+ },
+ enumerable: true
+ },
+ artists: {
+ get: function() {
+ return artists;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ artists = converter_.toArray(v, true);
+ }
+ },
+ enumerable: true
+ },
+ composers: {
+ get: function() {
+ return composers;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ composers = converter_.toArray(v, true);
+ }
+ },
+ enumerable: true
+ },
+ lyrics: {
+ get: function() {
+ if (lyrics === undefined) {
+ lyrics = getLyrics();
+ }
+ return lyrics;
+ },
+ set: function(v) {
+ if (edit_.isAllowed && type_.isObject(v)) {
+ lyrics = new AudioContentLyrics(v);
+ }
+ },
+ enumerable: true
+ },
+ copyright: {
+ get: function() {
+ return copyright;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ copyright = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ bitrate: {
+ get: function() {
+ return bitrate;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ bitrate = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ trackNumber: {
+ get: function() {
+ return trackNumber;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ trackNumber = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ duration: {
+ get: function() {
+ return duration;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ duration = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ }
+ });
+
+ if (type_.isObject(data)) {
+ // fill object with data
+ edit_.allow();
+ for (var key in data) {
+ if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
+ this[key] = data[key];
+ }
+ }
+ edit_.disallow();
}
- edit_.disallow();
- }
}
AudioContent.prototype = new Content();
AudioContent.prototype.constructor = AudioContent;
-
function ImageContent(data) {
- Content.call(this, data);
-
- var editableAttributes = this.editableAttributes;
- editableAttributes.push('geolocation');
- editableAttributes.push('orientation');
-
- var geolocation;
- var width;
- var height;
- var orientation;
-
- Object.defineProperties(this, {
- editableAttributes: {
- value: editableAttributes,
- writable: false,
- enumerable: true
- },
- geolocation: {
- get: function() {
- return geolocation;
- },
- set: function(v) {
- if (!type_.isNull(v)) {
- var latitude = converter_.toDouble(v.latitude, false);
- var longitude = converter_.toDouble(v.longitude, false);
- geolocation = new tizen.SimpleCoordinates(latitude, longitude);
- }
- },
- enumerable: true
- },
- width: {
- get: function() {
- return width;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- width = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- height: {
- get: function() {
- return height;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- height = converter_.toUnsignedLong(v, false);
- }
- },
- enumerable: true
- },
- orientation: {
- get: function() {
- return orientation;
- },
- set: function(v) {
- if (!type_.isNull(v)) {
- orientation = converter_.toEnum(v, Object.keys(ImageContentOrientation), false);
- }
- },
- enumerable: true
- }
- });
-
- if (type_.isObject(data)) {
- // fill object with data
- edit_.allow();
- for (var key in data) {
- if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
- this[key] = data[key];
- }
+ Content.call(this, data);
+
+ var editableAttributes = this.editableAttributes;
+ editableAttributes.push('geolocation');
+ editableAttributes.push('orientation');
+
+ var geolocation;
+ var width;
+ var height;
+ var orientation;
+
+ Object.defineProperties(this, {
+ editableAttributes: {
+ value: editableAttributes,
+ writable: false,
+ enumerable: true
+ },
+ geolocation: {
+ get: function() {
+ return geolocation;
+ },
+ set: function(v) {
+ if (!type_.isNull(v)) {
+ var latitude = converter_.toDouble(v.latitude, false);
+ var longitude = converter_.toDouble(v.longitude, false);
+ geolocation = new tizen.SimpleCoordinates(latitude, longitude);
+ }
+ },
+ enumerable: true
+ },
+ width: {
+ get: function() {
+ return width;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ width = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ height: {
+ get: function() {
+ return height;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ height = converter_.toUnsignedLong(v, false);
+ }
+ },
+ enumerable: true
+ },
+ orientation: {
+ get: function() {
+ return orientation;
+ },
+ set: function(v) {
+ if (!type_.isNull(v)) {
+ orientation = converter_.toEnum(
+ v,
+ Object.keys(ImageContentOrientation),
+ false
+ );
+ }
+ },
+ enumerable: true
+ }
+ });
+
+ if (type_.isObject(data)) {
+ // fill object with data
+ edit_.allow();
+ for (var key in data) {
+ if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
+ this[key] = data[key];
+ }
+ }
+ edit_.disallow();
}
- edit_.disallow();
- }
}
ImageContent.prototype = new Content();
ImageContent.prototype.constructor = ImageContent;
-
function PlaylistItem(data) {
- var content = data;
-
- Object.defineProperties(this, {
- content: {
- get: function() {
- return content;
- },
- set: function(v) {
- if (edit_.isAllowed && v instanceof Content) {
- content = v;
- }
- },
- enumerable: true
- }
- });
+ var content = data;
+
+ Object.defineProperties(this, {
+ content: {
+ get: function() {
+ return content;
+ },
+ set: function(v) {
+ if (edit_.isAllowed && v instanceof Content) {
+ content = v;
+ }
+ },
+ enumerable: true
+ }
+ });
}
diff --git a/src/content/js/manager.js b/src/content/js/manager.js
index db388dc6..3c585458 100755
--- a/src/content/js/manager.js
+++ b/src/content/js/manager.js
@@ -18,487 +18,597 @@ var T_ = xwalk.utils.type;
var privUtils_ = xwalk.utils;
var CONTENT_MANAGER_LISTENER_ID = 'ContentManagerChangeCallback';
-
function _ContentManagerChangeCallback(result) {
- if (result.state === 'oncontentadded' || result.state === 'oncontentupdated') {
- var content = native_.getResultObject(result);
- native_.callIfPossible(this[result.state], createContentObject_(content));
- } else if (result.state === 'oncontentdiradded' || result.state === 'oncontentdirupdated') {
- var contentDir = native_.getResultObject(result);
- native_.callIfPossible(this[result.state], createContentDirObject_(contentDir));
- } else if (result.state === 'oncontentremoved' || result.state === 'oncontentdirremoved') {
- native_.callIfPossible(this[result.state], native_.getResultObject(result));
- }
+ if (result.state === 'oncontentadded' || result.state === 'oncontentupdated') {
+ var content = native_.getResultObject(result);
+ native_.callIfPossible(this[result.state], createContentObject_(content));
+ } else if (
+ result.state === 'oncontentdiradded' ||
+ result.state === 'oncontentdirupdated'
+ ) {
+ var contentDir = native_.getResultObject(result);
+ native_.callIfPossible(this[result.state], createContentDirObject_(contentDir));
+ } else if (
+ result.state === 'oncontentremoved' ||
+ result.state === 'oncontentdirremoved'
+ ) {
+ native_.callIfPossible(this[result.state], native_.getResultObject(result));
+ }
}
-
var ContentListenersManager = (function() {
+ function changeContent(event) {
+ if (T_.isEmptyObject(this.listeners)) {
+ return;
+ }
- function changeContent(event) {
- if (T_.isEmptyObject(this.listeners)) {
- return;
- }
+ var result = null;
+
+ if (event.state === 'oncontentadded' || event.state === 'oncontentupdated') {
+ result = createContentObject_(native_.getResultObject(event));
+ } else if (
+ event.state === 'oncontentdiradded' ||
+ event.state === 'oncontentdirupdated'
+ ) {
+ result = createContentDirObject_(native_.getResultObject(event));
+ } else if (
+ event.state === 'oncontentremoved' ||
+ event.state === 'oncontentdirremoved'
+ ) {
+ result = native_.getResultObject(event);
+ }
- var result = null;
+ if (!result) {
+ return;
+ }
- if (event.state === 'oncontentadded' || event.state === 'oncontentupdated') {
- result = createContentObject_(native_.getResultObject(event));
- } else if (event.state === 'oncontentdiradded' || event.state === 'oncontentdirupdated') {
- result = createContentDirObject_(native_.getResultObject(event));
- } else if (event.state === 'oncontentremoved' || event.state === 'oncontentdirremoved') {
- result = native_.getResultObject(event);
+ var callback;
+ for (var listenerId in this.listeners) {
+ if (this.listeners.hasOwnProperty(listenerId)) {
+ callback = this.listeners[listenerId];
+ if (T_.isFunction(callback[event.state])) {
+ callback[event.state](result);
+ }
+ }
+ }
}
- if (!result) {
- return;
+ function _ContentListenersManager() {
+ this.listeners = {};
+ this.lastListenerId = 0;
+ this.changeContent = changeContent.bind(this);
}
- var callback;
- for (var listenerId in this.listeners) {
- if (this.listeners.hasOwnProperty(listenerId)) {
- callback = this.listeners[listenerId];
- if (T_.isFunction(callback[event.state])) {
- callback[event.state](result);
- }
- }
- }
- }
-
- function _ContentListenersManager() {
- this.listeners = {};
- this.lastListenerId = 0;
- this.changeContent = changeContent.bind(this);
- }
-
- _ContentListenersManager.prototype.addChangeListener = function(changeCallback) {
- if (T_.isEmptyObject(this.listeners)) {
- var result = native_.callSync('ContentManager_addChangeListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ _ContentListenersManager.prototype.addChangeListener = function(changeCallback) {
+ if (T_.isEmptyObject(this.listeners)) {
+ var result = native_.callSync('ContentManager_addChangeListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- native_.addListener(CONTENT_MANAGER_LISTENER_ID, this.changeContent);
- }
+ native_.addListener(CONTENT_MANAGER_LISTENER_ID, this.changeContent);
+ }
- this.listeners[++this.lastListenerId] = changeCallback;
- return this.lastListenerId;
- };
+ this.listeners[++this.lastListenerId] = changeCallback;
+ return this.lastListenerId;
+ };
- _ContentListenersManager.prototype.removeChangeListener = function(listenerId) {
- delete this.listeners[listenerId];
+ _ContentListenersManager.prototype.removeChangeListener = function(listenerId) {
+ delete this.listeners[listenerId];
- if (T_.isEmptyObject(this.listeners)) {
- var result = native_.callSync('ContentManager_removeChangeListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (T_.isEmptyObject(this.listeners)) {
+ var result = native_.callSync('ContentManager_removeChangeListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- native_.removeListener(CONTENT_MANAGER_LISTENER_ID);
- }
- };
+ native_.removeListener(CONTENT_MANAGER_LISTENER_ID);
+ }
+ };
- return _ContentListenersManager;
+ return _ContentListenersManager;
})();
var listenersManager = new ContentListenersManager();
-
-function ContentManager() {
-}
+function ContentManager() {}
var ContentManagerUpdate = function(content) {
- var args = validator_.validateArgs(arguments, [
- {name: 'content', type: types_.PLATFORM_OBJECT, values: Content}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'content', type: types_.PLATFORM_OBJECT, values: Content }
+ ]);
- var data = {
- content: args.content
- };
+ var data = {
+ content: args.content
+ };
- var result = native_.callSync('ContentManager_update', data);
+ var result = native_.callSync('ContentManager_update', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
ContentManager.prototype.update = function() {
- ContentManagerUpdate.apply(this, arguments);
+ ContentManagerUpdate.apply(this, arguments);
};
-ContentManager.prototype.updateBatch = function(contents, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'contents', type: types_.ARRAY, values: Content},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ContentManager.prototype.updateBatch = function(
+ contents,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'contents', type: types_.ARRAY, values: Content },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = {
+ contents: args.contents
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
- var data = {
- contents: args.contents
- };
+ var result = native_.call('ContentManager_updateBatch', data, callback);
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback);
- };
-
- var result = native_.call('ContentManager_updateBatch', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
ContentManager.prototype.getDirectories = function(successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+
+ var out = [];
+ result = native_.getResultObject(result);
+ for (var i = 0, max = result.length; i < max; i++) {
+ out.push(new ContentDirectory(result[i]));
+ }
+ native_.callIfPossible(args.successCallback, out);
+ };
+
+ var result = native_.call('ContentManager_getDirectories', null, callback);
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
+};
- var out = [];
- result = native_.getResultObject(result);
- for (var i = 0, max = result.length; i < max; i++) {
- out.push(new ContentDirectory(result[i]));
- }
- native_.callIfPossible(args.successCallback, out);
- };
+ContentManager.prototype.find = function(
+ successCallback,
+ errorCallback,
+ directoryId,
+ filter,
+ sortMode,
+ count,
+ offset
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'directoryId', type: types_.STRING, optional: true, nullable: true },
+ {
+ name: 'filter',
+ type: types_.PLATFORM_OBJECT,
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ],
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'sortMode',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.SortMode,
+ optional: true,
+ nullable: true
+ },
+ { name: 'count', type: types_.UNSIGNED_LONG, optional: true, nullable: true },
+ { name: 'offset', type: types_.UNSIGNED_LONG, optional: true, nullable: true }
+ ]);
+
+ var data = {
+ directoryId: args.directoryId,
+ filter: utils_.repackFilter(args.filter),
+ sortMode: args.sortMode,
+ count: args.count,
+ offset: args.offset
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
- var result = native_.call('ContentManager_getDirectories', null, callback);
+ var out = [];
+ result = native_.getResultObject(result);
+ try {
+ for (var i = 0, max = result.length; i < max; i++) {
+ out.push(createContentObject_(result[i]));
+ }
+ } catch (e) {
+ native_.callIfPossible(args.errorCallback, e);
+ return;
+ }
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ native_.callIfPossible(args.successCallback, out);
+ };
+
+ var result = native_.call('ContentManager_find', data, callback);
-ContentManager.prototype.find = function(successCallback, errorCallback, directoryId, filter, sortMode, count, offset) {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'directoryId', type: types_.STRING, optional: true, nullable: true},
- {
- name: 'filter',
- type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter],
- optional: true,
- nullable: true
- },
- {name: 'sortMode', type: types_.PLATFORM_OBJECT, values: tizen.SortMode, optional: true, nullable: true},
- {name: 'count', type: types_.UNSIGNED_LONG, optional: true, nullable: true},
- {name: 'offset', type: types_.UNSIGNED_LONG, optional: true, nullable: true}
- ]);
-
- var data = {
- directoryId: args.directoryId,
- filter: utils_.repackFilter(args.filter),
- sortMode: args.sortMode,
- count: args.count,
- offset: args.offset
- };
-
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
+};
- var out = [];
- result = native_.getResultObject(result);
- try {
- for (var i = 0, max = result.length; i < max; i++) {
- out.push(createContentObject_(result[i]));
- }
- } catch(e) {
- native_.callIfPossible(args.errorCallback, e);
- return;
+ContentManager.prototype.scanFile = function(contentURI, successCallback, errorCallback) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'contentURI', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var path = args.contentURI.trim();
+ if (!path.length) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'File path is not valid.'
+ );
}
- native_.callIfPossible(args.successCallback, out);
- };
+ var data = {
+ contentURI: convertUriToPath_(path)
+ };
- var result = native_.call('ContentManager_find', data, callback);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback, args.contentURI);
+ };
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ var result = native_.call('ContentManager_scanFile', data, callback);
-ContentManager.prototype.scanFile = function(contentURI, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'contentURI', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var path = args.contentURI.trim();
- if (!path.length) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'File path is not valid.');
- }
-
- var data = {
- contentURI: convertUriToPath_(path)
- };
-
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback, args.contentURI);
- };
-
- var result = native_.call('ContentManager_scanFile', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
-ContentManager.prototype.scanDirectory = function(contentDirURI, recursive, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'contentDirURI', type: types_.STRING},
- {name: 'recursive', type: types_.BOOLEAN},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var path = args.contentDirURI.trim();
- if (!path.length) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Directory path is not valid.');
- }
-
- var data = {
- contentDirURI: convertUriToPath_(path),
- recursive: args.recursive
- };
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ContentManager.prototype.scanDirectory = function(
+ contentDirURI,
+ recursive,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'contentDirURI', type: types_.STRING },
+ { name: 'recursive', type: types_.BOOLEAN },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var path = args.contentDirURI.trim();
+ if (!path.length) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Directory path is not valid.'
+ );
}
- native_.callIfPossible(args.successCallback, args.contentDirURI);
- };
- var result = native_.call('ContentManager_scanDirectory', data, callback);
+ var data = {
+ contentDirURI: convertUriToPath_(path),
+ recursive: args.recursive
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback, args.contentDirURI);
+ };
+
+ var result = native_.call('ContentManager_scanDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
ContentManager.prototype.cancelScanDirectory = function(contentDirURI) {
- var args = validator_.validateArgs(arguments, [
- {name: 'contentDirURI', type: types_.STRING}
- ]);
-
- var path = args.contentDirURI.trim();
- if (!path.length) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Directory path is not valid.');
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'contentDirURI', type: types_.STRING }
+ ]);
+
+ var path = args.contentDirURI.trim();
+ if (!path.length) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Directory path is not valid.'
+ );
+ }
- var data = {
- contentDirURI: convertUriToPath_(path)
- };
+ var data = {
+ contentDirURI: convertUriToPath_(path)
+ };
- var result = native_.callSync('ContentManager_cancelScanDirectory', data);
+ var result = native_.callSync('ContentManager_cancelScanDirectory', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
ContentManager.prototype.addChangeListener = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'changeCallback',
- type: types_.LISTENER,
- values: ['oncontentadded', 'oncontentupdated', 'oncontentremoved', 'oncontentdiradded', 'oncontentdirupdated', 'oncontentdirremoved']
- }]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'changeCallback',
+ type: types_.LISTENER,
+ values: [
+ 'oncontentadded',
+ 'oncontentupdated',
+ 'oncontentremoved',
+ 'oncontentdiradded',
+ 'oncontentdirupdated',
+ 'oncontentdirremoved'
+ ]
+ }
+ ]);
- return listenersManager.addChangeListener(args.changeCallback);
+ return listenersManager.addChangeListener(args.changeCallback);
};
ContentManager.prototype.removeChangeListener = function() {
- var args = validator_.validateArgs(arguments, [{
- name: 'listenerId',
- type: types_.LONG
- }]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listenerId',
+ type: types_.LONG
+ }
+ ]);
- listenersManager.removeChangeListener(args.listenerId);
+ listenersManager.removeChangeListener(args.listenerId);
};
ContentManager.prototype.setChangeListener = function(changeCallback) {
- privUtils_.warn('DEPRECATION WARNING: setChangeListener() is deprecated and will be removed '
- + 'from next release. Use addChangeListener() instead.');
-
- var args = validator_.validateArgs(arguments, [{
- name: 'changeCallback',
- type: types_.LISTENER,
- values: ['oncontentadded', 'oncontentupdated', 'oncontentremoved', 'oncontentdiradded', 'oncontentdirupdated', 'oncontentdirremoved']
- }]);
-
- var listenerId = 'ContentManagerChangeCallback_';
-
- var data = {
- listenerId: listenerId
- };
-
- var callbacks = {
- oncontentadded: args.changeCallback.oncontentadded,
- oncontentupdated: args.changeCallback.oncontentupdated,
- oncontentremoved: args.changeCallback.oncontentremoved,
- oncontentdiradded: args.changeCallback.oncontentdiradded,
- oncontentdirupdated: args.changeCallback.oncontentdirupdated,
- oncontentdirremoved: args.changeCallback.oncontentdirremoved
- };
-
- var result = native_.callSync('ContentManager_setChangeListener', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- native_.addListener('ContentManagerChangeCallback_',
- _ContentManagerChangeCallback.bind(callbacks));
+ privUtils_.warn(
+ 'DEPRECATION WARNING: setChangeListener() is deprecated and will be removed ' +
+ 'from next release. Use addChangeListener() instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'changeCallback',
+ type: types_.LISTENER,
+ values: [
+ 'oncontentadded',
+ 'oncontentupdated',
+ 'oncontentremoved',
+ 'oncontentdiradded',
+ 'oncontentdirupdated',
+ 'oncontentdirremoved'
+ ]
+ }
+ ]);
+
+ var listenerId = 'ContentManagerChangeCallback_';
+
+ var data = {
+ listenerId: listenerId
+ };
+
+ var callbacks = {
+ oncontentadded: args.changeCallback.oncontentadded,
+ oncontentupdated: args.changeCallback.oncontentupdated,
+ oncontentremoved: args.changeCallback.oncontentremoved,
+ oncontentdiradded: args.changeCallback.oncontentdiradded,
+ oncontentdirupdated: args.changeCallback.oncontentdirupdated,
+ oncontentdirremoved: args.changeCallback.oncontentdirremoved
+ };
+
+ var result = native_.callSync('ContentManager_setChangeListener', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ native_.addListener(
+ 'ContentManagerChangeCallback_',
+ _ContentManagerChangeCallback.bind(callbacks)
+ );
};
ContentManager.prototype.unsetChangeListener = function() {
- privUtils_.warn('DEPRECATION WARNING: unsetChangeListener() is deprecated and will be removed '
- + 'from next release. Use removeChangeListener() instead.');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: unsetChangeListener() is deprecated and will be removed ' +
+ 'from next release. Use removeChangeListener() instead.'
+ );
- var data = {};
+ var data = {};
- var result = native_.callSync('ContentManager_unsetChangeListener', data);
+ var result = native_.callSync('ContentManager_unsetChangeListener', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- native_.removeListener('ContentManagerChangeCallback_');
+ native_.removeListener('ContentManagerChangeCallback_');
};
ContentManager.prototype.getPlaylists = function(successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = {};
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ var out = [];
+ result = native_.getResultObject(result);
+ for (var i = 0, max = result.length; i < max; i++) {
+ out.push(new Playlist(result[i]));
+ }
+ native_.callIfPossible(args.successCallback, out);
+ };
- var data = {};
+ var result = native_.call('ContentManager_getPlaylists', data, callback);
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- var out = [];
- result = native_.getResultObject(result);
- for (var i = 0, max = result.length; i < max; i++) {
- out.push(new Playlist(result[i]));
+};
+
+ContentManager.prototype.createPlaylist = function(
+ name,
+ successCallback,
+ errorCallback,
+ sourcePlaylist
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'name', type: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ {
+ name: 'sourcePlaylist',
+ type: types_.PLATFORM_OBJECT,
+ values: Playlist,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (
+ !arguments.length ||
+ !type_.isString(arguments[0]) ||
+ (type_.isString(arguments[0]) && !arguments[0].length)
+ ) {
+ setTimeout(function() {
+ args.errorCallback(new WebAPIException(WebAPIException.INVALID_VALUES_ERR));
+ }, 0);
+ return;
}
- native_.callIfPossible(args.successCallback, out);
- };
- var result = native_.call('ContentManager_getPlaylists', data, callback);
+ var data = {
+ name: args.name,
+ sourcePlaylist: args.sourcePlaylist
+ };
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(
+ args.successCallback,
+ new Playlist(native_.getResultObject(result))
+ );
+ };
+
+ var result = native_.call('ContentManager_createPlaylist', data, callback);
-ContentManager.prototype.createPlaylist = function(name, successCallback, errorCallback, sourcePlaylist) {
- var args = validator_.validateArgs(arguments, [
- {name: 'name', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'sourcePlaylist', type: types_.PLATFORM_OBJECT, values: Playlist, optional: true, nullable: true}
- ]);
-
- if (!arguments.length || !type_.isString(arguments[0]) ||
- (type_.isString(arguments[0]) && !arguments[0].length)) {
- setTimeout(function() {
- args.errorCallback(new WebAPIException(WebAPIException.INVALID_VALUES_ERR));
- }, 0);
- return;
- }
-
- var data = {
- name: args.name,
- sourcePlaylist: args.sourcePlaylist
- };
-
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback, new Playlist(native_.getResultObject(result)));
- };
-
- var result = native_.call('ContentManager_createPlaylist', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
ContentManager.prototype.removePlaylist = function(id, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'id', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'id', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = {
+ id: args.id
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
- var data = {
- id: args.id
- };
+ var result = native_.call('ContentManager_removePlaylist', data, callback);
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback);
- };
-
- var result = native_.call('ContentManager_removePlaylist', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
-ContentManager.prototype.createThumbnail = function(content, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'content', type: types_.PLATFORM_OBJECT, values: Content},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ContentManager.prototype.createThumbnail = function(
+ content,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'content', type: types_.PLATFORM_OBJECT, values: Content },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = {
+ id: args.content.id
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ args.successCallback(native_.getResultObject(result));
+ };
- var data = {
- id: args.content.id
- };
+ var result = native_.call('ContentManager_createThumbnail', data, callback);
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- args.successCallback(native_.getResultObject(result));
- };
-
- var result = native_.call('ContentManager_createThumbnail', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
exports = new ContentManager();
diff --git a/src/content/js/playlist.js b/src/content/js/playlist.js
index b3b4a199..14ff1fab 100755
--- a/src/content/js/playlist.js
+++ b/src/content/js/playlist.js
@@ -14,289 +14,322 @@
* limitations under the License.
*/
function Playlist(data) {
- var id;
- var numberOfTracks;
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return id;
- },
- set: function(v) {
- if (edit_.isAllowed) {
- id = converter_.toString(v, false);
+ var id;
+ var numberOfTracks;
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return id;
+ },
+ set: function(v) {
+ if (edit_.isAllowed) {
+ id = converter_.toString(v, false);
+ }
+ },
+ enumerable: true
+ },
+ name: {
+ get: function() {
+ var result = native_.callSync('ContentPlaylist_getName', {
+ id: Number(id)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
+ },
+ set: function(v) {
+ if (!type_.isNull(v)) {
+ var name = converter_.toString(v, false);
+ var result = native_.callSync('ContentPlaylist_setName', {
+ id: Number(id),
+ name: name
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ }
+ },
+ enumerable: true
+ },
+ numberOfTracks: {
+ get: function() {
+ var result = native_.callSync('ContentPlaylist_getNumberOfTracks', {
+ id: Number(id)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
+ },
+ set: function() {},
+ enumerable: true
+ },
+ thumbnailURI: {
+ get: function() {
+ var result = native_.callSync('ContentPlaylist_getThumbnailUri', {
+ id: Number(id)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var res = native_.getResultObject(result);
+ //CoreAPI not support empty thumbnail, so one space must be used instead
+ //null thumbnail
+ return res === ' ' ? null : res;
+ },
+ set: function(v) {
+ var thumbnailURI = converter_.toString(v, true);
+ if (type_.isNullOrUndefined(thumbnailURI)) {
+ //CoreAPI not support empty thumbnail, so one space must be used
+ //instead null thumbnail
+ thumbnailURI = ' ';
+ }
+ //TODO probably thumbnailURI should be converted here to absolute uri
+ //in case of virtual
+ var result = native_.callSync('ContentPlaylist_setThumbnailUri', {
+ id: Number(id),
+ uri: thumbnailURI
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ },
+ enumerable: true
}
- },
- enumerable: true
- },
- name: {
- get: function() {
- var result = native_.callSync('ContentPlaylist_getName', {'id' : Number(id)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
- },
- set: function(v) {
- if (!type_.isNull(v)) {
- var name = converter_.toString(v, false);
- var result = native_.callSync('ContentPlaylist_setName',
- {'id' : Number(id), 'name' : name});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- }
- },
- enumerable: true
- },
- numberOfTracks: {
- get: function() {
- var result = native_.callSync('ContentPlaylist_getNumberOfTracks', {'id' : Number(id)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
- },
- set: function() {},
- enumerable: true
- },
- thumbnailURI: {
- get: function() {
- var result = native_.callSync('ContentPlaylist_getThumbnailUri', {'id' : Number(id)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ });
+
+ if (type_.isObject(data)) {
+ // fill object with data
+ edit_.allow();
+ for (var key in data) {
+ if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
+ this[key] = data[key];
+ }
}
- var res = native_.getResultObject(result);
- //CoreAPI not support empty thumbnail, so one space must be used instead null thumbnail
- return res === " " ? null : res;
- },
- set: function(v) {
- var thumbnailURI = converter_.toString(v, true);
- if (type_.isNullOrUndefined(thumbnailURI)) {
- //CoreAPI not support empty thumbnail, so one space must be used instead null thumbnail
- thumbnailURI = " ";
- }
- //TODO probably thumbnailURI should be converted here to absolute uri in case of virtual
- var result = native_.callSync('ContentPlaylist_setThumbnailUri',
- {'id' : Number(id), 'uri' : thumbnailURI});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- },
- enumerable: true
- },
- });
-
- if (type_.isObject(data)) {
- // fill object with data
- edit_.allow();
- for (var key in data) {
- if (data.hasOwnProperty(key) && this.hasOwnProperty(key)) {
- this[key] = data[key];
- }
+ edit_.disallow();
}
- edit_.disallow();
- }
}
-Playlist.prototype.add = function (item) {
- var args = validator_.validateArgs(arguments, [
- {name: 'item', type: types_.PLATFORM_OBJECT, values: Content}
- ]);
+Playlist.prototype.add = function(item) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'item', type: types_.PLATFORM_OBJECT, values: Content }
+ ]);
- var data = {
- contentId: args.item.id,
- playlistId: this.id,
- };
+ var data = {
+ contentId: args.item.id,
+ playlistId: this.id
+ };
- var result = native_.callSync('ContentPlaylist_add', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('ContentPlaylist_add', data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
-Playlist.prototype.addBatch = function (items, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'items', type: types_.ARRAY, values: Content},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+Playlist.prototype.addBatch = function(items, successCallback, errorCallback) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'items', type: types_.ARRAY, values: Content },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = {
+ playlistId: this.id,
+ contents: args.items
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
- var data = {
- playlistId: this.id,
- contents: args.items
- };
+ var result = native_.call('ContentPlaylist_addBatch', data, callback);
- var callback = function (result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback);
- };
-
- var result = native_.call('ContentPlaylist_addBatch', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
-Playlist.prototype.remove = function (item) {
- var args = validator_.validateArgs(arguments, [
- {name: 'item', type: types_.PLATFORM_OBJECT, values: PlaylistItem}
- ]);
+Playlist.prototype.remove = function(item) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'item', type: types_.PLATFORM_OBJECT, values: PlaylistItem }
+ ]);
- var data = {
- playlistId: this.id,
- memberId: args.item.content.memberId
- };
- var result = native_.callSync('ContentPlaylist_remove', data);
+ var data = {
+ playlistId: this.id,
+ memberId: args.item.content.memberId
+ };
+ var result = native_.callSync('ContentPlaylist_remove', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
-Playlist.prototype.removeBatch = function (items, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'items', type: types_.ARRAY, values: PlaylistItem},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+Playlist.prototype.removeBatch = function(items, successCallback, errorCallback) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'items', type: types_.ARRAY, values: PlaylistItem },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var members = [];
+ for (var i = 0; i < args.items.length; i++) {
+ members.push(args.items[i].content.memberId);
+ }
- var members = [];
- for (var i = 0; i < args.items.length; i++) {
- members.push(args.items[i].content.memberId);
- }
+ var data = {
+ playlistId: this.id,
+ members: members
+ };
- var data = {
- playlistId: this.id,
- members: members
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var result = native_.call('ContentPlaylist_removeBatch', data, callback);
- var callback = function (result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback);
- };
+};
- var result = native_.call('ContentPlaylist_removeBatch', data, callback);
+Playlist.prototype.get = function(successCallback, errorCallback, count, offset) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'count', type: types_.LONG, optional: true },
+ { name: 'offset', type: types_.LONG, optional: true }
+ ]);
+
+ if (args.offset < 0 || args.count < 0) {
+ setTimeout(function() {
+ args.errorCallback(new WebAPIException(WebAPIException.INVALID_VALUES_ERR));
+ }, 0);
+ return;
+ }
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ var data = {
+ playlistId: this.id,
+ count: type_.isNullOrUndefined(args.count) ? -1 : args.count,
+ offset: type_.isNullOrUndefined(args.offset) ? -1 : args.offset
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ result = native_.getResultObject(result);
+ var out = [];
+ for (var i = 0, max = result.length; i < max; i++) {
+ var itemToPush = createContentObject_(result[i]);
+ itemToPush['memberId'] = result[i]['playlist_member_id'];
+ out.push(new PlaylistItem(itemToPush));
+ }
+ native_.callIfPossible(args.successCallback, out);
+ };
+
+ var result = native_.call('ContentPlaylist_get', data, callback);
-Playlist.prototype.get = function (successCallback, errorCallback, count, offset) {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'count', type: types_.LONG, optional: true},
- {name: 'offset', type: types_.LONG, optional: true}
- ]);
-
- if (args.offset < 0 || args.count < 0) {
- setTimeout(function() {
- args.errorCallback(new WebAPIException(WebAPIException.INVALID_VALUES_ERR));
- }, 0);
- return;
- }
-
- var data = {
- playlistId: this.id,
- count: type_.isNullOrUndefined(args.count) ? -1 : args.count,
- offset: type_.isNullOrUndefined(args.offset) ? -1 : args.offset
- };
-
- var callback = function (result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- result = native_.getResultObject(result);
- var out = [];
- for (var i = 0, max = result.length; i < max; i++) {
- var itemToPush = createContentObject_(result[i]);
- itemToPush['memberId'] = result[i]['playlist_member_id'];
- out.push(new PlaylistItem(itemToPush));
+};
+
+Playlist.prototype.setOrder = function(items, successCallback, errorCallback) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'items', type: types_.ARRAY, values: PlaylistItem },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (!args.items.length) {
+ setTimeout(function() {
+ args.errorCallback(new WebAPIException(WebAPIException.INVALID_VALUES_ERR));
+ }, 0);
+ return;
}
- native_.callIfPossible(args.successCallback, out);
- };
- var result = native_.call('ContentPlaylist_get', data, callback);
+ var members = [];
+ for (var i = 0; i < args.items.length; i++) {
+ members.push(args.items[i].content.memberId);
+ }
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ var data = {
+ playlistId: this.id,
+ members: members
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var result = native_.call('ContentPlaylist_setOrder', data, callback);
-Playlist.prototype.setOrder = function (items, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'items', type: types_.ARRAY, values: PlaylistItem},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- if (!args.items.length) {
- setTimeout(function() {
- args.errorCallback(new WebAPIException(WebAPIException.INVALID_VALUES_ERR));
- }, 0);
- return;
- }
-
- var members = [];
- for (var i = 0; i < args.items.length; i++) {
- members.push(args.items[i].content.memberId);
- }
-
- var data = {
- playlistId: this.id,
- members: members,
- };
-
- var callback = function (result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback);
- };
+};
- var result = native_.call('ContentPlaylist_setOrder', data, callback);
+Playlist.prototype.move = function(item, delta, successCallback, errorCallback) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'item', type: types_.PLATFORM_OBJECT, values: PlaylistItem },
+ { name: 'delta', type: types_.LONG },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = {
+ playlistId: this.id,
+ memberId: args.item.content.memberId,
+ delta: args.delta
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ var result = native_.call('ContentPlaylist_move', data, callback);
-Playlist.prototype.move = function (item, delta, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'item', type: types_.PLATFORM_OBJECT, values: PlaylistItem},
- {name: 'delta', type: types_.LONG},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var data = {
- playlistId: this.id,
- memberId: args.item.content.memberId,
- delta: args.delta
- };
-
- var callback = function (result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback);
- };
-
- var result = native_.call('ContentPlaylist_move', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
diff --git a/src/datacontrol/datacontrol_api.js b/src/datacontrol/datacontrol_api.js
index 5de955ec..18ff77fc 100755
--- a/src/datacontrol/datacontrol_api.js
+++ b/src/datacontrol/datacontrol_api.js
@@ -23,560 +23,652 @@ var native_ = new xwalk.utils.NativeManager(extension);
var DATA_CONTROL_MANAGER_LISTENER_ID = 'DataControlManagerChangeCallback';
var DataType = {
- 'MAP': 'MAP',
- 'SQL': 'SQL'
+ MAP: 'MAP',
+ SQL: 'SQL'
};
var DataControlListenersManager = (function() {
+ function changeEvent(event) {
+ var successCallback;
- function changeEvent(event) {
- var successCallback;
-
- if (DataType.SQL === event.type.substr(0,3)) {
- if (type_.isEmptyObject(this._SQLDataControlCbMap)) {
- return;
- }
- for (var listenerId in this._SQLDataControlCbMap) {
- if (this._SQLDataControlCbMap.hasOwnProperty(listenerId)) {
- if (this._SQLDataControlCbMap[listenerId].providerId === event.providerId &&
- this._SQLDataControlCbMap[listenerId].dataId === event.dataId) {
- successCallback = this._SQLDataControlCbMap[listenerId].changeCallback;
- if (type_.isFunction(successCallback)) {
- successCallback(event.type, {columns: event.columns, values: event.values});
+ if (DataType.SQL === event.type.substr(0, 3)) {
+ if (type_.isEmptyObject(this._SQLDataControlCbMap)) {
+ return;
}
- }
- }
- }
- } else {
- if (type_.isEmptyObject(this._MAPDataControlCbMap)) {
- return;
- }
- for (var listenerId in this._MAPDataControlCbMap) {
- if (this._MAPDataControlCbMap.hasOwnProperty(listenerId)) {
- if (this._MAPDataControlCbMap[listenerId].providerId === event.providerId &&
- this._MAPDataControlCbMap[listenerId].dataId === event.dataId) {
- successCallback = this._MAPDataControlCbMap[listenerId].changeCallback;
- if (type_.isFunction(successCallback)) {
- successCallback(event.type, {columns: event.columns, values: event.values});
+ for (var listenerId in this._SQLDataControlCbMap) {
+ if (this._SQLDataControlCbMap.hasOwnProperty(listenerId)) {
+ if (
+ this._SQLDataControlCbMap[listenerId].providerId ===
+ event.providerId &&
+ this._SQLDataControlCbMap[listenerId].dataId === event.dataId
+ ) {
+ successCallback = this._SQLDataControlCbMap[listenerId]
+ .changeCallback;
+ if (type_.isFunction(successCallback)) {
+ successCallback(event.type, {
+ columns: event.columns,
+ values: event.values
+ });
+ }
+ }
+ }
+ }
+ } else {
+ if (type_.isEmptyObject(this._MAPDataControlCbMap)) {
+ return;
+ }
+ for (var listenerId in this._MAPDataControlCbMap) {
+ if (this._MAPDataControlCbMap.hasOwnProperty(listenerId)) {
+ if (
+ this._MAPDataControlCbMap[listenerId].providerId ===
+ event.providerId &&
+ this._MAPDataControlCbMap[listenerId].dataId === event.dataId
+ ) {
+ successCallback = this._MAPDataControlCbMap[listenerId]
+ .changeCallback;
+ if (type_.isFunction(successCallback)) {
+ successCallback(event.type, {
+ columns: event.columns,
+ values: event.values
+ });
+ }
+ }
+ }
}
- }
}
- }
}
- }
- function _DataControlListenerManager() {
- this._SQLDataControlCbMap = {};
- this._MAPDataControlCbMap = {};
- this.lastListenerId = 0;
- this.changeEvent = changeEvent.bind(this);
- }
-
- _DataControlListenerManager.prototype.addChangeListener = function(type, providerId, dataId, changeCallback, errorCallback) {
- var _realWatchId = 0;
- if (DataType.SQL === type) {
- for (var i in this._SQLDataControlCbMap) {
- if (this._SQLDataControlCbMap.hasOwnProperty(i) &&
- this._SQLDataControlCbMap[i].providerId === providerId &&
- this._SQLDataControlCbMap[i].dataId === dataId) {
- _realWatchId = this._SQLDataControlCbMap[i].realWatchId;
- }
- }
- } else {
- for (var i in this._MAPDataControlCbMap) {
- if (this._MAPDataControlCbMap.hasOwnProperty(i) &&
- this._MAPDataControlCbMap[i].providerId === providerId &&
- this._MAPDataControlCbMap[i].dataId === dataId) {
- _realWatchId = this._MAPDataControlCbMap[i].realWatchId;
- }
- }
+ function _DataControlListenerManager() {
+ this._SQLDataControlCbMap = {};
+ this._MAPDataControlCbMap = {};
+ this.lastListenerId = 0;
+ this.changeEvent = changeEvent.bind(this);
}
- if (!_realWatchId) {
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(errorCallback, native_.getErrorObject(result));
- return;
+ _DataControlListenerManager.prototype.addChangeListener = function(
+ type,
+ providerId,
+ dataId,
+ changeCallback,
+ errorCallback
+ ) {
+ var _realWatchId = 0;
+ if (DataType.SQL === type) {
+ for (var i in this._SQLDataControlCbMap) {
+ if (
+ this._SQLDataControlCbMap.hasOwnProperty(i) &&
+ this._SQLDataControlCbMap[i].providerId === providerId &&
+ this._SQLDataControlCbMap[i].dataId === dataId
+ ) {
+ _realWatchId = this._SQLDataControlCbMap[i].realWatchId;
+ }
+ }
+ } else {
+ for (var i in this._MAPDataControlCbMap) {
+ if (
+ this._MAPDataControlCbMap.hasOwnProperty(i) &&
+ this._MAPDataControlCbMap[i].providerId === providerId &&
+ this._MAPDataControlCbMap[i].dataId === dataId
+ ) {
+ _realWatchId = this._MAPDataControlCbMap[i].realWatchId;
+ }
+ }
}
- };
- var result =
- native_.call('DataControlConsumerObject_addChangeListener', {
- providerId: providerId,
- dataId: dataId,
- type: type
- }, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- result = native_.getResultObject(result);
- _realWatchId = converter_.toLong(result.watchId, true);
- }
- if (type_.isEmptyObject(this._SQLDataControlCbMap) &&
- type_.isEmptyObject(this._MAPDataControlCbMap)) {
- native_.addListener(DATA_CONTROL_MANAGER_LISTENER_ID, this.changeEvent);
- }
- }
- if (DataType.SQL === type) {
- this._SQLDataControlCbMap[++this.lastListenerId] = {'providerId': providerId,
- 'dataId': dataId,
- 'changeCallback': changeCallback,
- 'realWatchId': _realWatchId};
- } else {
- this._MAPDataControlCbMap[++this.lastListenerId] = {'providerId': providerId,
- 'dataId': dataId,
- 'changeCallback': changeCallback,
- 'realWatchId': _realWatchId};
- }
-
- return this.lastListenerId;
- };
-
- _DataControlListenerManager.prototype.removeChangeListener = function(type, providerId, dataId, listenerId) {
- var _realWatchId = 0;
- if (DataType.SQL === type &&
- !type_.isUndefined(this._SQLDataControlCbMap[listenerId])) {
- _realWatchId = this._SQLDataControlCbMap[listenerId].realWatchId;
- delete this._SQLDataControlCbMap[listenerId];
- for (var i in this._SQLDataControlCbMap) {
- if (this._SQLDataControlCbMap.hasOwnProperty(i) &&
- this._SQLDataControlCbMap[i].realWatchId === _realWatchId) {
- return;
+ if (!_realWatchId) {
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ };
+ var result = native_.call(
+ 'DataControlConsumerObject_addChangeListener',
+ {
+ providerId: providerId,
+ dataId: dataId,
+ type: type
+ },
+ callback
+ );
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ result = native_.getResultObject(result);
+ _realWatchId = converter_.toLong(result.watchId, true);
+ }
+ if (
+ type_.isEmptyObject(this._SQLDataControlCbMap) &&
+ type_.isEmptyObject(this._MAPDataControlCbMap)
+ ) {
+ native_.addListener(DATA_CONTROL_MANAGER_LISTENER_ID, this.changeEvent);
+ }
}
- }
- } else if (DataType.MAP === type &&
- !type_.isUndefined(this._MAPDataControlCbMap[listenerId])) {
- _realWatchId = this._MAPDataControlCbMap[listenerId].realWatchId;
- delete this._MAPDataControlCbMap[listenerId];
- for (var i in this._MAPDataControlCbMap) {
- if (this._MAPDataControlCbMap.hasOwnProperty(i) &&
- this._MAPDataControlCbMap[i].realWatchId === _realWatchId) {
- return;
+
+ if (DataType.SQL === type) {
+ this._SQLDataControlCbMap[++this.lastListenerId] = {
+ providerId: providerId,
+ dataId: dataId,
+ changeCallback: changeCallback,
+ realWatchId: _realWatchId
+ };
+ } else {
+ this._MAPDataControlCbMap[++this.lastListenerId] = {
+ providerId: providerId,
+ dataId: dataId,
+ changeCallback: changeCallback,
+ realWatchId: _realWatchId
+ };
}
- }
- } else {
- console.log('Type invalid or listener was not added');
- return;
- }
- if (0 != _realWatchId) {
- native_.call('DataControlConsumerObject_removeChangeListener',{
- watchId: _realWatchId,
- });
+ return this.lastListenerId;
+ };
+
+ _DataControlListenerManager.prototype.removeChangeListener = function(
+ type,
+ providerId,
+ dataId,
+ listenerId
+ ) {
+ var _realWatchId = 0;
+ if (
+ DataType.SQL === type &&
+ !type_.isUndefined(this._SQLDataControlCbMap[listenerId])
+ ) {
+ _realWatchId = this._SQLDataControlCbMap[listenerId].realWatchId;
+ delete this._SQLDataControlCbMap[listenerId];
+ for (var i in this._SQLDataControlCbMap) {
+ if (
+ this._SQLDataControlCbMap.hasOwnProperty(i) &&
+ this._SQLDataControlCbMap[i].realWatchId === _realWatchId
+ ) {
+ return;
+ }
+ }
+ } else if (
+ DataType.MAP === type &&
+ !type_.isUndefined(this._MAPDataControlCbMap[listenerId])
+ ) {
+ _realWatchId = this._MAPDataControlCbMap[listenerId].realWatchId;
+ delete this._MAPDataControlCbMap[listenerId];
+ for (var i in this._MAPDataControlCbMap) {
+ if (
+ this._MAPDataControlCbMap.hasOwnProperty(i) &&
+ this._MAPDataControlCbMap[i].realWatchId === _realWatchId
+ ) {
+ return;
+ }
+ }
+ } else {
+ console.log('Type invalid or listener was not added');
+ return;
+ }
- if (type_.isEmptyObject(this._SQLDataControlCbMap) &&
- type_.isEmptyObject(this._MAPDataControlCbMap)) {
- native_.removeListener(DATA_CONTROL_MANAGER_LISTENER_ID);
- }
- }
- };
+ if (0 != _realWatchId) {
+ native_.call('DataControlConsumerObject_removeChangeListener', {
+ watchId: _realWatchId
+ });
- return _DataControlListenerManager;
+ if (
+ type_.isEmptyObject(this._SQLDataControlCbMap) &&
+ type_.isEmptyObject(this._MAPDataControlCbMap)
+ ) {
+ native_.removeListener(DATA_CONTROL_MANAGER_LISTENER_ID);
+ }
+ }
+ };
+ return _DataControlListenerManager;
})();
var listenersManager = new DataControlListenersManager();
function SetReadOnlyProperty(obj, n, v) {
- Object.defineProperty(obj, n, {value: v, writable: false});
+ Object.defineProperty(obj, n, { value: v, writable: false });
}
function DataControlManager() {
- // constructor of DataControlManager
+ // constructor of DataControlManager
}
var privUtils_ = xwalk.utils;
var getDataControlConsumer = function(providerId, dataId, type) {
- privUtils_.checkPrivilegeAccess(privUtils_.privilege.DATACONTROL_CONSUMER);
- var args = validator_.validateArgs(arguments, [
- {'name': 'providerId', 'type': types_.STRING},
- {'name': 'dataId', 'type': types_.STRING},
- {'name': 'type', 'type': types_.ENUM, 'values': [DataType.SQL, DataType.MAP]}
- ]);
-
- var returnObject = null;
- if (DataType.SQL === type) {
- returnObject = new SQLDataControlConsumer();
- } else if (DataType.MAP == type) {
- returnObject = new MappedDataControlConsumer();
- }
-
- SetReadOnlyProperty(returnObject, 'type', args.type); // read only property
- SetReadOnlyProperty(returnObject, 'providerId', args.providerId); // read only property
- SetReadOnlyProperty(returnObject, 'dataId', args.dataId); // read only property
-
- return returnObject;
-};
+ privUtils_.checkPrivilegeAccess(privUtils_.privilege.DATACONTROL_CONSUMER);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'providerId', type: types_.STRING },
+ { name: 'dataId', type: types_.STRING },
+ { name: 'type', type: types_.ENUM, values: [DataType.SQL, DataType.MAP] }
+ ]);
+
+ var returnObject = null;
+ if (DataType.SQL === type) {
+ returnObject = new SQLDataControlConsumer();
+ } else if (DataType.MAP == type) {
+ returnObject = new MappedDataControlConsumer();
+ }
+
+ SetReadOnlyProperty(returnObject, 'type', args.type); // read only property
+ SetReadOnlyProperty(returnObject, 'providerId', args.providerId); // read only
+ // property
+ SetReadOnlyProperty(returnObject, 'dataId', args.dataId); // read only property
+ return returnObject;
+};
DataControlManager.prototype.getDataControlConsumer = function(providerId, dataId, type) {
- return getDataControlConsumer.apply(null, arguments);
+ return getDataControlConsumer.apply(null, arguments);
};
function DataControlConsumerObject() {
- // constructor of DataControlConsumerObject
+ // constructor of DataControlConsumerObject
}
DataControlConsumerObject.prototype.addChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'dataChangeCallback', 'type': types_.FUNCTION, optional: false,
- nullable: false},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var type = DataType.SQL;
- if (this instanceof MappedDataControlConsumer) {
- type = DataType.MAP;
- }
-
- return listenersManager.addChangeListener(type, this.providerId, this.dataId,
- args.dataChangeCallback, args.errorCallback);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'dataChangeCallback',
+ type: types_.FUNCTION,
+ optional: false,
+ nullable: false
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var type = DataType.SQL;
+ if (this instanceof MappedDataControlConsumer) {
+ type = DataType.MAP;
+ }
+
+ return listenersManager.addChangeListener(
+ type,
+ this.providerId,
+ this.dataId,
+ args.dataChangeCallback,
+ args.errorCallback
+ );
};
DataControlConsumerObject.prototype.removeChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'watchId', 'type': types_.LONG}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG }
+ ]);
- var type = DataType.SQL;
- if (this instanceof MappedDataControlConsumer) {
- type = DataType.MAP;
- }
+ var type = DataType.SQL;
+ if (this instanceof MappedDataControlConsumer) {
+ type = DataType.MAP;
+ }
- listenersManager.removeChangeListener(type, this.providerId, this.dataId, args.watchId);
+ listenersManager.removeChangeListener(
+ type,
+ this.providerId,
+ this.dataId,
+ args.watchId
+ );
};
function SQLDataControlConsumer() {
- // constructor of SQLDataControlConsumer
+ // constructor of SQLDataControlConsumer
}
SQLDataControlConsumer.prototype = new DataControlConsumerObject();
SQLDataControlConsumer.prototype.constructor = SQLDataControlConsumer;
SQLDataControlConsumer.prototype.insert = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'insertionData', 'type': types_.DICTIONARY},
- {'name': 'successCallback', 'type': types_.FUNCTION, optional: true, nullable: true},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- // doing conversion of all elements to string
- var ins = validator_.validateArgs([args.insertionData.columns, args.insertionData.values], [
- {name : 'columns', type : types_.ARRAY, values : types_.STRING},
- {name : 'values', type : types_.ARRAY, values : types_.STRING}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'insertionData': args.insertionData
- };
-
- var syncResult =
- native_.call('SQLDataControlConsumer_insert', nativeParam, function(result) {
- if (result.status == 'success') {
- if (args.successCallback) {
- args.successCallback(result['requestId'], result['result']);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'insertionData', type: types_.DICTIONARY },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ // doing conversion of all elements to string
+ var ins = validator_.validateArgs(
+ [args.insertionData.columns, args.insertionData.values],
+ [
+ { name: 'columns', type: types_.ARRAY, values: types_.STRING },
+ { name: 'values', type: types_.ARRAY, values: types_.STRING }
+ ]
+ );
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ insertionData: args.insertionData
+ };
+
+ var syncResult = native_.call('SQLDataControlConsumer_insert', nativeParam, function(
+ result
+ ) {
+ if (result.status == 'success') {
+ if (args.successCallback) {
+ args.successCallback(result['requestId'], result['result']);
+ }
}
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
}
- }
});
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
SQLDataControlConsumer.prototype.update = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'updateData', 'type': types_.DICTIONARY},
- {'name': 'where', 'type': types_.STRING},
- {'name': 'successCallback', 'type': types_.FUNCTION, optional: true, nullable: true},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'where': args.where,
- 'updateData': args.updateData
- };
-
- var syncResult =
- native_.call('SQLDataControlConsumer_update', nativeParam, function(result) {
- if (result.status == 'success') {
- if (args.successCallback) {
- args.successCallback(result['requestId']);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'updateData', type: types_.DICTIONARY },
+ { name: 'where', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ where: args.where,
+ updateData: args.updateData
+ };
+
+ var syncResult = native_.call('SQLDataControlConsumer_update', nativeParam, function(
+ result
+ ) {
+ if (result.status == 'success') {
+ if (args.successCallback) {
+ args.successCallback(result['requestId']);
+ }
}
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
}
- }
});
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
SQLDataControlConsumer.prototype.remove = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'where', 'type': types_.STRING},
- {'name': 'successCallback', 'type': types_.FUNCTION, optional: true, nullable: true},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'where': args.where
- };
-
- var syncResult =
- native_.call('SQLDataControlConsumer_remove', nativeParam, function(result) {
- if (result.status == 'success') {
- if (args.successCallback) {
- args.successCallback(result['requestId']);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'where', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ where: args.where
+ };
+
+ var syncResult = native_.call('SQLDataControlConsumer_remove', nativeParam, function(
+ result
+ ) {
+ if (result.status == 'success') {
+ if (args.successCallback) {
+ args.successCallback(result['requestId']);
+ }
}
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
}
- }
});
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
-
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
SQLDataControlConsumer.prototype.select = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'columns', 'type': types_.ARRAY},
- {'name': 'where', 'type': types_.STRING},
- {'name': 'successCallback', 'type': types_.FUNCTION},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true},
- {'name': 'page', 'type': types_.LONG, optional: true, nullable: true},
- {'name': 'maxNumberPerPage', 'type': types_.LONG, optional: true, nullable: true},
- {'name': 'order', 'type': types_.STRING, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'columns': args.columns,
- 'where': args.where
- };
- if (args['page']) {
- nativeParam['page'] = args.page;
- }
- if (args['maxNumberPerPage']) {
- nativeParam['maxNumberPerPage'] = args.maxNumberPerPage;
- }
- if (args['order']) {
- nativeParam['order'] = args.order;
- }
-
- var syncResult =
- native_.call('SQLDataControlConsumer_select', nativeParam, function(result) {
- if (result.status == 'success') {
- args.successCallback(result['result'], result['requestId']);
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'columns', type: types_.ARRAY },
+ { name: 'where', type: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'page', type: types_.LONG, optional: true, nullable: true },
+ { name: 'maxNumberPerPage', type: types_.LONG, optional: true, nullable: true },
+ { name: 'order', type: types_.STRING, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ columns: args.columns,
+ where: args.where
+ };
+ if (args['page']) {
+ nativeParam['page'] = args.page;
+ }
+ if (args['maxNumberPerPage']) {
+ nativeParam['maxNumberPerPage'] = args.maxNumberPerPage;
+ }
+ if (args['order']) {
+ nativeParam['order'] = args.order;
+ }
+
+ var syncResult = native_.call('SQLDataControlConsumer_select', nativeParam, function(
+ result
+ ) {
+ if (result.status == 'success') {
+ args.successCallback(result['result'], result['requestId']);
+ }
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
}
- }
});
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
-
function MappedDataControlConsumer() {
- // constructor of MappedDataControlConsumer
+ // constructor of MappedDataControlConsumer
}
MappedDataControlConsumer.prototype = new DataControlConsumerObject();
MappedDataControlConsumer.prototype.constructor = MappedDataControlConsumer;
MappedDataControlConsumer.prototype.addValue = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'key', 'type': types_.STRING},
- {'name': 'value', 'type': types_.STRING},
- {'name': 'successCallback', 'type': types_.FUNCTION, optional: true, nullable: true},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'key': args.key,
- 'value': args.value
- };
-
- var syncResult =
- native_.call('MappedDataControlConsumer_addValue', nativeParam, function(result) {
- if (result.status == 'success') {
- if (args.successCallback) {
- args.successCallback(result['requestId']);
- }
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'key', type: types_.STRING },
+ { name: 'value', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ key: args.key,
+ value: args.value
+ };
+
+ var syncResult = native_.call(
+ 'MappedDataControlConsumer_addValue',
+ nativeParam,
+ function(result) {
+ if (result.status == 'success') {
+ if (args.successCallback) {
+ args.successCallback(result['requestId']);
+ }
+ }
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
+ }
}
- }
- });
-
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
+ );
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
MappedDataControlConsumer.prototype.removeValue = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'key', 'type': types_.STRING},
- {'name': 'value', 'type': types_.STRING},
- {'name': 'successCallback', 'type': types_.FUNCTION},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'key': args.key,
- 'value': args.value
- };
-
- var syncResult =
- native_.call('MappedDataControlConsumer_removeValue', nativeParam, function(result) {
- if (result.status == 'success') {
- args.successCallback(result['requestId']);
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'key', type: types_.STRING },
+ { name: 'value', type: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ key: args.key,
+ value: args.value
+ };
+
+ var syncResult = native_.call(
+ 'MappedDataControlConsumer_removeValue',
+ nativeParam,
+ function(result) {
+ if (result.status == 'success') {
+ args.successCallback(result['requestId']);
+ }
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
+ }
}
- }
- });
-
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
+ );
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
MappedDataControlConsumer.prototype.getValue = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'key', 'type': types_.STRING},
- {'name': 'successCallback', 'type': types_.FUNCTION},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'key': args.key
- };
-
- var syncResult =
- native_.call('MappedDataControlConsumer_getValue', nativeParam, function(result) {
- if (result.status == 'success') {
- args.successCallback(result['result'], result['requestId']);
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'key', type: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ key: args.key
+ };
+
+ var syncResult = native_.call(
+ 'MappedDataControlConsumer_getValue',
+ nativeParam,
+ function(result) {
+ if (result.status == 'success') {
+ args.successCallback(result['result'], result['requestId']);
+ }
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
+ }
}
- }
- });
-
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
+ );
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
MappedDataControlConsumer.prototype.updateValue = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'reqId', 'type': types_.LONG},
- {'name': 'key', 'type': types_.STRING},
- {'name': 'oldValue', 'type': types_.STRING},
- {'name': 'newValue', 'type': types_.STRING},
- {'name': 'successCallback', 'type': types_.FUNCTION},
- {'name': 'errorCallback', 'type': types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'providerId': this.providerId,
- 'dataId': this.dataId,
- 'reqId': args.reqId,
- 'key': args.key,
- 'oldValue': args.oldValue,
- 'newValue': args.newValue
- };
-
- var syncResult =
- native_.call('MappedDataControlConsumer_updateValue', nativeParam, function(result) {
- if (result.status == 'success') {
- args.successCallback(result['requestId']);
- }
- if (result.status == 'error') {
- if (args.errorCallback) {
- var err = result['result'];
- var e = new WebAPIException(err.name, err.message);
- args.errorCallback(result['requestId'], e);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'reqId', type: types_.LONG },
+ { name: 'key', type: types_.STRING },
+ { name: 'oldValue', type: types_.STRING },
+ { name: 'newValue', type: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ providerId: this.providerId,
+ dataId: this.dataId,
+ reqId: args.reqId,
+ key: args.key,
+ oldValue: args.oldValue,
+ newValue: args.newValue
+ };
+
+ var syncResult = native_.call(
+ 'MappedDataControlConsumer_updateValue',
+ nativeParam,
+ function(result) {
+ if (result.status == 'success') {
+ args.successCallback(result['requestId']);
+ }
+ if (result.status == 'error') {
+ if (args.errorCallback) {
+ var err = result['result'];
+ var e = new WebAPIException(err.name, err.message);
+ args.errorCallback(result['requestId'], e);
+ }
+ }
}
- }
- });
-
- if (native_.isFailure(syncResult)) {
- throw native_.getErrorObject(syncResult);
- }
+ );
+ if (native_.isFailure(syncResult)) {
+ throw native_.getErrorObject(syncResult);
+ }
};
exports = new DataControlManager();
-
diff --git a/src/download/download_api.js b/src/download/download_api.js
index c689ed2c..20536eab 100755
--- a/src/download/download_api.js
+++ b/src/download/download_api.js
@@ -27,302 +27,323 @@ var callbacks = {};
var requests = {};
function DownloadManagerChangeCallback(result) {
- var callback = callbacks[result.downloadId];
-
- if (!callback) {
- privUtils_.log('Ignoring unknown callback: ' + result.downloadId);
- return;
- }
- setTimeout(function() {
- if (result.status == 'progress') {
- if (callback.onprogress) {
- var receivedSize = result.receivedSize;
- var totalSize = result.totalSize;
- callback.onprogress(result.downloadId, receivedSize, totalSize);
- }
- } else if (result.status == 'paused') {
- if (callback.onpaused) {
- callback.onpaused(result.downloadId);
- }
- } else if (result.status == 'canceled') {
- if (callback.oncanceled) {
- callback.oncanceled(result.downloadId);
- delete callbacks[result.downloadId];
- }
- } else if (result.status == 'completed') {
- if (callback.oncompleted) {
- var fullPath = result.fullPath;
- callback.oncompleted(result.downloadId, fullPath);
- delete callbacks[result.downloadId];
- }
- } else if (result.status == 'error') {
- if (callback.onfailed) {
- callback.onfailed(result.downloadId,
- new WebAPIException(result.error));
- delete callbacks[result.downloadId];
- }
+ var callback = callbacks[result.downloadId];
+
+ if (!callback) {
+ privUtils_.log('Ignoring unknown callback: ' + result.downloadId);
+ return;
}
- }, 0);
+ setTimeout(function() {
+ if (result.status == 'progress') {
+ if (callback.onprogress) {
+ var receivedSize = result.receivedSize;
+ var totalSize = result.totalSize;
+ callback.onprogress(result.downloadId, receivedSize, totalSize);
+ }
+ } else if (result.status == 'paused') {
+ if (callback.onpaused) {
+ callback.onpaused(result.downloadId);
+ }
+ } else if (result.status == 'canceled') {
+ if (callback.oncanceled) {
+ callback.oncanceled(result.downloadId);
+ delete callbacks[result.downloadId];
+ }
+ } else if (result.status == 'completed') {
+ if (callback.oncompleted) {
+ var fullPath = result.fullPath;
+ callback.oncompleted(result.downloadId, fullPath);
+ delete callbacks[result.downloadId];
+ }
+ } else if (result.status == 'error') {
+ if (callback.onfailed) {
+ callback.onfailed(result.downloadId, new WebAPIException(result.error));
+ delete callbacks[result.downloadId];
+ }
+ }
+ }, 0);
}
function nextDownloadId() {
- return ++downloadId;
+ return ++downloadId;
}
function SetReadOnlyProperty(obj, n, v) {
- Object.defineProperty(obj, n, {value: v, writable: false});
+ Object.defineProperty(obj, n, { value: v, writable: false });
}
var DownloadState = {
- 'QUEUED': 'QUEUED',
- 'DOWNLOADING': 'DOWNLOADING',
- 'PAUSED': 'PAUSED',
- 'CANCELED': 'CANCELED',
- 'COMPLETED': 'COMPLETED',
- 'FAILED': 'FAILED'
+ QUEUED: 'QUEUED',
+ DOWNLOADING: 'DOWNLOADING',
+ PAUSED: 'PAUSED',
+ CANCELED: 'CANCELED',
+ COMPLETED: 'COMPLETED',
+ FAILED: 'FAILED'
};
var DownloadNetworkType = {
- 'CELLULAR': 'CELLULAR',
- 'WIFI': 'WIFI',
- 'ALL': 'ALL'
+ CELLULAR: 'CELLULAR',
+ WIFI: 'WIFI',
+ ALL: 'ALL'
};
tizen.DownloadRequest = function(url, destination, fileName, networkType, httpHeader) {
- validator_.isConstructorCall(this, tizen.DownloadRequest);
-
- var url_ = converter_.toString(url);
- var destination_ = destination === undefined ? '' : converter_.toString(destination);
- var fileName_ = fileName === undefined ? '' : converter_.toString(fileName);
-
- var networkType_;
-
- if (networkType === undefined || !(networkType in DownloadNetworkType)) {
- networkType_ = 'ALL';
- } else {
- networkType_ = networkType;
- }
-
- Object.defineProperties(this, {
- 'url': {
- enumerable: true,
- get: function() {
- return url_;
- },
- set: function(value) {
- if (value !== null) {
- url_ = converter_.toString(value);
- }
- },
- },
- 'destination': {
- enumerable: true,
- get: function() {
- return destination_;
- },
- set: function(value) {
- if (value !== null) {
- destination_ = converter_.toString(value);
- }
- },
- },
- 'fileName': {
- enumerable: true,
- get: function() {
- return fileName_;
- },
- set: function(value) {
- if (value !== null) {
- fileName_ = converter_.toString(value);
- }
- },
- },
- 'networkType': {
- enumerable: true,
- get: function() {
- return networkType_;
- },
- set: function(value) {
- if (value === null || value in DownloadNetworkType) {
- networkType_ = value;
- }
- },
- },
- 'httpHeader': {
- writable: true,
- enumerable: true,
- value: httpHeader === undefined ? {} : httpHeader,
+ validator_.isConstructorCall(this, tizen.DownloadRequest);
+
+ var url_ = converter_.toString(url);
+ var destination_ = destination === undefined ? '' : converter_.toString(destination);
+ var fileName_ = fileName === undefined ? '' : converter_.toString(fileName);
+
+ var networkType_;
+
+ if (networkType === undefined || !(networkType in DownloadNetworkType)) {
+ networkType_ = 'ALL';
+ } else {
+ networkType_ = networkType;
}
- });
-};
+ Object.defineProperties(this, {
+ url: {
+ enumerable: true,
+ get: function() {
+ return url_;
+ },
+ set: function(value) {
+ if (value !== null) {
+ url_ = converter_.toString(value);
+ }
+ }
+ },
+ destination: {
+ enumerable: true,
+ get: function() {
+ return destination_;
+ },
+ set: function(value) {
+ if (value !== null) {
+ destination_ = converter_.toString(value);
+ }
+ }
+ },
+ fileName: {
+ enumerable: true,
+ get: function() {
+ return fileName_;
+ },
+ set: function(value) {
+ if (value !== null) {
+ fileName_ = converter_.toString(value);
+ }
+ }
+ },
+ networkType: {
+ enumerable: true,
+ get: function() {
+ return networkType_;
+ },
+ set: function(value) {
+ if (value === null || value in DownloadNetworkType) {
+ networkType_ = value;
+ }
+ }
+ },
+ httpHeader: {
+ writable: true,
+ enumerable: true,
+ value: httpHeader === undefined ? {} : httpHeader
+ }
+ });
+};
function DownloadManager() {
- // constructor of DownloadManager
+ // constructor of DownloadManager
}
DownloadManager.prototype.start = function() {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'downloadRequest', 'type': types_.PLATFORM_OBJECT, 'values': tizen.DownloadRequest},
- {'name' : 'downloadCallback', 'type': types_.LISTENER,
- 'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed'],
- optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- 'url': args.downloadRequest.url,
- 'destination': args.downloadRequest.destination,
- 'fileName': args.downloadRequest.fileName,
- 'networkType': args.downloadRequest.networkType,
- 'httpHeader': args.downloadRequest.httpHeader,
- 'downloadId': nextDownloadId()
- };
-
- if (args.downloadCallback) {
- this.setListener(nativeParam.downloadId, args.downloadCallback);
- }
-
- var result = native_.callSync('DownloadManager_start', nativeParam);
-
- if (native_.isFailure(result)) {
- if ('NetworkError' === result.error.name) {
- return -1;
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'downloadRequest',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.DownloadRequest
+ },
+ {
+ name: 'downloadCallback',
+ type: types_.LISTENER,
+ values: ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed'],
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var nativeParam = {
+ url: args.downloadRequest.url,
+ destination: args.downloadRequest.destination,
+ fileName: args.downloadRequest.fileName,
+ networkType: args.downloadRequest.networkType,
+ httpHeader: args.downloadRequest.httpHeader,
+ downloadId: nextDownloadId()
+ };
+
+ if (args.downloadCallback) {
+ this.setListener(nativeParam.downloadId, args.downloadCallback);
+ }
+
+ var result = native_.callSync('DownloadManager_start', nativeParam);
+
+ if (native_.isFailure(result)) {
+ if ('NetworkError' === result.error.name) {
+ return -1;
+ }
+ throw native_.getErrorObject(result);
}
- throw native_.getErrorObject(result);
- }
- requests[nativeParam.downloadId] = args.downloadRequest;
+ requests[nativeParam.downloadId] = args.downloadRequest;
- return nativeParam.downloadId;
+ return nativeParam.downloadId;
};
DownloadManager.prototype.cancel = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'downloadId', type: types_.LONG, 'nullable': false, 'optional': false}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
+ ]);
- var nativeParam = {
- 'downloadId': args.downloadId
- };
+ var nativeParam = {
+ downloadId: args.downloadId
+ };
- if (typeof requests[args.downloadId] === 'undefined')
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'the identifier does not match any download operation in progress');
+ if (typeof requests[args.downloadId] === 'undefined')
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'the identifier does not match any download operation in progress'
+ );
- var result = native_.callSync('DownloadManager_cancel', nativeParam);
+ var result = native_.callSync('DownloadManager_cancel', nativeParam);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
DownloadManager.prototype.pause = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
+ ]);
- var nativeParam = {
- 'downloadId': args.downloadId
- };
+ var nativeParam = {
+ downloadId: args.downloadId
+ };
- if (typeof requests[args.downloadId] === 'undefined')
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'the identifier does not match any download operation in progress');
+ if (typeof requests[args.downloadId] === 'undefined')
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'the identifier does not match any download operation in progress'
+ );
- var result = native_.callSync('DownloadManager_pause', nativeParam);
+ var result = native_.callSync('DownloadManager_pause', nativeParam);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
DownloadManager.prototype.resume = function() {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
+ ]);
- var nativeParam = {
- 'downloadId': args.downloadId
- };
+ var nativeParam = {
+ downloadId: args.downloadId
+ };
- if (typeof requests[args.downloadId] === 'undefined')
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'the identifier does not match any download operation in progress');
+ if (typeof requests[args.downloadId] === 'undefined')
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'the identifier does not match any download operation in progress'
+ );
- var result = native_.callSync('DownloadManager_resume', nativeParam);
+ var result = native_.callSync('DownloadManager_resume', nativeParam);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
DownloadManager.prototype.getState = function() {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
- ]);
-
- var nativeParam = {
- 'downloadId': args.downloadId
- };
-
- if (typeof requests[args.downloadId] === 'undefined')
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'the identifier does not match any download operation in progress');
-
- var result = native_.callSync('DownloadManager_getState', nativeParam);
-
- if (native_.isSuccess(result)) {
- return native_.getResultObject(result);
- } else {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
+ ]);
+
+ var nativeParam = {
+ downloadId: args.downloadId
+ };
+
+ if (typeof requests[args.downloadId] === 'undefined')
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'the identifier does not match any download operation in progress'
+ );
+
+ var result = native_.callSync('DownloadManager_getState', nativeParam);
+
+ if (native_.isSuccess(result)) {
+ return native_.getResultObject(result);
+ } else {
+ throw native_.getErrorObject(result);
+ }
};
DownloadManager.prototype.getDownloadRequest = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
+ ]);
- if (typeof requests[args.downloadId] === 'undefined')
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'the identifier does not match any download operation in progress');
+ if (typeof requests[args.downloadId] === 'undefined')
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'the identifier does not match any download operation in progress'
+ );
- return requests[args.downloadId];
+ return requests[args.downloadId];
};
DownloadManager.prototype.getMIMEType = function() {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
- ]);
-
- var nativeParam = {
- 'downloadId': args.downloadId
- };
-
- if (typeof requests[args.downloadId] === 'undefined')
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'the identifier does not match any download operation in progress');
-
- var result = native_.callSync('DownloadManager_getMIMEType', nativeParam);
-
- if (native_.isSuccess(result)) {
- return native_.getResultObject(result);
- } else {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
+ ]);
+
+ var nativeParam = {
+ downloadId: args.downloadId
+ };
+
+ if (typeof requests[args.downloadId] === 'undefined')
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'the identifier does not match any download operation in progress'
+ );
+
+ var result = native_.callSync('DownloadManager_getMIMEType', nativeParam);
+
+ if (native_.isSuccess(result)) {
+ return native_.getResultObject(result);
+ } else {
+ throw native_.getErrorObject(result);
+ }
};
DownloadManager.prototype.setListener = function() {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'downloadId', 'type': types_.LONG},
- {'name' : 'downloadCallback', 'type': types_.LISTENER,
- 'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed']}
- ]);
-
- if (!native_.isListenerSet(DOWNLOAD_MANAGER_LISTENER_ID)) {
- native_.addListener(DOWNLOAD_MANAGER_LISTENER_ID, DownloadManagerChangeCallback);
- }
- callbacks[args.downloadId] = args.downloadCallback;
+ var args = validator_.validateArgs(arguments, [
+ { name: 'downloadId', type: types_.LONG },
+ {
+ name: 'downloadCallback',
+ type: types_.LISTENER,
+ values: ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed']
+ }
+ ]);
+
+ if (!native_.isListenerSet(DOWNLOAD_MANAGER_LISTENER_ID)) {
+ native_.addListener(DOWNLOAD_MANAGER_LISTENER_ID, DownloadManagerChangeCallback);
+ }
+ callbacks[args.downloadId] = args.downloadCallback;
};
-exports = new DownloadManager(); \ No newline at end of file
+exports = new DownloadManager();
diff --git a/src/exif/exif_api.js b/src/exif/exif_api.js
index fc25fa3f..841ad213 100644
--- a/src/exif/exif_api.js
+++ b/src/exif/exif_api.js
@@ -15,7 +15,7 @@
*/
var _global = window || global || {};
-
+
var validator_ = xwalk.utils.validator;
var type_ = xwalk.utils.type;
var native_ = new xwalk.utils.NativeManager(extension);
@@ -24,537 +24,565 @@ var converter_ = xwalk.utils.converter;
function ExifManager() {}
var ImageContentOrientation = {
- NORMAL: 'NORMAL',
- FLIP_HORIZONTAL: 'FLIP_HORIZONTAL',
- ROTATE_180: 'ROTATE_180',
- FLIP_VERTICAL: 'FLIP_VERTICAL',
- TRANSPOSE: 'TRANSPOSE',
- ROTATE_90: 'ROTATE_90',
- TRANSVERSE: 'TRANSVERSE',
- ROTATE_270: 'ROTATE_270'
+ NORMAL: 'NORMAL',
+ FLIP_HORIZONTAL: 'FLIP_HORIZONTAL',
+ ROTATE_180: 'ROTATE_180',
+ FLIP_VERTICAL: 'FLIP_VERTICAL',
+ TRANSPOSE: 'TRANSPOSE',
+ ROTATE_90: 'ROTATE_90',
+ TRANSVERSE: 'TRANSVERSE',
+ ROTATE_270: 'ROTATE_270'
};
var ExposureProgram = {
- NOT_DEFINED: 'NOT_DEFINED',
- MANUAL: 'MANUAL',
- NORMAL: 'NORMAL',
- APERTURE_PRIORITY: 'APERTURE_PRIORITY',
- SHUTTER_PRIORITY: 'SHUTTER_PRIORITY',
- CREATIVE_PROGRAM: 'CREATIVE_PROGRAM',
- ACTION_PROGRAM: 'ACTION_PROGRAM',
- PORTRAIT_MODE: 'PORTRAIT_MODE',
- LANDSCAPE_MODE: 'LANDSCAPE_MODE'
+ NOT_DEFINED: 'NOT_DEFINED',
+ MANUAL: 'MANUAL',
+ NORMAL: 'NORMAL',
+ APERTURE_PRIORITY: 'APERTURE_PRIORITY',
+ SHUTTER_PRIORITY: 'SHUTTER_PRIORITY',
+ CREATIVE_PROGRAM: 'CREATIVE_PROGRAM',
+ ACTION_PROGRAM: 'ACTION_PROGRAM',
+ PORTRAIT_MODE: 'PORTRAIT_MODE',
+ LANDSCAPE_MODE: 'LANDSCAPE_MODE'
};
var WhiteBalanceMode = {
- AUTO: 'AUTO',
- MANUAL: 'MANUAL'
+ AUTO: 'AUTO',
+ MANUAL: 'MANUAL'
};
var propertiesList = {
- URI: 'uri',
- WIDTH: 'width',
- HEIGHT: 'height',
- DEVICE_MAKER: 'deviceMaker',
- DEVICE_MODEL: 'deviceModel',
- ORIGINAL_TIME: 'originalTime',
- ORIENTATION: 'orientation',
- FNUMBER: 'fNumber',
- ISO_SPEED_RATINGS: 'isoSpeedRatings',
- EXPOSURE_TIME: 'exposureTime',
- EXPOSURE_PROGRAM: 'exposureProgram',
- FLASH: 'flash',
- FOCAL_LENGTH: 'focalLength',
- WHITE_BALANCE: 'whiteBalance',
- GPS_LOCATION: 'gpsLocation',
- GPS_ALTITUDE: 'gpsAltitude',
- GPS_PROCESSING_METHOD: 'gpsProcessingMethod',
- GPS_TIME: 'gpsTime',
- USER_COMMENT: 'userComment'
+ URI: 'uri',
+ WIDTH: 'width',
+ HEIGHT: 'height',
+ DEVICE_MAKER: 'deviceMaker',
+ DEVICE_MODEL: 'deviceModel',
+ ORIGINAL_TIME: 'originalTime',
+ ORIENTATION: 'orientation',
+ FNUMBER: 'fNumber',
+ ISO_SPEED_RATINGS: 'isoSpeedRatings',
+ EXPOSURE_TIME: 'exposureTime',
+ EXPOSURE_PROGRAM: 'exposureProgram',
+ FLASH: 'flash',
+ FOCAL_LENGTH: 'focalLength',
+ WHITE_BALANCE: 'whiteBalance',
+ GPS_LOCATION: 'gpsLocation',
+ GPS_ALTITUDE: 'gpsAltitude',
+ GPS_PROCESSING_METHOD: 'gpsProcessingMethod',
+ GPS_TIME: 'gpsTime',
+ USER_COMMENT: 'userComment'
};
-var URI_ABSOLUTE_PREFIX = "file:///";
+var URI_ABSOLUTE_PREFIX = 'file:///';
function _isValidAbsoluteURI(uri) {
- return 0 === uri.indexOf(URI_ABSOLUTE_PREFIX);
+ return 0 === uri.indexOf(URI_ABSOLUTE_PREFIX);
}
function _getJsonFromExifInformation(exifInfo) {
- var json = {};
-
- for (var prop in propertiesList) {
- var propName = propertiesList[prop];
-
- if (exifInfo[propName] !== null) {
- if (propName === 'originalTime') {
- json[propName] = Math.floor(exifInfo[propName].getTime() / 1000);
- } else if (propName === 'gpsTime') {
- var str = exifInfo[propName].toLocaleString().split(', ');
- var res = str[1] + ', ' + str[2] + ', ' + str[3];
-
- json[propName] = Math.floor(Date.parse(res) / 1000);
- } else {
- json[propName] = exifInfo[propName];
- }
+ var json = {};
+
+ for (var prop in propertiesList) {
+ var propName = propertiesList[prop];
+
+ if (exifInfo[propName] !== null) {
+ if (propName === 'originalTime') {
+ json[propName] = Math.floor(exifInfo[propName].getTime() / 1000);
+ } else if (propName === 'gpsTime') {
+ var str = exifInfo[propName].toLocaleString().split(', ');
+ var res = str[1] + ', ' + str[2] + ', ' + str[3];
+
+ json[propName] = Math.floor(Date.parse(res) / 1000);
+ } else {
+ json[propName] = exifInfo[propName];
+ }
+ }
}
- }
- return json;
+ return json;
}
function _calculateDegDecimal(degrees, minutes, seconds) {
- return parseInt(degrees) + parseInt(minutes) / 60.0 + parseInt(seconds) / 3600.0;
+ return parseInt(degrees) + parseInt(minutes) / 60.0 + parseInt(seconds) / 3600.0;
}
function _calculateExifInfo(exifInfoNative) {
- // copy all properties that share name from
- // exifInfoNative to exifInfo
- var exifInfo = new tizen.ExifInformation(exifInfoNative);
-
- // copy all remaining properties that do not share name or need extra calculations
- if (exifInfoNative.originalTimeSeconds) {
- exifInfo.originalTime = new Date(exifInfoNative.originalTimeSeconds * 1000);
- }
-
- if (parseInt(exifInfoNative.whiteBalanceValue) === 0) { // 0=AUTO
- exifInfo.whiteBalance = WhiteBalanceMode.AUTO;
- } else if (parseInt(exifInfoNative.whiteBalanceValue) === 1) { // 1=MANUAL
- exifInfo.whiteBalance = WhiteBalanceMode.MANUAL;
- }
-
- // gpsLocation
- if (exifInfoNative.gpsLatitudeDegrees &&
- exifInfoNative.gpsLongitudeDegrees &&
- exifInfoNative.gpsLatitudeRef &&
- exifInfoNative.gpsLongitudeRef) {
- exifInfo.gpsLocation = new tizen.SimpleCoordinates();
- exifInfo.gpsLocation.latitude = _calculateDegDecimal(exifInfoNative.gpsLatitudeDegrees,
- exifInfoNative.gpsLatitudeMinutes, exifInfoNative.gpsLatitudeSeconds);
- exifInfo.gpsLocation.longitude = _calculateDegDecimal(exifInfoNative.gpsLongitudeDegrees,
- exifInfoNative.gpsLongitudeMinutes, exifInfoNative.gpsLongitudeSeconds);
-
- if (exifInfoNative.gpsLatitudeRef === 'SOUTH') {
- exifInfo.gpsLocation.latitude = -exifInfo.gpsLocation.latitude;
- } else if (exifInfoNative.gpsLatitudeRef !== 'NORTH') {
- exifInfo.gpsLocation.latitude = null; // invalid gpsLatitudeRef
+ // copy all properties that share name from
+ // exifInfoNative to exifInfo
+ var exifInfo = new tizen.ExifInformation(exifInfoNative);
+
+ // copy all remaining properties that do not share name or need extra calculations
+ if (exifInfoNative.originalTimeSeconds) {
+ exifInfo.originalTime = new Date(exifInfoNative.originalTimeSeconds * 1000);
+ }
+
+ if (parseInt(exifInfoNative.whiteBalanceValue) === 0) {
+ // 0=AUTO
+ exifInfo.whiteBalance = WhiteBalanceMode.AUTO;
+ } else if (parseInt(exifInfoNative.whiteBalanceValue) === 1) {
+ // 1=MANUAL
+ exifInfo.whiteBalance = WhiteBalanceMode.MANUAL;
+ }
+
+ // gpsLocation
+ if (
+ exifInfoNative.gpsLatitudeDegrees &&
+ exifInfoNative.gpsLongitudeDegrees &&
+ exifInfoNative.gpsLatitudeRef &&
+ exifInfoNative.gpsLongitudeRef
+ ) {
+ exifInfo.gpsLocation = new tizen.SimpleCoordinates();
+ exifInfo.gpsLocation.latitude = _calculateDegDecimal(
+ exifInfoNative.gpsLatitudeDegrees,
+ exifInfoNative.gpsLatitudeMinutes,
+ exifInfoNative.gpsLatitudeSeconds
+ );
+ exifInfo.gpsLocation.longitude = _calculateDegDecimal(
+ exifInfoNative.gpsLongitudeDegrees,
+ exifInfoNative.gpsLongitudeMinutes,
+ exifInfoNative.gpsLongitudeSeconds
+ );
+
+ if (exifInfoNative.gpsLatitudeRef === 'SOUTH') {
+ exifInfo.gpsLocation.latitude = -exifInfo.gpsLocation.latitude;
+ } else if (exifInfoNative.gpsLatitudeRef !== 'NORTH') {
+ exifInfo.gpsLocation.latitude = null; // invalid gpsLatitudeRef
+ }
+
+ if (exifInfoNative.gpsLongitudeRef === 'WEST') {
+ exifInfo.gpsLocation.longitude = -exifInfo.gpsLocation.longitude;
+ } else if (exifInfoNative.gpsLongitudeRef !== 'EAST') {
+ exifInfo.gpsLocation.longitude = null; // invalid gpsLongitudeRef
+ }
}
- if (exifInfoNative.gpsLongitudeRef === 'WEST') {
- exifInfo.gpsLocation.longitude = -exifInfo.gpsLocation.longitude;
- } else if (exifInfoNative.gpsLongitudeRef !== 'EAST') {
- exifInfo.gpsLocation.longitude = null; // invalid gpsLongitudeRef
+ // gpsAltitude
+ if (exifInfoNative.gpsAltitude && exifInfoNative.gpsAltitudeRef) {
+ if (parseInt(exifInfoNative.gpsAltitudeRef) === 0) {
+ // 0=ABOVE SEA LEVEL
+ exifInfo.gpsAltitude = exifInfoNative.gpsAltitude;
+ } else if (parseInt(exifInfoNative.gpsAltitudeRef) === 1) {
+ // 1=BELOW SEA LEVEL
+ exifInfo.gpsAltitude = -exifInfoNative.gpsAltitude;
+ }
}
- }
-
- // gpsAltitude
- if (exifInfoNative.gpsAltitude && exifInfoNative.gpsAltitudeRef) {
- if (parseInt(exifInfoNative.gpsAltitudeRef) === 0) { // 0=ABOVE SEA LEVEL
- exifInfo.gpsAltitude = exifInfoNative.gpsAltitude;
- } else if (parseInt(exifInfoNative.gpsAltitudeRef) === 1) { // 1=BELOW SEA LEVEL
- exifInfo.gpsAltitude = -exifInfoNative.gpsAltitude;
+
+ // gpsTime
+ if (exifInfoNative.gpsExifDate) {
+ var dateSplit = exifInfoNative.gpsExifDate.split(':');
+ exifInfo.gpsTime = new Date(
+ dateSplit[0], // year
+ dateSplit[1], // month
+ dateSplit[2], // day
+ exifInfoNative.gpsExifTimeHours,
+ exifInfoNative.gpsExifTimeMinutes,
+ exifInfoNative.gpsExifTimeSeconds
+ );
}
- }
-
- // gpsTime
- if (exifInfoNative.gpsExifDate) {
- var dateSplit = exifInfoNative.gpsExifDate.split(':');
- exifInfo.gpsTime = new Date(
- dateSplit[0], // year
- dateSplit[1], // month
- dateSplit[2], // day
- exifInfoNative.gpsExifTimeHours,
- exifInfoNative.gpsExifTimeMinutes,
- exifInfoNative.gpsExifTimeSeconds);
- }
-
- return exifInfo;
+
+ return exifInfo;
}
ExifManager.prototype.getExifInfo = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'uri',
- type: validator_.Types.STRING,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: validator_.Types.FUNCTION,
- optional: false,
- nullable: false
- },
- {
- name: 'errorCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'uri',
+ type: validator_.Types.STRING,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: validator_.Types.FUNCTION,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'errorCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (!_isValidAbsoluteURI(args.uri)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid URI.')
+ );
+ }, 0);
+ return;
}
- ]);
-
- if (!_isValidAbsoluteURI(args.uri)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Invalid URI.'));
- }, 0);
- return;
- }
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- // call to c++ code. Fields that do not exist are undefined.
- var exifInfoNative = native_.getResultObject(result);
- // calculate ExifInformation struct. All fields are initially null.
- // Fields that do not exist in jpg EXIF must remain null.
- var exifInfo = _calculateExifInfo(exifInfoNative);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ // call to c++ code. Fields that do not exist are undefined.
+ var exifInfoNative = native_.getResultObject(result);
- // make successCalback and pass exifInfo
- args.successCallback(exifInfo);
- }
- };
+ // calculate ExifInformation struct. All fields are initially null.
+ // Fields that do not exist in jpg EXIF must remain null.
+ var exifInfo = _calculateExifInfo(exifInfoNative);
+
+ // make successCalback and pass exifInfo
+ args.successCallback(exifInfo);
+ }
+ };
- var result = native_.call('ExifManager_getExifInfo', {'uri': args.uri}, callback);
+ var result = native_.call('ExifManager_getExifInfo', { uri: args.uri }, callback);
- if (native_.isFailure(result)) {
- // since tizen 5.0 the only possible error type here is SecurityError
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ // since tizen 5.0 the only possible error type here is SecurityError
+ throw native_.getErrorObject(result);
+ }
};
ExifManager.prototype.saveExifInfo = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'exifInfo',
- type: validator_.Types.PLATFORM_OBJECT,
- values: tizen.ExifInformation,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- if (!args.exifInfo.uri || !_isValidAbsoluteURI(args.exifInfo.uri)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Invalid URI.'));
- }, 0);
- return;
- }
-
- var json = _getJsonFromExifInformation(args.exifInfo);
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback,
- native_.getErrorObject(result));
- } else {
- var exifInfo = native_.getResultObject(result);
- args.successCallback(exifInfo);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'exifInfo',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.ExifInformation,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (!args.exifInfo.uri || !_isValidAbsoluteURI(args.exifInfo.uri)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid URI.')
+ );
+ }, 0);
+ return;
}
- };
- var result = native_.call('ExifManager_saveExifInfo', json, callback);
+ var json = _getJsonFromExifInformation(args.exifInfo);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var exifInfo = native_.getResultObject(result);
+ args.successCallback(exifInfo);
+ }
+ };
- if (native_.isFailure(result)) {
- // since tizen 5.0 the only possible error type here is SecurityError
- throw native_.getErrorObject(result);
- }
+ var result = native_.call('ExifManager_saveExifInfo', json, callback);
+
+ if (native_.isFailure(result)) {
+ // since tizen 5.0 the only possible error type here is SecurityError
+ throw native_.getErrorObject(result);
+ }
};
ExifManager.prototype.getThumbnail = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'uri',
- type: validator_.Types.STRING,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: validator_.Types.FUNCTION,
- optional: false,
- nullable: false
- },
- {
- name: 'errorCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- if (!_isValidAbsoluteURI(args.uri)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Invalid URI.'));
- }, 0);
- return;
- }
-
- var _callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback,
- native_.getErrorObject(result));
- } else {
- var thumb = native_.getResultObject(result);
- args.successCallback(thumb.src);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'uri',
+ type: validator_.Types.STRING,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: validator_.Types.FUNCTION,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'errorCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (!_isValidAbsoluteURI(args.uri)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid URI.')
+ );
+ }, 0);
+ return;
}
- };
- var result = native_.call('ExifManager_getThumbnail', {'uri': args.uri}, _callback);
+ var _callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var thumb = native_.getResultObject(result);
+ args.successCallback(thumb.src);
+ }
+ };
+
+ var result = native_.call('ExifManager_getThumbnail', { uri: args.uri }, _callback);
- if (native_.isFailure(result)) {
- // since tizen 5.0 the only possible error type here is SecurityError
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ // since tizen 5.0 the only possible error type here is SecurityError
+ throw native_.getErrorObject(result);
+ }
};
tizen.ExifInformation = function(exifInitDict) {
- validator_.isConstructorCall(this, tizen.ExifInformation);
-
- var uri_ = '',
- width_ = null,
- height_ = null,
- deviceMaker_ = null,
- deviceModel_ = null,
- originalTime_ = null,
- orientation_ = null,
- fNumber_ = null,
- isoSpeedRatings_ = null,
- exposureTime_ = null,
- exposureProgram_ = null,
- flash_ = null,
- focalLength_ = null,
- whiteBalance_ = null,
- gpsLocation_ = null,
- gpsAltitude_ = null,
- gpsProcessingMethod_ = null,
- gpsTime_ = null,
- userComment_ = null;
-
- Object.defineProperties(this, {
- uri: {
- get: function() {
- return uri_;
- },
- set: function(v) {
- uri_ = v ? converter_.toString(v) : uri_;
- },
- enumerable: true
- },
- width: {
- get: function() {
- return width_;
- },
- set: function(v) {
- width_ = (!type_.isUndefined(v)) ? converter_.toLong(v, true) : width_;
- },
- enumerable: true
- },
- height: {
- get: function() {
- return height_;
- },
- set: function(v) {
- height_ = (!type_.isUndefined(v)) ? converter_.toLong(v, true) : height_;
- },
- enumerable: true
- },
- deviceMaker: {
- get: function() {
- return deviceMaker_;
- },
- set: function(v) {
- deviceMaker_ = (!type_.isUndefined(v)) ?
- converter_.toString(v, true) : deviceMaker_;
- },
- enumerable: true
- },
- deviceModel: {
- get: function() {
- return deviceModel_;
- },
- set: function(v) {
- deviceModel_ = (!type_.isUndefined(v)) ?
- converter_.toString(v, true) : deviceModel_;
- },
- enumerable: true
- },
- originalTime: {
- get: function() {
- return originalTime_;
- },
- set: function(v) {
- if (!type_.isUndefined(v)) {
- if (v === null || v instanceof Date) originalTime_ = v;
- }
- },
- enumerable: true
- },
- orientation: {
- get: function() {
- return orientation_;
- },
- set: function(v) {
- orientation_ = (!type_.isUndefined(v)) ?
- converter_.toEnum(v, Object.keys(ImageContentOrientation), true) : orientation_;
- },
- enumerable: true
- },
- fNumber: {
- get: function() {
- return fNumber_;
- },
- set: function(v) {
- fNumber_ = (!type_.isUndefined(v)) ? converter_.toDouble(v, true) : fNumber_;
- },
- enumerable: true
- },
- isoSpeedRatings: {
- get: function() {
- return isoSpeedRatings_;
- },
- set: function(v) {
- if (!type_.isUndefined(v)) {
- if (v === null) {
- isoSpeedRatings_ = null;
- } else if (type_.isArray(v)) {
- for (var i = 0; i < v.length; i++) {
- v[i] = converter_.toUnsignedShort(v[i], false);
+ validator_.isConstructorCall(this, tizen.ExifInformation);
+
+ var uri_ = '',
+ width_ = null,
+ height_ = null,
+ deviceMaker_ = null,
+ deviceModel_ = null,
+ originalTime_ = null,
+ orientation_ = null,
+ fNumber_ = null,
+ isoSpeedRatings_ = null,
+ exposureTime_ = null,
+ exposureProgram_ = null,
+ flash_ = null,
+ focalLength_ = null,
+ whiteBalance_ = null,
+ gpsLocation_ = null,
+ gpsAltitude_ = null,
+ gpsProcessingMethod_ = null,
+ gpsTime_ = null,
+ userComment_ = null;
+
+ Object.defineProperties(this, {
+ uri: {
+ get: function() {
+ return uri_;
+ },
+ set: function(v) {
+ uri_ = v ? converter_.toString(v) : uri_;
+ },
+ enumerable: true
+ },
+ width: {
+ get: function() {
+ return width_;
+ },
+ set: function(v) {
+ width_ = !type_.isUndefined(v) ? converter_.toLong(v, true) : width_;
+ },
+ enumerable: true
+ },
+ height: {
+ get: function() {
+ return height_;
+ },
+ set: function(v) {
+ height_ = !type_.isUndefined(v) ? converter_.toLong(v, true) : height_;
+ },
+ enumerable: true
+ },
+ deviceMaker: {
+ get: function() {
+ return deviceMaker_;
+ },
+ set: function(v) {
+ deviceMaker_ = !type_.isUndefined(v)
+ ? converter_.toString(v, true)
+ : deviceMaker_;
+ },
+ enumerable: true
+ },
+ deviceModel: {
+ get: function() {
+ return deviceModel_;
+ },
+ set: function(v) {
+ deviceModel_ = !type_.isUndefined(v)
+ ? converter_.toString(v, true)
+ : deviceModel_;
+ },
+ enumerable: true
+ },
+ originalTime: {
+ get: function() {
+ return originalTime_;
+ },
+ set: function(v) {
+ if (!type_.isUndefined(v)) {
+ if (v === null || v instanceof Date) originalTime_ = v;
+ }
+ },
+ enumerable: true
+ },
+ orientation: {
+ get: function() {
+ return orientation_;
+ },
+ set: function(v) {
+ orientation_ = !type_.isUndefined(v)
+ ? converter_.toEnum(v, Object.keys(ImageContentOrientation), true)
+ : orientation_;
+ },
+ enumerable: true
+ },
+ fNumber: {
+ get: function() {
+ return fNumber_;
+ },
+ set: function(v) {
+ fNumber_ = !type_.isUndefined(v)
+ ? converter_.toDouble(v, true)
+ : fNumber_;
+ },
+ enumerable: true
+ },
+ isoSpeedRatings: {
+ get: function() {
+ return isoSpeedRatings_;
+ },
+ set: function(v) {
+ if (!type_.isUndefined(v)) {
+ if (v === null) {
+ isoSpeedRatings_ = null;
+ } else if (type_.isArray(v)) {
+ for (var i = 0; i < v.length; i++) {
+ v[i] = converter_.toUnsignedShort(v[i], false);
+ }
+ isoSpeedRatings_ = v;
+ }
+ }
+ },
+ enumerable: true
+ },
+ exposureTime: {
+ get: function() {
+ return exposureTime_;
+ },
+ set: function(v) {
+ exposureTime_ = !type_.isUndefined(v)
+ ? converter_.toString(v, true)
+ : exposureTime_;
+ },
+ enumerable: true
+ },
+ exposureProgram: {
+ get: function() {
+ return exposureProgram_;
+ },
+ set: function(v) {
+ exposureProgram_ = !type_.isUndefined(v)
+ ? converter_.toEnum(v, Object.keys(ExposureProgram), true)
+ : exposureProgram_;
+ },
+ enumerable: true
+ },
+ flash: {
+ get: function() {
+ return flash_;
+ },
+ set: function(v) {
+ flash_ = converter_.toBoolean(v, true);
+ },
+ enumerable: true
+ },
+ focalLength: {
+ get: function() {
+ return focalLength_;
+ },
+ set: function(v) {
+ focalLength_ = !type_.isUndefined(v)
+ ? converter_.toDouble(v, true)
+ : focalLength_;
+ },
+ enumerable: true
+ },
+ whiteBalance: {
+ get: function() {
+ return whiteBalance_;
+ },
+ set: function(v) {
+ whiteBalance_ = !type_.isUndefined(v)
+ ? converter_.toEnum(v, Object.keys(WhiteBalanceMode), true)
+ : whiteBalance_;
+ },
+ enumerable: true
+ },
+ gpsLocation: {
+ get: function() {
+ return gpsLocation_;
+ },
+ set: function(v) {
+ if (!type_.isUndefined(v)) {
+ if (v === null || v instanceof tizen.SimpleCoordinates)
+ gpsLocation_ = v;
+ }
+ },
+ enumerable: true
+ },
+ gpsAltitude: {
+ get: function() {
+ return gpsAltitude_;
+ },
+ set: function(v) {
+ gpsAltitude_ = !type_.isUndefined(v)
+ ? converter_.toDouble(v, true)
+ : gpsAltitude_;
+ },
+ enumerable: true
+ },
+ gpsProcessingMethod: {
+ get: function() {
+ return gpsProcessingMethod_;
+ },
+ set: function(v) {
+ gpsProcessingMethod_ = !type_.isUndefined(v)
+ ? converter_.toString(v, true)
+ : gpsProcessingMethod_;
+ },
+ enumerable: true
+ },
+ gpsTime: {
+ enumerable: true,
+ get: function() {
+ return gpsTime_;
+ },
+ set: function(v) {
+ if (!type_.isUndefined(v)) {
+ if (v === null || v instanceof Date || v instanceof tizen.TZDate)
+ gpsTime_ = v;
+ }
+ }
+ },
+ userComment: {
+ enumerable: true,
+ get: function() {
+ return userComment_;
+ },
+ set: function(v) {
+ userComment_ = !type_.isUndefined(v)
+ ? converter_.toString(v, true)
+ : userComment_;
}
- isoSpeedRatings_ = v;
- }
- }
- },
- enumerable: true
- },
- exposureTime: {
- get: function() {
- return exposureTime_;
- },
- set: function(v) {
- exposureTime_ = (!type_.isUndefined(v)) ?
- converter_.toString(v, true) : exposureTime_;
- },
- enumerable: true
- },
- exposureProgram: {
- get: function() {
- return exposureProgram_;
- },
- set: function(v) {
- exposureProgram_ = (!type_.isUndefined(v)) ?
- converter_.toEnum(v, Object.keys(ExposureProgram), true) : exposureProgram_;
- },
- enumerable: true
- },
- flash: {
- get: function() {
- return flash_;
- },
- set: function(v) {
- flash_ = converter_.toBoolean(v, true);
- },
- enumerable: true
- },
- focalLength: {
- get: function() {
- return focalLength_;
- },
- set: function(v) {
- focalLength_ = (!type_.isUndefined(v)) ?
- converter_.toDouble(v, true) : focalLength_;
- },
- enumerable: true
- },
- whiteBalance: {
- get: function() {
- return whiteBalance_;
- },
- set: function(v) {
- whiteBalance_ = (!type_.isUndefined(v)) ?
- converter_.toEnum(v, Object.keys(WhiteBalanceMode), true) : whiteBalance_;
- },
- enumerable: true
- },
- gpsLocation: {
- get: function() {
- return gpsLocation_;
- },
- set: function(v) {
- if (!type_.isUndefined(v)) {
- if (v === null || v instanceof tizen.SimpleCoordinates) gpsLocation_ = v;
}
- },
- enumerable: true
- },
- gpsAltitude: {
- get: function() {
- return gpsAltitude_;
- },
- set: function(v) {
- gpsAltitude_ = (!type_.isUndefined(v)) ?
- converter_.toDouble(v, true) : gpsAltitude_;
- },
- enumerable: true
- },
- gpsProcessingMethod: {
- get: function() {
- return gpsProcessingMethod_;
- },
- set: function(v) {
- gpsProcessingMethod_ = (!type_.isUndefined(v)) ?
- converter_.toString(v, true) : gpsProcessingMethod_;
- },
- enumerable: true
- },
- gpsTime: {
- enumerable: true,
- get: function() {
- return gpsTime_;
- },
- set: function(v) {
- if (!type_.isUndefined(v)) {
- if (v === null || v instanceof Date || v instanceof tizen.TZDate) gpsTime_ = v;
+ });
+
+ //--- copy values from exifInitDict using setters above.
+ if (exifInitDict instanceof _global.Object) {
+ for (var prop in exifInitDict) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = exifInitDict[prop];
+ }
}
- }
- },
- userComment: {
- enumerable: true,
- get: function() {
- return userComment_;
- },
- set: function(v) {
- userComment_ = (!type_.isUndefined(v)) ?
- converter_.toString(v, true) : userComment_;
- }
- }
- });
-
- //--- copy values from exifInitDict using setters above.
- if (exifInitDict instanceof _global.Object) {
- for (var prop in exifInitDict) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = exifInitDict[prop];
- }
}
- }
};
exports = new ExifManager();
diff --git a/src/feedback/feedback_api.js b/src/feedback/feedback_api.js
index c19fbee1..378d91ca 100755
--- a/src/feedback/feedback_api.js
+++ b/src/feedback/feedback_api.js
@@ -26,99 +26,98 @@ var FeedbackType = {
};
var FeedbackPattern = {
- TAP: 'TAP',
- SIP: 'SIP',
- KEY0: 'KEY0',
- KEY1: 'KEY1',
- KEY2: 'KEY2',
- KEY3: 'KEY3',
- KEY4: 'KEY4',
- KEY5: 'KEY5',
- KEY6: 'KEY6',
- KEY7: 'KEY7',
- KEY8: 'KEY8',
- KEY9: 'KEY9',
- KEY_STAR: 'KEY_STAR',
- KEY_SHARP: 'KEY_SHARP',
- KEY_BACK: 'KEY_BACK',
- HOLD: 'HOLD',
- HW_TAP: 'HW_TAP',
- HW_HOLD: 'HW_HOLD',
- MESSAGE: 'MESSAGE',
- EMAIL: 'EMAIL',
- WAKEUP: 'WAKEUP',
- SCHEDULE: 'SCHEDULE',
- TIMER: 'TIMER',
- GENERAL: 'GENERAL',
- POWERON: 'POWERON',
- POWEROFF: 'POWEROFF',
- CHARGERCONN: 'CHARGERCONN',
- CHARGING_ERROR: 'CHARGING_ERROR',
- FULLCHARGED: 'FULLCHARGED',
- LOWBATT: 'LOWBATT',
- LOCK: 'LOCK',
- UNLOCK: 'UNLOCK',
- VIBRATION_ON: 'VIBRATION_ON',
- SILENT_OFF: 'SILENT_OFF',
- BT_CONNECTED: 'BT_CONNECTED',
- BT_DISCONNECTED: 'BT_DISCONNECTED',
- LIST_REORDER: 'LIST_REORDER',
- LIST_SLIDER: 'LIST_SLIDER',
- VOLUME_KEY: 'VOLUME_KEY'
+ TAP: 'TAP',
+ SIP: 'SIP',
+ KEY0: 'KEY0',
+ KEY1: 'KEY1',
+ KEY2: 'KEY2',
+ KEY3: 'KEY3',
+ KEY4: 'KEY4',
+ KEY5: 'KEY5',
+ KEY6: 'KEY6',
+ KEY7: 'KEY7',
+ KEY8: 'KEY8',
+ KEY9: 'KEY9',
+ KEY_STAR: 'KEY_STAR',
+ KEY_SHARP: 'KEY_SHARP',
+ KEY_BACK: 'KEY_BACK',
+ HOLD: 'HOLD',
+ HW_TAP: 'HW_TAP',
+ HW_HOLD: 'HW_HOLD',
+ MESSAGE: 'MESSAGE',
+ EMAIL: 'EMAIL',
+ WAKEUP: 'WAKEUP',
+ SCHEDULE: 'SCHEDULE',
+ TIMER: 'TIMER',
+ GENERAL: 'GENERAL',
+ POWERON: 'POWERON',
+ POWEROFF: 'POWEROFF',
+ CHARGERCONN: 'CHARGERCONN',
+ CHARGING_ERROR: 'CHARGING_ERROR',
+ FULLCHARGED: 'FULLCHARGED',
+ LOWBATT: 'LOWBATT',
+ LOCK: 'LOCK',
+ UNLOCK: 'UNLOCK',
+ VIBRATION_ON: 'VIBRATION_ON',
+ SILENT_OFF: 'SILENT_OFF',
+ BT_CONNECTED: 'BT_CONNECTED',
+ BT_DISCONNECTED: 'BT_DISCONNECTED',
+ LIST_REORDER: 'LIST_REORDER',
+ LIST_SLIDER: 'LIST_SLIDER',
+ VOLUME_KEY: 'VOLUME_KEY'
};
function FeedbackManager() {
- // constructor of FeedbackManager
+ // constructor of FeedbackManager
}
-
FeedbackManager.prototype.isPatternSupported = function(pattern, type) {
- var args = validator_.validateArgs(arguments, [
- {name: 'pattern', type: types_.ENUM, values: Object.keys(FeedbackPattern)},
- {name: 'type', type: types_.ENUM, values: Object.keys(FeedbackType)},
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'pattern', type: types_.ENUM, values: Object.keys(FeedbackPattern) },
+ { name: 'type', type: types_.ENUM, values: Object.keys(FeedbackType) }
+ ]);
- var result = native_.callSync('FeedbackManager_isPatternSupported', args);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
+ var result = native_.callSync('FeedbackManager_isPatternSupported', args);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
};
FeedbackManager.prototype.play = function(pattern, type) {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'pattern',
- type: types_.ENUM,
- values: Object.keys(FeedbackPattern)
- },
- {
- name: 'type',
- type: types_.ENUM,
- values: Object.keys(FeedbackType),
- optional : true,
- nullable : true
- },
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'pattern',
+ type: types_.ENUM,
+ values: Object.keys(FeedbackPattern)
+ },
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(FeedbackType),
+ optional: true,
+ nullable: true
+ }
+ ]);
- var nativeParam = {
- 'pattern': args.pattern,
- 'type': args.type ? args.type : 'any'
- };
+ var nativeParam = {
+ pattern: args.pattern,
+ type: args.type ? args.type : 'any'
+ };
- var result = native_.callSync('FeedbackManager_play', nativeParam);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('FeedbackManager_play', nativeParam);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FeedbackManager.prototype.stop = function() {
- var args = validator_.validateArgs(arguments, []);
+ var args = validator_.validateArgs(arguments, []);
- var result = native_.callSync('FeedbackManager_stop', args);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('FeedbackManager_stop', args);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
exports = new FeedbackManager();
diff --git a/src/filesystem/js/base64.js b/src/filesystem/js/base64.js
index 0952f239..b4ca7edd 100755
--- a/src/filesystem/js/base64.js
+++ b/src/filesystem/js/base64.js
@@ -15,30 +15,30 @@
*/
function base64_encode(data) {
- var _b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
- var output = '';
- var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
- var i = 0;
+ var _b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
+ var output = '';
+ var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
+ var i = 0;
- while (i < data.length) {
- chr1 = data[i++];
- chr2 = data[i++];
- chr3 = data[i++];
+ while (i < data.length) {
+ chr1 = data[i++];
+ chr2 = data[i++];
+ chr3 = data[i++];
- enc1 = chr1 >> 2;
- enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
- enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
- enc4 = chr3 & 63;
+ enc1 = chr1 >> 2;
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+ enc4 = chr3 & 63;
- if (isNaN(chr2)) {
- enc3 = enc4 = 64;
- } else if (isNaN(chr3)) {
- enc4 = 64;
- }
+ if (isNaN(chr2)) {
+ enc3 = enc4 = 64;
+ } else if (isNaN(chr3)) {
+ enc4 = 64;
+ }
- output += _b64.charAt(enc1) + _b64.charAt(enc2) +
- _b64.charAt(enc3) + _b64.charAt(enc4);
- }
+ output +=
+ _b64.charAt(enc1) + _b64.charAt(enc2) + _b64.charAt(enc3) + _b64.charAt(enc4);
+ }
- return output;
+ return output;
}
diff --git a/src/filesystem/js/common.js b/src/filesystem/js/common.js
index 61ffe4f5..f90e6537 100644
--- a/src/filesystem/js/common.js
+++ b/src/filesystem/js/common.js
@@ -28,12 +28,12 @@ var native_ = new xwalk.utils.NativeManager(extension);
* Useful for passing data through crosswalk.
*/
function StringToArray(str, type) {
- var len = str.length;
- var output = new type(len);
- for (var i = 0; i < len; i++) {
- output[i] = str.charCodeAt(i);
- }
- return output;
+ var len = str.length;
+ var output = new type(len);
+ for (var i = 0; i < len; i++) {
+ output[i] = str.charCodeAt(i);
+ }
+ return output;
}
/*
@@ -42,29 +42,29 @@ function StringToArray(str, type) {
* Useful for passing data through crosswalk.
*/
function ArrayToString(data) {
- var output = '';
- var len = data.length;
- for (var i = 0; i < len; i++) {
- output += String.fromCharCode(data[i] & 0xFF); // conversion to octet
- }
- return output;
+ var output = '';
+ var len = data.length;
+ for (var i = 0; i < len; i++) {
+ output += String.fromCharCode(data[i] & 0xff); // conversion to octet
+ }
+ return output;
}
function SetReadOnlyProperty(obj, n, v) {
- Object.defineProperty(obj, n, {value: v, writable: false});
+ Object.defineProperty(obj, n, { value: v, writable: false });
}
-var FileSystemStorageType = {INTERNAL: 'INTERNAL', EXTERNAL: 'EXTERNAL'};
+var FileSystemStorageType = { INTERNAL: 'INTERNAL', EXTERNAL: 'EXTERNAL' };
var FileSystemStorageState = {
- MOUNTED: 'MOUNTED',
- REMOVED: 'REMOVED',
- UNMOUNTABLE: 'UNMOUNTABLE'
+ MOUNTED: 'MOUNTED',
+ REMOVED: 'REMOVED',
+ UNMOUNTABLE: 'UNMOUNTABLE'
};
-var FileMode = {a: 'a', r: 'r', rw: 'rw', rwo: 'rwo', w: 'w'};
+var FileMode = { a: 'a', r: 'r', rw: 'rw', rwo: 'rwo', w: 'w' };
-var BaseSeekPosition = {BEGIN: 'BEGIN', CURRENT: 'CURRENT', END: 'END'};
+var BaseSeekPosition = { BEGIN: 'BEGIN', CURRENT: 'CURRENT', END: 'END' };
var tizen24home = '/opt/usr/media';
@@ -73,365 +73,388 @@ var tizen24home = '/opt/usr/media';
var kVirtualRootImages = 'images';
var commonFS_ = (function() {
- var cacheReady = false;
- var listenerRegistered = false;
- var cacheVirtualToReal = {};
- var cacheStorages = [];
- var uriPrefix = 'file://';
- // special condition for previous versions paths
- // (global paths usage issue workaround)
- var isAppForEarlierVersion = privUtils_.isAppVersionEarlierThan('3.0');
- var homeDir = undefined;
-
- function clearCache() {
- cacheVirtualToReal = {};
- cacheStorages = [];
- cacheReady = false;
- }
-
- // initalize home directory for correct mapping global paths from tizen 2.4
- // (global paths usage issue workaround)
- function initHomeDir(aPath) {
- if (homeDir || !isAppForEarlierVersion) {
- return;
- }
- var imagesPath = cacheVirtualToReal[kVirtualRootImages].path;
-
- if (imagesPath[imagesPath.length - 1] === '/') {
- homeDir = imagesPath.split('/').slice(0, -2).join('/');
- } else {
- homeDir = imagesPath.split('/').slice(0, -1).join('/');
- }
- }
+ var cacheReady = false;
+ var listenerRegistered = false;
+ var cacheVirtualToReal = {};
+ var cacheStorages = [];
+ var uriPrefix = 'file://';
+ // special condition for previous versions paths
+ // (global paths usage issue workaround)
+ var isAppForEarlierVersion = privUtils_.isAppVersionEarlierThan('3.0');
+ var homeDir = undefined;
- function initCache() {
- if (cacheReady) {
- return;
+ function clearCache() {
+ cacheVirtualToReal = {};
+ cacheStorages = [];
+ cacheReady = false;
}
- var result = native_.callSync('Filesystem_fetchVirtualRoots', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var virtualRoots = native_.getResultObject(result);
-
- for (var i = 0; i < virtualRoots.length; ++i) {
- cacheVirtualToReal[virtualRoots[i].name] = {
- path: virtualRoots[i].path,
- label: virtualRoots[i].name,
- type: FileSystemStorageType.INTERNAL,
- state: FileSystemStorageState.MOUNTED
- };
- }
// initalize home directory for correct mapping global paths from tizen 2.4
// (global paths usage issue workaround)
- initHomeDir();
-
- var result = native_.callSync('FileSystemManager_fetchStorages', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- var storages = native_.getResultObject(result);
- for (var i = 0; i < storages.length; ++i) {
- cacheStorages.push({
- path: storages[i].path,
- label: storages[i].name,
- type: storages[i].type,
- state: storages[i].state,
- storage_id: storages[i].storage_id
- });
+ function initHomeDir(aPath) {
+ if (homeDir || !isAppForEarlierVersion) {
+ return;
+ }
+ var imagesPath = cacheVirtualToReal[kVirtualRootImages].path;
+
+ if (imagesPath[imagesPath.length - 1] === '/') {
+ homeDir = imagesPath
+ .split('/')
+ .slice(0, -2)
+ .join('/');
+ } else {
+ homeDir = imagesPath
+ .split('/')
+ .slice(0, -1)
+ .join('/');
+ }
}
- if (!listenerRegistered) {
- try {
- tizen.filesystem.addStorageStateChangeListener(function() {
- clearCache();
- });
- listenerRegistered = true;
- } catch (e) {
- privUtils_.log(
- 'Failed to register storage change listener, ' +
- 'storage information may be corrupted: ' + e.message);
- }
- }
+ function initCache() {
+ if (cacheReady) {
+ return;
+ }
- cacheReady = true;
- }
+ var result = native_.callSync('Filesystem_fetchVirtualRoots', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var virtualRoots = native_.getResultObject(result);
+
+ for (var i = 0; i < virtualRoots.length; ++i) {
+ cacheVirtualToReal[virtualRoots[i].name] = {
+ path: virtualRoots[i].path,
+ label: virtualRoots[i].name,
+ type: FileSystemStorageType.INTERNAL,
+ state: FileSystemStorageState.MOUNTED
+ };
+ }
+ // initalize home directory for correct mapping global paths from tizen 2.4
+ // (global paths usage issue workaround)
+ initHomeDir();
- function mergeMultipleSlashes(str) {
- var retStr = str.replace(/(^(file\:\/\/\/)|^(file\:\/\/)|\/)\/{0,}/g, '$1');
- return retStr;
- }
+ var result = native_.callSync('FileSystemManager_fetchStorages', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- function removeDotsFromPath(str) {
- if (str === undefined) {
- return str;
- }
+ var storages = native_.getResultObject(result);
+ for (var i = 0; i < storages.length; ++i) {
+ cacheStorages.push({
+ path: storages[i].path,
+ label: storages[i].name,
+ type: storages[i].type,
+ state: storages[i].state,
+ storage_id: storages[i].storage_id
+ });
+ }
- var _pathTokens = str.split('/');
- var _correctDir = [];
- var _fileRealPath = _pathTokens[0];
- _correctDir.push(_pathTokens[0]);
- for (var i = 1; i < _pathTokens.length; ++i) {
- if (_pathTokens[i] == '..') {
- if (_fileRealPath == '') {
- _fileRealPath = undefined;
- break;
+ if (!listenerRegistered) {
+ try {
+ tizen.filesystem.addStorageStateChangeListener(function() {
+ clearCache();
+ });
+ listenerRegistered = true;
+ } catch (e) {
+ privUtils_.log(
+ 'Failed to register storage change listener, ' +
+ 'storage information may be corrupted: ' +
+ e.message
+ );
+ }
}
- var _lastDir = _correctDir.pop();
- _fileRealPath =
- _fileRealPath.substring(0, _fileRealPath.length - _lastDir.length - 1);
- } else if (_pathTokens[i] != '.') {
- _fileRealPath += '/' + _pathTokens[i];
- _correctDir.push(_pathTokens[i]);
- }
- }
- return _fileRealPath;
- }
- function checkPathWithoutDots(aPath) {
- if (-1 !== aPath.indexOf('/../')) {
- return false;
+ cacheReady = true;
}
- if (-1 !== aPath.indexOf('/./')) {
- return false;
+
+ function mergeMultipleSlashes(str) {
+ var retStr = str.replace(/(^(file\:\/\/\/)|^(file\:\/\/)|\/)\/{0,}/g, '$1');
+ return retStr;
}
- // check if path ends with '/.' or '/..'
- if (aPath.match(/\/\.\.?$/)) {
- return false;
+
+ function removeDotsFromPath(str) {
+ if (str === undefined) {
+ return str;
+ }
+
+ var _pathTokens = str.split('/');
+ var _correctDir = [];
+ var _fileRealPath = _pathTokens[0];
+ _correctDir.push(_pathTokens[0]);
+ for (var i = 1; i < _pathTokens.length; ++i) {
+ if (_pathTokens[i] == '..') {
+ if (_fileRealPath == '') {
+ _fileRealPath = undefined;
+ break;
+ }
+ var _lastDir = _correctDir.pop();
+ _fileRealPath = _fileRealPath.substring(
+ 0,
+ _fileRealPath.length - _lastDir.length - 1
+ );
+ } else if (_pathTokens[i] != '.') {
+ _fileRealPath += '/' + _pathTokens[i];
+ _correctDir.push(_pathTokens[i]);
+ }
+ }
+ return _fileRealPath;
}
- // check if path starts with './' or '../'
- if (aPath.match(/^\.\.?\//)) {
- return false;
+
+ function checkPathWithoutDots(aPath) {
+ if (-1 !== aPath.indexOf('/../')) {
+ return false;
+ }
+ if (-1 !== aPath.indexOf('/./')) {
+ return false;
+ }
+ // check if path ends with '/.' or '/..'
+ if (aPath.match(/\/\.\.?$/)) {
+ return false;
+ }
+ // check if path starts with './' or '../'
+ if (aPath.match(/^\.\.?\//)) {
+ return false;
+ }
+ return true;
}
- return true;
- }
-
- function convertForEarlierVersionPath(aPath) {
- if (isAppForEarlierVersion) {
- if (aPath && aPath.indexOf(tizen24home) === 0) {
- privUtils_.log('Converting 2.4 style path to 3.0 pattern');
- aPath = homeDir + aPath.substr(tizen24home.length);
- }
+
+ function convertForEarlierVersionPath(aPath) {
+ if (isAppForEarlierVersion) {
+ if (aPath && aPath.indexOf(tizen24home) === 0) {
+ privUtils_.log('Converting 2.4 style path to 3.0 pattern');
+ aPath = homeDir + aPath.substr(tizen24home.length);
+ }
+ }
+ return aPath;
}
- return aPath;
- }
- function toRealPath(aPath) {
- var _fileRealPath = '';
+ function toRealPath(aPath) {
+ var _fileRealPath = '';
+
+ aPath = mergeMultipleSlashes(aPath);
+
+ if (aPath.indexOf(uriPrefix) === 0) {
+ _fileRealPath = aPath.substr(uriPrefix.length);
+ } else if (aPath[0] !== '/') {
+ // virtual path
+ initCache();
+
+ var _pathTokens = aPath.split('/');
+
+ if (cacheVirtualToReal[_pathTokens[0]]) {
+ _fileRealPath = cacheVirtualToReal[_pathTokens[0]].path;
+ for (var i = 1; i < _pathTokens.length; ++i) {
+ _fileRealPath += '/' + _pathTokens[i];
+ }
+ } else {
+ // If path token is not present in cache then it is invalid
+ _fileRealPath = undefined;
+ // check storages
+ for (var j = 0; j < cacheStorages.length; ++j) {
+ if (cacheStorages[j].label === _pathTokens[0]) {
+ _fileRealPath = cacheStorages[j].path;
+ for (var i = 1; i < _pathTokens.length; ++i) {
+ _fileRealPath += '/' + _pathTokens[i];
+ }
+ break;
+ }
+ }
+ }
+ } else {
+ _fileRealPath = aPath;
+ }
+ // removeDotsFromPath execution here, results with '.' and '..' beeing
+ // supported in paths, next methods throw an error when getting argument
+ // with '.' or '..' in it
+ // (see commonFS_.checkPathWithoutDots() method)
+ _fileRealPath = removeDotsFromPath(_fileRealPath);
+ // convert path to be compatibile with previous version of Tizen
+ // (global paths usage issue workaround)
+ _fileRealPath = convertForEarlierVersionPath(_fileRealPath);
+ // if path is valid try to cut last '/' if it is present
+ if (_fileRealPath) {
+ _fileRealPath = mergeMultipleSlashes(_fileRealPath);
+ }
+ return _fileRealPath;
+ }
- aPath = mergeMultipleSlashes(aPath);
+ function toVirtualPath(aPath) {
+ aPath = mergeMultipleSlashes(aPath);
+ var _virtualPath = aPath;
- if (aPath.indexOf(uriPrefix) === 0) {
- _fileRealPath = aPath.substr(uriPrefix.length);
- } else if (aPath[0] !== '/') {
- // virtual path
- initCache();
+ if (_virtualPath.indexOf(uriPrefix) === 0) {
+ _virtualPath = _virtualPath.substr(uriPrefix.length);
+ }
- var _pathTokens = aPath.split('/');
+ initCache();
- if (cacheVirtualToReal[_pathTokens[0]]) {
- _fileRealPath = cacheVirtualToReal[_pathTokens[0]].path;
- for (var i = 1; i < _pathTokens.length; ++i) {
- _fileRealPath += '/' + _pathTokens[i];
- }
- } else {
- // If path token is not present in cache then it is invalid
- _fileRealPath = undefined;
- // check storages
- for (var j = 0; j < cacheStorages.length; ++j) {
- if (cacheStorages[j].label === _pathTokens[0]) {
- _fileRealPath = cacheStorages[j].path;
- for (var i = 1; i < _pathTokens.length; ++i) {
- _fileRealPath += '/' + _pathTokens[i];
+ for (var virtual_root in cacheVirtualToReal) {
+ var real_root_path = cacheVirtualToReal[virtual_root].path;
+ if (_virtualPath.indexOf(real_root_path, 0) === 0) {
+ return _virtualPath.replace(real_root_path, virtual_root);
}
- break;
- }
}
- }
- } else {
- _fileRealPath = aPath;
- }
- // removeDotsFromPath execution here, results with '.' and '..' beeing supported in
- // paths, next methods throw an error when getting argument with '.' or '..' in it
- // (see commonFS_.checkPathWithoutDots() method)
- _fileRealPath = removeDotsFromPath(_fileRealPath);
- // convert path to be compatibile with previous version of Tizen
- // (global paths usage issue workaround)
- _fileRealPath = convertForEarlierVersionPath(_fileRealPath);
- // if path is valid try to cut last '/' if it is present
- if (_fileRealPath) {
- _fileRealPath = mergeMultipleSlashes(_fileRealPath);
+
+ return _virtualPath;
}
- return _fileRealPath;
- }
- function toVirtualPath(aPath) {
- aPath = mergeMultipleSlashes(aPath);
- var _virtualPath = aPath;
+ function getFileInfo(aStatObj, secondIter, aMode) {
+ var _result = {},
+ _pathTokens,
+ _fileParentPath = '',
+ i;
+ var aPath = toVirtualPath(aStatObj.path);
+
+ _result.readOnly = aStatObj.readOnly;
+ _result.isFile = aStatObj.isFile;
+ _result.isDirectory = aStatObj.isDirectory;
+ _result.created = new Date(aStatObj.ctime * 1000);
+ _result.modified = new Date(aStatObj.mtime * 1000);
+ _result.fullPath = aPath;
+ _result.fileSize = aStatObj.size;
+ _result.mode = aMode;
+ if (_result.isDirectory) {
+ try {
+ _result.length = aStatObj.nlink;
+ } catch (err) {
+ _result.length = 0;
+ }
+ } else {
+ _result.length = undefined;
+ }
- if (_virtualPath.indexOf(uriPrefix) === 0) {
- _virtualPath = _virtualPath.substr(uriPrefix.length);
+ _pathTokens = aPath.split('/');
+ if (_pathTokens.length > 1) {
+ var last = _pathTokens.length - 1;
+ var lastToken = '';
+ if (_pathTokens[last] === '') {
+ // 'abc/d/e/' case with trailing '/' sign
+ last = _pathTokens.length - 2;
+ lastToken = '/';
+ }
+ for (i = 0; i < last; ++i) {
+ _fileParentPath += _pathTokens[i] + '/';
+ }
+ if (last > 0) {
+ _result.path = _fileParentPath;
+ _result.name = secondIter
+ ? _pathTokens[last]
+ : _pathTokens[last] + lastToken;
+ _result.parent = secondIter ? null : _fileParentPath;
+ } else {
+ // '/' dir case
+ _result.path = _pathTokens[last] + lastToken;
+ _result.name = '';
+ _result.parent = secondIter ? null : _fileParentPath;
+ }
+ } else {
+ _result.parent = null;
+ _result.path = aPath;
+ _result.name = '';
+ }
+ return _result;
}
- initCache();
+ function isLocationAllowed(aPath) {
+ if (!aPath) {
+ return false;
+ }
+ initCache();
+ if (aPath.indexOf(cacheVirtualToReal.ringtones.path) === 0) {
+ return false;
+ }
+ if (aPath.indexOf(cacheVirtualToReal['wgt-package'].path) === 0) {
+ return false;
+ }
- for (var virtual_root in cacheVirtualToReal) {
- var real_root_path = cacheVirtualToReal[virtual_root].path;
- if (_virtualPath.indexOf(real_root_path, 0) === 0) {
- return _virtualPath.replace(real_root_path, virtual_root);
- }
+ return true;
}
- return _virtualPath;
- }
-
- function getFileInfo(aStatObj, secondIter, aMode) {
- var _result = {}, _pathTokens, _fileParentPath = '', i;
- var aPath = toVirtualPath(aStatObj.path);
-
- _result.readOnly = aStatObj.readOnly;
- _result.isFile = aStatObj.isFile;
- _result.isDirectory = aStatObj.isDirectory;
- _result.created = new Date(aStatObj.ctime * 1000);
- _result.modified = new Date(aStatObj.mtime * 1000);
- _result.fullPath = aPath;
- _result.fileSize = aStatObj.size;
- _result.mode = aMode;
- if (_result.isDirectory) {
- try {
- _result.length = aStatObj.nlink;
- } catch (err) {
- _result.length = 0;
- }
- } else {
- _result.length = undefined;
- }
+ function toCanonicalPath(path) {
+ var result = native_.callSync('FileSystemManager_getCanonicalPath', {
+ path: path
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- _pathTokens = aPath.split('/');
- if (_pathTokens.length > 1) {
- var last = _pathTokens.length - 1;
- var lastToken = '';
- if (_pathTokens[last] === '') {
- // 'abc/d/e/' case with trailing '/' sign
- last = _pathTokens.length - 2;
- lastToken = '/';
- }
- for (i = 0; i < last; ++i) {
- _fileParentPath += _pathTokens[i] + '/';
- }
- if (last > 0) {
- _result.path = _fileParentPath;
- _result.name = (secondIter) ? _pathTokens[last] : _pathTokens[last] + lastToken;
- _result.parent = (secondIter) ? null : _fileParentPath;
- } else {
- // '/' dir case
- _result.path = _pathTokens[last] + lastToken;
- _result.name = '';
- _result.parent = (secondIter) ? null : _fileParentPath;
- }
- } else {
- _result.parent = null;
- _result.path = aPath;
- _result.name = '';
+ return native_.getResultObject(result);
}
- return _result;
- }
- function isLocationAllowed(aPath) {
- if (!aPath) {
- return false;
- }
- initCache();
- if (aPath.indexOf(cacheVirtualToReal.ringtones.path) === 0) {
- return false;
- }
- if (aPath.indexOf(cacheVirtualToReal['wgt-package'].path) === 0) {
- return false;
- }
+ function f_isSubDir(fullPathToCheck, fullPath) {
+ var fullCanonicalPathToCheck = toCanonicalPath(toRealPath(fullPathToCheck));
+ var fullCanonicalPath = toCanonicalPath(toRealPath(fullPath));
- return true;
- }
+ if (fullCanonicalPathToCheck === fullCanonicalPath) {
+ return false;
+ }
- function toCanonicalPath(path) {
- var result = native_.callSync('FileSystemManager_getCanonicalPath', {'path': path});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ return fullCanonicalPathToCheck.indexOf(fullCanonicalPath) === 0;
}
- return native_.getResultObject(result);
- }
-
- function f_isSubDir(fullPathToCheck, fullPath) {
- var fullCanonicalPathToCheck = toCanonicalPath(toRealPath(fullPathToCheck));
- var fullCanonicalPath = toCanonicalPath(toRealPath(fullPath));
-
- if (fullCanonicalPathToCheck === fullCanonicalPath) {
- return false;
+ function f_isCorrectRelativePath(relativePath) {
+ return (
+ 0 !== relativePath.indexOf('/') &&
+ 0 !== relativePath.indexOf('\\') &&
+ -1 === relativePath.indexOf('?') &&
+ -1 === relativePath.indexOf('*') &&
+ -1 === relativePath.indexOf(':') &&
+ -1 === relativePath.indexOf('"') &&
+ -1 === relativePath.indexOf('<') &&
+ -1 === relativePath.indexOf('>')
+ );
}
- return fullCanonicalPathToCheck.indexOf(fullCanonicalPath) === 0;
- }
-
- function f_isCorrectRelativePath(relativePath) {
- return (
- (0 !== relativePath.indexOf('/')) && (0 !== relativePath.indexOf('\\')) &&
- (-1 === relativePath.indexOf('?')) && (-1 === relativePath.indexOf('*')) &&
- (-1 === relativePath.indexOf(':')) && (-1 === relativePath.indexOf('"')) &&
- (-1 === relativePath.indexOf('<')) && (-1 === relativePath.indexOf('>')));
- };
-
- function cloneStorage(storage) {
- return {label: storage.label, type: storage.type, state: storage.state};
- }
-
- function getStorage(label) {
- initCache();
- for (var i = 0; i < cacheStorages.length; ++i) {
- if (cacheStorages[i].label === label) {
- return cloneStorage(cacheStorages[i]);
- }
+ function cloneStorage(storage) {
+ return { label: storage.label, type: storage.type, state: storage.state };
}
- for (var key in cacheVirtualToReal) {
- if (cacheVirtualToReal.hasOwnProperty(key)) {
- if (cacheVirtualToReal[key].label === label) {
- return cloneStorage(cacheVirtualToReal[key]);
+ function getStorage(label) {
+ initCache();
+ for (var i = 0; i < cacheStorages.length; ++i) {
+ if (cacheStorages[i].label === label) {
+ return cloneStorage(cacheStorages[i]);
+ }
}
- }
- }
- return null;
- }
+ for (var key in cacheVirtualToReal) {
+ if (cacheVirtualToReal.hasOwnProperty(key)) {
+ if (cacheVirtualToReal[key].label === label) {
+ return cloneStorage(cacheVirtualToReal[key]);
+ }
+ }
+ }
- function getAllStorages() {
- var ret = [];
- initCache();
- for (var i = 0; i < cacheStorages.length; ++i) {
- ret.push(cloneStorage(cacheStorages[i]));
+ return null;
}
- for (var key in cacheVirtualToReal) {
- if (cacheVirtualToReal.hasOwnProperty(key)) {
- ret.push(cloneStorage(cacheVirtualToReal[key]));
- }
+ function getAllStorages() {
+ var ret = [];
+ initCache();
+ for (var i = 0; i < cacheStorages.length; ++i) {
+ ret.push(cloneStorage(cacheStorages[i]));
+ }
+
+ for (var key in cacheVirtualToReal) {
+ if (cacheVirtualToReal.hasOwnProperty(key)) {
+ ret.push(cloneStorage(cacheVirtualToReal[key]));
+ }
+ }
+
+ return ret;
}
- return ret;
- }
-
- return {
- clearCache: clearCache,
- checkPathWithoutDots: checkPathWithoutDots,
- toRealPath: toRealPath,
- toVirtualPath: toVirtualPath,
- getFileInfo: getFileInfo,
- isLocationAllowed: isLocationAllowed,
- f_isSubDir: f_isSubDir,
- f_isCorrectRelativePath: f_isCorrectRelativePath,
- getStorage: getStorage,
- getAllStorages: getAllStorages,
- mergeMultipleSlashes: mergeMultipleSlashes
- };
+ return {
+ clearCache: clearCache,
+ checkPathWithoutDots: checkPathWithoutDots,
+ toRealPath: toRealPath,
+ toVirtualPath: toVirtualPath,
+ getFileInfo: getFileInfo,
+ isLocationAllowed: isLocationAllowed,
+ f_isSubDir: f_isSubDir,
+ f_isCorrectRelativePath: f_isCorrectRelativePath,
+ getStorage: getStorage,
+ getAllStorages: getAllStorages,
+ mergeMultipleSlashes: mergeMultipleSlashes
+ };
})();
diff --git a/src/filesystem/js/file.js b/src/filesystem/js/file.js
index 0885dead..0848a8d2 100644
--- a/src/filesystem/js/file.js
+++ b/src/filesystem/js/file.js
@@ -15,984 +15,1193 @@
*/
function File(data) {
- function fileSizeGetter() {
- var _realPath = commonFS_.toRealPath(this.fullPath);
- var _result = native_.callSync('File_statSync', {location: _realPath});
- var _aStatObj = native_.getResultObject(_result);
- return _aStatObj.isFile ? _aStatObj.size : undefined;
- }
-
- Object.defineProperties(this, {
- parent: {
- value: (function(data) {
- try {
- if (data.parent) { // prevent recursive - only one parent
- var _parentPath = data.path;
- var _location = {location: commonFS_.toRealPath(_parentPath)};
- var _result = native_.callSync('File_statSync', _location);
- var _statObj = native_.getResultObject(_result);
- var _info = commonFS_.getFileInfo(_statObj, true);
- return new File(_info);
- } else {
- return null;
- }
- } catch (err) {
- privUtils_.log(err.name, err.message);
- return null;
- }
- }(data)),
- writable: false,
- enumerable: true
- },
- readOnly: {value: data.readOnly, writable: false, enumerable: true},
- isFile: {value: data.isFile, writable: false, enumerable: true},
- isDirectory: {value: data.isDirectory, writable: false, enumerable: true},
- created: {value: data.created, writable: false, enumerable: true},
- modified: {value: data.modified, writable: false, enumerable: true},
- path: {value: data.path, writable: false, enumerable: true},
- name: {value: data.name, writable: false, enumerable: true},
- fullPath: {value: data.fullPath, writable: false, enumerable: true},
- fileSize: {enumerable: true, set: function() {
- }, get: fileSizeGetter},
- length: {value: data.length, writable: false, enumerable: true},
- mode: {value: data.mode, writable: false}
- });
+ function fileSizeGetter() {
+ var _realPath = commonFS_.toRealPath(this.fullPath);
+ var _result = native_.callSync('File_statSync', { location: _realPath });
+ var _aStatObj = native_.getResultObject(_result);
+ return _aStatObj.isFile ? _aStatObj.size : undefined;
+ }
+
+ Object.defineProperties(this, {
+ parent: {
+ value: (function(data) {
+ try {
+ if (data.parent) {
+ // prevent recursive - only one parent
+ var _parentPath = data.path;
+ var _location = { location: commonFS_.toRealPath(_parentPath) };
+ var _result = native_.callSync('File_statSync', _location);
+ var _statObj = native_.getResultObject(_result);
+ var _info = commonFS_.getFileInfo(_statObj, true);
+ return new File(_info);
+ } else {
+ return null;
+ }
+ } catch (err) {
+ privUtils_.log(err.name, err.message);
+ return null;
+ }
+ })(data),
+ writable: false,
+ enumerable: true
+ },
+ readOnly: { value: data.readOnly, writable: false, enumerable: true },
+ isFile: { value: data.isFile, writable: false, enumerable: true },
+ isDirectory: { value: data.isDirectory, writable: false, enumerable: true },
+ created: { value: data.created, writable: false, enumerable: true },
+ modified: { value: data.modified, writable: false, enumerable: true },
+ path: { value: data.path, writable: false, enumerable: true },
+ name: { value: data.name, writable: false, enumerable: true },
+ fullPath: { value: data.fullPath, writable: false, enumerable: true },
+ fileSize: { enumerable: true, set: function() {}, get: fileSizeGetter },
+ length: { value: data.length, writable: false, enumerable: true },
+ mode: { value: data.mode, writable: false }
+ });
}
function toURI() {
- privUtils_.warn("DEPRECATION WARNING: File.toURI() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.toURI() instead.");
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.toURI() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.toURI() instead.'
+ );
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.FILESYSTEM_READ);
- return 'file://' + commonFS_.toRealPath(this.fullPath);
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.FILESYSTEM_READ);
+ return 'file://' + commonFS_.toRealPath(this.fullPath);
}
File.prototype.toURI = function() {
- return toURI.apply(this, arguments);
+ return toURI.apply(this, arguments);
};
function stringToRegex(str) {
- var _regString = '^';
- if (str === '') {
- return new RegExp(_regString + "$", 'i');
- }
- // single '\' sign is not visible in JS string, escaping % wildcard need to be done by '\\%'
- str = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
-
- var _percentTokens = str.split('%');
- var i;
- for (i = 0; i < _percentTokens.length - 1; ++i) {
- _regString = _regString + _percentTokens[i];
- if (_regString[_regString.length - 1] === '\\') {
- // special handling \\% sequence - '%' sign is threaten as regular sign - not wildcard
- _regString = _regString.split('');
- _regString.pop();
- _regString = _regString.join('') + '%';
- }
- else {
- // handling '%' as a wildcard
- _regString = _regString + '.*';
- }
- }
- return new RegExp(_regString + _percentTokens[i] + '$', 'i');
+ var _regString = '^';
+ if (str === '') {
+ return new RegExp(_regString + '$', 'i');
+ }
+ // single '\' sign is not visible in JS string, escaping % wildcard need to
+ // be done by '\\%'
+ str = str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
+
+ var _percentTokens = str.split('%');
+ var i;
+ for (i = 0; i < _percentTokens.length - 1; ++i) {
+ _regString = _regString + _percentTokens[i];
+ if (_regString[_regString.length - 1] === '\\') {
+ // special handling \\% sequence - '%' sign is threaten as
+ // regular sign - not wildcard
+ _regString = _regString.split('');
+ _regString.pop();
+ _regString = _regString.join('') + '%';
+ } else {
+ // handling '%' as a wildcard
+ _regString = _regString + '.*';
+ }
+ }
+ return new RegExp(_regString + _percentTokens[i] + '$', 'i');
}
-
function createFilter(fileFilter) {
- if (type_.isNull(fileFilter)) {
- return null;
- }
-
- var FileFilter = {
- name: 'name',
- startModified: 'startModified',
- endModified: 'endModified',
- startCreated: 'startCreated',
- endCreated: 'endCreated'
- };
-
- var _fileFilter = {}, i;
- for (i in fileFilter) {
- if (!type_.isNullOrUndefined(fileFilter[i])) {
- if (Object.keys(FileFilter).indexOf(i) >= 0) {
- if (FileFilter.name === i) {
- _fileFilter[i] = stringToRegex(fileFilter[i]);
- } else {
- if (!(fileFilter[i] instanceof Date)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid date');
- }
- _fileFilter[i] = fileFilter[i];
+ if (type_.isNull(fileFilter)) {
+ return null;
+ }
+
+ var FileFilter = {
+ name: 'name',
+ startModified: 'startModified',
+ endModified: 'endModified',
+ startCreated: 'startCreated',
+ endCreated: 'endCreated'
+ };
+
+ var _fileFilter = {},
+ i;
+ for (i in fileFilter) {
+ if (!type_.isNullOrUndefined(fileFilter[i])) {
+ if (Object.keys(FileFilter).indexOf(i) >= 0) {
+ if (FileFilter.name === i) {
+ _fileFilter[i] = stringToRegex(fileFilter[i]);
+ } else {
+ if (!(fileFilter[i] instanceof Date)) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid date'
+ );
+ }
+ _fileFilter[i] = fileFilter[i];
+ }
+ }
}
- }
}
- }
- return !type_.isEmptyObject(_fileFilter) ? _fileFilter : null;
+ return !type_.isEmptyObject(_fileFilter) ? _fileFilter : null;
}
function matchRange(value, min, max) {
- if (min !== undefined && value < min) {
- return false;
- }
- if (max !== undefined && value > max) {
- return false;
- }
- return true;
+ if (min !== undefined && value < min) {
+ return false;
+ }
+ if (max !== undefined && value > max) {
+ return false;
+ }
+ return true;
}
function matchName(value, filter_name) {
- if (filter_name === undefined || filter_name.test(value)) {
- return true;
- }
- return false;
+ if (filter_name === undefined || filter_name.test(value)) {
+ return true;
+ }
+ return false;
}
function checkFile(file, fileFilter) {
- if (!matchName(file.name, fileFilter.name)) {
- return false;
- }
+ if (!matchName(file.name, fileFilter.name)) {
+ return false;
+ }
- if (!matchRange(file.modified, fileFilter.startModified, fileFilter.endModified)) {
- return false;
- }
+ if (!matchRange(file.modified, fileFilter.startModified, fileFilter.endModified)) {
+ return false;
+ }
- if (!matchRange(file.created, fileFilter.startCreated, fileFilter.endCreated)) {
- return false;
- }
+ if (!matchRange(file.created, fileFilter.startCreated, fileFilter.endCreated)) {
+ return false;
+ }
- return true;
+ return true;
}
function listFiles() {
- privUtils_.warn("DEPRECATION WARNING: File.listFiles() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.listDirectory() instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'onsuccess', type: types_.FUNCTION},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'filter', type: types_.DICTIONARY, optional: true, nullable: true}
- ]);
-
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Arguments missing');
- }
- if (!this.isDirectory) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is not directory'));
- }, 0);
- return;
- }
-
- var _fileFilter = null;
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.listFiles() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.listDirectory() instead.'
+ );
- if (args.has.filter) {
- _fileFilter = createFilter(args.filter);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'filter', type: types_.DICTIONARY, optional: true, nullable: true }
+ ]);
- var _myPath = this.fullPath;
- var _realMyPath = commonFS_.toRealPath(_myPath);
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Arguments missing');
+ }
+ if (!this.isDirectory) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is not directory'
+ )
+ );
+ }, 0);
+ return;
+ }
- var data = {
- pathToDir: _realMyPath
- };
+ var _fileFilter = null;
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.onerror, native_.getErrorObject(result));
- return;
+ if (args.has.filter) {
+ _fileFilter = createFilter(args.filter);
}
- var aFiles = native_.getResultObject(result);
- var _result = [],
- i,
- _statObj,
- _fileInfo;
- for (i = 0; i < aFiles.length; ++i) {
- _statObj = aFiles[i];
- _fileInfo = commonFS_.getFileInfo(_statObj);
- if (_fileFilter === null) {
- _result.push(new File(_fileInfo));
- } else if (checkFile(_fileInfo, _fileFilter)) {
- _result.push(new File(_fileInfo));
- }
- }
- native_.callIfPossible(args.onsuccess, _result);
- };
+ var _myPath = this.fullPath;
+ var _realMyPath = commonFS_.toRealPath(_myPath);
- native_.call('File_readDir', data, callback);
-};
+ var data = {
+ pathToDir: _realMyPath
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.onerror, native_.getErrorObject(result));
+ return;
+ }
+ var aFiles = native_.getResultObject(result);
+ var _result = [],
+ i,
+ _statObj,
+ _fileInfo;
+ for (i = 0; i < aFiles.length; ++i) {
+ _statObj = aFiles[i];
+ _fileInfo = commonFS_.getFileInfo(_statObj);
+
+ if (_fileFilter === null) {
+ _result.push(new File(_fileInfo));
+ } else if (checkFile(_fileInfo, _fileFilter)) {
+ _result.push(new File(_fileInfo));
+ }
+ }
+ native_.callIfPossible(args.onsuccess, _result);
+ };
+
+ native_.call('File_readDir', data, callback);
+}
File.prototype.listFiles = function() {
- listFiles.apply(this, arguments);
+ listFiles.apply(this, arguments);
};
var Encoding = {
- 'utf-8': 'utf-8',
- 'iso-8859-1': 'iso-8859-1',
- 'sjis': 'sjis', // backward compatibility
- 'null': 'utf-8',
- 'undefined': 'utf-8' // default value
+ 'utf-8': 'utf-8',
+ 'iso-8859-1': 'iso-8859-1',
+ sjis: 'sjis', // backward compatibility
+ // prettier-ignore
+ 'null': 'utf-8',
+ // prettier-ignore
+ 'undefined': 'utf-8' // default value
};
function _checkEncoding(encoding) {
- encoding = String(encoding).toLowerCase();
- if (undefined === Encoding[encoding]) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "encoding" has invalid value: ' + encoding);
- } else {
- return Encoding[encoding];
- }
+ encoding = String(encoding).toLowerCase();
+ if (undefined === Encoding[encoding]) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "encoding" has invalid value: ' + encoding
+ );
+ } else {
+ return Encoding[encoding];
+ }
}
function openStream() {
- privUtils_.warn("DEPRECATION WARNING: File.openStream() is deprecated since Tizen 5.0. "
- + "Use FileHandle interface to read/write operations instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'mode', type: types_.ENUM, values: ['r', 'rw', 'w', 'a']},
- {name: 'onsuccess', type: types_.FUNCTION},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'encoding', type: types_.STRING, optional: true, nullable: true}
- ]);
-
- if (arguments.length < 2) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Arguments missing');
- }
- if (this.mode === 'r' && args.mode !== 'r') {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Read only mode'));
- }, 0);
- return;
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.openStream() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle interface to read/write operations instead.'
+ );
- if (this.isDirectory) {
- var directoryMessage = 'This method should be called on file, not directory';
- setTimeout(function() {
- native_.callIfPossible(args.onerror, new WebAPIException(WebAPIException.IO_ERR,
- directoryMessage));
- }, 0);
- return;
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'mode', type: types_.ENUM, values: ['r', 'rw', 'w', 'a'] },
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'encoding', type: types_.STRING, optional: true, nullable: true }
+ ]);
+
+ if (arguments.length < 2) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Arguments missing');
+ }
+ if (this.mode === 'r' && args.mode !== 'r') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Read only mode')
+ );
+ }, 0);
+ return;
+ }
+
+ if (this.isDirectory) {
+ var directoryMessage = 'This method should be called on file, not directory';
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.IO_ERR, directoryMessage)
+ );
+ }, 0);
+ return;
+ }
+
+ args.encoding = _checkEncoding(args.encoding);
- args.encoding = _checkEncoding(args.encoding);
+ var _realPath = commonFS_.toRealPath(this.fullPath);
+ var _result = native_.callSync('File_statSync', { location: _realPath });
+ if (native_.isFailure(_result)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.IO_ERR, 'File does not exist')
+ );
+ }, 0);
+ return;
+ }
- var _realPath = commonFS_.toRealPath(this.fullPath);
- var _result = native_.callSync('File_statSync', {location: _realPath});
- if (native_.isFailure(_result)) {
+ var fileStream = new FileStream(this, args.mode, args.encoding);
setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR, 'File does not exist'));
+ native_.callIfPossible(args.onsuccess, fileStream);
}, 0);
- return;
- }
-
- var fileStream = new FileStream(this, args.mode, args.encoding);
- setTimeout(function() {
- native_.callIfPossible(args.onsuccess, fileStream);
- }, 0);
-};
+}
File.prototype.openStream = function() {
- openStream.apply(this, arguments);
+ openStream.apply(this, arguments);
};
function readAsText() {
- privUtils_.warn("DEPRECATION WARNING: File.readAsText() is deprecated since Tizen 5.0. "
- + "Use FileHandle.readString() or FileHandle.readStringNonBlocking() instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'onsuccess', type: types_.FUNCTION},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'encoding', type: types_.STRING, optional: true, nullable: true}
- ]);
-
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Arguments missing');
- }
- if (this.isDirectory) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is directory'));
- }, 0);
- return;
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.readAsText() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.readString() or FileHandle.readStringNonBlocking() instead.'
+ );
- args.encoding = _checkEncoding(args.encoding);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'encoding', type: types_.STRING, optional: true, nullable: true }
+ ]);
- var data = {
- location: commonFS_.toRealPath(this.fullPath),
- offset: 0,
- encoding: args.encoding
- };
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Arguments missing');
+ }
+ if (this.isDirectory) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is directory'
+ )
+ );
+ }, 0);
+ return;
+ }
- function readFile() {
- var result;
+ args.encoding = _checkEncoding(args.encoding);
- result = native_.callSync('File_readString', data);
- if (native_.isFailure(result)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror, native_.getErrorObject(result));
- }, 0);
- return;
- }
- result = native_.getResultObject(result);
+ var data = {
+ location: commonFS_.toRealPath(this.fullPath),
+ offset: 0,
+ encoding: args.encoding
+ };
- setTimeout(function() {
- native_.callIfPossible(args.onsuccess, result);
- }, 0);
- }
+ function readFile() {
+ var result;
- setTimeout(readFile, 0);
-};
+ result = native_.callSync('File_readString', data);
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.onerror, native_.getErrorObject(result));
+ }, 0);
+ return;
+ }
+ result = native_.getResultObject(result);
+
+ setTimeout(function() {
+ native_.callIfPossible(args.onsuccess, result);
+ }, 0);
+ }
+
+ setTimeout(readFile, 0);
+}
File.prototype.readAsText = function() {
- readAsText.apply(this, arguments);
+ readAsText.apply(this, arguments);
};
function copyTo() {
- privUtils_.warn("DEPRECATION WARNING: File.copyTo() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.CopyFile() or FileSystemManager.CopyDirectory() instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'originFilePath', type: types_.STRING},
- {name: 'destinationFilePath', type: types_.STRING},
- {name: 'overwrite', type: types_.BOOLEAN},
- {name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- if (arguments.length < 3) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Invalid arguments given');
- }
-
- if (this.isFile) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is not directory'));
- }, 0);
- return;
- }
-
- // Validation against '.' and '..' directories used in path - not allowed
- var resultSource = commonFS_.checkPathWithoutDots(args.originFilePath);
- var resultDestination = commonFS_.checkPathWithoutDots(args.destinationFilePath);
- if (!resultSource || !resultDestination) {
- // path contains dots - it is not allowed - return InvalidValuesError
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.'));
- }, 0);
- return;
- }
-
- var _realOriginalPath = commonFS_.toRealPath(args.originFilePath);
- var _realDestinationPath = commonFS_.toRealPath(args.destinationFilePath);
-
- if (!_realOriginalPath) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'Source path is not valid'));
- }, 0);
- return;
- }
-
- if (!_realDestinationPath) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'Destination path is not valid'));
- }, 0);
- return;
- }
-
- var resultOldPath = native_.callSync('File_statSync', {location: _realOriginalPath});
- if (native_.isFailure(resultOldPath)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror, native_.getErrorObject(resultOldPath));
- }, 0);
- return;
- }
- var _oldNode = native_.getResultObject(resultOldPath);
-
- var addFileName = false;
- var lastChar = _realDestinationPath.substr(_realDestinationPath.length -1);
-
- var resultNewPath = native_.callSync('File_statSync', {location: _realDestinationPath});
- if (native_.isSuccess(resultNewPath)) {
- var _newNode = native_.getResultObject(resultNewPath);
- if (_newNode.isDirectory) {
- if (lastChar !== '/') {
- _realDestinationPath += '/';
- }
- addFileName = true;
- }
- } else {
- var destinationFileName, destinationDirectoryPath;
- if (lastChar !== '/') {
- destinationFileName = _realDestinationPath.split('/').pop();
- }
- destinationDirectoryPath = _realDestinationPath.substr(0, _realDestinationPath.lastIndexOf('/') + 1);
-
- var resultDestinationDirectory = native_.callSync('File_statSync', {location: destinationDirectoryPath});
- if (native_.isFailure(resultDestinationDirectory)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror, native_.getErrorObject(resultDestinationDirectory));
- }, 0);
- return;
- }
-
- if (destinationFileName.length == 0) {
- addFileName = true;
- }
- }
-
- if (_oldNode.isFile && addFileName) {
- _realDestinationPath += _realOriginalPath.split('/').pop();
- }
-
- if (!args.overwrite) {
- var resultPath = native_.callSync('File_statSync', {location: _realDestinationPath});
- if (native_.isSuccess(resultPath)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR, 'Overwrite is not allowed'));
- }, 0);
- return;
- }
- }
-
- if (!commonFS_.f_isSubDir(_realOriginalPath, this.fullPath)) {
- var m1 = 'Source file should be subdirectory of: ' + this.fullPath;
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m1));
- }, 0);
- return;
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.copyTo() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.CopyFile() or FileSystemManager.CopyDirectory() ' +
+ 'instead.'
+ );
- if (!commonFS_.isLocationAllowed(_realDestinationPath)) {
- var m2 = 'Destination is read only folder: ' + this.fullPath;
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m2));
- }, 0);
- return;
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'originFilePath', type: types_.STRING },
+ { name: 'destinationFilePath', type: types_.STRING },
+ { name: 'overwrite', type: types_.BOOLEAN },
+ { name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (arguments.length < 3) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Invalid arguments given'
+ );
+ }
+
+ if (this.isFile) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is not directory'
+ )
+ );
+ }, 0);
+ return;
+ }
- var data = {
- originFilePath: _realOriginalPath,
- destinationFilePath: _realDestinationPath,
- overwrite: args.overwrite
- };
+ // Validation against '.' and '..' directories used in path - not allowed
+ var resultSource = commonFS_.checkPathWithoutDots(args.originFilePath);
+ var resultDestination = commonFS_.checkPathWithoutDots(args.destinationFilePath);
+ if (!resultSource || !resultDestination) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ )
+ );
+ }, 0);
+ return;
+ }
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR, result));
- return;
+ var _realOriginalPath = commonFS_.toRealPath(args.originFilePath);
+ var _realDestinationPath = commonFS_.toRealPath(args.destinationFilePath);
+
+ if (!_realOriginalPath) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Source path is not valid'
+ )
+ );
+ }, 0);
+ return;
}
- native_.callIfPossible(args.onsuccess);
- };
- native_.call('File_copyTo', data, callback);
-};
+ if (!_realDestinationPath) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Destination path is not valid'
+ )
+ );
+ }, 0);
+ return;
+ }
+
+ var resultOldPath = native_.callSync('File_statSync', {
+ location: _realOriginalPath
+ });
+ if (native_.isFailure(resultOldPath)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.onerror, native_.getErrorObject(resultOldPath));
+ }, 0);
+ return;
+ }
+ var _oldNode = native_.getResultObject(resultOldPath);
+
+ var addFileName = false;
+ var lastChar = _realDestinationPath.substr(_realDestinationPath.length - 1);
+
+ var resultNewPath = native_.callSync('File_statSync', {
+ location: _realDestinationPath
+ });
+ if (native_.isSuccess(resultNewPath)) {
+ var _newNode = native_.getResultObject(resultNewPath);
+ if (_newNode.isDirectory) {
+ if (lastChar !== '/') {
+ _realDestinationPath += '/';
+ }
+ addFileName = true;
+ }
+ } else {
+ var destinationFileName, destinationDirectoryPath;
+ if (lastChar !== '/') {
+ destinationFileName = _realDestinationPath.split('/').pop();
+ }
+ destinationDirectoryPath = _realDestinationPath.substr(
+ 0,
+ _realDestinationPath.lastIndexOf('/') + 1
+ );
+
+ var resultDestinationDirectory = native_.callSync('File_statSync', {
+ location: destinationDirectoryPath
+ });
+ if (native_.isFailure(resultDestinationDirectory)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ native_.getErrorObject(resultDestinationDirectory)
+ );
+ }, 0);
+ return;
+ }
+
+ if (destinationFileName.length == 0) {
+ addFileName = true;
+ }
+ }
+
+ if (_oldNode.isFile && addFileName) {
+ _realDestinationPath += _realOriginalPath.split('/').pop();
+ }
+
+ if (!args.overwrite) {
+ var resultPath = native_.callSync('File_statSync', {
+ location: _realDestinationPath
+ });
+ if (native_.isSuccess(resultPath)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'Overwrite is not allowed'
+ )
+ );
+ }, 0);
+ return;
+ }
+ }
+
+ if (!commonFS_.f_isSubDir(_realOriginalPath, this.fullPath)) {
+ var m1 = 'Source file should be subdirectory of: ' + this.fullPath;
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m1)
+ );
+ }, 0);
+ return;
+ }
+
+ if (!commonFS_.isLocationAllowed(_realDestinationPath)) {
+ var m2 = 'Destination is read only folder: ' + this.fullPath;
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m2)
+ );
+ }, 0);
+ return;
+ }
+
+ var data = {
+ originFilePath: _realOriginalPath,
+ destinationFilePath: _realDestinationPath,
+ overwrite: args.overwrite
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.IO_ERR, result)
+ );
+ return;
+ }
+ native_.callIfPossible(args.onsuccess);
+ };
+
+ native_.call('File_copyTo', data, callback);
+}
File.prototype.copyTo = function() {
- copyTo.apply(this, arguments);
+ copyTo.apply(this, arguments);
};
function moveTo() {
- privUtils_.warn("DEPRECATION WARNING: File.moveTo() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.moveFile() or FileSystemManager.moveDirectory() instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'originFilePath', type: types_.STRING},
- {name: 'destinationFilePath', type: types_.STRING},
- {name: 'overwrite', type: types_.BOOLEAN},
- {name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- if (arguments.length < 3) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Arguments missing');
- }
- if (this.isFile) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is not directory'));
- }, 0);
- return;
- }
-
- // Validation against '.' and '..' directories used in path - not allowed
- var resultSource = commonFS_.checkPathWithoutDots(args.originFilePath);
- var resultDestination = commonFS_.checkPathWithoutDots(args.destinationFilePath);
- if (!resultSource || !resultDestination) {
- // path contains dots - it is not allowed - return InvalidValuesError
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.'));
- }, 0);
- return;
- }
-
- var _realOriginalPath = commonFS_.toRealPath(args.originFilePath);
- var _realDestinationPath = commonFS_.toRealPath(args.destinationFilePath);
-
- if (!_realOriginalPath) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'Source path is not valid'));
- }, 0);
- return;
- }
-
- if (!_realDestinationPath) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'Destination path is not valid'));
- }, 0);
- return;
- }
-
- var resultOldPath = native_.callSync('File_statSync', {location: _realOriginalPath});
- if (native_.isFailure(resultOldPath)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'Source file is not avalaible'));
- }, 0);
- return;
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.moveTo() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.moveFile() or FileSystemManager.moveDirectory() ' +
+ 'instead.'
+ );
- if (!args.overwrite) {
- var resultNewPath = native_.callSync('File_statSync', {location: _realDestinationPath});
- if (native_.isSuccess(resultNewPath)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR, 'Overwrite is not allowed'));
- }, 0);
- return;
+ var args = validator_.validateArgs(arguments, [
+ { name: 'originFilePath', type: types_.STRING },
+ { name: 'destinationFilePath', type: types_.STRING },
+ { name: 'overwrite', type: types_.BOOLEAN },
+ { name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (arguments.length < 3) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Arguments missing');
+ }
+ if (this.isFile) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is not directory'
+ )
+ );
+ }, 0);
+ return;
}
- }
- if (!commonFS_.f_isSubDir(_realOriginalPath, this.fullPath)) {
- var m1 = 'Source file should be subdirectory of: ' + this.fullPath;
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m1));
- }, 0);
- return;
- }
+ // Validation against '.' and '..' directories used in path - not allowed
+ var resultSource = commonFS_.checkPathWithoutDots(args.originFilePath);
+ var resultDestination = commonFS_.checkPathWithoutDots(args.destinationFilePath);
+ if (!resultSource || !resultDestination) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ )
+ );
+ }, 0);
+ return;
+ }
- if (this.mode === 'r' || !commonFS_.isLocationAllowed(_realDestinationPath)) {
- var m2 = 'Source/Destination is read only folder: ' + this.fullPath;
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m2));
- }, 0);
- return;
- }
+ var _realOriginalPath = commonFS_.toRealPath(args.originFilePath);
+ var _realDestinationPath = commonFS_.toRealPath(args.destinationFilePath);
+
+ if (!_realOriginalPath) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Source path is not valid'
+ )
+ );
+ }, 0);
+ return;
+ }
- var data = {
- oldPath: _realOriginalPath,
- newPath: _realDestinationPath
- };
+ if (!_realDestinationPath) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Destination path is not valid'
+ )
+ );
+ }, 0);
+ return;
+ }
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.onerror, new WebAPIException(WebAPIException.IO_ERR,
- result));
- return;
+ var resultOldPath = native_.callSync('File_statSync', {
+ location: _realOriginalPath
+ });
+ if (native_.isFailure(resultOldPath)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Source file is not avalaible'
+ )
+ );
+ }, 0);
+ return;
}
- native_.callIfPossible(args.onsuccess);
- };
- native_.call('File_rename', data, callback);
-};
+ if (!args.overwrite) {
+ var resultNewPath = native_.callSync('File_statSync', {
+ location: _realDestinationPath
+ });
+ if (native_.isSuccess(resultNewPath)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'Overwrite is not allowed'
+ )
+ );
+ }, 0);
+ return;
+ }
+ }
+
+ if (!commonFS_.f_isSubDir(_realOriginalPath, this.fullPath)) {
+ var m1 = 'Source file should be subdirectory of: ' + this.fullPath;
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m1)
+ );
+ }, 0);
+ return;
+ }
+
+ if (this.mode === 'r' || !commonFS_.isLocationAllowed(_realDestinationPath)) {
+ var m2 = 'Source/Destination is read only folder: ' + this.fullPath;
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m2)
+ );
+ }, 0);
+ return;
+ }
+
+ var data = {
+ oldPath: _realOriginalPath,
+ newPath: _realDestinationPath
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.IO_ERR, result)
+ );
+ return;
+ }
+ native_.callIfPossible(args.onsuccess);
+ };
+
+ native_.call('File_rename', data, callback);
+}
File.prototype.moveTo = function() {
- moveTo.apply(this, arguments);
+ moveTo.apply(this, arguments);
};
function createDirectory() {
- privUtils_.warn("DEPRECATION WARNING: File.createDirectory() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.createDirectory() instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'dirPath', type: types_.STRING}
- ]);
-
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid path');
- }
- if (!args.dirPath.length) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid path');
- }
-
- var _newPath = this.fullPath + '/' + args.dirPath,
- _statObj,
- _fileInfo;
-
- // Validation against '.' and '..' directories used in path - not allowed
- var result = commonFS_.checkPathWithoutDots(_newPath);
- if (!result) {
- // path contains dots - it is not allowed - return InvalidValuesError
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.');
- }
-
- var _realNewPath = commonFS_.toRealPath(_newPath);
-
- if (!_realNewPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Path is not valid');
- }
-
- if (this.isDirectory) {
- if (this.mode === 'r') {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid path or readonly access');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.createDirectory() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.createDirectory() instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'dirPath', type: types_.STRING }
+ ]);
+
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path');
+ }
+ if (!args.dirPath.length) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path');
}
- var _resultExist = native_.callSync('File_statSync', {location: _realNewPath});
- if (native_.isSuccess(_resultExist)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Directory already exist');
+ var _newPath = this.fullPath + '/' + args.dirPath,
+ _statObj,
+ _fileInfo;
+
+ // Validation against '.' and '..' directories used in path - not allowed
+ var result = commonFS_.checkPathWithoutDots(_newPath);
+ if (!result) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ );
}
- var result = native_.callSync('FileSystemManager_mkdirSync', {location: _realNewPath});
- if (native_.isFailure(result)) {
- throw new WebAPIException(WebAPIException.IO_ERR, native_.getErrorObject(result));
+ var _realNewPath = commonFS_.toRealPath(_newPath);
+
+ if (!_realNewPath) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path is not valid'
+ );
}
- var _result = native_.callSync('File_statSync', {location: _realNewPath});
- _statObj = native_.getResultObject(_result);
+ if (this.isDirectory) {
+ if (this.mode === 'r') {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path or readonly access'
+ );
+ }
- _fileInfo = commonFS_.getFileInfo(_statObj, false, this.mode);
- return new File(_fileInfo);
- } else {
- throw new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is not directory');
- }
-};
+ var _resultExist = native_.callSync('File_statSync', { location: _realNewPath });
+ if (native_.isSuccess(_resultExist)) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Directory already exist'
+ );
+ }
-File.prototype.createDirectory = function() {
- return createDirectory.apply(this, arguments);
+ var result = native_.callSync('FileSystemManager_mkdirSync', {
+ location: _realNewPath
+ });
+ if (native_.isFailure(result)) {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ native_.getErrorObject(result)
+ );
+ }
+
+ var _result = native_.callSync('File_statSync', { location: _realNewPath });
+ _statObj = native_.getResultObject(_result);
+
+ _fileInfo = commonFS_.getFileInfo(_statObj, false, this.mode);
+ return new File(_fileInfo);
+ } else {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is not directory'
+ );
+ }
}
-function createFile() {
- privUtils_.warn("DEPRECATION WARNING: File.createFile() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.createFile() instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'relativeFilePath', type: types_.STRING}
- ]);
-
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Argument "relativeFilePath" missing');
- }
- if (this.isFile) {
- throw new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is not directory');
- }
-
- if (!commonFS_.f_isCorrectRelativePath(args.relativeFilePath) || this.mode === 'r') {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid path or readonly acces');
- }
-
- var _outputPath = this.fullPath + '/' + args.relativeFilePath;
-
- // Validation against '.' and '..' directories used in path - not allowed
- var result = commonFS_.checkPathWithoutDots(_outputPath);
- if (!result) {
- // path contains dots - it is not allowed - return InvalidValuesError
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.');
- }
-
- var _outputRealPath = commonFS_.toRealPath(_outputPath);
- if (!_outputRealPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Path is not valid');
- }
-
- var _resultExist = native_.callSync('File_statSync', {location: _outputRealPath});
-
- if (native_.isSuccess(_resultExist)) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Overwrite is not allowed');
- }
-
- var result = native_.callSync('File_createSync', {location: _outputRealPath});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- var _result = native_.callSync('File_statSync', {location: _outputRealPath});
- var _statObj = native_.getResultObject(_result);
- var _fileInfo = commonFS_.getFileInfo(_statObj, false, this.mode);
-
- return new File(_fileInfo);
+File.prototype.createDirectory = function() {
+ return createDirectory.apply(this, arguments);
};
+function createFile() {
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.createFile() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.createFile() instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'relativeFilePath', type: types_.STRING }
+ ]);
+
+ if (!arguments.length) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Argument "relativeFilePath" missing'
+ );
+ }
+ if (this.isFile) {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is not directory'
+ );
+ }
+
+ if (!commonFS_.f_isCorrectRelativePath(args.relativeFilePath) || this.mode === 'r') {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path or readonly acces'
+ );
+ }
+
+ var _outputPath = this.fullPath + '/' + args.relativeFilePath;
+
+ // Validation against '.' and '..' directories used in path - not allowed
+ var result = commonFS_.checkPathWithoutDots(_outputPath);
+ if (!result) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ );
+ }
+
+ var _outputRealPath = commonFS_.toRealPath(_outputPath);
+ if (!_outputRealPath) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path is not valid'
+ );
+ }
+
+ var _resultExist = native_.callSync('File_statSync', { location: _outputRealPath });
+
+ if (native_.isSuccess(_resultExist)) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Overwrite is not allowed');
+ }
+
+ var result = native_.callSync('File_createSync', { location: _outputRealPath });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ var _result = native_.callSync('File_statSync', { location: _outputRealPath });
+ var _statObj = native_.getResultObject(_result);
+ var _fileInfo = commonFS_.getFileInfo(_statObj, false, this.mode);
+
+ return new File(_fileInfo);
+}
+
File.prototype.createFile = function() {
- return createFile.apply(this, arguments);
+ return createFile.apply(this, arguments);
};
function resolveFile() {
- privUtils_.warn("DEPRECATION WARNING: File.resolve() is deprecated since Tizen 5.0. "
- + "Use FileHandle and FileSystemManager interfaces instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'filePath', type: types_.STRING}
- ]);
-
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "filePath" missing');
- }
- if (this.isFile) {
- throw new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is not directory');
- }
-
- if (!commonFS_.f_isCorrectRelativePath(args.filePath)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path');
- }
-
- var _newPath = this.fullPath + '/' + args.filePath;
-
- // Validation against '.' and '..' directories used in path - not allowed
- var result = commonFS_.checkPathWithoutDots(_newPath);
- if (!result) {
- // path contains dots - it is not allowed - return InvalidValuesError
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.');
- }
-
- var _realPath = commonFS_.toRealPath(_newPath);
-
- if (!_realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Path is not valid');
- }
-
- var _result = native_.callSync('File_statSync', {location: _realPath});
- if (native_.isFailure(_result)) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR, native_.getErrorObject(_result));
- }
- var _statObj = native_.getResultObject(_result);
- var _fileInfo = commonFS_.getFileInfo(_statObj, false, this.mode);
-
- return new File(_fileInfo);
-};
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.resolve() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle and FileSystemManager interfaces instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'filePath', type: types_.STRING }
+ ]);
+
+ if (!arguments.length) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "filePath" missing'
+ );
+ }
+ if (this.isFile) {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is not directory'
+ );
+ }
+
+ if (!commonFS_.f_isCorrectRelativePath(args.filePath)) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path');
+ }
+
+ var _newPath = this.fullPath + '/' + args.filePath;
+
+ // Validation against '.' and '..' directories used in path - not allowed
+ var result = commonFS_.checkPathWithoutDots(_newPath);
+ if (!result) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ );
+ }
+
+ var _realPath = commonFS_.toRealPath(_newPath);
+
+ if (!_realPath) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path is not valid'
+ );
+ }
+
+ var _result = native_.callSync('File_statSync', { location: _realPath });
+ if (native_.isFailure(_result)) {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ native_.getErrorObject(_result)
+ );
+ }
+ var _statObj = native_.getResultObject(_result);
+ var _fileInfo = commonFS_.getFileInfo(_statObj, false, this.mode);
+
+ return new File(_fileInfo);
+}
File.prototype.resolve = function() {
- return resolveFile.apply(this, arguments);
+ return resolveFile.apply(this, arguments);
};
function deleteDirectory() {
- privUtils_.warn("DEPRECATION WARNING: File.deleteDirectory() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.deleteDirectory() instead." );
-
- var args = validator_.validateArgs(arguments, [
- {name: 'directoryPath', type: types_.STRING},
- {name: 'recursive', type: types_.BOOLEAN},
- {name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- if (arguments.length < 2) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Arguments missing');
- }
- if (this.mode === 'r') {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid path or readonly access'));
- }, 0);
- return;
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.deleteDirectory() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.deleteDirectory() instead.'
+ );
- // Validation against '.' and '..' directories used in path - not allowed
- var result = commonFS_.checkPathWithoutDots(args.directoryPath);
- if (!result) {
- // path contains dots - it is not allowed - return InvalidValuesError
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.'));
- }, 0);
- return;
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'directoryPath', type: types_.STRING },
+ { name: 'recursive', type: types_.BOOLEAN },
+ { name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
- var _myPath = commonFS_.toRealPath(args.directoryPath);
+ if (arguments.length < 2) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Arguments missing');
+ }
+ if (this.mode === 'r') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path or readonly access'
+ )
+ );
+ }, 0);
+ return;
+ }
- if (_myPath !== undefined && !commonFS_.f_isSubDir(_myPath, this.fullPath)) {
- var m1 = 'Deleted directory should be under the current directory: ' + this.fullPath;
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m1));
- }, 0);
- return;
- }
+ // Validation against '.' and '..' directories used in path - not allowed
+ var result = commonFS_.checkPathWithoutDots(args.directoryPath);
+ if (!result) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ )
+ );
+ }, 0);
+ return;
+ }
- var _result = native_.callSync('File_statSync', {location: _myPath});
- if (native_.isFailure(_result)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Directory not found'));
- }, 0);
- return;
- }
- var _statObj = native_.getResultObject(_result);
- var _info = commonFS_.getFileInfo(_statObj);
- var _node = new File(_info);
+ var _myPath = commonFS_.toRealPath(args.directoryPath);
+
+ if (_myPath !== undefined && !commonFS_.f_isSubDir(_myPath, this.fullPath)) {
+ var m1 =
+ 'Deleted directory should be under the current directory: ' + this.fullPath;
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, m1)
+ );
+ }, 0);
+ return;
+ }
- if (!_node.isDirectory) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'It is file not directory'));
- }, 0);
- return;
- } else {
- _node.listFiles(
- function(files) {
- if (files.length > 0) {
- if (!args.recursive) {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR,
- 'Non empty folder ' + _myPath + ' passed for non recursive delete'));
- return;
- }
- }
- var data = {
- pathToDelete: _myPath
- };
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.onerror, native_.getErrorObject(result));
+ var _result = native_.callSync('File_statSync', { location: _myPath });
+ if (native_.isFailure(_result)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Directory not found')
+ );
+ }, 0);
+ return;
+ }
+ var _statObj = native_.getResultObject(_result);
+ var _info = commonFS_.getFileInfo(_statObj);
+ var _node = new File(_info);
+
+ if (!_node.isDirectory) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'It is file not directory'
+ )
+ );
+ }, 0);
+ return;
+ } else {
+ _node.listFiles(
+ function(files) {
+ if (files.length > 0) {
+ if (!args.recursive) {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'Non empty folder ' +
+ _myPath +
+ ' passed for non recursive delete'
+ )
+ );
+ return;
+ }
+ }
+ var data = {
+ pathToDelete: _myPath
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(
+ args.onerror,
+ native_.getErrorObject(result)
+ );
+ }
+ native_.callIfPossible(args.onsuccess);
+ };
+
+ native_.call('File_removeDirectory', data, callback);
+ },
+ function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'List files failed for ' + _myPath
+ )
+ );
}
- native_.callIfPossible(args.onsuccess);
- };
-
- native_.call('File_removeDirectory', data, callback);
- },
- function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR,
- 'List files failed for ' + _myPath));
- }
- );
- }
-};
+ );
+ }
+}
File.prototype.deleteDirectory = function() {
- deleteDirectory.apply(this, arguments);
+ deleteDirectory.apply(this, arguments);
};
function deleteFile() {
- privUtils_.warn("DEPRECATION WARNING: File.deleteFile() is deprecated since Tizen 5.0. "
- + "Use FileSystemManager.deleteFile() instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'filePath', type: types_.STRING},
- {name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "filePath" missing');
- }
- if (this.isFile) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.IO_ERR,
- 'File object which call this method is not directory'));
- }, 0);
- return;
- }
-
- // Validation against '.' and '..' directories used in path - not allowed
- var result = commonFS_.checkPathWithoutDots(args.filePath);
- if (!result) {
- // path contains dots - it is not allowed - return InvalidValuesError
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.'));
- }, 0);
- return;
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: File.deleteFile() is deprecated since Tizen 5.0. ' +
+ 'Use FileSystemManager.deleteFile() instead.'
+ );
- var _fileRealPath = commonFS_.toRealPath(args.filePath);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'filePath', type: types_.STRING },
+ { name: 'onsuccess', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (!arguments.length) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "filePath" missing'
+ );
+ }
+ if (this.isFile) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'File object which call this method is not directory'
+ )
+ );
+ }, 0);
+ return;
+ }
- var _result = native_.callSync('File_statSync', {location: _fileRealPath});
- if (native_.isFailure(_result)) {
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'File is not avalaible'));
- }, 0);
- return;
- }
- var _statObj = native_.getResultObject(_result);
+ // Validation against '.' and '..' directories used in path - not allowed
+ var result = commonFS_.checkPathWithoutDots(args.filePath);
+ if (!result) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ )
+ );
+ }, 0);
+ return;
+ }
- if (_statObj.isDirectory) {
- var message = 'Requested object is a directory.';
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, message));
- }, 0);
- return;
- }
+ var _fileRealPath = commonFS_.toRealPath(args.filePath);
+
+ var _result = native_.callSync('File_statSync', { location: _fileRealPath });
+ if (native_.isFailure(_result)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'File is not avalaible'
+ )
+ );
+ }, 0);
+ return;
+ }
+ var _statObj = native_.getResultObject(_result);
+
+ if (_statObj.isDirectory) {
+ var message = 'Requested object is a directory.';
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, message)
+ );
+ }, 0);
+ return;
+ }
- if (!commonFS_.f_isSubDir(_fileRealPath, this.fullPath) || this.mode === 'r') {
- var _message = 'Deleted file [' + args.filePath + '] should have write access ' +
- 'and should be subdirectory of: [' + this.fullPath + ']';
- setTimeout(function() {
- native_.callIfPossible(args.onerror,
- new WebAPIException(WebAPIException.INVALID_VALUES_ERR, _message));
- }, 0);
- return;
- }
+ if (!commonFS_.f_isSubDir(_fileRealPath, this.fullPath) || this.mode === 'r') {
+ var _message =
+ 'Deleted file [' +
+ args.filePath +
+ '] should have write access ' +
+ 'and should be subdirectory of: [' +
+ this.fullPath +
+ ']';
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.INVALID_VALUES_ERR, _message)
+ );
+ }, 0);
+ return;
+ }
- var data = {
- pathToFile: _fileRealPath
- };
+ var data = {
+ pathToFile: _fileRealPath
+ };
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.onerror, native_.getErrorObject(result));
- return;
- }
- native_.callIfPossible(args.onsuccess);
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.onerror, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.onsuccess);
+ };
- native_.call('File_unlinkFile', data, callback);
-};
+ native_.call('File_unlinkFile', data, callback);
+}
File.prototype.deleteFile = function() {
- deleteFile.apply(this, arguments);
+ deleteFile.apply(this, arguments);
};
diff --git a/src/filesystem/js/file_handle.js b/src/filesystem/js/file_handle.js
index 3d9a2ed9..47ab9836 100644
--- a/src/filesystem/js/file_handle.js
+++ b/src/filesystem/js/file_handle.js
@@ -14,664 +14,789 @@
* limitations under the License.
*/
-
function FileHandle(_id, _path, _mode) {
- Object.defineProperties(this, {
- id: {value: _id, writable: false, enumerable: false},
- path: {value: _path, writable: false, enumerable: true},
- mode: {value: _mode, writable: false, enumerable: false},
- state: {value: 'opened', writable: true, enumerable: false}
- });
+ Object.defineProperties(this, {
+ id: { value: _id, writable: false, enumerable: false },
+ path: { value: _path, writable: false, enumerable: true },
+ mode: { value: _mode, writable: false, enumerable: false },
+ state: { value: 'opened', writable: true, enumerable: false }
+ });
}
FileHandle.prototype.seek = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'offset', type: types_.LONG}, {
- name: 'whence',
- type: types_.ENUM,
- values: type_.getValues(BaseSeekPosition),
- optional: true
- }
- ]);
-
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- var data = {id: this.id, offset: args.offset};
- if (undefined === args.whence) {
- data.whence = 'BEGIN';
- } else {
- data.whence = args.whence;
- }
- var result = native_.callSync('FileHandle_seek', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'offset', type: types_.LONG },
+ {
+ name: 'whence',
+ type: types_.ENUM,
+ values: type_.getValues(BaseSeekPosition),
+ optional: true
+ }
+ ]);
+
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ var data = { id: this.id, offset: args.offset };
+ if (undefined === args.whence) {
+ data.whence = 'BEGIN';
+ } else {
+ data.whence = args.whence;
+ }
+ var result = native_.callSync('FileHandle_seek', data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
};
FileHandle.prototype.seekNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'offset', type: types_.LONG},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}, {
- name: 'whence',
- type: types_.ENUM,
- values: type_.getValues(BaseSeekPosition),
- optional: true
- }
- ]);
-
- if (!(this.state === 'opened')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
- var data = {id: this.id, offset: args.offset, blocking: false};
- if (undefined === args.whence) {
- data.whence = 'BEGIN';
- } else {
- data.whence = args.whence;
- }
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ var args = validator_.validateArgs(arguments, [
+ { name: 'offset', type: types_.LONG },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ {
+ name: 'whence',
+ type: types_.ENUM,
+ values: type_.getValues(BaseSeekPosition),
+ optional: true
+ }
+ ]);
+
+ if (!(this.state === 'opened')) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
+ }
+ var data = { id: this.id, offset: args.offset, blocking: false };
+ if (undefined === args.whence) {
+ data.whence = 'BEGIN';
} else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ data.whence = args.whence;
}
- };
- var result = native_.call('FileHandle_seek', data, callback);
- if (native_.isFailure(result)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- }, 0);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
+
+ var result = native_.call('FileHandle_seek', data, callback);
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ }, 0);
+ }
};
FileHandle.prototype.readString = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'count', type: types_.LONG, optional: true, nullable: true},
- {name: 'inputEncoding', type: types_.STRING, optional: true}
- ]);
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- if ((this.mode === 'w') || (this.mode === 'a')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is write-only');
- }
- var data = {id: this.id, encoding: args.inputEncoding};
- if (!type_.isNullOrUndefined(args.count)) {
- data.count = args.count;
- }
- var result = native_.callSync('FileHandle_readString', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'count', type: types_.LONG, optional: true, nullable: true },
+ { name: 'inputEncoding', type: types_.STRING, optional: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ if (this.mode === 'w' || this.mode === 'a') {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is write-only'
+ );
+ }
+ var data = { id: this.id, encoding: args.inputEncoding };
+ if (!type_.isNullOrUndefined(args.count)) {
+ data.count = args.count;
+ }
+ var result = native_.callSync('FileHandle_readString', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
};
FileHandle.prototype.readStringNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'count', type: types_.LONG, optional: true},
- {name: 'inputEncoding', type: types_.STRING, optional: true}
- ]);
- if (!(this.state === 'opened')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
- if ((this.mode === 'w') || (this.mode === 'a')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is write-only'));
- }, 0);
- return;
- }
- var data = {id: this.id, encoding: args.inputEncoding, blocking: false};
- if (!type_.isNullOrUndefined(args.count)) {
- data.count = args.count;
- }
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'count', type: types_.LONG, optional: true },
+ { name: 'inputEncoding', type: types_.STRING, optional: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
+ }
+ if (this.mode === 'w' || this.mode === 'a') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is write-only'
+ )
+ );
+ }, 0);
+ return;
+ }
+ var data = { id: this.id, encoding: args.inputEncoding, blocking: false };
+ if (!type_.isNullOrUndefined(args.count)) {
+ data.count = args.count;
}
- };
- var result = native_.call('FileHandle_readString', data, callback);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
- if (native_.isFailure(result)) {
- var err = native_.getErrorObject(result);
- if ('IOError' === err.name) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- } else {
- throw native_.getErrorObject(result);
+ var result = native_.call('FileHandle_readString', data, callback);
+
+ if (native_.isFailure(result)) {
+ var err = native_.getErrorObject(result);
+ if ('IOError' === err.name) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ } else {
+ throw native_.getErrorObject(result);
+ }
}
- }
};
FileHandle.prototype.writeString = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'string', type: types_.STRING},
- {name: 'outputEncoding', type: types_.STRING, optional: true}
- ]);
- if (!('opened' === this.state)) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- if ('r' === this.mode) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only');
- }
- var data = {id: this.id, string: args.string, encoding: args.outputEncoding};
- var result = native_.callSync('FileHandle_writeString', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
-};
+ var args = validator_.validateArgs(arguments, [
+ { name: 'string', type: types_.STRING },
+ { name: 'outputEncoding', type: types_.STRING, optional: true }
+ ]);
+ if (!('opened' === this.state)) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ if ('r' === this.mode) {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ );
+ }
+ var data = { id: this.id, string: args.string, encoding: args.outputEncoding };
+ var result = native_.callSync('FileHandle_writeString', data);
-FileHandle.prototype.writeStringNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'string', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'outputEncoding', type: types_.STRING, optional: true}
- ]);
- if (!('opened' === this.state)) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
- if ('r' === this.mode) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only'));
- }, 0);
- return;
- }
- var data =
- {id: this.id, string: args.string, encoding: args.outputEncoding, blocking: false};
-
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ throw native_.getErrorObject(result);
}
- };
+ return native_.getResultObject(result);
+};
- var result = native_.call('FileHandle_writeString', data, callback);
+FileHandle.prototype.writeStringNonBlocking = function() {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'string', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'outputEncoding', type: types_.STRING, optional: true }
+ ]);
+ if (!('opened' === this.state)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
+ }
+ if ('r' === this.mode) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ )
+ );
+ }, 0);
+ return;
+ }
+ var data = {
+ id: this.id,
+ string: args.string,
+ encoding: args.outputEncoding,
+ blocking: false
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
+
+ var result = native_.call('FileHandle_writeString', data, callback);
- if (native_.isFailure(result)) {
- var err = native_.getErrorObject(result);
- if ('IOError' === err.name) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- } else {
- throw native_.getErrorObject(result);
+ if (native_.isFailure(result)) {
+ var err = native_.getErrorObject(result);
+ if ('IOError' === err.name) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ } else {
+ throw native_.getErrorObject(result);
+ }
}
- }
};
FileHandle.prototype.readBlob = function() {
- var args = validator_.validateArgs(
- arguments, [{name: 'size', type: types_.LONG, optional: true}]);
-
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- if ((this.mode === 'w') || (this.mode === 'a')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is write-only');
- }
- var data = {id: this.id};
- if (!type_.isNullOrUndefined(args.size)) {
- data.size = args.size;
- }
- var result = native_.call('FileHandle_readData', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var encodedData = native_.getResultObject(result);
- var data = StringToArray(encodedData, Uint8Array);
- return new Blob([data]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'size', type: types_.LONG, optional: true }
+ ]);
+
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ if (this.mode === 'w' || this.mode === 'a') {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is write-only'
+ );
+ }
+ var data = { id: this.id };
+ if (!type_.isNullOrUndefined(args.size)) {
+ data.size = args.size;
+ }
+ var result = native_.call('FileHandle_readData', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var encodedData = native_.getResultObject(result);
+ var data = StringToArray(encodedData, Uint8Array);
+ return new Blob([data]);
};
FileHandle.prototype.readBlobNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'size', type: types_.LONG, optional: true, nullable: true}
- ]);
- if (!(this.state === 'opened')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
-
- var data = {id: this.id, blocking: false};
- if (!type_.isNullOrUndefined(args.size)) {
- data.size = args.size;
- }
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var encodedData = native_.getResultObject(result);
- var data = StringToArray(encodedData, Uint8Array);
- native_.callIfPossible(args.successCallback, new Blob([data]));
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'size', type: types_.LONG, optional: true, nullable: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
}
- };
- var result = native_.call('FileHandle_readData', data, callback);
+ var data = { id: this.id, blocking: false };
+ if (!type_.isNullOrUndefined(args.size)) {
+ data.size = args.size;
+ }
- if (native_.isFailure(result)) {
- var err = native_.getErrorObject(result);
- if ('IOError' === err.name) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- } else {
- throw native_.getErrorObject(result);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var encodedData = native_.getResultObject(result);
+ var data = StringToArray(encodedData, Uint8Array);
+ native_.callIfPossible(args.successCallback, new Blob([data]));
+ }
+ };
+
+ var result = native_.call('FileHandle_readData', data, callback);
+
+ if (native_.isFailure(result)) {
+ var err = native_.getErrorObject(result);
+ if ('IOError' === err.name) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ } else {
+ throw native_.getErrorObject(result);
+ }
}
- }
};
function blobToUint8Array(b) {
- var uri = URL.createObjectURL(b), xhr = new XMLHttpRequest(), i, ui8;
- xhr.open('GET', uri, false);
- xhr.send();
- URL.revokeObjectURL(uri);
- var stringUtf8 = unescape(encodeURIComponent(xhr.response));
- ui8 = new Uint8Array(stringUtf8.length);
- for (i = 0; i < stringUtf8.length; ++i) {
- ui8[i] = stringUtf8.charCodeAt(i);
- }
- return ui8;
+ var uri = URL.createObjectURL(b),
+ xhr = new XMLHttpRequest(),
+ i,
+ ui8;
+ xhr.open('GET', uri, false);
+ xhr.send();
+ URL.revokeObjectURL(uri);
+ var stringUtf8 = unescape(encodeURIComponent(xhr.response));
+ ui8 = new Uint8Array(stringUtf8.length);
+ for (i = 0; i < stringUtf8.length; ++i) {
+ ui8[i] = stringUtf8.charCodeAt(i);
+ }
+ return ui8;
}
FileHandle.prototype.writeBlob = function() {
- var args = validator_.validateArgs(
- arguments, [{name: 'blob', type: types_.PLATFORM_OBJECT, values: Blob}]);
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- if (this.mode === 'r') {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only');
- }
-
- var encodedData = ArrayToString(blobToUint8Array(args.blob));
- var data = {id: this.id, data: encodedData};
- var result = native_.callSync('FileHandle_writeData', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'blob', type: types_.PLATFORM_OBJECT, values: Blob }
+ ]);
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ if (this.mode === 'r') {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ );
+ }
+
+ var encodedData = ArrayToString(blobToUint8Array(args.blob));
+ var data = { id: this.id, data: encodedData };
+ var result = native_.callSync('FileHandle_writeData', data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileHandle.prototype.writeBlobNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'blob', type: types_.PLATFORM_OBJECT, values: Blob},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
- if (!('opened' === this.state)) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- } else if (this.mode === 'r') {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only'));
- }, 0);
- return;
- }
-
- var encodedData = ArrayToString(blobToUint8Array(args.blob));
- var data = {id: this.id, data: encodedData, blocking: false};
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ var args = validator_.validateArgs(arguments, [
+ { name: 'blob', type: types_.PLATFORM_OBJECT, values: Blob },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+ if (!('opened' === this.state)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
+ } else if (this.mode === 'r') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ )
+ );
+ }, 0);
+ return;
}
- };
- var result = native_.call('FileHandle_writeData', data, callback);
+ var encodedData = ArrayToString(blobToUint8Array(args.blob));
+ var data = { id: this.id, data: encodedData, blocking: false };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
+
+ var result = native_.call('FileHandle_writeData', data, callback);
- // Only IOError is possible to be returned synchronously, so it is passed to
- // errorCallback in each case.
- if (native_.isFailure(result)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- }, 0);
- return;
- }
+ // Only IOError is possible to be returned synchronously, so it is passed to
+ // errorCallback in each case.
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ }, 0);
+ return;
+ }
};
FileHandle.prototype.readData = function() {
- var args = validator_.validateArgs(
- arguments, [{name: 'size', type: types_.LONG, optional: true}]);
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- if ((this.mode === 'w') || (this.mode === 'a')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is write-only');
- }
- var data = {id: this.id};
- if (!type_.isNullOrUndefined(args.size)) {
- data.size = args.size;
- }
- var result = native_.callSync('FileHandle_readData', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var encodedData = native_.getResultObject(result);
- var data = StringToArray(encodedData, Uint8Array);
- return new Uint8Array(data);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'size', type: types_.LONG, optional: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ if (this.mode === 'w' || this.mode === 'a') {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is write-only'
+ );
+ }
+ var data = { id: this.id };
+ if (!type_.isNullOrUndefined(args.size)) {
+ data.size = args.size;
+ }
+ var result = native_.callSync('FileHandle_readData', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var encodedData = native_.getResultObject(result);
+ var data = StringToArray(encodedData, Uint8Array);
+ return new Uint8Array(data);
};
FileHandle.prototype.readDataNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'size', type: types_.LONG, optional: true, nullable: true}
- ]);
- if (!(this.state === 'opened')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
- if ((this.mode === 'w') || (this.mode === 'a')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is write-only'));
- }, 0);
- return;
- }
-
- var data = {id: this.id, blocking: false};
- if (!type_.isNullOrUndefined(args.size)) {
- data.size = args.size;
- }
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var data_out =
- new Uint8Array(StringToArray(native_.getResultObject(result), Uint8Array));
- native_.callIfPossible(args.successCallback, data_out);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'size', type: types_.LONG, optional: true, nullable: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
+ }
+ if (this.mode === 'w' || this.mode === 'a') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is write-only'
+ )
+ );
+ }, 0);
+ return;
}
- };
- var result = native_.call('FileHandle_readData', data, callback);
+ var data = { id: this.id, blocking: false };
+ if (!type_.isNullOrUndefined(args.size)) {
+ data.size = args.size;
+ }
- if (native_.isFailure(result)) {
- var err = native_.getErrorObject(result);
- if ('IOError' === err.name) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- } else {
- throw native_.getErrorObject(result);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var data_out = new Uint8Array(
+ StringToArray(native_.getResultObject(result), Uint8Array)
+ );
+ native_.callIfPossible(args.successCallback, data_out);
+ }
+ };
+
+ var result = native_.call('FileHandle_readData', data, callback);
+
+ if (native_.isFailure(result)) {
+ var err = native_.getErrorObject(result);
+ if ('IOError' === err.name) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ } else {
+ throw native_.getErrorObject(result);
+ }
}
- }
};
FileHandle.prototype.writeData = function() {
- var args = validator_.validateArgs(
- arguments, [{name: 'data', type: types_.PLATFORM_OBJECT, values: Uint8Array}]);
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- } else if (this.mode === 'r') {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only');
- }
- var encodedData = ArrayToString(args.data);
- var data = {id: this.id, data: encodedData};
- var result = native_.callSync('FileHandle_writeData', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'data', type: types_.PLATFORM_OBJECT, values: Uint8Array }
+ ]);
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ } else if (this.mode === 'r') {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ );
+ }
+ var encodedData = ArrayToString(args.data);
+ var data = { id: this.id, data: encodedData };
+ var result = native_.callSync('FileHandle_writeData', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileHandle.prototype.writeDataNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'data', type: types_.PLATFORM_OBJECT, values: Uint8Array},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
- if (!('opened' === this.state)) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- } else if (this.mode === 'r') {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only'));
- }, 0);
- return;
- }
-
- var encodedData = ArrayToString(args.data);
-
- var data = {id: this.id, data: encodedData, blocking: false};
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ var args = validator_.validateArgs(arguments, [
+ { name: 'data', type: types_.PLATFORM_OBJECT, values: Uint8Array },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+ if (!('opened' === this.state)) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
+ } else if (this.mode === 'r') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ )
+ );
+ }, 0);
+ return;
}
- };
- var result = native_.call('FileHandle_writeData', data, callback);
+ var encodedData = ArrayToString(args.data);
- // Only IOError is possible to be returned synchronously, so it is passed to
- // errorCallback in each case.
- if (native_.isFailure(result)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- }
+ var data = { id: this.id, data: encodedData, blocking: false };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
+
+ var result = native_.call('FileHandle_writeData', data, callback);
+
+ // Only IOError is possible to be returned synchronously, so it is passed to
+ // errorCallback in each case.
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ }
};
FileHandle.prototype.flush = function() {
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- if (this.mode === 'r') {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only');
- }
- var data = {id: this.id};
- var result = native_.callSync('FileHandle_flush', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ if (this.mode === 'r') {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ );
+ }
+ var data = { id: this.id };
+ var result = native_.callSync('FileHandle_flush', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileHandle.prototype.flushNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
- if (!(this.state === 'opened')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
- if (this.mode === 'r') {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only'));
- }, 0);
- return;
- }
- var data = {id: this.id, blocking: false};
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
+ }
+ if (this.mode === 'r') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ )
+ );
+ }, 0);
+ return;
}
- };
+ var data = { id: this.id, blocking: false };
- var result = native_.call('FileHandle_flush', data, callback);
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
- // Only IOError is possible to be returned synchronously, so it is passed to
- // errorCallback in each case.
- if (native_.isFailure(result)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- }
+ var result = native_.call('FileHandle_flush', data, callback);
+
+ // Only IOError is possible to be returned synchronously, so it is passed to
+ // errorCallback in each case.
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ }
};
FileHandle.prototype.sync = function() {
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- if (this.mode === 'r') {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only');
- }
-
- var data = {id: this.id};
- var result = native_.callSync('FileHandle_sync', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ if (this.mode === 'r') {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ );
+ }
+
+ var data = { id: this.id };
+ var result = native_.callSync('FileHandle_sync', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileHandle.prototype.syncNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
- if (!(this.state === 'opened')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
- if (this.mode === 'r') {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle state is read-only'));
- }, 0);
- return;
- }
- var data = {id: this.id, blocking: false};
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
}
- };
+ if (this.mode === 'r') {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'FileHandle state is read-only'
+ )
+ );
+ }, 0);
+ return;
+ }
+ var data = { id: this.id, blocking: false };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
- var result = native_.call('FileHandle_sync', data, callback);
+ var result = native_.call('FileHandle_sync', data, callback);
- // Only IOError is possible to be returned synchronously, so it is passed to
- // errorCallback in each case.
- if (native_.isFailure(result)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- }
+ // Only IOError is possible to be returned synchronously, so it is passed to
+ // errorCallback in each case.
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ }
};
FileHandle.prototype.close = function() {
- if (!(this.state === 'opened')) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
- }
- var data = {id: this.id};
- var result = native_.callSync('FileHandle_close', data);
- this.state = 'closed';
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (!(this.state === 'opened')) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened');
+ }
+ var data = { id: this.id };
+ var result = native_.callSync('FileHandle_close', data);
+ this.state = 'closed';
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileHandle.prototype.closeNonBlocking = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
- if (!(this.state === 'opened')) {
- setTimeout(function() {
- native_.callIfPossible(
- args.errorCallback,
- new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened'));
- }, 0);
- return;
- }
-
- var data = {id: this.id, blocking: false};
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+ if (!(this.state === 'opened')) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(WebAPIException.IO_ERR, 'FileHandle is not opened')
+ );
+ }, 0);
+ return;
}
- };
- var result = native_.call('FileHandle_close', data, callback);
- this.state = 'closed';
+ var data = { id: this.id, blocking: false };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ }
+ };
- // Only IOError is possible to be returned synchronously, so it is passed to
- // errorCallback in each case.
- if (native_.isFailure(result)) {
- setTimeout(function() {
- native_.callIfPossible(args.errorCallback, err);
- }, 0);
- }
+ var result = native_.call('FileHandle_close', data, callback);
+ this.state = 'closed';
+
+ // Only IOError is possible to be returned synchronously, so it is passed to
+ // errorCallback in each case.
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, err);
+ }, 0);
+ }
};
diff --git a/src/filesystem/js/file_stream.js b/src/filesystem/js/file_stream.js
index 89eed34a..61add68f 100644
--- a/src/filesystem/js/file_stream.js
+++ b/src/filesystem/js/file_stream.js
@@ -17,313 +17,345 @@
var can_change_size = false;
function FileStream(data, mode, encoding) {
- var _totalBytes = data.fileSize || 0;
- var _position = mode === 'a' ? _totalBytes : 0;
-
- Object.defineProperties(this, {
- eof: {
- get: function() {
- return _totalBytes < _position;
- },
- set: function(v) {},
- enumerable: true
- },
- position: {
- get: function() {
- return _position;
- },
- set: function(v) {
- _position = Math.max(0, v);
- if (can_change_size) {
- _totalBytes = Math.max(_position, _totalBytes);
+ var _totalBytes = data.fileSize || 0;
+ var _position = mode === 'a' ? _totalBytes : 0;
+
+ Object.defineProperties(this, {
+ eof: {
+ get: function() {
+ return _totalBytes < _position;
+ },
+ set: function(v) {},
+ enumerable: true
+ },
+ position: {
+ get: function() {
+ return _position;
+ },
+ set: function(v) {
+ _position = Math.max(0, v);
+ if (can_change_size) {
+ _totalBytes = Math.max(_position, _totalBytes);
+ }
+ },
+ enumerable: true
+ },
+ bytesAvailable: {
+ get: function() {
+ return this.eof ? -1 : Math.max(0, _totalBytes - _position);
+ },
+ set: function(v) {},
+ enumerable: true
+ },
+ _mode: { value: mode, writable: false, enumerable: false },
+ _encoding: { value: encoding, writable: false, enumerable: false },
+ _file: { value: data, writable: false, enumerable: false },
+ _closed: { value: false, writable: true, enumerable: false },
+ _truncate: {
+ value: mode === 'w', // 'w' truncates file to zero length
+ writable: true,
+ enumerable: false
}
- },
- enumerable: true
- },
- bytesAvailable: {
- get: function() {
- return this.eof ? -1 : Math.max(0, _totalBytes - _position);
- },
- set: function(v) {},
- enumerable: true
- },
- _mode: {value: mode, writable: false, enumerable: false},
- _encoding: {value: encoding, writable: false, enumerable: false},
- _file: {value: data, writable: false, enumerable: false},
- _closed: {value: false, writable: true, enumerable: false},
- _truncate: {
- value: mode === 'w', // 'w' truncates file to zero length
- writable: true,
- enumerable: false
- }
- });
+ });
}
function _checkClosed(stream) {
- if (stream._closed) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is closed.');
- }
+ if (stream._closed) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is closed.');
+ }
}
function closeFileStream() {
- privUtils_.warn("DEPRECATION WARNING: FileStream.close() is deprecated since Tizen 5.0. "
- + "Use FileHandle.close() instead.");
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileStream.close() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.close() instead.'
+ );
- this._closed = true;
+ this._closed = true;
}
FileStream.prototype.close = function() {
- closeFileStream.apply(this, arguments);
+ closeFileStream.apply(this, arguments);
};
function _checkReadAccess(mode) {
- if (mode !== 'r' && mode !== 'rw') {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is not in read mode.');
- }
+ if (mode !== 'r' && mode !== 'rw') {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is not in read mode.');
+ }
}
function _checkWriteAccess(mode) {
- if (mode !== 'a' && mode !== 'w' && mode !== 'rw') {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is not in write mode.');
- }
+ if (mode !== 'a' && mode !== 'w' && mode !== 'rw') {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is not in write mode.');
+ }
}
function read() {
- privUtils_.warn("DEPRECATION WARNING: FileStream.read() is deprecated since Tizen 5.0. "
- + "Use FileHandle.readString() or FileHandle.readStringNonBlocking() instead.");
-
- var args = validator_.validateArgs(arguments, [{name: 'charCount', type: types_.LONG}]);
-
- _checkClosed(this);
- _checkReadAccess(this._mode);
-
- if (!arguments.length) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'Argument "charCount" missing');
- }
- if (!type_.isNumber(args.charCount)) {
- throw new WebAPIException(
- WebAPIException.TYPE_MISMATCH_ERR, 'Argument "charCount" must be a number');
- }
- if (args.charCount <= 0) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Argument "charCount" must be greater than 0');
- }
- if (this.eof) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is marked as EOF.');
- }
-
- var _count = this.bytesAvailable;
-
- var data = {
- location: commonFS_.toRealPath(this._file.fullPath),
- encoding: this._encoding,
- offset: this.position || 0,
- length: args.charCount > _count ? _count : args.charCount,
- };
-
- var result = native_.callSync('File_readString', data);
- if (native_.isFailure(result)) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Could not read');
- }
- var outData = native_.getResultObject(result);
-
- if (outData.length) {
- can_change_size = true;
- this.position += outData.length;
- can_change_size = false;
- } else {
- this.position += 1; // Set EOF
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileStream.read() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.readString() or FileHandle.readStringNonBlocking() instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'charCount', type: types_.LONG }
+ ]);
+
+ _checkClosed(this);
+ _checkReadAccess(this._mode);
+
+ if (!arguments.length) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Argument "charCount" missing'
+ );
+ }
+ if (!type_.isNumber(args.charCount)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "charCount" must be a number'
+ );
+ }
+ if (args.charCount <= 0) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Argument "charCount" must be greater than 0'
+ );
+ }
+ if (this.eof) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Stream is marked as EOF.');
+ }
+
+ var _count = this.bytesAvailable;
+
+ var data = {
+ location: commonFS_.toRealPath(this._file.fullPath),
+ encoding: this._encoding,
+ offset: this.position || 0,
+ length: args.charCount > _count ? _count : args.charCount
+ };
- return outData;
+ var result = native_.callSync('File_readString', data);
+ if (native_.isFailure(result)) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Could not read');
+ }
+ var outData = native_.getResultObject(result);
+
+ if (outData.length) {
+ can_change_size = true;
+ this.position += outData.length;
+ can_change_size = false;
+ } else {
+ this.position += 1; // Set EOF
+ }
+
+ return outData;
}
FileStream.prototype.read = function() {
- return read.apply(this, arguments);
+ return read.apply(this, arguments);
};
function readBytes() {
- var args = validator_.validateArgs(arguments, [{name: 'byteCount', type: types_.LONG}]);
-
- _checkClosed(this);
- _checkReadAccess(this._mode);
-
- if (args.byteCount <= 0) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Argument "byteCount" must be greater than 0');
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'byteCount', type: types_.LONG }
+ ]);
+
+ _checkClosed(this);
+ _checkReadAccess(this._mode);
+
+ if (args.byteCount <= 0) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Argument "byteCount" must be greater than 0'
+ );
+ }
- var _count = this.bytesAvailable;
+ var _count = this.bytesAvailable;
- var data = {
- location: commonFS_.toRealPath(this._file.fullPath),
- offset: this.position || 0,
- length: (args.byteCount > _count ? _count : args.byteCount)
- };
+ var data = {
+ location: commonFS_.toRealPath(this._file.fullPath),
+ offset: this.position || 0,
+ length: args.byteCount > _count ? _count : args.byteCount
+ };
- var result = native_.callSync('File_readBytes', data);
- if (native_.isFailure(result)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Could not read');
- }
+ var result = native_.callSync('File_readBytes', data);
+ if (native_.isFailure(result)) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Could not read');
+ }
- var decoded = StringToArray(native_.getResultObject(result), Array);
+ var decoded = StringToArray(native_.getResultObject(result), Array);
- if (decoded.length) {
- can_change_size = true;
- this.position += decoded.length;
- can_change_size = false;
- } else {
- this.position += 1; // Set EOF
- }
+ if (decoded.length) {
+ can_change_size = true;
+ this.position += decoded.length;
+ can_change_size = false;
+ } else {
+ this.position += 1; // Set EOF
+ }
- return decoded;
+ return decoded;
}
FileStream.prototype.readBytes = function() {
- privUtils_.warn("DEPRECATION WARNING: FileStream.readBytes() is deprecated since Tizen 5.0. "
- + "Use FileHandle.readData() or FileHandle.readDataNonBlocking() instead.");
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileStream.readBytes() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.readData() or FileHandle.readDataNonBlocking() instead.'
+ );
- return readBytes.apply(this, arguments);
+ return readBytes.apply(this, arguments);
};
FileStream.prototype.readBase64 = function() {
- privUtils_.warn("DEPRECATION WARNING: FileStream.readBase64() is deprecated since Tizen 5.0. "
- + "Use FileHandle.readData() or FileHandle.readDataNonBlocking() in combination "
- + "with atob() and btoa() functions instead.");
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileStream.readBase64() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.readData() or FileHandle.readDataNonBlocking() in ' +
+ 'combination with atob() and btoa() functions instead.'
+ );
- return base64_encode(readBytes.apply(this, arguments));
+ return base64_encode(readBytes.apply(this, arguments));
};
function check_characters_outside_latin1(str) {
- var len = str.length;
- for (var i = 0; i < len; ++i) {
- if (str.charCodeAt(i) > 255) {
- throw new WebAPIException(
- WebAPIException.IO_ERR,
- 'Invalid character at ' + i + ': ' + str.charAt(i) + ' (not ISO-8859-1)');
+ var len = str.length;
+ for (var i = 0; i < len; ++i) {
+ if (str.charCodeAt(i) > 255) {
+ throw new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'Invalid character at ' + i + ': ' + str.charAt(i) + ' (not ISO-8859-1)'
+ );
+ }
}
- }
}
function write() {
- privUtils_.warn("DEPRECATION WARNING: FileStream.write() is deprecated since Tizen 5.0. "
- + "Use FileHandle.writeString() or FileHandle.writeStringNonBlocking() instead.");
-
- var args =
- validator_.validateArgs(arguments, [{name: 'stringData', type: types_.STRING}]);
-
- _checkClosed(this);
- _checkWriteAccess(this._mode);
-
- if (!arguments.length) {
- throw new WebAPIException(
- WebAPIException.NOT_FOUND_ERR, 'Argument "stringData" missing');
- }
-
- var data = {
- location: commonFS_.toRealPath(this._file.fullPath),
- encoding: this._encoding,
- offset: this.position,
- data: args.stringData,
- truncate: this._truncate
- };
-
- if (data.encoding == 'iso-8859-1') {
- check_characters_outside_latin1(data.data);
- }
-
- var result = native_.callSync('File_writeString', data);
-
- if (native_.isFailure(result)) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Could not write');
- }
- can_change_size = true;
- this.position = this.position + args.stringData.length;
- can_change_size = false;
- this._truncate = false;
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileStream.write() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.writeString() or FileHandle.writeStringNonBlocking() instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'stringData', type: types_.STRING }
+ ]);
+
+ _checkClosed(this);
+ _checkWriteAccess(this._mode);
+
+ if (!arguments.length) {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Argument "stringData" missing'
+ );
+ }
+
+ var data = {
+ location: commonFS_.toRealPath(this._file.fullPath),
+ encoding: this._encoding,
+ offset: this.position,
+ data: args.stringData,
+ truncate: this._truncate
+ };
+
+ if (data.encoding == 'iso-8859-1') {
+ check_characters_outside_latin1(data.data);
+ }
+
+ var result = native_.callSync('File_writeString', data);
+
+ if (native_.isFailure(result)) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Could not write');
+ }
+ can_change_size = true;
+ this.position = this.position + args.stringData.length;
+ can_change_size = false;
+ this._truncate = false;
}
FileStream.prototype.write = function() {
- write.apply(this, arguments);
+ write.apply(this, arguments);
};
function writeBytes() {
- privUtils_.warn("DEPRECATION WARNING: FileStream.writeBytes() is deprecated since Tizen 5.0. "
- + "Use FileHandle.writeData() or FileHandle.writeDataNonBlocking() instead.");
-
- var args = validator_.validateArgs(
- arguments, [{
- name: 'byteData',
- type: types_.ARRAY,
- values: undefined /* was types_.OCTET, but checking moved to ArrayToString for
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileStream.writeBytes() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.writeData() or FileHandle.writeDataNonBlocking() instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'byteData',
+ type: types_.ARRAY,
+ values: undefined /* was types_.OCTET, but checking moved to ArrayToString for
performance */
- }]);
-
- _checkClosed(this);
- _checkWriteAccess(this._mode);
-
- if (!arguments.length) {
- throw new WebAPIException(
- WebAPIException.TYPE_MISMATCH_ERR, 'Argument "byteData" missing');
- }
-
- var data = {
- location: commonFS_.toRealPath(this._file.fullPath),
- offset: this.position,
- data: ArrayToString(args.byteData),
- truncate: this._truncate,
- };
-
- var result = native_.callSync('File_writeBytes', data);
-
- if (native_.isFailure(result)) {
- throw new WebAPIException(WebAPIException.IO_ERR, 'Could not write');
- }
- can_change_size = true;
- this.position = this.position + args.byteData.length;
- can_change_size = false;
- this._truncate = false;
-}
+ }
+ ]);
-FileStream.prototype.writeBytes = function() {
- writeBytes.apply(this, arguments);
-};
+ _checkClosed(this);
+ _checkWriteAccess(this._mode);
-function writeBase64() {
- privUtils_.warn("DEPRECATION WARNING: FileStream.writeBase64() is deprecated since Tizen 5.0. "
- + "Use FileHandle.writeData() or FileHandle.writeDataNonBlocking() in combination "
- + "with atob() and btoa() functions instead.");
+ if (!arguments.length) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "byteData" missing'
+ );
+ }
- var args =
- validator_.validateArgs(arguments, [{name: 'base64Data', type: types_.STRING}]);
+ var data = {
+ location: commonFS_.toRealPath(this._file.fullPath),
+ offset: this.position,
+ data: ArrayToString(args.byteData),
+ truncate: this._truncate
+ };
- _checkClosed(this);
- _checkWriteAccess(this._mode);
+ var result = native_.callSync('File_writeBytes', data);
- var data = {
- location: commonFS_.toRealPath(this._file.fullPath),
- offset: this.position,
- data: args.base64Data,
- truncate: this._truncate,
- };
+ if (native_.isFailure(result)) {
+ throw new WebAPIException(WebAPIException.IO_ERR, 'Could not write');
+ }
+ can_change_size = true;
+ this.position = this.position + args.byteData.length;
+ can_change_size = false;
+ this._truncate = false;
+}
- var result = native_.callSync('File_writeBase64', data);
+FileStream.prototype.writeBytes = function() {
+ writeBytes.apply(this, arguments);
+};
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+function writeBase64() {
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileStream.writeBase64() is deprecated since Tizen 5.0. ' +
+ 'Use FileHandle.writeData() or FileHandle.writeDataNonBlocking() in ' +
+ 'combination with atob() and btoa() functions instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'base64Data', type: types_.STRING }
+ ]);
+
+ _checkClosed(this);
+ _checkWriteAccess(this._mode);
+
+ var data = {
+ location: commonFS_.toRealPath(this._file.fullPath),
+ offset: this.position,
+ data: args.base64Data,
+ truncate: this._truncate
+ };
+
+ var result = native_.callSync('File_writeBase64', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var written_bytes = native_.getResultObject(result);
+ var written_bytes = native_.getResultObject(result);
- can_change_size = true;
- this.position += written_bytes;
- can_change_size = false;
- this._truncate = false;
+ can_change_size = true;
+ this.position += written_bytes;
+ can_change_size = false;
+ this._truncate = false;
}
FileStream.prototype.writeBase64 = function() {
- writeBase64.apply(this, arguments);
+ writeBase64.apply(this, arguments);
};
diff --git a/src/filesystem/js/file_system_manager.js b/src/filesystem/js/file_system_manager.js
index 22f4ba27..943453fc 100644
--- a/src/filesystem/js/file_system_manager.js
+++ b/src/filesystem/js/file_system_manager.js
@@ -15,735 +15,839 @@
*/
function FileSystemStorage(data) {
- Object.defineProperties(this, {
- label: {value: data.label, writable: false, enumerable: true},
- type: {value: data.type, writable: false, enumerable: true},
- state: {value: data.state, writable: false, enumerable: true}
- });
+ Object.defineProperties(this, {
+ label: { value: data.label, writable: false, enumerable: true },
+ type: { value: data.type, writable: false, enumerable: true },
+ state: { value: data.state, writable: false, enumerable: true }
+ });
}
-
var FileStreamManager = function() {
- this.nextId = 0;
+ this.nextId = 0;
};
FileStreamManager.prototype.getNextFileHandleId = function() {
- return ++this.nextId;
+ return ++this.nextId;
};
var fileStreamManager = new FileStreamManager();
function FileSystemManager() {
- var limits = native_.getResultObject(native_.callSync('FileSystemManager_getLimits'));
- Object.defineProperties(this, {
- maxNameLength: {value: limits[0], writable: false, enumerable: true},
- maxPathLength: {value: limits[1], writable: false, enumerable: true}
- });
+ var limits = native_.getResultObject(native_.callSync('FileSystemManager_getLimits'));
+ Object.defineProperties(this, {
+ maxNameLength: { value: limits[0], writable: false, enumerable: true },
+ maxPathLength: { value: limits[1], writable: false, enumerable: true }
+ });
}
FileSystemManager.prototype.openFile = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING},
- {name: 'openMode', type: types_.ENUM, values: type_.getValues(FileMode)},
- {name: 'makeParents', type: types_.BOOLEAN, optional: true}
- ]);
-
- if (!args.has.makeParents) {
- args.makeParents = true;
- }
-
- var data = {
- path: commonFS_.toRealPath(args.path),
- openMode: args.openMode,
- makeParents: args.makeParents,
- id: fileStreamManager.getNextFileHandleId()
- };
-
- if (!data.path) {
- throw new WebAPIException(
- WebAPIException.NOT_FOUND_ERR, 'Invalid path: ' + args.path);
- }
-
- var result = native_.callSync('FileSystemManager_openFile', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- return new FileHandle(data.id, args.path, args.openMode);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'openMode', type: types_.ENUM, values: type_.getValues(FileMode) },
+ { name: 'makeParents', type: types_.BOOLEAN, optional: true }
+ ]);
+
+ if (!args.has.makeParents) {
+ args.makeParents = true;
+ }
+
+ var data = {
+ path: commonFS_.toRealPath(args.path),
+ openMode: args.openMode,
+ makeParents: args.makeParents,
+ id: fileStreamManager.getNextFileHandleId()
+ };
+
+ if (!data.path) {
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Invalid path: ' + args.path
+ );
+ }
+
+ var result = native_.callSync('FileSystemManager_openFile', data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ return new FileHandle(data.id, args.path, args.openMode);
+ }
};
FileSystemManager.prototype.createDirectory = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING},
- {name: 'makeParents', type: types_.BOOLEAN, optional: true},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'makeParents', type: types_.BOOLEAN, optional: true },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (!args.has.makeParents) {
+ args.makeParents = true;
+ }
- if (!args.has.makeParents) {
- args.makeParents = true;
- }
+ var data = { path: commonFS_.toRealPath(args.path), makeParents: args.makeParents };
- var data = {path: commonFS_.toRealPath(args.path), makeParents: args.makeParents};
+ if (!data.path) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path: ' + args.path
+ );
+ }
- if (!data.path) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'Invalid path: ' + args.path);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
- var callback = function(result) {
+ var result = native_.call('FileSystemManager_createDirectory', data, callback);
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ throw native_.getErrorObject(result);
}
- };
-
- var result = native_.call('FileSystemManager_createDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
FileSystemManager.prototype.deleteFile = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var data = {path: commonFS_.toRealPath(args.path)};
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = { path: commonFS_.toRealPath(args.path) };
+
+ if (!data.path) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path: ' + args.path
+ );
+ }
- if (!data.path) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'Invalid path: ' + args.path);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
- var callback = function(result) {
+ var result = native_.call('FileSystemManager_deleteFile', data, callback);
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ throw native_.getErrorObject(result);
}
- };
-
- var result = native_.call('FileSystemManager_deleteFile', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
FileSystemManager.prototype.deleteDirectory = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING},
- {name: 'recursive', type: types_.BOOLEAN, optional: true},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'recursive', type: types_.BOOLEAN, optional: true },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (!args.has.recursive) {
+ args.recursive = true;
+ }
- if (!args.has.recursive) {
- args.recursive = true;
- }
+ var realPath = commonFS_.toRealPath(args.path);
+ if (!realPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
- var realPath = commonFS_.toRealPath(args.path);
- if (!realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
+ var data = { path: realPath, recursive: args.recursive };
- var data = {path: realPath, recursive: args.recursive};
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
- var callback = function(result) {
+ var result = native_.call('FileSystemManager_deleteDirectory', data, callback);
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ throw native_.getErrorObject(result);
}
- };
-
- var result = native_.call('FileSystemManager_deleteDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
FileSystemManager.prototype.copyFile = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING}, {name: 'destinationPath', type: types_.STRING},
- {name: 'overwrite', type: types_.BOOLEAN, optional: true},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- if (!args.has.overwrite) {
- args.overwrite = false;
- }
-
- var data = {
- path: commonFS_.toRealPath(args.path),
- destinationPath: commonFS_.toRealPath(args.destinationPath),
- overwrite: args.overwrite
- };
-
- if (!data.path) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'Invalid path: ' + args.path);
- }
- if (!data.destinationPath) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'Invalid path: ' + args.destinationPath);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'destinationPath', type: types_.STRING },
+ { name: 'overwrite', type: types_.BOOLEAN, optional: true },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (!args.has.overwrite) {
+ args.overwrite = false;
+ }
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ var data = {
+ path: commonFS_.toRealPath(args.path),
+ destinationPath: commonFS_.toRealPath(args.destinationPath),
+ overwrite: args.overwrite
+ };
+
+ if (!data.path) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path: ' + args.path
+ );
+ }
+ if (!data.destinationPath) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path: ' + args.destinationPath
+ );
}
- };
- var result = native_.call('FileSystemManager_copyFile', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
+
+ var result = native_.call('FileSystemManager_copyFile', data, callback);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileSystemManager.prototype.copyDirectory = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING}, {name: 'destinationPath', type: types_.STRING},
- {name: 'overwrite', type: types_.BOOLEAN, optional: true},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var realPath = commonFS_.toRealPath(args.path);
- var realDestinationPath = commonFS_.toRealPath(args.destinationPath);
- if (!realPath || !realDestinationPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
-
- if (!args.has.overwrite) {
- args.overwrite = false;
- }
-
- var data = {
- path: realPath,
- destinationPath: realDestinationPath,
- overwrite: args.overwrite
- };
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'destinationPath', type: types_.STRING },
+ { name: 'overwrite', type: types_.BOOLEAN, optional: true },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var realPath = commonFS_.toRealPath(args.path);
+ var realDestinationPath = commonFS_.toRealPath(args.destinationPath);
+ if (!realPath || !realDestinationPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
+
+ if (!args.has.overwrite) {
+ args.overwrite = false;
}
- };
- var result = native_.call('FileSystemManager_copyDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var data = {
+ path: realPath,
+ destinationPath: realDestinationPath,
+ overwrite: args.overwrite
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
+
+ var result = native_.call('FileSystemManager_copyDirectory', data, callback);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileSystemManager.prototype.moveFile = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING}, {name: 'destinationPath', type: types_.STRING},
- {name: 'overwrite', type: types_.BOOLEAN, optional: true},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var realPath = commonFS_.toRealPath(args.path);
- var realDestinationPath = commonFS_.toRealPath(args.destinationPath);
- if (!realPath || !realDestinationPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
-
- if (!args.has.overwrite) {
- args.overwrite = false;
- }
-
- var data = {
- path: realPath,
- destinationPath: realDestinationPath,
- overwrite: args.overwrite
- };
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'destinationPath', type: types_.STRING },
+ { name: 'overwrite', type: types_.BOOLEAN, optional: true },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var realPath = commonFS_.toRealPath(args.path);
+ var realDestinationPath = commonFS_.toRealPath(args.destinationPath);
+ if (!realPath || !realDestinationPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
}
- };
- var result = native_.call('FileSystemManager_moveFile', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (!args.has.overwrite) {
+ args.overwrite = false;
+ }
+
+ var data = {
+ path: realPath,
+ destinationPath: realDestinationPath,
+ overwrite: args.overwrite
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
+
+ var result = native_.call('FileSystemManager_moveFile', data, callback);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileSystemManager.prototype.moveDirectory = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING}, {name: 'destinationPath', type: types_.STRING},
- {name: 'overwrite', type: types_.BOOLEAN, optional: true},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var realPath = commonFS_.toRealPath(args.path);
- var realDestinationPath = commonFS_.toRealPath(args.destinationPath);
- if (!realPath || !realDestinationPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
-
- if (!args.has.overwrite) {
- args.overwrite = false;
- }
-
- var data = {
- path: realPath,
- destinationPath: realDestinationPath,
- overwrite: args.overwrite
- };
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'destinationPath', type: types_.STRING },
+ { name: 'overwrite', type: types_.BOOLEAN, optional: true },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var realPath = commonFS_.toRealPath(args.path);
+ var realDestinationPath = commonFS_.toRealPath(args.destinationPath);
+ if (!realPath || !realDestinationPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
+
+ if (!args.has.overwrite) {
+ args.overwrite = false;
}
- };
- var result = native_.call('FileSystemManager_moveDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var data = {
+ path: realPath,
+ destinationPath: realDestinationPath,
+ overwrite: args.overwrite
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
+
+ var result = native_.call('FileSystemManager_moveDirectory', data, callback);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileSystemManager.prototype.rename = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING}, {name: 'newName', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'newName', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (-1 !== args.newName.indexOf('/') || -1 !== args.newName.indexOf('\x00')) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'newName contains invalid character.'
+ );
+ }
- if ((-1 !== args.newName.indexOf('/')) || (-1 !== args.newName.indexOf('\x00'))) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'newName contains invalid character.');
- }
+ var realPath = commonFS_.toRealPath(args.path);
+ if (!realPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
- var realPath = commonFS_.toRealPath(args.path);
- if (!realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
+ var data = { path: realPath, newName: args.newName };
- var data = {path: realPath, newName: args.newName};
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var path = native_.getResultObject(result);
+ native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ }
+ };
- var callback = function(result) {
+ var result = native_.call('FileSystemManager_rename', data, callback);
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var path = native_.getResultObject(result);
- native_.callIfPossible(args.successCallback, commonFS_.toVirtualPath(path));
+ throw native_.getErrorObject(result);
}
- };
-
- var result = native_.call('FileSystemManager_rename', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
function throwIfNotDate(argument, name) {
- if (argument instanceof Date) {
- return true;
- }
- throw new WebAPIException(
- WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "' + name + '" in a filter is not of type Date.');
+ if (argument instanceof Date) {
+ return true;
+ }
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "' + name + '" in a filter is not of type Date.'
+ );
}
FileSystemManager.prototype.listDirectory = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'path', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION, optional: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'filter', type: types_.DICTIONARY, optional: true, nullable: true}
- ]);
-
- if (!args.has.filter) {
- args.filter = {};
- }
-
- if (args.filter.hasOwnProperty('startModified')) {
- throwIfNotDate(args.filter.startModified, 'startModified');
- args.filter.startModified = args.filter.startModified.getTime() / 1000;
- }
- if (args.filter.hasOwnProperty('endModified')) {
- throwIfNotDate(args.filter.endModified, 'endModified');
- args.filter.endModified = args.filter.endModified.getTime() / 1000;
- }
- if (args.filter.hasOwnProperty('startCreated')) {
- throwIfNotDate(args.filter.startCreated, 'startCreated');
- args.filter.startCreated = args.filter.startCreated.getTime() / 1000;
- }
- if (args.filter.hasOwnProperty('endCreated')) {
- throwIfNotDate(args.filter.endCreated, 'endCreated');
- args.filter.endCreated = args.filter.endCreated.getTime() / 1000;
- }
-
- var data = {path: commonFS_.toRealPath(args.path), filter: args.filter};
-
- if (!data.path) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'Invalid path: ' + args.path);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION, optional: true },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'filter', type: types_.DICTIONARY, optional: true, nullable: true }
+ ]);
+
+ if (!args.has.filter) {
+ args.filter = {};
+ }
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var obj = native_.getResultObject(result);
- var names = obj.names;
- if (args.filter.hasOwnProperty('name')) {
- var regex_name = stringToRegex(args.filter.name);
- for (var i = names.length - 1; i >= 0; i--) {
- if (!regex_name.test(names[i])) {
- names.splice(i, 1);
- }
- }
- }
- native_.callIfPossible(
- args.successCallback, names, commonFS_.toVirtualPath(obj.path));
+ if (args.filter.hasOwnProperty('startModified')) {
+ throwIfNotDate(args.filter.startModified, 'startModified');
+ args.filter.startModified = args.filter.startModified.getTime() / 1000;
+ }
+ if (args.filter.hasOwnProperty('endModified')) {
+ throwIfNotDate(args.filter.endModified, 'endModified');
+ args.filter.endModified = args.filter.endModified.getTime() / 1000;
+ }
+ if (args.filter.hasOwnProperty('startCreated')) {
+ throwIfNotDate(args.filter.startCreated, 'startCreated');
+ args.filter.startCreated = args.filter.startCreated.getTime() / 1000;
+ }
+ if (args.filter.hasOwnProperty('endCreated')) {
+ throwIfNotDate(args.filter.endCreated, 'endCreated');
+ args.filter.endCreated = args.filter.endCreated.getTime() / 1000;
+ }
+
+ var data = { path: commonFS_.toRealPath(args.path), filter: args.filter };
+
+ if (!data.path) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid path: ' + args.path
+ );
}
- };
- var result = native_.call('FileSystemManager_listDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var obj = native_.getResultObject(result);
+ var names = obj.names;
+ if (args.filter.hasOwnProperty('name')) {
+ var regex_name = stringToRegex(args.filter.name);
+ for (var i = names.length - 1; i >= 0; i--) {
+ if (!regex_name.test(names[i])) {
+ names.splice(i, 1);
+ }
+ }
+ }
+ native_.callIfPossible(
+ args.successCallback,
+ names,
+ commonFS_.toVirtualPath(obj.path)
+ );
+ }
+ };
+
+ var result = native_.call('FileSystemManager_listDirectory', data, callback);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
FileSystemManager.prototype.toURI = function() {
- var args = validator_.validateArgs(arguments, [{name: 'path', type: types_.STRING}]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING }
+ ]);
- // The toRealPath function will convert any string to absolute path, if possible.
- // The function returns undefined for path, which starts with not-existing virtual root.
- var realPath = commonFS_.toRealPath(args.path);
+ // The toRealPath function will convert any string to absolute path, if possible.
+ // The function returns undefined for path, which starts with not-existing
+ // virtual root.
+ var realPath = commonFS_.toRealPath(args.path);
- if (!realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
+ if (!realPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
- return 'file://' + realPath;
+ return 'file://' + realPath;
};
FileSystemManager.prototype.isFile = function() {
- var args = validator_.validateArgs(arguments, [{name: 'path', type: types_.STRING}]);
- // The toRealPath function will convert any string to absolute path, if possible.
- // The function returns undefined for path, which starts with not-existing virtual root.
- var realPath = commonFS_.toRealPath(args.path);
-
- if (!realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
-
- var data = {path: realPath};
-
- var result = native_.callSync('FileSystemManager_isFile', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- return native_.getResultObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING }
+ ]);
+ // The toRealPath function will convert any string to absolute path, if possible.
+ // The function returns undefined for path, which starts with not-existing
+ // virtual root.
+ var realPath = commonFS_.toRealPath(args.path);
+
+ if (!realPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
+
+ var data = { path: realPath };
+
+ var result = native_.callSync('FileSystemManager_isFile', data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ return native_.getResultObject(result);
+ }
};
FileSystemManager.prototype.isDirectory = function() {
- var args = validator_.validateArgs(arguments, [{name: 'path', type: types_.STRING}]);
- // The toRealPath function will convert any string to absolute path, if possible.
- // The function returns undefined for path, which starts with not-existing virtual root.
- var realPath = commonFS_.toRealPath(args.path);
-
- if (!realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
-
- var data = {path: realPath};
-
- var result = native_.callSync('FileSystemManager_isDirectory', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- return native_.getResultObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING }
+ ]);
+ // The toRealPath function will convert any string to absolute path, if possible.
+ // The function returns undefined for path, which starts with not-existing
+ // virtual root.
+ var realPath = commonFS_.toRealPath(args.path);
+
+ if (!realPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
+
+ var data = { path: realPath };
+
+ var result = native_.callSync('FileSystemManager_isDirectory', data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ return native_.getResultObject(result);
+ }
};
FileSystemManager.prototype.pathExists = function() {
- var args = validator_.validateArgs(arguments, [{name: 'path', type: types_.STRING}]);
- // The toRealPath function will convert any string to absolute path, if possible.
- // The function returns undefined for path, which starts with not-existing virtual root.
- var realPath = commonFS_.toRealPath(args.path);
-
- if (!realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
- }
- var data = {path: realPath};
-
- var result = native_.callSync('FileSystemManager_pathExists', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- return native_.getResultObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING }
+ ]);
+ // The toRealPath function will convert any string to absolute path, if possible.
+ // The function returns undefined for path, which starts with not-existing
+ // virtual root.
+ var realPath = commonFS_.toRealPath(args.path);
+
+ if (!realPath) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
+ }
+ var data = { path: realPath };
+
+ var result = native_.callSync('FileSystemManager_pathExists', data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ return native_.getResultObject(result);
+ }
};
FileSystemManager.prototype.getDirName = function() {
- var args = validator_.validateArgs(arguments, [{name: 'path', type: types_.STRING}]);
- var path = args.path;
-
- path = commonFS_.mergeMultipleSlashes(path);
- if (path.startsWith('file://')) {
- path = path.substring('file://'.length - 1, path.length - 1);
- }
-
- if (path.startsWith('/') &&
- 0 === path.lastIndexOf('/')) { // handle the "/" and "/file.ext"
- return '/';
- } else if (path.endsWith('/')) { // cut the last '/'
- path = path.substring(0, path.length - 1);
- }
-
- var index = path.lastIndexOf('/');
- if (-1 !== index) {
- path = path.substring(0, index); // cut the directory/file the path points to
- }
- return path;
+ var args = validator_.validateArgs(arguments, [
+ { name: 'path', type: types_.STRING }
+ ]);
+ var path = args.path;
+
+ path = commonFS_.mergeMultipleSlashes(path);
+ if (path.startsWith('file://')) {
+ path = path.substring('file://'.length - 1, path.length - 1);
+ }
+
+ if (path.startsWith('/') && 0 === path.lastIndexOf('/')) {
+ // handle the "/" and "/file.ext"
+ return '/';
+ } else if (path.endsWith('/')) {
+ // cut the last '/'
+ path = path.substring(0, path.length - 1);
+ }
+
+ var index = path.lastIndexOf('/');
+ if (-1 !== index) {
+ path = path.substring(0, index); // cut the directory/file the path points to
+ }
+ return path;
};
function resolve() {
- privUtils_.warn("DEPRECATION WARNING: FileSystemManager.resolve() is deprecated since Tizen 5.0. "
- + "Use FileHandle and FileSystemManager interfaces instead.");
-
- var args = validator_.validateArgs(arguments, [
- {name: 'location', type: types_.STRING}, {name: 'onsuccess', type: types_.FUNCTION},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}, {
- name: 'mode',
- type: types_.ENUM,
- values: Object.keys(FileMode),
- optional: true,
- nullable: true
- }
- ]);
-
- if (!args.has.mode) {
- args.mode = 'rw';
- } else if ('rwo' == args.mode) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'rwo mode was introduced in version 5.0 and is not supported in earlier version methods');
- }
-
- // resolving a path on unmounted storage should result in exception
- var storage = commonFS_.getStorage(args.location.split('/')[0]);
- if (storage && FileSystemStorageState.MOUNTED !== storage.state) {
- setTimeout(function() {
- native_.callIfPossible(
- args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Storage is not mounted.'));
- }, 0);
- return;
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: FileSystemManager.resolve() is deprecated since ' +
+ 'Tizen 5.0. Use FileHandle and FileSystemManager interfaces instead.'
+ );
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'location', type: types_.STRING },
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true },
+ {
+ name: 'mode',
+ type: types_.ENUM,
+ values: Object.keys(FileMode),
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (!args.has.mode) {
+ args.mode = 'rw';
+ } else if ('rwo' == args.mode) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'rwo mode was introduced in version 5.0 and is not supported in earlier ' +
+ 'version methods'
+ );
+ }
- // Validation against '.' and '..' directories used in path - not allowed
- var result = commonFS_.checkPathWithoutDots(args.location);
- if (!result) {
- // path contains dots - it is not allowed - return InvalidValuesError
- setTimeout(function() {
- native_.callIfPossible(
- args.onerror, new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Path contains \'.\' or \'..\' - it is not allowed.'));
- }, 0);
- return;
- }
+ // resolving a path on unmounted storage should result in exception
+ var storage = commonFS_.getStorage(args.location.split('/')[0]);
+ if (storage && FileSystemStorageState.MOUNTED !== storage.state) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'Storage is not mounted.'
+ )
+ );
+ }, 0);
+ return;
+ }
- var _realPath = commonFS_.toRealPath(args.location);
+ // Validation against '.' and '..' directories used in path - not allowed
+ var result = commonFS_.checkPathWithoutDots(args.location);
+ if (!result) {
+ // path contains dots - it is not allowed - return InvalidValuesError
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Path contains \'.\' or \'..\' - it is not allowed.'
+ )
+ );
+ }, 0);
+ return;
+ }
- if (!_realPath) {
- // invalid real path means that virtual root does not exist
- setTimeout(function() {
- native_.callIfPossible(
- args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Invalid path.'));
- }, 0);
- return;
- }
+ var _realPath = commonFS_.toRealPath(args.location);
+
+ if (!_realPath) {
+ // invalid real path means that virtual root does not exist
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Invalid path.')
+ );
+ }, 0);
+ return;
+ }
- var _isLocationAllowed = commonFS_.isLocationAllowed(_realPath);
+ var _isLocationAllowed = commonFS_.isLocationAllowed(_realPath);
+
+ if (args.mode !== 'r' && !_isLocationAllowed) {
+ setTimeout(function() {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Provided arguments are not valid.'
+ )
+ );
+ }, 0);
+ return;
+ }
- if (args.mode !== 'r' && !_isLocationAllowed) {
- setTimeout(function() {
- native_.callIfPossible(
- args.onerror,
- new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'Provided arguments are not valid.'));
- }, 0);
- return;
- }
+ var data = { location: _realPath };
- var data = {location: _realPath};
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.onerror, native_.getErrorObject(result));
+ return;
+ }
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.onerror, native_.getErrorObject(result));
- return;
- }
+ var aStatObj = native_.getResultObject(result);
+ var _result = commonFS_.getFileInfo(aStatObj, false, args.mode);
+ if (_result.readOnly && args.mode !== 'r') {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.IO_ERR, 'File is read-only.')
+ );
+ } else {
+ native_.callIfPossible(args.onsuccess, new File(_result));
+ }
+ };
- var aStatObj = native_.getResultObject(result);
- var _result = commonFS_.getFileInfo(aStatObj, false, args.mode);
- if (_result.readOnly && args.mode !== 'r') {
- native_.callIfPossible(
- args.onerror,
- new WebAPIException(WebAPIException.IO_ERR, 'File is read-only.'));
- } else {
- native_.callIfPossible(args.onsuccess, new File(_result));
+ var ret = native_.call('File_stat', data, callback);
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
}
- };
-
- var ret = native_.call('File_stat', data, callback);
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
}
FileSystemManager.prototype.resolve = function() {
- resolve.apply(this, arguments);
+ resolve.apply(this, arguments);
};
function getStorage() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.FILESYSTEM_READ);
- var args = validator_.validateArgs(arguments, [
- {name: 'label', type: types_.STRING}, {name: 'onsuccess', type: types_.FUNCTION},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- setTimeout(function() {
- var storage = commonFS_.getStorage(args.label);
-
- if (!storage) {
- native_.callIfPossible(
- args.onerror,
- new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Storage not found.'));
- } else {
- native_.callIfPossible(args.onsuccess, new FileSystemStorage(storage));
- }
- }, 0);
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.FILESYSTEM_READ);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'label', type: types_.STRING },
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ setTimeout(function() {
+ var storage = commonFS_.getStorage(args.label);
+
+ if (!storage) {
+ native_.callIfPossible(
+ args.onerror,
+ new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Storage not found.')
+ );
+ } else {
+ native_.callIfPossible(args.onsuccess, new FileSystemStorage(storage));
+ }
+ }, 0);
}
FileSystemManager.prototype.getStorage = function() {
- getStorage.apply(this, arguments);
+ getStorage.apply(this, arguments);
};
function listStorages() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.FILESYSTEM_READ);
- var args = validator_.validateArgs(arguments, [
- {name: 'onsuccess', type: types_.FUNCTION},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.FILESYSTEM_READ);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
- setTimeout(function() {
- var storages = [];
- var cache = commonFS_.getAllStorages();
- for (var i = 0; i < cache.length; ++i) {
- storages.push(new FileSystemStorage(cache[i]));
- }
+ setTimeout(function() {
+ var storages = [];
+ var cache = commonFS_.getAllStorages();
+ for (var i = 0; i < cache.length; ++i) {
+ storages.push(new FileSystemStorage(cache[i]));
+ }
- native_.callIfPossible(args.onsuccess, storages);
- }, 0);
+ native_.callIfPossible(args.onsuccess, storages);
+ }, 0);
}
FileSystemManager.prototype.listStorages = function() {
- listStorages.apply(this, arguments);
+ listStorages.apply(this, arguments);
};
var callbackId = 0;
var callbacks = {};
function nextCallbackId() {
- return ++callbackId;
+ return ++callbackId;
}
function _StorageStateChangeListener(result) {
- commonFS_.clearCache();
- var storage = new FileSystemStorage(result);
- for (var id in callbacks) {
- native_.callIfPossible(callbacks[id], storage);
- }
+ commonFS_.clearCache();
+ var storage = new FileSystemStorage(result);
+ for (var id in callbacks) {
+ native_.callIfPossible(callbacks[id], storage);
+ }
}
function addStorageStateChangeListener() {
- var args = validator_.validateArgs(arguments, [
- {name: 'onsuccess', type: types_.FUNCTION},
- {name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var register = false;
- if (type_.isEmptyObject(callbacks)) {
- register = true;
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'onsuccess', type: types_.FUNCTION },
+ { name: 'onerror', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var register = false;
+ if (type_.isEmptyObject(callbacks)) {
+ register = true;
+ }
- var id = nextCallbackId();
- callbacks[id] = args.onsuccess;
+ var id = nextCallbackId();
+ callbacks[id] = args.onsuccess;
- if (register) {
- native_.addListener('StorageStateChangeListener', _StorageStateChangeListener);
- var result = native_.callSync('FileSystemManager_addStorageStateChangeListener', {});
+ if (register) {
+ native_.addListener('StorageStateChangeListener', _StorageStateChangeListener);
+ var result = native_.callSync(
+ 'FileSystemManager_addStorageStateChangeListener',
+ {}
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- return id;
+ return id;
}
FileSystemManager.prototype.addStorageStateChangeListener = function() {
- return addStorageStateChangeListener.apply(this, arguments);
+ return addStorageStateChangeListener.apply(this, arguments);
};
function removeStorageStateChangeListener() {
- var args = validator_.validateArgs(arguments, [{name: 'watchId', type: types_.LONG}]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG }
+ ]);
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Missing watchId');
- }
- var id = args.watchId;
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Missing watchId');
+ }
+ var id = args.watchId;
- if (type_.isNullOrUndefined(callbacks[id])) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Watch ID not found.');
- }
+ if (type_.isNullOrUndefined(callbacks[id])) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR, 'Watch ID not found.');
+ }
- delete callbacks[id];
+ delete callbacks[id];
- if (type_.isEmptyObject(callbacks)) {
- var result =
- native_.callSync('FileSystemManager_removeStorageStateChangeListener', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (type_.isEmptyObject(callbacks)) {
+ var result = native_.callSync(
+ 'FileSystemManager_removeStorageStateChangeListener',
+ {}
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
}
FileSystemManager.prototype.removeStorageStateChangeListener = function() {
- removeStorageStateChangeListener.apply(this, arguments);
+ removeStorageStateChangeListener.apply(this, arguments);
};
exports = new FileSystemManager();
diff --git a/src/humanactivitymonitor/humanactivitymonitor_api.js b/src/humanactivitymonitor/humanactivitymonitor_api.js
index a8ebf7be..8397d1af 100755
--- a/src/humanactivitymonitor/humanactivitymonitor_api.js
+++ b/src/humanactivitymonitor/humanactivitymonitor_api.js
@@ -26,11 +26,11 @@ var callbackId = 0;
var callbacks = {};
function nextCallbackId() {
- return callbackId++;
+ return callbackId++;
}
function SetReadOnlyProperty(obj, n, v) {
- Object.defineProperty(obj, n, {value: v, writable: false});
+ Object.defineProperty(obj, n, { value: v, writable: false });
}
var ACCUMULATIVE_PEDOMETER_DATA = 'ACCUMULATIVE_PEDOMETER_DATA';
@@ -40,279 +40,296 @@ var MIN_QUERY_TIME = 0;
var MIN_QUERY_INTERVAL = 0;
var HumanActivityType = {
- PEDOMETER: 'PEDOMETER',
- WRIST_UP: 'WRIST_UP',
- HRM: 'HRM',
- GPS: 'GPS',
- SLEEP_MONITOR: 'SLEEP_MONITOR',
- SLEEP_DETECTOR: 'SLEEP_DETECTOR',
- STRESS_MONITOR: 'STRESS_MONITOR'
+ PEDOMETER: 'PEDOMETER',
+ WRIST_UP: 'WRIST_UP',
+ HRM: 'HRM',
+ GPS: 'GPS',
+ SLEEP_MONITOR: 'SLEEP_MONITOR',
+ SLEEP_DETECTOR: 'SLEEP_DETECTOR',
+ STRESS_MONITOR: 'STRESS_MONITOR'
};
var HumanActivityRecorderType = {
- PEDOMETER: 'PEDOMETER',
- HRM: 'HRM',
- SLEEP_MONITOR: 'SLEEP_MONITOR',
- PRESSURE: 'PRESSURE'
+ PEDOMETER: 'PEDOMETER',
+ HRM: 'HRM',
+ SLEEP_MONITOR: 'SLEEP_MONITOR',
+ PRESSURE: 'PRESSURE'
};
var PedometerStepStatus = {
- NOT_MOVING: 'NOT_MOVING',
- WALKING: 'WALKING',
- RUNNING: 'RUNNING',
- UNKNOWN: 'UNKNOWN'
+ NOT_MOVING: 'NOT_MOVING',
+ WALKING: 'WALKING',
+ RUNNING: 'RUNNING',
+ UNKNOWN: 'UNKNOWN'
};
var ActivityRecognitionType = {
- STATIONARY: 'STATIONARY',
- WALKING: 'WALKING',
- RUNNING: 'RUNNING',
- IN_VEHICLE: 'IN_VEHICLE'
+ STATIONARY: 'STATIONARY',
+ WALKING: 'WALKING',
+ RUNNING: 'RUNNING',
+ IN_VEHICLE: 'IN_VEHICLE'
};
var ActivityAccuracy = {
- LOW: 'LOW',
- MEDIUM: 'MEDIUM',
- HIGH: 'HIGH'
+ LOW: 'LOW',
+ MEDIUM: 'MEDIUM',
+ HIGH: 'HIGH'
};
var SleepStatus = {
- ASLEEP: 'ASLEEP',
- AWAKE: 'AWAKE'
+ ASLEEP: 'ASLEEP',
+ AWAKE: 'AWAKE'
};
var GestureType = {
- GESTURE_DOUBLE_TAP : 'GESTURE_DOUBLE_TAP',
- GESTURE_MOVE_TO_EAR : 'GESTURE_MOVE_TO_EAR',
- GESTURE_NO_MOVE : 'GESTURE_NO_MOVE',
- GESTURE_PICK_UP : 'GESTURE_PICK_UP',
- GESTURE_SHAKE : 'GESTURE_SHAKE',
- GESTURE_SNAP : 'GESTURE_SNAP',
- GESTURE_TILT : 'GESTURE_TILT',
- GESTURE_TURN_FACE_DOWN : 'GESTURE_TURN_FACE_DOWN',
- GESTURE_WRIST_UP : 'GESTURE_WRIST_UP',
+ GESTURE_DOUBLE_TAP: 'GESTURE_DOUBLE_TAP',
+ GESTURE_MOVE_TO_EAR: 'GESTURE_MOVE_TO_EAR',
+ GESTURE_NO_MOVE: 'GESTURE_NO_MOVE',
+ GESTURE_PICK_UP: 'GESTURE_PICK_UP',
+ GESTURE_SHAKE: 'GESTURE_SHAKE',
+ GESTURE_SNAP: 'GESTURE_SNAP',
+ GESTURE_TILT: 'GESTURE_TILT',
+ GESTURE_TURN_FACE_DOWN: 'GESTURE_TURN_FACE_DOWN',
+ GESTURE_WRIST_UP: 'GESTURE_WRIST_UP'
};
function convertActivityData(type, data) {
- switch (type) {
+ switch (type) {
case HumanActivityType.PEDOMETER:
- return new HumanActivityPedometerData(data);
+ return new HumanActivityPedometerData(data);
case ACCUMULATIVE_PEDOMETER_DATA:
- return new HumanActivityAccumulativePedometerData(data);
+ return new HumanActivityAccumulativePedometerData(data);
case HumanActivityType.WRIST_UP:
- return null;
+ return null;
case HumanActivityType.HRM:
- return new HumanActivityHRMData(data);
+ return new HumanActivityHRMData(data);
case HumanActivityType.GPS:
- var gpsInfo = [];
- for (var i = 0, max = data.gpsInfo.length; i < max; i++) {
- gpsInfo.push(new HumanActivityGPSInfo(data.gpsInfo[i]));
- }
- return new HumanActivityGPSInfoArray(gpsInfo);
+ var gpsInfo = [];
+ for (var i = 0, max = data.gpsInfo.length; i < max; i++) {
+ gpsInfo.push(new HumanActivityGPSInfo(data.gpsInfo[i]));
+ }
+ return new HumanActivityGPSInfoArray(gpsInfo);
case HumanActivityType.SLEEP_MONITOR:
- return new HumanActivitySleepMonitorData(data);
+ return new HumanActivitySleepMonitorData(data);
case HumanActivityType.SLEEP_DETECTOR:
- return new HumanActivitySleepDetectorData(data);
+ return new HumanActivitySleepDetectorData(data);
case HumanActivityType.STRESS_MONITOR:
- return new HumanActivityStressMonitorData(data);
+ return new HumanActivityStressMonitorData(data);
default:
- utils_.error('Uknown human activity type: ' + type);
- }
+ utils_.error('Uknown human activity type: ' + type);
+ }
}
function createRecorderData(func, data) {
- var array = [];
+ var array = [];
- data.forEach(function (d) {
- array.push(new func(d));
- });
+ data.forEach(function(d) {
+ array.push(new func(d));
+ });
- return array;
+ return array;
}
function convertActivityRecorderData(type, data) {
- var func = undefined;
- switch (type) {
+ var func = undefined;
+ switch (type) {
case HumanActivityRecorderType.PEDOMETER:
- func = HumanActivityRecorderPedometerData;
- break;
+ func = HumanActivityRecorderPedometerData;
+ break;
case HumanActivityRecorderType.HRM:
- func = HumanActivityRecorderHRMData;
- break;
+ func = HumanActivityRecorderHRMData;
+ break;
case HumanActivityRecorderType.SLEEP_MONITOR:
- func = HumanActivityRecorderSleepMonitorData;
- break;
+ func = HumanActivityRecorderSleepMonitorData;
+ break;
case HumanActivityRecorderType.PRESSURE:
- func = HumanActivityRecorderPressureData;
- break;
+ func = HumanActivityRecorderPressureData;
+ break;
default:
- utils_.error('Uknown human activity recorder type: ' + type);
- return;
- }
+ utils_.error('Uknown human activity recorder type: ' + type);
+ return;
+ }
- return createRecorderData(func, data);
+ return createRecorderData(func, data);
}
function StressMonitorDataRange(label, min, max) {
- validator_.validateConstructorCall(this, tizen.StressMonitorDataRange);
-
- var args = validator_.validateArgs(arguments, [
- { name: 'label', type: types_.STRING, optional: true, nullable: false },
- { name: 'min', type: types_.UNSIGNED_LONG, optional: true, nullable: false },
- { name: 'max', type: types_.UNSIGNED_LONG, optional: true, nullable: false }
- ]);
-
- var _label = !type_.isNullOrUndefined(args.label) ? args.label : "";
- var _min = !type_.isNullOrUndefined(args.min) ? args.min : 0;
- var _max = !type_.isNull(args.max) ? args.max : undefined;
-
- Object.defineProperties(this, {
- label: {
- get: function() {
- return _label;
- },
- set: function(v) {
- _label = !type_.isNullOrUndefined(v) ? v : _label;
- },
- enumerable: true
- },
- min: {
- get: function() {
- return _min;
- },
- set: function(v) {
- _min = !type_.isNullOrUndefined(v) ? converter_.toUnsignedLong(v) : _min;
- },
- enumerable: true
- },
- max: {
- get: function() {
- return _max;
- },
- set: function(v) {
- _max = !type_.isNullOrUndefined(v) ? converter_.toUnsignedLong(v) : _max;
- },
- enumerable: true
- }
- });
-};
-
+ validator_.validateConstructorCall(this, tizen.StressMonitorDataRange);
+
+ var args = validator_.validateArgs(arguments, [
+ { name: 'label', type: types_.STRING, optional: true, nullable: false },
+ { name: 'min', type: types_.UNSIGNED_LONG, optional: true, nullable: false },
+ { name: 'max', type: types_.UNSIGNED_LONG, optional: true, nullable: false }
+ ]);
+
+ var _label = !type_.isNullOrUndefined(args.label) ? args.label : '';
+ var _min = !type_.isNullOrUndefined(args.min) ? args.min : 0;
+ var _max = !type_.isNull(args.max) ? args.max : undefined;
+
+ Object.defineProperties(this, {
+ label: {
+ get: function() {
+ return _label;
+ },
+ set: function(v) {
+ _label = !type_.isNullOrUndefined(v) ? v : _label;
+ },
+ enumerable: true
+ },
+ min: {
+ get: function() {
+ return _min;
+ },
+ set: function(v) {
+ _min = !type_.isNullOrUndefined(v) ? converter_.toUnsignedLong(v) : _min;
+ },
+ enumerable: true
+ },
+ max: {
+ get: function() {
+ return _max;
+ },
+ set: function(v) {
+ _max = !type_.isNullOrUndefined(v) ? converter_.toUnsignedLong(v) : _max;
+ },
+ enumerable: true
+ }
+ });
+}
function ActivityRecognitionListenerManager() {
- this.listeners = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native_;
- this.listenerName = 'ActivityRecognitionListener';
-};
+ this.listeners = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native_;
+ this.listenerName = 'ActivityRecognitionListener';
+}
ActivityRecognitionListenerManager.prototype.onListener = function(data) {
- var watchId = data.watchId;
+ var watchId = data.watchId;
+
+ if (this.listeners[watchId]) {
+ if (native_.isFailure(data)) {
+ native_.callIfPossible(
+ this.listeners[watchId].errorCallback,
+ native_.getErrorObject(data)
+ );
+ return;
+ }
- if (this.listeners[watchId]) {
- if (native_.isFailure(data)) {
- native_.callIfPossible(this.listeners[watchId].errorCallback, native_.getErrorObject(data));
- return;
+ native_.callIfPossible(
+ this.listeners[watchId].listener,
+ new HumanActivityRecognitionData(native_.getResultObject(data))
+ );
}
-
- native_.callIfPossible(
- this.listeners[watchId].listener,
- new HumanActivityRecognitionData(native_.getResultObject(data)));
- }
};
-ActivityRecognitionListenerManager.prototype.addListener = function(watchId, listener, errorCallback) {
- this.listeners[watchId] = {
- listener: listener,
- errorCallback: errorCallback
- };
+ActivityRecognitionListenerManager.prototype.addListener = function(
+ watchId,
+ listener,
+ errorCallback
+) {
+ this.listeners[watchId] = {
+ listener: listener,
+ errorCallback: errorCallback
+ };
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, this.onListener.bind(this));
- this.nativeSet = true;
- }
+ if (!this.nativeSet) {
+ this.native.addListener(this.listenerName, this.onListener.bind(this));
+ this.nativeSet = true;
+ }
};
ActivityRecognitionListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- if (type_.isEmptyObject(this.listeners)) {
- this.native.removeListener(this.listenerName);
- this.nativeSet = false;
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ if (type_.isEmptyObject(this.listeners)) {
+ this.native.removeListener(this.listenerName);
+ this.nativeSet = false;
+ }
}
- }
};
var activityRecognitionListener = new ActivityRecognitionListenerManager();
-function HumanActivityMonitorManager() {
-}
+function HumanActivityMonitorManager() {}
+
+HumanActivityMonitorManager.prototype.getHumanActivityData = function(
+ type,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityType) },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (-1 === [HumanActivityType.HRM, HumanActivityType.PEDOMETER].indexOf(args.type)) {
+ throw new WebAPIException(WebAPIException.NOT_SUPPORTED_ERR);
+ }
-HumanActivityMonitorManager.prototype.getHumanActivityData = function(type, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityType)},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var data = {
+ type: args.type
+ };
- if (-1 === [HumanActivityType.HRM, HumanActivityType.PEDOMETER].indexOf(args.type)) {
- throw new WebAPIException(WebAPIException.NOT_SUPPORTED_ERR);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
- var data = {
- type: args.type
- };
+ native_.callIfPossible(
+ args.successCallback,
+ convertActivityData(args.type, native_.getResultObject(result))
+ );
+ };
+
+ var result = native_.call(
+ 'HumanActivityMonitorManager_getHumanActivityData',
+ data,
+ callback
+ );
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
-
- native_.callIfPossible(args.successCallback,
- convertActivityData(args.type, native_.getResultObject(result)));
- };
-
- var result = native_.call('HumanActivityMonitorManager_getHumanActivityData', data, callback);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
function startListener(listenerId, listener, method, data) {
- if (!native_.isListenerSet(listenerId)) {
- var result = native_.callSync(method, data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (!native_.isListenerSet(listenerId)) {
+ var result = native_.callSync(method, data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- // always set the listener, if it's another call to startListener() overwrite the old one
- native_.addListener(listenerId, listener);
+ // always set the listener
+ // if it's another call to startListener() overwrite the old one
+ native_.addListener(listenerId, listener);
}
function checkPrivilegesForMethod(method, type) {
- utils_.checkPrivilegeAccess(utils_.privilege.HEALTHINFO);
- if ('HumanActivityMonitorManager_stop' === method && 'GPS' === type) {
- utils_.checkPrivilegeAccess(utils_.privilege.LOCATION);
- }
+ utils_.checkPrivilegeAccess(utils_.privilege.HEALTHINFO);
+ if ('HumanActivityMonitorManager_stop' === method && 'GPS' === type) {
+ utils_.checkPrivilegeAccess(utils_.privilege.LOCATION);
+ }
}
function stopListener(listenerId, method, data, doRemoval) {
- if (!native_.isListenerSet(listenerId)) {
- checkPrivilegesForMethod(method, data.type);
- return;
- }
-
- if (doRemoval) {
- var result = native_.callSync(method, data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (!native_.isListenerSet(listenerId)) {
+ checkPrivilegesForMethod(method, data.type);
+ return;
}
- native_.removeListener(listenerId);
- }
+ if (doRemoval) {
+ var result = native_.callSync(method, data);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ native_.removeListener(listenerId);
+ }
}
// Pedometer listener and accumulative pedometer listener are handled by a single
@@ -322,673 +339,792 @@ var pedometerListener = null;
var accumulativePedometerListener = null;
function pedometerCallback(result) {
- if (pedometerListener) {
- pedometerListener(convertActivityData(HumanActivityType.PEDOMETER, result));
- }
+ if (pedometerListener) {
+ pedometerListener(convertActivityData(HumanActivityType.PEDOMETER, result));
+ }
- if (accumulativePedometerListener) {
- accumulativePedometerListener(convertActivityData(ACCUMULATIVE_PEDOMETER_DATA, result));
- }
+ if (accumulativePedometerListener) {
+ accumulativePedometerListener(
+ convertActivityData(ACCUMULATIVE_PEDOMETER_DATA, result)
+ );
+ }
}
var GPSListener = null;
function GPSCallback(result) {
- if (GPSListener) {
- GPSListener(result);
- }
+ if (GPSListener) {
+ GPSListener(result);
+ }
}
var stressListener = null;
HumanActivityMonitorManager.prototype.start = function(type, changedCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityType)},
- {name: 'changedCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'options', type : types_.DICTIONARY, optional : true, nullable : true}
- ]);
-
- if (HumanActivityType.WRIST_UP === args.type) {
- utils_.warn('DEPRECATION WARNING: HumanActivityType.WRIST_UP is deprecated since Tizen 4.0. '
- + 'Use GestureType and addGestureRecognitionListener to monitor WRIST_UP gesture');
- }
-
- var listenerId = 'HumanActivityMonitor_' + args.type;
- var optionsAttributes = ["callbackInterval", "sampleInterval"], options = args.options || {};
-
- var callbackInterval = null, sampleInterval = null;
-
- switch (args.type) {
- case HumanActivityType.GPS:
- callbackInterval = !type_.isNullOrUndefined(options[optionsAttributes[0]]) ?
- options[optionsAttributes[0]] : 150000;
- sampleInterval = !type_.isNullOrUndefined(options[optionsAttributes[1]]) ?
- options[optionsAttributes[1]] : 1000;
- break;
- case HumanActivityType.HRM:
- callbackInterval = !type_.isNullOrUndefined(options[optionsAttributes[0]]) ?
- options[optionsAttributes[0]] : 100;
- if (callbackInterval < 10 || callbackInterval > 1000) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'callbackInterval is out of range');
- }
- break;
- }
-
- var listener = null;
- switch (args.type) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityType) },
+ {
+ name: 'changedCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'options', type: types_.DICTIONARY, optional: true, nullable: true }
+ ]);
+
+ if (HumanActivityType.WRIST_UP === args.type) {
+ utils_.warn(
+ 'DEPRECATION WARNING: HumanActivityType.WRIST_UP is deprecated since ' +
+ 'Tizen 4.0. Use GestureType and addGestureRecognitionListener to ' +
+ 'monitor WRIST_UP gesture'
+ );
+ }
+
+ var listenerId = 'HumanActivityMonitor_' + args.type;
+ var optionsAttributes = ['callbackInterval', 'sampleInterval'],
+ options = args.options || {};
+
+ var callbackInterval = null,
+ sampleInterval = null;
+
+ switch (args.type) {
+ case HumanActivityType.GPS:
+ callbackInterval = !type_.isNullOrUndefined(options[optionsAttributes[0]])
+ ? options[optionsAttributes[0]]
+ : 150000;
+ sampleInterval = !type_.isNullOrUndefined(options[optionsAttributes[1]])
+ ? options[optionsAttributes[1]]
+ : 1000;
+ break;
+ case HumanActivityType.HRM:
+ callbackInterval = !type_.isNullOrUndefined(options[optionsAttributes[0]])
+ ? options[optionsAttributes[0]]
+ : 100;
+ if (callbackInterval < 10 || callbackInterval > 1000) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'callbackInterval is out of range'
+ );
+ }
+ break;
+ }
+
+ var listener = null;
+ switch (args.type) {
case HumanActivityType.PEDOMETER:
- listener = pedometerCallback;
- break;
+ listener = pedometerCallback;
+ break;
case HumanActivityType.GPS:
- listener = GPSCallback;
- break;
+ listener = GPSCallback;
+ break;
case HumanActivityType.STRESS_MONITOR:
- listener = stressMonitorListener.onListener;
- break;
+ listener = stressMonitorListener.onListener;
+ break;
default:
- listener = function(result) {
- native_.callIfPossible(args.changedCallback, convertActivityData(args.type, result));
- };
- }
-
- utils_.log("callbackInterval = " + callbackInterval + ", sampleInterval = " + sampleInterval);
- startListener(listenerId,
- listener,
- 'HumanActivityMonitorManager_start',
- { type: args.type,
- listenerId: listenerId,
- callbackInterval: callbackInterval,
- sampleInterval: sampleInterval
- }
- );
-
- if (HumanActivityType.PEDOMETER === args.type) {
- pedometerListener = args.changedCallback;
- }
+ listener = function(result) {
+ native_.callIfPossible(
+ args.changedCallback,
+ convertActivityData(args.type, result)
+ );
+ };
+ }
- if (HumanActivityType.GPS === args.type || HumanActivityType.STRESS_MONITOR === args.type) {
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.changedCallback, convertActivityData(args.type, result));
- }
- };
+ utils_.log(
+ 'callbackInterval = ' + callbackInterval + ', sampleInterval = ' + sampleInterval
+ );
+ startListener(listenerId, listener, 'HumanActivityMonitorManager_start', {
+ type: args.type,
+ listenerId: listenerId,
+ callbackInterval: callbackInterval,
+ sampleInterval: sampleInterval
+ });
+
+ if (HumanActivityType.PEDOMETER === args.type) {
+ pedometerListener = args.changedCallback;
+ }
- if (HumanActivityType.GPS === args.type) {
- GPSListener = callback;
- } else if (HumanActivityType.STRESS_MONITOR === args.type){
- stressListener = callback;
+ if (
+ HumanActivityType.GPS === args.type ||
+ HumanActivityType.STRESS_MONITOR === args.type
+ ) {
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(
+ args.errorCallback,
+ native_.getErrorObject(result)
+ );
+ } else {
+ native_.callIfPossible(
+ args.changedCallback,
+ convertActivityData(args.type, result)
+ );
+ }
+ };
+
+ if (HumanActivityType.GPS === args.type) {
+ GPSListener = callback;
+ } else if (HumanActivityType.STRESS_MONITOR === args.type) {
+ stressListener = callback;
+ }
}
- }
};
HumanActivityMonitorManager.prototype.stop = function(type) {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityType)}
- ]);
-
- if (HumanActivityType.WRIST_UP === args.type) {
- utils_.warn('DEPRECATION WARNING: HumanActivityType.WRIST_UP is deprecated since Tizen 4.0. '
- + 'Use GestureType and addGestureRecognitionListener to monitor WRIST_UP gesture');
- }
-
- if (HumanActivityType.PEDOMETER === args.type) {
- stopListener('HumanActivityMonitor_PEDOMETER',
- 'HumanActivityMonitorManager_stop',
- { type: HumanActivityType.PEDOMETER },
- pedometerListener && !accumulativePedometerListener);
- pedometerListener = null;
- } else {
- stopListener('HumanActivityMonitor_' + args.type,
- 'HumanActivityMonitorManager_stop',
- { type: args.type }, true);
- }
-
- if (HumanActivityType.GPS === args.type) {
- GPSListener = null;
- }
-
- if (HumanActivityType.STRESS_MONITOR === args.type) {
- stressListener = null;
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityType) }
+ ]);
+
+ if (HumanActivityType.WRIST_UP === args.type) {
+ utils_.warn(
+ 'DEPRECATION WARNING: HumanActivityType.WRIST_UP is deprecated since ' +
+ 'Tizen 4.0. Use GestureType and addGestureRecognitionListener to ' +
+ 'monitor WRIST_UP gesture'
+ );
+ }
+
+ if (HumanActivityType.PEDOMETER === args.type) {
+ stopListener(
+ 'HumanActivityMonitor_PEDOMETER',
+ 'HumanActivityMonitorManager_stop',
+ { type: HumanActivityType.PEDOMETER },
+ pedometerListener && !accumulativePedometerListener
+ );
+ pedometerListener = null;
+ } else {
+ stopListener(
+ 'HumanActivityMonitor_' + args.type,
+ 'HumanActivityMonitorManager_stop',
+ { type: args.type },
+ true
+ );
+ }
+
+ if (HumanActivityType.GPS === args.type) {
+ GPSListener = null;
+ }
+
+ if (HumanActivityType.STRESS_MONITOR === args.type) {
+ stressListener = null;
+ }
};
HumanActivityMonitorManager.prototype.setAccumulativePedometerListener = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'changeCallback', type: types_.FUNCTION}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'changeCallback', type: types_.FUNCTION }
+ ]);
- var oldPedometerListener = pedometerListener;
+ var oldPedometerListener = pedometerListener;
- // calling start() will overwrite pedometerListener, needs to be restored afterwards
- this.start(HumanActivityType.PEDOMETER, args.changeCallback);
+ // calling start() will overwrite pedometerListener, needs to be restored afterwards
+ this.start(HumanActivityType.PEDOMETER, args.changeCallback);
- accumulativePedometerListener = args.changeCallback;
- pedometerListener = oldPedometerListener;
+ accumulativePedometerListener = args.changeCallback;
+ pedometerListener = oldPedometerListener;
};
HumanActivityMonitorManager.prototype.unsetAccumulativePedometerListener = function() {
- stopListener('HumanActivityMonitor_PEDOMETER',
- 'HumanActivityMonitorManager_stop',
- { type: HumanActivityType.PEDOMETER },
- accumulativePedometerListener && !pedometerListener);
- accumulativePedometerListener = null;
+ stopListener(
+ 'HumanActivityMonitor_PEDOMETER',
+ 'HumanActivityMonitorManager_stop',
+ { type: HumanActivityType.PEDOMETER },
+ accumulativePedometerListener && !pedometerListener
+ );
+ accumulativePedometerListener = null;
};
-
HumanActivityMonitorManager.prototype.addActivityRecognitionListener = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(ActivityRecognitionType)},
- {name: 'listener', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
-
- var result = native_.call(
- 'HumanActivityMonitorManager_addActivityRecognitionListener',
- { type: args.type,
- listenerId: activityRecognitionListener.listenerName });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'type', type: types_.ENUM, values: Object.keys(ActivityRecognitionType) },
+ { name: 'listener', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var result = native_.call(
+ 'HumanActivityMonitorManager_addActivityRecognitionListener',
+ { type: args.type, listenerId: activityRecognitionListener.listenerName }
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var watchId = result.watchId;
- activityRecognitionListener.addListener(watchId, args.listener, args.errorCallback);
+ var watchId = result.watchId;
+ activityRecognitionListener.addListener(watchId, args.listener, args.errorCallback);
- return watchId;
+ return watchId;
};
HumanActivityMonitorManager.prototype.removeActivityRecognitionListener = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'watchId', type: types_.LONG},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var result = native_.call(
- 'HumanActivityMonitorManager_removeActivityRecognitionListener',
- { watchId: args.watchId });
- if (native_.isFailure(result)) {
- setTimeout(function () { native_.callIfPossible(args.errorCallback, native_.getErrorObject(result)); }, 0);
- return;
- }
- activityRecognitionListener.removeListener(args.watchId);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var result = native_.call(
+ 'HumanActivityMonitorManager_removeActivityRecognitionListener',
+ { watchId: args.watchId }
+ );
+ if (native_.isFailure(result)) {
+ setTimeout(function() {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ }, 0);
+ return;
+ }
+ activityRecognitionListener.removeListener(args.watchId);
};
HumanActivityMonitorManager.prototype.startRecorder = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityRecorderType)},
- {name: 'options', type : types_.DICTIONARY, optional: true, nullable: false}
- ]);
-
- var callArgs = {};
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(HumanActivityRecorderType)
+ },
+ { name: 'options', type: types_.DICTIONARY, optional: true, nullable: false }
+ ]);
+
+ var callArgs = {};
+
+ if (args.options) {
+ if (
+ MIN_OPTION_INTERVAL > args.options.interval ||
+ MIN_OPTION_RETENTION_PERIOD > args.options.interval
+ ) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid option value'
+ );
+ }
- if (args.options) {
- if (MIN_OPTION_INTERVAL > args.options.interval ||
- MIN_OPTION_RETENTION_PERIOD > args.options.interval) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid option value');
+ callArgs.options = args.options;
}
- callArgs.options = args.options;
- }
-
- callArgs.type = args.type;
+ callArgs.type = args.type;
- var result = native_.callSync('HumanActivityMonitorManager_startRecorder', callArgs);
+ var result = native_.callSync('HumanActivityMonitorManager_startRecorder', callArgs);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
HumanActivityMonitorManager.prototype.stopRecorder = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityRecorderType)},
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(HumanActivityRecorderType)
+ }
+ ]);
- var callArgs = {};
- callArgs.type = args.type;
+ var callArgs = {};
+ callArgs.type = args.type;
- var result = native_.callSync('HumanActivityMonitorManager_stopRecorder', callArgs);
+ var result = native_.callSync('HumanActivityMonitorManager_stopRecorder', callArgs);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
HumanActivityMonitorManager.prototype.readRecorderData = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(HumanActivityRecorderType)},
- {name: 'query', type : types_.DICTIONARY, optional: false, nullable: true},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var callArgs = {};
-
- if (args.query) {
- if ((args.query.startTime && MIN_QUERY_TIME > args.query.startTime) ||
- (args.query.endTime && MIN_QUERY_TIME > args.query.endTime) ||
- (args.query.anchorTime && MIN_QUERY_TIME > args.query.anchorTime) ||
- (args.query.interval && MIN_QUERY_INTERVAL > args.query.interval) ||
- (args.query.startTime && args.query.endTime && args.query.startTime > args.query.endTime)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid query value');
- }
- }
-
- callArgs.options = args.options;
- callArgs.type = args.type;
- callArgs.query = args.query;
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var array = convertActivityRecorderData(args.type, native_.getResultObject(result));
- args.successCallback(array);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(HumanActivityRecorderType)
+ },
+ { name: 'query', type: types_.DICTIONARY, optional: false, nullable: true },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var callArgs = {};
+
+ if (args.query) {
+ if (
+ (args.query.startTime && MIN_QUERY_TIME > args.query.startTime) ||
+ (args.query.endTime && MIN_QUERY_TIME > args.query.endTime) ||
+ (args.query.anchorTime && MIN_QUERY_TIME > args.query.anchorTime) ||
+ (args.query.interval && MIN_QUERY_INTERVAL > args.query.interval) ||
+ (args.query.startTime &&
+ args.query.endTime &&
+ args.query.startTime > args.query.endTime)
+ ) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid query value'
+ );
+ }
}
- };
- var result = native_.call('HumanActivityMonitorManager_readRecorderData', callArgs, callback);
+ callArgs.options = args.options;
+ callArgs.type = args.type;
+ callArgs.query = args.query;
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var array = convertActivityRecorderData(
+ args.type,
+ native_.getResultObject(result)
+ );
+ args.successCallback(array);
+ }
+ };
+
+ var result = native_.call(
+ 'HumanActivityMonitorManager_readRecorderData',
+ callArgs,
+ callback
+ );
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
HumanActivityMonitorManager.prototype.isGestureSupported = function() {
- var args = validator_.validateMethod(arguments, [{
- name : 'type',
- type: types_.ENUM,
- values: Object.keys(GestureType)
- }
- ]);
-
- var callArgs = {};
- callArgs.type = args.type;
-
- var result = native_.callSync('GestureManager_isGestureSupported', callArgs);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- return native_.getResultObject(result);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(GestureType)
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.type = args.type;
+
+ var result = native_.callSync('GestureManager_isGestureSupported', callArgs);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ return native_.getResultObject(result);
};
function GestureListenerManager(native, listenerName) {
- this.listeners = {};
- //below maps keep information about number of registered listeners for the specific type
- //there are two maps as one keeps information about listeners which should be always called
- //and one keeps information about number of the listeners which should be called only
- //if power-saving mode is off
- this.typeCountMapDefault = {};
- this.typeCountMapAlwaysOn = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
- for (var type in GestureType) {
- this.typeCountMapDefault[type] = this.typeCountMapAlwaysOn[type] = 0;
- }
-};
+ this.listeners = {};
+ //below maps keep information about number of registered listeners for the specific
+ //type there are two maps as one keeps information about listeners which should be
+ //always called and one keeps information about number of the listeners which should
+ //be called only if power-saving mode is off
+ this.typeCountMapDefault = {};
+ this.typeCountMapAlwaysOn = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
+ for (var type in GestureType) {
+ this.typeCountMapDefault[type] = this.typeCountMapAlwaysOn[type] = 0;
+ }
+}
GestureListenerManager.prototype.onListenerCalled = function(msg) {
- var d = undefined;
- var result = undefined;
- var alwaysOn = msg.alwaysOn;
- switch (msg.action) {
+ var d = undefined;
+ var result = undefined;
+ var alwaysOn = msg.alwaysOn;
+ switch (msg.action) {
case 'ondetect':
- d = new GestureData(this.native.getResultObject(msg));
- break;
+ d = new GestureData(this.native.getResultObject(msg));
+ break;
case 'onerror':
- d = this.native.getErrorObject(msg);
- break;
+ d = this.native.getErrorObject(msg);
+ break;
default:
- utils_.log('Unknown mode: ' + msg.action);
- return;
- }
+ utils_.log('Unknown mode: ' + msg.action);
+ return;
+ }
- for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId)) {
- var listener = this.listeners[watchId];
- var call = alwaysOn ? listener.alwaysOn : true;
- if (call && listener[msg.action]) {
- listener[msg.action](d);
- }
+ for (var watchId in this.listeners) {
+ if (this.listeners.hasOwnProperty(watchId)) {
+ var listener = this.listeners[watchId];
+ var call = alwaysOn ? listener.alwaysOn : true;
+ if (call && listener[msg.action]) {
+ listener[msg.action](d);
+ }
+ }
}
- }
};
-GestureListenerManager.prototype.addListener = function(successCb, errorCb, type, alwaysOn) {
- var listener = {
- 'type' : type,
- 'alwaysOn' : converter_.toBoolean(alwaysOn),
- 'ondetect' : successCb,
- 'onerror' : errorCb
- };
+GestureListenerManager.prototype.addListener = function(
+ successCb,
+ errorCb,
+ type,
+ alwaysOn
+) {
+ var listener = {
+ type: type,
+ alwaysOn: converter_.toBoolean(alwaysOn),
+ ondetect: successCb,
+ onerror: errorCb
+ };
- var typeCountMap = alwaysOn ? this.typeCountMapAlwaysOn : this.typeCountMapDefault;
- if (typeCountMap[type] === 0) {
- var result = this.native.callSync('GestureManager_addGestureRecognitionListener', listener);
- if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
+ var typeCountMap = alwaysOn ? this.typeCountMapAlwaysOn : this.typeCountMapDefault;
+ if (typeCountMap[type] === 0) {
+ var result = this.native.callSync(
+ 'GestureManager_addGestureRecognitionListener',
+ listener
+ );
+ if (this.native.isFailure(result)) {
+ throw this.native.getErrorObject(result);
+ }
}
- }
- typeCountMap[type]++;
- var id = this.nextId++;
- this.listeners[id] = listener;
+ typeCountMap[type]++;
+ var id = this.nextId++;
+ this.listeners[id] = listener;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- this.nativeSet = true;
- }
+ if (!this.nativeSet) {
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ this.nativeSet = true;
+ }
- return id;
+ return id;
};
GestureListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- var listener = this.listeners[watchId];
- var typeCountMap = listener.alwaysOn ? this.typeCountMapAlwaysOn : this.typeCountMapDefault;
-
- if (typeCountMap[listener.type] === 1) {
- var result = this.native.callSync('GestureManager_removeGestureRecognitionListener', listener);
- if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
+ if (this.listeners.hasOwnProperty(watchId)) {
+ var listener = this.listeners[watchId];
+ var typeCountMap = listener.alwaysOn
+ ? this.typeCountMapAlwaysOn
+ : this.typeCountMapDefault;
+
+ if (typeCountMap[listener.type] === 1) {
+ var result = this.native.callSync(
+ 'GestureManager_removeGestureRecognitionListener',
+ listener
+ );
+ if (this.native.isFailure(result)) {
+ throw this.native.getErrorObject(result);
+ }
}
- }
- delete this.listeners[watchId];
- typeCountMap[listener.type]--;
- }
+ delete this.listeners[watchId];
+ typeCountMap[listener.type]--;
+ }
- if (this.nativeSet && type_.isEmptyObject(this.listeners)) {
- this.native.removeListener(this.listenerName);
- this.nativeSet = false;
- }
+ if (this.nativeSet && type_.isEmptyObject(this.listeners)) {
+ this.native.removeListener(this.listenerName);
+ this.nativeSet = false;
+ }
};
var GESTURE_RECOGNITION_LISTENER = 'GestureRecognitionListener';
-var gestureRecognitionListener = new GestureListenerManager(native_, GESTURE_RECOGNITION_LISTENER);
+var gestureRecognitionListener = new GestureListenerManager(
+ native_,
+ GESTURE_RECOGNITION_LISTENER
+);
HumanActivityMonitorManager.prototype.addGestureRecognitionListener = function() {
- var args = validator_.validateMethod(arguments, [{
- name : 'type',
- type: types_.ENUM,
- values: Object.keys(GestureType)
- },
- {
- name : 'eventCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name : 'alwaysOn',
- type : types_.BOOLEAN,
- optional : true,
- nullable : true
- }]);
-
- return gestureRecognitionListener.addListener(args.eventCallback, args.errorCallback, args.type, args.alwaysOn);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: Object.keys(GestureType)
+ },
+ {
+ name: 'eventCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'alwaysOn',
+ type: types_.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ return gestureRecognitionListener.addListener(
+ args.eventCallback,
+ args.errorCallback,
+ args.type,
+ args.alwaysOn
+ );
};
HumanActivityMonitorManager.prototype.removeGestureRecognitionListener = function() {
- var args = validator_.validateMethod(arguments, [{
- name : 'watchId',
- type : types_.LONG,
- }]);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'watchId',
+ type: types_.LONG
+ }
+ ]);
- gestureRecognitionListener.removeListener(args.watchId);
+ gestureRecognitionListener.removeListener(args.watchId);
};
function StressMonitorListenerManager() {
- this.listeners = {};
- this.nextId = 1;
-};
+ this.listeners = {};
+ this.nextId = 1;
+}
StressMonitorListenerManager.prototype.onListener = function(data) {
-
- if (stressListener) {
- stressListener(data);
- }
- var score = data.stressScore;
- for (var watchId in stressMonitorListener.listeners) {
- if (stressMonitorListener.listeners.hasOwnProperty(watchId)) {
- var _listener = stressMonitorListener.listeners[watchId];
- var rangeArray = _listener.ranges;
- for (var id in rangeArray) {
- var _min = rangeArray[id].min;
- var _max = !type_.isUndefined(rangeArray[id].max) ? rangeArray[id].max : Number.MAX_VALUE;
- if ((score >= _min && score < _max) && (_listener.lastStressScore < _min || _listener.lastStressScore >= _max)) {
- _listener.listener(rangeArray[id].label);
+ if (stressListener) {
+ stressListener(data);
+ }
+ var score = data.stressScore;
+ for (var watchId in stressMonitorListener.listeners) {
+ if (stressMonitorListener.listeners.hasOwnProperty(watchId)) {
+ var _listener = stressMonitorListener.listeners[watchId];
+ var rangeArray = _listener.ranges;
+ for (var id in rangeArray) {
+ var _min = rangeArray[id].min;
+ var _max = !type_.isUndefined(rangeArray[id].max)
+ ? rangeArray[id].max
+ : Number.MAX_VALUE;
+ if (
+ score >= _min &&
+ score < _max &&
+ (_listener.lastStressScore < _min ||
+ _listener.lastStressScore >= _max)
+ ) {
+ _listener.listener(rangeArray[id].label);
+ }
+ }
+ _listener.lastStressScore = score;
}
- }
- _listener.lastStressScore = score;
}
- }
};
-StressMonitorListenerManager.prototype.addListener = function(ranges, listener, errorCallback) {
-
- var id = this.nextId++;
-
- this.listeners[id] = {
- ranges: ranges,
- listener: listener,
- lastStressScore: -1
- };
+StressMonitorListenerManager.prototype.addListener = function(
+ ranges,
+ listener,
+ errorCallback
+) {
+ var id = this.nextId++;
+
+ this.listeners[id] = {
+ ranges: ranges,
+ listener: listener,
+ lastStressScore: -1
+ };
- return id;
+ return id;
};
StressMonitorListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- }
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ }
};
var stressMonitorListener = new StressMonitorListenerManager();
HumanActivityMonitorManager.prototype.addStressMonitorChangeListener = function() {
- utils_.checkPrivilegeAccess(privilege_.HEALTHINFO);
- var args = validator_.validateMethod(arguments, [{
- name : 'ranges',
- type: types_.ARRAY,
- values: StressMonitorDataRange
- },
- {
- name : 'listener',
- type : types_.FUNCTION
- }]);
-
- return stressMonitorListener.addListener(args.ranges, args.listener);
+ utils_.checkPrivilegeAccess(privilege_.HEALTHINFO);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'ranges',
+ type: types_.ARRAY,
+ values: StressMonitorDataRange
+ },
+ {
+ name: 'listener',
+ type: types_.FUNCTION
+ }
+ ]);
+
+ return stressMonitorListener.addListener(args.ranges, args.listener);
};
-HumanActivityMonitorManager.prototype.removeStressMonitorChangeListener = function() {
- var args = validator_.validateMethod(arguments, [{
- name : 'watchId',
- type : types_.LONG,
- }]);
+HumanActivityMonitorManager.prototype.removeStressMonitorChangeListener = function() {
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'watchId',
+ type: types_.LONG
+ }
+ ]);
- stressMonitorListener.removeListener(args.watchId);
+ stressMonitorListener.removeListener(args.watchId);
};
function StepDifference(data) {
- SetReadOnlyProperty(this, 'stepCountDifference', data.stepCountDifference);
- SetReadOnlyProperty(this, 'timestamp', data.timestamp);
-}
-
-
-function HumanActivityData() {
+ SetReadOnlyProperty(this, 'stepCountDifference', data.stepCountDifference);
+ SetReadOnlyProperty(this, 'timestamp', data.timestamp);
}
+function HumanActivityData() {}
function HumanActivityPedometerData(data) {
- SetReadOnlyProperty(this, 'stepStatus', data.stepStatus);
- SetReadOnlyProperty(this, 'speed', data.speed);
- SetReadOnlyProperty(this, 'walkingFrequency', data.walkingFrequency);
- SetReadOnlyProperty(this, 'cumulativeDistance', data.cumulativeDistance);
- SetReadOnlyProperty(this, 'cumulativeCalorie', data.cumulativeCalorie);
- SetReadOnlyProperty(this, 'cumulativeTotalStepCount', data.cumulativeTotalStepCount);
- SetReadOnlyProperty(this, 'cumulativeWalkStepCount', data.cumulativeWalkStepCount);
- SetReadOnlyProperty(this, 'cumulativeRunStepCount', data.cumulativeRunStepCount);
-
- var steps = [];
- for (var i = 0; i < data.stepCountDifferences.length; ++i) {
- steps.push(new StepDifference(data.stepCountDifferences[i]));
- }
- SetReadOnlyProperty(this, 'stepCountDifferences', steps);
+ SetReadOnlyProperty(this, 'stepStatus', data.stepStatus);
+ SetReadOnlyProperty(this, 'speed', data.speed);
+ SetReadOnlyProperty(this, 'walkingFrequency', data.walkingFrequency);
+ SetReadOnlyProperty(this, 'cumulativeDistance', data.cumulativeDistance);
+ SetReadOnlyProperty(this, 'cumulativeCalorie', data.cumulativeCalorie);
+ SetReadOnlyProperty(this, 'cumulativeTotalStepCount', data.cumulativeTotalStepCount);
+ SetReadOnlyProperty(this, 'cumulativeWalkStepCount', data.cumulativeWalkStepCount);
+ SetReadOnlyProperty(this, 'cumulativeRunStepCount', data.cumulativeRunStepCount);
+
+ var steps = [];
+ for (var i = 0; i < data.stepCountDifferences.length; ++i) {
+ steps.push(new StepDifference(data.stepCountDifferences[i]));
+ }
+ SetReadOnlyProperty(this, 'stepCountDifferences', steps);
}
HumanActivityPedometerData.prototype = new HumanActivityData();
HumanActivityPedometerData.prototype.constructor = HumanActivityPedometerData;
-
function HumanActivityAccumulativePedometerData(data) {
- SetReadOnlyProperty(this, 'stepStatus', data.stepStatus);
- SetReadOnlyProperty(this, 'speed', data.speed);
- SetReadOnlyProperty(this, 'walkingFrequency', data.walkingFrequency);
- SetReadOnlyProperty(this, 'accumulativeDistance', data.accumulativeDistance);
- SetReadOnlyProperty(this, 'accumulativeCalorie', data.accumulativeCalorie);
- SetReadOnlyProperty(this, 'accumulativeTotalStepCount', data.accumulativeTotalStepCount);
- SetReadOnlyProperty(this, 'accumulativeWalkStepCount', data.accumulativeWalkStepCount);
- SetReadOnlyProperty(this, 'accumulativeRunStepCount', data.accumulativeRunStepCount);
-
- var steps = [];
- for (var i = 0; i < data.stepCountDifferences.length; ++i) {
- steps.push(new StepDifference(data.stepCountDifferences[i]));
- }
- SetReadOnlyProperty(this, 'stepCountDifferences', steps);
+ SetReadOnlyProperty(this, 'stepStatus', data.stepStatus);
+ SetReadOnlyProperty(this, 'speed', data.speed);
+ SetReadOnlyProperty(this, 'walkingFrequency', data.walkingFrequency);
+ SetReadOnlyProperty(this, 'accumulativeDistance', data.accumulativeDistance);
+ SetReadOnlyProperty(this, 'accumulativeCalorie', data.accumulativeCalorie);
+ SetReadOnlyProperty(
+ this,
+ 'accumulativeTotalStepCount',
+ data.accumulativeTotalStepCount
+ );
+ SetReadOnlyProperty(
+ this,
+ 'accumulativeWalkStepCount',
+ data.accumulativeWalkStepCount
+ );
+ SetReadOnlyProperty(this, 'accumulativeRunStepCount', data.accumulativeRunStepCount);
+
+ var steps = [];
+ for (var i = 0; i < data.stepCountDifferences.length; ++i) {
+ steps.push(new StepDifference(data.stepCountDifferences[i]));
+ }
+ SetReadOnlyProperty(this, 'stepCountDifferences', steps);
}
HumanActivityAccumulativePedometerData.prototype = new HumanActivityData();
-HumanActivityAccumulativePedometerData.prototype.constructor = HumanActivityAccumulativePedometerData;
-
+// prettier-ignore
+HumanActivityAccumulativePedometerData.prototype.constructor =
+ HumanActivityAccumulativePedometerData;
function HumanActivityHRMData(data) {
- SetReadOnlyProperty(this, 'heartRate', data.heartRate);
- SetReadOnlyProperty(this, 'rRInterval', data.rRInterval);
+ SetReadOnlyProperty(this, 'heartRate', data.heartRate);
+ SetReadOnlyProperty(this, 'rRInterval', data.rRInterval);
}
HumanActivityHRMData.prototype = new HumanActivityData();
HumanActivityHRMData.prototype.constructor = HumanActivityHRMData;
function HumanActivityRecognitionData(data) {
- SetReadOnlyProperty(this, 'type', data.type);
- SetReadOnlyProperty(this, 'timestamp', data.timestamp);
- SetReadOnlyProperty(this, 'accuracy', data.accuracy);
+ SetReadOnlyProperty(this, 'type', data.type);
+ SetReadOnlyProperty(this, 'timestamp', data.timestamp);
+ SetReadOnlyProperty(this, 'accuracy', data.accuracy);
}
HumanActivityRecognitionData.prototype = new HumanActivityData();
HumanActivityRecognitionData.prototype.constructor = HumanActivityRecognitionData;
function HumanActivityGPSInfo(data) {
- SetReadOnlyProperty(this, 'latitude', data.latitude);
- SetReadOnlyProperty(this, 'longitude', data.longitude);
- SetReadOnlyProperty(this, 'altitude', data.altitude);
- SetReadOnlyProperty(this, 'speed', data.speed);
- SetReadOnlyProperty(this, 'errorRange', data.errorRange);
- SetReadOnlyProperty(this, 'timestamp', data.timestamp);
+ SetReadOnlyProperty(this, 'latitude', data.latitude);
+ SetReadOnlyProperty(this, 'longitude', data.longitude);
+ SetReadOnlyProperty(this, 'altitude', data.altitude);
+ SetReadOnlyProperty(this, 'speed', data.speed);
+ SetReadOnlyProperty(this, 'errorRange', data.errorRange);
+ SetReadOnlyProperty(this, 'timestamp', data.timestamp);
}
-
function HumanActivityGPSInfoArray(data) {
- SetReadOnlyProperty(this, 'gpsInfo', data);
+ SetReadOnlyProperty(this, 'gpsInfo', data);
}
HumanActivityGPSInfoArray.prototype = new HumanActivityData();
HumanActivityGPSInfoArray.prototype.constructor = HumanActivityGPSInfoArray;
function HumanActivitySleepMonitorData(data) {
- SetReadOnlyProperty(this, 'status', data.status);
- SetReadOnlyProperty(this, 'timestamp', data.timestamp);
+ SetReadOnlyProperty(this, 'status', data.status);
+ SetReadOnlyProperty(this, 'timestamp', data.timestamp);
}
HumanActivitySleepMonitorData.prototype = new HumanActivityData();
HumanActivitySleepMonitorData.prototype.constructor = HumanActivitySleepMonitorData;
function HumanActivitySleepDetectorData(data) {
- SetReadOnlyProperty(this, 'status', data.status);
+ SetReadOnlyProperty(this, 'status', data.status);
}
HumanActivitySleepDetectorData.prototype = new HumanActivityData();
HumanActivitySleepDetectorData.prototype.constructor = HumanActivitySleepMonitorData;
function HumanActivityStressMonitorData(data) {
- SetReadOnlyProperty(this, 'stressScore', data.stressScore);
+ SetReadOnlyProperty(this, 'stressScore', data.stressScore);
}
HumanActivityStressMonitorData.prototype = new HumanActivityData();
-HumanActivityStressMonitorData.prototype.constructor = HumanActivityStressMonitorData
+HumanActivityStressMonitorData.prototype.constructor = HumanActivityStressMonitorData;
//Recorded data
function HumanActivityRecorderData(data) {
- if (data) {
- SetReadOnlyProperty(this, 'startTime', data.startTime);
- SetReadOnlyProperty(this, 'endTime', data.endTime);
- }
+ if (data) {
+ SetReadOnlyProperty(this, 'startTime', data.startTime);
+ SetReadOnlyProperty(this, 'endTime', data.endTime);
+ }
}
function HumanActivityRecorderPedometerData(data) {
- HumanActivityRecorderData.call(this, data);
- SetReadOnlyProperty(this, 'distance', data.distance);
- SetReadOnlyProperty(this, 'calorie', data.calorie);
- SetReadOnlyProperty(this, 'totalStepCount', data.totalStepCount);
- SetReadOnlyProperty(this, 'walkStepCount', data.walkStepCount);
- SetReadOnlyProperty(this, 'runStepCount', data.runStepCount);
+ HumanActivityRecorderData.call(this, data);
+ SetReadOnlyProperty(this, 'distance', data.distance);
+ SetReadOnlyProperty(this, 'calorie', data.calorie);
+ SetReadOnlyProperty(this, 'totalStepCount', data.totalStepCount);
+ SetReadOnlyProperty(this, 'walkStepCount', data.walkStepCount);
+ SetReadOnlyProperty(this, 'runStepCount', data.runStepCount);
}
HumanActivityRecorderPedometerData.prototype = new HumanActivityRecorderData();
-HumanActivityRecorderPedometerData.prototype.constructor = HumanActivityRecorderPedometerData;
+// prettier-ignore
+HumanActivityRecorderPedometerData.prototype.constructor =
+ HumanActivityRecorderPedometerData;
function HumanActivityRecorderHRMData(data) {
- HumanActivityRecorderData.call(this, data);
- SetReadOnlyProperty(this, 'heartRate', data.heartRate);
+ HumanActivityRecorderData.call(this, data);
+ SetReadOnlyProperty(this, 'heartRate', data.heartRate);
}
HumanActivityRecorderHRMData.prototype = new HumanActivityRecorderData();
HumanActivityRecorderHRMData.prototype.constructor = HumanActivityRecorderHRMData;
function HumanActivityRecorderSleepMonitorData(data) {
- HumanActivityRecorderData.call(this, data);
- SetReadOnlyProperty(this, 'status', data.status);
+ HumanActivityRecorderData.call(this, data);
+ SetReadOnlyProperty(this, 'status', data.status);
}
HumanActivityRecorderSleepMonitorData.prototype = new HumanActivityRecorderData();
-HumanActivityRecorderSleepMonitorData.prototype.constructor = HumanActivityRecorderSleepMonitorData;
+// prettier-ignore
+HumanActivityRecorderSleepMonitorData.prototype.constructor =
+ HumanActivityRecorderSleepMonitorData;
function HumanActivityRecorderPressureData(data) {
- HumanActivityRecorderData.call(this, data);
- SetReadOnlyProperty(this, 'max', data.max);
- SetReadOnlyProperty(this, 'min', data.min);
- SetReadOnlyProperty(this, 'average', data.average);
+ HumanActivityRecorderData.call(this, data);
+ SetReadOnlyProperty(this, 'max', data.max);
+ SetReadOnlyProperty(this, 'min', data.min);
+ SetReadOnlyProperty(this, 'average', data.average);
}
function GestureData(data) {
- if (data) {
- SetReadOnlyProperty(this, 'type', data.type);
- SetReadOnlyProperty(this, 'event', data.event);
- SetReadOnlyProperty(this, 'timestamp', data.timestamp);
-
- if (data.type === 'GESTURE_TILT') {
- SetReadOnlyProperty(this, 'x', data.x);
- SetReadOnlyProperty(this, 'y', data.y);
- } else {
- SetReadOnlyProperty(this, 'x', null);
- SetReadOnlyProperty(this, 'y', null);
+ if (data) {
+ SetReadOnlyProperty(this, 'type', data.type);
+ SetReadOnlyProperty(this, 'event', data.event);
+ SetReadOnlyProperty(this, 'timestamp', data.timestamp);
+
+ if (data.type === 'GESTURE_TILT') {
+ SetReadOnlyProperty(this, 'x', data.x);
+ SetReadOnlyProperty(this, 'y', data.y);
+ } else {
+ SetReadOnlyProperty(this, 'x', null);
+ SetReadOnlyProperty(this, 'y', null);
+ }
}
- }
}
HumanActivityRecorderPressureData.prototype = new HumanActivityRecorderData();
-HumanActivityRecorderPressureData.prototype.constructor = HumanActivityRecorderPressureData;
+// prettier-ignore
+HumanActivityRecorderPressureData.prototype.constructor =
+ HumanActivityRecorderPressureData;
tizen.StressMonitorDataRange = StressMonitorDataRange;
diff --git a/src/inputdevice/inputdevice_api.js b/src/inputdevice/inputdevice_api.js
index 1bd9576b..e8281980 100644
--- a/src/inputdevice/inputdevice_api.js
+++ b/src/inputdevice/inputdevice_api.js
@@ -13,43 +13,42 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var native = new xwalk.utils.NativeManager(extension);
var validator = xwalk.utils.validator;
var types = validator.Types;
var map = {
- "VolumeUp": {
- keyName: "XF86AudioRaiseVolume",
- keyCode: 175
- },
- "VolumeDown": {
- keyName: "XF86AudioLowerVolume",
- keyCode: 174
- },
+ VolumeUp: {
+ keyName: 'XF86AudioRaiseVolume',
+ keyCode: 175
+ },
+ VolumeDown: {
+ keyName: 'XF86AudioLowerVolume',
+ keyCode: 174
+ }
};
-
function InputDeviceKey(dict) {
- for (var key in dict) {
- if (dict.hasOwnProperty(key)) {
- Object.defineProperty(this, key, {
- value: dict[key],
- enumerable: true
- });
+ for (var key in dict) {
+ if (dict.hasOwnProperty(key)) {
+ Object.defineProperty(this, key, {
+ value: dict[key],
+ enumerable: true
+ });
+ }
}
- }
- Object.freeze(this);
+ Object.freeze(this);
}
-
/**
- * This class provides access to the API functionalities through the tizen.tvinputdevice interface.
+ * This class provides access to the API functionalities through the
+ * tizen.tvinputdevice interface.
* @constructor
*/
function InputDeviceManager() {
- if (!(this instanceof InputDeviceManager)) {
- throw new TypeError;
- }
+ if (!(this instanceof InputDeviceManager)) {
+ throw new TypeError();
+ }
}
/**
@@ -57,160 +56,196 @@ function InputDeviceManager() {
* @return {array} Array of keys
*/
InputDeviceManager.prototype.getSupportedKeys = function() {
+ var re = [];
+ for (var key in map) {
+ if (map.hasOwnProperty(key)) {
+ re.push(new InputDeviceKey({ name: key, code: map[key].keyCode }));
+ }
+ }
- var re = [];
- for (var key in map) {
- if (map.hasOwnProperty(key)) {
- re.push(new InputDeviceKey({name: key, code: map[key].keyCode}));
- }
- }
-
- return re;
+ return re;
};
-
/**
* Returns information about the key which has the given name.
* @param {!string} keyName The key name
* @return {object} Key object
*/
InputDeviceManager.prototype.getKey = function(keyName) {
- var args = validator.validateArgs(arguments, [
- {name: 'keyName', type: types.STRING}
- ]);
-
- if (!map[args.keyName]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Parameter "keyName" is invalid.');
- }
-
- return new InputDeviceKey( { name: args.keyName, code: map[args.keyName].keyCode } );
+ var args = validator.validateArgs(arguments, [
+ { name: 'keyName', type: types.STRING }
+ ]);
+
+ if (!map[args.keyName]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Parameter "keyName" is invalid.'
+ );
+ }
+ return new InputDeviceKey({ name: args.keyName, code: map[args.keyName].keyCode });
};
-
/**
- * Registers an input device key to receive DOM keyboard event when it is pressed or released.
+ * Registers an input device key to receive DOM keyboard event when it is pressed or
+ * released.
* @param {!string} keyName The key name
*/
InputDeviceManager.prototype.registerKey = function(keyName) {
- var args = validator.validateArgs(arguments, [
- {name: 'keyName', type: types.STRING}
- ]);
- if (!map[args.keyName]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Parameter "keyName" is invalid.');
- }
-
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/registerKey',map[args.keyName].keyName);
-
- if (ret === 'error') {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
- }
-};
+ var args = validator.validateArgs(arguments, [
+ { name: 'keyName', type: types.STRING }
+ ]);
+ if (!map[args.keyName]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Parameter "keyName" is invalid.'
+ );
+ }
+
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/registerKey',
+ map[args.keyName].keyName
+ );
+ if (ret === 'error') {
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
+ }
+};
/**
* Unregisters an input device key.
* @param {!string} keyName The key name
*/
InputDeviceManager.prototype.unregisterKey = function(keyName) {
- var args = validator.validateArgs(arguments, [
- {name: 'keyName', type: types.STRING}
- ]);
-
- if (!map[args.keyName]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Parameter "keyName" is invalid.');
- }
-
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/unregisterKey',map[args.keyName].keyName);
-
- if (ret === 'error') {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
- }
-};
-
-InputDeviceManager.prototype.registerKeyBatch = function() {
- var args = validator.validateMethod(arguments, [
- {
- name: 'keyNames',
- type: types.ARRAY,
- values: types.STRING
- },
- {
- name: 'successCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
+ var args = validator.validateArgs(arguments, [
+ { name: 'keyName', type: types.STRING }
+ ]);
+
+ if (!map[args.keyName]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Parameter "keyName" is invalid.'
+ );
}
- ]);
- var keysList = "";
- for (var i = 0; i < args.keyNames.length; ++i) {
- if (!map[args.keyNames[i]]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid key name: "' + args.keyNames[i] + '"');
- }
- keysList += map[args.keyNames[i]].keyName + ((i < args.keyNames.length - 1) ? "," : "");
- }
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/unregisterKey',
+ map[args.keyName].keyName
+ );
- setTimeout(function() {
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/registerKeyBatch', keysList);
if (ret === 'error') {
- native.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.UNKNOWN_ERR, 'Failed to register keys.'));
- } else {
- native.callIfPossible(args.successCallback);
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
}
- }.bind(this), 0);
};
-InputDeviceManager.prototype.unregisterKeyBatch = function() {
- var args = validator.validateMethod(arguments, [
- {
- name: 'keyNames',
- type: types.ARRAY,
- values: types.STRING
- },
- {
- name: 'successCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
+InputDeviceManager.prototype.registerKeyBatch = function() {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'keyNames',
+ type: types.ARRAY,
+ values: types.STRING
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var keysList = '';
+ for (var i = 0; i < args.keyNames.length; ++i) {
+ if (!map[args.keyNames[i]]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid key name: "' + args.keyNames[i] + '"'
+ );
+ }
+ keysList +=
+ map[args.keyNames[i]].keyName + (i < args.keyNames.length - 1 ? ',' : '');
}
- ]);
- var keysList = "";
- for (var i = 0; i < args.keyNames.length; ++i) {
- if (!map[args.keyNames[i]]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid key name: "' + args.keyNames[i] + '"');
- }
- keysList += map[args.keyNames[i]].keyName + ((i < args.keyNames.length - 1) ? "," : "");
- }
+ setTimeout(
+ function() {
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/registerKeyBatch',
+ keysList
+ );
+ if (ret === 'error') {
+ native.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Failed to register keys.'
+ )
+ );
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ }.bind(this),
+ 0
+ );
+};
- setTimeout(function() {
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/unregisterKeyBatch', keysList);
- if (ret === 'error') {
- native.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.UNKNOWN_ERR, 'Failed to unregister keys.'));
- } else {
- native.callIfPossible(args.successCallback);
+InputDeviceManager.prototype.unregisterKeyBatch = function() {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'keyNames',
+ type: types.ARRAY,
+ values: types.STRING
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var keysList = '';
+ for (var i = 0; i < args.keyNames.length; ++i) {
+ if (!map[args.keyNames[i]]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid key name: "' + args.keyNames[i] + '"'
+ );
+ }
+ keysList +=
+ map[args.keyNames[i]].keyName + (i < args.keyNames.length - 1 ? ',' : '');
}
- }.bind(this), 0);
+
+ setTimeout(
+ function() {
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/unregisterKeyBatch',
+ keysList
+ );
+ if (ret === 'error') {
+ native.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Failed to unregister keys.'
+ )
+ );
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ }.bind(this),
+ 0
+ );
};
// Exports
diff --git a/src/iotcon/iotcon_api.js b/src/iotcon/iotcon_api.js
index bd3f32db..e7a7d16a 100644
--- a/src/iotcon/iotcon_api.js
+++ b/src/iotcon/iotcon_api.js
@@ -19,1421 +19,1525 @@ var validator = xwalk.utils.validator;
var types = validator.Types;
var T = xwalk.utils.type;
var kIdKey = Symbol();
-var converter = xwalk.utils.converter;
+var converter = xwalk.utils.converter;
var privUtils_ = xwalk.utils;
function createListener(name, c) {
- var listenerName = name;
- var callback = c || function(response) {
- return response;
- };
- var listeners = {};
- var jsListenerRegistered = false;
-
- function internalCallback(response) {
- if (native.isSuccess(response)) {
- response = native.getResultObject(response);
- if (listeners[response.id]) {
- listeners[response.id](callback(response));
- }
- }
- }
-
- function addListener(id, func) {
- if (!jsListenerRegistered) {
- native.addListener(listenerName, internalCallback);
- jsListenerRegistered = true;
+ var listenerName = name;
+ var callback =
+ c ||
+ function(response) {
+ return response;
+ };
+ var listeners = {};
+ var jsListenerRegistered = false;
+
+ function internalCallback(response) {
+ if (native.isSuccess(response)) {
+ response = native.getResultObject(response);
+ if (listeners[response.id]) {
+ listeners[response.id](callback(response));
+ }
+ }
}
- listeners[id] = func;
- }
+ function addListener(id, func) {
+ if (!jsListenerRegistered) {
+ native.addListener(listenerName, internalCallback);
+ jsListenerRegistered = true;
+ }
- function removeListener(id) {
- if (listeners[id]) {
- delete listeners[id];
+ listeners[id] = func;
}
- if (jsListenerRegistered && T.isEmptyObject(listeners)) {
- native.removeListener(listenerName, internalCallback);
- jsListenerRegistered = false;
+ function removeListener(id) {
+ if (listeners[id]) {
+ delete listeners[id];
+ }
+
+ if (jsListenerRegistered && T.isEmptyObject(listeners)) {
+ native.removeListener(listenerName, internalCallback);
+ jsListenerRegistered = false;
+ }
}
- }
- return {
- addListener: addListener,
- removeListener: removeListener
- };
+ return {
+ addListener: addListener,
+ removeListener: removeListener
+ };
}
function InternalData(d) {
- for (var prop in d) {
- if (d.hasOwnProperty(prop)) {
- this[prop] = d[prop];
+ for (var prop in d) {
+ if (d.hasOwnProperty(prop)) {
+ this[prop] = d[prop];
+ }
}
- }
}
InternalData.prototype.update = function(dst) {
- for (var prop in this) {
- if (this.hasOwnProperty(prop) && dst.hasOwnProperty(prop)) {
- dst[prop] = this;
+ for (var prop in this) {
+ if (this.hasOwnProperty(prop) && dst.hasOwnProperty(prop)) {
+ dst[prop] = this;
+ }
}
- }
};
InternalData.prototype.decorate = function(dst) {
- var that = this;
- function getBuilder(prop) {
- if (T.isArray(that[prop])) {
- return function() {
- return that[prop].slice();
- };
- } else {
- return function() {
- return that[prop];
- };
+ var that = this;
+ function getBuilder(prop) {
+ if (T.isArray(that[prop])) {
+ return function() {
+ return that[prop].slice();
+ };
+ } else {
+ return function() {
+ return that[prop];
+ };
+ }
}
- }
- function setBuilder(prop) {
- return function(d) {
- if (d instanceof InternalData) {
- that[prop] = d[prop];
- }
- };
- }
- for (var prop in this) {
- if (this.hasOwnProperty(prop)) {
- Object.defineProperty(dst, prop, {
- get: getBuilder(prop),
- set: setBuilder(prop),
- enumerable: true
- });
+ function setBuilder(prop) {
+ return function(d) {
+ if (d instanceof InternalData) {
+ that[prop] = d[prop];
+ }
+ };
+ }
+ for (var prop in this) {
+ if (this.hasOwnProperty(prop)) {
+ Object.defineProperty(dst, prop, {
+ get: getBuilder(prop),
+ set: setBuilder(prop),
+ enumerable: true
+ });
+ }
}
- }
};
function updateWithInternalData(src, dst) {
- new InternalData(src).update(dst);
+ new InternalData(src).update(dst);
}
function decorateWithData(data, dst) {
- for (var prop in data) {
- if (data.hasOwnProperty(prop)) {
- Object.defineProperty(dst, prop, {
- value: data[prop],
- writable: false,
- enumerable: true
- });
+ for (var prop in data) {
+ if (data.hasOwnProperty(prop)) {
+ Object.defineProperty(dst, prop, {
+ value: data[prop],
+ writable: false,
+ enumerable: true
+ });
+ }
}
- }
}
var ResponseResult = {
- SUCCESS: 'SUCCESS',
- ERROR: 'ERROR',
- RESOURCE_CREATED: 'RESOURCE_CREATED',
- RESOURCE_DELETED: 'RESOURCE_DELETED',
- RESOURCE_CHANGED: 'RESOURCE_CHANGED',
- SLOW: 'SLOW',
- FORBIDDEN: 'FORBIDDEN',
+ SUCCESS: 'SUCCESS',
+ ERROR: 'ERROR',
+ RESOURCE_CREATED: 'RESOURCE_CREATED',
+ RESOURCE_DELETED: 'RESOURCE_DELETED',
+ RESOURCE_CHANGED: 'RESOURCE_CHANGED',
+ SLOW: 'SLOW',
+ FORBIDDEN: 'FORBIDDEN'
};
var PresenceResponseResultType = {
- SUCCESS: 'SUCCESS',
- STOPPED: 'STOPPED',
- TIMEOUT: 'TIMEOUT'
+ SUCCESS: 'SUCCESS',
+ STOPPED: 'STOPPED',
+ TIMEOUT: 'TIMEOUT'
};
var PresenceTriggerType = {
- CREATED: 'CREATED',
- UPDATED: 'UPDATED',
- DESTROYED: 'DESTROYED'
+ CREATED: 'CREATED',
+ UPDATED: 'UPDATED',
+ DESTROYED: 'DESTROYED'
};
var ConnectivityType = {
- IP: "IP",
- PREFER_UDP: "PREFER_UDP",
- PREFER_TCP: "PREFER_TCP",
- IPV4_ONLY: "IPV4_ONLY",
- IPV6_ONLY: "IPV6_ONLY",
- ALL: 'ALL'
+ IP: 'IP',
+ PREFER_UDP: 'PREFER_UDP',
+ PREFER_TCP: 'PREFER_TCP',
+ IPV4_ONLY: 'IPV4_ONLY',
+ IPV6_ONLY: 'IPV6_ONLY',
+ ALL: 'ALL'
};
var ObservePolicy = {
- IGNORE_OUT_OF_ORDER: 'IGNORE_OUT_OF_ORDER',
- ACCEPT_OUT_OF_ORDER: 'ACCEPT_OUT_OF_ORDER'
+ IGNORE_OUT_OF_ORDER: 'IGNORE_OUT_OF_ORDER',
+ ACCEPT_OUT_OF_ORDER: 'ACCEPT_OUT_OF_ORDER'
};
var PresenceTriggerType = {
- NO_TYPE: 'NO_TYPE',
- REGISTER: 'REGISTER',
- DEREGISTER: 'DEREGISTER'
+ NO_TYPE: 'NO_TYPE',
+ REGISTER: 'REGISTER',
+ DEREGISTER: 'DEREGISTER'
};
var QosLevel = {
- LOW: 'LOW',
- HIGH: 'HIGH'
+ LOW: 'LOW',
+ HIGH: 'HIGH'
};
var RequestType = {
- UNKNOWN: 'UNKNOWN',
- GET: 'GET',
- PUT: 'PUT',
- POST: 'POST',
- DELETE: 'DELETE'
+ UNKNOWN: 'UNKNOWN',
+ GET: 'GET',
+ PUT: 'PUT',
+ POST: 'POST',
+ DELETE: 'DELETE'
};
var ObserveType = {
- NO_TYPE: 'NO_TYPE',
- REGISTER: 'REGISTER',
- DEREGISTER: 'DEREGISTER'
+ NO_TYPE: 'NO_TYPE',
+ REGISTER: 'REGISTER',
+ DEREGISTER: 'DEREGISTER'
};
function DeviceInfo(data) {
- decorateWithData(data, this);
+ decorateWithData(data, this);
}
function IotconOption(id, data) {
- validator.isConstructorCall(this, tizen.IotconOption);
-
- var _id = 0;
- var _data = '';
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return _id;
- },
- set: function(v) {
- if (v) {
- _id = v;
- }
- },
- enumerable: true
- },
- data: {
- get: function() {
- return _data;
- },
- set: function(v) {
- if (v) {
- _data = v;
+ validator.isConstructorCall(this, tizen.IotconOption);
+
+ var _id = 0;
+ var _data = '';
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return _id;
+ },
+ set: function(v) {
+ if (v) {
+ _id = v;
+ }
+ },
+ enumerable: true
+ },
+ data: {
+ get: function() {
+ return _data;
+ },
+ set: function(v) {
+ if (v) {
+ _data = v;
+ }
+ },
+ enumerable: true
}
- },
- enumerable: true
- }
- });
+ });
- this["id"] = id;
- this["data"] = data;
+ this['id'] = id;
+ this['data'] = data;
}
function PlatformInfo(data) {
- decorateWithData(data, this);
+ decorateWithData(data, this);
}
function PresenceResponse(data) {
- decorateWithData(data, this);
+ decorateWithData(data, this);
}
function Representation(uriPath) {
- validator.isConstructorCall(this, tizen.Representation);
-
- Object.defineProperties(this, {
- uriPath: {
- value: uriPath,
- writable: true,
- enumerable: true
- },
- resourceTypes: {
- value: [],
- writable: true,
- enumerable: true
- },
- resourceInterfaces: {
- value: [],
- writable: true,
- enumerable: true
- },
- attributes: {
- value: null,
- writable: true,
- enumerable: true
- },
- children: {
- value: null,
- writable: true,
- enumerable: true
- }
- });
+ validator.isConstructorCall(this, tizen.Representation);
+
+ Object.defineProperties(this, {
+ uriPath: {
+ value: uriPath,
+ writable: true,
+ enumerable: true
+ },
+ resourceTypes: {
+ value: [],
+ writable: true,
+ enumerable: true
+ },
+ resourceInterfaces: {
+ value: [],
+ writable: true,
+ enumerable: true
+ },
+ attributes: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ children: {
+ value: null,
+ writable: true,
+ enumerable: true
+ }
+ });
}
function createRepresentation(data) {
- var r = new tizen.Representation(data.uriPath);
- var props = ['resourceTypes', 'resourceInterfaces', 'attributes'];
+ var r = new tizen.Representation(data.uriPath);
+ var props = ['resourceTypes', 'resourceInterfaces', 'attributes'];
- for (var p = 0; p < props.length; ++p) {
- if (data[props[p]]) {
- r[props[p]] = data[props[p]];
+ for (var p = 0; p < props.length; ++p) {
+ if (data[props[p]]) {
+ r[props[p]] = data[props[p]];
+ }
}
- }
- if (data.children) {
- r.children = [];
- for (var i = 0; i < data.children.length; ++i) {
- r.children.push(createRepresentation(data.children[i]));
+ if (data.children) {
+ r.children = [];
+ for (var i = 0; i < data.children.length; ++i) {
+ r.children.push(createRepresentation(data.children[i]));
+ }
}
- }
- return r;
+ return r;
}
function Request(id, data) {
- data.id = id;
-
- if (data.representation) {
- data.representation = createRepresentation(data.representation);
- } else {
- data.representation = null;
- }
-
- if (data.options) {
- var options = [];
- for (var i = 0; i < data.options.length; ++i) {
- options.push(new IotconOption(data.options[i].id, data.options[i].data));
+ data.id = id;
+
+ if (data.representation) {
+ data.representation = createRepresentation(data.representation);
+ } else {
+ data.representation = null;
+ }
+
+ if (data.options) {
+ var options = [];
+ for (var i = 0; i < data.options.length; ++i) {
+ options.push(new IotconOption(data.options[i].id, data.options[i].data));
+ }
+ data.options = options;
}
- data.options = options;
- }
- decorateWithData(data, this);
+ decorateWithData(data, this);
}
function Resource(data) {
- Object.defineProperties(this, {
- observerIds: {
- get: function() {
- var callArgs = {};
- callArgs.id = this[kIdKey];
- var result = native.callSync('IotconResource_getObserverIds', callArgs);
- return native.getResultObject(result);
- }.bind(this),
- set: function() {},
- enumerable: true
- }
- });
+ Object.defineProperties(this, {
+ observerIds: {
+ get: function() {
+ var callArgs = {};
+ callArgs.id = this[kIdKey];
+ var result = native.callSync('IotconResource_getObserverIds', callArgs);
+ return native.getResultObject(result);
+ }.bind(this),
+ set: function() {},
+ enumerable: true
+ }
+ });
- this[kIdKey] = data.id;
+ this[kIdKey] = data.id;
- delete data.id;
+ delete data.id;
- var internal = new InternalData(data);
- internal.decorate(this);
+ var internal = new InternalData(data);
+ internal.decorate(this);
- this.attributes = null;
+ this.attributes = null;
}
Resource.prototype.notify = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'qos',
- type: types.ENUM,
- values: T.getValues(QosLevel)
- }, {
- name: 'observerIds',
- type: types.ARRAY,
- values: types.LONG,
- optional: true,
- nullable: true
- }]);
-
- var attributes = {};
- function getAttributes(r) {
- attributes[r[kIdKey]] = r.attributes;
- for (var i = 0; i < r.resources.length; ++i) {
- getAttributes(r.resources[i]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'qos',
+ type: types.ENUM,
+ values: T.getValues(QosLevel)
+ },
+ {
+ name: 'observerIds',
+ type: types.ARRAY,
+ values: types.LONG,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var attributes = {};
+ function getAttributes(r) {
+ attributes[r[kIdKey]] = r.attributes;
+ for (var i = 0; i < r.resources.length; ++i) {
+ getAttributes(r.resources[i]);
+ }
}
- }
- getAttributes(this);
+ getAttributes(this);
- var callArgs = {};
- callArgs.id = this[kIdKey];
- callArgs.qos = args.qos;
- callArgs.observerIds = args.observerIds;
- callArgs.attributes = attributes;
+ var callArgs = {};
+ callArgs.id = this[kIdKey];
+ callArgs.qos = args.qos;
+ callArgs.observerIds = args.observerIds;
+ callArgs.attributes = attributes;
- var result = native.callSync('IotconResource_notify', callArgs);
+ var result = native.callSync('IotconResource_notify', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
Resource.prototype.addResourceTypes = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'types',
- type: types.ARRAY,
- values: types.STRING
- }]);
-
- var callArgs = {};
- callArgs.id = this[kIdKey];
- callArgs.types = args.types;
-
- var result = native.callSync('IotconResource_addResourceTypes', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var t = this.resourceTypes;
- t = t.concat(args.types);
- updateWithInternalData({ resourceTypes: t }, this);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'types',
+ type: types.ARRAY,
+ values: types.STRING
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = this[kIdKey];
+ callArgs.types = args.types;
+
+ var result = native.callSync('IotconResource_addResourceTypes', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var t = this.resourceTypes;
+ t = t.concat(args.types);
+ updateWithInternalData({ resourceTypes: t }, this);
+ }
};
Resource.prototype.addResourceInterface = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'iface',
- type: types.STRING
- }]);
-
- var callArgs = {};
- callArgs.id = this[kIdKey];
- callArgs.iface = args.iface;
-
- var result = native.callSync('IotconResource_addResourceInterface', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var interfaces = this.resourceInterfaces;
- interfaces.push(args.iface);
- updateWithInternalData({ resourceInterfaces: interfaces }, this);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'iface',
+ type: types.STRING
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = this[kIdKey];
+ callArgs.iface = args.iface;
+
+ var result = native.callSync('IotconResource_addResourceInterface', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var interfaces = this.resourceInterfaces;
+ interfaces.push(args.iface);
+ updateWithInternalData({ resourceInterfaces: interfaces }, this);
+ }
};
Resource.prototype.addChildResource = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'resource',
- type: types.PLATFORM_OBJECT,
- values: Resource
- }]);
-
- var callArgs = {};
- callArgs.id = this[kIdKey];
- callArgs.childId = args.resource[kIdKey];
-
- var result = native.callSync('IotconResource_addChildResource', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var children = this.resources;
- children.push(args.resource);
- updateWithInternalData({ resources: children }, this);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'resource',
+ type: types.PLATFORM_OBJECT,
+ values: Resource
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = this[kIdKey];
+ callArgs.childId = args.resource[kIdKey];
+
+ var result = native.callSync('IotconResource_addChildResource', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var children = this.resources;
+ children.push(args.resource);
+ updateWithInternalData({ resources: children }, this);
+ }
};
Resource.prototype.removeChildResource = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'resource',
- type: types.PLATFORM_OBJECT,
- values: Resource
- }]);
-
- var callArgs = {};
- callArgs.id = this[kIdKey];
- callArgs.childId = args.resource[kIdKey];
-
- var result = native.callSync('IotconResource_removeChildResource', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var children = this.resources;
- var position = children.indexOf(args.resource);
- if (-1 !== position) {
- children.splice(position, 1);
- updateWithInternalData({ resources: children }, this);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'resource',
+ type: types.PLATFORM_OBJECT,
+ values: Resource
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = this[kIdKey];
+ callArgs.childId = args.resource[kIdKey];
+
+ var result = native.callSync('IotconResource_removeChildResource', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var children = this.resources;
+ var position = children.indexOf(args.resource);
+ if (-1 !== position) {
+ children.splice(position, 1);
+ updateWithInternalData({ resources: children }, this);
+ }
}
- }
};
var resourceRequestListener = createListener('ResourceRequestListener');
var _setRequestListener = function(id, args_listener) {
- var callArgs = {};
- callArgs.id = id;
-
- var listener = function(result) {
- if(!result.data.request.representation && result.data.uriPath) {
- result.data.request.representation = new tizen.Representation(result.data.uriPath);
- }
- var request = new Request(result.data.id, result.data.request);
+ var callArgs = {};
+ callArgs.id = id;
+
+ var listener = function(result) {
+ if (!result.data.request.representation && result.data.uriPath) {
+ result.data.request.representation = new tizen.Representation(
+ result.data.uriPath
+ );
+ }
+ var request = new Request(result.data.id, result.data.request);
- switch (converter.toString(result.data.type, false)) {
- case RequestType.GET:
- native.callIfPossible(args_listener.onget, request);
- break;
+ switch (converter.toString(result.data.type, false)) {
+ case RequestType.GET:
+ native.callIfPossible(args_listener.onget, request);
+ break;
- case RequestType.PUT:
- native.callIfPossible(args_listener.onput, request);
- break;
+ case RequestType.PUT:
+ native.callIfPossible(args_listener.onput, request);
+ break;
- case RequestType.POST:
- native.callIfPossible(args_listener.onpost, request);
- break;
+ case RequestType.POST:
+ native.callIfPossible(args_listener.onpost, request);
+ break;
- case RequestType.DELETE:
- native.callIfPossible(args_listener.ondelete, request);
- break;
- }
+ case RequestType.DELETE:
+ native.callIfPossible(args_listener.ondelete, request);
+ break;
+ }
- var observeType = converter.toString(result.data.observeType, false);
- var observerId = converter.toUnsignedLong(result.data.observerId, false);
- if (observeType !== ObserveType.NO_TYPE && observerId) {
- native.callIfPossible(args_listener.onobserving(request, observeType, observerId));
- }
- };
+ var observeType = converter.toString(result.data.observeType, false);
+ var observerId = converter.toUnsignedLong(result.data.observerId, false);
+ if (observeType !== ObserveType.NO_TYPE && observerId) {
+ native.callIfPossible(
+ args_listener.onobserving(request, observeType, observerId)
+ );
+ }
+ };
- var result = native.callSync('IotconResource_setRequestListener', callArgs);
+ var result = native.callSync('IotconResource_setRequestListener', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- resourceRequestListener.addListener(id, listener);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ resourceRequestListener.addListener(id, listener);
+ }
};
Resource.prototype.setRequestListener = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'listener',
- type: types.LISTENER,
- values: ['onget', 'onput', 'onpost', 'ondelete', 'onobserving']
- }]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'listener',
+ type: types.LISTENER,
+ values: ['onget', 'onput', 'onpost', 'ondelete', 'onobserving']
+ }
+ ]);
- _setRequestListener(this[kIdKey], args.listener);
+ _setRequestListener(this[kIdKey], args.listener);
};
Resource.prototype.unsetRequestListener = function() {
- var callArgs = {};
- callArgs.id = this[kIdKey];
+ var callArgs = {};
+ callArgs.id = this[kIdKey];
- var result = native.callSync('IotconResource_unsetRequestListener', callArgs);
+ var result = native.callSync('IotconResource_unsetRequestListener', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- resourceRequestListener.removeListener(this[kIdKey]);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ resourceRequestListener.removeListener(this[kIdKey]);
+ }
};
function Response(request) {
- validator.isConstructorCall(this, tizen.Response);
-
- Object.defineProperties(this, {
- request: {
- value: request,
- writable: false,
- enumerable: true
- },
- result: {
- value: null,
- writable: true,
- enumerable: true
- },
- representation: {
- value: null,
- writable: true,
- enumerable: true
- },
- options: {
- value: null,
- writable: true,
- enumerable: true
- }
- });
+ validator.isConstructorCall(this, tizen.Response);
+
+ Object.defineProperties(this, {
+ request: {
+ value: request,
+ writable: false,
+ enumerable: true
+ },
+ result: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ representation: {
+ value: null,
+ writable: true,
+ enumerable: true
+ },
+ options: {
+ value: null,
+ writable: true,
+ enumerable: true
+ }
+ });
}
Response.prototype.send = function() {
- var callArgs = {};
- callArgs.id = this.request.id;
- callArgs.result = this.result;
- callArgs.representation = this.representation;
- callArgs.options = this.options;
+ var callArgs = {};
+ callArgs.id = this.request.id;
+ callArgs.result = this.result;
+ callArgs.representation = this.representation;
+ callArgs.options = this.options;
- var result = native.callSync('IotconResponse_send', callArgs);
+ var result = native.callSync('IotconResponse_send', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
function RemoteResponse(data) {
- if (data.representation) {
- data.representation = createRepresentation(data.representation);
- } else {
- data.representation = null;
- }
-
- if (data.options) {
- var options = [];
- for (var i = 0; i < data.options.length; ++i) {
- options.push(new IotconOption(data.options[i].id, data.options[i].data));
+ if (data.representation) {
+ data.representation = createRepresentation(data.representation);
+ } else {
+ data.representation = null;
+ }
+
+ if (data.options) {
+ var options = [];
+ for (var i = 0; i < data.options.length; ++i) {
+ options.push(new IotconOption(data.options[i].id, data.options[i].data));
+ }
+ data.options = options;
}
- data.options = options;
- }
- decorateWithData(data, this);
+ decorateWithData(data, this);
}
function State(key, state) {
- validator.isConstructorCall(this, tizen.State);
-
- Object.defineProperties(this, {
- key: {
- value: key,
- writable: false,
- enumerable: true
- },
- state: {
- value: state,
- writable: false,
- enumerable: true
- }
- });
+ validator.isConstructorCall(this, tizen.State);
+
+ Object.defineProperties(this, {
+ key: {
+ value: key,
+ writable: false,
+ enumerable: true
+ },
+ state: {
+ value: state,
+ writable: false,
+ enumerable: true
+ }
+ });
}
-function prepareResourceInfo(that, notIncludeOptions){
- var callArgs = {};
- callArgs.id = that[kIdKey];
- if (!callArgs.id) {
- privUtils_.log("RemoteResource is not already stored in C++ layer, adding all members");
- callArgs.hostAddress = that.hostAddress;
- callArgs.connectivityType = that.connectivityType;
- callArgs.uriPath = that.uriPath;
- //properties flags
- callArgs.isObservable = that.isObservable;
- callArgs.isDiscoverable = that.isDiscoverable;
- callArgs.isActive = that.isActive;
- callArgs.isSlow = that.isSlow;
- callArgs.isSecure = that.isSecure;
- callArgs.isExplicitDiscoverable = that.isExplicitDiscoverable;
- callArgs.resourceTypes = that.resourceTypes;
- callArgs.resourceInterfaces = that.resourceInterfaces;
- if (!notIncludeOptions) {
- callArgs.options = that.options;
+function prepareResourceInfo(that, notIncludeOptions) {
+ var callArgs = {};
+ callArgs.id = that[kIdKey];
+ if (!callArgs.id) {
+ privUtils_.log(
+ 'RemoteResource is not already stored in C++ layer, adding all members'
+ );
+ callArgs.hostAddress = that.hostAddress;
+ callArgs.connectivityType = that.connectivityType;
+ callArgs.uriPath = that.uriPath;
+ //properties flags
+ callArgs.isObservable = that.isObservable;
+ callArgs.isDiscoverable = that.isDiscoverable;
+ callArgs.isActive = that.isActive;
+ callArgs.isSlow = that.isSlow;
+ callArgs.isSecure = that.isSecure;
+ callArgs.isExplicitDiscoverable = that.isExplicitDiscoverable;
+ callArgs.resourceTypes = that.resourceTypes;
+ callArgs.resourceInterfaces = that.resourceInterfaces;
+ if (!notIncludeOptions) {
+ callArgs.options = that.options;
+ }
+ } else {
+ privUtils_.log('Already stored in C++, all needed info is id');
}
- } else {
- privUtils_.log("Already stored in C++, all needed info is id");
- }
- return callArgs;
+ return callArgs;
}
function manageId(that, result) {
- if (result.keepId) {
- that[kIdKey] = result.id;
- privUtils_.log("Keep id of resource: " + that[kIdKey]);
- } else {
- privUtils_.log("Clear id of resource");
- delete that[kIdKey];
- }
- delete result.keepId;
- delete result.id;
+ if (result.keepId) {
+ that[kIdKey] = result.id;
+ privUtils_.log('Keep id of resource: ' + that[kIdKey]);
+ } else {
+ privUtils_.log('Clear id of resource');
+ delete that[kIdKey];
+ }
+ delete result.keepId;
+ delete result.id;
}
function RemoteResource(data) {
- Object.defineProperties(this, {
- cachedRepresentation: {
- get: function() {
- var callArgs = prepareResourceInfo(this);
- var result = native.callSync('IotconRemoteResource_getCachedRepresentation', callArgs);
- if (native.isSuccess(result)) {
- return createRepresentation(native.getResultObject(result));
- } else {
- return null;
- }
- }.bind(this),
- set: function() {},
- enumerable: true
- },
- options: {
- get: function() {
- var options_ = null;
- var callArgs = prepareResourceInfo(this, true);
- var result = native.callSync('IotconRemoteResource_getOptions', callArgs);
- if (native.isSuccess(result)) {
- var data = native.getResultObject(result);
- options_ = [];
- for (var i = 0; i < data.length; ++i) {
- options_.push(new IotconOption(data[i].id, data[i].data));
- }
- }
- return options_;
- }.bind(this),
- set: function(val) {
- // array or null are only acceptable values
- if (!T.isArray(val) && null != val) {
- return;
- }
- // check types of array values
- if (T.isArray(val)) {
- for (var i = 0; i < val.length; ++i) {
- if (!(val[i] instanceof tizen.IotconOption)) {
- return;
- }
- }
+ Object.defineProperties(this, {
+ cachedRepresentation: {
+ get: function() {
+ var callArgs = prepareResourceInfo(this);
+ var result = native.callSync(
+ 'IotconRemoteResource_getCachedRepresentation',
+ callArgs
+ );
+ if (native.isSuccess(result)) {
+ return createRepresentation(native.getResultObject(result));
+ } else {
+ return null;
+ }
+ }.bind(this),
+ set: function() {},
+ enumerable: true
+ },
+ options: {
+ get: function() {
+ var options_ = null;
+ var callArgs = prepareResourceInfo(this, true);
+ var result = native.callSync('IotconRemoteResource_getOptions', callArgs);
+ if (native.isSuccess(result)) {
+ var data = native.getResultObject(result);
+ options_ = [];
+ for (var i = 0; i < data.length; ++i) {
+ options_.push(new IotconOption(data[i].id, data[i].data));
+ }
+ }
+ return options_;
+ }.bind(this),
+ set: function(val) {
+ // array or null are only acceptable values
+ if (!T.isArray(val) && null != val) {
+ return;
+ }
+ // check types of array values
+ if (T.isArray(val)) {
+ for (var i = 0; i < val.length; ++i) {
+ if (!(val[i] instanceof tizen.IotconOption)) {
+ return;
+ }
+ }
+ }
+
+ var callArgs = prepareResourceInfo(this, true);
+ callArgs['options'] = val;
+
+ var result = native.callSync('IotconRemoteResource_setOptions', callArgs);
+ if (native.isSuccess(result)) {
+ manageId(this, native.getResultObject(result));
+ }
+ }.bind(this),
+ enumerable: true
+ },
+ timeInterval: {
+ get: function() {
+ var callArgs = prepareResourceInfo(this, true);
+
+ var result = native.callSync(
+ 'IotconRemoteResource_getTimeInterval',
+ callArgs
+ );
+ if (native.isSuccess(result)) {
+ return native.getResultObject(result);
+ }
+ return null;
+ }.bind(this),
+ set: function(val) {
+ var callArgs = prepareResourceInfo(this, true);
+ callArgs[timeInterval] = converter.toLong(val);
+
+ native.callSync('IotconRemoteResource_setTimeInterval', callArgs);
+ }.bind(this),
+ enumerable: true
}
+ });
- var callArgs = prepareResourceInfo(this, true);
- callArgs['options'] = val;
+ this[kIdKey] = data.id;
- var result = native.callSync('IotconRemoteResource_setOptions', callArgs);
- if (native.isSuccess(result)) {
- manageId(this, native.getResultObject(result));
- }
- }.bind(this),
- enumerable: true
- },
- timeInterval: {
- get: function() {
- var callArgs = prepareResourceInfo(this, true);
-
- var result = native.callSync('IotconRemoteResource_getTimeInterval', callArgs);
- if (native.isSuccess(result)) {
- return native.getResultObject(result);
- }
- return null;
- }.bind(this),
- set: function(val) {
- var callArgs = prepareResourceInfo(this, true);
- callArgs[timeInterval] = converter.toLong(val);
-
- native.callSync('IotconRemoteResource_setTimeInterval', callArgs);
- }.bind(this),
- enumerable: true
- }
- });
-
- this[kIdKey] = data.id;
-
- delete data.id;
+ delete data.id;
- var internal = new InternalData(data);
- internal.decorate(this);
+ var internal = new InternalData(data);
+ internal.decorate(this);
}
RemoteResource.prototype.methodGet = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'responseCallback',
- type: types.FUNCTION
- }, {
- name: 'query',
- type: types.DICTIONARY,
- optional: true,
- nullable: true
- }, {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = prepareResourceInfo(this);
- if (args.query) {
- callArgs.query = args.query;
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'responseCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'query',
+ type: types.DICTIONARY,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var callback = function(result) {
- result = native.getResultObject(result);
- manageId(this, result);
- if (!result.data) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- args.responseCallback(new RemoteResponse(result.data));
+ var callArgs = prepareResourceInfo(this);
+ if (args.query) {
+ callArgs.query = args.query;
}
- }.bind(this);
- var result = native.call('IotconRemoteResource_methodGet', callArgs, callback);
+ var callback = function(result) {
+ result = native.getResultObject(result);
+ manageId(this, result);
+ if (!result.data) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ args.responseCallback(new RemoteResponse(result.data));
+ }
+ }.bind(this);
+
+ var result = native.call('IotconRemoteResource_methodGet', callArgs, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ }
};
RemoteResource.prototype.methodPut = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'representation',
- type: types.PLATFORM_OBJECT,
- values: Representation
- }, {
- name: 'responseCallback',
- type: types.FUNCTION
- }, {
- name: 'query',
- type: types.DICTIONARY,
- optional: true,
- nullable: true
- }, {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = prepareResourceInfo(this);
- callArgs.representation = args.representation;
- if (args.query) {
- callArgs.query = args.query;
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'representation',
+ type: types.PLATFORM_OBJECT,
+ values: Representation
+ },
+ {
+ name: 'responseCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'query',
+ type: types.DICTIONARY,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var callback = function(result) {
- result = native.getResultObject(result);
- manageId(this, result);
- if (!result.data) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- args.responseCallback(new RemoteResponse(result.data));
+ var callArgs = prepareResourceInfo(this);
+ callArgs.representation = args.representation;
+ if (args.query) {
+ callArgs.query = args.query;
}
- }.bind(this);
- var result = native.call('IotconRemoteResource_methodPut', callArgs, callback);
+ var callback = function(result) {
+ result = native.getResultObject(result);
+ manageId(this, result);
+ if (!result.data) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ args.responseCallback(new RemoteResponse(result.data));
+ }
+ }.bind(this);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- }
+ var result = native.call('IotconRemoteResource_methodPut', callArgs, callback);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ }
};
RemoteResource.prototype.methodPost = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'representation',
- type: types.PLATFORM_OBJECT,
- values: Representation
- }, {
- name: 'responseCallback',
- type: types.FUNCTION
- }, {
- name: 'query',
- type: types.DICTIONARY,
- optional: true,
- nullable: true
- }, {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = prepareResourceInfo(this);
- callArgs.representation = args.representation;
- if (args.query) {
- callArgs.query = args.query;
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'representation',
+ type: types.PLATFORM_OBJECT,
+ values: Representation
+ },
+ {
+ name: 'responseCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'query',
+ type: types.DICTIONARY,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var callback = function(result) {
- result = native.getResultObject(result);
- manageId(this, result);
- if (!result.data) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- args.responseCallback(new RemoteResponse(result.data));
+ var callArgs = prepareResourceInfo(this);
+ callArgs.representation = args.representation;
+ if (args.query) {
+ callArgs.query = args.query;
}
- }.bind(this);
- var result = native.call('IotconRemoteResource_methodPost', callArgs, callback);
+ var callback = function(result) {
+ result = native.getResultObject(result);
+ manageId(this, result);
+ if (!result.data) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ args.responseCallback(new RemoteResponse(result.data));
+ }
+ }.bind(this);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- }
-};
+ var result = native.call('IotconRemoteResource_methodPost', callArgs, callback);
-RemoteResource.prototype.methodDelete = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'responseCallback',
- type: types.FUNCTION
- }, {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = prepareResourceInfo(this);
-
- var callback = function(result) {
- result = native.getResultObject(result);
- manageId(this, result);
- if (!result.data) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
} else {
- args.responseCallback(new RemoteResponse(result.data));
+ manageId(this, native.getResultObject(result));
}
- }.bind(this);
+};
+
+RemoteResource.prototype.methodDelete = function() {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'responseCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = prepareResourceInfo(this);
- var result = native.call('IotconRemoteResource_methodDelete', callArgs, callback);
+ var callback = function(result) {
+ result = native.getResultObject(result);
+ manageId(this, result);
+ if (!result.data) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ args.responseCallback(new RemoteResponse(result.data));
+ }
+ }.bind(this);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- }
+ var result = native.call('IotconRemoteResource_methodDelete', callArgs, callback);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ }
};
var resourceChangeListener = createListener('RemoteResourceChangeListener');
RemoteResource.prototype.startObserving = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'observePolicy',
- type: types.ENUM,
- values: T.getValues(ObservePolicy)
- }, {
- name: 'successCallback',
- type: types.FUNCTION
- }, {
- name: 'query',
- type: types.DICTIONARY,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = prepareResourceInfo(this);
- callArgs.observePolicy = args.observePolicy;
- if (args.query) {
- callArgs.query = args.query;
- }
- var that = this;
-
- var listener = function(result) {
- //TODO check what should be updated
- //updateWithInternalData(result, that);
- args.successCallback(new RemoteResponse(result.data));
- };
-
- var result = native.callSync('IotconRemoteResource_startObserving', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- resourceChangeListener.addListener(this[kIdKey], listener);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'observePolicy',
+ type: types.ENUM,
+ values: T.getValues(ObservePolicy)
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'query',
+ type: types.DICTIONARY,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = prepareResourceInfo(this);
+ callArgs.observePolicy = args.observePolicy;
+ if (args.query) {
+ callArgs.query = args.query;
+ }
+ var that = this;
+
+ var listener = function(result) {
+ //TODO check what should be updated
+ //updateWithInternalData(result, that);
+ args.successCallback(new RemoteResponse(result.data));
+ };
+
+ var result = native.callSync('IotconRemoteResource_startObserving', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ resourceChangeListener.addListener(this[kIdKey], listener);
+ }
};
RemoteResource.prototype.stopObserving = function() {
- var callArgs = prepareResourceInfo(this);
+ var callArgs = prepareResourceInfo(this);
- var result = native.callSync('IotconRemoteResource_stopObserving', callArgs);
+ var result = native.callSync('IotconRemoteResource_stopObserving', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- resourceChangeListener.removeListener(this[kIdKey]);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ resourceChangeListener.removeListener(this[kIdKey]);
+ }
};
var cacheChangeListener = createListener('RemoteResourceCacheChangeListener');
RemoteResource.prototype.startCaching = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'successCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = prepareResourceInfo(this);
-
- var listener = function(result) {
- native.callIfPossible(args.successCallback(createRepresentation(result.data)));
- }
-
- var result = native.callSync('IotconRemoteResource_startCaching', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- cacheChangeListener.addListener(this[kIdKey], listener);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = prepareResourceInfo(this);
+
+ var listener = function(result) {
+ native.callIfPossible(args.successCallback(createRepresentation(result.data)));
+ };
+
+ var result = native.callSync('IotconRemoteResource_startCaching', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ cacheChangeListener.addListener(this[kIdKey], listener);
+ }
};
RemoteResource.prototype.stopCaching = function() {
- var callArgs = prepareResourceInfo(this);
+ var callArgs = prepareResourceInfo(this);
- var result = native.callSync('IotconRemoteResource_stopCaching', callArgs);
+ var result = native.callSync('IotconRemoteResource_stopCaching', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- cacheChangeListener.removeListener(this[kIdKey]);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ cacheChangeListener.removeListener(this[kIdKey]);
+ }
};
var resourceStateChangeListener = createListener('RemoteResourceStateChangeListener');
RemoteResource.prototype.setResourceStateChangeListener = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'successCallback',
- type: types.FUNCTION
- }]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ }
+ ]);
- var callArgs = prepareResourceInfo(this);
+ var callArgs = prepareResourceInfo(this);
- var listener = function(result) {
- args.successCallback(result.data);
- };
+ var listener = function(result) {
+ args.successCallback(result.data);
+ };
- var result = native.callSync('IotconRemoteResource_setResourceStateChangeListener', callArgs);
+ var result = native.callSync(
+ 'IotconRemoteResource_setResourceStateChangeListener',
+ callArgs
+ );
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- resourceStateChangeListener.addListener(this[kIdKey], listener);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ resourceStateChangeListener.addListener(this[kIdKey], listener);
+ }
};
RemoteResource.prototype.unsetResourceStateChangeListener = function() {
- var callArgs = prepareResourceInfo(this);
+ var callArgs = prepareResourceInfo(this);
- var result = native.callSync('IotconRemoteResource_unsetResourceStateChangeListener', callArgs);
+ var result = native.callSync(
+ 'IotconRemoteResource_unsetResourceStateChangeListener',
+ callArgs
+ );
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- manageId(this, native.getResultObject(result));
- resourceStateChangeListener.removeListener(this[kIdKey]);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ manageId(this, native.getResultObject(result));
+ resourceStateChangeListener.removeListener(this[kIdKey]);
+ }
};
-function Client() {
-}
+function Client() {}
var findResourceListener = createListener('FindResourceListener');
var globalFindResourceId = 0;
Client.prototype.findResource = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'hostAddress',
- type: types.STRING,
- nullable: true
- }, {
- name: 'query',
- type: types.DICTIONARY,
- nullable: true
- }, {
- name: 'connectivityType',
- type: types.ENUM,
- values: T.getValues(ConnectivityType)
- }, {
- name: 'successCallback',
- type: types.FUNCTION
- }, {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = {};
- callArgs.id = ++globalFindResourceId;
- callArgs.hostAddress = args.hostAddress;
- callArgs.query = args.query;
- callArgs.connectivityType = args.connectivityType;
-
- var callback = function(result) {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'hostAddress',
+ type: types.STRING,
+ nullable: true
+ },
+ {
+ name: 'query',
+ type: types.DICTIONARY,
+ nullable: true
+ },
+ {
+ name: 'connectivityType',
+ type: types.ENUM,
+ values: T.getValues(ConnectivityType)
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = ++globalFindResourceId;
+ callArgs.hostAddress = args.hostAddress;
+ callArgs.query = args.query;
+ callArgs.connectivityType = args.connectivityType;
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var rr = new RemoteResource(native.getResultObject(result));
+ args.successCallback(rr);
+ }
+ };
+
+ var result = native.callSync('IotconClient_findResource', callArgs);
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ throw native.getErrorObject(result);
} else {
- var rr = new RemoteResource(native.getResultObject(result));
- args.successCallback(rr);
+ findResourceListener.addListener(callArgs.id, callback);
}
- };
-
- var result = native.callSync('IotconClient_findResource', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- findResourceListener.addListener(callArgs.id, callback);
- }
};
var presenceEventListener = createListener('PresenceEventListener', function(response) {
- return new PresenceResponse(response.data);
+ return new PresenceResponse(response.data);
});
Client.prototype.addPresenceEventListener = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'hostAddress',
- type: types.STRING,
- nullable: true
- }, {
- name: 'resourceType',
- type: types.STRING,
- nullable: true
- }, {
- name: 'connectivityType',
- type: types.ENUM,
- values: T.getValues(ConnectivityType)
- }, {
- name: 'successCallback',
- type: types.FUNCTION
- }]);
-
- var callArgs = {};
- callArgs.hostAddress = args.hostAddress;
- callArgs.resourceType = args.resourceType;
- callArgs.connectivityType = args.connectivityType;
-
- var result = native.callSync('IotconClient_addPresenceEventListener', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var id = native.getResultObject(result);
- presenceEventListener.addListener(id, args.successCallback);
- return id;
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'hostAddress',
+ type: types.STRING,
+ nullable: true
+ },
+ {
+ name: 'resourceType',
+ type: types.STRING,
+ nullable: true
+ },
+ {
+ name: 'connectivityType',
+ type: types.ENUM,
+ values: T.getValues(ConnectivityType)
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.hostAddress = args.hostAddress;
+ callArgs.resourceType = args.resourceType;
+ callArgs.connectivityType = args.connectivityType;
+
+ var result = native.callSync('IotconClient_addPresenceEventListener', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var id = native.getResultObject(result);
+ presenceEventListener.addListener(id, args.successCallback);
+ return id;
+ }
};
Client.prototype.removePresenceEventListener = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'watchId',
- type: types.LONG
- }]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'watchId',
+ type: types.LONG
+ }
+ ]);
- var callArgs = {};
- callArgs.id = args.watchId;
+ var callArgs = {};
+ callArgs.id = args.watchId;
- var result = native.callSync('IotconClient_removePresenceEventListener', callArgs);
+ var result = native.callSync('IotconClient_removePresenceEventListener', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- presenceEventListener.removeListener(args.watchId);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ presenceEventListener.removeListener(args.watchId);
+ }
};
var findDeviceInfoListener = createListener('FindDeviceInfoListener');
var globalFindDeviceInfoId = 0;
Client.prototype.findDeviceInfo = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'hostAddress',
- type: types.STRING,
- nullable: true
- }, {
- name: 'query',
- type: types.DICTIONARY,
- nullable: true
- }, {
- name: 'connectivityType',
- type: types.ENUM,
- values: T.getValues(ConnectivityType)
- }, {
- name: 'successCallback',
- type: types.FUNCTION
- }, {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = {};
- callArgs.id = ++globalFindDeviceInfoId;
- callArgs.hostAddress = args.hostAddress;
- callArgs.query = args.query;
- callArgs.connectivityType = args.connectivityType;
-
- var callback = function(result) {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'hostAddress',
+ type: types.STRING,
+ nullable: true
+ },
+ {
+ name: 'query',
+ type: types.DICTIONARY,
+ nullable: true
+ },
+ {
+ name: 'connectivityType',
+ type: types.ENUM,
+ values: T.getValues(ConnectivityType)
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = ++globalFindDeviceInfoId;
+ callArgs.hostAddress = args.hostAddress;
+ callArgs.query = args.query;
+ callArgs.connectivityType = args.connectivityType;
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ args.successCallback(new DeviceInfo(native.getResultObject(result)));
+ }
+ };
+
+ var result = native.call('IotconClient_findDeviceInfo', callArgs);
+
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ throw native.getErrorObject(result);
} else {
- args.successCallback(new DeviceInfo(native.getResultObject(result)));
+ findDeviceInfoListener.addListener(callArgs.id, callback);
}
- };
-
- var result = native.call('IotconClient_findDeviceInfo', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }else{
- findDeviceInfoListener.addListener(callArgs.id, callback);
- }
};
var findPlatformInfoListener = createListener('FindPlatformInfoListener');
var globalFindPlatformInfoId = 0;
Client.prototype.findPlatformInfo = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'hostAddress',
- type: types.STRING,
- nullable: true
- }, {
- name: 'query',
- type: types.DICTIONARY,
- nullable: true
- }, {
- name: 'connectivityType',
- type: types.ENUM,
- values: T.getValues(ConnectivityType)
- }, {
- name: 'successCallback',
- type: types.FUNCTION
- }, {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- var callArgs = {};
- callArgs.id = ++globalFindPlatformInfoId;
- callArgs.hostAddress = args.hostAddress;
- callArgs.query = args.query;
- callArgs.connectivityType = args.connectivityType;
-
- var callback = function(result) {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'hostAddress',
+ type: types.STRING,
+ nullable: true
+ },
+ {
+ name: 'query',
+ type: types.DICTIONARY,
+ nullable: true
+ },
+ {
+ name: 'connectivityType',
+ type: types.ENUM,
+ values: T.getValues(ConnectivityType)
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = ++globalFindPlatformInfoId;
+ callArgs.hostAddress = args.hostAddress;
+ callArgs.query = args.query;
+ callArgs.connectivityType = args.connectivityType;
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ args.successCallback(new PlatformInfo(native.getResultObject(result)));
+ }
+ };
+
+ var result = native.call('IotconClient_findPlatformInfo', callArgs);
+
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ throw native.getErrorObject(result);
} else {
- args.successCallback(new PlatformInfo(native.getResultObject(result)));
+ findPlatformInfoListener.addListener(callArgs.id, callback);
}
- };
-
- var result = native.call('IotconClient_findPlatformInfo', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }else{
- findPlatformInfoListener.addListener(callArgs.id, callback);
- }
};
-function Server() {
-}
+function Server() {}
var serverResources = {};
Server.prototype.createResource = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'uriPath',
- type: types.STRING
- }, {
- name: 'resourceTypes',
- type: types.ARRAY,
- values: types.STRING
- }, {
- name: 'resourceInterfaces',
- type: types.ARRAY,
- values: types.STRING
- }, {
- name: 'listener',
- type: types.LISTENER,
- values: ['onget', 'onput', 'onpost', 'ondelete', 'onobserving']
- }, {
- name: 'policy',
- type: types.DICTIONARY,
- optional: true,
- nullable: false
- }]);
-
- var callArgs = args.policy || {};
- callArgs.uriPath = args.uriPath;
- callArgs.resourceTypes = args.resourceTypes;
- callArgs.resourceInterfaces = args.resourceInterfaces;
-
- var result = native.callSync('IotconServer_createResource', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var resource = new Resource(native.getResultObject(result));
- serverResources[resource[kIdKey]] = resource;
-
- _setRequestListener(resource[kIdKey], args.listener);
-
- return resource;
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'uriPath',
+ type: types.STRING
+ },
+ {
+ name: 'resourceTypes',
+ type: types.ARRAY,
+ values: types.STRING
+ },
+ {
+ name: 'resourceInterfaces',
+ type: types.ARRAY,
+ values: types.STRING
+ },
+ {
+ name: 'listener',
+ type: types.LISTENER,
+ values: ['onget', 'onput', 'onpost', 'ondelete', 'onobserving']
+ },
+ {
+ name: 'policy',
+ type: types.DICTIONARY,
+ optional: true,
+ nullable: false
+ }
+ ]);
+
+ var callArgs = args.policy || {};
+ callArgs.uriPath = args.uriPath;
+ callArgs.resourceTypes = args.resourceTypes;
+ callArgs.resourceInterfaces = args.resourceInterfaces;
+
+ var result = native.callSync('IotconServer_createResource', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var resource = new Resource(native.getResultObject(result));
+ serverResources[resource[kIdKey]] = resource;
+
+ _setRequestListener(resource[kIdKey], args.listener);
+
+ return resource;
+ }
};
Server.prototype.removeResource = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'resource',
- type: types.PLATFORM_OBJECT,
- values: Resource
- }]);
-
- var callArgs = {};
- callArgs.id = args.resource[kIdKey];
-
- var result = native.callSync('IotconServer_removeResource', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- delete serverResources[callArgs.id];
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'resource',
+ type: types.PLATFORM_OBJECT,
+ values: Resource
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.id = args.resource[kIdKey];
+
+ var result = native.callSync('IotconServer_removeResource', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ delete serverResources[callArgs.id];
+ }
};
Server.prototype.getResources = function() {
- var result = [];
+ var result = [];
- for (var id in serverResources) {
- if (serverResources.hasOwnProperty(id)) {
- result.push(serverResources[id]);
+ for (var id in serverResources) {
+ if (serverResources.hasOwnProperty(id)) {
+ result.push(serverResources[id]);
+ }
}
- }
- return result;
+ return result;
};
Server.prototype.startPresence = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'timeToLive',
- type: types.UNSIGNED_LONG
- }]);
-
- var callArgs = {
- timeToLive: args.timeToLive
- };
-
- var result = native.callSync('IotconServer_startPresence', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'timeToLive',
+ type: types.UNSIGNED_LONG
+ }
+ ]);
+
+ var callArgs = {
+ timeToLive: args.timeToLive
+ };
+
+ var result = native.callSync('IotconServer_startPresence', callArgs);
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
Server.prototype.stopPresence = function() {
- var result = native.callSync('IotconServer_stopPresence', {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var result = native.callSync('IotconServer_stopPresence', {});
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
var client = new Client();
var server = new Server();
function Iotcon() {
- var _deviceName = '';
-
- Object.defineProperties(this, {
- deviceName: {
- get: function() {
- return _deviceName;
- },
- set: function(v) {
- if (v) {
- var deviceName = v;
-
- var callArgs = {
- deviceName: deviceName
- };
-
- var result = native.callSync('Iotcon_setDeviceName', callArgs);
- if (native.isSuccess(result)) {
- _deviceName = deviceName;
- }
+ var _deviceName = '';
+
+ Object.defineProperties(this, {
+ deviceName: {
+ get: function() {
+ return _deviceName;
+ },
+ set: function(v) {
+ if (v) {
+ var deviceName = v;
+
+ var callArgs = {
+ deviceName: deviceName
+ };
+
+ var result = native.callSync('Iotcon_setDeviceName', callArgs);
+ if (native.isSuccess(result)) {
+ _deviceName = deviceName;
+ }
+ }
+ },
+ enumerable: true
}
- },
- enumerable: true
- }
- });
+ });
}
Iotcon.prototype.initialize = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'filePath',
- type: types.STRING
- }]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'filePath',
+ type: types.STRING
+ }
+ ]);
- var data = {
- filePath: args.filePath
- };
+ var data = {
+ filePath: args.filePath
+ };
- var result = native.callSync('Iotcon_initialize', data);
+ var result = native.callSync('Iotcon_initialize', data);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
Iotcon.prototype.getClient = function() {
- return client;
+ return client;
};
Iotcon.prototype.getServer = function() {
- return server;
+ return server;
};
Iotcon.prototype.getTimeout = function() {
- var result = native.callSync('Iotcon_getTimeout', {});
+ var result = native.callSync('Iotcon_getTimeout', {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- return native.getResultObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ return native.getResultObject(result);
+ }
};
Iotcon.prototype.setTimeout = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'timeout',
- type: types.LONG
- }]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'timeout',
+ type: types.LONG
+ }
+ ]);
- var callArgs = {};
- callArgs.timeout = args.timeout;
+ var callArgs = {};
+ callArgs.timeout = args.timeout;
- var result = native.callSync('Iotcon_setTimeout', callArgs);
+ var result = native.callSync('Iotcon_setTimeout', callArgs);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
-var generatedPinListener = createListener( 'GeneratedPinListener' /* kGeneratedPinToken in iotcon_instance.cc */,
- function(response) { return response.pin; } );
+var generatedPinListener = createListener(
+ 'GeneratedPinListener' /* kGeneratedPinToken in iotcon_instance.cc */,
+ function(response) {
+ return response.pin;
+ }
+);
-Iotcon.prototype.addGeneratedPinListener = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'successCallback',
- type: types.FUNCTION
- }]);
+Iotcon.prototype.addGeneratedPinListener = function() {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ }
+ ]);
- var result = native.callSync('Iotcon_addGeneratedPinListener', {});
+ var result = native.callSync('Iotcon_addGeneratedPinListener', {});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- var watchId = native.getResultObject(result);
- generatedPinListener.addListener(watchId, args.successCallback);
- return watchId;
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ var watchId = native.getResultObject(result);
+ generatedPinListener.addListener(watchId, args.successCallback);
+ return watchId;
+ }
};
-Iotcon.prototype.removeGeneratedPinListener = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'watchId',
- type: types.LONG
- }]);
+Iotcon.prototype.removeGeneratedPinListener = function() {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'watchId',
+ type: types.LONG
+ }
+ ]);
- var result = native.callSync('Iotcon_removeGeneratedPinListener', { watchId: args.watchId });
+ var result = native.callSync('Iotcon_removeGeneratedPinListener', {
+ watchId: args.watchId
+ });
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- } else {
- generatedPinListener.removeListener(args.watchId);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ } else {
+ generatedPinListener.removeListener(args.watchId);
+ }
};
-
// Exports
tizen.IotconOption = IotconOption;
tizen.Representation = Representation;
diff --git a/src/keymanager/keymanager_api.js b/src/keymanager/keymanager_api.js
index 7e10bff6..4eb2bb1f 100755
--- a/src/keymanager/keymanager_api.js
+++ b/src/keymanager/keymanager_api.js
@@ -20,182 +20,186 @@ var type = xwalk.utils.type;
var native = new xwalk.utils.NativeManager(extension);
var PermissionType = {
- "NONE" : "NONE",
- "READ": "READ",
- "REMOVE" : "REMOVE",
- "READ_REMOVE": "READ_REMOVE"
+ NONE: 'NONE',
+ READ: 'READ',
+ REMOVE: 'REMOVE',
+ READ_REMOVE: 'READ_REMOVE'
};
-function KeyManager() {
-
-}
+function KeyManager() {}
KeyManager.prototype.saveData = function() {
var args = validator.validateArgs(arguments, [
- {
- name: 'aliasName',
- type: validator.Types.STRING
- },
- {
- name: 'rawData',
- type: validator.Types.STRING
- },
- {
- name: "password",
- type: validator.Types.STRING,
- optional: true,
- nullable: true
- },
- {
- name: 'successCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- }
+ {
+ name: 'aliasName',
+ type: validator.Types.STRING
+ },
+ {
+ name: 'rawData',
+ type: validator.Types.STRING
+ },
+ {
+ name: 'password',
+ type: validator.Types.STRING,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'successCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- var result = native.call('KeyManager_saveData', {
- aliasName: _trim(args.aliasName),
- rawData: args.rawData,
- password: (args.password ? converter.toString(args.password) : null)
- }, function(msg) {
- if (native.isFailure(msg)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(msg));
- } else {
- native.callIfPossible(args.successCallback);
+ var result = native.call(
+ 'KeyManager_saveData',
+ {
+ aliasName: _trim(args.aliasName),
+ rawData: args.rawData,
+ password: args.password ? converter.toString(args.password) : null
+ },
+ function(msg) {
+ if (native.isFailure(msg)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(msg));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
}
- }
);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
- };
+};
KeyManager.prototype.removeData = function() {
+ var args = validator.validateArgs(arguments, [
+ {
+ name: 'dataAlias',
+ type: validator.Types.DICTIONARY
+ }
+ ]);
- var args = validator.validateArgs(arguments, [
- {
- name : 'dataAlias',
- type : validator.Types.DICTIONARY
+ var data_alias = _trim(args.dataAlias.name);
+ if (args.dataAlias.hasOwnProperty('packageId')) {
+ data_alias = args.dataAlias.packageId + ' ' + data_alias;
+ }
+
+ var ret = native.callSync('KeyManager_removeAlias', {
+ aliasName: data_alias
+ });
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
}
- ]);
-
- var data_alias = _trim(args.dataAlias.name);
- if(args.dataAlias.hasOwnProperty('packageId')) {
- data_alias = args.dataAlias.packageId + ' ' + data_alias;
- }
-
- var ret = native.callSync('KeyManager_removeAlias', {
- aliasName: data_alias
- });
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
};
KeyManager.prototype.getData = function() {
- var args = validator.validateArgs(arguments, [
- {
- name: "dataAlias",
- type: validator.Types.DICTIONARY
- },
- {
- name: "password",
- type: validator.Types.STRING,
- optional: true,
- nullable: true
+ var args = validator.validateArgs(arguments, [
+ {
+ name: 'dataAlias',
+ type: validator.Types.DICTIONARY
+ },
+ {
+ name: 'password',
+ type: validator.Types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var data_alias = _trim(args.dataAlias.name);
+ if (args.dataAlias.hasOwnProperty('packageId')) {
+ data_alias = args.dataAlias.packageId + ' ' + data_alias;
}
- ]);
-
- var data_alias = _trim(args.dataAlias.name);
- if(args.dataAlias.hasOwnProperty('packageId')) {
- data_alias = args.dataAlias.packageId + ' ' + data_alias;
- }
-
- var ret = native.callSync('KeyManager_getData', {
- name: data_alias,
- password: args.password
- });
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
- var result = native.getResultObject(ret);
- return result.rawData;
+
+ var ret = native.callSync('KeyManager_getData', {
+ name: data_alias,
+ password: args.password
+ });
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
+ var result = native.getResultObject(ret);
+ return result.rawData;
};
KeyManager.prototype.getDataAliasList = function() {
- var ret = native.callSync('KeyManager_getDataAliasList', {});
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
- return native.getResultObject(ret);
+ var ret = native.callSync('KeyManager_getDataAliasList', {});
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
+ return native.getResultObject(ret);
};
KeyManager.prototype.setPermission = function() {
- var args = validator.validateArgs(arguments, [
- {
- name: "dataAlias",
- type: validator.Types.DICTIONARY
- },
- {
- name: "packageId",
- type: validator.Types.STRING
- },
- {
- name: 'permissionType',
- type: validator.Types.ENUM,
- values: Object.keys(PermissionType)
- },
- {
- name: 'successCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- var data_alias = _trim(args.dataAlias.name);
- if(args.dataAlias.hasOwnProperty('packageId')) {
- data_alias = args.dataAlias.packageId + ' ' + data_alias;
- }
-
- var result = native.call('KeyManager_setPermissions', {
- aliasName: data_alias,
- packageId: args.packageId,
- permissionType: args.permissionType
- }, function(msg) {
- if (native.isFailure(msg)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(msg));
- } else {
- native.callIfPossible(args.successCallback);
+ var args = validator.validateArgs(arguments, [
+ {
+ name: 'dataAlias',
+ type: validator.Types.DICTIONARY
+ },
+ {
+ name: 'packageId',
+ type: validator.Types.STRING
+ },
+ {
+ name: 'permissionType',
+ type: validator.Types.ENUM,
+ values: Object.keys(PermissionType)
+ },
+ {
+ name: 'successCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var data_alias = _trim(args.dataAlias.name);
+ if (args.dataAlias.hasOwnProperty('packageId')) {
+ data_alias = args.dataAlias.packageId + ' ' + data_alias;
}
- });
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var result = native.call(
+ 'KeyManager_setPermissions',
+ {
+ aliasName: data_alias,
+ packageId: args.packageId,
+ permissionType: args.permissionType
+ },
+ function(msg) {
+ if (native.isFailure(msg)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(msg));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ }
+ );
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
-function _trim(str){
- var val = str;
- if (!type.isString(str)) {
- val = converter.toString(str);
- }
+function _trim(str) {
+ var val = str;
+ if (!type.isString(str)) {
+ val = converter.toString(str);
+ }
- return val.replace(/\s/gi, '');
+ return val.replace(/\s/gi, '');
}
exports = new KeyManager();
diff --git a/src/mediacontroller/mediacontroller_api.js b/src/mediacontroller/mediacontroller_api.js
index a0878387..9a2c6df0 100755
--- a/src/mediacontroller/mediacontroller_api.js
+++ b/src/mediacontroller/mediacontroller_api.js
@@ -24,787 +24,930 @@ var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
function ListenerManager(native, listenerName, handle) {
- this.listeners = {};
- this.listenerNameToIds = {};
- this.listenerIdToName = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
- this.handle = handle || function(msg, listener, watchId) {};
- this.requestIdToListenerId = {};
+ this.listeners = {};
+ this.listenerNameToIds = {};
+ this.listenerIdToName = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
+ this.handle = handle || function(msg, listener, watchId) {};
+ this.requestIdToListenerId = {};
}
ListenerManager.prototype.addListener = function(callback) {
- var id = this.nextId;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, function(msg) {
- for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId)) {
- var stop = this.handle(msg, this.listeners[watchId], watchId);
- if (stop) {
- break;
- }
- }
- }
- }.bind(this));
-
- this.nativeSet = true;
- }
+ var id = this.nextId;
+ if (!this.nativeSet) {
+ this.native.addListener(
+ this.listenerName,
+ function(msg) {
+ for (var watchId in this.listeners) {
+ if (this.listeners.hasOwnProperty(watchId)) {
+ var stop = this.handle(msg, this.listeners[watchId], watchId);
+ if (stop) {
+ break;
+ }
+ }
+ }
+ }.bind(this)
+ );
+
+ this.nativeSet = true;
+ }
- this.listeners[id] = callback;
- ++this.nextId;
- return id;
+ this.listeners[id] = callback;
+ ++this.nextId;
+ return id;
};
ListenerManager.prototype.addServerInfoListener = function(callback, name) {
- var id = this.nextId;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, function(msg) {
- if (this.listenerNameToIds.hasOwnProperty(msg.name)) {
- var cbArray = this.listenerNameToIds[msg.name];
- for (var i = 0; i < cbArray.length; ++i) {
- var watchId = cbArray[i];
- this.handle(msg, this.listeners[watchId], watchId);
- }
- }
- }.bind(this));
-
- this.nativeSet = true;
- }
+ var id = this.nextId;
+ if (!this.nativeSet) {
+ this.native.addListener(
+ this.listenerName,
+ function(msg) {
+ if (this.listenerNameToIds.hasOwnProperty(msg.name)) {
+ var cbArray = this.listenerNameToIds[msg.name];
+ for (var i = 0; i < cbArray.length; ++i) {
+ var watchId = cbArray[i];
+ this.handle(msg, this.listeners[watchId], watchId);
+ }
+ }
+ }.bind(this)
+ );
+
+ this.nativeSet = true;
+ }
- this.listenerIdToName[id] = name;
- if (this.listenerNameToIds[name]) {
- this.listenerNameToIds[name].push(id);
- } else {
- this.listenerNameToIds[name] = [id];
- }
- this.listeners[id] = callback;
- ++this.nextId;
- return id;
+ this.listenerIdToName[id] = name;
+ if (this.listenerNameToIds[name]) {
+ this.listenerNameToIds[name].push(id);
+ } else {
+ this.listenerNameToIds[name] = [id];
+ }
+ this.listeners[id] = callback;
+ ++this.nextId;
+ return id;
};
ListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- }
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ }
};
function removeArrayElement(arr, elem) {
- var index = arr.indexOf(elem);
- if (index !== -1) {
- arr.splice(index, 1);
- }
+ var index = arr.indexOf(elem);
+ if (index !== -1) {
+ arr.splice(index, 1);
+ }
}
ListenerManager.prototype.removeServerInfoListener = function(watchId) {
- this.removeListener(watchId);
- if (this.listenerIdToName.hasOwnProperty(watchId)) {
- var name = this.listenerIdToName[watchId];
- removeArrayElement(this.listenerNameToIds[name], watchId);
- delete this.listenerIdToName[watchId];
- }
-};
-
-var ServerCommandListener = new ListenerManager(native_, '_ServerCommandListener', function(msg, listener) {
- var data = undefined;
- data = listener(msg.clientName, msg.command, msg.data);
-
- if (type_.isUndefined(data)) {
- data = null;
- }
-
- var nativeData = {
- clientName: msg.clientName,
- requestId: msg.requestId,
- data: data
- };
-
- var result = native_.callSync('MediaControllerServer_replyCommand', nativeData);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-});
-
-var ReplyCommandListener = new ListenerManager(native_, '_ReplyCommandListener', function(msg, listener, watchId) {
- if (this.requestIdToListenerId[watchId] === msg.requestId) {
- listener(msg);
this.removeListener(watchId);
- delete this.requestIdToListenerId[watchId];
- return true;
- }
- return false;
-});
+ if (this.listenerIdToName.hasOwnProperty(watchId)) {
+ var name = this.listenerIdToName[watchId];
+ removeArrayElement(this.listenerNameToIds[name], watchId);
+ delete this.listenerIdToName[watchId];
+ }
+};
-var ServerPlaybackInfoListener = new ListenerManager(native_, '_ServerPlaybackInfoListener', function(msg, listener) {
- if (msg.action === 'onplaybackstaterequest') {
- native_.callIfPossible(listener[msg.action], msg.state);
- }
- if (msg.action === 'onplaybackpositionrequest') {
- native_.callIfPossible(listener[msg.action], msg.position);
- }
- if (msg.action === 'onshufflemoderequest' || msg.action === 'onrepeatmoderequest') {
- native_.callIfPossible(listener[msg.action], msg.mode);
- }
-});
+var ServerCommandListener = new ListenerManager(
+ native_,
+ '_ServerCommandListener',
+ function(msg, listener) {
+ var data = undefined;
+ data = listener(msg.clientName, msg.command, msg.data);
-var ServerInfoStatusListener = new ListenerManager(native_, '_ServerInfoStatusListener', function(msg, listener) {
- listener(msg.state);
-});
+ if (type_.isUndefined(data)) {
+ data = null;
+ }
+
+ var nativeData = {
+ clientName: msg.clientName,
+ requestId: msg.requestId,
+ data: data
+ };
-var ServerInfoPlaybackInfoListener = new ListenerManager(native_, '_ServerInfoPlaybackInfoListener', function(msg, listener) {
- if (msg.action === 'onplaybackchanged') {
- listener[msg.action](msg.state, msg.position);
- }
- if (msg.action === 'onshufflemodechanged' || msg.action === 'onrepeatmodechanged') {
- listener[msg.action](msg.mode);
- }
- if (msg.action === 'onmetadatachanged') {
- listener[msg.action](new MediaControllerMetadata(msg.metadata));
- }
+ var result = native_.callSync('MediaControllerServer_replyCommand', nativeData);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ }
+);
+
+var ReplyCommandListener = new ListenerManager(native_, '_ReplyCommandListener', function(
+ msg,
+ listener,
+ watchId
+) {
+ if (this.requestIdToListenerId[watchId] === msg.requestId) {
+ listener(msg);
+ this.removeListener(watchId);
+ delete this.requestIdToListenerId[watchId];
+ return true;
+ }
+ return false;
});
+var ServerPlaybackInfoListener = new ListenerManager(
+ native_,
+ '_ServerPlaybackInfoListener',
+ function(msg, listener) {
+ if (msg.action === 'onplaybackstaterequest') {
+ native_.callIfPossible(listener[msg.action], msg.state);
+ }
+ if (msg.action === 'onplaybackpositionrequest') {
+ native_.callIfPossible(listener[msg.action], msg.position);
+ }
+ if (
+ msg.action === 'onshufflemoderequest' ||
+ msg.action === 'onrepeatmoderequest'
+ ) {
+ native_.callIfPossible(listener[msg.action], msg.mode);
+ }
+ }
+);
+
+var ServerInfoStatusListener = new ListenerManager(
+ native_,
+ '_ServerInfoStatusListener',
+ function(msg, listener) {
+ listener(msg.state);
+ }
+);
+
+var ServerInfoPlaybackInfoListener = new ListenerManager(
+ native_,
+ '_ServerInfoPlaybackInfoListener',
+ function(msg, listener) {
+ if (msg.action === 'onplaybackchanged') {
+ listener[msg.action](msg.state, msg.position);
+ }
+ if (
+ msg.action === 'onshufflemodechanged' ||
+ msg.action === 'onrepeatmodechanged'
+ ) {
+ listener[msg.action](msg.mode);
+ }
+ if (msg.action === 'onmetadatachanged') {
+ listener[msg.action](new MediaControllerMetadata(msg.metadata));
+ }
+ }
+);
+
var EditManager = function() {
- this.isAllowed = false;
+ this.isAllowed = false;
};
EditManager.prototype.allow = function() {
- this.isAllowed = true;
+ this.isAllowed = true;
};
EditManager.prototype.disallow = function() {
- this.isAllowed = false;
+ this.isAllowed = false;
};
var edit_ = new EditManager();
-
var MediaControllerServerState = {
- ACTIVE: 'ACTIVE',
- INACTIVE: 'INACTIVE'
+ ACTIVE: 'ACTIVE',
+ INACTIVE: 'INACTIVE'
};
var MediaControllerPlaybackState = {
- PLAY: 'PLAY',
- PAUSE: 'PAUSE',
- STOP: 'STOP',
- NEXT: 'NEXT',
- PREV: 'PREV',
- FORWARD: 'FORWARD',
- REWIND: 'REWIND'
+ PLAY: 'PLAY',
+ PAUSE: 'PAUSE',
+ STOP: 'STOP',
+ NEXT: 'NEXT',
+ PREV: 'PREV',
+ FORWARD: 'FORWARD',
+ REWIND: 'REWIND'
};
-
var MediaControllerContentType = {
- IMAGE: "IMAGE",
- MUSIC: "MUSIC",
- VIDEO: "VIDEO",
- OTHER: "OTHER",
- UNDECIDED: "UNDECIDED"
+ IMAGE: 'IMAGE',
+ MUSIC: 'MUSIC',
+ VIDEO: 'VIDEO',
+ OTHER: 'OTHER',
+ UNDECIDED: 'UNDECIDED'
};
function MediaControllerManager() {}
MediaControllerManager.prototype.getClient = function() {
- var result = native_.callSync('MediaControllerManager_getClient', {});
+ var result = native_.callSync('MediaControllerManager_getClient', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return new MediaControllerClient(native_.getResultObject(result));
+ return new MediaControllerClient(native_.getResultObject(result));
};
MediaControllerManager.prototype.createServer = function() {
- var result = native_.callSync('MediaControllerManager_createServer', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('MediaControllerManager_createServer', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return new MediaControllerServer(native_.getResultObject(result));
+ return new MediaControllerServer(native_.getResultObject(result));
};
-
var MediaControllerMetadata = function(data) {
- var _title = '';
- var _artist = '';
- var _album = '';
- var _author = '';
- var _genre = '';
- var _duration = '';
- var _date = '';
- var _copyright = '';
- var _description = '';
- var _trackNum = '';
- var _picture = '';
- Object.defineProperties(this, {
- title: {
- get: function() {return _title;},
- set: function(v) {_title = converter_.toString(v)},
- enumerable: true
- },
- artist: {
- get: function() {return _artist;},
- set: function(v) {_artist = converter_.toString(v)},
- enumerable: true
- },
- album: {
- get: function() {return _album;},
- set: function(v) {_album = converter_.toString(v)},
- enumerable: true
- },
- author: {
- get: function() {return _author;},
- set: function(v) {_author = converter_.toString(v)},
- enumerable: true
- },
- genre: {
- get: function() {return _genre;},
- set: function(v) {_genre = converter_.toString(v)},
- enumerable: true
- },
- duration: {
- get: function() {return _duration;},
- set: function(v) {_duration = converter_.toString(v)},
- enumerable: true
- },
- date: {
- get: function() {return _date;},
- set: function(v) {_date = converter_.toString(v)},
- enumerable: true
- },
- copyright: {
- get: function() {return _copyright;},
- set: function(v) {_copyright = converter_.toString(v)},
- enumerable: true
- },
- description: {
- get: function() {return _description;},
- set: function(v) {_description = converter_.toString(v)},
- enumerable: true
- },
- trackNum: {
- get: function() {return _trackNum;},
- set: function(v) {_trackNum = converter_.toString(v)},
- enumerable: true
- },
- picture: {
- get: function() {return _picture;},
- set: function(v) {_picture = converter_.toString(v)},
- enumerable: true
- }
- });
+ var _title = '';
+ var _artist = '';
+ var _album = '';
+ var _author = '';
+ var _genre = '';
+ var _duration = '';
+ var _date = '';
+ var _copyright = '';
+ var _description = '';
+ var _trackNum = '';
+ var _picture = '';
+ Object.defineProperties(this, {
+ title: {
+ get: function() {
+ return _title;
+ },
+ set: function(v) {
+ _title = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ artist: {
+ get: function() {
+ return _artist;
+ },
+ set: function(v) {
+ _artist = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ album: {
+ get: function() {
+ return _album;
+ },
+ set: function(v) {
+ _album = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ author: {
+ get: function() {
+ return _author;
+ },
+ set: function(v) {
+ _author = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ genre: {
+ get: function() {
+ return _genre;
+ },
+ set: function(v) {
+ _genre = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ duration: {
+ get: function() {
+ return _duration;
+ },
+ set: function(v) {
+ _duration = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ date: {
+ get: function() {
+ return _date;
+ },
+ set: function(v) {
+ _date = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ copyright: {
+ get: function() {
+ return _copyright;
+ },
+ set: function(v) {
+ _copyright = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ description: {
+ get: function() {
+ return _description;
+ },
+ set: function(v) {
+ _description = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ trackNum: {
+ get: function() {
+ return _trackNum;
+ },
+ set: function(v) {
+ _trackNum = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ picture: {
+ get: function() {
+ return _picture;
+ },
+ set: function(v) {
+ _picture = converter_.toString(v);
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (data.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (data.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
var MediaControllerPlaybackInfo = function(data) {
- var _state = 'STOP';
- var _position = 0;
- var _shuffleMode = false;
- var _repeatMode = false;
- var _metadata = new MediaControllerMetadata();
- Object.defineProperties(this, {
- state: {
- get: function() {
- return _state;
- },
- set: function(v) {
- _state = edit_.isAllowed && v ? v : _state;
- },
- enumerable: true
- },
- position: {
- get: function() {
- return _position;
- },
- set: function(v) {
- _position = edit_.isAllowed ? converter_.toLong(v) : _position;
- },
- enumerable: true
- },
- shuffleMode: {
- get: function() {
- return _shuffleMode;
- },
- set: function(v) {
- _shuffleMode = edit_.isAllowed ? converter_.toBoolean(v) : _shuffleMode;
- },
- enumerable: true
- },
- repeatMode: {
- get: function() {
- return _repeatMode;
- },
- set: function(v) {
- _repeatMode = edit_.isAllowed ? converter_.toBoolean(v) : _repeatMode;
- },
- enumerable: true
- },
- metadata: {
- get: function() {
- return _metadata;
- },
- set: function(v) {
- _metadata = edit_.isAllowed && v ? new MediaControllerMetadata(v) : _metadata;
- },
- enumerable: true
- }
- });
+ var _state = 'STOP';
+ var _position = 0;
+ var _shuffleMode = false;
+ var _repeatMode = false;
+ var _metadata = new MediaControllerMetadata();
+ Object.defineProperties(this, {
+ state: {
+ get: function() {
+ return _state;
+ },
+ set: function(v) {
+ _state = edit_.isAllowed && v ? v : _state;
+ },
+ enumerable: true
+ },
+ position: {
+ get: function() {
+ return _position;
+ },
+ set: function(v) {
+ _position = edit_.isAllowed ? converter_.toLong(v) : _position;
+ },
+ enumerable: true
+ },
+ shuffleMode: {
+ get: function() {
+ return _shuffleMode;
+ },
+ set: function(v) {
+ _shuffleMode = edit_.isAllowed ? converter_.toBoolean(v) : _shuffleMode;
+ },
+ enumerable: true
+ },
+ repeatMode: {
+ get: function() {
+ return _repeatMode;
+ },
+ set: function(v) {
+ _repeatMode = edit_.isAllowed ? converter_.toBoolean(v) : _repeatMode;
+ },
+ enumerable: true
+ },
+ metadata: {
+ get: function() {
+ return _metadata;
+ },
+ set: function(v) {
+ _metadata =
+ edit_.isAllowed && v ? new MediaControllerMetadata(v) : _metadata;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (data.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (data.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
};
function MediaControllerServer(data) {
- Object.defineProperties(this, {
- playbackInfo: {
- value: new MediaControllerPlaybackInfo(data),
- writable: false,
- enumerable: true
- }
- });
+ Object.defineProperties(this, {
+ playbackInfo: {
+ value: new MediaControllerPlaybackInfo(data),
+ writable: false,
+ enumerable: true
+ }
+ });
}
MediaControllerServer.prototype.updatePlaybackState = function(state) {
- var args = validator_.validateArgs(arguments, [
- {name: 'state', type: types_.ENUM, values: Object.keys(MediaControllerPlaybackState)}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'state',
+ type: types_.ENUM,
+ values: Object.keys(MediaControllerPlaybackState)
+ }
+ ]);
- var data = {
- state: args.state
- };
+ var data = {
+ state: args.state
+ };
- var result = native_.callSync('MediaControllerServer_updatePlaybackState', data);
+ var result = native_.callSync('MediaControllerServer_updatePlaybackState', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- edit_.allow();
- this.playbackInfo.state = args.state;
- edit_.disallow();
+ edit_.allow();
+ this.playbackInfo.state = args.state;
+ edit_.disallow();
};
MediaControllerServer.prototype.updatePlaybackPosition = function(position) {
- var args = validator_.validateArgs(arguments, [
- {name: 'position', type: types_.UNSIGNED_LONG_LONG}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'position', type: types_.UNSIGNED_LONG_LONG }
+ ]);
- var data = {
- position: args.position
- };
+ var data = {
+ position: args.position
+ };
- var result = native_.callSync('MediaControllerServer_updatePlaybackPosition', data);
+ var result = native_.callSync('MediaControllerServer_updatePlaybackPosition', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- edit_.allow();
- this.playbackInfo.position = args.position;
- edit_.disallow();
+ edit_.allow();
+ this.playbackInfo.position = args.position;
+ edit_.disallow();
};
MediaControllerServer.prototype.updateShuffleMode = function(mode) {
- var args = validator_.validateArgs(arguments, [
- {name: 'mode', type: types_.BOOLEAN}
- ]);
-
- var data = {
- mode: args.mode
- };
-
- var result = native_.callSync('MediaControllerServer_updateShuffleMode', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- edit_.allow();
- this.playbackInfo.shuffleMode = args.mode;
- edit_.disallow();
-};
-
-MediaControllerServer.prototype.updateRepeatMode = function(mode) {
- var args = validator_.validateArgs(arguments, [
- {name: 'mode', type: types_.BOOLEAN}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'mode', type: types_.BOOLEAN }
+ ]);
- var data = {
- mode: args.mode
- };
+ var data = {
+ mode: args.mode
+ };
- var result = native_.callSync('MediaControllerServer_updateRepeatMode', data);
+ var result = native_.callSync('MediaControllerServer_updateShuffleMode', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- edit_.allow();
- this.playbackInfo.repeatMode = args.mode;
- edit_.disallow();
-};
-
-MediaControllerServer.prototype.updateMetadata = function(metadata) {
- var args = validator_.validateArgs(arguments, [
- {name: 'metadata', type: types_.PLATFORM_OBJECT, values: MediaControllerMetadata}
- ]);
-
- var data = {
- metadata: args.metadata
- };
-
- var result = native_.callSync('MediaControllerServer_updateMetadata', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- edit_.allow();
- this.playbackInfo.metadata = args.metadata;
- edit_.disallow();
-};
-
-MediaControllerServer.prototype.addChangeRequestPlaybackInfoListener = function(listener) {
- var args = validator_.validateArgs(arguments, [{
- name: 'listener',
- type: types_.LISTENER,
- values: [
- 'onplaybackstaterequest',
- 'onplaybackpositionrequest',
- 'onshufflemoderequest',
- 'onrepeatmoderequest'
- ]
- }]);
-
- if (type_.isEmptyObject(ServerPlaybackInfoListener.listeners)) {
- var result = native_.callSync('MediaControllerServer_addChangeRequestPlaybackInfoListener', {
- listenerId: ServerPlaybackInfoListener.listenerName
- });
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
- }
- return ServerPlaybackInfoListener.addListener(args.listener);
+ edit_.allow();
+ this.playbackInfo.shuffleMode = args.mode;
+ edit_.disallow();
};
-MediaControllerServer.prototype.removeChangeRequestPlaybackInfoListener = function(watchId) {
- var args = validator_.validateArgs(arguments, [
- {name: 'watchId', type: types_.LONG}
- ]);
-
- ServerPlaybackInfoListener.removeListener(args.watchId);
+MediaControllerServer.prototype.updateRepeatMode = function(mode) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'mode', type: types_.BOOLEAN }
+ ]);
- if (type_.isEmptyObject(ServerPlaybackInfoListener.listeners)) {
- native_.callSync('MediaControllerServer_removeCommandListener');
- }
-};
+ var data = {
+ mode: args.mode
+ };
-MediaControllerServer.prototype.addCommandListener = function(listener) {
- var args = validator_.validateArgs(arguments, [
- {name: 'listener', type: types_.FUNCTION}
- ]);
+ var result = native_.callSync('MediaControllerServer_updateRepeatMode', data);
- if (type_.isEmptyObject(ServerCommandListener.listeners)) {
- var result = native_.callSync('MediaControllerServer_addCommandListener', {
- listenerId: ServerCommandListener.listenerName
- });
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
- }
- return ServerCommandListener.addListener(args.listener);
-};
-
-MediaControllerServer.prototype.removeCommandListener = function(watchId) {
- var args = validator_.validateArgs(arguments, [
- {name: 'watchId', type: types_.LONG}
- ]);
-
- ServerCommandListener.removeListener(args.watchId);
-
- if (type_.isEmptyObject(ServerCommandListener.listeners)) {
- native_.callSync('MediaControllerServer_removeCommandListener');
- }
+ edit_.allow();
+ this.playbackInfo.repeatMode = args.mode;
+ edit_.disallow();
};
+MediaControllerServer.prototype.updateMetadata = function(metadata) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'metadata',
+ type: types_.PLATFORM_OBJECT,
+ values: MediaControllerMetadata
+ }
+ ]);
-function MediaControllerClient() {}
+ var data = {
+ metadata: args.metadata
+ };
-MediaControllerClient.prototype.findServers = function(successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+ var result = native_.callSync('MediaControllerServer_updateMetadata', data);
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- var info = [];
- var data = native_.getResultObject(result);
- for (var i = 0; i < data.length; i++) {
- info.push(new MediaControllerServerInfo(data[i]));
+
+ edit_.allow();
+ this.playbackInfo.metadata = args.metadata;
+ edit_.disallow();
+};
+
+MediaControllerServer.prototype.addChangeRequestPlaybackInfoListener = function(
+ listener
+) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listener',
+ type: types_.LISTENER,
+ values: [
+ 'onplaybackstaterequest',
+ 'onplaybackpositionrequest',
+ 'onshufflemoderequest',
+ 'onrepeatmoderequest'
+ ]
+ }
+ ]);
+
+ if (type_.isEmptyObject(ServerPlaybackInfoListener.listeners)) {
+ var result = native_.callSync(
+ 'MediaControllerServer_addChangeRequestPlaybackInfoListener',
+ {
+ listenerId: ServerPlaybackInfoListener.listenerName
+ }
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- native_.callIfPossible(args.successCallback, info);
- };
- native_.call('MediaControllerClient_findServers', {}, callback);
+ return ServerPlaybackInfoListener.addListener(args.listener);
};
-MediaControllerClient.prototype.getLatestServerInfo = function() {
-
- var result = native_.callSync('MediaControllerClient_getLatestServerInfo', {});
+MediaControllerServer.prototype.removeChangeRequestPlaybackInfoListener = function(
+ watchId
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG }
+ ]);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ ServerPlaybackInfoListener.removeListener(args.watchId);
- var serverInfo = native_.getResultObject(result);
- if (serverInfo) {
- if ('NONE' === serverInfo.state) {
- serverInfo.state = 'INACTIVE';
+ if (type_.isEmptyObject(ServerPlaybackInfoListener.listeners)) {
+ native_.callSync('MediaControllerServer_removeCommandListener');
}
- serverInfo = new MediaControllerServerInfo(serverInfo);
- }
- return serverInfo;
};
+MediaControllerServer.prototype.addCommandListener = function(listener) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'listener', type: types_.FUNCTION }
+ ]);
-function MediaControllerServerInfo(data) {
- Object.defineProperties(this, {
- name: {
- value: data.name,
- writable: false,
- enumerable: true
- },
- state: {
- value: data.state,
- writable: false,
- enumerable: true
- },
- playbackInfo: {
- get: function () {
- var result = native_.callSync('MediaControllerClient_getPlaybackInfo', {name: this.name});
+ if (type_.isEmptyObject(ServerCommandListener.listeners)) {
+ var result = native_.callSync('MediaControllerServer_addCommandListener', {
+ listenerId: ServerCommandListener.listenerName
+ });
if (native_.isFailure(result)) {
- throw new native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
- edit_.allow();
- var data = native_.getResultObject(result);
- var playbackInfo = new MediaControllerPlaybackInfo(data);
- edit_.disallow();
-
- return playbackInfo;
- }.bind(this),
- set: function() {},
- enumerable: true
}
- });
-}
+ return ServerCommandListener.addListener(args.listener);
+};
-MediaControllerServerInfo.prototype.sendPlaybackState = function(state, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'state', type: types_.ENUM, values: Object.keys(MediaControllerPlaybackState)},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+MediaControllerServer.prototype.removeCommandListener = function(watchId) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG }
+ ]);
- var data = {
- name: this.name,
- state: args.state
- };
+ ServerCommandListener.removeListener(args.watchId);
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ if (type_.isEmptyObject(ServerCommandListener.listeners)) {
+ native_.callSync('MediaControllerServer_removeCommandListener');
}
- native_.callIfPossible(args.successCallback);
- };
-
- native_.call('MediaControllerServerInfo_sendPlaybackState', data, callback);
};
-MediaControllerServerInfo.prototype.sendPlaybackPosition = function(position, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'position', type: types_.LONG_LONG},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- if (args.position < 0) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
+function MediaControllerClient() {}
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
- }
- native_.callIfPossible(args.successCallback);
- };
+MediaControllerClient.prototype.findServers = function(successCallback, errorCallback) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
- var data = {
- position: args.position,
- name: this.name
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ var info = [];
+ var data = native_.getResultObject(result);
+ for (var i = 0; i < data.length; i++) {
+ info.push(new MediaControllerServerInfo(data[i]));
+ }
+ native_.callIfPossible(args.successCallback, info);
+ };
- native_.call('MediaControllerServerInfo_sendPlaybackPosition', data, callback);
+ native_.call('MediaControllerClient_findServers', {}, callback);
};
-MediaControllerServerInfo.prototype.sendShuffleMode = function(mode, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'mode', type: types_.BOOLEAN},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+MediaControllerClient.prototype.getLatestServerInfo = function() {
+ var result = native_.callSync('MediaControllerClient_getLatestServerInfo', {});
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
- native_.callIfPossible(args.successCallback);
- };
- var data = {
- mode: args.mode,
- name: this.name
- };
- native_.call('MediaControllerServerInfo_sendShuffleMode', data, callback);
-};
-
-MediaControllerServerInfo.prototype.sendRepeatMode = function(mode, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'mode', type: types_.BOOLEAN},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ var serverInfo = native_.getResultObject(result);
+ if (serverInfo) {
+ if ('NONE' === serverInfo.state) {
+ serverInfo.state = 'INACTIVE';
+ }
+ serverInfo = new MediaControllerServerInfo(serverInfo);
}
- native_.callIfPossible(args.successCallback);
- };
-
- var data = {
- mode: args.mode,
- name: this.name
- };
- native_.call('MediaControllerServerInfo_sendRepeatMode', data, callback);
+ return serverInfo;
};
-MediaControllerServerInfo.prototype.sendCommand = function(command, data, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'command', type: types_.STRING},
- {name: 'data', type: types_.DICTIONARY},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+function MediaControllerServerInfo(data) {
+ Object.defineProperties(this, {
+ name: {
+ value: data.name,
+ writable: false,
+ enumerable: true
+ },
+ state: {
+ value: data.state,
+ writable: false,
+ enumerable: true
+ },
+ playbackInfo: {
+ get: function() {
+ var result = native_.callSync('MediaControllerClient_getPlaybackInfo', {
+ name: this.name
+ });
+ if (native_.isFailure(result)) {
+ throw new native_.getErrorObject(result);
+ }
+ edit_.allow();
+ var data = native_.getResultObject(result);
+ var playbackInfo = new MediaControllerPlaybackInfo(data);
+ edit_.disallow();
+
+ return playbackInfo;
+ }.bind(this),
+ set: function() {},
+ enumerable: true
+ }
+ });
+}
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+MediaControllerServerInfo.prototype.sendPlaybackState = function(
+ state,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'state',
+ type: types_.ENUM,
+ values: Object.keys(MediaControllerPlaybackState)
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var data = {
+ name: this.name,
+ state: args.state
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
+
+ native_.call('MediaControllerServerInfo_sendPlaybackState', data, callback);
+};
+
+MediaControllerServerInfo.prototype.sendPlaybackPosition = function(
+ position,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'position', type: types_.LONG_LONG },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ if (args.position < 0) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- native_.callIfPossible(args.successCallback, native_.getResultObject(result).data);
- };
- var nativeData = {
- command: args.command,
- data: args.data,
- name: this.name,
- listenerId: ReplyCommandListener.listenerName
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var data = {
+ position: args.position,
+ name: this.name
+ };
+
+ native_.call('MediaControllerServerInfo_sendPlaybackPosition', data, callback);
+};
+
+MediaControllerServerInfo.prototype.sendShuffleMode = function(
+ mode,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'mode', type: types_.BOOLEAN },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var data = {
+ mode: args.mode,
+ name: this.name
+ };
+ native_.call('MediaControllerServerInfo_sendShuffleMode', data, callback);
+};
+
+MediaControllerServerInfo.prototype.sendRepeatMode = function(
+ mode,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'mode', type: types_.BOOLEAN },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
+
+ var data = {
+ mode: args.mode,
+ name: this.name
+ };
+ native_.call('MediaControllerServerInfo_sendRepeatMode', data, callback);
+};
+
+MediaControllerServerInfo.prototype.sendCommand = function(
+ command,
+ data,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'command', type: types_.STRING },
+ { name: 'data', type: types_.DICTIONARY },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(
+ args.successCallback,
+ native_.getResultObject(result).data
+ );
+ };
- var replyListenerId = ReplyCommandListener.addListener(callback);
- var result = native_.callSync('MediaControllerServerInfo_sendCommand', nativeData);
+ var nativeData = {
+ command: args.command,
+ data: args.data,
+ name: this.name,
+ listenerId: ReplyCommandListener.listenerName
+ };
- ReplyCommandListener.requestIdToListenerId[replyListenerId] = result.requestId;
+ var replyListenerId = ReplyCommandListener.addListener(callback);
+ var result = native_.callSync('MediaControllerServerInfo_sendCommand', nativeData);
+
+ ReplyCommandListener.requestIdToListenerId[replyListenerId] = result.requestId;
};
MediaControllerServerInfo.prototype.addServerStatusChangeListener = function(listener) {
- var args = validator_.validateArgs(arguments, [
- {name: 'listener', type: types_.FUNCTION}
- ]);
-
- if (type_.isEmptyObject(ServerInfoStatusListener.listeners)) {
- var result = native_.callSync('MediaControllerServerInfo_addServerStatusChangeListener', {
- listenerId: ServerInfoStatusListener.listenerName
- });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'listener', type: types_.FUNCTION }
+ ]);
+
+ if (type_.isEmptyObject(ServerInfoStatusListener.listeners)) {
+ var result = native_.callSync(
+ 'MediaControllerServerInfo_addServerStatusChangeListener',
+ {
+ listenerId: ServerInfoStatusListener.listenerName
+ }
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- return ServerInfoStatusListener.addServerInfoListener(args.listener, this.name);
+ return ServerInfoStatusListener.addServerInfoListener(args.listener, this.name);
};
MediaControllerServerInfo.prototype.removeServerStatusChangeListener = function(watchId) {
- var args = validator_.validateArgs(arguments, [
- {name: 'watchId', type: types_.LONG}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG }
+ ]);
- ServerInfoStatusListener.removeServerInfoListener(args.watchId);
+ ServerInfoStatusListener.removeServerInfoListener(args.watchId);
- if (type_.isEmptyObject(ServerInfoStatusListener.listeners)) {
- native_.callSync('MediaControllerServerInfo_removeServerStatusChangeListener');
- }
+ if (type_.isEmptyObject(ServerInfoStatusListener.listeners)) {
+ native_.callSync('MediaControllerServerInfo_removeServerStatusChangeListener');
+ }
};
MediaControllerServerInfo.prototype.addPlaybackInfoChangeListener = function(listener) {
- var args = validator_.validateArgs(arguments, [{
- name: 'listener',
- type: types_.LISTENER,
- values: [
- 'onplaybackchanged',
- 'onshufflemodechanged',
- 'onrepeatmodechanged',
- 'onmetadatachanged'
- ]
- }]);
-
- if (type_.isEmptyObject(ServerInfoPlaybackInfoListener.listeners)) {
- var result = native_.callSync(
- 'MediaControllerServerInfo_addPlaybackInfoChangeListener', {
- listenerId: ServerInfoPlaybackInfoListener.listenerName
- });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listener',
+ type: types_.LISTENER,
+ values: [
+ 'onplaybackchanged',
+ 'onshufflemodechanged',
+ 'onrepeatmodechanged',
+ 'onmetadatachanged'
+ ]
+ }
+ ]);
+
+ if (type_.isEmptyObject(ServerInfoPlaybackInfoListener.listeners)) {
+ var result = native_.callSync(
+ 'MediaControllerServerInfo_addPlaybackInfoChangeListener',
+ {
+ listenerId: ServerInfoPlaybackInfoListener.listenerName
+ }
+ );
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- return ServerInfoPlaybackInfoListener.addServerInfoListener(args.listener, this.name);
+ return ServerInfoPlaybackInfoListener.addServerInfoListener(args.listener, this.name);
};
MediaControllerServerInfo.prototype.removePlaybackInfoChangeListener = function(watchId) {
- var args = validator_.validateArgs(arguments, [
- {name: 'watchId', type: types_.LONG}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG }
+ ]);
- ServerInfoPlaybackInfoListener.removeServerInfoListener(args.watchId);
+ ServerInfoPlaybackInfoListener.removeServerInfoListener(args.watchId);
- if (type_.isEmptyObject(ServerInfoPlaybackInfoListener.listeners)) {
- native_.callSync('MediaControllerServerInfo_removePlaybackInfoChangeListener');
- }
+ if (type_.isEmptyObject(ServerInfoPlaybackInfoListener.listeners)) {
+ native_.callSync('MediaControllerServerInfo_removePlaybackInfoChangeListener');
+ }
};
-
exports = new MediaControllerManager();
diff --git a/src/mediakey/mediakey_api.js b/src/mediakey/mediakey_api.js
index d04e382b..3fd8a33b 100755
--- a/src/mediakey/mediakey_api.js
+++ b/src/mediakey/mediakey_api.js
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var validator = xwalk.utils.validator;
var type = xwalk.utils.type;
var native = new xwalk.utils.NativeManager(extension);
@@ -23,16 +23,16 @@ var ON_PRESSED_MEDIA_KEY_EVENT_CALLBACK = 'onPressedMediaKeyEventCallback';
var ON_RELEASED_MEDIA_KEY_EVENT_CALLBACK = 'onReleasedMediaKeyEventCallback';
function MediaKeyManager() {
- validator.isConstructorCall(this, MediaKeyManager);
+ validator.isConstructorCall(this, MediaKeyManager);
}
MediaKeyManager.prototype.setMediaKeyEventListener = function(callback) {
var args = validator.validateArgs(arguments, [
- {
- name: 'callback',
- type: validator.Types.LISTENER,
- values: ['onpressed', 'onreleased']
- }
+ {
+ name: 'callback',
+ type: validator.Types.LISTENER,
+ values: ['onpressed', 'onreleased']
+ }
]);
var ret = native.callSync('MediaKeyManager_setMediaKeyEventListener', {});
@@ -50,11 +50,10 @@ MediaKeyManager.prototype.setMediaKeyEventListener = function(callback) {
native.addListener(ON_RELEASED_MEDIA_KEY_EVENT_CALLBACK, function(msg) {
native.callIfPossible(args.callback.onreleased, msg.type);
});
-
};
MediaKeyManager.prototype.unsetMediaKeyEventListener = function() {
- var ret = native.callSync('MediaKeyManager_unsetMediaKeyEventListener',{});
+ var ret = native.callSync('MediaKeyManager_unsetMediaKeyEventListener', {});
if (native.isFailure(ret)) {
throw native.getErrorObject(ret);
diff --git a/src/messageport/messageport_api.js b/src/messageport/messageport_api.js
index 3219ed2f..00e77435 100755
--- a/src/messageport/messageport_api.js
+++ b/src/messageport/messageport_api.js
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var validator_ = xwalk.utils.validator;
var types_ = validator_.Types;
var type_ = xwalk.utils.type;
@@ -27,270 +27,329 @@ var callbacks = {};
var ports = [];
function MessagePortChangeCallback(msg) {
- var listeners = callbacks[msg['localPortId']];
- var rmp;
-
- if (!msg.hasOwnProperty('remotePort'))
- rmp = null;
- else
- rmp = new RemoteMessagePort(msg.remotePort, msg.remoteAppId, msg.trusted);
- for (var i = 0; i < listeners.length; i++) {
- var func = listeners[i][0];
- setTimeout(function() {
- func(msg.message, rmp);
- }, 0);
- }
+ var listeners = callbacks[msg['localPortId']];
+ var rmp;
+
+ if (!msg.hasOwnProperty('remotePort')) rmp = null;
+ else rmp = new RemoteMessagePort(msg.remotePort, msg.remoteAppId, msg.trusted);
+ for (var i = 0; i < listeners.length; i++) {
+ var func = listeners[i][0];
+ setTimeout(function() {
+ func(msg.message, rmp);
+ }, 0);
+ }
}
function nextCallbackId() {
- return callbackId++;
+ return callbackId++;
}
function MessagePortManager() {
- // constructor of MessagePortManager
+ // constructor of MessagePortManager
}
-
MessagePortManager.prototype.requestLocalMessagePort = function(localMessagePortName) {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'localMessagePortName', 'type': types_.STRING}
- ]);
-
- if ('' === args.localMessagePortName) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Port name cannot be empty.');
- }
-
- var localPortId; // TODO remove
- var nativeParam = {
- 'localMessagePortName': args.localMessagePortName
- };
-
- var result = native_.callSync('MessagePortManager_requestLocalMessagePort', nativeParam);
-
- if (native_.isSuccess(result)) {
- var returnObject = new LocalMessagePort(args.localMessagePortName, false);
- ports[nativeParam.localMessagePortName] = native_.getResultObject(result);
- } else {
- throw native_.getErrorObject(result);
- }
-
- return returnObject;
-};
-
-MessagePortManager.prototype.requestTrustedLocalMessagePort = function(localMessagePortName) {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'localMessagePortName', 'type': types_.STRING}
- ]);
-
- if ('' === args.localMessagePortName) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Port name cannot be empty.');
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'localMessagePortName', type: types_.STRING }
+ ]);
+
+ if ('' === args.localMessagePortName) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Port name cannot be empty.'
+ );
+ }
- var nativeParam = {
- 'localMessagePortName': args.localMessagePortName
- };
+ var localPortId; // TODO remove
+ var nativeParam = {
+ localMessagePortName: args.localMessagePortName
+ };
- var result = native_.callSync('MessagePortManager_requestTrustedLocalMessagePort', nativeParam);
+ var result = native_.callSync(
+ 'MessagePortManager_requestLocalMessagePort',
+ nativeParam
+ );
- if (native_.isSuccess(result)) {
- var returnObject = new LocalMessagePort(args.localMessagePortName, true);
- ports[nativeParam.localMessagePortName] = native_.getResultObject(result);
- } else {
- throw native_.getErrorObject(result);
- }
+ if (native_.isSuccess(result)) {
+ var returnObject = new LocalMessagePort(args.localMessagePortName, false);
+ ports[nativeParam.localMessagePortName] = native_.getResultObject(result);
+ } else {
+ throw native_.getErrorObject(result);
+ }
- return returnObject;
+ return returnObject;
};
-MessagePortManager.prototype.requestRemoteMessagePort =
- function(appId, remoteMessagePortName) {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'appId', 'type': types_.STRING},
- {'name' : 'remoteMessagePortName', 'type': types_.STRING}
- ]);
-
- var nativeParam = {
- 'appId': args.appId,
- 'remoteMessagePortName': args.remoteMessagePortName
- };
+MessagePortManager.prototype.requestTrustedLocalMessagePort = function(
+ localMessagePortName
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'localMessagePortName', type: types_.STRING }
+ ]);
+
+ if ('' === args.localMessagePortName) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Port name cannot be empty.'
+ );
+ }
- var result = native_.callSync('MessagePortManager_requestRemoteMessagePort', nativeParam);
+ var nativeParam = {
+ localMessagePortName: args.localMessagePortName
+ };
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync(
+ 'MessagePortManager_requestTrustedLocalMessagePort',
+ nativeParam
+ );
- var returnObject = new RemoteMessagePort(args.remoteMessagePortName, args.appId, false);
+ if (native_.isSuccess(result)) {
+ var returnObject = new LocalMessagePort(args.localMessagePortName, true);
+ ports[nativeParam.localMessagePortName] = native_.getResultObject(result);
+ } else {
+ throw native_.getErrorObject(result);
+ }
- return returnObject;
+ return returnObject;
};
-MessagePortManager.prototype.requestTrustedRemoteMessagePort =
- function(appId, remoteMessagePortName) {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'appId', 'type': types_.STRING},
- {'name' : 'remoteMessagePortName', 'type': types_.STRING}
- ]);
+MessagePortManager.prototype.requestRemoteMessagePort = function(
+ appId,
+ remoteMessagePortName
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'appId', type: types_.STRING },
+ { name: 'remoteMessagePortName', type: types_.STRING }
+ ]);
+
+ var nativeParam = {
+ appId: args.appId,
+ remoteMessagePortName: args.remoteMessagePortName
+ };
+
+ var result = native_.callSync(
+ 'MessagePortManager_requestRemoteMessagePort',
+ nativeParam
+ );
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var nativeParam = {
- 'appId' : args.appId,
- 'remoteMessagePortName': args.remoteMessagePortName
- };
+ var returnObject = new RemoteMessagePort(
+ args.remoteMessagePortName,
+ args.appId,
+ false
+ );
- var result = native_.callSync('MessagePortManager_requestTrustedRemoteMessagePort', nativeParam);
+ return returnObject;
+};
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+MessagePortManager.prototype.requestTrustedRemoteMessagePort = function(
+ appId,
+ remoteMessagePortName
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'appId', type: types_.STRING },
+ { name: 'remoteMessagePortName', type: types_.STRING }
+ ]);
+
+ var nativeParam = {
+ appId: args.appId,
+ remoteMessagePortName: args.remoteMessagePortName
+ };
+
+ var result = native_.callSync(
+ 'MessagePortManager_requestTrustedRemoteMessagePort',
+ nativeParam
+ );
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var returnObject = new RemoteMessagePort(args.remoteMessagePortName, args.appId, true);
+ var returnObject = new RemoteMessagePort(
+ args.remoteMessagePortName,
+ args.appId,
+ true
+ );
- return returnObject;
+ return returnObject;
};
-
function LocalMessagePort(messagePortName, isTrusted) {
- Object.defineProperties(this, {
- 'messagePortName': { value: messagePortName, writable: false, enumerable: true },
- 'isTrusted': { value: !!isTrusted, writable: false, enumerable: true }
- });
+ Object.defineProperties(this, {
+ messagePortName: { value: messagePortName, writable: false, enumerable: true },
+ isTrusted: { value: !!isTrusted, writable: false, enumerable: true }
+ });
}
-
LocalMessagePort.prototype.addMessagePortListener = function(listener) {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'listener', 'type': types_.FUNCTION, 'nullable': false}
- ]);
-
- native_.addListener(LOCAL_MESSAGE_PORT_LISTENER_ID, MessagePortChangeCallback);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'listener', type: types_.FUNCTION, nullable: false }
+ ]);
- var portId = ports[this.messagePortName];
+ native_.addListener(LOCAL_MESSAGE_PORT_LISTENER_ID, MessagePortChangeCallback);
- if (!callbacks.hasOwnProperty(portId)) callbacks[portId] = [];
+ var portId = ports[this.messagePortName];
- callbackId++;
- callbacks[portId].push([listener, callbackId]);
+ if (!callbacks.hasOwnProperty(portId)) callbacks[portId] = [];
- return callbackId;
+ callbackId++;
+ callbacks[portId].push([listener, callbackId]);
+ return callbackId;
};
LocalMessagePort.prototype.removeMessagePortListener = function(watchId) {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'watchId', 'type': types_.LONG, 'nullable': false, 'optional': false }
- ]);
-
- var toDelete;
- var listeners = callbacks[ports[this.messagePortName]];
-
- for (var key in listeners) {
- var listenerId = listeners[key][1];
- if (watchId == listenerId) {
- toDelete = key;
- break;
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG, nullable: false, optional: false }
+ ]);
+
+ var toDelete;
+ var listeners = callbacks[ports[this.messagePortName]];
+
+ for (var key in listeners) {
+ var listenerId = listeners[key][1];
+ if (watchId == listenerId) {
+ toDelete = key;
+ break;
+ }
}
- }
-
- if (typeof toDelete === 'undefined')
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR,
- 'The port of the target application is not found.');
- listeners.splice(toDelete, 1);
+ if (typeof toDelete === 'undefined')
+ throw new WebAPIException(
+ WebAPIException.NOT_FOUND_ERR,
+ 'The port of the target application is not found.'
+ );
+ listeners.splice(toDelete, 1);
};
-
function RemoteMessagePort(messagePortName, appId, isTrusted) {
- Object.defineProperties(this, {
- 'messagePortName': { value: messagePortName, writable: false },
- 'appId': { value: appId, writable: false },
- 'isTrusted': { value: !!isTrusted, writable: false }
- });
+ Object.defineProperties(this, {
+ messagePortName: { value: messagePortName, writable: false },
+ appId: { value: appId, writable: false },
+ isTrusted: { value: !!isTrusted, writable: false }
+ });
}
function _isOctet(valArray) {
- for(var i=0;i<valArray.length; i++) {
- if (valArray[i]<0 || valArray[i]>255) {
- return false;
+ for (var i = 0; i < valArray.length; i++) {
+ if (valArray[i] < 0 || valArray[i] > 255) {
+ return false;
+ }
}
- }
- return true;
+ return true;
}
RemoteMessagePort.prototype.sendMessage = function() {
- var args = validator_.validateArgs(arguments, [
- {'name' : 'data', 'type': types_.ARRAY},
- {'name' : 'localMessagePort', 'type': types_.PLATFORM_OBJECT, 'optional' : true,
- 'nullable' : true, 'values' : LocalMessagePort }
- ]);
-
- var filteredData = new Array(args.data.length);
- var uniqueDataKey = {};
- var dataLength = args.data.length;
- for (var i = 0; i < dataLength; i++) {
- if (!args.data[i].hasOwnProperty('key')) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'MessagePortDataItem should contain \'key\' property.');
- }
- var key = args.data[i].key;
- if ('' === key) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Property \'key\' should not be empty.');
- }
- if (true === uniqueDataKey[key]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Property \'key\' should not be duplicated.');
- }
- var value = args.data[i].value;
- if (type_.isString(value)) {
- filteredData[i] = { key: key, value: value, valueType: 'stringValueType'};
- } else if(type_.isArray(value)) {
- var arrayMember = value[0];
- if(type_.isString(arrayMember)) {
- for(var j=1;j<value.length;j++) {
- if (!(type_.isString(value[j]))) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid array value');
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'data', type: types_.ARRAY },
+ {
+ name: 'localMessagePort',
+ type: types_.PLATFORM_OBJECT,
+ optional: true,
+ nullable: true,
+ values: LocalMessagePort
}
- filteredData[i] = { key: key, value: value, valueType: 'stringArrayValueType'};
- } else if(!type_.isArray(arrayMember)) {
- if (!_isOctet(value)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Data is not octet array');
+ ]);
+
+ var filteredData = new Array(args.data.length);
+ var uniqueDataKey = {};
+ var dataLength = args.data.length;
+ for (var i = 0; i < dataLength; i++) {
+ if (!args.data[i].hasOwnProperty('key')) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'MessagePortDataItem should contain \'key\' property.'
+ );
}
- filteredData[i] = { key: key, value: value, valueType: 'byteStreamValueType'};
- } else {
- for(var j=0;j<value.length;j++) {
- if (!_isOctet(value[j])) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Data is not octet array');
- }
+ var key = args.data[i].key;
+ if ('' === key) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Property \'key\' should not be empty.'
+ );
}
- filteredData[i] = { key: key, value: value, valueType: 'byteStreamArrayValueType'};
- }
- } else {
- // convert any other value to string -> backward compatibility
- filteredData[i] = { key: key, value: converter_.toString(value), valueType: 'stringValueType'};
+ if (true === uniqueDataKey[key]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Property \'key\' should not be duplicated.'
+ );
+ }
+ var value = args.data[i].value;
+ if (type_.isString(value)) {
+ filteredData[i] = { key: key, value: value, valueType: 'stringValueType' };
+ } else if (type_.isArray(value)) {
+ var arrayMember = value[0];
+ if (type_.isString(arrayMember)) {
+ for (var j = 1; j < value.length; j++) {
+ if (!type_.isString(value[j])) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid array value'
+ );
+ }
+ }
+ filteredData[i] = {
+ key: key,
+ value: value,
+ valueType: 'stringArrayValueType'
+ };
+ } else if (!type_.isArray(arrayMember)) {
+ if (!_isOctet(value)) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Data is not octet array'
+ );
+ }
+ filteredData[i] = {
+ key: key,
+ value: value,
+ valueType: 'byteStreamValueType'
+ };
+ } else {
+ for (var j = 0; j < value.length; j++) {
+ if (!_isOctet(value[j])) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Data is not octet array'
+ );
+ }
+ }
+ filteredData[i] = {
+ key: key,
+ value: value,
+ valueType: 'byteStreamArrayValueType'
+ };
+ }
+ } else {
+ // convert any other value to string -> backward compatibility
+ filteredData[i] = {
+ key: key,
+ value: converter_.toString(value),
+ valueType: 'stringValueType'
+ };
+ }
+ uniqueDataKey[key] = true;
+ }
+
+ var nativeParam = {
+ appId: this.appId,
+ messagePortName: this.messagePortName,
+ data: filteredData,
+ trusted: this.isTrusted,
+ localPortId: args.localMessagePort
+ ? ports[args.localMessagePort.messagePortName]
+ : -1
+ };
+
+ var result = native_.callSync('RemoteMessagePort_sendMessage', nativeParam);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- uniqueDataKey[key] = true;
- }
-
- var nativeParam = {
- 'appId': this.appId,
- 'messagePortName': this.messagePortName,
- 'data': filteredData,
- 'trusted': this.isTrusted,
- 'localPortId': args.localMessagePort ? ports[args.localMessagePort.messagePortName] : -1
- };
-
- var result = native_.callSync('RemoteMessagePort_sendMessage', nativeParam);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
exports = new MessagePortManager();
diff --git a/src/messaging/messaging_api.js b/src/messaging/messaging_api.js
index fe4f4f7e..d46536e4 100755
--- a/src/messaging/messaging_api.js
+++ b/src/messaging/messaging_api.js
@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
var validator_ = xwalk.utils.validator;
var types_ = validator_.Types;
var T_ = xwalk.utils.type;
@@ -25,34 +25,33 @@ function throwException_(err) {
}
var Property = {
- W: 1 << 0, // WRITABLE
- E: 1 << 1, // ENUMERABLE
- C: 1 << 2 // CONFIGURABLE
-}
+ W: 1 << 0, // WRITABLE
+ E: 1 << 1, // ENUMERABLE
+ C: 1 << 2 // CONFIGURABLE
+};
-function addTypeToFilter_(data)
-{
+function addTypeToFilter_(data) {
var filter = {};
- for(var field in data) {
+ for (var field in data) {
filter[field] = data[field];
}
if (data instanceof tizen.AttributeFilter) {
- filter.filterType = "AttributeFilter";
+ filter.filterType = 'AttributeFilter';
//convert to string
filter.matchValue = String(filter.matchValue);
} else if (data instanceof tizen.AttributeRangeFilter) {
- filter.filterType = "AttributeRangeFilter";
+ filter.filterType = 'AttributeRangeFilter';
} else if (data instanceof tizen.CompositeFilter) {
- filter.filterType = "CompositeFilter";
+ filter.filterType = 'CompositeFilter';
// recursively convert all sub-filters
filter.filters = [];
for (var i = 0; i < data.filters.length; ++i) {
filter.filters[i] = addTypeToFilter_(data.filters[i]);
}
} else {
- filter.filterType = "Unknown";
+ filter.filterType = 'Unknown';
}
return filter;
@@ -83,24 +82,26 @@ function propertyFactory_(that, name, value, flags, options) {
if (options === null || typeof options !== 'object') {
options = {};
}
- if (!(options.get) && !(options.set)) {
+ if (!options.get && !options.set) {
options.value = value;
}
- if ((flags & Property.W) != 0) { options.writable = true; }
- if ((flags & Property.E) != 0) { options.enumerable = true; }
- if ((flags & Property.C) != 0) { options.configurable = true; }
- Object.defineProperty(
- that,
- name,
- options
- );
+ if ((flags & Property.W) != 0) {
+ options.writable = true;
+ }
+ if ((flags & Property.E) != 0) {
+ options.enumerable = true;
+ }
+ if ((flags & Property.C) != 0) {
+ options.configurable = true;
+ }
+ Object.defineProperty(that, name, options);
}
function InternalValues_(data) {
if (!(this instanceof InternalValues_)) {
return new InternalValues_(data);
}
- for(var key in data) {
+ for (var key in data) {
if (data.hasOwnProperty(key)) {
this[key] = data[key];
}
@@ -109,7 +110,7 @@ function InternalValues_(data) {
function updateInternal_(internal, data) {
var values = new InternalValues_(data);
- for(var key in data) {
+ for (var key in data) {
if (values.hasOwnProperty(key) && internal.hasOwnProperty(key)) {
internal[key] = values;
}
@@ -123,27 +124,32 @@ var MessageServiceTag = ['messaging.sms', 'messaging.mms', 'messaging.email'];
function Message(type, data) {
if (!(this instanceof Message)) {
- throw new TypeError("Constructor called like a function");
+ throw new TypeError('Constructor called like a function');
}
if (MessageServiceTag.indexOf(type) === -1) {
throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
- if ( !data || typeof data !== 'object') { // 'data' is optional
+ if (!data || typeof data !== 'object') {
+ // 'data' is optional
data = {};
}
// set initial data from internal MessageInit_ object or to default values
- var internal = data instanceof MessageInit_,
- id = internal ? data.id : null,
+ var internal = data instanceof MessageInit_,
+ id = internal ? data.id : null,
conversationId = internal ? data.conversationId : null,
- folderId = internal ? data.folderId : null,
- timestamp = internal ? data.timestamp : null,
- from = internal ? data.from : null,
- hasAttachment = internal ? data.hasAttachment : false,
- isRead = internal ? data.isRead : false,
- inResponseTo = internal ? data.inResponseTo : null;
+ folderId = internal ? data.folderId : null,
+ timestamp = internal ? data.timestamp : null,
+ from = internal ? data.from : null,
+ hasAttachment = internal ? data.hasAttachment : false,
+ isRead = internal ? data.isRead : false,
+ inResponseTo = internal ? data.inResponseTo : null;
// create MessageBody object
- var body = new MessageBody({messageId: id, plainBody: data.plainBody, htmlBody: data.htmlBody});
+ var body = new MessageBody({
+ messageId: id,
+ plainBody: data.plainBody,
+ htmlBody: data.htmlBody
+ });
// check 'to', 'cc' and 'bcc' fields
var to = data.to;
if (!(to instanceof Array)) {
@@ -179,270 +185,245 @@ function Message(type, data) {
attachments: attachments
};
// id
- Object.defineProperty(
- this,
- 'id',
- {
- get: function () {return _internal.id;},
- set: function (value) { if (value instanceof InternalValues_) _internal.id = value.id;},
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'id', {
+ get: function() {
+ return _internal.id;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.id = value.id;
+ },
+ enumerable: true
+ });
//conversationId
- Object.defineProperty(
- this,
- 'conversationId',
- {
- get: function () {return _internal.conversationId;},
- set: function (value) {
- if (value instanceof InternalValues_)
- _internal.conversationId = value.conversationId;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'conversationId', {
+ get: function() {
+ return _internal.conversationId;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_)
+ _internal.conversationId = value.conversationId;
+ },
+ enumerable: true
+ });
// folderId
- Object.defineProperty(
- this,
- 'folderId',
- {
- get: function () {return _internal.folderId;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.folderId = value.folderId;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'folderId', {
+ get: function() {
+ return _internal.folderId;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.folderId = value.folderId;
+ },
+ enumerable: true
+ });
// type
- Object.defineProperty(
- this,
- 'type',
- {
- get: function () {return _internal.type;},
- set: function (value) {return;},
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'type', {
+ get: function() {
+ return _internal.type;
+ },
+ set: function(value) {
+ return;
+ },
+ enumerable: true
+ });
// timestamp
- Object.defineProperty(
- this,
- 'timestamp',
- {
- get: function () {
- return _internal.timestamp ? new Date(_internal.timestamp * 1000) : _internal.timestamp;
- },
- set: function (value) {
- if (value instanceof InternalValues_) {
- _internal.timestamp = value.timestamp;
- }
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'timestamp', {
+ get: function() {
+ return _internal.timestamp
+ ? new Date(_internal.timestamp * 1000)
+ : _internal.timestamp;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) {
+ _internal.timestamp = value.timestamp;
+ }
+ },
+ enumerable: true
+ });
// from
- Object.defineProperty(
- this,
- 'from',
- {
- get: function () {return _internal.from;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.from = value.from;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'from', {
+ get: function() {
+ return _internal.from;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.from = value.from;
+ },
+ enumerable: true
+ });
// to
- Object.defineProperty(
- this,
- 'to',
- {
- get: function () {return _internal.to;},
- set: function (value) {
- if (value instanceof InternalValues_) value = value.to;
- if (value instanceof Array) _internal.to = value;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'to', {
+ get: function() {
+ return _internal.to;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) value = value.to;
+ if (value instanceof Array) _internal.to = value;
+ },
+ enumerable: true
+ });
// cc
- Object.defineProperty(
- this,
- 'cc',
- {
- get: function () {return _internal.cc;},
- set: function (value) {
- if (value instanceof InternalValues_) value = value.cc;
- if (value instanceof Array) _internal.cc = value;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'cc', {
+ get: function() {
+ return _internal.cc;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) value = value.cc;
+ if (value instanceof Array) _internal.cc = value;
+ },
+ enumerable: true
+ });
// bcc
- Object.defineProperty(
- this,
- 'bcc',
- {
- get: function () {return _internal.bcc;},
- set: function (value) {
- if (value instanceof InternalValues_) value = value.bcc;
- if (value instanceof Array) _internal.bcc = value;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'bcc', {
+ get: function() {
+ return _internal.bcc;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) value = value.bcc;
+ if (value instanceof Array) _internal.bcc = value;
+ },
+ enumerable: true
+ });
// body
- Object.defineProperty(
- this,
- 'body',
- {
- get: function () {return _internal.body;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.body = new MessageBody(value.body);
- if (value instanceof MessageBody) _internal.body = value;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'body', {
+ get: function() {
+ return _internal.body;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_)
+ _internal.body = new MessageBody(value.body);
+ if (value instanceof MessageBody) _internal.body = value;
+ },
+ enumerable: true
+ });
// isRead
- Object.defineProperty(
- this,
- 'isRead',
- {
- get: function () {return _internal.isRead;},
- set: function (value) {
- if (value instanceof InternalValues_) {value = value.isRead;}
- _internal.isRead = !!value;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'isRead', {
+ get: function() {
+ return _internal.isRead;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) {
+ value = value.isRead;
+ }
+ _internal.isRead = !!value;
+ },
+ enumerable: true
+ });
// hasAttachment
- Object.defineProperty(
- this,
- 'hasAttachment',
- {
- get: function () {return _internal.attachments.length > 0;},
- set: function (value) {
- if (value instanceof InternalValues_)
- _internal.hasAttachment = value.hasAttachment;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'hasAttachment', {
+ get: function() {
+ return _internal.attachments.length > 0;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_)
+ _internal.hasAttachment = value.hasAttachment;
+ },
+ enumerable: true
+ });
// isHighPriority
- Object.defineProperty(
- this,
- 'isHighPriority',
- {
- get: function () {return _internal.isHighPriority;},
- set: function (value) {
- if (value instanceof InternalValues_) value = value.isHighPriority;
- _internal.isHighPriority = !!value;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'isHighPriority', {
+ get: function() {
+ return _internal.isHighPriority;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) value = value.isHighPriority;
+ _internal.isHighPriority = !!value;
+ },
+ enumerable: true
+ });
// subject
- Object.defineProperty(
- this,
- 'subject',
- {
- get: function () {return _internal.subject;},
- set: function (value) {
- if (value instanceof InternalValues_) value = value.subject;
- _internal.subject = String(value);
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'subject', {
+ get: function() {
+ return _internal.subject;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) value = value.subject;
+ _internal.subject = String(value);
+ },
+ enumerable: true
+ });
// inResponseTo
- Object.defineProperty(
- this,
- 'inResponseTo',
- {
- get: function () {return _internal.inResponseTo;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.inResponseTo = value.inResponseTo;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'inResponseTo', {
+ get: function() {
+ return _internal.inResponseTo;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_)
+ _internal.inResponseTo = value.inResponseTo;
+ },
+ enumerable: true
+ });
// messageStatus
- Object.defineProperty(
- this,
- 'messageStatus',
- {
- get: function () {
- if (_internal.id) {
- var callArgs = {
- id: _internal.id,
- type: _internal.type
- };
- var result = native.callSync('Message_messageStatus', callArgs);
- if (native.isSuccess(result)) {
+ Object.defineProperty(this, 'messageStatus', {
+ get: function() {
+ if (_internal.id) {
+ var callArgs = {
+ id: _internal.id,
+ type: _internal.type
+ };
+ var result = native.callSync('Message_messageStatus', callArgs);
+ if (native.isSuccess(result)) {
return native.getResultObject(result);
- }
}
- return '';
- },
- set: function (value) {return;},
- enumerable: true
- }
- );
+ }
+ return '';
+ },
+ set: function(value) {
+ return;
+ },
+ enumerable: true
+ });
// attachments
- Object.defineProperty(
- this,
- 'attachments',
- {
- get: function () {return _internal.attachments;},
- set: function(value) {
- if (value instanceof InternalValues_) {
- value = value.attachments;
- for (var k = 0; k < value.length; ++k) {
- if (!(value[k] instanceof tizen.MessageAttachment)) {
- if (_internal.attachments[k]) {
- updateInternal_(_internal.attachments[k], value[k]);
- } else {
- _internal.attachments[k] = new MessageAttachment(
- new InternalValues_(value[k]));
- }
+ Object.defineProperty(this, 'attachments', {
+ get: function() {
+ return _internal.attachments;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) {
+ value = value.attachments;
+ for (var k = 0; k < value.length; ++k) {
+ if (!(value[k] instanceof tizen.MessageAttachment)) {
+ if (_internal.attachments[k]) {
+ updateInternal_(_internal.attachments[k], value[k]);
} else {
- _internal.attachments[k] = value[k];
+ _internal.attachments[k] = new MessageAttachment(
+ new InternalValues_(value[k])
+ );
}
+ } else {
+ _internal.attachments[k] = value[k];
}
- // if new array is shorter than the old one, remove excess elements
- if (value.length < _internal.length) {
- _internal.splice(value.length, _internal.length - value.length);
- }
- } else if (T_.isArray(value)) {
- for (var k = 0; k < value.length; ++k) {
- if (!(value[k] instanceof tizen.MessageAttachment)) {
- return;
- }
+ }
+ // if new array is shorter than the old one, remove excess elements
+ if (value.length < _internal.length) {
+ _internal.splice(value.length, _internal.length - value.length);
+ }
+ } else if (T_.isArray(value)) {
+ for (var k = 0; k < value.length; ++k) {
+ if (!(value[k] instanceof tizen.MessageAttachment)) {
+ return;
}
- _internal.attachments = value;
}
- },
- enumerable: true
- }
- );
-};
+ _internal.attachments = value;
+ }
+ },
+ enumerable: true
+ });
+}
function MessageInit(data) {
if (!(this instanceof MessageInit)) {
@@ -451,52 +432,57 @@ function MessageInit(data) {
if (data === null || typeof data !== 'object') {
data = {};
}
- propertyFactory_(this, 'subject' , data.subject || '' , Property.E | Property.W);
- propertyFactory_(this, 'to' , data.to || [] , Property.E | Property.W);
- propertyFactory_(this, 'cc' , data.cc || [] , Property.E | Property.W);
- propertyFactory_(this, 'bcc' , data.bcc || [] , Property.E | Property.W);
- propertyFactory_(this, 'plainBody' , data.plainBody || '' , Property.E | Property.W);
- propertyFactory_(this, 'htmlBody' , data.htmlBody || '' , Property.E | Property.W);
- propertyFactory_(this, 'isHighPriority', data.isHighPriority || false, Property.E | Property.W);
-};
+ propertyFactory_(this, 'subject', data.subject || '', Property.E | Property.W);
+ propertyFactory_(this, 'to', data.to || [], Property.E | Property.W);
+ propertyFactory_(this, 'cc', data.cc || [], Property.E | Property.W);
+ propertyFactory_(this, 'bcc', data.bcc || [], Property.E | Property.W);
+ propertyFactory_(this, 'plainBody', data.plainBody || '', Property.E | Property.W);
+ propertyFactory_(this, 'htmlBody', data.htmlBody || '', Property.E | Property.W);
+ propertyFactory_(
+ this,
+ 'isHighPriority',
+ data.isHighPriority || false,
+ Property.E | Property.W
+ );
+}
function MessageInit_(data) {
if (!(this instanceof MessageInit_)) {
return new MessageInit_(data);
}
- if ( !data || typeof data !== 'object') {
+ if (!data || typeof data !== 'object') {
data = {};
}
- this.id = data.id || null;
+ this.id = data.id || null;
this.conversationId = data.conversationId || null;
- this.folderId = data.folderId || null;
- this.timestamp = data.timestamp || null;
- this.from = data.from || '';
- this.to = data.to || [];
- this.cc = data.cc || [];
- this.bcc = data.bcc || [];
- this.isRead = data.isRead || false;
- this.hasAttachment = data.hasAttachment || null;
+ this.folderId = data.folderId || null;
+ this.timestamp = data.timestamp || null;
+ this.from = data.from || '';
+ this.to = data.to || [];
+ this.cc = data.cc || [];
+ this.bcc = data.bcc || [];
+ this.isRead = data.isRead || false;
+ this.hasAttachment = data.hasAttachment || null;
this.isHighPriority = data.isHighPriority || false;
- this.subject = data.subject || '';
- this.inResponseTo = data.inResponseTo || null;
+ this.subject = data.subject || '';
+ this.inResponseTo = data.inResponseTo || null;
this.attachments = [];
- this.plainBody = data.body ? data.body.plainBody : '';
- this.htmlBody = data.body ? data.body.htmlBody : '';
+ this.plainBody = data.body ? data.body.plainBody : '';
+ this.htmlBody = data.body ? data.body.htmlBody : '';
var self = this;
if (data.attachments && data.attachments.constructor === Array) {
data.attachments.forEach(function(el) {
- if (!el) return;
+ if (!el) return;
- if (el.constructor === MessageAttachment) {
- self.attachments.push(el);
- } else {
- self.attachments.push(new MessageAttachment(new InternalValues_(el)));
- }
+ if (el.constructor === MessageAttachment) {
+ self.attachments.push(el);
+ } else {
+ self.attachments.push(new MessageAttachment(new InternalValues_(el)));
+ }
});
}
-};
+}
function MessageBody(data) {
if (!this instanceof MessageBody) {
@@ -515,82 +501,72 @@ function MessageBody(data) {
};
// messageId
- Object.defineProperty(
- this,
- 'messageId',
- {
- get: function () {return _internal.messageId;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.messageId = value.messageId;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'messageId', {
+ get: function() {
+ return _internal.messageId;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.messageId = value.messageId;
+ },
+ enumerable: true
+ });
// loaded
- Object.defineProperty(
- this,
- 'loaded',
- {
- get: function () {return _internal.loaded;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.loaded = value.loaded;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'loaded', {
+ get: function() {
+ return _internal.loaded;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.loaded = value.loaded;
+ },
+ enumerable: true
+ });
// plainBody
- Object.defineProperty(
- this,
- 'plainBody',
- {
- get: function () {return _internal.plainBody;},
- set: function (value) {
- if (value instanceof InternalValues_) {
- _internal.plainBody = String(value.plainBody);
- } else {
- _internal.plainBody = String(value);
- }
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'plainBody', {
+ get: function() {
+ return _internal.plainBody;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) {
+ _internal.plainBody = String(value.plainBody);
+ } else {
+ _internal.plainBody = String(value);
+ }
+ },
+ enumerable: true
+ });
// htmlBody
- Object.defineProperty(
- this,
- 'htmlBody',
- {
- get: function () {return _internal.htmlBody;},
- set: function (value) {
- if (value instanceof InternalValues_) {
- _internal.htmlBody = String(value.htmlBody);
- } else {
- _internal.htmlBody = String(value);
- }
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'htmlBody', {
+ get: function() {
+ return _internal.htmlBody;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) {
+ _internal.htmlBody = String(value.htmlBody);
+ } else {
+ _internal.htmlBody = String(value);
+ }
+ },
+ enumerable: true
+ });
// inlineAttachments
- Object.defineProperty(
- this,
- 'inlineAttachments',
- {
- get: function () {return _internal.inlineAttachments;},
- set: function (value) {
- if (value instanceof InternalValues_) {
- _internal.inlineAttachments = value.inlineAttachments;
- } else if (T_.isArray(value)) {
- _internal.inlineAttachments = value;
- }
- },
- enumerable: true
- }
- );
-};
+ Object.defineProperty(this, 'inlineAttachments', {
+ get: function() {
+ return _internal.inlineAttachments;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) {
+ _internal.inlineAttachments = value.inlineAttachments;
+ } else if (T_.isArray(value)) {
+ _internal.inlineAttachments = value;
+ }
+ },
+ enumerable: true
+ });
+}
var messageAttachmentsLoaded = {};
@@ -604,115 +580,115 @@ function MessageAttachment(first, second) {
var _internal = {
messageId: internalConstructor ? first.messageId : null,
id: internalConstructor ? first.id : null,
- mimeType: internalConstructor ? first.mimeType : (undefined == second ? null : second),
- filePath: internalConstructor ? first.filePath : first,
+ mimeType: internalConstructor
+ ? first.mimeType
+ : undefined == second
+ ? null
+ : second,
+ filePath: internalConstructor ? first.filePath : first
};
// messageId
- Object.defineProperty(
- this,
- 'messageId',
- {
- get: function () {return _internal.messageId;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.messageId = value.messageId;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'messageId', {
+ get: function() {
+ return _internal.messageId;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.messageId = value.messageId;
+ },
+ enumerable: true
+ });
// id
- Object.defineProperty(
- this,
- 'id',
- {
- get: function () {return _internal.id;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.id = value.id;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'id', {
+ get: function() {
+ return _internal.id;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.id = value.id;
+ },
+ enumerable: true
+ });
// mimeType
- Object.defineProperty(
- this,
- 'mimeType',
- {
- get: function () {return _internal.mimeType;},
- set: function (value) {
- if (value instanceof InternalValues_) _internal.mimeType = value.mimeType;
- },
- enumerable: true
- }
- );
+ Object.defineProperty(this, 'mimeType', {
+ get: function() {
+ return _internal.mimeType;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.mimeType = value.mimeType;
+ },
+ enumerable: true
+ });
// filePath
- Object.defineProperty(
- this,
- 'filePath',
- {
- get: function () {
- if (_internal.id && !messageAttachmentsLoaded[_internal.id]) {
- return null;
- }
+ Object.defineProperty(this, 'filePath', {
+ get: function() {
+ if (_internal.id && !messageAttachmentsLoaded[_internal.id]) {
+ return null;
+ }
- return _internal.filePath;
- },
- set: function (value) {
- if (value instanceof InternalValues_) _internal.filePath = value.filePath;
- },
- enumerable: true
- }
- );
-};
+ return _internal.filePath;
+ },
+ set: function(value) {
+ if (value instanceof InternalValues_) _internal.filePath = value.filePath;
+ },
+ enumerable: true
+ });
+}
-function Messaging() {};
+function Messaging() {}
/**
* Gets the messaging service of a given type for a given account.
* @param {!MessageServiceTag} messageServiceType Type of the services to be retrieved.
- * @param {!MessageServiceArraySuccessCallback} successCallback Callback function that is called
- * when the services are successfully retrieved.
- * @param {ErrorCallback} errorCallback Callback function that is called when an error occurs.
+ * @param {!MessageServiceArraySuccessCallback} successCallback Callback function that
+ * is called when the services are successfully retrieved.
+ * @param {ErrorCallback} errorCallback Callback function that is called when
+ * an error occurs.
*/
-Messaging.prototype.getMessageServices = function () {
+Messaging.prototype.getMessageServices = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'messageServiceType', type: types_.ENUM, values: MessageServiceTag},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'messageServiceType', type: types_.ENUM, values: MessageServiceTag },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
- var callArgs = {messageServiceType: args.messageServiceType};
+ var callArgs = { messageServiceType: args.messageServiceType };
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var servicesArr = [];
- data.forEach(function(e){
- servicesArr.push(new MessageService(e));
- });
- args.successCallback(servicesArr);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var servicesArr = [];
+ data.forEach(function(e) {
+ servicesArr.push(new MessageService(e));
+ });
+ args.successCallback(servicesArr);
+ }
};
var result = native.call('Messaging_getMessageServices', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
-}
+};
-function MessageStorage(){};
+function MessageStorage() {}
function MessageService(data) {
propertyFactory_(this, 'id', data.id, Property.E);
propertyFactory_(this, 'type', data.type, Property.E);
propertyFactory_(this, 'name', data.name, Property.E);
propertyFactory_(this, 'messageStorage', new MessageStorage(this), Property.E);
-};
+}
-MessageService.prototype.sendMessage = function () {
+MessageService.prototype.sendMessage = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'simIndex', type: types_.LONG, optional: true, nullable: true}
+ { name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'simIndex', type: types_.LONG, optional: true, nullable: true }
]);
if (args.message.type != this.type) {
@@ -727,33 +703,33 @@ MessageService.prototype.sendMessage = function () {
serviceId: self.id
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var message = data.message;
- if (message) {
- var body = message.body;
- if (body) {
- updateInternal_(args.message.body, body)
- delete message.body;
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var message = data.message;
+ if (message) {
+ var body = message.body;
+ if (body) {
+ updateInternal_(args.message.body, body);
+ delete message.body;
+ }
+ updateInternal_(args.message, message);
}
- updateInternal_(args.message, message);
+ native.callIfPossible(args.successCallback, data.recipients);
}
- native.callIfPossible(args.successCallback, data.recipients);
- }
};
var result = native.call('MessageService_sendMessage', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-MessageService.prototype.loadMessageBody = function () {
+MessageService.prototype.loadMessageBody = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
if (args.message.type != this.type) {
@@ -768,31 +744,30 @@ MessageService.prototype.loadMessageBody = function () {
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var body = data.messageBody;
- if (body) {
- updateInternal_(args.message.body, body)
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var body = data.messageBody;
+ if (body) {
+ updateInternal_(args.message.body, body);
+ }
- args.successCallback(args.message);
- }
+ args.successCallback(args.message);
+ }
};
var result = native.call('MessageService_loadMessageBody', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
-
};
-MessageService.prototype.loadMessageAttachment = function () {
+MessageService.prototype.loadMessageAttachment = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'attachment', type: types_.PLATFORM_OBJECT, values: MessageAttachment},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'attachment', type: types_.PLATFORM_OBJECT, values: MessageAttachment },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var self = this;
@@ -808,32 +783,36 @@ MessageService.prototype.loadMessageAttachment = function () {
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var messageAttachment = data.messageAttachment;
- if (messageAttachment) {
- updateInternal_(args.attachment, messageAttachment);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var messageAttachment = data.messageAttachment;
+ if (messageAttachment) {
+ updateInternal_(args.attachment, messageAttachment);
+ }
- args.successCallback(args.attachment);
- }
+ args.successCallback(args.attachment);
+ }
};
var result = native.call('MessageService_loadMessageAttachment', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
-
};
-MessageService.prototype.sync = function () {
+MessageService.prototype.sync = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true}
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true }
]);
var self = this;
@@ -844,28 +823,33 @@ MessageService.prototype.sync = function () {
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- native.callIfPossible(args.successCallback);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
};
var result = native.call('MessageService_sync', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
return native.getResultObject(result);
};
-MessageService.prototype.syncFolder = function () {
+MessageService.prototype.syncFolder = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'folder', type: types_.PLATFORM_OBJECT, values: MessageFolder},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true}
+ { name: 'folder', type: types_.PLATFORM_OBJECT, values: MessageFolder },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ { name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true }
]);
var self = this;
@@ -877,27 +861,24 @@ MessageService.prototype.syncFolder = function () {
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- native.callIfPossible(args.successCallback);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
};
var result = native.call('MessageService_syncFolder', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
return native.getResultObject(result);
-
};
-MessageService.prototype.stopSync = function () {
- var args = validator_.validateArgs(arguments, [
- {name: 'opId', type: types_.LONG}
- ]);
+MessageService.prototype.stopSync = function() {
+ var args = validator_.validateArgs(arguments, [{ name: 'opId', type: types_.LONG }]);
var self = this;
var callArgs = {
@@ -912,13 +893,18 @@ MessageService.prototype.stopSync = function () {
function MessageStorage(service) {
propertyFactory_(this, 'service', service);
-};
+}
-MessageStorage.prototype.addDraftMessage = function () {
+MessageStorage.prototype.addDraftMessage = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'message', type: types_.PLATFORM_OBJECT, values: tizen.Message },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
if (args.message.type != this.service.type) {
@@ -932,47 +918,56 @@ MessageStorage.prototype.addDraftMessage = function () {
serviceId: self.service.id
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var message = data.message;
- if (message) {
- var body = message.body;
- if (body) {
- updateInternal_(args.message.body, body)
- delete message.body;
- }
- var attachments = message.attachments;
- if (attachments) {
- for (var i = 0; i < attachments.length; i++) {
- messageAttachmentsLoaded[attachments[i].id] = true;
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var message = data.message;
+ if (message) {
+ var body = message.body;
+ if (body) {
+ updateInternal_(args.message.body, body);
+ delete message.body;
+ }
+ var attachments = message.attachments;
+ if (attachments) {
+ for (var i = 0; i < attachments.length; i++) {
+ messageAttachmentsLoaded[attachments[i].id] = true;
+ }
}
+ updateInternal_(args.message, message);
}
- updateInternal_(args.message, message);
+ native.callIfPossible(args.successCallback, data.recipients);
}
- native.callIfPossible(args.successCallback, data.recipients);
- }
};
var result = native.call('MessageStorage_addDraftMessage', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-MessageStorage.prototype.findMessages = function () {
+MessageStorage.prototype.findMessages = function() {
var args = validator_.validateArgs(arguments, [
{
name: 'filter',
type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter]
- },
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'sort', type: types_.PLATFORM_OBJECT, values: tizen.SortMode, optional: true,
- nullable: true},
- {name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true},
- {name: 'offset', type: types_.UNSIGNED_LONG, optional: true, nullable: true}
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ]
+ },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ {
+ name: 'sort',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.SortMode,
+ optional: true,
+ nullable: true
+ },
+ { name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true },
+ { name: 'offset', type: types_.UNSIGNED_LONG, optional: true, nullable: true }
]);
var self = this;
@@ -986,28 +981,33 @@ MessageStorage.prototype.findMessages = function () {
type: self.service.type
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var messages = [];
- data.forEach(function (el) {
- messages.push(new tizen.Message(el.type, new MessageInit_(el)));
- });
- native.callIfPossible(args.successCallback, messages);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var messages = [];
+ data.forEach(function(el) {
+ messages.push(new tizen.Message(el.type, new MessageInit_(el)));
+ });
+ native.callIfPossible(args.successCallback, messages);
+ }
};
var result = native.call('MessageStorage_findMessages', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-MessageStorage.prototype.removeMessages = function () {
+MessageStorage.prototype.removeMessages = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'messages', type: types_.ARRAY, values: Message},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'messages', type: types_.ARRAY, values: Message },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var self = this;
@@ -1024,23 +1024,28 @@ MessageStorage.prototype.removeMessages = function () {
type: self.service.type
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- native.callIfPossible(args.successCallback);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
};
var result = native.call('MessageStorage_removeMessages', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-MessageStorage.prototype.updateMessages = function () {
+MessageStorage.prototype.updateMessages = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'messages', type: types_.ARRAY, values: Message},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'messages', type: types_.ARRAY, values: Message },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var self = this;
@@ -1056,55 +1061,64 @@ MessageStorage.prototype.updateMessages = function () {
serviceId: self.service.id
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var originals = {},
- i = args.messages.length,
- m;
- while (i--) {
- m = args.messages[i];
- if (m.id) {
- originals[m.id] = m;
- }
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var originals = {},
+ i = args.messages.length,
+ m;
+ while (i--) {
+ m = args.messages[i];
+ if (m.id) {
+ originals[m.id] = m;
+ }
+ }
- i = data.length;
- while (i--) {
- m = data[i];
- if (originals[m.oldId]) {
- var body = m.body;
- if (body) {
- updateInternal_(originals[m.oldId].body, body)
- delete m.body;
+ i = data.length;
+ while (i--) {
+ m = data[i];
+ if (originals[m.oldId]) {
+ var body = m.body;
+ if (body) {
+ updateInternal_(originals[m.oldId].body, body);
+ delete m.body;
+ }
+ updateInternal_(originals[m.oldId], m);
+ }
}
- updateInternal_(originals[m.oldId], m);
- }
- }
- native.callIfPossible(args.successCallback);
- }
+ native.callIfPossible(args.successCallback);
+ }
};
var result = native.call('MessageStorage_updateMessages', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-MessageStorage.prototype.findConversations = function () {
+MessageStorage.prototype.findConversations = function() {
var args = validator_.validateArgs(arguments, [
{
name: 'filter',
type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter]
- },
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'sort', type: types_.PLATFORM_OBJECT, values: tizen.SortMode, optional: true,
- nullable: true},
- {name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true},
- {name: 'offset', type: types_.UNSIGNED_LONG, optional: true, nullable: true}
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ]
+ },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true },
+ {
+ name: 'sort',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.SortMode,
+ optional: true,
+ nullable: true
+ },
+ { name: 'limit', type: types_.UNSIGNED_LONG, optional: true, nullable: true },
+ { name: 'offset', type: types_.UNSIGNED_LONG, optional: true, nullable: true }
]);
var self = this;
@@ -1117,31 +1131,36 @@ MessageStorage.prototype.findConversations = function () {
serviceId: self.service.id
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var conversations = [];
- data.forEach(function (el) {
- conversations.push(new MessageConversation(el));
- });
- args.successCallback(conversations);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var conversations = [];
+ data.forEach(function(el) {
+ conversations.push(new MessageConversation(el));
+ });
+ args.successCallback(conversations);
+ }
};
var result = native.call('MessageStorage_findConversations', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-MessageStorage.prototype.removeConversations = function () {
+MessageStorage.prototype.removeConversations = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'conversations', type: types_.ARRAY},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'conversations', type: types_.ARRAY },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
- args.conversations.forEach(function (el) {
+ args.conversations.forEach(function(el) {
if (!el || el.constructor !== MessageConversation) {
throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
@@ -1155,27 +1174,31 @@ MessageStorage.prototype.removeConversations = function () {
type: self.service.type
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- native.callIfPossible(args.successCallback);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
};
var result = native.call('MessageStorage_removeConversations', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
-MessageStorage.prototype.findFolders = function () {
+MessageStorage.prototype.findFolders = function() {
var args = validator_.validateArgs(arguments, [
{
name: 'filter',
type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter]
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ]
},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var self = this;
@@ -1188,75 +1211,88 @@ MessageStorage.prototype.findFolders = function () {
serviceId: self.service.id
};
var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var data = native.getResultObject(result);
- var folders = [];
- data.forEach(function (el) {
- folders.push(new MessageFolder(el));
- });
- args.successCallback(folders);
- }
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var data = native.getResultObject(result);
+ var folders = [];
+ data.forEach(function(el) {
+ folders.push(new MessageFolder(el));
+ });
+ args.successCallback(folders);
+ }
};
var result = native.call('MessageStorage_findFolders', callArgs, callback);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
}
};
function pushMessage(messages, el) {
- messages.push(new tizen.Message(el.type, new MessageInit_(el)));
-};
+ messages.push(new tizen.Message(el.type, new MessageInit_(el)));
+}
function pushConversation(conversations, el) {
- conversations.push(new MessageConversation(el));
-};
+ conversations.push(new MessageConversation(el));
+}
function pushFolder(folders, el) {
- folders.push(new MessageFolder(el));
-};
+ folders.push(new MessageFolder(el));
+}
function getListenerFunction(listenerMap, pushMethod) {
- return function(msg) {
- var action = msg.action;
- var data = native.getResultObject(msg);
- var messages = [];
- data.forEach(function (el) {
- pushMethod(messages, el);
- });
+ return function(msg) {
+ var action = msg.action;
+ var data = native.getResultObject(msg);
+ var messages = [];
+ data.forEach(function(el) {
+ pushMethod(messages, el);
+ });
- for (var key in listenerMap) {
- if (listenerMap.hasOwnProperty(key)) {
- native.callIfPossible(listenerMap[key][action], messages);
- }
- }
- }
-};
+ for (var key in listenerMap) {
+ if (listenerMap.hasOwnProperty(key)) {
+ native.callIfPossible(listenerMap[key][action], messages);
+ }
+ }
+ };
+}
var MESSAGES_CHANGE_LISTENER = 'MessagesChangeListener';
var MessagesChangeListeners = {};
-native.addListener(MESSAGES_CHANGE_LISTENER,
- getListenerFunction(MessagesChangeListeners, pushMessage));
+native.addListener(
+ MESSAGES_CHANGE_LISTENER,
+ getListenerFunction(MessagesChangeListeners, pushMessage)
+);
var CONVERSATIONS_CHANGE_LISTENER = 'ConversationsChangeListener';
var ConversationsChangeListeners = {};
-native.addListener(CONVERSATIONS_CHANGE_LISTENER,
- getListenerFunction(ConversationsChangeListeners, pushConversation));
+native.addListener(
+ CONVERSATIONS_CHANGE_LISTENER,
+ getListenerFunction(ConversationsChangeListeners, pushConversation)
+);
var FOLDERS_CHANGE_LISTENER = 'FoldersChangeListener';
var FoldersChangeListeners = {};
-native.addListener(FOLDERS_CHANGE_LISTENER,
- getListenerFunction(FoldersChangeListeners, pushFolder));
+native.addListener(
+ FOLDERS_CHANGE_LISTENER,
+ getListenerFunction(FoldersChangeListeners, pushFolder)
+);
-MessageStorage.prototype.addMessagesChangeListener = function () {
- var args = validator_.validateArgs(arguments, [
- {name: 'messagesChangeCallback', type: types_.LISTENER,
- values: ['messagesadded', 'messagesupdated', 'messagesremoved']},
+MessageStorage.prototype.addMessagesChangeListener = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'messagesChangeCallback',
+ type: types_.LISTENER,
+ values: ['messagesadded', 'messagesupdated', 'messagesremoved']
+ },
{
name: 'filter',
type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter],
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ],
optional: true,
nullable: true
}
@@ -1270,22 +1306,29 @@ MessageStorage.prototype.addMessagesChangeListener = function () {
};
var result = native.callSync('MessageStorage_addMessagesChangeListener', callArgs);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
} else {
- var opId = native.getResultObject(result);
- MessagesChangeListeners[opId] = args.messagesChangeCallback;
- return opId;
+ var opId = native.getResultObject(result);
+ MessagesChangeListeners[opId] = args.messagesChangeCallback;
+ return opId;
}
};
-MessageStorage.prototype.addConversationsChangeListener = function () {
+MessageStorage.prototype.addConversationsChangeListener = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'conversationsChangeCallback', type: types_.LISTENER,
- values: ['conversationsadded', 'conversationsupdated', 'conversationsremoved']},
+ {
+ name: 'conversationsChangeCallback',
+ type: types_.LISTENER,
+ values: ['conversationsadded', 'conversationsupdated', 'conversationsremoved']
+ },
{
name: 'filter',
type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter],
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ],
optional: true,
nullable: true
}
@@ -1297,24 +1340,34 @@ MessageStorage.prototype.addConversationsChangeListener = function () {
filter: args.filter ? addTypeToFilter_(args.filter) : null,
serviceId: self.service.id
};
- var result = native.callSync('MessageStorage_addConversationsChangeListener', callArgs);
+ var result = native.callSync(
+ 'MessageStorage_addConversationsChangeListener',
+ callArgs
+ );
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
} else {
- var opId = native.getResultObject(result);
- ConversationsChangeListeners[opId] = args.conversationsChangeCallback;
- return opId;
+ var opId = native.getResultObject(result);
+ ConversationsChangeListeners[opId] = args.conversationsChangeCallback;
+ return opId;
}
};
-MessageStorage.prototype.addFoldersChangeListener = function () {
+MessageStorage.prototype.addFoldersChangeListener = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'foldersChangeCallback', type: types_.LISTENER,
- values: ['foldersadded', 'foldersupdated', 'foldersremoved']},
+ {
+ name: 'foldersChangeCallback',
+ type: types_.LISTENER,
+ values: ['foldersadded', 'foldersupdated', 'foldersremoved']
+ },
{
name: 'filter',
type: types_.PLATFORM_OBJECT,
- values: [tizen.AttributeFilter, tizen.AttributeRangeFilter, tizen.CompositeFilter],
+ values: [
+ tizen.AttributeFilter,
+ tizen.AttributeRangeFilter,
+ tizen.CompositeFilter
+ ],
optional: true,
nullable: true
}
@@ -1328,17 +1381,17 @@ MessageStorage.prototype.addFoldersChangeListener = function () {
};
var result = native.callSync('MessageStorage_addFoldersChangeListener', callArgs);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
} else {
- var opId = native.getResultObject(result);
- FoldersChangeListeners[opId] = args.foldersChangeCallback;
- return opId;
+ var opId = native.getResultObject(result);
+ FoldersChangeListeners[opId] = args.foldersChangeCallback;
+ return opId;
}
};
-MessageStorage.prototype.removeChangeListener = function () {
+MessageStorage.prototype.removeChangeListener = function() {
var args = validator_.validateArgs(arguments, [
- {name: 'watchId', type: types_.LONG}
+ { name: 'watchId', type: types_.LONG }
]);
var self = this;
@@ -1349,120 +1402,113 @@ MessageStorage.prototype.removeChangeListener = function () {
};
var result = native.callSync('MessageStorage_removeChangeListener', callArgs);
if (native.isFailure(result)) {
- throw native.getErrorObject(result);
+ throw native.getErrorObject(result);
} else {
- if (MessagesChangeListeners.hasOwnProperty(args.watchId)) {
- delete MessagesChangeListeners[args.watchId];
- } else if (ConversationsChangeListeners.hasOwnProperty(args.watchId)) {
- delete ConversationsChangeListeners[args.watchId];
- } else if (FoldersChangeListeners.hasOwnProperty(args.watchId)) {
- delete FoldersChangeListeners[args.watchId];
- }
+ if (MessagesChangeListeners.hasOwnProperty(args.watchId)) {
+ delete MessagesChangeListeners[args.watchId];
+ } else if (ConversationsChangeListeners.hasOwnProperty(args.watchId)) {
+ delete ConversationsChangeListeners[args.watchId];
+ } else if (FoldersChangeListeners.hasOwnProperty(args.watchId)) {
+ delete FoldersChangeListeners[args.watchId];
+ }
}
};
function MessageConversation(data) {
- propertyFactory_(this, 'id' , data.id || null , Property.E);
- propertyFactory_(this, 'type' , data.type || '' , Property.E);
- propertyFactory_(this, 'timestamp' , data.timestamp ? new Date(data.timestamp * 1000) : null , Property.E);
- propertyFactory_(this, 'messageCount' , data.messageCount || 0 , Property.E);
- propertyFactory_(this, 'unreadMessages', data.unreadMessages || 0 , Property.E);
- propertyFactory_(this, 'preview' , data.preview || '' , Property.E);
- propertyFactory_(this, 'subject' , data.subject || '' , Property.E);
- propertyFactory_(this, 'isRead' , data.isRead || false, Property.E);
- propertyFactory_(this, 'from' , data.from || null , Property.E);
- propertyFactory_(this, 'to' , data.to || [] , Property.E);
- propertyFactory_(this, 'cc' , data.cc || [] , Property.E);
- propertyFactory_(this, 'bcc' , data.bcc || [] , Property.E);
- propertyFactory_(this, 'lastMessageId' , data.lastMessageId || null , Property.E);
-};
+ propertyFactory_(this, 'id', data.id || null, Property.E);
+ propertyFactory_(this, 'type', data.type || '', Property.E);
+ propertyFactory_(
+ this,
+ 'timestamp',
+ data.timestamp ? new Date(data.timestamp * 1000) : null,
+ Property.E
+ );
+ propertyFactory_(this, 'messageCount', data.messageCount || 0, Property.E);
+ propertyFactory_(this, 'unreadMessages', data.unreadMessages || 0, Property.E);
+ propertyFactory_(this, 'preview', data.preview || '', Property.E);
+ propertyFactory_(this, 'subject', data.subject || '', Property.E);
+ propertyFactory_(this, 'isRead', data.isRead || false, Property.E);
+ propertyFactory_(this, 'from', data.from || null, Property.E);
+ propertyFactory_(this, 'to', data.to || [], Property.E);
+ propertyFactory_(this, 'cc', data.cc || [], Property.E);
+ propertyFactory_(this, 'bcc', data.bcc || [], Property.E);
+ propertyFactory_(this, 'lastMessageId', data.lastMessageId || null, Property.E);
+}
function MessageFolder(data) {
var _internal = {
- id: data.id || null,
- parentId: data.parentId || null,
- serviceId: data.serviceId || '',
- contentType: data.contentType || '',
- name: data.name || '',
- path: data.path || '',
- type: data.type || '',
- synchronizable: data.synchronizable || false
- };
-
- Object.defineProperty(
- this,
- 'id',
- {
- get: function () {return _internal.id;},
- enumerable: true
- }
- );
-
- Object.defineProperty(
- this,
- 'parentId',
- {
- get: function () {return _internal.parentId;},
- enumerable: true
- }
- );
-
- Object.defineProperty(
- this,
- 'serviceId',
- {
- get: function () {return _internal.serviceId;},
- enumerable: true
- }
- );
-
- Object.defineProperty(
- this,
- 'contentType',
- {
- get: function () {return _internal.contentType;},
- enumerable: true
- }
- );
-
- Object.defineProperty(
- this,
- 'name',
- {
- get: function () {return _internal.name;},
- set: function (value) { if (value) _internal.name = value;},
- enumerable: true
- }
- );
-
- Object.defineProperty(
- this,
- 'path',
- {
- get: function () {return _internal.path;},
- enumerable: true
- }
- );
-
- Object.defineProperty(
- this,
- 'type',
- {
- get: function () {return _internal.type;},
- enumerable: true
- }
- );
-
- Object.defineProperty(
- this,
- 'synchronizable',
- {
- get: function () {return _internal.synchronizable;},
- set: function (value) { _internal.synchronizable = Boolean(value);},
- enumerable: true
- }
- );
-};
+ id: data.id || null,
+ parentId: data.parentId || null,
+ serviceId: data.serviceId || '',
+ contentType: data.contentType || '',
+ name: data.name || '',
+ path: data.path || '',
+ type: data.type || '',
+ synchronizable: data.synchronizable || false
+ };
+
+ Object.defineProperty(this, 'id', {
+ get: function() {
+ return _internal.id;
+ },
+ enumerable: true
+ });
+
+ Object.defineProperty(this, 'parentId', {
+ get: function() {
+ return _internal.parentId;
+ },
+ enumerable: true
+ });
+
+ Object.defineProperty(this, 'serviceId', {
+ get: function() {
+ return _internal.serviceId;
+ },
+ enumerable: true
+ });
+
+ Object.defineProperty(this, 'contentType', {
+ get: function() {
+ return _internal.contentType;
+ },
+ enumerable: true
+ });
+
+ Object.defineProperty(this, 'name', {
+ get: function() {
+ return _internal.name;
+ },
+ set: function(value) {
+ if (value) _internal.name = value;
+ },
+ enumerable: true
+ });
+
+ Object.defineProperty(this, 'path', {
+ get: function() {
+ return _internal.path;
+ },
+ enumerable: true
+ });
+
+ Object.defineProperty(this, 'type', {
+ get: function() {
+ return _internal.type;
+ },
+ enumerable: true
+ });
+
+ Object.defineProperty(this, 'synchronizable', {
+ get: function() {
+ return _internal.synchronizable;
+ },
+ set: function(value) {
+ _internal.synchronizable = Boolean(value);
+ },
+ enumerable: true
+ });
+}
tizen.Message = Message;
diff --git a/src/networkbearerselection/networkbearerselection_api.js b/src/networkbearerselection/networkbearerselection_api.js
index f0c3bc1d..6c4d1824 100644
--- a/src/networkbearerselection/networkbearerselection_api.js
+++ b/src/networkbearerselection/networkbearerselection_api.js
@@ -22,99 +22,113 @@ var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
var NetworkType = {
- CELLULAR: 'CELLULAR',
- UNKNOWN: 'UNKNOWN'
+ CELLULAR: 'CELLULAR',
+ UNKNOWN: 'UNKNOWN'
};
var callbackId = 0;
var callbacks = {};
function nextCallbackId() {
- return callbackId++;
+ return callbackId++;
}
function _networkBearerSelectionCallback(result) {
- var id, callback;
-
- for (id in callbacks) {
- if (callbacks.hasOwnProperty(result.id) && result.id == id) {
- callback = callbacks[id];
- if (result.status === 'success') {
- native_.callIfPossible(callback.onsuccess);
- }
-
- if (result.status === 'disconnected') {
- native_.callIfPossible(callback.ondisconnected);
- }
-
- if (result.status === 'error') {
- native_.callIfPossible(callback.onerror, native_.getErrorObject(result));
- native_.removeListener('NetworkBearerSelectionCallback_' + id);
- delete callbacks[id];
- }
- break;
+ var id, callback;
+
+ for (id in callbacks) {
+ if (callbacks.hasOwnProperty(result.id) && result.id == id) {
+ callback = callbacks[id];
+ if (result.status === 'success') {
+ native_.callIfPossible(callback.onsuccess);
+ }
+
+ if (result.status === 'disconnected') {
+ native_.callIfPossible(callback.ondisconnected);
+ }
+
+ if (result.status === 'error') {
+ native_.callIfPossible(callback.onerror, native_.getErrorObject(result));
+ native_.removeListener('NetworkBearerSelectionCallback_' + id);
+ delete callbacks[id];
+ }
+ break;
+ }
}
- }
}
function NetworkBearerSelection() {}
NetworkBearerSelection.prototype.requestRouteToHost = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'networkType', type: types_.ENUM, values: Object.keys(NetworkType)},
- {name: 'domainName', type: types_.STRING},
- {name: 'successCallback', type: types_.LISTENER, values: ['onsuccess', 'ondisconnected']},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var id = nextCallbackId();
-
- var nativeParam = {
- networkType: args.networkType,
- domainName: args.domainName,
- id: id
- };
-
- callbacks[id] = {
- onsuccess: args.successCallback.onsuccess,
- ondisconnected: args.successCallback.ondisconnected,
- onerror: args.errorCallback
- };
-
- native_.addListener('NetworkBearerSelectionCallback_' + id, _networkBearerSelectionCallback);
- var result = native_.callSync('NetworkBearerSelection_requestRouteToHost', nativeParam);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
+ var args = validator_.validateArgs(arguments, [
+ { name: 'networkType', type: types_.ENUM, values: Object.keys(NetworkType) },
+ { name: 'domainName', type: types_.STRING },
+ {
+ name: 'successCallback',
+ type: types_.LISTENER,
+ values: ['onsuccess', 'ondisconnected']
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var id = nextCallbackId();
+
+ var nativeParam = {
+ networkType: args.networkType,
+ domainName: args.domainName,
+ id: id
+ };
+
+ callbacks[id] = {
+ onsuccess: args.successCallback.onsuccess,
+ ondisconnected: args.successCallback.ondisconnected,
+ onerror: args.errorCallback
+ };
+
+ native_.addListener(
+ 'NetworkBearerSelectionCallback_' + id,
+ _networkBearerSelectionCallback
+ );
+ var result = native_.callSync(
+ 'NetworkBearerSelection_requestRouteToHost',
+ nativeParam
+ );
-NetworkBearerSelection.prototype.releaseRouteToHost = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'networkType', type: types_.ENUM, values: Object.keys(NetworkType)},
- {name: 'domainName', type: types_.STRING},
- {name: 'successCallback', type: types_.FUNCTION},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
-
- var nativeParam = {
- domainName: args.domainName
- };
-
- var callback = function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
+ throw native_.getErrorObject(result);
}
+};
- args.successCallback();
- };
-
- var result = native_.call('NetworkBearerSelection_releaseRouteToHost', nativeParam, callback);
+NetworkBearerSelection.prototype.releaseRouteToHost = function() {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'networkType', type: types_.ENUM, values: Object.keys(NetworkType) },
+ { name: 'domainName', type: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {
+ domainName: args.domainName
+ };
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+
+ args.successCallback();
+ };
+
+ var result = native_.call(
+ 'NetworkBearerSelection_releaseRouteToHost',
+ nativeParam,
+ callback
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
exports = new NetworkBearerSelection();
diff --git a/src/nfc/nfc_api.js b/src/nfc/nfc_api.js
index dc1e25a7..851ee585 100644
--- a/src/nfc/nfc_api.js
+++ b/src/nfc/nfc_api.js
@@ -22,111 +22,110 @@ var type_ = privUtils_.type;
var converter_ = privUtils_.converter;
var native_ = new xwalk.utils.NativeManager(extension);
-
var NDEFRecordTextEncoding = {
- UTF8: 'UTF8',
- UTF16: 'UTF16'
+ UTF8: 'UTF8',
+ UTF16: 'UTF16'
};
var NFCTagType = {
- GENERIC_TARGET: 'GENERIC_TARGET',
- ISO14443_A: 'ISO14443_A',
- ISO14443_4A: 'ISO14443_4A',
- ISO14443_3A: 'ISO14443_3A',
- MIFARE_MINI: 'MIFARE_MINI',
- MIFARE_1K: 'MIFARE_1K',
- MIFARE_4K: 'MIFARE_4K',
- MIFARE_ULTRA: 'MIFARE_ULTRA',
- MIFARE_DESFIRE: 'MIFARE_DESFIRE',
- ISO14443_B: 'ISO14443_B',
- ISO14443_4B: 'ISO14443_4B',
- ISO14443_BPRIME: 'ISO14443_BPRIME',
- FELICA: 'FELICA',
- JEWEL: 'JEWEL',
- ISO15693: 'ISO15693',
- UNKNOWN_TARGET: 'UNKNOWN_TARGET'
+ GENERIC_TARGET: 'GENERIC_TARGET',
+ ISO14443_A: 'ISO14443_A',
+ ISO14443_4A: 'ISO14443_4A',
+ ISO14443_3A: 'ISO14443_3A',
+ MIFARE_MINI: 'MIFARE_MINI',
+ MIFARE_1K: 'MIFARE_1K',
+ MIFARE_4K: 'MIFARE_4K',
+ MIFARE_ULTRA: 'MIFARE_ULTRA',
+ MIFARE_DESFIRE: 'MIFARE_DESFIRE',
+ ISO14443_B: 'ISO14443_B',
+ ISO14443_4B: 'ISO14443_4B',
+ ISO14443_BPRIME: 'ISO14443_BPRIME',
+ FELICA: 'FELICA',
+ JEWEL: 'JEWEL',
+ ISO15693: 'ISO15693',
+ UNKNOWN_TARGET: 'UNKNOWN_TARGET'
};
var CardEmulationMode = {
- ALWAYS_ON: 'ALWAYS_ON',
- OFF: 'OFF'
+ ALWAYS_ON: 'ALWAYS_ON',
+ OFF: 'OFF'
};
var SecureElementType = {
- ESE: 'ESE',
- UICC: 'UICC',
- HCE: 'HCE'
+ ESE: 'ESE',
+ UICC: 'UICC',
+ HCE: 'HCE'
};
var CardEmulationCategoryType = {
- PAYMENT: 'PAYMENT',
- OTHER: 'OTHER'
+ PAYMENT: 'PAYMENT',
+ OTHER: 'OTHER'
};
var HCEEventType = {
- DEACTIVATED: 'DEACTIVATED',
- ACTIVATED: 'ACTIVATED',
- APDU_RECEIVED: 'APDU_RECEIVED'
+ DEACTIVATED: 'DEACTIVATED',
+ ACTIVATED: 'ACTIVATED',
+ APDU_RECEIVED: 'APDU_RECEIVED'
};
function HCEEventData(data) {
- Object.defineProperties(this, {
- eventType: {
- value: data.eventType,
- writable: false,
- enumerable: true
- },
- apdu: {
- value: data.apdu || [],
- writable: false,
- enumerable: true
- },
- length: {
- value: data.length || 0,
- writable: false,
- enumerable: true
- }
- });
+ Object.defineProperties(this, {
+ eventType: {
+ value: data.eventType,
+ writable: false,
+ enumerable: true
+ },
+ apdu: {
+ value: data.apdu || [],
+ writable: false,
+ enumerable: true
+ },
+ length: {
+ value: data.length || 0,
+ writable: false,
+ enumerable: true
+ }
+ });
}
function ListenerManager(native, listenerName) {
- this.listeners = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
+ this.listeners = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
}
ListenerManager.prototype.onListenerCalled = function(msg) {
- for (var key in this.listeners) {
- if (this.listeners.hasOwnProperty(key)) {
- if ('CardElement' === msg.type) {
- this.listeners[key](msg.mode);
- } else if ('Transaction' === msg.type) {
- this.listeners[key](msg.aid, msg.data);
- } else if('HCEEventData' === msg.type) {
- var hceData = new HCEEventData(msg.result);
- this.listeners[key](hceData);
- }
- }
- }
+ for (var key in this.listeners) {
+ if (this.listeners.hasOwnProperty(key)) {
+ if ('CardElement' === msg.type) {
+ this.listeners[key](msg.mode);
+ } else if ('Transaction' === msg.type) {
+ this.listeners[key](msg.aid, msg.data);
+ } else if ('HCEEventData' === msg.type) {
+ var hceData = new HCEEventData(msg.result);
+ this.listeners[key](hceData);
+ }
+ }
+ }
};
ListenerManager.prototype.addListener = function(callback) {
- var id = this.nextId;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- this.nativeSet = true;
- }
- this.listeners[id] = callback;
- ++this.nextId;
- return id;
+ var id = this.nextId;
+ if (!this.nativeSet) {
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ this.nativeSet = true;
+ }
+ this.listeners[id] = callback;
+ ++this.nextId;
+ return id;
};
ListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- }
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ }
};
var PEER_LISTENER = 'PeerListener';
@@ -137,1201 +136,1258 @@ var TRANSACTION_EVENT_ESE_LISTENER = 'TransactionEventListener_ESE';
var TRANSACTION_EVENT_UICC_LISTENER = 'TransactionEventListener_UICC';
var HCE_EVENT_LISTENER = 'HCEEventListener';
var TAG_LISTENER = 'TagListener';
-var cardEmulationModeListener = new ListenerManager(native_, CARD_EMULATION_MODE_LISTENER);
-var activeSecureElementChangeListener = new ListenerManager(native_, ACTIVE_SECURE_ELEMENT_LISTENER);
-var transactionEventListenerEse = new ListenerManager(native_, TRANSACTION_EVENT_ESE_LISTENER);
-var transactionEventListenerUicc = new ListenerManager(native_, TRANSACTION_EVENT_UICC_LISTENER);
+var cardEmulationModeListener = new ListenerManager(
+ native_,
+ CARD_EMULATION_MODE_LISTENER
+);
+var activeSecureElementChangeListener = new ListenerManager(
+ native_,
+ ACTIVE_SECURE_ELEMENT_LISTENER
+);
+var transactionEventListenerEse = new ListenerManager(
+ native_,
+ TRANSACTION_EVENT_ESE_LISTENER
+);
+var transactionEventListenerUicc = new ListenerManager(
+ native_,
+ TRANSACTION_EVENT_UICC_LISTENER
+);
var HCEEventListener = new ListenerManager(native_, HCE_EVENT_LISTENER);
var isWebkitVisibilityChangeListenerSet = false;
//////////////////NFCManager /////////////////
function NFCManager() {
- Object.defineProperties(this, {
- NFC_RECORD_TNF_EMPTY: {value: 0, writable: false, enumerable: true},
- NFC_RECORD_TNF_WELL_KNOWN: {value: 1, writable: false, enumerable: true},
- NFC_RECORD_TNF_MIME_MEDIA: {value: 2, writable: false, enumerable: true},
- NFC_RECORD_TNF_URI: {value: 3, writable: false, enumerable: true},
- NFC_RECORD_TNF_EXTERNAL_RTD: {value: 4, writable: false, enumerable: true},
- NFC_RECORD_TNF_UNKNOWN: {value: 5, writable: false, enumerable: true},
- NFC_RECORD_TNF_UNCHANGED: {value: 6, writable: false, enumerable: true}
- });
+ Object.defineProperties(this, {
+ NFC_RECORD_TNF_EMPTY: { value: 0, writable: false, enumerable: true },
+ NFC_RECORD_TNF_WELL_KNOWN: { value: 1, writable: false, enumerable: true },
+ NFC_RECORD_TNF_MIME_MEDIA: { value: 2, writable: false, enumerable: true },
+ NFC_RECORD_TNF_URI: { value: 3, writable: false, enumerable: true },
+ NFC_RECORD_TNF_EXTERNAL_RTD: { value: 4, writable: false, enumerable: true },
+ NFC_RECORD_TNF_UNKNOWN: { value: 5, writable: false, enumerable: true },
+ NFC_RECORD_TNF_UNCHANGED: { value: 6, writable: false, enumerable: true }
+ });
}
NFCManager.prototype.getDefaultAdapter = function() {
- // First check NFC suppor on C++ level
- var result = native_.callSync(
- 'NFCManager_getDefaultAdapter',
- {}
- );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- // If NFC is supported then return new NFCAdapter instance
- return new NFCAdapter();
+ // First check NFC suppor on C++ level
+ var result = native_.callSync('NFCManager_getDefaultAdapter', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ // If NFC is supported then return new NFCAdapter instance
+ return new NFCAdapter();
};
NFCManager.prototype.setExclusiveMode = function() {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'exclusiveMode', type: types_.BOOLEAN }
+ ]);
- var args = validator_.validateArgs(arguments, [
- {name: 'exclusiveMode', type: types_.BOOLEAN}
- ]);
-
- var result = native_.callSync('NFCManager_setExclusiveMode', {
- exclusiveMode: args.exclusiveMode
- });
+ var result = native_.callSync('NFCManager_setExclusiveMode', {
+ exclusiveMode: args.exclusiveMode
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
//////////////////NFCAdapter /////////////////
function NFCAdapter() {
- function poweredGetter() {
- var ret = native_.callSync('NFCAdapter_getPowered');
+ function poweredGetter() {
+ var ret = native_.callSync('NFCAdapter_getPowered');
+
+ if (native_.isFailure(ret)) {
+ return false;
+ }
- if (native_.isFailure(ret)) {
- return false;
+ return native_.getResultObject(ret);
}
- return native_.getResultObject(ret);
- }
+ function cardEmulationModeGetter() {
+ var result = native_.callSync('NFCAdapter_cardEmulationModeGetter');
- function cardEmulationModeGetter() {
- var result = native_.callSync('NFCAdapter_cardEmulationModeGetter');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ return native_.getResultObject(result);
}
- return native_.getResultObject(result);
- }
+ function cardEmulationModeSetter(cem) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'emulationMode', type: types_.STRING }
+ ]);
- function cardEmulationModeSetter(cem) {
+ var result = native_.callSync('NFCAdapter_cardEmulationModeSetter', {
+ emulationMode: args.emulationMode
+ });
- var args = validator_.validateArgs(arguments, [
- {name: 'emulationMode', type: types_.STRING}
- ]);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return;
+ }
- var result = native_.callSync(
- 'NFCAdapter_cardEmulationModeSetter',
- { 'emulationMode': args.emulationMode}
- );
+ function activeSecureElementGetter() {
+ var result = native_.callSync('NFCAdapter_activeSecureElementGetter');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ return native_.getResultObject(result);
}
- return;
- }
- function activeSecureElementGetter() {
+ function activeSecureElementSetter(ase) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'secureElement', type: types_.STRING }
+ ]);
- var result = native_.callSync('NFCAdapter_activeSecureElementGetter');
+ var result = native_.callSync('NFCAdapter_activeSecureElementSetter', {
+ secureElement: args.secureElement
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return;
}
- return native_.getResultObject(result);
- }
+ Object.defineProperties(this, {
+ powered: { enumerable: true, set: function() {}, get: poweredGetter },
+ cardEmulationMode: {
+ enumerable: true,
+ set: cardEmulationModeSetter,
+ get: cardEmulationModeGetter
+ },
+ activeSecureElement: {
+ enumerable: true,
+ set: activeSecureElementSetter,
+ get: activeSecureElementGetter
+ }
+ });
+}
- function activeSecureElementSetter(ase) {
+NFCAdapter.prototype.setPowered = function() {
+ privUtils_.warn(
+ 'DEPRECATION WARNING: setPowered() is deprecated and will be removed from ' +
+ 'next release. Let the user turn NFC on/off through the Settings ' +
+ 'application instead.'
+ );
var args = validator_.validateArgs(arguments, [
- {name: 'secureElement', type: types_.STRING}
+ {
+ name: 'powered',
+ type: types_.BOOLEAN
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- var result = native_.callSync(
- 'NFCAdapter_activeSecureElementSetter',
- { 'secureElement': args.secureElement}
- );
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return;
- }
-
- Object.defineProperties(this, {
- powered: {enumerable: true,
- set: function() {},
- get: poweredGetter
- },
- cardEmulationMode: {enumerable: true,
- set: cardEmulationModeSetter,
- get: cardEmulationModeGetter
- },
- activeSecureElement: {enumerable: true,
- set: activeSecureElementSetter,
- get: activeSecureElementGetter
- }
- });
-}
+ var result = native_.call(
+ 'NFCAdapter_setPowered',
+ {
+ powered: args.powered
+ },
+ function(result) {
+ if (native_.isFailure(result)) {
+ args.errorCallback(result.error);
+ } else {
+ args.successCallback();
+ }
+ }
+ );
-NFCAdapter.prototype.setPowered = function() {
- privUtils_.warn('DEPRECATION WARNING: setPowered() is deprecated and will be removed from next release. Let the user turn NFC on/off '
- + 'through the Settings application instead.');
-
- var args = validator_.validateArgs(arguments, [
- {
- name: 'powered',
- type: types_.BOOLEAN
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- var result = native_.call('NFCAdapter_setPowered', {
- powered: args.powered
- }, function(result) {
if (native_.isFailure(result)) {
- args.errorCallback(result.error);
- } else {
- args.successCallback();
+ throw native_.getErrorObject(result);
}
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
function setTagListener() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'listener',
- type: types_.LISTENER,
- values: ['onattach', 'ondetach']
- },
- {
- name: 'tagType',
- type: types_.ARRAY,
- values: types_.STRING,
- optional: true,
- nullable: true
- }
- ]);
-
- if (!type_.isNullOrUndefined(args.tagType)) {
- for (var i = 0; i < args.tagType.length; i++) {
- if (NFCTagType[args.tagType[i]] === undefined) {
- throw new WebAPIException(
- WebAPIException.TYPE_MISMATCH_ERR, 'Invalid tag type.');
- }
- }
- }
-
- // Listener object creation
- var listenerCallback = function(message) {
- var tagObject = undefined;
-
- if ('onattach' === message.action) {
- tagObject = new NFCTag(message.id);
-
- // If filter is set for listener but tag type is not searched one
- if (!type_.isNullOrUndefined(args.tagType) &&
- args.tagType.indexOf(tagObject.type) < 0) {
- return;
- }
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listener',
+ type: types_.LISTENER,
+ values: ['onattach', 'ondetach']
+ },
+ {
+ name: 'tagType',
+ type: types_.ARRAY,
+ values: types_.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (!type_.isNullOrUndefined(args.tagType)) {
+ for (var i = 0; i < args.tagType.length; i++) {
+ if (NFCTagType[args.tagType[i]] === undefined) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Invalid tag type.'
+ );
+ }
+ }
}
- native_.callIfPossible(args.listener[message.action], tagObject);
- };
- // Register (acivate) core listener if not done yet
- if (!native_.isListenerSet(TAG_LISTENER)) {
- var result = native_.callSync('NFCAdapter_setTagListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ // Listener object creation
+ var listenerCallback = function(message) {
+ var tagObject = undefined;
+
+ if ('onattach' === message.action) {
+ tagObject = new NFCTag(message.id);
+
+ // If filter is set for listener but tag type is not searched one
+ if (
+ !type_.isNullOrUndefined(args.tagType) &&
+ args.tagType.indexOf(tagObject.type) < 0
+ ) {
+ return;
+ }
+ }
+ native_.callIfPossible(args.listener[message.action], tagObject);
+ };
+
+ // Register (acivate) core listener if not done yet
+ if (!native_.isListenerSet(TAG_LISTENER)) {
+ var result = native_.callSync('NFCAdapter_setTagListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- native_.addListener(TAG_LISTENER, listenerCallback);
- return;
-};
+ native_.addListener(TAG_LISTENER, listenerCallback);
+ return;
+}
NFCAdapter.prototype.setTagListener = function() {
- setTagListener.apply(this, arguments);
-}
+ setTagListener.apply(this, arguments);
+};
function setPeerListener() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'listener',
- type: types_.LISTENER,
- values: ['onattach', 'ondetach']
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listener',
+ type: types_.LISTENER,
+ values: ['onattach', 'ondetach']
+ }
+ ]);
- var listener = function(msg) {
- var data = undefined;
- if ('onattach' === msg.action) {
- data = new NFCPeer(msg.id);
- }
- native_.callIfPossible(args.listener[msg.action], data);
- };
+ var listener = function(msg) {
+ var data = undefined;
+ if ('onattach' === msg.action) {
+ data = new NFCPeer(msg.id);
+ }
+ native_.callIfPossible(args.listener[msg.action], data);
+ };
- if (!native_.isListenerSet(PEER_LISTENER)) {
- var result = native_.callSync('NFCAdapter_setPeerListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (!native_.isListenerSet(PEER_LISTENER)) {
+ var result = native_.callSync('NFCAdapter_setPeerListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- native_.addListener(PEER_LISTENER, listener);
- return;
-};
+ native_.addListener(PEER_LISTENER, listener);
+ return;
+}
NFCAdapter.prototype.setPeerListener = function() {
- setPeerListener.apply(this, arguments);
+ setPeerListener.apply(this, arguments);
};
NFCAdapter.prototype.unsetTagListener = function() {
+ native_.removeListener(TAG_LISTENER);
- native_.removeListener(TAG_LISTENER);
-
- var result = native_.callSync('NFCAdapter_unsetTagListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('NFCAdapter_unsetTagListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return;
+ return;
};
NFCAdapter.prototype.unsetPeerListener = function() {
- native_.removeListener(PEER_LISTENER);
+ native_.removeListener(PEER_LISTENER);
- var result = native_.callSync('NFCAdapter_unsetPeerListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('NFCAdapter_unsetPeerListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return;
+ return;
};
function addCardEmulationModeChangeListener() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'callback',
- type: types_.FUNCTION
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'callback',
+ type: types_.FUNCTION
+ }
+ ]);
- if (type_.isEmptyObject(cardEmulationModeListener.listeners) &&
- type_.isEmptyObject(activeSecureElementChangeListener.listeners)) {
- var result = native_.callSync(
- 'NFCAdapter_addCardEmulationModeChangeListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (
+ type_.isEmptyObject(cardEmulationModeListener.listeners) &&
+ type_.isEmptyObject(activeSecureElementChangeListener.listeners)
+ ) {
+ var result = native_.callSync('NFCAdapter_addCardEmulationModeChangeListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- return cardEmulationModeListener.addListener(args.callback);
-};
+ return cardEmulationModeListener.addListener(args.callback);
+}
NFCAdapter.prototype.addCardEmulationModeChangeListener = function() {
- return addCardEmulationModeChangeListener.apply(this, arguments);
+ return addCardEmulationModeChangeListener.apply(this, arguments);
};
function removeCardEmulationModeChangeListener() {
- if (type_.isEmptyObject(cardEmulationModeListener.listeners)) {
- privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
- }
-
- var args = validator_.validateArgs(arguments, [
- {
- name: 'listenerId',
- type: types_.LONG
+ if (type_.isEmptyObject(cardEmulationModeListener.listeners)) {
+ privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
}
- ]);
- cardEmulationModeListener.removeListener(args.listenerId);
- if (type_.isEmptyObject(cardEmulationModeListener.listeners) &&
- type_.isEmptyObject(activeSecureElementChangeListener.listeners)) {
- var result = native_.callSync('NFCAdapter_removeCardEmulationModeChangeListener');
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listenerId',
+ type: types_.LONG
+ }
+ ]);
+ cardEmulationModeListener.removeListener(args.listenerId);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (
+ type_.isEmptyObject(cardEmulationModeListener.listeners) &&
+ type_.isEmptyObject(activeSecureElementChangeListener.listeners)
+ ) {
+ var result = native_.callSync('NFCAdapter_removeCardEmulationModeChangeListener');
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
-};
+}
NFCAdapter.prototype.removeCardEmulationModeChangeListener = function() {
- removeCardEmulationModeChangeListener.apply(this, arguments);
+ removeCardEmulationModeChangeListener.apply(this, arguments);
};
function addTransactionEventListener() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'type',
- type: types_.ENUM,
- values: type_.getValues(SecureElementType)
- },
- {
- name: 'callback',
- type: types_.FUNCTION
- }
- ]);
-
- var result;
-
- if (SecureElementType.ESE === args.type) {
- if (type_.isEmptyObject(transactionEventListenerEse.listeners)) {
- result = native_.callSync('NFCAdapter_addTransactionEventListener', {
- type: args.type});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- }
- return transactionEventListenerEse.addListener(args.callback);
- } else {
- if (type_.isEmptyObject(transactionEventListenerUicc.listeners)) {
- result = native_.callSync('NFCAdapter_addTransactionEventListener', {
- type: args.type});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(SecureElementType)
+ },
+ {
+ name: 'callback',
+ type: types_.FUNCTION
+ }
+ ]);
+
+ var result;
+
+ if (SecureElementType.ESE === args.type) {
+ if (type_.isEmptyObject(transactionEventListenerEse.listeners)) {
+ result = native_.callSync('NFCAdapter_addTransactionEventListener', {
+ type: args.type
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ }
+ return transactionEventListenerEse.addListener(args.callback);
+ } else {
+ if (type_.isEmptyObject(transactionEventListenerUicc.listeners)) {
+ result = native_.callSync('NFCAdapter_addTransactionEventListener', {
+ type: args.type
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ }
+ return transactionEventListenerUicc.addListener(args.callback);
}
- return transactionEventListenerUicc.addListener(args.callback);
- }
-};
+}
NFCAdapter.prototype.addTransactionEventListener = function() {
- return addTransactionEventListener.apply(this, arguments);
+ return addTransactionEventListener.apply(this, arguments);
};
function removeTransactionEventListener() {
- var ese_empty = type_.isEmptyObject(transactionEventListenerEse.listeners);
- var uicc_empty = type_.isEmptyObject(transactionEventListenerUicc.listeners);
+ var ese_empty = type_.isEmptyObject(transactionEventListenerEse.listeners);
+ var uicc_empty = type_.isEmptyObject(transactionEventListenerUicc.listeners);
- if (!ese_empty || !uicc_empty) {
- privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
- }
-
- var args = validator_.validateArgs(arguments, [
- {
- name: 'watchId',
- type: types_.LONG
+ if (!ese_empty || !uicc_empty) {
+ privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
}
- ]);
- transactionEventListenerEse.removeListener(args.watchId);
- transactionEventListenerUicc.removeListener(args.watchId);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'watchId',
+ type: types_.LONG
+ }
+ ]);
- if (type_.isEmptyObject(transactionEventListenerEse.listeners) && !ese_empty) {
- var result = native_.callSync('NFCAdapter_removeTransactionEventListener', {
- type: SecureElementType.ESE});
+ transactionEventListenerEse.removeListener(args.watchId);
+ transactionEventListenerUicc.removeListener(args.watchId);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (type_.isEmptyObject(transactionEventListenerEse.listeners) && !ese_empty) {
+ var result = native_.callSync('NFCAdapter_removeTransactionEventListener', {
+ type: SecureElementType.ESE
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- if (type_.isEmptyObject(transactionEventListenerUicc.listeners)
- && !uicc_empty) {
- var result = native_.callSync('NFCAdapter_removeTransactionEventListener', {
- type: SecureElementType.UICC});
+ if (type_.isEmptyObject(transactionEventListenerUicc.listeners) && !uicc_empty) {
+ var result = native_.callSync('NFCAdapter_removeTransactionEventListener', {
+ type: SecureElementType.UICC
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
-
-};
+}
NFCAdapter.prototype.removeTransactionEventListener = function() {
- removeTransactionEventListener.apply(this, arguments);
+ removeTransactionEventListener.apply(this, arguments);
};
function addActiveSecureElementChangeListener() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'callback',
- type: types_.FUNCTION
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'callback',
+ type: types_.FUNCTION
+ }
+ ]);
- if (type_.isEmptyObject(cardEmulationModeListener.listeners) &&
- type_.isEmptyObject(activeSecureElementChangeListener.listeners)) {
- var result = native_.callSync(
- 'NFCAdapter_addActiveSecureElementChangeListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (
+ type_.isEmptyObject(cardEmulationModeListener.listeners) &&
+ type_.isEmptyObject(activeSecureElementChangeListener.listeners)
+ ) {
+ var result = native_.callSync('NFCAdapter_addActiveSecureElementChangeListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- return activeSecureElementChangeListener.addListener(args.callback);
-};
+ return activeSecureElementChangeListener.addListener(args.callback);
+}
NFCAdapter.prototype.addActiveSecureElementChangeListener = function() {
- return addActiveSecureElementChangeListener.apply(this, arguments);
+ return addActiveSecureElementChangeListener.apply(this, arguments);
};
function removeActiveSecureElementChangeListener() {
- if (type_.isEmptyObject(activeSecureElementChangeListener.listeners)) {
- privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
- }
-
- var args = validator_.validateArgs(arguments, [
- {
- name: 'listenerId',
- type: types_.LONG
+ if (type_.isEmptyObject(activeSecureElementChangeListener.listeners)) {
+ privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
}
- ]);
- activeSecureElementChangeListener.removeListener(args.listenerId);
- if (type_.isEmptyObject(cardEmulationModeListener.listeners) &&
- type_.isEmptyObject(activeSecureElementChangeListener.listeners)) {
- var result = native_.callSync('NFCAdapter_removeCardEmulationModeChangeListener');
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listenerId',
+ type: types_.LONG
+ }
+ ]);
+ activeSecureElementChangeListener.removeListener(args.listenerId);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (
+ type_.isEmptyObject(cardEmulationModeListener.listeners) &&
+ type_.isEmptyObject(activeSecureElementChangeListener.listeners)
+ ) {
+ var result = native_.callSync('NFCAdapter_removeCardEmulationModeChangeListener');
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
-};
+}
NFCAdapter.prototype.removeActiveSecureElementChangeListener = function() {
- removeActiveSecureElementChangeListener.apply(this, arguments);
+ removeActiveSecureElementChangeListener.apply(this, arguments);
};
NFCAdapter.prototype.getCachedMessage = function() {
- var result = native_.callSync('NFCAdapter_getCachedMessage');
+ var result = native_.callSync('NFCAdapter_getCachedMessage');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- if (!result.records) {
- return new tizen.NDEFMessage();
- }
+ if (!result.records) {
+ return new tizen.NDEFMessage();
+ }
- return new tizen.NDEFMessage(toRecordsArray(result.records));
+ return new tizen.NDEFMessage(toRecordsArray(result.records));
};
NFCAdapter.prototype.setExclusiveModeForTransaction = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'transactionMode',
+ type: types_.BOOLEAN
+ }
+ ]);
- var args = validator_.validateArgs(arguments, [
- {
- name: 'transactionMode',
- type: types_.BOOLEAN
- }
- ]);
-
- var result = native_.callSync(
- 'NFCAdapter_setExclusiveModeForTransaction',
- { 'transactionMode': args.transactionMode}
- );
+ var result = native_.callSync('NFCAdapter_setExclusiveModeForTransaction', {
+ transactionMode: args.transactionMode
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return;
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return;
};
function addHCEEventListener() {
- var args = validator_.validateArgs(arguments, [
- {name: 'eventCallback', type: types_.FUNCTION}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'eventCallback', type: types_.FUNCTION }
+ ]);
- if (!arguments.length || !type_.isFunction(arguments[0])) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
+ if (!arguments.length || !type_.isFunction(arguments[0])) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
- if (type_.isEmptyObject(HCEEventListener.listeners)) {
- var result = native_.callSync('NFCAdapter_addHCEEventListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (type_.isEmptyObject(HCEEventListener.listeners)) {
+ var result = native_.callSync('NFCAdapter_addHCEEventListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
- return HCEEventListener.addListener(args.eventCallback);
-};
+ return HCEEventListener.addListener(args.eventCallback);
+}
NFCAdapter.prototype.addHCEEventListener = function() {
- return addHCEEventListener.apply(this, arguments);
-}
+ return addHCEEventListener.apply(this, arguments);
+};
function removeHCEEventListener() {
- if (type_.isEmptyObject(HCEEventListener.listeners)) {
- privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
- }
+ if (type_.isEmptyObject(HCEEventListener.listeners)) {
+ privUtils_.checkPrivilegeAccess(privilege_.NFC_CARDEMULATION);
+ }
- var args = validator_.validateArgs(arguments, [
- {name: 'watchId', type: types_.LONG}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'watchId', type: types_.LONG }
+ ]);
- if (!arguments.length || !type_.isNumber(arguments[0])) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
+ if (!arguments.length || !type_.isNumber(arguments[0])) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
- HCEEventListener.removeListener(args.watchId);
+ HCEEventListener.removeListener(args.watchId);
- if (type_.isEmptyObject(HCEEventListener.listeners)) {
- var result = native_.callSync('NFCAdapter_removeHCEEventListener');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ if (type_.isEmptyObject(HCEEventListener.listeners)) {
+ var result = native_.callSync('NFCAdapter_removeHCEEventListener');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
}
- }
-};
+}
NFCAdapter.prototype.removeHCEEventListener = function() {
- removeHCEEventListener.apply(this, arguments);
+ removeHCEEventListener.apply(this, arguments);
};
-NFCAdapter.prototype.sendHostAPDUResponse = function(apdu, successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'apdu', type: types_.ARRAY, values: types_.BYTE},
- {name: 'successCallback', type: types_.FUNCTION, optional: true, nullable: true},
- {name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true}
- ]);
+NFCAdapter.prototype.sendHostAPDUResponse = function(
+ apdu,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'apdu', type: types_.ARRAY, values: types_.BYTE },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
- if (!arguments.length || !type_.isArray(arguments[0])) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
+ if (!arguments.length || !type_.isArray(arguments[0])) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
- var data = {
- apdu: args.apdu
- };
+ var data = {
+ apdu: args.apdu
+ };
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
- }
- native_.callIfPossible(args.successCallback);
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ native_.callIfPossible(args.successCallback);
+ };
- var result = native_.call('NFCAdapter_sendHostAPDUResponse', data, callback);
+ var result = native_.call('NFCAdapter_sendHostAPDUResponse', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
NFCAdapter.prototype.isActivatedHandlerForAID = function(type, aid) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(SecureElementType)
+ },
+ { name: 'aid', type: types_.STRING }
+ ]);
+
+ if (arguments.length < 2) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
+
+ var data = {
+ type: args.type,
+ aid: args.aid
+ };
- var args = validator_.validateArgs(arguments, [
- {
- name: 'type',
- type: types_.ENUM,
- values: type_.getValues(SecureElementType)
- },
- {name: 'aid', type: types_.STRING}
- ]);
-
- if (arguments.length < 2) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
-
- var data = {
- type: args.type,
- aid: args.aid
- };
-
- var result = native_.callSync('NFCAdapter_isActivatedHandlerForAID', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
+ var result = native_.callSync('NFCAdapter_isActivatedHandlerForAID', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
};
NFCAdapter.prototype.isActivatedHandlerForCategory = function(type, category) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(SecureElementType)
+ },
+ {
+ name: 'category',
+ type: types_.ENUM,
+ values: Object.keys(CardEmulationCategoryType)
+ }
+ ]);
+
+ if (arguments.length < 2) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: type_.getValues(SecureElementType)
- }, {
- name: 'category',
- type: types_.ENUM,
- values: Object.keys(CardEmulationCategoryType)
- }]);
-
- if (arguments.length < 2) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
-
- var data = {
- type: args.type,
- category: args.category
- };
-
- var result = native_.callSync('NFCAdapter_isActivatedHandlerForCategory', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
+ var data = {
+ type: args.type,
+ category: args.category
+ };
+
+ var result = native_.callSync('NFCAdapter_isActivatedHandlerForCategory', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
};
NFCAdapter.prototype.registerAID = function(type, aid, category) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(SecureElementType)
+ },
+ {
+ name: 'aid',
+ type: types_.STRING
+ },
+ {
+ name: 'category',
+ type: types_.ENUM,
+ values: Object.keys(CardEmulationCategoryType)
+ }
+ ]);
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: type_.getValues(SecureElementType)
- }, {
- name: 'aid',
- type: types_.STRING
- }, {
- name: 'category',
- type: types_.ENUM,
- values: Object.keys(CardEmulationCategoryType)
- }]);
-
- if (arguments.length < 3 || !type_.isString(arguments[0])) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
-
- var data = {
- type: args.type,
- aid: args.aid,
- category: args.category
- };
-
- var result = native_.callSync('NFCAdapter_registerAID', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (arguments.length < 3 || !type_.isString(arguments[0])) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
+
+ var data = {
+ type: args.type,
+ aid: args.aid,
+ category: args.category
+ };
+
+ var result = native_.callSync('NFCAdapter_registerAID', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
NFCAdapter.prototype.unregisterAID = function(type, aid, category) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(SecureElementType)
+ },
+ { name: 'aid', type: types_.STRING },
+ {
+ name: 'category',
+ type: types_.ENUM,
+ values: Object.keys(CardEmulationCategoryType)
+ }
+ ]);
- var args = validator_.validateArgs(arguments, [
- {
- name: 'type',
- type: types_.ENUM,
- values: type_.getValues(SecureElementType)
- },
- {name: 'aid', type: types_.STRING},
- {name: 'category', type: types_.ENUM, values: Object.keys(CardEmulationCategoryType)}
- ]);
-
- if (arguments.length < 3 || !type_.isString(arguments[0])) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
-
- var data = {
- type: args.type,
- aid: args.aid,
- category: args.category
- };
-
- var result = native_.callSync('NFCAdapter_unregisterAID', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (arguments.length < 3 || !type_.isString(arguments[0])) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
+
+ var data = {
+ type: args.type,
+ aid: args.aid,
+ category: args.category
+ };
+
+ var result = native_.callSync('NFCAdapter_unregisterAID', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
function AIDData(data) {
- Object.defineProperties(this, {
- type: {
- value: data.type,
- writable: false,
- enumerable: true
- },
- aid: {
- value: data.aid || [],
- writable: false,
- enumerable: true
- },
- readOnly: {
- value: data.readOnly || false,
- writable: false,
- enumerable: true
- }
- });
+ Object.defineProperties(this, {
+ type: {
+ value: data.type,
+ writable: false,
+ enumerable: true
+ },
+ aid: {
+ value: data.aid || [],
+ writable: false,
+ enumerable: true
+ },
+ readOnly: {
+ value: data.readOnly || false,
+ writable: false,
+ enumerable: true
+ }
+ });
}
-NFCAdapter.prototype.getAIDsForCategory = function(type, category, successCallback, errorCallback) {
-
- var args = validator_.validateArgs(arguments, [{
- name: 'type',
- type: types_.ENUM,
- values: type_.getValues(SecureElementType)
- }, {
- name: 'category',
- type: types_.ENUM,
- values: Object.keys(CardEmulationCategoryType)
- }, {
- name: 'successCallback',
- type: types_.FUNCTION
- }, {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }]);
-
- if (arguments.length < 3) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
-
- var data = {
- type: args.type,
- category: args.category
- };
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- return;
- }
- var aids = [];
- var r = native_.getResultObject(result);
- for (var i = 0; i < r.length; i++) {
- aids.push(new AIDData(r[i]));
+NFCAdapter.prototype.getAIDsForCategory = function(
+ type,
+ category,
+ successCallback,
+ errorCallback
+) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(SecureElementType)
+ },
+ {
+ name: 'category',
+ type: types_.ENUM,
+ values: Object.keys(CardEmulationCategoryType)
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ if (arguments.length < 3) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
}
- native_.callIfPossible(args.successCallback, aids);
- };
- var result = native_.call('NFCAdapter_getAIDsForCategory', data, callback);
+ var data = {
+ type: args.type,
+ category: args.category
+ };
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
+ var aids = [];
+ var r = native_.getResultObject(result);
+ for (var i = 0; i < r.length; i++) {
+ aids.push(new AIDData(r[i]));
+ }
+ native_.callIfPossible(args.successCallback, aids);
+ };
+
+ var result = native_.call('NFCAdapter_getAIDsForCategory', data, callback);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
function WebkitVisibilityChangeListener() {
- var result;
- if (true === privUtils_.global.document.hidden) {
- result = native_.call('NFCAdapter_unsetPreferredApp');
- } else if (false === privUtils_.global.document.hidden) {
- result = native_.call('NFCAdapter_setPreferredApp');
- }
-
- if (native_.isFailure(result)) {
- privUtils_.log('Failed to (un)set: ' + result.error.message);
- }
+ var result;
+ if (true === privUtils_.global.document.hidden) {
+ result = native_.call('NFCAdapter_unsetPreferredApp');
+ } else if (false === privUtils_.global.document.hidden) {
+ result = native_.call('NFCAdapter_setPreferredApp');
+ }
+
+ if (native_.isFailure(result)) {
+ privUtils_.log('Failed to (un)set: ' + result.error.message);
+ }
}
NFCAdapter.prototype.setPreferredApp = function() {
- var result = native_.call('NFCAdapter_setPreferredApp');
+ var result = native_.call('NFCAdapter_setPreferredApp');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- if (false === isWebkitVisibilityChangeListenerSet) {
- privUtils_.global.document.addEventListener("webkitvisibilitychange", WebkitVisibilityChangeListener);
- isWebkitVisibilityChangeListenerSet = true;
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ if (false === isWebkitVisibilityChangeListenerSet) {
+ privUtils_.global.document.addEventListener(
+ 'webkitvisibilitychange',
+ WebkitVisibilityChangeListener
+ );
+ isWebkitVisibilityChangeListenerSet = true;
+ }
}
- }
};
NFCAdapter.prototype.unsetPreferredApp = function() {
- var result = native_.call('NFCAdapter_unsetPreferredApp');
+ var result = native_.call('NFCAdapter_unsetPreferredApp');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- if (true === isWebkitVisibilityChangeListenerSet) {
- privUtils_.global.document.removeEventListener("webkitvisibilitychange", WebkitVisibilityChangeListener);
- isWebkitVisibilityChangeListenerSet = false;
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ if (true === isWebkitVisibilityChangeListenerSet) {
+ privUtils_.global.document.removeEventListener(
+ 'webkitvisibilitychange',
+ WebkitVisibilityChangeListener
+ );
+ isWebkitVisibilityChangeListenerSet = false;
+ }
}
- }
};
function InternalRecordData(tnf, type, payload, id) {
- this.tnf = tnf;
- this.type = type;
- this.payload = payload;
- this.id = id;
-};
+ this.tnf = tnf;
+ this.type = type;
+ this.payload = payload;
+ this.id = id;
+}
var toRecordsArray = function(array) {
- var result = [];
- if (type_.isNullOrUndefined(array) || !type_.isArray(array)) {
- return result;
- }
+ var result = [];
+ if (type_.isNullOrUndefined(array) || !type_.isArray(array)) {
+ return result;
+ }
- for (var i = 0; i < array.length; i++) {
- var data = new InternalRecordData(array[i].tnf, array[i].type, array[i].payload, array[i].id);
+ for (var i = 0; i < array.length; i++) {
+ var data = new InternalRecordData(
+ array[i].tnf,
+ array[i].type,
+ array[i].payload,
+ array[i].id
+ );
- if (array[i].recordType == 'Record') {
- result.push(new tizen.NDEFRecord(data.tnf, data.type, data.payload, data.id));
- continue;
- }
+ if (array[i].recordType == 'Record') {
+ result.push(new tizen.NDEFRecord(data.tnf, data.type, data.payload, data.id));
+ continue;
+ }
- if (array[i].recordType == 'RecordText') {
- result.push(new tizen.NDEFRecordText(array[i].text, array[i].languageCode,
- array[i].encoding, data));
- continue;
- }
+ if (array[i].recordType == 'RecordText') {
+ result.push(
+ new tizen.NDEFRecordText(
+ array[i].text,
+ array[i].languageCode,
+ array[i].encoding,
+ data
+ )
+ );
+ continue;
+ }
- if (array[i].recordType == 'RecordURI') {
- result.push(new tizen.NDEFRecordURI(array[i].uri, data));
- continue;
- }
+ if (array[i].recordType == 'RecordURI') {
+ result.push(new tizen.NDEFRecordURI(array[i].uri, data));
+ continue;
+ }
- if (array[i].recordType == 'RecordMedia') {
- result.push(new tizen.NDEFRecordMedia(array[i].mimeType, null, data));
- continue;
+ if (array[i].recordType == 'RecordMedia') {
+ result.push(new tizen.NDEFRecordMedia(array[i].mimeType, null, data));
+ continue;
+ }
}
- }
- return result;
+ return result;
};
//////////////////NFCTag /////////////////
function NFCTag(tagid) {
+ var _my_id = tagid;
- var _my_id = tagid;
-
- function TypeGetter() {
-
- var result = native_.callSync('NFCTag_typeGetter', {'id' : _my_id});
-
- if (native_.isFailure(result)) {
- return;
- }
- return native_.getResultObject(result);
- }
-
- function IsSupportedNDEFGetter() {
-
- var result = native_.callSync('NFCTag_isSupportedNDEFGetter', {'id' : _my_id});
+ function TypeGetter() {
+ var result = native_.callSync('NFCTag_typeGetter', { id: _my_id });
- if (native_.isFailure(result)) {
- return;
- }
- return native_.getResultObject(result);
- }
-
- function NDEFSizeGetter() {
-
- var result = native_.callSync('NFCTag_NDEFSizeGetter', {'id' : _my_id});
-
- if (native_.isFailure(result)) {
- return;
+ if (native_.isFailure(result)) {
+ return;
+ }
+ return native_.getResultObject(result);
}
- return native_.getResultObject(result);
- }
-
- function PropertiesGetter() {
- var result = native_.callSync('NFCTag_propertiesGetter', {'id' : _my_id});
+ function IsSupportedNDEFGetter() {
+ var result = native_.callSync('NFCTag_isSupportedNDEFGetter', { id: _my_id });
- if (native_.isFailure(result)) {
- return;
+ if (native_.isFailure(result)) {
+ return;
+ }
+ return native_.getResultObject(result);
}
- privUtils_.log('Current result: ' + result);
+ function NDEFSizeGetter() {
+ var result = native_.callSync('NFCTag_NDEFSizeGetter', { id: _my_id });
- var result_array = {};
- for (var i in result.result) {
- var current = result.result[i];
- var keys = Object.keys(current);
- for (var x in keys) {
- result_array[keys[x]] = current[keys[x]];
- }
+ if (native_.isFailure(result)) {
+ return;
+ }
+ return native_.getResultObject(result);
}
- return result_array;
- }
-
- function IsConnectedGetter() {
- var result = native_.callSync('NFCTag_isConnectedGetter', {'id' : _my_id});
+ function PropertiesGetter() {
+ var result = native_.callSync('NFCTag_propertiesGetter', { id: _my_id });
- if (native_.isFailure(result)) {
- return;
- }
- return native_.getResultObject(result);
- }
+ if (native_.isFailure(result)) {
+ return;
+ }
- // Function defined here (not outside Tag "constructor"
- // because access to internal _my_id variable is needed)
- NFCTag.prototype.readNDEF = function() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_TAG);
+ privUtils_.log('Current result: ' + result);
- var args = validator_.validateArgs(arguments, [
- {
- name: 'readCallback',
- type: types_.FUNCTION
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- var result = native_.call('NFCTag_readNDEF', {'id' : _my_id},
- function(result) {
- if (native_.isFailure(result)) {
- if (!type_.isNullOrUndefined(args.errorCallback)) {
- args.errorCallback(native_.getErrorObject(result));
+ var result_array = {};
+ for (var i in result.result) {
+ var current = result.result[i];
+ var keys = Object.keys(current);
+ for (var x in keys) {
+ result_array[keys[x]] = current[keys[x]];
}
- } else {
- var message = new tizen.NDEFMessage(toRecordsArray(result.records));
- args.readCallback(message);
- }
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ }
+ return result_array;
}
- };
- NFCTag.prototype.writeNDEF = function() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_TAG);
+ function IsConnectedGetter() {
+ var result = native_.callSync('NFCTag_isConnectedGetter', { id: _my_id });
- var args = validator_.validateArgs(arguments, [
- {
- name: 'message',
- type: types_.PLATFORM_OBJECT,
- values: tizen.NDEFMessage
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
-
- var result = native_.call('NFCTag_writeNDEF',
- {
- 'id' : _my_id,
- 'records' : args.message.records,
- 'recordsSize' : args.message.recordCount
- },
- function(result) {
- if (native_.isFailure(result)) {
- if (!type_.isNullOrUndefined(args.errorCallback)) {
- args.errorCallback(native_.getErrorObject(result));
+ if (native_.isFailure(result)) {
+ return;
+ }
+ return native_.getResultObject(result);
+ }
+
+ // Function defined here (not outside Tag "constructor"
+ // because access to internal _my_id variable is needed)
+ NFCTag.prototype.readNDEF = function() {
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_TAG);
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'readCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
}
- } else {
- if (!type_.isNullOrUndefined(args.successCallback)) {
- args.successCallback();
+ ]);
+
+ var result = native_.call('NFCTag_readNDEF', { id: _my_id }, function(result) {
+ if (native_.isFailure(result)) {
+ if (!type_.isNullOrUndefined(args.errorCallback)) {
+ args.errorCallback(native_.getErrorObject(result));
+ }
+ } else {
+ var message = new tizen.NDEFMessage(toRecordsArray(result.records));
+ args.readCallback(message);
}
- }
});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- };
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ };
- NFCTag.prototype.transceive = function() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_TAG);
+ NFCTag.prototype.writeNDEF = function() {
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_TAG);
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'message',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.NDEFMessage
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var result = native_.call(
+ 'NFCTag_writeNDEF',
+ {
+ id: _my_id,
+ records: args.message.records,
+ recordsSize: args.message.recordCount
+ },
+ function(result) {
+ if (native_.isFailure(result)) {
+ if (!type_.isNullOrUndefined(args.errorCallback)) {
+ args.errorCallback(native_.getErrorObject(result));
+ }
+ } else {
+ if (!type_.isNullOrUndefined(args.successCallback)) {
+ args.successCallback();
+ }
+ }
+ }
+ );
- var args = validator_.validateArgs(arguments, [
- {
- name: 'data',
- type: types_.ARRAY,
- values: types_.BYTE
- },
- {
- name: 'dataCallback',
- type: types_.FUNCTION
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ };
- var result = native_.call('NFCTag_transceive',
- {
- 'id' : _my_id,
- 'data' : args.data
- },
- function(result) {
- if (native_.isFailure(result)) {
- if (!type_.isNullOrUndefined(args.errorCallback)) {
- args.errorCallback(result.error);
+ NFCTag.prototype.transceive = function() {
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_TAG);
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'data',
+ type: types_.ARRAY,
+ values: types_.BYTE
+ },
+ {
+ name: 'dataCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
}
- } else {
- if (!type_.isNullOrUndefined(args.dataCallback)) {
- args.dataCallback(result.data);
+ ]);
+
+ var result = native_.call(
+ 'NFCTag_transceive',
+ {
+ id: _my_id,
+ data: args.data
+ },
+ function(result) {
+ if (native_.isFailure(result)) {
+ if (!type_.isNullOrUndefined(args.errorCallback)) {
+ args.errorCallback(result.error);
+ }
+ } else {
+ if (!type_.isNullOrUndefined(args.dataCallback)) {
+ args.dataCallback(result.data);
+ }
+ }
}
- }
- });
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- };
-
- Object.defineProperties(this, {
- type: {
- set: function() {},
- get: TypeGetter,
- enumerable: true
- },
- isSupportedNDEF: {
- set: function() {},
- get: IsSupportedNDEFGetter,
- enumerable: true
- },
- ndefSize: {
- set: function() {},
- get: NDEFSizeGetter,
- enumerable: true
- },
- properties: {
- set: function() {},
- get: PropertiesGetter,
- enumerable: true
- },
- isConnected: {
- set: function() {},
- get: IsConnectedGetter,
- enumerable: true
- }
- });
-}
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ };
+ Object.defineProperties(this, {
+ type: {
+ set: function() {},
+ get: TypeGetter,
+ enumerable: true
+ },
+ isSupportedNDEF: {
+ set: function() {},
+ get: IsSupportedNDEFGetter,
+ enumerable: true
+ },
+ ndefSize: {
+ set: function() {},
+ get: NDEFSizeGetter,
+ enumerable: true
+ },
+ properties: {
+ set: function() {},
+ get: PropertiesGetter,
+ enumerable: true
+ },
+ isConnected: {
+ set: function() {},
+ get: IsConnectedGetter,
+ enumerable: true
+ }
+ });
+}
//////////////////NFCPeer /////////////////
function NFCPeer(peerid) {
- var _my_id = peerid;
+ var _my_id = peerid;
- function isConnectedGetter() {
- var ret = native_.callSync('NFCAdapter_PeerIsConnectedGetter', {'id' : _my_id});
- if (native_.isFailure(ret)) {
- return false;
- }
- return native_.getResultObject(ret);
- }
-
- NFCPeer.prototype.sendNDEF = function() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_P2P);
+ function isConnectedGetter() {
+ var ret = native_.callSync('NFCAdapter_PeerIsConnectedGetter', { id: _my_id });
+ if (native_.isFailure(ret)) {
+ return false;
+ }
+ return native_.getResultObject(ret);
+ }
+
+ NFCPeer.prototype.sendNDEF = function() {
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_P2P);
+
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'message',
+ type: types_.PLATFORM_OBJECT,
+ values: tizen.NDEFMessage
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var result = native_.call(
+ 'NFCPeer_sendNDEF',
+ {
+ id: _my_id,
+ records: args.message.records,
+ recordsSize: args.message.recordCount
+ },
+ function(result) {
+ if (native_.isFailure(result)) {
+ args.errorCallback(result.error);
+ } else {
+ args.successCallback();
+ }
+ }
+ );
- var args = validator_.validateArgs(arguments, [
- {
- name: 'message',
- type: types_.PLATFORM_OBJECT,
- values: tizen.NDEFMessage
- },
- {
- name: 'successCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types_.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ };
- var result = native_.call('NFCPeer_sendNDEF', {
- 'id' : _my_id,
- 'records' : args.message.records,
- 'recordsSize' : args.message.recordCount
- }, function(result) {
- if (native_.isFailure(result)) {
- args.errorCallback(result.error);
- } else {
- args.successCallback();
- }
- });
+ NFCPeer.prototype.setReceiveNDEFListener = function() {
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_P2P);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- };
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'listener',
+ type: types_.FUNCTION
+ }
+ ]);
- NFCPeer.prototype.setReceiveNDEFListener = function() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_P2P);
+ var listener = function(msg) {
+ var data = undefined;
+ if ('onsuccess' === msg.action && _my_id === msg.id) {
+ data = new tizen.NDEFMessage(toRecordsArray(msg.records));
+ }
+ args.listener(data);
+ };
- var args = validator_.validateArgs(arguments, [
- {
- name: 'listener',
- type: types_.FUNCTION
- }
- ]);
+ var result = native_.callSync('NFCPeer_setReceiveNDEFListener', { id: _my_id });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var listener = function(msg) {
- var data = undefined;
- if ('onsuccess' === msg.action && _my_id === msg.id) {
- data = new tizen.NDEFMessage(toRecordsArray(msg.records));
- }
- args.listener(data);
+ native_.addListener(RECEIVE_NDEF_LISTENER, listener);
+ return;
};
- var result = native_.callSync('NFCPeer_setReceiveNDEFListener', {'id' : _my_id});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- native_.addListener(RECEIVE_NDEF_LISTENER, listener);
- return;
- };
-
- NFCPeer.prototype.unsetReceiveNDEFListener = function() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_P2P);
+ NFCPeer.prototype.unsetReceiveNDEFListener = function() {
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.NFC_P2P);
- native_.removeListener(RECEIVE_NDEF_LISTENER);
+ native_.removeListener(RECEIVE_NDEF_LISTENER);
- var result = native_.callSync('NFCPeer_unsetReceiveNDEFListener', {'id' : _my_id});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('NFCPeer_unsetReceiveNDEFListener', { id: _my_id });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return;
- };
+ return;
+ };
- Object.defineProperties(this, {
- isConnected: {
- enumerable: true,
- set: function() {},
- get: isConnectedGetter
- }
- });
+ Object.defineProperties(this, {
+ isConnected: {
+ enumerable: true,
+ set: function() {},
+ get: isConnectedGetter
+ }
+ });
}
var toByteArray = function(array, max_size, nullable) {
- var resultArray = [];
- if (type_.isNullOrUndefined(array) && nullable === true)
- return resultArray;
+ var resultArray = [];
+ if (type_.isNullOrUndefined(array) && nullable === true) return resultArray;
- var convertedArray = converter_.toArray(array);
- var len = convertedArray.length;
+ var convertedArray = converter_.toArray(array);
+ var len = convertedArray.length;
- if (len > max_size)
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- for (var i = 0; i < len; i++) {
- resultArray.push(converter_.toOctet(convertedArray[i]));
- }
- return resultArray;
+ if (len > max_size) throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ for (var i = 0; i < len; i++) {
+ resultArray.push(converter_.toOctet(convertedArray[i]));
+ }
+ return resultArray;
};
var isArrayOfType = function(array, type) {
- for (var i = 0; i < array.length; i++) {
- if (!(array[i] instanceof type))
- return false;
- }
- return true;
+ for (var i = 0; i < array.length; i++) {
+ if (!(array[i] instanceof type)) return false;
+ }
+ return true;
};
//////////////////NDEFMessage /////////////////
@@ -1347,174 +1403,193 @@ var isArrayOfType = function(array, type) {
//};
tizen.NDEFMessage = function(data) {
- validator_.isConstructorCall(this, tizen.NDEFMessage);
- var records_ = [];
- try {
- if (arguments.length >= 1) {
- if (type_.isArray(data)) {
- if (isArrayOfType(data, tizen.NDEFRecord)) {
- records_ = data;
- } else {
- var raw_data_ = toByteArray(data);
- var result = native_.callSync(
- 'NDEFMessage_constructor', {
- 'rawData': raw_data_,
- 'rawDataSize' : raw_data_.length
- }
- );
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- var records_array = result.result.records;
- for (var i = 0; i < records_array.length; i++) {
- records_.push(new tizen.NDEFRecord(records_array[i].tnf,
- records_array[i].type, records_array[i].payload,
- records_array[i].id));
- }
- }
- } else {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
- }
- } catch (e) {
- //constructor call failed - empty object should be created
- records_ = undefined;
- }
-
- var recordsSetter = function(data) {
- if (type_.isArray(data)) {
- // Do not check type of array elements - allow all arrays
- //if ( isArrayOfType(data, tizen.NDEFRecord) ) {
- records_ = data;
- //}
- }
- };
-
- Object.defineProperties(this, {
- recordCount: { enumerable: true,
- set: function() {},
- get: function() { return records_ ? records_.length : undefined;}},
- records: { enumerable: true,
- set: recordsSetter,
- get: function() {return records_;}}
- });
+ validator_.isConstructorCall(this, tizen.NDEFMessage);
+ var records_ = [];
+ try {
+ if (arguments.length >= 1) {
+ if (type_.isArray(data)) {
+ if (isArrayOfType(data, tizen.NDEFRecord)) {
+ records_ = data;
+ } else {
+ var raw_data_ = toByteArray(data);
+ var result = native_.callSync('NDEFMessage_constructor', {
+ rawData: raw_data_,
+ rawDataSize: raw_data_.length
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ var records_array = result.result.records;
+ for (var i = 0; i < records_array.length; i++) {
+ records_.push(
+ new tizen.NDEFRecord(
+ records_array[i].tnf,
+ records_array[i].type,
+ records_array[i].payload,
+ records_array[i].id
+ )
+ );
+ }
+ }
+ } else {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+ }
+ } catch (e) {
+ //constructor call failed - empty object should be created
+ records_ = undefined;
+ }
+
+ var recordsSetter = function(data) {
+ if (type_.isArray(data)) {
+ // Do not check type of array elements - allow all arrays
+ //if ( isArrayOfType(data, tizen.NDEFRecord) ) {
+ records_ = data;
+ //}
+ }
+ };
+
+ Object.defineProperties(this, {
+ recordCount: {
+ enumerable: true,
+ set: function() {},
+ get: function() {
+ return records_ ? records_.length : undefined;
+ }
+ },
+ records: {
+ enumerable: true,
+ set: recordsSetter,
+ get: function() {
+ return records_;
+ }
+ }
+ });
};
tizen.NDEFMessage.prototype.toByte = function() {
- var result = native_.callSync(
- 'NDEFMessage_toByte', {
- 'records' : this.records,
- 'recordsSize' : this.recordCount
- }
- );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- return toByteArray(result.result.bytes);
+ var result = native_.callSync('NDEFMessage_toByte', {
+ records: this.records,
+ recordsSize: this.recordCount
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ return toByteArray(result.result.bytes);
};
//helper for inherited object constructors /////////////////////////////////////////////
-function InternalData() {
-}
+function InternalData() {}
//////////////////NDEFRecord /////////////////
tizen.NDEFRecord = function(first, type, payload, id) {
- var tnf_ = undefined;
- var typ_ = undefined;
- var payload_ = undefined;
- var id_ = undefined;
- //if it is inherited call, then ignore validation
- if (!(first instanceof InternalData)) {
- validator_.isConstructorCall(this, tizen.NDEFRecord);
- try {
- if (arguments.length >= 1) {
- if (type_.isArray(first)) {
- var raw_data_ = toByteArray(first);
- var result = native_.callSync(
- 'NDEFRecord_constructor', {
- 'rawData': raw_data_,
- 'rawDataSize' : raw_data_.length
- }
- );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- tnf_ = converter_.toLong(result.result.tnf);
- typ_ = toByteArray(result.result.type, 255);
- payload_ = toByteArray(result.result.payload, Math.pow(2, 32) - 1);
- id_ = toByteArray(result.result.id, 255);
- } else if (arguments.length >= 3) {
- tnf_ = converter_.toLong(first);
- typ_ = toByteArray(type, 255);
- payload_ = toByteArray(payload, Math.pow(2, 32) - 1);
- id_ = toByteArray(id, 255, true, []);
- }
- } else {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
- } catch (e) {
- //constructor call failed - empty object should be created
- tnf_ = undefined;
- typ_ = undefined;
- payload_ = undefined;
- id_ = undefined;
- }
- }
-
- Object.defineProperties(this, {
- tnf: {value: tnf_, writable: false, enumerable: true},
- type: {value: typ_, writable: false, enumerable: true},
- id: {value: id_, writable: false, enumerable: true},
- payload: {value: payload_, writable: false, enumerable: true}
- });
+ var tnf_ = undefined;
+ var typ_ = undefined;
+ var payload_ = undefined;
+ var id_ = undefined;
+ //if it is inherited call, then ignore validation
+ if (!(first instanceof InternalData)) {
+ validator_.isConstructorCall(this, tizen.NDEFRecord);
+ try {
+ if (arguments.length >= 1) {
+ if (type_.isArray(first)) {
+ var raw_data_ = toByteArray(first);
+ var result = native_.callSync('NDEFRecord_constructor', {
+ rawData: raw_data_,
+ rawDataSize: raw_data_.length
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ tnf_ = converter_.toLong(result.result.tnf);
+ typ_ = toByteArray(result.result.type, 255);
+ payload_ = toByteArray(result.result.payload, Math.pow(2, 32) - 1);
+ id_ = toByteArray(result.result.id, 255);
+ } else if (arguments.length >= 3) {
+ tnf_ = converter_.toLong(first);
+ typ_ = toByteArray(type, 255);
+ payload_ = toByteArray(payload, Math.pow(2, 32) - 1);
+ id_ = toByteArray(id, 255, true, []);
+ }
+ } else {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+ } catch (e) {
+ //constructor call failed - empty object should be created
+ tnf_ = undefined;
+ typ_ = undefined;
+ payload_ = undefined;
+ id_ = undefined;
+ }
+ }
+
+ Object.defineProperties(this, {
+ tnf: { value: tnf_, writable: false, enumerable: true },
+ type: { value: typ_, writable: false, enumerable: true },
+ id: { value: id_, writable: false, enumerable: true },
+ payload: { value: payload_, writable: false, enumerable: true }
+ });
};
//////////////////NDEFRecordText /////////////////
tizen.NDEFRecordText = function(text, languageCode, encoding, internal_) {
- var text_ = undefined;
- var languageCode_ = undefined;
- var encoding_ = NDEFRecordTextEncoding[encoding] ?
- NDEFRecordTextEncoding[encoding] : NDEFRecordTextEncoding['UTF8'];
- try {
- if (arguments.length >= 2) {
- text_ = converter_.toString(text);
- languageCode_ = converter_.toString(languageCode);
-
- if (!type_.isNullOrUndefined(internal_) && (internal_ instanceof InternalRecordData)) {
- tizen.NDEFRecord.call(this, internal_.tnf, internal_.type, internal_.payload, internal_.id);
- } else {
- var result = native_.callSync(
- 'NDEFRecordText_constructor', {
- 'text': text_,
- 'languageCode' : languageCode_,
- 'encoding' : encoding_
+ var text_ = undefined;
+ var languageCode_ = undefined;
+ var encoding_ = NDEFRecordTextEncoding[encoding]
+ ? NDEFRecordTextEncoding[encoding]
+ : NDEFRecordTextEncoding['UTF8'];
+ try {
+ if (arguments.length >= 2) {
+ text_ = converter_.toString(text);
+ languageCode_ = converter_.toString(languageCode);
+
+ if (
+ !type_.isNullOrUndefined(internal_) &&
+ internal_ instanceof InternalRecordData
+ ) {
+ tizen.NDEFRecord.call(
+ this,
+ internal_.tnf,
+ internal_.type,
+ internal_.payload,
+ internal_.id
+ );
+ } else {
+ var result = native_.callSync('NDEFRecordText_constructor', {
+ text: text_,
+ languageCode: languageCode_,
+ encoding: encoding_
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ tizen.NDEFRecord.call(
+ this,
+ result.result.tnf,
+ result.result.type,
+ result.result.payload,
+ result.result.id
+ );
}
- );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ } else {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- tizen.NDEFRecord.call(this, result.result.tnf, result.result.type,
- result.result.payload, result.result.id);
- }
- } else {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
- } catch (e) {
- //constructor call failed - empty object should be created
- tizen.NDEFRecord.call(this);
- text_ = undefined;
- languageCode_ = undefined;
- encoding_ = undefined;
- }
-
- Object.defineProperties(this, {
- text: {value: text_, writable: false, enumerable: true},
- languageCode: {value: languageCode_, writable: false, enumerable: true},
- encoding: {value: encoding_, writable: false, enumerable: true}
- });
+ } catch (e) {
+ //constructor call failed - empty object should be created
+ tizen.NDEFRecord.call(this);
+ text_ = undefined;
+ languageCode_ = undefined;
+ encoding_ = undefined;
+ }
+
+ Object.defineProperties(this, {
+ text: { value: text_, writable: false, enumerable: true },
+ languageCode: { value: languageCode_, writable: false, enumerable: true },
+ encoding: { value: encoding_, writable: false, enumerable: true }
+ });
};
tizen.NDEFRecordText.prototype = new tizen.NDEFRecord(new InternalData());
@@ -1523,37 +1598,49 @@ tizen.NDEFRecordText.prototype.constructor = tizen.NDEFRecordText;
//////////////////NDEFRecordURI /////////////////
tizen.NDEFRecordURI = function(uri, internal_) {
- var uri_ = undefined;
- try {
- if (arguments.length >= 1) {
- uri_ = converter_.toString(uri);
-
- if (!type_.isNullOrUndefined(internal_) && (internal_ instanceof InternalRecordData)) {
- tizen.NDEFRecord.call(this, internal_.tnf, internal_.type, internal_.payload, internal_.id);
- } else {
- var result = native_.callSync(
- 'NDEFRecordURI_constructor', {
- 'uri': uri_
+ var uri_ = undefined;
+ try {
+ if (arguments.length >= 1) {
+ uri_ = converter_.toString(uri);
+
+ if (
+ !type_.isNullOrUndefined(internal_) &&
+ internal_ instanceof InternalRecordData
+ ) {
+ tizen.NDEFRecord.call(
+ this,
+ internal_.tnf,
+ internal_.type,
+ internal_.payload,
+ internal_.id
+ );
+ } else {
+ var result = native_.callSync('NDEFRecordURI_constructor', {
+ uri: uri_
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ tizen.NDEFRecord.call(
+ this,
+ result.result.tnf,
+ result.result.type,
+ result.result.payload,
+ result.result.id
+ );
}
- );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ } else {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- tizen.NDEFRecord.call(this, result.result.tnf, result.result.type,
- result.result.payload, result.result.id);
- }
- } else {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ } catch (e) {
+ //constructor call failed - empty object should be created
+ tizen.NDEFRecord.call(this);
+ uri_ = undefined;
}
- } catch (e) {
- //constructor call failed - empty object should be created
- tizen.NDEFRecord.call(this);
- uri_ = undefined;
- }
- Object.defineProperties(this, {
- uri: {value: uri_, writable: false, enumerable: true}
- });
+ Object.defineProperties(this, {
+ uri: { value: uri_, writable: false, enumerable: true }
+ });
};
tizen.NDEFRecordURI.prototype = new tizen.NDEFRecord(new InternalData());
@@ -1562,41 +1649,53 @@ tizen.NDEFRecordURI.prototype.constructor = tizen.NDEFRecordURI;
//////////////////NDEFRecordMedia /////////////////
tizen.NDEFRecordMedia = function(mimeType, data, internal_) {
- var mimeType_ = undefined;
- var data_ = undefined;
- try {
- if (arguments.length >= 2) {
- mimeType_ = converter_.toString(mimeType);
-
- if (!type_.isNullOrUndefined(internal_) && (internal_ instanceof InternalRecordData)) {
- tizen.NDEFRecord.call(this, internal_.tnf, internal_.type, internal_.payload, internal_.id);
- } else {
- data_ = toByteArray(data, Math.pow(2, 32) - 1);
- var result = native_.callSync(
- 'NDEFRecordMedia_constructor', {
- 'mimeType': mimeType_,
- 'data': data_,
- 'dataSize': data_.length
+ var mimeType_ = undefined;
+ var data_ = undefined;
+ try {
+ if (arguments.length >= 2) {
+ mimeType_ = converter_.toString(mimeType);
+
+ if (
+ !type_.isNullOrUndefined(internal_) &&
+ internal_ instanceof InternalRecordData
+ ) {
+ tizen.NDEFRecord.call(
+ this,
+ internal_.tnf,
+ internal_.type,
+ internal_.payload,
+ internal_.id
+ );
+ } else {
+ data_ = toByteArray(data, Math.pow(2, 32) - 1);
+ var result = native_.callSync('NDEFRecordMedia_constructor', {
+ mimeType: mimeType_,
+ data: data_,
+ dataSize: data_.length
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ tizen.NDEFRecord.call(
+ this,
+ result.result.tnf,
+ result.result.type,
+ result.result.payload,
+ result.result.id
+ );
}
- );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ } else {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
}
- tizen.NDEFRecord.call(this, result.result.tnf, result.result.type,
- result.result.payload, result.result.id);
- }
- } else {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ } catch (e) {
+ //constructor call failed - empty object should be created
+ tizen.NDEFRecord.call(this);
+ mimeType_ = undefined;
}
- } catch (e) {
- //constructor call failed - empty object should be created
- tizen.NDEFRecord.call(this);
- mimeType_ = undefined;
- }
- Object.defineProperties(this, {
- mimeType: {value: mimeType_, writable: false, enumerable: true}
- });
+ Object.defineProperties(this, {
+ mimeType: { value: mimeType_, writable: false, enumerable: true }
+ });
};
tizen.NDEFRecordMedia.prototype = new tizen.NDEFRecord(new InternalData());
diff --git a/src/notification/notification_api.js b/src/notification/notification_api.js
index 8e186f1e..6679ab3c 100644
--- a/src/notification/notification_api.js
+++ b/src/notification/notification_api.js
@@ -24,258 +24,263 @@ var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
function convertColorToInt(rgbaColor) {
- var color = rgbaColor.length === 7 ? rgbaColor + 'ff' : rgbaColor;
- var isLengthOk = color.length === 9;
- var isHash = color.substr(0, 1) === '#';
- var hex = '0123456789abcdefABCDEF';
- var isHex = true;
- var c = color.replace('#', '');
-
- for (var i = 0; i < c.length; i++) {
- if (hex.indexOf(c[i]) < 0) {
- isHex = false;
+ var color = rgbaColor.length === 7 ? rgbaColor + 'ff' : rgbaColor;
+ var isLengthOk = color.length === 9;
+ var isHash = color.substr(0, 1) === '#';
+ var hex = '0123456789abcdefABCDEF';
+ var isHex = true;
+ var c = color.replace('#', '');
+
+ for (var i = 0; i < c.length; i++) {
+ if (hex.indexOf(c[i]) < 0) {
+ isHex = false;
+ }
}
- }
- if (!isLengthOk || !isHash || !isHex) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'invalid value');
- }
+ if (!isLengthOk || !isHash || !isHex) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'invalid value');
+ }
- return parseInt('0x' + c);
+ return parseInt('0x' + c);
}
var EditManager = function() {
- this.canEdit = false;
+ this.canEdit = false;
};
EditManager.prototype.allow = function() {
- this.canEdit = true;
+ this.canEdit = true;
};
EditManager.prototype.disallow = function() {
- this.canEdit = false;
+ this.canEdit = false;
};
var _edit = new EditManager();
var NotificationType = {
- STATUS: 'STATUS'
+ STATUS: 'STATUS'
};
var StatusNotificationType = {
- SIMPLE: 'SIMPLE',
- THUMBNAIL: 'THUMBNAIL',
- ONGOING: 'ONGOING',
- PROGRESS: 'PROGRESS'
+ SIMPLE: 'SIMPLE',
+ THUMBNAIL: 'THUMBNAIL',
+ ONGOING: 'ONGOING',
+ PROGRESS: 'PROGRESS'
};
var UserNotificationType = {
- SIMPLE: 'SIMPLE',
- THUMBNAIL: 'THUMBNAIL',
- ONGOING: 'ONGOING',
- PROGRESS: 'PROGRESS'
+ SIMPLE: 'SIMPLE',
+ THUMBNAIL: 'THUMBNAIL',
+ ONGOING: 'ONGOING',
+ PROGRESS: 'PROGRESS'
};
var NotificationProgressType = {
- PERCENTAGE: 'PERCENTAGE',
- BYTE: 'BYTE'
+ PERCENTAGE: 'PERCENTAGE',
+ BYTE: 'BYTE'
};
var LEDCustomFlags = {
- LED_CUSTOM_DUTY_ON: 'LED_CUSTOM_DUTY_ON',
- LED_CUSTOM_DEFAULT: 'LED_CUSTOM_DEFAULT'
+ LED_CUSTOM_DUTY_ON: 'LED_CUSTOM_DUTY_ON',
+ LED_CUSTOM_DEFAULT: 'LED_CUSTOM_DEFAULT'
};
function NotificationManager() {}
-
NotificationManager.prototype.post = function(notification) {
- var args = validator_.validateArgs(arguments, [
- {name: 'notification', type: types_.PLATFORM_OBJECT, values: Notification}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'notification', type: types_.PLATFORM_OBJECT, values: Notification }
+ ]);
+
+ if (args.notification instanceof tizen.StatusNotification) {
+ utils_.warn(
+ 'DEPRECATION WARNING: StatusNotification is deprecated since Tizen 4.0. ' +
+ 'Use UserNotification instead.'
+ );
+ }
- if (args.notification instanceof tizen.StatusNotification) {
- utils_.warn('DEPRECATION WARNING: StatusNotification is deprecated since Tizen 4.0. Use UserNotification instead.');
- }
+ var data = {
+ //add marker for UserNotification implementation
+ newImpl: args.notification instanceof tizen.UserNotification,
+ notification: args.notification
+ };
- var data = {
- //add marker for UserNotification implementation
- newImpl: (args.notification instanceof tizen.UserNotification),
- notification: args.notification
- };
-
- var result = native_.callSync('NotificationManager_post', data);
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- _edit.allow();
- var d = native_.getResultObject(result);
- notification.id = d.id;
- notification.postedTime = new Date(d.postedTime) || new Date();
- notification.type = d.type || NotificationType.STATUS;
- _edit.disallow();
+ var result = native_.callSync('NotificationManager_post', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ _edit.allow();
+ var d = native_.getResultObject(result);
+ notification.id = d.id;
+ notification.postedTime = new Date(d.postedTime) || new Date();
+ notification.type = d.type || NotificationType.STATUS;
+ _edit.disallow();
};
NotificationManager.prototype.update = function(notification) {
- var args = validator_.validateArgs(arguments, [
- {name: 'notification', type: types_.PLATFORM_OBJECT, values: Notification}
- ]);
-
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- }
- if (!args.notification.id) {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
- }
-
- if (args.notification instanceof tizen.StatusNotification) {
- utils_.warn('DEPRECATION WARNING: StatusNotification is deprecated since Tizen 4.0. Use UserNotification instead.');
- }
-
- var data = {
- //add marker for UserNotification implementation
- newImpl: (args.notification instanceof tizen.UserNotification),
- notification: args.notification
- };
+ var args = validator_.validateArgs(arguments, [
+ { name: 'notification', type: types_.PLATFORM_OBJECT, values: Notification }
+ ]);
+
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
+ if (!args.notification.id) {
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
+ }
- var result = native_.callSync('NotificationManager_update', data);
+ if (args.notification instanceof tizen.StatusNotification) {
+ utils_.warn(
+ 'DEPRECATION WARNING: StatusNotification is deprecated since Tizen 4.0. ' +
+ 'Use UserNotification instead.'
+ );
+ }
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var data = {
+ //add marker for UserNotification implementation
+ newImpl: args.notification instanceof tizen.UserNotification,
+ notification: args.notification
+ };
+
+ var result = native_.callSync('NotificationManager_update', data);
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
NotificationManager.prototype.remove = function(id) {
- var args = validator_.validateArgs(arguments, [
- {name: 'id', type: types_.STRING}
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'id', type: types_.STRING }]);
- if (!arguments.length || !(parseInt(arguments[0]) > 0)) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- }
+ if (!arguments.length || !(parseInt(arguments[0]) > 0)) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
- var data = {
- id: args.id
- };
+ var data = {
+ id: args.id
+ };
- var result = native_.callSync('NotificationManager_remove', data);
+ var result = native_.callSync('NotificationManager_remove', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
NotificationManager.prototype.removeAll = function() {
- var result = native_.callSync('NotificationManager_removeAll', {});
+ var result = native_.callSync('NotificationManager_removeAll', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
NotificationManager.prototype.get = function(id) {
- var args = validator_.validateArgs(arguments, [
- {name: 'id', type: types_.STRING}
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'id', type: types_.STRING }]);
- utils_.warn('DEPRECATION WARNING: get() is deprecated since Tizen 4.0. Use getNotification() instead.');
+ utils_.warn(
+ 'DEPRECATION WARNING: get() is deprecated since Tizen 4.0. ' +
+ 'Use getNotification() instead.'
+ );
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- }
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
- var data = {
- id: args.id
- };
+ var data = {
+ id: args.id
+ };
- var result = native_.callSync('NotificationManager_get', data);
+ var result = native_.callSync('NotificationManager_get', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var n = native_.getResultObject(result);
+ var n = native_.getResultObject(result);
- _edit.allow();
- var returnObject = new StatusNotification(n.statusType, n.title, n);
- _edit.disallow();
+ _edit.allow();
+ var returnObject = new StatusNotification(n.statusType, n.title, n);
+ _edit.disallow();
- return returnObject;
+ return returnObject;
};
NotificationManager.prototype.getNotification = function(id) {
- var args = validator_.validateArgs(arguments, [
- {name: 'id', type: types_.STRING}
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'id', type: types_.STRING }]);
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- }
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
- var data = {
- //add marker for UserNotification implementation
- newImpl: true,
- id: args.id
- };
+ var data = {
+ //add marker for UserNotification implementation
+ newImpl: true,
+ id: args.id
+ };
- var result = native_.callSync('NotificationManager_get', data);
+ var result = native_.callSync('NotificationManager_get', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var n = native_.getResultObject(result);
+ var n = native_.getResultObject(result);
- _edit.allow();
- var returnObject = new UserNotification(n.userType, n.title, n);
- _edit.disallow();
+ _edit.allow();
+ var returnObject = new UserNotification(n.userType, n.title, n);
+ _edit.disallow();
- return returnObject;
+ return returnObject;
};
NotificationManager.prototype.getAll = function() {
- utils_.warn('DEPRECATION WARNING: getAll() is deprecated since Tizen 4.0. Use getAllNotifications() instead.');
+ utils_.warn(
+ 'DEPRECATION WARNING: getAll() is deprecated since Tizen 4.0. ' +
+ 'Use getAllNotifications() instead.'
+ );
- var result = native_.callSync('NotificationManager_getAll', {});
+ var result = native_.callSync('NotificationManager_getAll', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var n = native_.getResultObject(result);
- var notifications = [];
+ var n = native_.getResultObject(result);
+ var notifications = [];
- _edit.allow();
- for (var i = 0; i < n.length; i++) {
- notifications.push(new StatusNotification(n[i].statusType, n[i].title, n[i]));
- }
- _edit.disallow();
+ _edit.allow();
+ for (var i = 0; i < n.length; i++) {
+ notifications.push(new StatusNotification(n[i].statusType, n[i].title, n[i]));
+ }
+ _edit.disallow();
- return notifications;
+ return notifications;
};
NotificationManager.prototype.getAllNotifications = function() {
- var result = native_.callSync('NotificationManager_getAll', {
- //add marker for UserNotification implementation
- newImpl: true
+ var result = native_.callSync('NotificationManager_getAll', {
+ //add marker for UserNotification implementation
+ newImpl: true
});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var n = native_.getResultObject(result);
- var notifications = [];
+ var n = native_.getResultObject(result);
+ var notifications = [];
- _edit.allow();
- for (var i = 0; i < n.length; i++) {
- notifications.push(new UserNotification(n[i].userType, n[i].title, n[i]));
- }
- _edit.disallow();
+ _edit.allow();
+ for (var i = 0; i < n.length; i++) {
+ notifications.push(new UserNotification(n[i].userType, n[i].title, n[i]));
+ }
+ _edit.disallow();
- return notifications;
+ return notifications;
};
/**
@@ -286,899 +291,978 @@ NotificationManager.prototype.getAllNotifications = function() {
* @param color String
* @param flags Array
*/
-NotificationManager.prototype.playLEDCustomEffect = function(timeOn, timeOff, color, flags) {
- var args = validator_.validateArgs(arguments, [
- {name: 'timeOn', type: types_.LONG},
- {name: 'timeOff', type: types_.LONG},
- {name: 'color', type: types_.STRING},
- {name: 'flags', type: types_.ARRAY, values: types_.STRING}
- ]);
-
- for (var i = 0; i < args.flags.length; ++i) {
- if (Object.keys(LEDCustomFlags).indexOf(args.flags[i]) < 0) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'invalid value');
+NotificationManager.prototype.playLEDCustomEffect = function(
+ timeOn,
+ timeOff,
+ color,
+ flags
+) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'timeOn', type: types_.LONG },
+ { name: 'timeOff', type: types_.LONG },
+ { name: 'color', type: types_.STRING },
+ { name: 'flags', type: types_.ARRAY, values: types_.STRING }
+ ]);
+
+ for (var i = 0; i < args.flags.length; ++i) {
+ if (Object.keys(LEDCustomFlags).indexOf(args.flags[i]) < 0) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'invalid value'
+ );
+ }
}
- }
- args.color = convertColorToInt(args.color);
- var result = native_.callSync('NotificationManager_playLEDCustomEffect', args);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ args.color = convertColorToInt(args.color);
+ var result = native_.callSync('NotificationManager_playLEDCustomEffect', args);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
/**
* Stops the custom effect of the service LED that is located to the front of a device.
*/
NotificationManager.prototype.stopLEDCustomEffect = function() {
- var result = native_.callSync('NotificationManager_stopLEDCustomEffect');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('NotificationManager_stopLEDCustomEffect');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
NotificationManager.prototype.saveNotificationAsTemplate = function(name, notification) {
- var args = validator_.validateArgs(arguments, [
- {name: 'name', type: types_.STRING},
- {name: 'notification', type: types_.PLATFORM_OBJECT, values: Notification}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'name', type: types_.STRING },
+ { name: 'notification', type: types_.PLATFORM_OBJECT, values: Notification }
+ ]);
- //add marker for UserNotification implementation
- args.newImpl = (args.notification instanceof tizen.UserNotification);
+ //add marker for UserNotification implementation
+ args.newImpl = args.notification instanceof tizen.UserNotification;
- var result = native_.callSync('NotificationManager_saveNotificationAsTemplate', args);
+ var result = native_.callSync('NotificationManager_saveNotificationAsTemplate', args);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
NotificationManager.prototype.createNotificationFromTemplate = function(name) {
- var args = validator_.validateArgs(arguments, [
- {name: 'name', type: types_.STRING}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'name', type: types_.STRING }
+ ]);
- if (!arguments.length) {
- throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
- }
+ if (!arguments.length) {
+ throw new WebAPIException(WebAPIException.NOT_FOUND_ERR);
+ }
- var result = native_.callSync('NotificationManager_createNotificationFromTemplate', args);
+ var result = native_.callSync(
+ 'NotificationManager_createNotificationFromTemplate',
+ args
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var n = native_.getResultObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var n = native_.getResultObject(result);
- _edit.allow();
- var returnObject = new UserNotification(n.userType, n.title, n);
- _edit.disallow();
+ _edit.allow();
+ var returnObject = new UserNotification(n.userType, n.title, n);
+ _edit.disallow();
- return returnObject;
+ return returnObject;
};
var _checkProgressValue = function(v, _progressType) {
- if ((_progressType === NotificationProgressType.PERCENTAGE && (v >= 0 && v <= 100))
- || (_progressType === NotificationProgressType.BYTE &&
- converter_.toUnsignedLong(v) >= 0)) {
- return true;
- }
- return false;
+ if (
+ (_progressType === NotificationProgressType.PERCENTAGE && (v >= 0 && v <= 100)) ||
+ (_progressType === NotificationProgressType.BYTE &&
+ converter_.toUnsignedLong(v) >= 0)
+ ) {
+ return true;
+ }
+ return false;
};
var _checkDetailInfo = function(v) {
- if (type_.isNull(v)) {
- return true;
- }
- if (!type_.isArray(v)) {
- return false;
- }
- for (var i = 0; i < v.length; ++i) {
- if (!(v[i] instanceof tizen.NotificationDetailInfo)) {
- return false;
+ if (type_.isNull(v)) {
+ return true;
+ }
+ if (!type_.isArray(v)) {
+ return false;
+ }
+ for (var i = 0; i < v.length; ++i) {
+ if (!(v[i] instanceof tizen.NotificationDetailInfo)) {
+ return false;
+ }
}
- }
- return true;
+ return true;
};
var _setDetailInfo = function(v) {
- var _d = [];
- for (var i = 0; i < v.length; ++i) {
- _d.push(new tizen.NotificationDetailInfo(v[i].mainText, v[i].subText || null));
- }
- return _d;
+ var _d = [];
+ for (var i = 0; i < v.length; ++i) {
+ _d.push(new tizen.NotificationDetailInfo(v[i].mainText, v[i].subText || null));
+ }
+ return _d;
};
var _checkStringArray = function(v) {
- if (type_.isNull(v)) {
- return true;
- }
- if (!type_.isArray(v)) {
- return false;
- }
- for (var i = 0; i < v.length; ++i) {
- if (!type_.isString(v[i])) {
- return false;
+ if (type_.isNull(v)) {
+ return true;
+ }
+ if (!type_.isArray(v)) {
+ return false;
}
- }
- return true;
+ for (var i = 0; i < v.length; ++i) {
+ if (!type_.isString(v[i])) {
+ return false;
+ }
+ }
+ return true;
};
var _isHex = function(v) {
- return v.length === 7 && v.substr(0, 1) === '#' && (/^([0-9A-Fa-f]{2})+$/).test(v.substr(1, 7));
+ return (
+ v.length === 7 &&
+ v.substr(0, 1) === '#' &&
+ /^([0-9A-Fa-f]{2})+$/.test(v.substr(1, 7))
+ );
};
-
function NotificationInitDict(data) {
- var _iconPath = null;
- var _soundPath = null;
- var _vibration = false;
- var _appControl = null;
- var _appId = null;
- var _progressType = NotificationProgressType.PERCENTAGE;
- var _progressValue = null;
- var _number = null;
- var _subIconPath = null;
- var _detailInfo = [];
- var _ledColor = null;
- var _ledOnPeriod = 0;
- var _ledOffPeriod = 0;
- var _backgroundImagePath = null;
- var _thumbnails = [];
-
-
- Object.defineProperties(this, {
- iconPath: {
- get: function() {
- return _iconPath;
- },
- set: function(v) {
- _iconPath = type_.isString(v) || type_.isNull(v) ? v : _iconPath;
- },
- enumerable: true
- },
- soundPath: {
- get: function() {
- return _soundPath;
- },
- set: function(v) {
- _soundPath = type_.isString(v) || type_.isNull(v) ? v : _soundPath;
- },
- enumerable: true
- },
- vibration: {
- get: function() {
- return _vibration;
- },
- set: function(v) {
- _vibration = type_.isBoolean(v) ? v : _vibration;
- },
- enumerable: true
- },
- appControl: {
- get: function() {
- return _appControl;
- },
- set: function(v) {
- _appControl = _edit.canEdit && v
- ? new tizen.ApplicationControl(v.operation, v.uri || null, v.mime || null, v.category
- || null, v.data || [])
- : v instanceof tizen.ApplicationControl || type_.isNull(v) ? v : _appControl;
- },
- enumerable: true
- },
- appId: {
- get: function() {
- return _appId;
- },
- set: function(v) {
- _appId = type_.isString(v) && !(/\s/.test(v)) || type_.isNull(v) ? v : _appId;
- },
- enumerable: true
- },
- progressType: {
- get: function() {
- return _progressType;
- },
- set: function(v) {
- _progressType = Object.keys(NotificationProgressType).indexOf(v) >= 0 ? v : _progressType;
- },
- enumerable: true
- },
- progressValue: {
- get: function() {
- if (null === _progressValue) {
- return _progressValue;
+ var _iconPath = null;
+ var _soundPath = null;
+ var _vibration = false;
+ var _appControl = null;
+ var _appId = null;
+ var _progressType = NotificationProgressType.PERCENTAGE;
+ var _progressValue = null;
+ var _number = null;
+ var _subIconPath = null;
+ var _detailInfo = [];
+ var _ledColor = null;
+ var _ledOnPeriod = 0;
+ var _ledOffPeriod = 0;
+ var _backgroundImagePath = null;
+ var _thumbnails = [];
+
+ Object.defineProperties(this, {
+ iconPath: {
+ get: function() {
+ return _iconPath;
+ },
+ set: function(v) {
+ _iconPath = type_.isString(v) || type_.isNull(v) ? v : _iconPath;
+ },
+ enumerable: true
+ },
+ soundPath: {
+ get: function() {
+ return _soundPath;
+ },
+ set: function(v) {
+ _soundPath = type_.isString(v) || type_.isNull(v) ? v : _soundPath;
+ },
+ enumerable: true
+ },
+ vibration: {
+ get: function() {
+ return _vibration;
+ },
+ set: function(v) {
+ _vibration = type_.isBoolean(v) ? v : _vibration;
+ },
+ enumerable: true
+ },
+ appControl: {
+ get: function() {
+ return _appControl;
+ },
+ set: function(v) {
+ _appControl =
+ _edit.canEdit && v
+ ? new tizen.ApplicationControl(
+ v.operation,
+ v.uri || null,
+ v.mime || null,
+ v.category || null,
+ v.data || []
+ )
+ : v instanceof tizen.ApplicationControl || type_.isNull(v)
+ ? v
+ : _appControl;
+ },
+ enumerable: true
+ },
+ appId: {
+ get: function() {
+ return _appId;
+ },
+ set: function(v) {
+ _appId =
+ (type_.isString(v) && !/\s/.test(v)) || type_.isNull(v) ? v : _appId;
+ },
+ enumerable: true
+ },
+ progressType: {
+ get: function() {
+ return _progressType;
+ },
+ set: function(v) {
+ _progressType =
+ Object.keys(NotificationProgressType).indexOf(v) >= 0
+ ? v
+ : _progressType;
+ },
+ enumerable: true
+ },
+ progressValue: {
+ get: function() {
+ if (null === _progressValue) {
+ return _progressValue;
+ }
+
+ return _progressType === NotificationProgressType.PERCENTAGE
+ ? _progressValue * 100
+ : _progressValue;
+ },
+ set: function(v) {
+ if (type_.isNull(v)) {
+ _progressValue = v;
+ return;
+ }
+ if (_checkProgressValue(v, _progressType)) {
+ _progressValue =
+ _progressType === NotificationProgressType.PERCENTAGE
+ ? v / 100
+ : converter_.toUnsignedLong(v);
+ }
+ },
+ enumerable: true
+ },
+ number: {
+ get: function() {
+ return _number;
+ },
+ set: function(v) {
+ _number = type_.isNumber(v) || type_.isNull(v) ? v : _number;
+ },
+ enumerable: true
+ },
+ subIconPath: {
+ get: function() {
+ return _subIconPath;
+ },
+ set: function(v) {
+ _subIconPath = type_.isString(v) || type_.isNull(v) ? v : _subIconPath;
+ },
+ enumerable: true
+ },
+ detailInfo: {
+ get: function() {
+ return _detailInfo;
+ },
+ set: function(v) {
+ _detailInfo =
+ _edit.canEdit && v
+ ? _setDetailInfo(v)
+ : _checkDetailInfo(v)
+ ? v
+ : _detailInfo;
+ },
+ enumerable: true
+ },
+ ledColor: {
+ get: function() {
+ return _ledColor;
+ },
+ set: function(v) {
+ _ledColor =
+ (type_.isString(v) && _isHex(v)) || type_.isNull(v) ? v : _ledColor;
+ },
+ enumerable: true
+ },
+ ledOnPeriod: {
+ get: function() {
+ return _ledOnPeriod;
+ },
+ set: function(v) {
+ _ledOnPeriod = type_.isNumber(v) ? v : _ledOnPeriod;
+ },
+ enumerable: true
+ },
+ ledOffPeriod: {
+ get: function() {
+ return _ledOffPeriod;
+ },
+ set: function(v) {
+ _ledOffPeriod = type_.isNumber(v) ? v : _ledOffPeriod;
+ },
+ enumerable: true
+ },
+ backgroundImagePath: {
+ get: function() {
+ return _backgroundImagePath;
+ },
+ set: function(v) {
+ _backgroundImagePath =
+ type_.isString(v) || type_.isNull(v) ? v : _backgroundImagePath;
+ },
+ enumerable: true
+ },
+ thumbnails: {
+ get: function() {
+ return _thumbnails;
+ },
+ set: function(v) {
+ _thumbnails = _checkStringArray(v) ? v : _thumbnails;
+ },
+ enumerable: true
}
+ });
- return (_progressType === NotificationProgressType.PERCENTAGE)
- ? _progressValue * 100
- : _progressValue;
- },
- set: function(v) {
- if (type_.isNull(v)) {
- _progressValue = v;
- return;
- }
- if (_checkProgressValue(v, _progressType)) {
- _progressValue = (_progressType === NotificationProgressType.PERCENTAGE)
- ? v / 100
- : converter_.toUnsignedLong(v);
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
}
- },
- enumerable: true
- },
- number: {
- get: function() {
- return _number;
- },
- set: function(v) {
- _number = type_.isNumber(v) || type_.isNull(v) ? v : _number;
- },
- enumerable: true
- },
- subIconPath: {
- get: function() {
- return _subIconPath;
- },
- set: function(v) {
- _subIconPath = type_.isString(v) || type_.isNull(v) ? v : _subIconPath;
- },
- enumerable: true
- },
- detailInfo: {
- get: function() {
- return _detailInfo;
- },
- set: function(v) {
- _detailInfo = _edit.canEdit && v ? _setDetailInfo(v) : _checkDetailInfo(v) ? v : _detailInfo;
- },
- enumerable: true
- },
- ledColor: {
- get: function() {
- return _ledColor;
- },
- set: function(v) {
- _ledColor = (type_.isString(v) && _isHex(v)) || type_.isNull(v) ? v : _ledColor;
- },
- enumerable: true
- },
- ledOnPeriod: {
- get: function() {
- return _ledOnPeriod;
- },
- set: function(v) {
- _ledOnPeriod = type_.isNumber(v) ? v : _ledOnPeriod;
- },
- enumerable: true
- },
- ledOffPeriod: {
- get: function() {
- return _ledOffPeriod;
- },
- set: function(v) {
- _ledOffPeriod = type_.isNumber(v) ? v : _ledOffPeriod;
- },
- enumerable: true
- },
- backgroundImagePath: {
- get: function() {
- return _backgroundImagePath;
- },
- set: function(v) {
- _backgroundImagePath = type_.isString(v) || type_.isNull(v) ? v : _backgroundImagePath;
- },
- enumerable: true
- },
- thumbnails: {
- get: function() {
- return _thumbnails;
- },
- set: function(v) {
- _thumbnails = _checkStringArray(v) ? v : _thumbnails;
- },
- enumerable: true
}
- });
-
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
- }
- }
}
function Notification(data) {
- var _id;
- var _type = NotificationType.STATUS;
- var _postedTime;
- var _title;
- var _content = null;
-
- Object.defineProperties(this, {
- id: {
- get: function() {
- return _id;
- },
- set: function(v) {
- _id = _edit.canEdit && v ? v : _id;
- },
- enumerable: true
- },
- type: {
- get: function() {
- return _type;
- },
- set: function(v) {
- _type = _edit.canEdit
- ? converter_.toEnum(v, Object.keys(NotificationType), false)
- : _type;
- },
- enumerable: true
- },
- postedTime: {
- get: function() {
- return _postedTime;
- },
- set: function(v) {
- _postedTime = _edit.canEdit && v ? new Date(v) : _postedTime;
- },
- enumerable: true
- },
- title: {
- get: function() {
- return _title;
- },
- set: function(v) {
- _title = converter_.toString(v);
- },
- enumerable: true
- },
- content: {
- get: function() {
- return _content;
- },
- set: function(v) {
- _content = type_.isString(v) || type_.isNull(v) ? v : _content;
- },
- enumerable: true
- }
- });
+ var _id;
+ var _type = NotificationType.STATUS;
+ var _postedTime;
+ var _title;
+ var _content = null;
+
+ Object.defineProperties(this, {
+ id: {
+ get: function() {
+ return _id;
+ },
+ set: function(v) {
+ _id = _edit.canEdit && v ? v : _id;
+ },
+ enumerable: true
+ },
+ type: {
+ get: function() {
+ return _type;
+ },
+ set: function(v) {
+ _type = _edit.canEdit
+ ? converter_.toEnum(v, Object.keys(NotificationType), false)
+ : _type;
+ },
+ enumerable: true
+ },
+ postedTime: {
+ get: function() {
+ return _postedTime;
+ },
+ set: function(v) {
+ _postedTime = _edit.canEdit && v ? new Date(v) : _postedTime;
+ },
+ enumerable: true
+ },
+ title: {
+ get: function() {
+ return _title;
+ },
+ set: function(v) {
+ _title = converter_.toString(v);
+ },
+ enumerable: true
+ },
+ content: {
+ get: function() {
+ return _content;
+ },
+ set: function(v) {
+ _content = type_.isString(v) || type_.isNull(v) ? v : _content;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (data.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (data.hasOwnProperty(prop) && this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
function StatusNotification(statusType, title, notificationInitDict) {
- validator_.isConstructorCall(this, StatusNotification);
- type_.isObject(notificationInitDict) ?
- notificationInitDict.title = title :
- notificationInitDict = {title: title};
- NotificationInitDict.call(this, notificationInitDict);
- Notification.call(this, notificationInitDict);
-
- utils_.warn('DEPRECATION WARNING: StatusNotification is deprecated since Tizen 4.0. Use UserNotification instead.');
-
- var _statusType = (Object.keys(StatusNotificationType)).indexOf(statusType) >= 0
- ? statusType : StatusNotificationType.SIMPLE;
-
- Object.defineProperties(this, {
- statusType: {
- get: function() {
- return _statusType;
- },
- set: function(v) {
- _statusType = (Object.keys(StatusNotificationType)).indexOf(v) >= 0 && _edit.canEdit
- ? v : _statusType;
- },
- enumerable: true
- }
- });
+ validator_.isConstructorCall(this, StatusNotification);
+ type_.isObject(notificationInitDict)
+ ? (notificationInitDict.title = title)
+ : (notificationInitDict = { title: title });
+ NotificationInitDict.call(this, notificationInitDict);
+ Notification.call(this, notificationInitDict);
+
+ utils_.warn(
+ 'DEPRECATION WARNING: StatusNotification is deprecated since Tizen 4.0. ' +
+ 'Use UserNotification instead.'
+ );
+
+ var _statusType =
+ Object.keys(StatusNotificationType).indexOf(statusType) >= 0
+ ? statusType
+ : StatusNotificationType.SIMPLE;
+
+ Object.defineProperties(this, {
+ statusType: {
+ get: function() {
+ return _statusType;
+ },
+ set: function(v) {
+ _statusType =
+ Object.keys(StatusNotificationType).indexOf(v) >= 0 && _edit.canEdit
+ ? v
+ : _statusType;
+ },
+ enumerable: true
+ }
+ });
}
StatusNotification.prototype = new Notification();
StatusNotification.prototype.constructor = StatusNotification;
function NotificationDetailInfo(mainText, subText) {
- validator_.isConstructorCall(this, NotificationDetailInfo);
-
- var _mainText = type_.isString(mainText) ? mainText : '';
- var _subText = type_.isString(subText) ? subText : null;
-
- Object.defineProperties(this, {
- mainText: {
- get: function() {
- return _mainText;
- },
- set: function(v) {
- _mainText = type_.isString(v) ? v : _mainText;
- },
- enumerable: true
- },
- subText: {
- get: function() {
- return _subText;
- },
- set: function(v) {
- _subText = type_.isString(v) ? v : _subText;
- },
- enumerable: true
- }
- });
+ validator_.isConstructorCall(this, NotificationDetailInfo);
+
+ var _mainText = type_.isString(mainText) ? mainText : '';
+ var _subText = type_.isString(subText) ? subText : null;
+
+ Object.defineProperties(this, {
+ mainText: {
+ get: function() {
+ return _mainText;
+ },
+ set: function(v) {
+ _mainText = type_.isString(v) ? v : _mainText;
+ },
+ enumerable: true
+ },
+ subText: {
+ get: function() {
+ return _subText;
+ },
+ set: function(v) {
+ _subText = type_.isString(v) ? v : _subText;
+ },
+ enumerable: true
+ }
+ });
}
function TextContentsInitDict(data) {
- if (!this) return;
- var _progressType = NotificationProgressType.PERCENTAGE;
- var _progressValue = null;
- var _number = null;
- var _detailInfo = [];
- var _buttonsTexts = [];
- var _contentForOff = null;
-
- Object.defineProperties(this, {
- progressType: {
- get: function() {
- return _progressType;
- },
- set: function(v) {
- _progressType = Object.keys(NotificationProgressType).indexOf(v) >= 0 ? v : _progressType;
- },
- enumerable: true
- },
- progressValue: {
- get: function() {
- if (null === _progressValue) {
- return _progressValue;
+ if (!this) return;
+ var _progressType = NotificationProgressType.PERCENTAGE;
+ var _progressValue = null;
+ var _number = null;
+ var _detailInfo = [];
+ var _buttonsTexts = [];
+ var _contentForOff = null;
+
+ Object.defineProperties(this, {
+ progressType: {
+ get: function() {
+ return _progressType;
+ },
+ set: function(v) {
+ _progressType =
+ Object.keys(NotificationProgressType).indexOf(v) >= 0
+ ? v
+ : _progressType;
+ },
+ enumerable: true
+ },
+ progressValue: {
+ get: function() {
+ if (null === _progressValue) {
+ return _progressValue;
+ }
+
+ return _progressType === NotificationProgressType.PERCENTAGE
+ ? _progressValue * 100
+ : _progressValue;
+ },
+ set: function(v) {
+ if (type_.isNull(v)) {
+ _progressValue = v;
+ return;
+ }
+ if (_checkProgressValue(v, _progressType)) {
+ _progressValue =
+ _progressType === NotificationProgressType.PERCENTAGE
+ ? v / 100
+ : converter_.toUnsignedLong(v);
+ }
+ },
+ enumerable: true
+ },
+ eventsNumber: {
+ get: function() {
+ return _number;
+ },
+ set: function(v) {
+ _number = type_.isNumber(v) || type_.isNull(v) ? v : _number;
+ },
+ enumerable: true
+ },
+ detailInfo: {
+ get: function() {
+ return _detailInfo;
+ },
+ set: function(v) {
+ _detailInfo =
+ _edit.canEdit && v
+ ? _setDetailInfo(v)
+ : _checkDetailInfo(v)
+ ? v
+ : _detailInfo;
+ },
+ enumerable: true
+ },
+ buttonsTexts: {
+ get: function() {
+ return _buttonsTexts;
+ },
+ set: function(v) {
+ _buttonsTexts = _checkStringArray(v) ? v : _buttonsTexts;
+ },
+ enumerable: true
+ },
+ contentForOff: {
+ get: function() {
+ return _contentForOff;
+ },
+ set: function(v) {
+ _contentForOff =
+ type_.isString(v) || type_.isNull(v) ? v : _contentForOff;
+ },
+ enumerable: true
}
+ });
- return (_progressType === NotificationProgressType.PERCENTAGE)
- ? _progressValue * 100
- : _progressValue;
- },
- set: function(v) {
- if (type_.isNull(v)) {
- _progressValue = v;
- return;
- }
- if (_checkProgressValue(v, _progressType)) {
- _progressValue = (_progressType === NotificationProgressType.PERCENTAGE)
- ? v / 100
- : converter_.toUnsignedLong(v);
+ if (data instanceof _global.Object) {
+ this['progressType'] = data['progressType'];
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
}
- },
- enumerable: true
- },
- eventsNumber: {
- get: function() {
- return _number;
- },
- set: function(v) {
- _number = type_.isNumber(v) || type_.isNull(v) ? v : _number;
- },
- enumerable: true
- },
- detailInfo: {
- get: function() {
- return _detailInfo;
- },
- set: function(v) {
- _detailInfo = _edit.canEdit && v ? _setDetailInfo(v) : _checkDetailInfo(v) ? v : _detailInfo;
- },
- enumerable: true
- },
- buttonsTexts: {
- get: function() {
- return _buttonsTexts;
- },
- set: function(v) {
- _buttonsTexts = _checkStringArray(v) ? v : _buttonsTexts;
- },
- enumerable: true
- },
- contentForOff: {
- get: function() {
- return _contentForOff;
- },
- set: function(v) {
- _contentForOff = type_.isString(v) || type_.isNull(v) ? v : _contentForOff;
- },
- enumerable: true
- }
- });
-
- if (data instanceof _global.Object) {
- this['progressType'] = data['progressType'];
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
}
- }
}
function ImagesInitDict(data) {
- if (!this) return;
- var _iconPath = null;
- var _subIconPath = null;
- var _indicatorIconPath = null;
- var _lockScreenIconPath = null;
- var _buttonIconPaths = [];
- var _backgroundImagePath = null;
-
- Object.defineProperties(this, {
- iconPath: {
- get: function() {
- return _iconPath;
- },
- set: function(v) {
- _iconPath = type_.isString(v) || type_.isNull(v) ? v : _iconPath;
- },
- enumerable: true
- },
- subIconPath: {
- get: function() {
- return _subIconPath;
- },
- set: function(v) {
- _subIconPath = type_.isString(v) || type_.isNull(v) ? v : _subIconPath;
- },
- enumerable: true
- },
- indicatorIconPath: {
- get: function() {
- return _indicatorIconPath;
- },
- set: function(v) {
- _indicatorIconPath = type_.isString(v) || type_.isNull(v) ? v : _indicatorIconPath;
- },
- enumerable: true
- },
- lockScreenIconPath: {
- get: function() {
- return _lockScreenIconPath;
- },
- set: function(v) {
- _lockScreenIconPath = type_.isString(v) || type_.isNull(v) ? v : _lockScreenIconPath;
- },
- enumerable: true
- },
- buttonIconPaths: {
- get: function() {
- return _buttonIconPaths;
- },
- set: function(v) {
- _buttonIconPaths = _checkStringArray(v) ? v : _buttonIconPaths;
- },
- enumerable: true
- },
- backgroundImagePath: {
- get: function() {
- return _backgroundImagePath;
- },
- set: function(v) {
- _backgroundImagePath = type_.isString(v) || type_.isNull(v) ? v : _backgroundImagePath;
- },
- enumerable: true
- }
- });
+ if (!this) return;
+ var _iconPath = null;
+ var _subIconPath = null;
+ var _indicatorIconPath = null;
+ var _lockScreenIconPath = null;
+ var _buttonIconPaths = [];
+ var _backgroundImagePath = null;
+
+ Object.defineProperties(this, {
+ iconPath: {
+ get: function() {
+ return _iconPath;
+ },
+ set: function(v) {
+ _iconPath = type_.isString(v) || type_.isNull(v) ? v : _iconPath;
+ },
+ enumerable: true
+ },
+ subIconPath: {
+ get: function() {
+ return _subIconPath;
+ },
+ set: function(v) {
+ _subIconPath = type_.isString(v) || type_.isNull(v) ? v : _subIconPath;
+ },
+ enumerable: true
+ },
+ indicatorIconPath: {
+ get: function() {
+ return _indicatorIconPath;
+ },
+ set: function(v) {
+ _indicatorIconPath =
+ type_.isString(v) || type_.isNull(v) ? v : _indicatorIconPath;
+ },
+ enumerable: true
+ },
+ lockScreenIconPath: {
+ get: function() {
+ return _lockScreenIconPath;
+ },
+ set: function(v) {
+ _lockScreenIconPath =
+ type_.isString(v) || type_.isNull(v) ? v : _lockScreenIconPath;
+ },
+ enumerable: true
+ },
+ buttonIconPaths: {
+ get: function() {
+ return _buttonIconPaths;
+ },
+ set: function(v) {
+ _buttonIconPaths = _checkStringArray(v) ? v : _buttonIconPaths;
+ },
+ enumerable: true
+ },
+ backgroundImagePath: {
+ get: function() {
+ return _backgroundImagePath;
+ },
+ set: function(v) {
+ _backgroundImagePath =
+ type_.isString(v) || type_.isNull(v) ? v : _backgroundImagePath;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
function ThumbnailsInitDict(data) {
- if (!this) return;
- var _lockScreenThumbnailIconPath = null;
- var _thumbnailIconPath = null;
- var _thumbnails = [];
-
- Object.defineProperties(this, {
- lockScreenThumbnailIconPath: {
- get: function() {
- return _lockScreenThumbnailIconPath;
- },
- set: function(v) {
- _lockScreenThumbnailIconPath = type_.isString(v) || type_.isNull(v) ? v : _lockScreenThumbnailIconPath;
- },
- enumerable: true
- },
- thumbnailIconPath: {
- get: function() {
- return _thumbnailIconPath;
- },
- set: function(v) {
- _thumbnailIconPath = type_.isString(v) || type_.isNull(v) ? v : _thumbnailIconPath;
- },
- enumerable: true
- },
- thumbnails: {
- get: function() {
- return _thumbnails;
- },
- set: function(v) {
- _thumbnails = _checkStringArray(v) ? v : _thumbnails;
- },
- enumerable: true
- }
- });
+ if (!this) return;
+ var _lockScreenThumbnailIconPath = null;
+ var _thumbnailIconPath = null;
+ var _thumbnails = [];
+
+ Object.defineProperties(this, {
+ lockScreenThumbnailIconPath: {
+ get: function() {
+ return _lockScreenThumbnailIconPath;
+ },
+ set: function(v) {
+ _lockScreenThumbnailIconPath =
+ type_.isString(v) || type_.isNull(v)
+ ? v
+ : _lockScreenThumbnailIconPath;
+ },
+ enumerable: true
+ },
+ thumbnailIconPath: {
+ get: function() {
+ return _thumbnailIconPath;
+ },
+ set: function(v) {
+ _thumbnailIconPath =
+ type_.isString(v) || type_.isNull(v) ? v : _thumbnailIconPath;
+ },
+ enumerable: true
+ },
+ thumbnails: {
+ get: function() {
+ return _thumbnails;
+ },
+ set: function(v) {
+ _thumbnails = _checkStringArray(v) ? v : _thumbnails;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
function ActionsInitDict(data) {
- if (!this) return;
- var _soundPath = null;
- var _vibration = false;
- var _appControl = null;
- var _appId = null;
-
- Object.defineProperties(this, {
- soundPath: {
- get: function() {
- return _soundPath;
- },
- set: function(v) {
- _soundPath = type_.isString(v) || type_.isNull(v) ? v : _soundPath;
- },
- enumerable: true
- },
- vibration: {
- get: function() {
- return _vibration;
- },
- set: function(v) {
- _vibration = type_.isBoolean(v) ? v : _vibration;
- },
- enumerable: true
- },
- appControl: {
- get: function() {
- return _appControl;
- },
- set: function(v) {
- _appControl = _edit.canEdit && v
- ? new tizen.ApplicationControl(v.operation, v.uri || null, v.mime || null, v.category
- || null, v.data || [])
- : v instanceof tizen.ApplicationControl || type_.isNull(v) ? v : _appControl;
- },
- enumerable: true
- },
- appId: {
- get: function() {
- return _appId;
- },
- set: function(v) {
- _appId = type_.isString(v) && !(/\s/.test(v)) || type_.isNull(v) ? v : _appId;
- },
- enumerable: true
- }
- });
+ if (!this) return;
+ var _soundPath = null;
+ var _vibration = false;
+ var _appControl = null;
+ var _appId = null;
+
+ Object.defineProperties(this, {
+ soundPath: {
+ get: function() {
+ return _soundPath;
+ },
+ set: function(v) {
+ _soundPath = type_.isString(v) || type_.isNull(v) ? v : _soundPath;
+ },
+ enumerable: true
+ },
+ vibration: {
+ get: function() {
+ return _vibration;
+ },
+ set: function(v) {
+ _vibration = type_.isBoolean(v) ? v : _vibration;
+ },
+ enumerable: true
+ },
+ appControl: {
+ get: function() {
+ return _appControl;
+ },
+ set: function(v) {
+ _appControl =
+ _edit.canEdit && v
+ ? new tizen.ApplicationControl(
+ v.operation,
+ v.uri || null,
+ v.mime || null,
+ v.category || null,
+ v.data || []
+ )
+ : v instanceof tizen.ApplicationControl || type_.isNull(v)
+ ? v
+ : _appControl;
+ },
+ enumerable: true
+ },
+ appId: {
+ get: function() {
+ return _appId;
+ },
+ set: function(v) {
+ _appId =
+ (type_.isString(v) && !/\s/.test(v)) || type_.isNull(v) ? v : _appId;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
function GroupContentsInitDict(data) {
- if (!this) return;
- var _groupTitle = null;
- var _groupContent = null;
- var _groupContentForOff = null;
-
- Object.defineProperties(this, {
- groupTitle: {
- get: function() {
- return _groupTitle;
- },
- set: function(v) {
- _groupTitle = type_.isString(v) || type_.isNull(v) ? v : _groupTitle;
- },
- enumerable: true
- },
- groupContent: {
- get: function() {
- return _groupContent;
- },
- set: function(v) {
- _groupContent = type_.isString(v) || type_.isNull(v) ? v : _groupContent;
- },
- enumerable: true
- },
- groupContentForOff: {
- get: function() {
- return _groupContentForOff;
- },
- set: function(v) {
- _groupContentForOff = type_.isString(v) || type_.isNull(v) ? v : _groupContentForOff;
- },
- enumerable: true
- }
- });
+ if (!this) return;
+ var _groupTitle = null;
+ var _groupContent = null;
+ var _groupContentForOff = null;
+
+ Object.defineProperties(this, {
+ groupTitle: {
+ get: function() {
+ return _groupTitle;
+ },
+ set: function(v) {
+ _groupTitle = type_.isString(v) || type_.isNull(v) ? v : _groupTitle;
+ },
+ enumerable: true
+ },
+ groupContent: {
+ get: function() {
+ return _groupContent;
+ },
+ set: function(v) {
+ _groupContent = type_.isString(v) || type_.isNull(v) ? v : _groupContent;
+ },
+ enumerable: true
+ },
+ groupContentForOff: {
+ get: function() {
+ return _groupContentForOff;
+ },
+ set: function(v) {
+ _groupContentForOff =
+ type_.isString(v) || type_.isNull(v) ? v : _groupContentForOff;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
function LedsInitDict(data) {
- if (!this) return;
- var _ledColor = null;
- var _ledOnPeriod = 0;
- var _ledOffPeriod = 0;
-
- Object.defineProperties(this, {
- ledColor: {
- get: function() {
- return _ledColor;
- },
- set: function(v) {
- _ledColor = (type_.isString(v) && _isHex(v)) || type_.isNull(v) ? v : _ledColor;
- },
- enumerable: true
- },
- ledOnPeriod: {
- get: function() {
- return _ledOnPeriod;
- },
- set: function(v) {
- _ledOnPeriod = type_.isNumber(v) ? v : _ledOnPeriod;
- },
- enumerable: true
- },
- ledOffPeriod: {
- get: function() {
- return _ledOffPeriod;
- },
- set: function(v) {
- _ledOffPeriod = type_.isNumber(v) ? v : _ledOffPeriod;
- },
- enumerable: true
- }
- });
+ if (!this) return;
+ var _ledColor = null;
+ var _ledOnPeriod = 0;
+ var _ledOffPeriod = 0;
+
+ Object.defineProperties(this, {
+ ledColor: {
+ get: function() {
+ return _ledColor;
+ },
+ set: function(v) {
+ _ledColor =
+ (type_.isString(v) && _isHex(v)) || type_.isNull(v) ? v : _ledColor;
+ },
+ enumerable: true
+ },
+ ledOnPeriod: {
+ get: function() {
+ return _ledOnPeriod;
+ },
+ set: function(v) {
+ _ledOnPeriod = type_.isNumber(v) ? v : _ledOnPeriod;
+ },
+ enumerable: true
+ },
+ ledOffPeriod: {
+ get: function() {
+ return _ledOffPeriod;
+ },
+ set: function(v) {
+ _ledOffPeriod = type_.isNumber(v) ? v : _ledOffPeriod;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
function UserNotification(userType, title, notificationGroupedInitDict) {
- validator_.isConstructorCall(this, UserNotification);
- type_.isObject(notificationGroupedInitDict) ?
- notificationGroupedInitDict.title = title :
- notificationGroupedInitDict = {title: title};
- UserNotificationInitDict.call(this, notificationGroupedInitDict);
- Notification.call(this, notificationGroupedInitDict);
-
- this.textContents = new TextContentsInitDict(notificationGroupedInitDict.textContents);
- this.images = new ImagesInitDict(notificationGroupedInitDict.images);
- this.thumbnails = new ThumbnailsInitDict(notificationGroupedInitDict.thumbnails);
- this.actions = new ActionsInitDict(notificationGroupedInitDict.actions);
- this.leds = new LedsInitDict(notificationGroupedInitDict.leds);
- this.groupContents = new GroupContentsInitDict(notificationGroupedInitDict.groupContents);
-
- var _userType = (Object.keys(UserNotificationType)).indexOf(userType) >= 0
- ? userType : StatusNotificationType.SIMPLE;
-
- Object.defineProperties(this, {
- userType: {
- get: function() {
- return _userType;
- },
- set: function(v) {
- _userType = (Object.keys(StatusNotificationType)).indexOf(v) >= 0 && _edit.canEdit
- ? v : _userType;
- },
- enumerable: true
- }
- });
+ validator_.isConstructorCall(this, UserNotification);
+ type_.isObject(notificationGroupedInitDict)
+ ? (notificationGroupedInitDict.title = title)
+ : (notificationGroupedInitDict = { title: title });
+ UserNotificationInitDict.call(this, notificationGroupedInitDict);
+ Notification.call(this, notificationGroupedInitDict);
+
+ this.textContents = new TextContentsInitDict(
+ notificationGroupedInitDict.textContents
+ );
+ this.images = new ImagesInitDict(notificationGroupedInitDict.images);
+ this.thumbnails = new ThumbnailsInitDict(notificationGroupedInitDict.thumbnails);
+ this.actions = new ActionsInitDict(notificationGroupedInitDict.actions);
+ this.leds = new LedsInitDict(notificationGroupedInitDict.leds);
+ this.groupContents = new GroupContentsInitDict(
+ notificationGroupedInitDict.groupContents
+ );
+
+ var _userType =
+ Object.keys(UserNotificationType).indexOf(userType) >= 0
+ ? userType
+ : StatusNotificationType.SIMPLE;
+
+ Object.defineProperties(this, {
+ userType: {
+ get: function() {
+ return _userType;
+ },
+ set: function(v) {
+ _userType =
+ Object.keys(StatusNotificationType).indexOf(v) >= 0 && _edit.canEdit
+ ? v
+ : _userType;
+ },
+ enumerable: true
+ }
+ });
}
UserNotification.prototype = new Notification();
UserNotification.prototype.constructor = UserNotification;
function UserNotificationInitDict(data) {
- var _textContents = null;
- var _images = null;
- var _thumbnails = null;
- var _actions = null;
- var _groupContents = null;
- var _leds = null;
-
- Object.defineProperties(this, {
- textContents: {
- get: function() {
- return _textContents;
- },
- set: function(v) {
- _textContents = type_.isObject(v) || type_.isNull(v) ? v : _textContents;
- },
- enumerable: true
- },
- images: {
- get: function() {
- return _images;
- },
- set: function(v) {
- _images = type_.isObject(v) || type_.isNull(v) ? v : _images;
- },
- enumerable: true
- },
- thumbnails: {
- get: function() {
- return _thumbnails;
- },
- set: function(v) {
- _thumbnails = type_.isObject(v) || type_.isNull(v) ? v : _thumbnails;
- },
- enumerable: true
- },
- actions: {
- get: function() {
- return _actions;
- },
- set: function(v) {
- _actions = type_.isObject(v) || type_.isNull(v) ? v : _actions;
- },
- enumerable: true
- },
- groupContents: {
- get: function() {
- return _groupContents;
- },
- set: function(v) {
- _groupContents = type_.isObject(v) || type_.isNull(v) ? v : _groupContents;
- },
- enumerable: true
- },
- leds: {
- get: function() {
- return _leds;
- },
- set: function(v) {
- _leds = type_.isObject(v) || type_.isNull(v) ? v : _leds;
- },
- enumerable: true
- }
- });
+ var _textContents = null;
+ var _images = null;
+ var _thumbnails = null;
+ var _actions = null;
+ var _groupContents = null;
+ var _leds = null;
+
+ Object.defineProperties(this, {
+ textContents: {
+ get: function() {
+ return _textContents;
+ },
+ set: function(v) {
+ _textContents = type_.isObject(v) || type_.isNull(v) ? v : _textContents;
+ },
+ enumerable: true
+ },
+ images: {
+ get: function() {
+ return _images;
+ },
+ set: function(v) {
+ _images = type_.isObject(v) || type_.isNull(v) ? v : _images;
+ },
+ enumerable: true
+ },
+ thumbnails: {
+ get: function() {
+ return _thumbnails;
+ },
+ set: function(v) {
+ _thumbnails = type_.isObject(v) || type_.isNull(v) ? v : _thumbnails;
+ },
+ enumerable: true
+ },
+ actions: {
+ get: function() {
+ return _actions;
+ },
+ set: function(v) {
+ _actions = type_.isObject(v) || type_.isNull(v) ? v : _actions;
+ },
+ enumerable: true
+ },
+ groupContents: {
+ get: function() {
+ return _groupContents;
+ },
+ set: function(v) {
+ _groupContents =
+ type_.isObject(v) || type_.isNull(v) ? v : _groupContents;
+ },
+ enumerable: true
+ },
+ leds: {
+ get: function() {
+ return _leds;
+ },
+ set: function(v) {
+ _leds = type_.isObject(v) || type_.isNull(v) ? v : _leds;
+ },
+ enumerable: true
+ }
+ });
- if (data instanceof _global.Object) {
- for (var prop in data) {
- if (this.hasOwnProperty(prop)) {
- this[prop] = data[prop];
- }
+ if (data instanceof _global.Object) {
+ for (var prop in data) {
+ if (this.hasOwnProperty(prop)) {
+ this[prop] = data[prop];
+ }
+ }
}
- }
}
exports = new NotificationManager();
diff --git a/src/package/package_api.js b/src/package/package_api.js
index ce00dbab..fb89be00 100644
--- a/src/package/package_api.js
+++ b/src/package/package_api.js
@@ -25,260 +25,291 @@ var PACKAGE_INFO_LISTENER_ID = 'PackageInfoListener';
var PACKAGE_PROGRESS_LISTENER_ID = 'PackageProgressListener_';
function PackageInfoChangeCallback(result) {
- if (result.status == 'installed') {
- listener.oninstalled(new PackageInformation(result.info));
- } else if (result.status == 'updated') {
- listener.onupdated(new PackageInformation(result.info));
- } else if (result.status == 'uninstalled') {
- listener.onuninstalled(result.id);
- }
+ if (result.status == 'installed') {
+ listener.oninstalled(new PackageInformation(result.info));
+ } else if (result.status == 'updated') {
+ listener.onupdated(new PackageInformation(result.info));
+ } else if (result.status == 'uninstalled') {
+ listener.onuninstalled(result.id);
+ }
}
function PackageProgressCallback(result) {
- if (result.status == 'progress') {
- callbacks[result['progressCallbackId']].progressCallback.onprogress(
- result.id, result.progress);
- } else if (result.status == 'complete') {
- callbacks[result['progressCallbackId']].progressCallback.oncomplete(result.id);
- delete callbacks[result['progressCallbackId']];
- native_.removeListener(PACKAGE_PROGRESS_LISTENER_ID + result['progressCallbackId']);
- } else if (result.status == 'error') {
- var err = result['error'];
- if (err) {
- callbacks[result['progressCallbackId']].errorCallback(new WebAPIException(err));
- delete callbacks[result['progressCallbackId']];
- native_.removeListener(PACKAGE_PROGRESS_LISTENER_ID + result['progressCallbackId']);
+ if (result.status == 'progress') {
+ callbacks[result['progressCallbackId']].progressCallback.onprogress(
+ result.id,
+ result.progress
+ );
+ } else if (result.status == 'complete') {
+ callbacks[result['progressCallbackId']].progressCallback.oncomplete(result.id);
+ delete callbacks[result['progressCallbackId']];
+ native_.removeListener(
+ PACKAGE_PROGRESS_LISTENER_ID + result['progressCallbackId']
+ );
+ } else if (result.status == 'error') {
+ var err = result['error'];
+ if (err) {
+ callbacks[result['progressCallbackId']].errorCallback(
+ new WebAPIException(err)
+ );
+ delete callbacks[result['progressCallbackId']];
+ native_.removeListener(
+ PACKAGE_PROGRESS_LISTENER_ID + result['progressCallbackId']
+ );
+ }
}
- }
}
function nextCallbackId() {
- return callbackId++;
+ return callbackId++;
}
function SetReadOnlyProperty(obj, n, v) {
- if (arguments.length > 2)
- Object.defineProperty(
- obj, n, {value: v, writable: false, enumerable: true, configurable: true});
- else
- Object.defineProperty(
- obj, n, {writable: false, enumerable: true, configurable: true});
+ if (arguments.length > 2)
+ Object.defineProperty(obj, n, {
+ value: v,
+ writable: false,
+ enumerable: true,
+ configurable: true
+ });
+ else
+ Object.defineProperty(obj, n, {
+ writable: false,
+ enumerable: true,
+ configurable: true
+ });
}
function PackageInformation(obj) {
- var lastModified = obj.lastModified;
- obj.lastModified = new Date(lastModified);
-
- SetReadOnlyProperty(this, 'id', obj.id); // read only property
- SetReadOnlyProperty(this, 'name', obj.name); // read only property
- SetReadOnlyProperty(this, 'iconPath', obj.iconPath); // read only property
- SetReadOnlyProperty(this, 'version', obj.version); // read only property
- SetReadOnlyProperty(this, 'lastModified', obj.lastModified); // read only property
- SetReadOnlyProperty(this, 'author', obj.author); // read only property
- SetReadOnlyProperty(this, 'description', obj.description); // read only property
- SetReadOnlyProperty(this, 'appIds', obj.appIds); // read only property
-
- var totalSize;
- var dataSize;
-
- Object.defineProperty(this, 'totalSize', {
- enumerable: true,
- set: function() {},
- get: function() {
- if (undefined === totalSize) {
- var result = native_.callSync('PackageManager_getTotalSize', {id: this.id});
- if (native_.isSuccess(result)) {
- totalSize = native_.getResultObject(result);
- } else {
- totalSize = -1;
+ var lastModified = obj.lastModified;
+ obj.lastModified = new Date(lastModified);
+
+ SetReadOnlyProperty(this, 'id', obj.id); // read only property
+ SetReadOnlyProperty(this, 'name', obj.name); // read only property
+ SetReadOnlyProperty(this, 'iconPath', obj.iconPath); // read only property
+ SetReadOnlyProperty(this, 'version', obj.version); // read only property
+ SetReadOnlyProperty(this, 'lastModified', obj.lastModified); // read only property
+ SetReadOnlyProperty(this, 'author', obj.author); // read only property
+ SetReadOnlyProperty(this, 'description', obj.description); // read only property
+ SetReadOnlyProperty(this, 'appIds', obj.appIds); // read only property
+
+ var totalSize;
+ var dataSize;
+
+ Object.defineProperty(this, 'totalSize', {
+ enumerable: true,
+ set: function() {},
+ get: function() {
+ if (undefined === totalSize) {
+ var result = native_.callSync('PackageManager_getTotalSize', {
+ id: this.id
+ });
+ if (native_.isSuccess(result)) {
+ totalSize = native_.getResultObject(result);
+ } else {
+ totalSize = -1;
+ }
+ }
+ return totalSize;
}
- }
- return totalSize;
- }
- });
-
- Object.defineProperty(this, 'dataSize', {
- enumerable: true,
- set: function() {},
- get: function() {
- if (undefined === dataSize) {
- var result = native_.callSync('PackageManager_getDataSize', {id: this.id});
- if (native_.isSuccess(result)) {
- dataSize = native_.getResultObject(result);
- } else {
- dataSize = -1;
+ });
+
+ Object.defineProperty(this, 'dataSize', {
+ enumerable: true,
+ set: function() {},
+ get: function() {
+ if (undefined === dataSize) {
+ var result = native_.callSync('PackageManager_getDataSize', {
+ id: this.id
+ });
+ if (native_.isSuccess(result)) {
+ dataSize = native_.getResultObject(result);
+ } else {
+ dataSize = -1;
+ }
+ }
+ return dataSize;
}
- }
- return dataSize;
- }
- });
+ });
}
function PackageManager() {
- // constructor of PackageManager
+ // constructor of PackageManager
}
var PackageManagerInstall = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'packageFileURI', 'type': types_.STRING}, {
- 'name': 'progressCallback',
- 'type': types_.LISTENER,
- 'values': ['onprogress', 'oncomplete']
- },
- {
- 'name': 'errorCallback',
- 'type': types_.FUNCTION,
- 'optional': true,
- 'nullable': true
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'packageFileURI', type: types_.STRING },
+ {
+ name: 'progressCallback',
+ type: types_.LISTENER,
+ values: ['onprogress', 'oncomplete']
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var progressCallbackId = nextCallbackId();
- callbacks[progressCallbackId] = args;
+ var progressCallbackId = nextCallbackId();
+ callbacks[progressCallbackId] = args;
- var nativeParam = {
- 'packageFileURI': args.packageFileURI,
- 'progressCallbackId': progressCallbackId
- };
+ var nativeParam = {
+ packageFileURI: args.packageFileURI,
+ progressCallbackId: progressCallbackId
+ };
+
+ var result = native_.call('PackageManager_install', nativeParam, function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ delete callbacks[result['progressCallbackId']];
+ }
+ });
- var result = native_.call('PackageManager_install', nativeParam, function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- delete callbacks[result['progressCallbackId']];
+ delete callbacks[progressCallbackId];
+ throw native_.getErrorObject(result);
}
- });
- if (native_.isFailure(result)) {
- delete callbacks[progressCallbackId];
- throw native_.getErrorObject(result);
- }
-
- native_.addListener(
- PACKAGE_PROGRESS_LISTENER_ID + progressCallbackId, PackageProgressCallback);
+ native_.addListener(
+ PACKAGE_PROGRESS_LISTENER_ID + progressCallbackId,
+ PackageProgressCallback
+ );
};
PackageManager.prototype.install = function(packageFileURI, progressCallback) {
- PackageManagerInstall.apply(this, arguments);
+ PackageManagerInstall.apply(this, arguments);
};
var PackageManagerUninstall = function() {
- var args = validator_.validateArgs(arguments, [
- {'name': 'id', 'type': types_.STRING}, {
- 'name': 'progressCallback',
- 'type': types_.LISTENER,
- 'values': ['onprogress', 'oncomplete']
- },
- {
- 'name': 'errorCallback',
- 'type': types_.FUNCTION,
- 'optional': true,
- 'nullable': true
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'id', type: types_.STRING },
+ {
+ name: 'progressCallback',
+ type: types_.LISTENER,
+ values: ['onprogress', 'oncomplete']
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var progressCallbackId = nextCallbackId();
- callbacks[progressCallbackId] = args;
+ var progressCallbackId = nextCallbackId();
+ callbacks[progressCallbackId] = args;
- var nativeParam = {'id': args.id, 'progressCallbackId': progressCallbackId};
+ var nativeParam = { id: args.id, progressCallbackId: progressCallbackId };
+
+ var result = native_.call('PackageManager_uninstall', nativeParam, function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ delete callbacks[result['progressCallbackId']];
+ }
+ });
- var result = native_.call('PackageManager_uninstall', nativeParam, function(result) {
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- delete callbacks[result['progressCallbackId']];
+ delete callbacks[result['progressCallbackId']];
+ throw native_.getErrorObject(result);
}
- });
- if (native_.isFailure(result)) {
- delete callbacks[result['progressCallbackId']];
- throw native_.getErrorObject(result);
- }
-
- native_.addListener(
- PACKAGE_PROGRESS_LISTENER_ID + progressCallbackId, PackageProgressCallback);
+ native_.addListener(
+ PACKAGE_PROGRESS_LISTENER_ID + progressCallbackId,
+ PackageProgressCallback
+ );
};
PackageManager.prototype.uninstall = function(id, progressCallback) {
- PackageManagerUninstall.apply(this, arguments);
+ PackageManagerUninstall.apply(this, arguments);
};
PackageManager.prototype.getPackagesInfo = function(successCallback, errorCallback) {
- var args = validator_.validateArgs(arguments, [
- {'name': 'successCallback', 'type': types_.FUNCTION}, {
- 'name': 'errorCallback',
- 'type': types_.FUNCTION,
- 'optional': true,
- 'nullable': true
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'successCallback', type: types_.FUNCTION },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var result = native_.call('PackageManager_getPackagesInfo', {}, function(result) {
- if (native_.isSuccess(result)) {
- for (var i = 0; i < result.informationArray.length; i++) {
- result.informationArray[i] = new PackageInformation(result.informationArray[i]);
- }
- args.successCallback(result.informationArray);
- } else if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- }
- });
+ var result = native_.call('PackageManager_getPackagesInfo', {}, function(result) {
+ if (native_.isSuccess(result)) {
+ for (var i = 0; i < result.informationArray.length; i++) {
+ result.informationArray[i] = new PackageInformation(
+ result.informationArray[i]
+ );
+ }
+ args.successCallback(result.informationArray);
+ } else if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ }
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
PackageManager.prototype.getPackageInfo = function() {
- var args = validator_.validateArgs(
- arguments,
- [{'name': 'id', 'type': types_.STRING, 'optional': true, 'nullable': true}]);
-
- var nativeParam = {};
-
- if (args['id']) {
- nativeParam['id'] = args.id;
- }
-
- var result = native_.callSync('PackageManager_getPackageInfo', nativeParam);
- if (native_.isSuccess(result)) {
- return new PackageInformation(native_.getResultObject(result));
- } else {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'id', type: types_.STRING, optional: true, nullable: true }
+ ]);
+
+ var nativeParam = {};
+
+ if (args['id']) {
+ nativeParam['id'] = args.id;
+ }
+
+ var result = native_.callSync('PackageManager_getPackageInfo', nativeParam);
+ if (native_.isSuccess(result)) {
+ return new PackageInformation(native_.getResultObject(result));
+ } else {
+ throw native_.getErrorObject(result);
+ }
};
PackageManager.prototype.setPackageInfoEventListener = function(eventCallback) {
- var args = validator_.validateArgs(
- arguments, [{
- 'name': 'eventCallback',
- 'type': types_.LISTENER,
- 'values': ['oninstalled', 'onupdated', 'onuninstalled']
- }]);
-
- var result = native_.callSync('PackageManager_setPackageInfoEventListener', {});
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-
- if (!native_.isListenerSet(PACKAGE_INFO_LISTENER_ID)) {
- native_.addListener(PACKAGE_INFO_LISTENER_ID, PackageInfoChangeCallback);
- }
- listener = args.eventCallback;
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'eventCallback',
+ type: types_.LISTENER,
+ values: ['oninstalled', 'onupdated', 'onuninstalled']
+ }
+ ]);
+
+ var result = native_.callSync('PackageManager_setPackageInfoEventListener', {});
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+
+ if (!native_.isListenerSet(PACKAGE_INFO_LISTENER_ID)) {
+ native_.addListener(PACKAGE_INFO_LISTENER_ID, PackageInfoChangeCallback);
+ }
+ listener = args.eventCallback;
};
PackageManager.prototype.unsetPackageInfoEventListener = function() {
- var nativeParam = {};
+ var nativeParam = {};
- var result =
- native_.callSync('PackageManager_unsetPackageInfoEventListener', nativeParam);
+ var result = native_.callSync(
+ 'PackageManager_unsetPackageInfoEventListener',
+ nativeParam
+ );
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- if (native_.isListenerSet(PACKAGE_INFO_LISTENER_ID)) {
- native_.removeListener(PACKAGE_INFO_LISTENER_ID);
- }
+ if (native_.isListenerSet(PACKAGE_INFO_LISTENER_ID)) {
+ native_.removeListener(PACKAGE_INFO_LISTENER_ID);
+ }
};
exports = new PackageManager();
diff --git a/src/playerutil/playerutil_api.js b/src/playerutil/playerutil_api.js
index 41ca4abc..c7874570 100644
--- a/src/playerutil/playerutil_api.js
+++ b/src/playerutil/playerutil_api.js
@@ -20,39 +20,40 @@ var types = validator.Types;
var T = xwalk.utils.type;
var LatencyMode = {
- LOW: 'LOW',
- MID: 'MID',
- HIGH: 'HIGH',
+ LOW: 'LOW',
+ MID: 'MID',
+ HIGH: 'HIGH'
};
-function PlayerUtil() {
-}
+function PlayerUtil() {}
PlayerUtil.prototype.getLatencyMode = function() {
- var result = native.callSync('PlayerUtil_getLatencyMode', {});
+ var result = native.callSync('PlayerUtil_getLatencyMode', {});
- if (native.isSuccess(result)) {
- return native.getResultObject(result);
- } else {
- throw native.getErrorObject(result);
- }
+ if (native.isSuccess(result)) {
+ return native.getResultObject(result);
+ } else {
+ throw native.getErrorObject(result);
+ }
};
PlayerUtil.prototype.setLatencyMode = function() {
- var args = validator.validateMethod(arguments, [{
- name: 'latencyMode',
- type: types.ENUM,
- values: T.getValues(LatencyMode)
- }]);
-
- var callArgs = {};
- callArgs.latencyMode = args.latencyMode;
-
- var result = native.callSync('PlayerUtil_setLatencyMode', callArgs);
-
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'latencyMode',
+ type: types.ENUM,
+ values: T.getValues(LatencyMode)
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.latencyMode = args.latencyMode;
+
+ var result = native.callSync('PlayerUtil_setLatencyMode', callArgs);
+
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
// Exports
diff --git a/src/power/power_api.js b/src/power/power_api.js
index 769ccf1b..7a93b53d 100755
--- a/src/power/power_api.js
+++ b/src/power/power_api.js
@@ -22,34 +22,34 @@ var privUtils_ = xwalk.utils;
var T_ = xwalk.utils.type;
function ListenerManager(native, listenerName) {
- this.listener;
- this.native = native;
- this.listenerName = listenerName;
+ this.listener;
+ this.native = native;
+ this.listenerName = listenerName;
}
ListenerManager.prototype.onListenerCalled = function(msg) {
- this.listener(msg.previousState, msg.changedState);
+ this.listener(msg.previousState, msg.changedState);
};
ListenerManager.prototype.addListener = function(callback) {
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- this.listener = callback;
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ this.listener = callback;
};
ListenerManager.prototype.removeListener = function() {
- this.native.removeListener(this.listenerName);
- delete this.listener;
+ this.native.removeListener(this.listenerName);
+ delete this.listener;
};
ListenerManager.prototype.isListenerSet = function() {
- return this.native.isListenerSet(this.listenerName);
+ return this.native.isListenerSet(this.listenerName);
};
var screenStateChangeListener = new ListenerManager(native_, 'ScreenStateChangeListener');
var PowerResource = {
- 'SCREEN': 'SCREEN',
- 'CPU': 'CPU'
+ SCREEN: 'SCREEN',
+ CPU: 'CPU'
};
/**
@@ -57,10 +57,10 @@ var PowerResource = {
* @enum {string}
*/
var PowerScreenState = {
- 'SCREEN_OFF': 'SCREEN_OFF',
- 'SCREEN_DIM': 'SCREEN_DIM',
- 'SCREEN_NORMAL': 'SCREEN_NORMAL',
- 'SCREEN_BRIGHT': 'SCREEN_BRIGHT'
+ SCREEN_OFF: 'SCREEN_OFF',
+ SCREEN_DIM: 'SCREEN_DIM',
+ SCREEN_NORMAL: 'SCREEN_NORMAL',
+ SCREEN_BRIGHT: 'SCREEN_BRIGHT'
};
/**
@@ -68,7 +68,7 @@ var PowerScreenState = {
* @enum {string}
*/
var PowerCpuState = {
- 'CPU_AWAKE': 'CPU_AWAKE'
+ CPU_AWAKE: 'CPU_AWAKE'
};
var PowerState = Object.assign({}, PowerScreenState, PowerCpuState);
@@ -89,35 +89,45 @@ function PowerManager() {
* is desired to be.
*/
PowerManager.prototype.request = function() {
- var args = validator_.validateMethod(arguments, [{
- name: 'resource',
- type: types_.ENUM,
- values: T_.getValues(PowerResource)
- }, {
- name: 'state',
- type: types_.ENUM,
- values: T_.getValues(PowerState)
- }]);
-
- if (args.state === PowerScreenState.SCREEN_BRIGHT) {
- privUtils_.warn('DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed from next release.');
- }
-
- if ((args.resource === PowerResource.SCREEN && args.state === PowerCpuState.CPU_AWAKE) ||
- (args.resource === PowerResource.CPU && args.state !== PowerCpuState.CPU_AWAKE) ||
- (args.resource === PowerResource.SCREEN && args.state === PowerScreenState.SCREEN_OFF)) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var nativeParam = {
- resource: args.resource,
- state: args.state
- };
-
- var ret = native_.callSync('PowerManager_request', nativeParam);
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'resource',
+ type: types_.ENUM,
+ values: T_.getValues(PowerResource)
+ },
+ {
+ name: 'state',
+ type: types_.ENUM,
+ values: T_.getValues(PowerState)
+ }
+ ]);
+
+ if (args.state === PowerScreenState.SCREEN_BRIGHT) {
+ privUtils_.warn(
+ 'DEPRECATION WARNING: SCREEN_BRIGHT is deprecated and will be removed ' +
+ 'from next release.'
+ );
+ }
+
+ if (
+ (args.resource === PowerResource.SCREEN &&
+ args.state === PowerCpuState.CPU_AWAKE) ||
+ (args.resource === PowerResource.CPU && args.state !== PowerCpuState.CPU_AWAKE) ||
+ (args.resource === PowerResource.SCREEN &&
+ args.state === PowerScreenState.SCREEN_OFF)
+ ) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var nativeParam = {
+ resource: args.resource,
+ state: args.state
+ };
+
+ var ret = native_.callSync('PowerManager_request', nativeParam);
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
};
/**
@@ -126,20 +136,22 @@ PowerManager.prototype.request = function() {
* be removed.
*/
PowerManager.prototype.release = function() {
- var args = validator_.validateMethod(arguments, [{
- name: 'resource',
- type: types_.ENUM,
- values: T_.getValues(PowerResource)
- }]);
-
- var nativeParam = {
- resource: args.resource
- };
-
- var ret = native_.callSync('PowerManager_release', nativeParam);
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'resource',
+ type: types_.ENUM,
+ values: T_.getValues(PowerResource)
+ }
+ ]);
+
+ var nativeParam = {
+ resource: args.resource
+ };
+
+ var ret = native_.callSync('PowerManager_release', nativeParam);
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
};
/**
@@ -147,30 +159,30 @@ PowerManager.prototype.release = function() {
* @param {!function} listener The screen state change callback.
*/
PowerManager.prototype.setScreenStateChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'listener', type: types_.FUNCTION}
- ]);
-
- if (!screenStateChangeListener.isListenerSet()) {
- var ret = native_.callSync('PowerManager_setScreenStateChangeListener', {});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'listener', type: types_.FUNCTION }
+ ]);
+
+ if (!screenStateChangeListener.isListenerSet()) {
+ var ret = native_.callSync('PowerManager_setScreenStateChangeListener', {});
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
}
- }
- screenStateChangeListener.addListener(args.listener);
+ screenStateChangeListener.addListener(args.listener);
};
/**
* Unsets the screen state change callback and stop monitoring it.
*/
PowerManager.prototype.unsetScreenStateChangeListener = function() {
- if (screenStateChangeListener.isListenerSet()) {
- var ret = native_.callSync('PowerManager_unsetScreenStateChangeListener', {});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
+ if (screenStateChangeListener.isListenerSet()) {
+ var ret = native_.callSync('PowerManager_unsetScreenStateChangeListener', {});
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
}
- }
- screenStateChangeListener.removeListener();
+ screenStateChangeListener.removeListener();
};
/**
@@ -178,79 +190,86 @@ PowerManager.prototype.unsetScreenStateChangeListener = function() {
* @return {number} Current screen brightness value.
*/
PowerManager.prototype.getScreenBrightness = function() {
- var ret = native_.callSync('PowerManager_getScreenBrightness', {});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- } else {
- return native_.getResultObject(ret);
- }
-}
+ var ret = native_.callSync('PowerManager_getScreenBrightness', {});
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ } else {
+ return native_.getResultObject(ret);
+ }
+};
/**
* Sets the screen brightness level for an application, from 0 to 1.
* @param {!number} brightness The screen brightness value to set.
*/
PowerManager.prototype.setScreenBrightness = function() {
- var args = validator_.validateArgs(arguments, [
- {name: 'brightness', type: types_.DOUBLE}
- ]);
-
- if (args.brightness < 0 || args.brightness > 1) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
-
- var ret = native_.callSync('PowerManager_setScreenBrightness',
- {brightness: args.brightness});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
-}
+ var args = validator_.validateArgs(arguments, [
+ { name: 'brightness', type: types_.DOUBLE }
+ ]);
+
+ if (args.brightness < 0 || args.brightness > 1) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+
+ var ret = native_.callSync('PowerManager_setScreenBrightness', {
+ brightness: args.brightness
+ });
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
+};
/**
* Returns true if the screen is on.
* @return {boolean} true if screen is on.
*/
PowerManager.prototype.isScreenOn = function() {
- var ret = native_.callSync('PowerManager_isScreenOn', {});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- } else {
- return native_.getResultObject(ret);
- }
-}
+ var ret = native_.callSync('PowerManager_isScreenOn', {});
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ } else {
+ return native_.getResultObject(ret);
+ }
+};
/**
* Restores the screen brightness to the system default setting value.
*/
PowerManager.prototype.restoreScreenBrightness = function() {
- var ret = native_.callSync('PowerManager_restoreScreenBrightness', {});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
-}
+ var ret = native_.callSync('PowerManager_restoreScreenBrightness', {});
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
+};
/**
* Turns the screen on.
*/
PowerManager.prototype.turnScreenOn = function() {
- privUtils_.warn('DEPRECATION WARNING: turnScreenOn() is deprecated and will be removed from next release. Use request() instead.');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: turnScreenOn() is deprecated and will be removed from ' +
+ 'next release. Use request() instead.'
+ );
- var ret = native_.callSync('PowerManager_turnScreenOn', {});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
-}
+ var ret = native_.callSync('PowerManager_turnScreenOn', {});
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
+};
/**
* Turns the screen off.
*/
PowerManager.prototype.turnScreenOff = function() {
- privUtils_.warn('DEPRECATION WARNING: turnScreenOff() is deprecated and will be removed from next release. Use release() instead.');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: turnScreenOff() is deprecated and will be removed from ' +
+ 'next release. Use release() instead.'
+ );
- var ret = native_.callSync('PowerManager_turnScreenOff', {});
- if (native_.isFailure(ret)) {
- throw native_.getErrorObject(ret);
- }
-}
+ var ret = native_.callSync('PowerManager_turnScreenOff', {});
+ if (native_.isFailure(ret)) {
+ throw native_.getErrorObject(ret);
+ }
+};
-exports = new PowerManager(); \ No newline at end of file
+exports = new PowerManager();
diff --git a/src/ppm/ppm_api.js b/src/ppm/ppm_api.js
index 3193a7df..972b5818 100644
--- a/src/ppm/ppm_api.js
+++ b/src/ppm/ppm_api.js
@@ -14,64 +14,62 @@
* limitations under the License.
*/
-
var validator_ = xwalk.utils.validator;
var type_ = xwalk.utils.type;
var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
-function PPMManager() {
-}
+function PPMManager() {}
function RequestStatus(privilege, result_) {
Object.defineProperties(this, {
- privilege : {value: privilege, writable: false},
- result : {value: result_, writable: false}
+ privilege: { value: privilege, writable: false },
+ result: { value: result_, writable: false }
});
-};
+}
PPMManager.prototype.checkPermission = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'privilege', type: types_.STRING }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'privilege', type: types_.STRING }
+ ]);
- var callArgs = {
- privilege: args.privilege
- };
+ var callArgs = {
+ privilege: args.privilege
+ };
- var result = native_.callSync('PPMManager_checkPermission', callArgs);
+ var result = native_.callSync('PPMManager_checkPermission', callArgs);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return native_.getResultObject(result);
+ return native_.getResultObject(result);
};
PPMManager.prototype.checkPermissions = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'privileges', type: types_.ARRAY, values: types_.STRING }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'privileges', type: types_.ARRAY, values: types_.STRING }
+ ]);
- var callArgs = {
- privileges: args.privileges
- };
+ var callArgs = {
+ privileges: args.privileges
+ };
- var result = native_.callSync('PPMManager_checkPermissions', callArgs);
+ var result = native_.callSync('PPMManager_checkPermissions', callArgs);
- var data = [];
+ var data = [];
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- var obj = native_.getResultObject(result);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ var obj = native_.getResultObject(result);
- obj.forEach(function (o) {
- data.push({'privilege':o.privilege, 'type':o.type});
- });
- }
+ obj.forEach(function(o) {
+ data.push({ privilege: o.privilege, type: o.type });
+ });
+ }
- return data;
+ return data;
};
PPMManager.prototype.requestPermission = function() {
@@ -96,41 +94,41 @@ PPMManager.prototype.requestPermission = function() {
var result = native_.call('PPMManager_requestPermission', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
PPMManager.prototype.requestPermissions = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'privileges', type: types_.ARRAY, values: types_.STRING },
- { name: 'successCallback', type: types_.FUNCTION },
- { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
- ]);
-
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var data = [];
- var obj = native_.getResultObject(result);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'privileges', type: types_.ARRAY, values: types_.STRING },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
- obj.forEach(function (o) {
- data.push(new RequestStatus(o.privilege, o.result));
- });
- args.successCallback(data);
- }
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var data = [];
+ var obj = native_.getResultObject(result);
- var callArgs = {
- privileges: args.privileges
- };
+ obj.forEach(function(o) {
+ data.push(new RequestStatus(o.privilege, o.result));
+ });
+ args.successCallback(data);
+ }
+ };
- var result = native_.call('PPMManager_requestPermissions', callArgs, callback);
+ var callArgs = {
+ privileges: args.privileges
+ };
+
+ var result = native_.call('PPMManager_requestPermissions', callArgs, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
// Exports
-exports = new PPMManager(); \ No newline at end of file
+exports = new PPMManager();
diff --git a/src/preference/preference_api.js b/src/preference/preference_api.js
index 8a0ed15b..9f9d8211 100644
--- a/src/preference/preference_api.js
+++ b/src/preference/preference_api.js
@@ -14,189 +14,180 @@
* limitations under the License.
*/
-
var validator_ = xwalk.utils.validator;
var type_ = xwalk.utils.type;
var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
function PreferenceData(data) {
- Object.defineProperties(this, {
- key: {
- value: data.key,
- writable: false,
- enumerable: true
- },
- value: {
- value: data.value,
- writable: false,
- enumerable: true
- },
- });
+ Object.defineProperties(this, {
+ key: {
+ value: data.key,
+ writable: false,
+ enumerable: true
+ },
+ value: {
+ value: data.value,
+ writable: false,
+ enumerable: true
+ }
+ });
}
-function PreferenceManager() {
-}
+function PreferenceManager() {}
PreferenceManager.prototype.getAll = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'successCallback', type: types_.FUNCTION },
- { name: 'errorCallback', type: types_.FUNCTION, optional : true, nullable : true }
- ]);
-
- var callback = function(result) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
+ ]);
+
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ var array = [];
+ var objects = native_.getResultObject(result);
+
+ objects.forEach(function(d) {
+ array.push(new PreferenceData(d));
+ });
+
+ args.successCallback(array);
+ }
+ };
+
+ var result = native_.call('PreferenceManager_getAll', {}, callback);
if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- var array = [];
- var objects = native_.getResultObject(result);
-
- objects.forEach(function (d) {
- array.push(new PreferenceData(d));
- });
-
- args.successCallback(array);
+ throw native_.getErrorObject(result);
}
- };
-
- var result = native_.call('PreferenceManager_getAll', {}, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
};
PreferenceManager.prototype.setValue = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'key', type: types_.STRING },
- { name: 'value', type: types_.SIMPLE_TYPE }
- ]);
-
- var result = native_.callSync('PreferenceManager_setValue',
- {
- key: args.key,
- value: args.value
- }
- );
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'key', type: types_.STRING },
+ { name: 'value', type: types_.SIMPLE_TYPE }
+ ]);
+
+ var result = native_.callSync('PreferenceManager_setValue', {
+ key: args.key,
+ value: args.value
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
PreferenceManager.prototype.getValue = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'key', type: types_.STRING }
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'key', type: types_.STRING }]);
- var result = native_.callSync('PreferenceManager_getValue', { key: args.key });
+ var result = native_.callSync('PreferenceManager_getValue', { key: args.key });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- return native_.getResultObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ return native_.getResultObject(result);
+ }
};
PreferenceManager.prototype.remove = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'key', type: types_.STRING }
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'key', type: types_.STRING }]);
- var result = native_.callSync('PreferenceManager_remove', { key: args.key });
+ var result = native_.callSync('PreferenceManager_remove', { key: args.key });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
PreferenceManager.prototype.removeAll = function() {
- var result = native_.callSync('PreferenceManager_removeAll', {});
+ var result = native_.callSync('PreferenceManager_removeAll', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
PreferenceManager.prototype.exists = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'key', type: types_.STRING }
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'key', type: types_.STRING }]);
- var result = native_.callSync('PreferenceManager_exists', { key: args.key });
+ var result = native_.callSync('PreferenceManager_exists', { key: args.key });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- return native_.getResultObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ } else {
+ return native_.getResultObject(result);
+ }
};
var PREFERENCE_CHANGED_LISTENER = 'PREFERENCE_CHANGED';
function PreferenceChangedListener() {
- var that = this;
- this.appListener = function (result) {
- var data = native_.getResultObject(result);
- var key = data.key;
-
- if (that.instances[key]) {
- var listener = that.instances[key];
- if (type_.isFunction(listener)) {
- listener(new PreferenceData(data));
- }
- }
- };
+ var that = this;
+ this.appListener = function(result) {
+ var data = native_.getResultObject(result);
+ var key = data.key;
+
+ if (that.instances[key]) {
+ var listener = that.instances[key];
+ if (type_.isFunction(listener)) {
+ listener(new PreferenceData(data));
+ }
+ }
+ };
}
PreferenceChangedListener.prototype.instances = {};
PreferenceChangedListener.prototype.addListener = function(key, listener) {
- if (type_.isEmptyObject(this.instances)) {
- native_.addListener(PREFERENCE_CHANGED_LISTENER, this.appListener);
- }
+ if (type_.isEmptyObject(this.instances)) {
+ native_.addListener(PREFERENCE_CHANGED_LISTENER, this.appListener);
+ }
- this.instances[key] = listener;
+ this.instances[key] = listener;
};
PreferenceChangedListener.prototype.removeListener = function(key) {
- if (this.instances[key]) {
- delete this.instances[key];
- if (type_.isEmptyObject(this.instances)) {
- native_.removeListener(PREFERENCE_CHANGED_LISTENER);
+ if (this.instances[key]) {
+ delete this.instances[key];
+ if (type_.isEmptyObject(this.instances)) {
+ native_.removeListener(PREFERENCE_CHANGED_LISTENER);
+ }
}
- }
};
var _preferenceChangedListener = new PreferenceChangedListener();
PreferenceManager.prototype.setChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'key', type: types_.STRING },
- { name: 'listener', type: types_.FUNCTION }
- ]);
-
- var result = native_.callSync('PreferenceManager_setChangeListener', { key: args.key });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'key', type: types_.STRING },
+ { name: 'listener', type: types_.FUNCTION }
+ ]);
+
+ var result = native_.callSync('PreferenceManager_setChangeListener', {
+ key: args.key
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- _preferenceChangedListener.addListener(args.key, args.listener);
-}
+ _preferenceChangedListener.addListener(args.key, args.listener);
+};
PreferenceManager.prototype.unsetChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- { name: 'key', type: types_.STRING }
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'key', type: types_.STRING }]);
- var result = native_.callSync('PreferenceManager_unsetChangeListener', { key: args.key });
+ var result = native_.callSync('PreferenceManager_unsetChangeListener', {
+ key: args.key
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- _preferenceChangedListener.removeListener(args.key);
+ _preferenceChangedListener.removeListener(args.key);
};
// Exports
exports = new PreferenceManager();
-
diff --git a/src/push/push_api.js b/src/push/push_api.js
index 78d4113e..6bea2c9f 100644
--- a/src/push/push_api.js
+++ b/src/push/push_api.js
@@ -30,264 +30,273 @@ var listener2_4 = undefined;
var listener3_0 = undefined;
var listenerFunction = function(msg) {
- // try to call each listener
- listener2_4 && listener2_4(msg);
- listener3_0 && listener3_0(msg);
-}
+ // try to call each listener
+ listener2_4 && listener2_4(msg);
+ listener3_0 && listener3_0(msg);
+};
function PushMessage(dict) {
- for (var key in dict) {
- if (dict.hasOwnProperty(key)) {
- Object.defineProperty(this, key, {
- value: key === 'date' ? new Date(dict[key] * 1000) : dict[key],
- enumerable: true
- });
+ for (var key in dict) {
+ if (dict.hasOwnProperty(key)) {
+ Object.defineProperty(this, key, {
+ value: key === 'date' ? new Date(dict[key] * 1000) : dict[key],
+ enumerable: true
+ });
+ }
}
- }
- Object.freeze(this);
+ Object.freeze(this);
}
-
-
/**
* @constructor
*/
function PushManager() {
- if (!(this instanceof PushManager)) {
- throw new TypeError;
- }
+ if (!(this instanceof PushManager)) {
+ throw new TypeError();
+ }
}
PushManager.prototype.registerService = function() {
- privUtils_.warn('DEPRECATION WARNING: registerService() is deprecated and will be removed from next release. Use register() instead.');
- var data = validator.validateArgs(arguments, [
- {
- name: 'appControl',
- type: validator.Types.PLATFORM_OBJECT,
- values: tizen.ApplicationControl
- },
- {
- name: 'successCallback',
- type: validator.Types.FUNCTION
- },
- {
- name: 'errorCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ privUtils_.warn(
+ 'DEPRECATION WARNING: registerService() is deprecated and will be removed ' +
+ 'from next release. Use register() instead.'
+ );
+ var data = validator.validateArgs(arguments, [
+ {
+ name: 'appControl',
+ type: validator.Types.PLATFORM_OBJECT,
+ values: tizen.ApplicationControl
+ },
+ {
+ name: 'successCallback',
+ type: validator.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var ret = native.call('Push_registerService', {}, function(msg) {
- if (msg.error) {
- if (validatorType.isFunction(data.errorCallback)) {
- data.errorCallback(native.getErrorObject(msg));
- }
- } else {
- data.successCallback(msg.registrationId);
+ var ret = native.call('Push_registerService', {}, function(msg) {
+ if (msg.error) {
+ if (validatorType.isFunction(data.errorCallback)) {
+ data.errorCallback(native.getErrorObject(msg));
+ }
+ } else {
+ data.successCallback(msg.registrationId);
+ }
+ });
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
}
- });
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
};
PushManager.prototype.register = function() {
- var data = validator.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: validator.Types.FUNCTION
- },
- {
- name: 'errorCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ var data = validator.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: validator.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var ret = native.call('Push_registerApplication', {}, function(msg) {
- if (msg.error) {
- if (validatorType.isFunction(data.errorCallback)) {
- data.errorCallback(native.getErrorObject(msg));
- }
- } else {
- data.successCallback(msg.registrationId);
+ var ret = native.call('Push_registerApplication', {}, function(msg) {
+ if (msg.error) {
+ if (validatorType.isFunction(data.errorCallback)) {
+ data.errorCallback(native.getErrorObject(msg));
+ }
+ } else {
+ data.successCallback(msg.registrationId);
+ }
+ });
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
}
- });
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
};
PushManager.prototype.unregisterService = function() {
- privUtils_.warn('DEPRECATION WARNING: unregisterService() is deprecated and will be removed from next release. Use unregister() instead.');
- var data = validator.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- }
+ privUtils_.warn(
+ 'DEPRECATION WARNING: unregisterService() is deprecated and will be removed ' +
+ 'from next release. Use unregister() instead.'
+ );
+ var data = validator.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- var result = native.call('Push_unregisterService', {}, function(msg) {
- if (msg.error) {
- if (validatorType.isFunction(data.errorCallback)) {
- data.errorCallback(native.getErrorObject(msg));
- }
- } else if (validatorType.isFunction(data.successCallback)) {
- data.successCallback();
- }
- });
+ var result = native.call('Push_unregisterService', {}, function(msg) {
+ if (msg.error) {
+ if (validatorType.isFunction(data.errorCallback)) {
+ data.errorCallback(native.getErrorObject(msg));
+ }
+ } else if (validatorType.isFunction(data.successCallback)) {
+ data.successCallback();
+ }
+ });
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
PushManager.prototype.unregister = function() {
- var data = validator.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
- var result = native.call('Push_unregisterApplication', {}, function(msg) {
- if (msg.error) {
- if (validatorType.isFunction(data.errorCallback)) {
- data.errorCallback(native.getErrorObject(msg));
- }
- } else if (validatorType.isFunction(data.successCallback)) {
- data.successCallback();
- }
- });
+ var data = validator.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+ var result = native.call('Push_unregisterApplication', {}, function(msg) {
+ if (msg.error) {
+ if (validatorType.isFunction(data.errorCallback)) {
+ data.errorCallback(native.getErrorObject(msg));
+ }
+ } else if (validatorType.isFunction(data.successCallback)) {
+ data.successCallback();
+ }
+ });
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
PushManager.prototype.connectService = function(notificationCallback) {
- privUtils_.warn('DEPRECATION WARNING: connectService() is deprecated and will be removed from next release. Use connect() instead.');
- var data = validator.validateArgs(arguments, [
- {
- name: 'notificationCallback',
- type: validator.Types.FUNCTION
+ privUtils_.warn(
+ 'DEPRECATION WARNING: connectService() is deprecated and will be removed from ' +
+ 'next release. Use connect() instead.'
+ );
+ var data = validator.validateArgs(arguments, [
+ {
+ name: 'notificationCallback',
+ type: validator.Types.FUNCTION
+ }
+ ]);
+ var ret = native.callSync('Push_connectService', {});
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
}
- ]);
- var ret = native.callSync('Push_connectService', {});
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
- listener2_4 = function(msg) {
- data.notificationCallback(new PushMessage(msg.pushMessage));
- };
- native.addListener(NOTIFICATION_LISTENER, listenerFunction);
+ listener2_4 = function(msg) {
+ data.notificationCallback(new PushMessage(msg.pushMessage));
+ };
+ native.addListener(NOTIFICATION_LISTENER, listenerFunction);
};
PushManager.prototype.connect = function(notificationCallback) {
- var data = validator.validateArgs(arguments, [
- {
- name: 'stateChangeCallback',
- type: validator.Types.FUNCTION
- },
- {
- name: 'notificationCallback',
- type: validator.Types.FUNCTION
- },
- {
- name: 'errorCallback',
- type: validator.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
- var result = native.call('Push_connect', {}, function(msg) {
- // in case of error, call errorCallback
- if (msg.error) {
- if (validatorType.isFunction(data.errorCallback)) {
- data.errorCallback(native.getErrorObject(msg));
- }
- }
- });
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
- // in case of successfully connect, below listener would be called automatically
- native.addListener(STATE_LISTENER, function(msg) {
- if (msg.error) {
- if (validatorType.isFunction(data.errorCallback)) {
- data.errorCallback(native.getErrorObject(msg));
- }
- } else {
- data.stateChangeCallback(msg.state);
+ var data = validator.validateArgs(arguments, [
+ {
+ name: 'stateChangeCallback',
+ type: validator.Types.FUNCTION
+ },
+ {
+ name: 'notificationCallback',
+ type: validator.Types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: validator.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+ var result = native.call('Push_connect', {}, function(msg) {
+ // in case of error, call errorCallback
+ if (msg.error) {
+ if (validatorType.isFunction(data.errorCallback)) {
+ data.errorCallback(native.getErrorObject(msg));
+ }
+ }
+ });
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
}
- });
+ // in case of successfully connect, below listener would be called automatically
+ native.addListener(STATE_LISTENER, function(msg) {
+ if (msg.error) {
+ if (validatorType.isFunction(data.errorCallback)) {
+ data.errorCallback(native.getErrorObject(msg));
+ }
+ } else {
+ data.stateChangeCallback(msg.state);
+ }
+ });
- listener3_0 = function(msg) {
- data.notificationCallback(new PushMessage(msg.pushMessage));
- };
- native.addListener(NOTIFICATION_LISTENER, listenerFunction);
+ listener3_0 = function(msg) {
+ data.notificationCallback(new PushMessage(msg.pushMessage));
+ };
+ native.addListener(NOTIFICATION_LISTENER, listenerFunction);
};
PushManager.prototype.disconnectService = function() {
- privUtils_.warn('DEPRECATION WARNING: disconnectService() is deprecated and will be removed from next release. Use disconnect() instead.');
- var ret = native.callSync('Push_disconnectService', {});
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
- listener2_4 = undefined;
- native.removeListener(NOTIFICATION_LISTENER);
+ privUtils_.warn(
+ 'DEPRECATION WARNING: disconnectService() is deprecated and will be removed ' +
+ 'from next release. Use disconnect() instead.'
+ );
+ var ret = native.callSync('Push_disconnectService', {});
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
+ listener2_4 = undefined;
+ native.removeListener(NOTIFICATION_LISTENER);
};
PushManager.prototype.disconnect = function() {
- var ret = native.callSync('Push_disconnect', {});
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
- listener3_0 = undefined;
- native.removeListener(NOTIFICATION_LISTENER);
+ var ret = native.callSync('Push_disconnect', {});
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
+ listener3_0 = undefined;
+ native.removeListener(NOTIFICATION_LISTENER);
};
PushManager.prototype.getRegistrationId = function() {
- var ret = native.callSync('Push_getRegistrationId', {});
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
- return native.getResultObject(ret);
+ var ret = native.callSync('Push_getRegistrationId', {});
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
+ return native.getResultObject(ret);
};
PushManager.prototype.getUnreadNotifications = function() {
- var ret = native.callSync('Push_getUnreadNotifications', {});
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
+ var ret = native.callSync('Push_getUnreadNotifications', {});
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
};
PushManager.prototype.getPushMessage = function() {
-
- var ret = native.callSync('Push_getPushMessage', {});
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- } else {
- var message = native.getResultObject(ret);
- return message ? new PushMessage(message) : null;
- }
+ var ret = native.callSync('Push_getPushMessage', {});
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ } else {
+ var message = native.getResultObject(ret);
+ return message ? new PushMessage(message) : null;
+ }
};
exports = new PushManager();
diff --git a/src/radio/radio_api.js b/src/radio/radio_api.js
index beaba45c..92f04c27 100644
--- a/src/radio/radio_api.js
+++ b/src/radio/radio_api.js
@@ -22,29 +22,28 @@ var _listeners_FMRadioInterrupted;
var _listeners_AntennaChange;
var RadioState = {
- PLAYING : 'PLAYING',
- SCANNING : 'SCANNING',
- READY : 'READY'
+ PLAYING: 'PLAYING',
+ SCANNING: 'SCANNING',
+ READY: 'READY'
};
function FMRadioInterruptCallbackManager() {
-
this.oninterrupted;
this.oninterruptfinished;
-};
+}
FMRadioInterruptCallbackManager.prototype.FMRadioInterruptedCBSwitch = function(args) {
- if (args.action == 'oninterrupted')
- this.oninterrupted(args.reason);
- else
- this.oninterruptfinished();
+ if (args.action == 'oninterrupted') this.oninterrupted(args.reason);
+ else this.oninterruptfinished();
};
FMRadioInterruptCallbackManager.prototype.FMRadioInterruptedSet = function(oi, oif) {
this.oninterrupted = oi;
this.oninterruptfinished = oif;
- native_.addListener('FMRadio_Interrupted', this.FMRadioInterruptedCBSwitch
- .bind(this));
+ native_.addListener(
+ 'FMRadio_Interrupted',
+ this.FMRadioInterruptedCBSwitch.bind(this)
+ );
};
FMRadioInterruptCallbackManager.prototype.FMRadioInterruptedUnset = function() {
@@ -52,10 +51,8 @@ FMRadioInterruptCallbackManager.prototype.FMRadioInterruptedUnset = function() {
};
function FMRadioScanCallbackManager() {
-
this.radioScanCallback;
-
-};
+}
FMRadioScanCallbackManager.prototype.FMRadioScanCBSwitch = function(args) {
this.radioScanCallback(args.frequency);
@@ -63,8 +60,7 @@ FMRadioScanCallbackManager.prototype.FMRadioScanCBSwitch = function(args) {
FMRadioScanCallbackManager.prototype.FMRadioScanSet = function(cb) {
this.radioScanCallback = cb;
- native_.addListener('FMRadio_Onfrequencyfound',
- this.FMRadioScanCBSwitch.bind(this));
+ native_.addListener('FMRadio_Onfrequencyfound', this.FMRadioScanCBSwitch.bind(this));
};
FMRadioScanCallbackManager.prototype.FMRadioScanUnset = function() {
@@ -72,10 +68,8 @@ FMRadioScanCallbackManager.prototype.FMRadioScanUnset = function() {
};
function FMRadioAntennaChangeCallbackManager() {
-
this.onchanged;
-
-};
+}
FMRadioAntennaChangeCallbackManager.prototype.FMRadioAntennaCBSwitch = function(args) {
this.onchanged(args.connected);
@@ -83,8 +77,7 @@ FMRadioAntennaChangeCallbackManager.prototype.FMRadioAntennaCBSwitch = function(
FMRadioAntennaChangeCallbackManager.prototype.FMRadioAntennaChangeSet = function(cb) {
this.onchanged = cb;
- native_.addListener('FMRadio_Antenna', this.FMRadioAntennaCBSwitch
- .bind(this));
+ native_.addListener('FMRadio_Antenna', this.FMRadioAntennaCBSwitch.bind(this));
};
FMRadioAntennaChangeCallbackManager.prototype.FMRadioAntennaUnset = function() {
@@ -97,46 +90,40 @@ var scanCBmanager = new FMRadioScanCallbackManager();
function FMRadioManager() {
Object.defineProperties(this, {
- 'frequency' : {
- enumerable : true,
- get : frequencyGetter,
- set : function() {
- }
+ frequency: {
+ enumerable: true,
+ get: frequencyGetter,
+ set: function() {}
},
- 'frequencyUpperBound' : {
- enumerable : true,
- get : frequencyUpperGetter,
- set : function() {
- }
+ frequencyUpperBound: {
+ enumerable: true,
+ get: frequencyUpperGetter,
+ set: function() {}
},
- 'frequencyLowerBound' : {
- enumerable : true,
- get : frequencyLowerGetter,
- set : function() {
- }
+ frequencyLowerBound: {
+ enumerable: true,
+ get: frequencyLowerGetter,
+ set: function() {}
},
- 'signalStrength' : {
- enumerable : true,
- get : signalStrengthGetter,
- set : function() {
- }
+ signalStrength: {
+ enumerable: true,
+ get: signalStrengthGetter,
+ set: function() {}
},
- 'state' : {
- enumerable : true,
- get : radioStateGetter,
- set : function() {
- }
+ state: {
+ enumerable: true,
+ get: radioStateGetter,
+ set: function() {}
},
- 'isAntennaConnected' : {
- enumerable : true,
- get : isAntennaConnectedGetter,
- set : function() {
- }
+ isAntennaConnected: {
+ enumerable: true,
+ get: isAntennaConnectedGetter,
+ set: function() {}
},
- 'mute' : {
- enumerable : true,
- get : muteGetter,
- set : muteSetter
+ mute: {
+ enumerable: true,
+ get: muteGetter,
+ set: muteSetter
}
});
@@ -146,11 +133,12 @@ function FMRadioManager() {
}
function muteSetter() {
-
- var args = validator_.validateArgs(arguments, [ {
- name : 'mute',
- type : types_.BOOLEAN
- } ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'mute',
+ type: types_.BOOLEAN
+ }
+ ]);
native_.callSync('FMRadio_MuteSetter', args);
}
@@ -173,7 +161,6 @@ function FMRadioManager() {
}
function frequencyGetter() {
-
var ret = native_.callSync('FMRadio_FrequencyGetter');
return native_.getResultObject(ret);
@@ -189,48 +176,52 @@ function FMRadioManager() {
}
FMRadioManager.prototype.seekUp = function() {
- var args = validator_.validateArgs(arguments, [ {
- name : 'successCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }, {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- } ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
native_.call('FMRadio_SeekUp', {}, function(result) {
if (native_.isFailure(result)) {
- if (args.errorCallback)
- args.errorCallback(native_.getErrorObject(result));
+ if (args.errorCallback) args.errorCallback(native_.getErrorObject(result));
} else {
- if (args.successCallback)
- args.successCallback();
+ if (args.successCallback) args.successCallback();
}
});
-
};
FMRadioManager.prototype.start = function() {
- var args = validator_.validateArgs(arguments, [ {
- name : 'frequency',
- type : types_.DOUBLE,
- optional : true,
- nullable : true
- } ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'frequency',
+ type: types_.DOUBLE,
+ optional: true,
+ nullable: true
+ }
+ ]);
if (args.frequency) {
- if (args.frequency < this.frequencyLowerBound
- || args.frequency > this.frequencyUpperBound)
+ if (
+ args.frequency < this.frequencyLowerBound ||
+ args.frequency > this.frequencyUpperBound
+ )
throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Frequency out of bounds');
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Frequency out of bounds'
+ );
}
var result = native_.callSync('FMRadio_Start', {
- 'frequency' : args.frequency ? args.frequency
- : this.frequencyLowerBound
+ frequency: args.frequency ? args.frequency : this.frequencyLowerBound
});
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
@@ -238,48 +229,50 @@ FMRadioManager.prototype.start = function() {
};
FMRadioManager.prototype.seekDown = function() {
- var args = validator_.validateArgs(arguments, [ {
- name : 'successCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }, {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- } ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
native_.call('FMRadio_SeekDown', {}, function(result) {
if (native_.isFailure(result)) {
- if (args.errorCallback)
- args.errorCallback(native_.getErrorObject(result));
+ if (args.errorCallback) args.errorCallback(native_.getErrorObject(result));
} else {
- if (args.successCallback)
- args.successCallback();
+ if (args.successCallback) args.successCallback();
}
});
};
FMRadioManager.prototype.scanStart = function() {
- var args = validator_.validateArgs(arguments, [ {
- name : 'radioScanCallback',
- type : types_.LISTENER,
- values : [ 'onfrequencyfound', 'onfinished' ]
- }, {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- } ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'radioScanCallback',
+ type: types_.LISTENER,
+ values: ['onfrequencyfound', 'onfinished']
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
scanCBmanager.FMRadioScanSet(args.radioScanCallback.onfrequencyfound);
native_.call('FMRadio_ScanStart', {}, function(result) {
if (native_.isFailure(result)) {
- if (args.errorCallback)
- args.errorCallback(native_.getErrorObject(result));
-
+ if (args.errorCallback) args.errorCallback(native_.getErrorObject(result));
} else {
scanCBmanager.FMRadioScanUnset();
args.radioScanCallback.onfinished(result.frequencies);
@@ -295,39 +288,42 @@ FMRadioManager.prototype.stop = function() {
};
FMRadioManager.prototype.scanStop = function() {
- var args = validator_.validateArgs(arguments, [ {
- name : 'successCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }, {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- } ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
native_.call('FMRadio_ScanStop', {}, function(result) {
if (native_.isFailure(result)) {
- if (args.errorCallback)
- args.errorCallback(native_.getErrorObject(result));
+ if (args.errorCallback) args.errorCallback(native_.getErrorObject(result));
} else {
-
args.successCallback();
-
}
});
};
FMRadioManager.prototype.setFMRadioInterruptedListener = function() {
-
- var args = validator_.validateArgs(arguments, [ {
- name : 'interruptCallback',
- type : types_.LISTENER,
- values : [ 'oninterrupted', 'oninterruptfinished' ]
- } ]);
- interruptedCBmanager.FMRadioInterruptedSet(args.interruptCallback.oninterrupted,
- args.interruptCallback.oninterruptfinished);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'interruptCallback',
+ type: types_.LISTENER,
+ values: ['oninterrupted', 'oninterruptfinished']
+ }
+ ]);
+ interruptedCBmanager.FMRadioInterruptedSet(
+ args.interruptCallback.oninterrupted,
+ args.interruptCallback.oninterruptfinished
+ );
var ret = native_.callSync('FMRadio_SetFMRadioInterruptedListener');
if (native_.isFailure(ret)) {
@@ -336,7 +332,6 @@ FMRadioManager.prototype.setFMRadioInterruptedListener = function() {
};
FMRadioManager.prototype.unsetFMRadioInterruptedListener = function() {
-
interruptedCBmanager.FMRadioInterruptedUnset();
var ret = native_.callSync('FMRadio_UnsetFMRadioInterruptedListener');
if (native_.isFailure(ret)) {
@@ -345,10 +340,12 @@ FMRadioManager.prototype.unsetFMRadioInterruptedListener = function() {
};
FMRadioManager.prototype.setAntennaChangeListener = function() {
- var args = validator_.validateArgs(arguments, [ {
- name : 'changeCallback',
- type : types_.FUNCTION
- } ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'changeCallback',
+ type: types_.FUNCTION
+ }
+ ]);
antennaCBmanager.FMRadioAntennaChangeSet(args.changeCallback);
var ret = native_.callSync('FMRadio_SetAntennaChangeListener');
@@ -358,7 +355,6 @@ FMRadioManager.prototype.setAntennaChangeListener = function() {
};
FMRadioManager.prototype.unsetAntennaChangeListener = function() {
-
antennaCBmanager.FMRadioAntennaUnset();
var ret = native_.callSync('FMRadio_UnsetAntennaChangeListener');
if (native_.isFailure(ret)) {
diff --git a/src/secureelement/secureelement_api.js b/src/secureelement/secureelement_api.js
index db67d021..99a9460d 100644
--- a/src/secureelement/secureelement_api.js
+++ b/src/secureelement/secureelement_api.js
@@ -29,14 +29,17 @@ function ListenerManager(native, listenerName) {
this.nativeSet = false;
this.native = native;
this.listenerName = listenerName;
-};
+}
ListenerManager.prototype.onListenerCalled = function(msg) {
var d = undefined;
var e = undefined;
switch (msg.action) {
case 'onSEError':
- e = new WebAPIException(WebAPIException.IO_ERR, 'I/O error occurred on Secure Element reader');
+ e = new WebAPIException(
+ WebAPIException.IO_ERR,
+ 'I/O error occurred on Secure Element reader'
+ );
case 'onSEReady':
case 'onSENotReady':
d = new Reader(msg.handle);
@@ -47,7 +50,10 @@ ListenerManager.prototype.onListenerCalled = function(msg) {
}
for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId) && this.listeners[watchId][msg.action]) {
+ if (
+ this.listeners.hasOwnProperty(watchId) &&
+ this.listeners[watchId][msg.action]
+ ) {
this.listeners[watchId][msg.action](d, e);
}
}
@@ -59,7 +65,7 @@ ListenerManager.prototype.addListener = function(callback) {
this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
var result = this.native.callSync('SEService_registerSEListener');
if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
+ throw this.native.getErrorObject(result);
}
this.nativeSet = true;
}
@@ -72,17 +78,17 @@ ListenerManager.prototype.addListener = function(callback) {
ListenerManager.prototype.removeListener = function(watchId) {
if (type_utils.isEmptyObject(this.listeners)) {
- privUtils_.checkPrivilegeAccess(privilege_.SECUREELEMENT);
+ privUtils_.checkPrivilegeAccess(privilege_.SECUREELEMENT);
}
if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
+ delete this.listeners[watchId];
}
if (this.nativeSet && type_utils.isEmptyObject(this.listeners)) {
var result = this.native.callSync('SEService_unregisterSEListener');
if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
+ throw this.native.getErrorObject(result);
}
this.native.removeListener(this.listenerName);
this.nativeSet = false;
@@ -92,24 +98,23 @@ ListenerManager.prototype.removeListener = function(watchId) {
var SE_CHANGE_LISTENER = 'SecureElementChangeListener';
var SEChangeListener = new ListenerManager(native_, SE_CHANGE_LISTENER);
-function SEService() {
-}
+function SEService() {}
var SEServiceGetReaders = function() {
xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.SECUREELEMENT);
var args = validator_.validateArgs(arguments, [
- { name: "successCallback", type: types_.FUNCTION },
- { name: "errorCallback", type: types_.FUNCTION, optional: true, nullable: true }
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var callback = function(result) {
- if(native_.isFailure(result)) {
+ if (native_.isFailure(result)) {
native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
} else {
var result_obj = native_.getResultObject(result);
var readers_array = [];
- result_obj.forEach(function (data) {
+ result_obj.forEach(function(data) {
readers_array.push(new Reader(data));
});
@@ -119,7 +124,7 @@ var SEServiceGetReaders = function() {
var result = native_.call('SEService_getReaders', {}, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
@@ -131,8 +136,8 @@ var SEServiceRegisterSEListener = function() {
xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.SECUREELEMENT);
var args = validator_.validateArgs(arguments, [
{
- name : 'eventCallback',
- type : types_.LISTENER,
+ name: 'eventCallback',
+ type: types_.LISTENER,
values: ['onSEReady', 'onSENotReady', 'onSEError']
}
]);
@@ -148,8 +153,8 @@ var SEServiceUnregisterSEListener = function() {
xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.SECUREELEMENT);
var args = validator_.validateArgs(arguments, [
{
- name : 'id',
- type : types_.UNSIGNED_LONG
+ name: 'id',
+ type: types_.UNSIGNED_LONG
}
]);
@@ -158,7 +163,7 @@ var SEServiceUnregisterSEListener = function() {
SEService.prototype.unregisterSEListener = function() {
SEServiceUnregisterSEListener.apply(this, arguments);
-}
+};
var SEServiceShutdown = function() {
xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.SECUREELEMENT);
@@ -177,23 +182,31 @@ SEService.prototype.shutdown = function() {
function Reader(reader_handle) {
Object.defineProperties(this, {
- isPresent: { configurable: false,
- enumerable: true,
- set: function() {},
- get: function() {
- var callArgs = { handle: reader_handle };
- var result = native_.callSync('SEReader_isPresent', callArgs);
- if (native_.isFailure(result)) {
- privUtils_.log('SEReader_isPresent error: ' + native_.getErrorObject(result));
- return false;
- } else {
- return native_.getResultObject(result);
- }
- }},
- _handle: { configurable: false,
- enumerable: false,
- set: function() {},
- get: function() { return reader_handle }}
+ isPresent: {
+ configurable: false,
+ enumerable: true,
+ set: function() {},
+ get: function() {
+ var callArgs = { handle: reader_handle };
+ var result = native_.callSync('SEReader_isPresent', callArgs);
+ if (native_.isFailure(result)) {
+ privUtils_.log(
+ 'SEReader_isPresent error: ' + native_.getErrorObject(result)
+ );
+ return false;
+ } else {
+ return native_.getResultObject(result);
+ }
+ }
+ },
+ _handle: {
+ configurable: false,
+ enumerable: false,
+ set: function() {},
+ get: function() {
+ return reader_handle;
+ }
+ }
});
}
@@ -201,7 +214,7 @@ Reader.prototype.getName = function() {
var callArgs = { handle: this._handle };
var result = native_.callSync('SEReader_getName', callArgs);
- if(native_.isFailure(result)) {
+ if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
@@ -210,12 +223,12 @@ Reader.prototype.getName = function() {
Reader.prototype.openSession = function() {
var args = validator_.validateArgs(arguments, [
- { name: "successCallback", type: types_.FUNCTION },
- { name: "errorCallback", type: types_.FUNCTION, optional: true, nullable: true }
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var callback = function(result) {
- if(native_.isFailure(result)) {
+ if (native_.isFailure(result)) {
native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
} else {
var result_obj = native_.getResultObject(result);
@@ -229,7 +242,7 @@ Reader.prototype.openSession = function() {
var result = native_.call('SEReader_openSession', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
@@ -237,16 +250,30 @@ Reader.prototype.closeSessions = function() {
var callArgs = { handle: this._handle };
var result = native_.callSync('SEReader_closeSessions', callArgs);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
//////////////////Channel/////////////////
-function Channel( channel_handle, is_basic_channel) {
+function Channel(channel_handle, is_basic_channel) {
Object.defineProperties(this, {
- _handle: { enumerable: false, configurable: false, set: function() {}, get: function() { return channel_handle }},
- isBasicChannel: { enumerable: true, configurable: false, set: function() {}, get: function() { return is_basic_channel }}
+ _handle: {
+ enumerable: false,
+ configurable: false,
+ set: function() {},
+ get: function() {
+ return channel_handle;
+ }
+ },
+ isBasicChannel: {
+ enumerable: true,
+ configurable: false,
+ set: function() {},
+ get: function() {
+ return is_basic_channel;
+ }
+ }
});
}
@@ -255,24 +282,24 @@ Channel.prototype.close = function() {
var result = native_.callSync('SEChannel_close', callArgs);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
Channel.prototype.transmit = function() {
var args = validator_.validateArgs(arguments, [
- { name: "command", type: types_.ARRAY, values: types_.BYTE },
- { name: "successCallback", type: types_.FUNCTION },
- { name: "errorCallback", type: types_.FUNCTION, optional: true, nullable: true }
+ { name: 'command', type: types_.ARRAY, values: types_.BYTE },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var callback = function(result) {
- if ( native_.isFailure(result)) {
- native_.callIfPossible( args.errorCallback, native_.getErrorObject(result));
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
} else {
args.successCallback(native_.getResultObject(result));
}
- }
+ };
var callArgs = {
handle: this._handle,
@@ -282,60 +309,67 @@ Channel.prototype.transmit = function() {
var result = native_.call('SEChannel_transmit', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
-}
+};
Channel.prototype.getSelectResponse = function() {
var callArgs = { handle: this._handle };
var result = native_.callSync('SEChannel_getSelectResponse', callArgs);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
-}
+};
//////////////////Session/////////////////
function Session(session_handle) {
Object.defineProperties(this, {
- isClosed: { configurable: false,
- enumerable: true,
- set: function() {},
- get: function() {
- var callArgs = { handle: session_handle };
- var result = native_.callSync('SESession_isClosed', callArgs);
- if (native_.isFailure(result)) {
- privUtils_.log('SESession_isClosed error: ' + native_.getErrorObject(result));
- return true;
- } else {
- return native_.getResultObject(result);
- }
- }
- },
- _handle: { enumerable: false,
- configurable: false,
- set: function() {},
- get: function() { return session_handle }}
+ isClosed: {
+ configurable: false,
+ enumerable: true,
+ set: function() {},
+ get: function() {
+ var callArgs = { handle: session_handle };
+ var result = native_.callSync('SESession_isClosed', callArgs);
+ if (native_.isFailure(result)) {
+ privUtils_.log(
+ 'SESession_isClosed error: ' + native_.getErrorObject(result)
+ );
+ return true;
+ } else {
+ return native_.getResultObject(result);
+ }
+ }
+ },
+ _handle: {
+ enumerable: false,
+ configurable: false,
+ set: function() {},
+ get: function() {
+ return session_handle;
+ }
+ }
});
}
Session.prototype.openBasicChannel = function() {
var args = validator_.validateArgs(arguments, [
- { name: "aid", type: types_.ARRAY, values: types_.BYTE },
- { name: "successCallback", type: types_.FUNCTION },
- { name: "errorCallback", type: types_.FUNCTION, optional: true, nullable: true }
+ { name: 'aid', type: types_.ARRAY, values: types_.BYTE },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var callback = function(result) {
- if ( native_.isFailure(result)) {
- native_.callIfPossible( args.errorCallback, native_.getErrorObject(result));
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
} else {
var result_obj = native_.getResultObject(result);
- var channel = new Channel( result_obj.handle, result_obj.isBasicChannel);
+ var channel = new Channel(result_obj.handle, result_obj.isBasicChannel);
args.successCallback(channel);
}
- }
+ };
var callArgs = {
handle: this._handle,
@@ -345,26 +379,26 @@ Session.prototype.openBasicChannel = function() {
var result = native_.call('SESession_openBasicChannel', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
Session.prototype.openLogicalChannel = function() {
var args = validator_.validateArgs(arguments, [
- { name: "aid", type: types_.ARRAY, values: types_.BYTE },
- { name: "successCallback", type: types_.FUNCTION },
- { name: "errorCallback", type: types_.FUNCTION, optional: true, nullable: true }
+ { name: 'aid', type: types_.ARRAY, values: types_.BYTE },
+ { name: 'successCallback', type: types_.FUNCTION },
+ { name: 'errorCallback', type: types_.FUNCTION, optional: true, nullable: true }
]);
var callback = function(result) {
- if ( native_.isFailure(result)) {
- native_.callIfPossible( args.errorCallback, native_.getErrorObject(result));
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
} else {
var result_obj = native_.getResultObject(result);
- var channel = new Channel( result_obj.handle, result_obj.isBasicChannel);
+ var channel = new Channel(result_obj.handle, result_obj.isBasicChannel);
args.successCallback(channel);
}
- }
+ };
var callArgs = {
handle: this._handle,
@@ -374,9 +408,9 @@ Session.prototype.openLogicalChannel = function() {
var result = native_.call('SESession_openLogicalChannel', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
-}
+};
Session.prototype.getATR = function() {
var callArgs = { handle: this._handle };
@@ -386,25 +420,24 @@ Session.prototype.getATR = function() {
} else {
return native_.getResultObject(result);
}
-}
+};
Session.prototype.close = function() {
var callArgs = { handle: this._handle };
var result = native_.callSync('SESession_close', callArgs);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
-}
+};
Session.prototype.closeChannels = function() {
var callArgs = { handle: this._handle };
var result = native_.callSync('SESession_closeChannels', callArgs);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
-}
-
+};
exports = new SEService();
diff --git a/src/sensor/sensor_api.js b/src/sensor/sensor_api.js
index 41c744e0..f3380ef0 100755
--- a/src/sensor/sensor_api.js
+++ b/src/sensor/sensor_api.js
@@ -24,43 +24,42 @@ var native_ = new utils_.NativeManager(extension);
// Enums
var SensorType = {
- LIGHT : 'LIGHT',
- MAGNETIC : 'MAGNETIC',
- PRESSURE : 'PRESSURE',
- PROXIMITY : 'PROXIMITY',
- ULTRAVIOLET : 'ULTRAVIOLET',
- HRM_RAW : 'HRM_RAW',
- GRAVITY : 'GRAVITY',
- GYROSCOPE : 'GYROSCOPE',
- GYROSCOPE_ROTATION_VECTOR : 'GYROSCOPE_ROTATION_VECTOR',
- LINEAR_ACCELERATION : 'LINEAR_ACCELERATION',
- MAGNETIC_UNCALIBRATED : 'MAGNETIC_UNCALIBRATED',
- GYROSCOPE_UNCALIBRATED : 'GYROSCOPE_UNCALIBRATED',
- ACCELERATION : 'ACCELERATION'
+ LIGHT: 'LIGHT',
+ MAGNETIC: 'MAGNETIC',
+ PRESSURE: 'PRESSURE',
+ PROXIMITY: 'PROXIMITY',
+ ULTRAVIOLET: 'ULTRAVIOLET',
+ HRM_RAW: 'HRM_RAW',
+ GRAVITY: 'GRAVITY',
+ GYROSCOPE: 'GYROSCOPE',
+ GYROSCOPE_ROTATION_VECTOR: 'GYROSCOPE_ROTATION_VECTOR',
+ LINEAR_ACCELERATION: 'LINEAR_ACCELERATION',
+ MAGNETIC_UNCALIBRATED: 'MAGNETIC_UNCALIBRATED',
+ GYROSCOPE_UNCALIBRATED: 'GYROSCOPE_UNCALIBRATED',
+ ACCELERATION: 'ACCELERATION'
};
var ProximityState = {
- FAR : 'FAR',
- NEAR : 'NEAR'
+ FAR: 'FAR',
+ NEAR: 'NEAR'
};
var MagneticSensorAccuracy = {
- UNDEFINED : 'ACCURACY_UNDEFINED',
- BAD : 'ACCURACY_BAD',
- NORMAL : 'ACCURACY_NORMAL',
- GOOD : 'ACCURACY_GOOD',
- VERYGOOD : 'ACCURACY_VERYGOOD'
+ UNDEFINED: 'ACCURACY_UNDEFINED',
+ BAD: 'ACCURACY_BAD',
+ NORMAL: 'ACCURACY_NORMAL',
+ GOOD: 'ACCURACY_GOOD',
+ VERYGOOD: 'ACCURACY_VERYGOOD'
};
var SensorStates = {
- NOT_STARTED : 0,
- STARTING : 1,
- STARTED : 2
+ NOT_STARTED: 0,
+ STARTING: 1,
+ STARTED: 2
};
-
// helper class for sensor listeners
-var SensorListener = function (type, constructor) {
+var SensorListener = function(type, constructor) {
this.sensorType = type;
this.state = SensorStates.NOT_STARTED;
this.callback = undefined;
@@ -69,39 +68,41 @@ var SensorListener = function (type, constructor) {
this.constructor = constructor;
};
-SensorListener.prototype.tryCall = function (object) {
+SensorListener.prototype.tryCall = function(object) {
if (this.callback) {
this.callback(new this.constructor(object));
}
};
-SensorListener.prototype.start = function (successCallback, errorCallback) {
+SensorListener.prototype.start = function(successCallback, errorCallback) {
if (SensorStates.STARTED != this.state) {
// sensor not started
this.state = SensorStates.STARTING;
var thisObject = this;
- native_.call('Sensor_start', {'sensorType' : thisObject.sensorType},
- function(result) {
- if (native_.isFailure(result)) {
- thisObject.state = SensorStates.NOT_STARTED;
- if (!T_.isNullOrUndefined(errorCallback)) {
- errorCallback(native_.getErrorObject(result));
- }
- } else {
- thisObject.state = SensorStates.STARTED;
- successCallback();
- }
+ native_.call('Sensor_start', { sensorType: thisObject.sensorType }, function(
+ result
+ ) {
+ if (native_.isFailure(result)) {
+ thisObject.state = SensorStates.NOT_STARTED;
+ if (!T_.isNullOrUndefined(errorCallback)) {
+ errorCallback(native_.getErrorObject(result));
}
- );
+ } else {
+ thisObject.state = SensorStates.STARTED;
+ successCallback();
+ }
+ });
} else {
// sensor is already started - just call success callback
- setTimeout(function(){successCallback()}, 0);
+ setTimeout(function() {
+ successCallback();
+ }, 0);
}
};
-SensorListener.prototype.stop = function () {
+SensorListener.prototype.stop = function() {
if (SensorStates.NOT_STARTED != this.state) {
- var result = native_.callSync('Sensor_stop', {'sensorType' : this.sensorType});
+ var result = native_.callSync('Sensor_stop', { sensorType: this.sensorType });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
@@ -109,14 +110,18 @@ SensorListener.prototype.stop = function () {
}
};
-SensorListener.prototype.setListener = function (successCallback, interval, batchLatency) {
- if (!this.callback || this.callbackInterval != interval ||
- this.callbackBatchLatency != batchLatency) {
+SensorListener.prototype.setListener = function(successCallback, interval, batchLatency) {
+ if (
+ !this.callback ||
+ this.callbackInterval != interval ||
+ this.callbackBatchLatency != batchLatency
+ ) {
//call platform only if there was no listener registered or parameters changed
var result = native_.callSync('Sensor_setChangeListener', {
- 'sensorType' : this.sensorType,
- 'interval' : interval,
- 'batchLatency' : batchLatency});
+ sensorType: this.sensorType,
+ interval: interval,
+ batchLatency: batchLatency
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
@@ -127,30 +132,34 @@ SensorListener.prototype.setListener = function (successCallback, interval, batc
this.callback = successCallback;
};
-SensorListener.prototype.unsetListener = function () {
+SensorListener.prototype.unsetListener = function() {
if (this.callback) {
//unregister in platform only if there is callback registered
this.callback = undefined;
- var result = native_.callSync('Sensor_unsetChangeListener', {'sensorType' : this.sensorType});
+ var result = native_.callSync('Sensor_unsetChangeListener', {
+ sensorType: this.sensorType
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
}
};
-SensorListener.prototype.getData = function (successCallback, errorCallback) {
+SensorListener.prototype.getData = function(successCallback, errorCallback) {
var thisObj = this;
if (SensorStates.STARTED != this.state) {
setTimeout(function() {
if (!T_.isNullOrUndefined(errorCallback)) {
- errorCallback(new WebAPIException(
+ errorCallback(
+ new WebAPIException(
WebAPIException.SERVICE_NOT_AVAILABLE_ERR,
- 'Service is not available.'));
+ 'Service is not available.'
+ )
+ );
}
}, 0);
} else {
- native_.call('Sensor_getData', { type : thisObj.sensorType },
- function(result) {
+ native_.call('Sensor_getData', { type: thisObj.sensorType }, function(result) {
if (native_.isFailure(result)) {
if (!T_.isNullOrUndefined(errorCallback)) {
errorCallback(native_.getErrorObject(result));
@@ -165,23 +174,23 @@ SensorListener.prototype.getData = function (successCallback, errorCallback) {
var _supportedSensors = [];
var _isChecked = false;
var _sensorListeners = {
- 'LIGHT' : {},
- 'MAGNETIC' : {},
- 'PRESSURE' : {},
- 'PROXIMITY' : {},
- 'ULTRAVIOLET' : {},
- 'HRM_RAW' : {},
- 'GRAVITY' : {},
- 'GYROSCOPE' : {},
- 'GYROSCOPE_ROTATION_VECTOR' : {},
- 'LINEAR_ACCELERATION' : {},
- 'MAGNETIC_UNCALIBRATED' : {},
- 'GYROSCOPE_UNCALIBRATED' : {},
- 'ACCELERATION' : {}
-};
-
-var errorWrapper = function (err) {
- if(err.name === "UnknownError") {
+ LIGHT: {},
+ MAGNETIC: {},
+ PRESSURE: {},
+ PROXIMITY: {},
+ ULTRAVIOLET: {},
+ HRM_RAW: {},
+ GRAVITY: {},
+ GYROSCOPE: {},
+ GYROSCOPE_ROTATION_VECTOR: {},
+ LINEAR_ACCELERATION: {},
+ MAGNETIC_UNCALIBRATED: {},
+ GYROSCOPE_UNCALIBRATED: {},
+ ACCELERATION: {}
+};
+
+var errorWrapper = function(err) {
+ if (err.name === 'UnknownError') {
err = new WebAPIException(WebAPIException.ABORT_ERR, err.message);
}
@@ -189,7 +198,7 @@ var errorWrapper = function (err) {
};
var _listener = function(object) {
- if (object.sensorType.substring(0,4) === 'LED_') {
+ if (object.sensorType.substring(0, 4) === 'LED_') {
object.sensorType = 'HRM_RAW';
}
_sensorListeners[object.sensorType].tryCall(object);
@@ -207,15 +216,14 @@ function getAvailableSensors() {
_isChecked = true;
}
-function SensorService() {
-};
+function SensorService() {}
function getDefaultSensor() {
var args = validator_.validateArgs(arguments, [
{
- name : 'type',
- type : types_.ENUM,
- values : T_.getValues(SensorType)
+ name: 'type',
+ type: types_.ENUM,
+ values: T_.getValues(SensorType)
}
]);
@@ -241,11 +249,11 @@ function getDefaultSensor() {
return new HRMRawSensor();
} else if (_supportedSensors[index] === SensorType.GRAVITY) {
return new GravitySensor();
- } else if (_supportedSensors[index] === SensorType.GYROSCOPE){
+ } else if (_supportedSensors[index] === SensorType.GYROSCOPE) {
return new GyroscopeSensor();
- } else if (_supportedSensors[index] === SensorType.GYROSCOPE_ROTATION_VECTOR){
+ } else if (_supportedSensors[index] === SensorType.GYROSCOPE_ROTATION_VECTOR) {
return new GyroscopeRotationVectorSensor();
- } else if (_supportedSensors[index] === SensorType.LINEAR_ACCELERATION){
+ } else if (_supportedSensors[index] === SensorType.LINEAR_ACCELERATION) {
return new LinearAccelerationSensor();
} else if (_supportedSensors[index] === SensorType.MAGNETIC_UNCALIBRATED) {
return new MagneticUncalibratedSensor();
@@ -254,10 +262,10 @@ function getDefaultSensor() {
} else if (_supportedSensors[index] === SensorType.ACCELERATION) {
return new AccelerationSensor();
}
-};
+}
SensorService.prototype.getDefaultSensor = function() {
- return getDefaultSensor.apply(this, arguments);
+ return getDefaultSensor.apply(this, arguments);
};
SensorService.prototype.getAvailableSensors = function() {
@@ -268,26 +276,26 @@ SensorService.prototype.getAvailableSensors = function() {
return _supportedSensors.slice();
};
-//////////////////////Sensor classes//////////////////////////////////////////////////////////
+//////////////////////Sensor classes/////////////////////////////
//// Base Sensor class
-var Sensor = function (type) {
+var Sensor = function(type) {
Object.defineProperties(this, {
- sensorType : {value: type, writable: false, enumerable: true}
+ sensorType: { value: type, writable: false, enumerable: true }
});
};
Sensor.prototype.start = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
_sensorListeners[this.sensorType].start(args.successCallback, args.errorCallback);
@@ -299,64 +307,75 @@ Sensor.prototype.stop = function() {
Sensor.prototype.setChangeListener = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type: types_.FUNCTION
- },
- {
- name : 'interval',
- type: types_.LONG,
- optional: true,
- nullable: true
- },
- {
- name : 'batchLatency',
- type: types_.LONG,
- optional: true,
- nullable: false
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'interval',
+ type: types_.LONG,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'batchLatency',
+ type: types_.LONG,
+ optional: true,
+ nullable: false
+ }
]);
var interval = args.interval || 100;
if (interval < 10 || interval > 1000) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Interval should be in range [10, 1000] milliseconds.');
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Interval should be in range [10, 1000] milliseconds.'
+ );
}
var batchLatency = args.batchLatency || 0;
- _sensorListeners[this.sensorType].setListener(args.successCallback, interval, batchLatency);
+ _sensorListeners[this.sensorType].setListener(
+ args.successCallback,
+ interval,
+ batchLatency
+ );
};
Sensor.prototype.unsetChangeListener = function() {
_sensorListeners[this.sensorType].unsetListener();
};
-Sensor.prototype.getSensorHardwareInfo = function(){
- var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+Sensor.prototype.getSensorHardwareInfo = function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- var callback = function(result){
- if (native_.isFailure(result)){
- if (!T_.isNullOrUndefined(errorCallback)) {
- errorCallback(native_.getErrorObject(result));
- }
- }else {
- args.successCallback(new SensorHardwareInfo(result));
- }
- }
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ if (!T_.isNullOrUndefined(errorCallback)) {
+ errorCallback(native_.getErrorObject(result));
+ }
+ } else {
+ args.successCallback(new SensorHardwareInfo(result));
+ }
+ };
- var result = native_.call("Sensor_getSensorHardwareInfo", {type: this.sensorType}, callback);
-}
+ var result = native_.call(
+ 'Sensor_getSensorHardwareInfo',
+ { type: this.sensorType },
+ callback
+ );
+};
//// LightSensor
var LightSensor = function(data) {
@@ -369,16 +388,16 @@ LightSensor.prototype.constructor = Sensor;
LightSensor.prototype.getLightSensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
_sensorListeners[this.sensorType].getData(args.successCallback, args.errorCallback);
@@ -395,16 +414,16 @@ MagneticSensor.prototype.constructor = Sensor;
MagneticSensor.prototype.getMagneticSensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
_sensorListeners[this.sensorType].getData(args.successCallback, args.errorCallback);
@@ -421,16 +440,16 @@ PressureSensor.prototype.constructor = Sensor;
PressureSensor.prototype.getPressureSensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
_sensorListeners[this.sensorType].getData(args.successCallback, args.errorCallback);
@@ -447,16 +466,16 @@ ProximitySensor.prototype.constructor = Sensor;
ProximitySensor.prototype.getProximitySensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
_sensorListeners[this.sensorType].getData(args.successCallback, args.errorCallback);
@@ -473,16 +492,16 @@ UltravioletSensor.prototype.constructor = Sensor;
UltravioletSensor.prototype.getUltravioletSensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
_sensorListeners[this.sensorType].getData(args.successCallback, args.errorCallback);
@@ -499,25 +518,25 @@ HRMRawSensor.prototype.constructor = Sensor;
function getHRMRawSensorData() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
utils_.checkPrivilegeAccess(privilege_.HEALTHINFO);
_sensorListeners[this.sensorType].getData(args.successCallback, args.errorCallback);
-};
+}
HRMRawSensor.prototype.getHRMRawSensorData = function() {
- getHRMRawSensorData.apply(this, arguments);
+ getHRMRawSensorData.apply(this, arguments);
};
//// GravitySensor
@@ -531,22 +550,24 @@ GravitySensor.prototype.constructor = Sensor;
GravitySensor.prototype.getGravitySensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- _sensorListeners[this.sensorType].getData(args.successCallback, errorWrapper.bind(args));
+ _sensorListeners[this.sensorType].getData(
+ args.successCallback,
+ errorWrapper.bind(args)
+ );
};
-
//// GyroscopeSensor
var GyroscopeSensor = function(data) {
Sensor.call(this, SensorType.GYROSCOPE);
@@ -558,19 +579,22 @@ GyroscopeSensor.prototype.constructor = Sensor;
GyroscopeSensor.prototype.getGyroscopeSensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- _sensorListeners[this.sensorType].getData(args.successCallback, errorWrapper.bind(args));
+ _sensorListeners[this.sensorType].getData(
+ args.successCallback,
+ errorWrapper.bind(args)
+ );
};
//// GyroscopeRotationVectorSensor
@@ -582,22 +606,27 @@ GyroscopeRotationVectorSensor.prototype = new Sensor();
GyroscopeRotationVectorSensor.prototype.constructor = Sensor;
-GyroscopeRotationVectorSensor.prototype.getGyroscopeRotationVectorSensorData = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
+// prettier-ignore
+GyroscopeRotationVectorSensor.prototype.getGyroscopeRotationVectorSensorData =
+ function() {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- _sensorListeners[this.sensorType].getData(args.successCallback, errorWrapper.bind(args));
-};
+ _sensorListeners[this.sensorType].getData(
+ args.successCallback,
+ errorWrapper.bind(args)
+ );
+ };
//// LinearAccelerationSensor
var LinearAccelerationSensor = function(data) {
@@ -610,19 +639,22 @@ LinearAccelerationSensor.prototype.constructor = Sensor;
LinearAccelerationSensor.prototype.getLinearAccelerationSensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- _sensorListeners[this.sensorType].getData(args.successCallback, errorWrapper.bind(args));
+ _sensorListeners[this.sensorType].getData(
+ args.successCallback,
+ errorWrapper.bind(args)
+ );
};
//// MagneticUncalibratedSensor
@@ -637,18 +669,21 @@ MagneticUncalibratedSensor.prototype.constructor = Sensor;
MagneticUncalibratedSensor.prototype.getMagneticUncalibratedSensorData = function() {
var args = validator_.validateArgs(arguments, [
{
- name : 'successCallback',
- type : types_.FUNCTION
+ name: 'successCallback',
+ type: types_.FUNCTION
},
{
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
- _sensorListeners[this.sensorType].getData(args.successCallback, errorWrapper.bind(args));
+ _sensorListeners[this.sensorType].getData(
+ args.successCallback,
+ errorWrapper.bind(args)
+ );
};
//// GyroscopeUncalibratedSensor
@@ -663,18 +698,21 @@ GyroscopeUncalibratedSensor.prototype.constructor = Sensor;
GyroscopeUncalibratedSensor.prototype.getGyroscopeUncalibratedSensorData = function() {
var args = validator_.validateArgs(arguments, [
{
- name : 'successCallback',
- type : types_.FUNCTION
+ name: 'successCallback',
+ type: types_.FUNCTION
},
{
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
}
]);
- _sensorListeners[this.sensorType].getData(args.successCallback, errorWrapper.bind(args));
+ _sensorListeners[this.sensorType].getData(
+ args.successCallback,
+ errorWrapper.bind(args)
+ );
};
//// AccelerationSensor
@@ -688,31 +726,33 @@ AccelerationSensor.prototype.constructor = Sensor;
AccelerationSensor.prototype.getAccelerationSensorData = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- _sensorListeners[this.sensorType].getData(args.successCallback, errorWrapper.bind(args));
+ _sensorListeners[this.sensorType].getData(
+ args.successCallback,
+ errorWrapper.bind(args)
+ );
};
-////////////////////// Sensor Data classes/////////////////////////////////////////////////////
+////////////////////// Sensor Data classes//////////////////////////
////Base SensorData class
-var SensorData = function () {
-};
+var SensorData = function() {};
//// SensorLightData
var SensorLightData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- lightLevel : {value: data.lightLevel, writable: false, enumerable: true}
+ lightLevel: { value: data.lightLevel, writable: false, enumerable: true }
});
};
@@ -720,17 +760,19 @@ SensorLightData.prototype = new SensorData();
SensorLightData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.LIGHT] = new SensorListener(SensorType.LIGHT,
- SensorLightData);
+_sensorListeners[SensorType.LIGHT] = new SensorListener(
+ SensorType.LIGHT,
+ SensorLightData
+);
//// SensorMagneticData
var SensorMagneticData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
- accuracy : {value: data.accuracy, writable: false, enumerable: true}
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true },
+ accuracy: { value: data.accuracy, writable: false, enumerable: true }
});
};
@@ -738,14 +780,16 @@ SensorMagneticData.prototype = new SensorData();
SensorMagneticData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.MAGNETIC] = new SensorListener(SensorType.MAGNETIC,
- SensorMagneticData);
+_sensorListeners[SensorType.MAGNETIC] = new SensorListener(
+ SensorType.MAGNETIC,
+ SensorMagneticData
+);
//// SensorPressureData
var SensorPressureData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- pressure : {value: data.pressure, writable: false, enumerable: true}
+ pressure: { value: data.pressure, writable: false, enumerable: true }
});
};
@@ -753,14 +797,16 @@ SensorPressureData.prototype = new SensorData();
SensorPressureData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.PRESSURE] = new SensorListener(SensorType.PRESSURE,
- SensorPressureData);
+_sensorListeners[SensorType.PRESSURE] = new SensorListener(
+ SensorType.PRESSURE,
+ SensorPressureData
+);
//// SensorProximityData
var SensorProximityData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- proximityState : {value: data.proximityState, writable: false, enumerable: true}
+ proximityState: { value: data.proximityState, writable: false, enumerable: true }
});
};
@@ -768,49 +814,57 @@ SensorProximityData.prototype = new SensorData();
SensorProximityData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.PROXIMITY] = new SensorListener(SensorType.PROXIMITY,
- SensorProximityData);
+_sensorListeners[SensorType.PROXIMITY] = new SensorListener(
+ SensorType.PROXIMITY,
+ SensorProximityData
+);
//// SensorUltravioletData
var SensorUltravioletData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- ultravioletLevel : {value: data.ultravioletLevel, writable: false, enumerable: true}
+ ultravioletLevel: {
+ value: data.ultravioletLevel,
+ writable: false,
+ enumerable: true
+ }
});
};
-
SensorUltravioletData.prototype = new SensorData();
SensorUltravioletData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.ULTRAVIOLET] = new SensorListener(SensorType.ULTRAVIOLET,
- SensorUltravioletData);
+_sensorListeners[SensorType.ULTRAVIOLET] = new SensorListener(
+ SensorType.ULTRAVIOLET,
+ SensorUltravioletData
+);
////SensorHRMRawData
var SensorHRMRawData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- lightType : {value: data.lightType, writable: false, enumerable: true},
- lightIntensity : {value: data.lightIntensity, writable: false, enumerable: true}
+ lightType: { value: data.lightType, writable: false, enumerable: true },
+ lightIntensity: { value: data.lightIntensity, writable: false, enumerable: true }
});
};
-
SensorHRMRawData.prototype = new SensorData();
SensorHRMRawData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.HRM_RAW] = new SensorListener(SensorType.HRM_RAW,
- SensorHRMRawData);
+_sensorListeners[SensorType.HRM_RAW] = new SensorListener(
+ SensorType.HRM_RAW,
+ SensorHRMRawData
+);
//// SensorGravityData
var SensorGravityData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true }
});
};
@@ -818,16 +872,18 @@ SensorGravityData.prototype = new SensorData();
SensorGravityData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.GRAVITY] = new SensorListener(SensorType.GRAVITY,
- SensorGravityData);
+_sensorListeners[SensorType.GRAVITY] = new SensorListener(
+ SensorType.GRAVITY,
+ SensorGravityData
+);
//// SensorGyroscopeData
var SensorGyroscopeData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true }
});
};
@@ -835,17 +891,19 @@ SensorGyroscopeData.prototype = new SensorData();
SensorGyroscopeData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.GYROSCOPE] = new SensorListener(SensorType.GYROSCOPE,
- SensorGyroscopeData);
+_sensorListeners[SensorType.GYROSCOPE] = new SensorListener(
+ SensorType.GYROSCOPE,
+ SensorGyroscopeData
+);
//// SensorGyroscopeRotationVectorData
var SensorGyroscopeRotationVectorData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
- w : {value: data.w, writable: false, enumerable: true},
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true },
+ w: { value: data.w, writable: false, enumerable: true }
});
};
@@ -853,16 +911,18 @@ SensorGyroscopeRotationVectorData.prototype = new SensorData();
SensorGyroscopeRotationVectorData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.GYROSCOPE_ROTATION_VECTOR] = new SensorListener(SensorType.GYROSCOPE_ROTATION_VECTOR,
- SensorGyroscopeRotationVectorData);
+_sensorListeners[SensorType.GYROSCOPE_ROTATION_VECTOR] = new SensorListener(
+ SensorType.GYROSCOPE_ROTATION_VECTOR,
+ SensorGyroscopeRotationVectorData
+);
//// SensorLinearAccelerationData
var SensorLinearAccelerationData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true }
});
};
@@ -870,19 +930,21 @@ SensorLinearAccelerationData.prototype = new SensorData();
SensorLinearAccelerationData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.LINEAR_ACCELERATION] = new SensorListener(SensorType.LINEAR_ACCELERATION,
- SensorLinearAccelerationData);
+_sensorListeners[SensorType.LINEAR_ACCELERATION] = new SensorListener(
+ SensorType.LINEAR_ACCELERATION,
+ SensorLinearAccelerationData
+);
//// SensorMagneticUncalibratedData
var SensorMagneticUncalibratedData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
- xAxisBias : {value: data.xAxisBias, writable: false, enumerable: true},
- yAxisBias : {value: data.yAxisBias, writable: false, enumerable: true},
- zAxisBias : {value: data.zAxisBias, writable: false, enumerable: true}
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true },
+ xAxisBias: { value: data.xAxisBias, writable: false, enumerable: true },
+ yAxisBias: { value: data.yAxisBias, writable: false, enumerable: true },
+ zAxisBias: { value: data.zAxisBias, writable: false, enumerable: true }
});
};
@@ -890,37 +952,40 @@ SensorMagneticUncalibratedData.prototype = new SensorData();
SensorMagneticUncalibratedData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.MAGNETIC_UNCALIBRATED] = new SensorListener(SensorType.MAGNETIC_UNCALIBRATED,
- SensorMagneticUncalibratedData);
+_sensorListeners[SensorType.MAGNETIC_UNCALIBRATED] = new SensorListener(
+ SensorType.MAGNETIC_UNCALIBRATED,
+ SensorMagneticUncalibratedData
+);
//// SensorGyroscopeUncalibratedData
var SensorGyroscopeUncalibratedData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
- xAxisDrift : {value: data.xAxisDrift, writable: false, enumerable: true},
- yAxisDrift : {value: data.yAxisDrift, writable: false, enumerable: true},
- zAxisDrift : {value: data.zAxisDrift, writable: false, enumerable: true}
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true },
+ xAxisDrift: { value: data.xAxisDrift, writable: false, enumerable: true },
+ yAxisDrift: { value: data.yAxisDrift, writable: false, enumerable: true },
+ zAxisDrift: { value: data.zAxisDrift, writable: false, enumerable: true }
});
-
};
SensorGyroscopeUncalibratedData.prototype = new SensorData();
SensorGyroscopeUncalibratedData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.GYROSCOPE_UNCALIBRATED] = new SensorListener(SensorType.GYROSCOPE_UNCALIBRATED,
- SensorGyroscopeUncalibratedData);
+_sensorListeners[SensorType.GYROSCOPE_UNCALIBRATED] = new SensorListener(
+ SensorType.GYROSCOPE_UNCALIBRATED,
+ SensorGyroscopeUncalibratedData
+);
//// SensorAccelerationData
var SensorAccelerationData = function(data) {
SensorData.call(this);
Object.defineProperties(this, {
- x : {value: data.x, writable: false, enumerable: true},
- y : {value: data.y, writable: false, enumerable: true},
- z : {value: data.z, writable: false, enumerable: true},
+ x: { value: data.x, writable: false, enumerable: true },
+ y: { value: data.y, writable: false, enumerable: true },
+ z: { value: data.z, writable: false, enumerable: true }
});
};
@@ -928,20 +993,22 @@ SensorAccelerationData.prototype = new SensorData();
SensorAccelerationData.prototype.constructor = SensorData;
-_sensorListeners[SensorType.ACCELERATION] = new SensorListener(SensorType.ACCELERATION,
- SensorAccelerationData);
+_sensorListeners[SensorType.ACCELERATION] = new SensorListener(
+ SensorType.ACCELERATION,
+ SensorAccelerationData
+);
-//////////////////////SensorHardwareInfo classes//////////////////////////////////////////////////////////
+//////////////////////SensorHardwareInfo classes/////////////////////////////
function SensorHardwareInfo(data) {
Object.defineProperties(this, {
- name : {value: data.name, writable: false, enumerable: true},
- type : {value: data.type, writable: false, enumerable: true},
- vendor : {value: data.vendor, writable: false, enumerable: true},
- minValue : {value: data.minValue, writable: false, enumerable: true},
- maxValue : {value: data.maxValue, writable: false, enumerable: true},
- resolution : {value: data.resolution, writable: false, enumerable: true},
- minInterval : {value: data.minInterval, writable: false, enumerable: true},
- maxBatchCount : {value: data.batchCount, writable: false, enumerable: true}
+ name: { value: data.name, writable: false, enumerable: true },
+ type: { value: data.type, writable: false, enumerable: true },
+ vendor: { value: data.vendor, writable: false, enumerable: true },
+ minValue: { value: data.minValue, writable: false, enumerable: true },
+ maxValue: { value: data.maxValue, writable: false, enumerable: true },
+ resolution: { value: data.resolution, writable: false, enumerable: true },
+ minInterval: { value: data.minInterval, writable: false, enumerable: true },
+ maxBatchCount: { value: data.batchCount, writable: false, enumerable: true }
});
}
// Exports
diff --git a/src/sound/sound_api.js b/src/sound/sound_api.js
index a72f8123..7c3c86d2 100644
--- a/src/sound/sound_api.js
+++ b/src/sound/sound_api.js
@@ -21,117 +21,119 @@ var validator_ = utils_.validator;
var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
-
var SoundType = {
- SYSTEM: 'SYSTEM',
- NOTIFICATION: 'NOTIFICATION',
- ALARM: 'ALARM',
- MEDIA: 'MEDIA',
- VOICE: 'VOICE',
- RINGTONE: 'RINGTONE'
+ SYSTEM: 'SYSTEM',
+ NOTIFICATION: 'NOTIFICATION',
+ ALARM: 'ALARM',
+ MEDIA: 'MEDIA',
+ VOICE: 'VOICE',
+ RINGTONE: 'RINGTONE'
};
var SoundModeType = {
- SOUND: 'SOUND',
- VIBRATE: 'VIBRATE',
- MUTE: 'MUTE'
+ SOUND: 'SOUND',
+ VIBRATE: 'VIBRATE',
+ MUTE: 'MUTE'
};
function _createSoundDeviceInfoArray(e) {
- var devices_array = [];
+ var devices_array = [];
- e.forEach(function (data) {
- devices_array.push(new SoundDeviceInfo(data));
- });
+ e.forEach(function(data) {
+ devices_array.push(new SoundDeviceInfo(data));
+ });
- return devices_array;
-};
+ return devices_array;
+}
function ListenerManager(native, listenerName) {
- this.listeners = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
-};
+ this.listeners = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
+}
ListenerManager.prototype.onListenerCalled = function(msg) {
- var obj = new SoundDeviceInfo(msg);
- for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId)) {
- this.listeners[watchId](obj);
+ var obj = new SoundDeviceInfo(msg);
+ for (var watchId in this.listeners) {
+ if (this.listeners.hasOwnProperty(watchId)) {
+ this.listeners[watchId](obj);
+ }
}
- }
};
ListenerManager.prototype.addListener = function(callback) {
- var id = this.nextId;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- this.native.callSync('SoundManager_addDeviceStateChangeListener');
- this.nativeSet = true;
- }
+ var id = this.nextId;
+ if (!this.nativeSet) {
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ this.native.callSync('SoundManager_addDeviceStateChangeListener');
+ this.nativeSet = true;
+ }
- this.listeners[id] = callback;
- ++this.nextId;
+ this.listeners[id] = callback;
+ ++this.nextId;
- return id;
+ return id;
};
ListenerManager.prototype.removeListener = function(watchId) {
- if (!this.listeners.hasOwnProperty(watchId)) {
- return;
- }
+ if (!this.listeners.hasOwnProperty(watchId)) {
+ return;
+ }
- delete this.listeners[watchId];
+ delete this.listeners[watchId];
- if (this.nativeSet && type_.isEmptyObject(this.listeners)) {
- this.native.callSync('SoundManager_removeDeviceStateChangeListener');
- this.native.removeListener(this.listenerName);
- this.nativeSet = false;
- }
+ if (this.nativeSet && type_.isEmptyObject(this.listeners)) {
+ this.native.callSync('SoundManager_removeDeviceStateChangeListener');
+ this.native.removeListener(this.listenerName);
+ this.nativeSet = false;
+ }
};
var DEVICE_STATE_CHANGE_LISTENER = 'SoundDeviceStateChangeCallback';
-var soundDeviceStateChangeListener = new ListenerManager(native_, DEVICE_STATE_CHANGE_LISTENER);
+var soundDeviceStateChangeListener = new ListenerManager(
+ native_,
+ DEVICE_STATE_CHANGE_LISTENER
+);
function SoundManager() {}
SoundManager.prototype.getSoundMode = function() {
- var result = native_.callSync('SoundManager_getSoundMode');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('SoundManager_getSoundMode');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return native_.getResultObject(result);
+ return native_.getResultObject(result);
};
SoundManager.prototype.setVolume = function(type, volume) {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(SoundType)},
- {name: 'volume', type: types_.DOUBLE}
- ]);
-
- if (args.volume < 0 || args.volume > 1) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
- }
- var result = native_.callSync('SoundManager_setVolume', args);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var args = validator_.validateArgs(arguments, [
+ { name: 'type', type: types_.ENUM, values: Object.keys(SoundType) },
+ { name: 'volume', type: types_.DOUBLE }
+ ]);
+
+ if (args.volume < 0 || args.volume > 1) {
+ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR);
+ }
+ var result = native_.callSync('SoundManager_setVolume', args);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
SoundManager.prototype.getVolume = function(type) {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: Object.keys(SoundType)}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'type', type: types_.ENUM, values: Object.keys(SoundType) }
+ ]);
- var result = native_.callSync('SoundManager_getVolume', args);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('SoundManager_getVolume', args);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return native_.getResultObject(result);
+ return native_.getResultObject(result);
};
var _soundModeChangeListener;
@@ -143,127 +145,130 @@ var _isFirstSoundModeChange = true;
// value caused by hazard of two values which should change simultaneously.
// By waiting whether second callback would fire we bypass this problem.
function _soundModeChangeListenerCallback(result) {
- _currentSoundMode = result;
- if (_isFirstSoundModeChange) {
- _isFirstSoundModeChange = false;
- setTimeout(function () {
- _isFirstSoundModeChange = true;
- native_.callIfPossible(_soundModeChangeListener, native_.getResultObject(_currentSoundMode));
- }, 100);
- }
+ _currentSoundMode = result;
+ if (_isFirstSoundModeChange) {
+ _isFirstSoundModeChange = false;
+ setTimeout(function() {
+ _isFirstSoundModeChange = true;
+ native_.callIfPossible(
+ _soundModeChangeListener,
+ native_.getResultObject(_currentSoundMode)
+ );
+ }, 100);
+ }
}
SoundManager.prototype.setSoundModeChangeListener = function(callback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'callback', type: types_.FUNCTION}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'callback', type: types_.FUNCTION }
+ ]);
- _soundModeChangeListener = args.callback;
- native_.addListener('SoundModeChangeListener', _soundModeChangeListenerCallback);
+ _soundModeChangeListener = args.callback;
+ native_.addListener('SoundModeChangeListener', _soundModeChangeListenerCallback);
- var result = native_.callSync('SoundManager_setSoundModeChangeListener', {});
+ var result = native_.callSync('SoundManager_setSoundModeChangeListener', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
SoundManager.prototype.unsetSoundModeChangeListener = function() {
- native_.removeListener('SoundModeChangeListener', _soundModeChangeListenerCallback);
+ native_.removeListener('SoundModeChangeListener', _soundModeChangeListenerCallback);
- var result = native_.callSync('SoundManager_unsetSoundModeChangeListener', {});
+ var result = native_.callSync('SoundManager_unsetSoundModeChangeListener', {});
- _soundModeChangeListener = undefined;
+ _soundModeChangeListener = undefined;
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
var _volumeChangeListener;
function _volumeChangeListenerCallback(result) {
- native_.callIfPossible(_volumeChangeListener, result.type, result.volume);
+ native_.callIfPossible(_volumeChangeListener, result.type, result.volume);
}
SoundManager.prototype.setVolumeChangeListener = function(callback) {
- var args = validator_.validateArgs(arguments, [
- {name: 'callback', type: types_.FUNCTION}
- ]);
+ var args = validator_.validateArgs(arguments, [
+ { name: 'callback', type: types_.FUNCTION }
+ ]);
- _volumeChangeListener = args.callback;
- native_.addListener('VolumeChangeListener', _volumeChangeListenerCallback);
+ _volumeChangeListener = args.callback;
+ native_.addListener('VolumeChangeListener', _volumeChangeListenerCallback);
- var result = native_.callSync('SoundManager_setVolumeChangeListener', {});
+ var result = native_.callSync('SoundManager_setVolumeChangeListener', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
SoundManager.prototype.unsetVolumeChangeListener = function() {
- native_.removeListener('VolumeChangeListener', _volumeChangeListenerCallback);
+ native_.removeListener('VolumeChangeListener', _volumeChangeListenerCallback);
- var result = native_.callSync('SoundManager_unsetVolumeChangeListener', {});
+ var result = native_.callSync('SoundManager_unsetVolumeChangeListener', {});
- _volumeChangeListener = undefined;
+ _volumeChangeListener = undefined;
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
SoundManager.prototype.getConnectedDeviceList = function() {
- var result = native_.callSync('SoundManager_getConnectedDeviceList', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('SoundManager_getConnectedDeviceList', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var devices = _createSoundDeviceInfoArray(native_.getResultObject(result));
- return devices;
+ var devices = _createSoundDeviceInfoArray(native_.getResultObject(result));
+ return devices;
};
SoundManager.prototype.getActivatedDeviceList = function() {
- var result = native_.callSync('SoundManager_getActivatedDeviceList', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ var result = native_.callSync('SoundManager_getActivatedDeviceList', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- var devices = _createSoundDeviceInfoArray(native_.getResultObject(result));
- return devices;
+ var devices = _createSoundDeviceInfoArray(native_.getResultObject(result));
+ return devices;
};
SoundManager.prototype.addDeviceStateChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name : 'eventCallback',
- type : types_.FUNCTION
- }
- ]);
-
- return soundDeviceStateChangeListener.addListener(args.eventCallback);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'eventCallback',
+ type: types_.FUNCTION
+ }
+ ]);
+
+ return soundDeviceStateChangeListener.addListener(args.eventCallback);
};
SoundManager.prototype.removeDeviceStateChangeListener = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name : 'watchId',
- type : types_.LONG
- }
- ]);
-
- soundDeviceStateChangeListener.removeListener(args.watchId);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'watchId',
+ type: types_.LONG
+ }
+ ]);
+
+ soundDeviceStateChangeListener.removeListener(args.watchId);
};
function SoundDeviceInfo(data) {
- Object.defineProperties(this, {
- id: {value: data.id, writable: false, enumerable: true},
- name: {value: data.name, writable: false, enumerable: true},
- device : {value: data.device, writable: false, enumerable: true},
- direction : {value: data.direction, writable: false, enumerable: true},
- isConnected: {value: data.isConnected, writable: false, enumerable: true},
- isActivated: {value: data.isActivated, writable: false, enumerable: true},
- });
-};
+ Object.defineProperties(this, {
+ id: { value: data.id, writable: false, enumerable: true },
+ name: { value: data.name, writable: false, enumerable: true },
+ device: { value: data.device, writable: false, enumerable: true },
+ direction: { value: data.direction, writable: false, enumerable: true },
+ isConnected: { value: data.isConnected, writable: false, enumerable: true },
+ isActivated: { value: data.isActivated, writable: false, enumerable: true }
+ });
+}
exports = new SoundManager();
diff --git a/src/systeminfo/systeminfo_api.js b/src/systeminfo/systeminfo_api.js
index b0628978..d60c3afd 100644
--- a/src/systeminfo/systeminfo_api.js
+++ b/src/systeminfo/systeminfo_api.js
@@ -27,387 +27,387 @@ var defaultListenerIndex = 0;
//enumeration SystemInfoPropertyId ////////////////////////////////////////////////////
var SystemInfoPropertyId = {
- BATTERY : 'BATTERY',
- CPU : 'CPU',
- STORAGE : 'STORAGE',
- DISPLAY : 'DISPLAY',
- DEVICE_ORIENTATION : 'DEVICE_ORIENTATION',
- BUILD : 'BUILD',
- LOCALE : 'LOCALE',
- NETWORK : 'NETWORK',
- WIFI_NETWORK : 'WIFI_NETWORK',
- ETHERNET_NETWORK : 'ETHERNET_NETWORK',
- CELLULAR_NETWORK : 'CELLULAR_NETWORK',
- NET_PROXY_NETWORK : 'NET_PROXY_NETWORK',
- SIM : 'SIM',
- PERIPHERAL : 'PERIPHERAL',
- MEMORY : 'MEMORY',
- CAMERA_FLASH : 'CAMERA_FLASH',
- ADS : 'ADS'
+ BATTERY: 'BATTERY',
+ CPU: 'CPU',
+ STORAGE: 'STORAGE',
+ DISPLAY: 'DISPLAY',
+ DEVICE_ORIENTATION: 'DEVICE_ORIENTATION',
+ BUILD: 'BUILD',
+ LOCALE: 'LOCALE',
+ NETWORK: 'NETWORK',
+ WIFI_NETWORK: 'WIFI_NETWORK',
+ ETHERNET_NETWORK: 'ETHERNET_NETWORK',
+ CELLULAR_NETWORK: 'CELLULAR_NETWORK',
+ NET_PROXY_NETWORK: 'NET_PROXY_NETWORK',
+ SIM: 'SIM',
+ PERIPHERAL: 'PERIPHERAL',
+ MEMORY: 'MEMORY',
+ CAMERA_FLASH: 'CAMERA_FLASH',
+ ADS: 'ADS'
};
var SystemInfoPropertyIdToFeature = {
- BATTERY : 'http://tizen.org/feature/battery',
- CAMERA_FLASH : 'http://tizen.org/feature/camera.back.flash',
- CELLULAR_NETWORK : 'http://tizen.org/feature/network.telephony',
- DISPLAY : 'http://tizen.org/feature/screen',
- ETHERNET_NETWORK : 'http://tizen.org/feature/network.ethernet',
- SIM : 'http://tizen.org/feature/network.telephony',
- NET_PROXY_NETWORK : 'http://tizen.org/feature/network.net_proxy',
- WIFI_NETWORK : 'http://tizen.org/feature/network.wifi'
+ BATTERY: 'http://tizen.org/feature/battery',
+ CAMERA_FLASH: 'http://tizen.org/feature/camera.back.flash',
+ CELLULAR_NETWORK: 'http://tizen.org/feature/network.telephony',
+ DISPLAY: 'http://tizen.org/feature/screen',
+ ETHERNET_NETWORK: 'http://tizen.org/feature/network.ethernet',
+ SIM: 'http://tizen.org/feature/network.telephony',
+ NET_PROXY_NETWORK: 'http://tizen.org/feature/network.net_proxy',
+ WIFI_NETWORK: 'http://tizen.org/feature/network.wifi'
};
//class SystemInfoDeviceCapability ////////////////////////////////////////////////////
function SystemInfoDeviceCapability(data) {
Object.defineProperties(this, {
- bluetooth : {
- value : data.bluetooth,
- writable : false,
- enumerable : true
- },
- nfc : {
- value : data.nfc,
- writable : false,
- enumerable : true
- },
- nfcReservedPush : {
- value : data.nfcReservedPush,
- writable : false,
- enumerable : true
- },
- multiTouchCount : {
- value : Converter_.toOctet(data.multiTouchCount),
- writable : false,
- enumerable : true
- },
- inputKeyboard : {
- value : data.inputKeyboard,
- writable : false,
- enumerable : true
- },
- inputKeyboardLayout : {
- value : data.inputKeyboardLayout,
- writable : false,
- enumerable : true
- },
- wifi : {
- value : data.wifi,
- writable : false,
- enumerable : true
- },
- wifiDirect : {
- value : data.wifiDirect,
- writable : false,
- enumerable : true
- },
- opengles : {
- value : data.opengles,
- writable : false,
- enumerable : true
- },
- openglestextureFormat : {
- value : data.openglestextureFormat,
- writable : false,
- enumerable : true
- },
- openglesVersion1_1 : {
- value : data.openglesVersion1_1,
- writable : false,
- enumerable : true
- },
- openglesVersion2_0 : {
- value : data.openglesVersion2_0,
- writable : false,
- enumerable : true
- },
- fmRadio : {
- value : data.fmRadio,
- writable : false,
- enumerable : true
- },
- platformVersion : {
- get : function() {
+ bluetooth: {
+ value: data.bluetooth,
+ writable: false,
+ enumerable: true
+ },
+ nfc: {
+ value: data.nfc,
+ writable: false,
+ enumerable: true
+ },
+ nfcReservedPush: {
+ value: data.nfcReservedPush,
+ writable: false,
+ enumerable: true
+ },
+ multiTouchCount: {
+ value: Converter_.toOctet(data.multiTouchCount),
+ writable: false,
+ enumerable: true
+ },
+ inputKeyboard: {
+ value: data.inputKeyboard,
+ writable: false,
+ enumerable: true
+ },
+ inputKeyboardLayout: {
+ value: data.inputKeyboardLayout,
+ writable: false,
+ enumerable: true
+ },
+ wifi: {
+ value: data.wifi,
+ writable: false,
+ enumerable: true
+ },
+ wifiDirect: {
+ value: data.wifiDirect,
+ writable: false,
+ enumerable: true
+ },
+ opengles: {
+ value: data.opengles,
+ writable: false,
+ enumerable: true
+ },
+ openglestextureFormat: {
+ value: data.openglestextureFormat,
+ writable: false,
+ enumerable: true
+ },
+ openglesVersion1_1: {
+ value: data.openglesVersion1_1,
+ writable: false,
+ enumerable: true
+ },
+ openglesVersion2_0: {
+ value: data.openglesVersion2_0,
+ writable: false,
+ enumerable: true
+ },
+ fmRadio: {
+ value: data.fmRadio,
+ writable: false,
+ enumerable: true
+ },
+ platformVersion: {
+ get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return data.platformVersion;
},
- set : function() {},
- enumerable : true
+ set: function() {},
+ enumerable: true
},
- webApiVersion : {
- get : function() {
+ webApiVersion: {
+ get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return data.webApiVersion;
},
- set : function() {},
- enumerable : true
+ set: function() {},
+ enumerable: true
},
- nativeApiVersion : {
- get : function() {
+ nativeApiVersion: {
+ get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return data.nativeApiVersion;
},
- set : function() {},
- enumerable : true
- },
- platformName : {
- value : data.platformName,
- writable : false,
- enumerable : true
- },
- camera : {
- value : data.camera,
- writable : false,
- enumerable : true
- },
- cameraFront : {
- value : data.cameraFront,
- writable : false,
- enumerable : true
- },
- cameraFrontFlash : {
- value : data.cameraFrontFlash,
- writable : false,
- enumerable : true
- },
- cameraBack : {
- value : data.cameraBack,
- writable : false,
- enumerable : true
- },
- cameraBackFlash : {
- value : data.cameraBackFlash,
- writable : false,
- enumerable : true
- },
- location : {
- value : data.location,
- writable : false,
- enumerable : true
- },
- locationGps : {
- value : data.locationGps,
- writable : false,
- enumerable : true
- },
- locationWps : {
- value : data.locationWps,
- writable : false,
- enumerable : true
- },
- microphone : {
- value : data.microphone,
- writable : false,
- enumerable : true
- },
- usbHost : {
- value : data.usbHost,
- writable : false,
- enumerable : true
- },
- usbAccessory : {
- value : data.usbAccessory,
- writable : false,
- enumerable : true
- },
- screenOutputRca : {
- value : data.screenOutputRca,
- writable : false,
- enumerable : true
- },
- screenOutputHdmi : {
- value : data.screenOutputHdmi,
- writable : false,
- enumerable : true
- },
- platformCoreCpuArch : {
- value : data.platformCoreCpuArch,
- writable : false,
- enumerable : true
- },
- platformCoreFpuArch : {
- value : data.platformCoreFpuArch,
- writable : false,
- enumerable : true
- },
- sipVoip : {
- value : data.sipVoip,
- writable : false,
- enumerable : true
- },
- duid : {
- value : data.duid,
- writable : false,
- enumerable : true
- },
- speechRecognition : {
- value : data.speechRecognition,
- writable : false,
- enumerable : true
- },
- speechSynthesis : {
- value : data.speechSynthesis,
- writable : false,
- enumerable : true
- },
- accelerometer : {
- value : data.accelerometer,
- writable : false,
- enumerable : true
- },
- accelerometerWakeup : {
- value : data.accelerometerWakeup,
- writable : false,
- enumerable : true
- },
- barometer : {
- value : data.barometer,
- writable : false,
- enumerable : true
- },
- barometerWakeup : {
- value : data.barometerWakeup,
- writable : false,
- enumerable : true
- },
- gyroscope : {
- value : data.gyroscope,
- writable : false,
- enumerable : true
- },
- gyroscopeWakeup : {
- value : data.gyroscopeWakeup,
- writable : false,
- enumerable : true
- },
- magnetometer : {
- value : data.magnetometer,
- writable : false,
- enumerable : true
- },
- magnetometerWakeup : {
- value : data.magnetometerWakeup,
- writable : false,
- enumerable : true
- },
- photometer : {
- value : data.photometer,
- writable : false,
- enumerable : true
- },
- photometerWakeup : {
- value : data.photometerWakeup,
- writable : false,
- enumerable : true
- },
- proximity : {
- value : data.proximity,
- writable : false,
- enumerable : true
- },
- proximityWakeup : {
- value : data.proximityWakeup,
- writable : false,
- enumerable : true
- },
- tiltmeter : {
- value : data.tiltmeter,
- writable : false,
- enumerable : true
- },
- tiltmeterWakeup : {
- value : data.tiltmeterWakeup,
- writable : false,
- enumerable : true
- },
- dataEncryption : {
- value : data.dataEncryption,
- writable : false,
- enumerable : true
- },
- graphicsAcceleration : {
- value : data.graphicsAcceleration,
- writable : false,
- enumerable : true
- },
- push : {
- value : data.push,
- writable : false,
- enumerable : true
- },
- telephony : {
- value : data.telephony,
- writable : false,
- enumerable : true
- },
- telephonyMms : {
- value : data.telephonyMms,
- writable : false,
- enumerable : true
- },
- telephonySms : {
- value : data.telephonySms,
- writable : false,
- enumerable : true
- },
- screenSizeNormal : {
- value : data.screenSizeNormal,
- writable : false,
- enumerable : true
- },
- screenSize480_800 : {
- value : data.screenSize480_800,
- writable : false,
- enumerable : true
- },
- screenSize720_1280 : {
- value : data.screenSize720_1280,
- writable : false,
- enumerable : true
- },
- autoRotation : {
- value : data.autoRotation,
- writable : false,
- enumerable : true
- },
- shellAppWidget : {
- value : data.shellAppWidget,
- writable : false,
- enumerable : true
- },
- visionImageRecognition : {
- value : data.visionImageRecognition,
- writable : false,
- enumerable : true
- },
- visionQrcodeGeneration : {
- value : data.visionQrcodeGeneration,
- writable : false,
- enumerable : true
- },
- visionQrcodeRecognition : {
- value : data.visionQrcodeRecognition,
- writable : false,
- enumerable : true
- },
- visionFaceRecognition : {
- value : data.visionFaceRecognition,
- writable : false,
- enumerable : true
- },
- secureElement : {
- value : data.secureElement,
- writable : false,
- enumerable : true
- },
- nativeOspCompatible : {
- value : data.nativeOspCompatible,
- writable : false,
- enumerable : true
- },
- profile : {
- value : data.profile,
- writable : false,
- enumerable : true
+ set: function() {},
+ enumerable: true
+ },
+ platformName: {
+ value: data.platformName,
+ writable: false,
+ enumerable: true
+ },
+ camera: {
+ value: data.camera,
+ writable: false,
+ enumerable: true
+ },
+ cameraFront: {
+ value: data.cameraFront,
+ writable: false,
+ enumerable: true
+ },
+ cameraFrontFlash: {
+ value: data.cameraFrontFlash,
+ writable: false,
+ enumerable: true
+ },
+ cameraBack: {
+ value: data.cameraBack,
+ writable: false,
+ enumerable: true
+ },
+ cameraBackFlash: {
+ value: data.cameraBackFlash,
+ writable: false,
+ enumerable: true
+ },
+ location: {
+ value: data.location,
+ writable: false,
+ enumerable: true
+ },
+ locationGps: {
+ value: data.locationGps,
+ writable: false,
+ enumerable: true
+ },
+ locationWps: {
+ value: data.locationWps,
+ writable: false,
+ enumerable: true
+ },
+ microphone: {
+ value: data.microphone,
+ writable: false,
+ enumerable: true
+ },
+ usbHost: {
+ value: data.usbHost,
+ writable: false,
+ enumerable: true
+ },
+ usbAccessory: {
+ value: data.usbAccessory,
+ writable: false,
+ enumerable: true
+ },
+ screenOutputRca: {
+ value: data.screenOutputRca,
+ writable: false,
+ enumerable: true
+ },
+ screenOutputHdmi: {
+ value: data.screenOutputHdmi,
+ writable: false,
+ enumerable: true
+ },
+ platformCoreCpuArch: {
+ value: data.platformCoreCpuArch,
+ writable: false,
+ enumerable: true
+ },
+ platformCoreFpuArch: {
+ value: data.platformCoreFpuArch,
+ writable: false,
+ enumerable: true
+ },
+ sipVoip: {
+ value: data.sipVoip,
+ writable: false,
+ enumerable: true
+ },
+ duid: {
+ value: data.duid,
+ writable: false,
+ enumerable: true
+ },
+ speechRecognition: {
+ value: data.speechRecognition,
+ writable: false,
+ enumerable: true
+ },
+ speechSynthesis: {
+ value: data.speechSynthesis,
+ writable: false,
+ enumerable: true
+ },
+ accelerometer: {
+ value: data.accelerometer,
+ writable: false,
+ enumerable: true
+ },
+ accelerometerWakeup: {
+ value: data.accelerometerWakeup,
+ writable: false,
+ enumerable: true
+ },
+ barometer: {
+ value: data.barometer,
+ writable: false,
+ enumerable: true
+ },
+ barometerWakeup: {
+ value: data.barometerWakeup,
+ writable: false,
+ enumerable: true
+ },
+ gyroscope: {
+ value: data.gyroscope,
+ writable: false,
+ enumerable: true
+ },
+ gyroscopeWakeup: {
+ value: data.gyroscopeWakeup,
+ writable: false,
+ enumerable: true
+ },
+ magnetometer: {
+ value: data.magnetometer,
+ writable: false,
+ enumerable: true
+ },
+ magnetometerWakeup: {
+ value: data.magnetometerWakeup,
+ writable: false,
+ enumerable: true
+ },
+ photometer: {
+ value: data.photometer,
+ writable: false,
+ enumerable: true
+ },
+ photometerWakeup: {
+ value: data.photometerWakeup,
+ writable: false,
+ enumerable: true
+ },
+ proximity: {
+ value: data.proximity,
+ writable: false,
+ enumerable: true
+ },
+ proximityWakeup: {
+ value: data.proximityWakeup,
+ writable: false,
+ enumerable: true
+ },
+ tiltmeter: {
+ value: data.tiltmeter,
+ writable: false,
+ enumerable: true
+ },
+ tiltmeterWakeup: {
+ value: data.tiltmeterWakeup,
+ writable: false,
+ enumerable: true
+ },
+ dataEncryption: {
+ value: data.dataEncryption,
+ writable: false,
+ enumerable: true
+ },
+ graphicsAcceleration: {
+ value: data.graphicsAcceleration,
+ writable: false,
+ enumerable: true
+ },
+ push: {
+ value: data.push,
+ writable: false,
+ enumerable: true
+ },
+ telephony: {
+ value: data.telephony,
+ writable: false,
+ enumerable: true
+ },
+ telephonyMms: {
+ value: data.telephonyMms,
+ writable: false,
+ enumerable: true
+ },
+ telephonySms: {
+ value: data.telephonySms,
+ writable: false,
+ enumerable: true
+ },
+ screenSizeNormal: {
+ value: data.screenSizeNormal,
+ writable: false,
+ enumerable: true
+ },
+ screenSize480_800: {
+ value: data.screenSize480_800,
+ writable: false,
+ enumerable: true
+ },
+ screenSize720_1280: {
+ value: data.screenSize720_1280,
+ writable: false,
+ enumerable: true
+ },
+ autoRotation: {
+ value: data.autoRotation,
+ writable: false,
+ enumerable: true
+ },
+ shellAppWidget: {
+ value: data.shellAppWidget,
+ writable: false,
+ enumerable: true
+ },
+ visionImageRecognition: {
+ value: data.visionImageRecognition,
+ writable: false,
+ enumerable: true
+ },
+ visionQrcodeGeneration: {
+ value: data.visionQrcodeGeneration,
+ writable: false,
+ enumerable: true
+ },
+ visionQrcodeRecognition: {
+ value: data.visionQrcodeRecognition,
+ writable: false,
+ enumerable: true
+ },
+ visionFaceRecognition: {
+ value: data.visionFaceRecognition,
+ writable: false,
+ enumerable: true
+ },
+ secureElement: {
+ value: data.secureElement,
+ writable: false,
+ enumerable: true
+ },
+ nativeOspCompatible: {
+ value: data.nativeOspCompatible,
+ writable: false,
+ enumerable: true
+ },
+ profile: {
+ value: data.profile,
+ writable: false,
+ enumerable: true
}
});
}
@@ -415,25 +415,25 @@ function SystemInfoDeviceCapability(data) {
//class SystemInfoBattery ////////////////////////////////////////////////////
function SystemInfoBattery(data) {
Object.defineProperties(this, {
- level : {
- value : data.level,
- writable : false,
- enumerable : true
- },
- isCharging : {
- value : data.isCharging,
- writable : false,
- enumerable : true
- },
- timeToDischarge : {
- value : data.timeToDischarge,
- writable : false,
- enumerable : true
- },
- timeToFullCharge : {
- value : data.timeToFullCharge,
- writable : false,
- enumerable : true
+ level: {
+ value: data.level,
+ writable: false,
+ enumerable: true
+ },
+ isCharging: {
+ value: data.isCharging,
+ writable: false,
+ enumerable: true
+ },
+ timeToDischarge: {
+ value: data.timeToDischarge,
+ writable: false,
+ enumerable: true
+ },
+ timeToFullCharge: {
+ value: data.timeToFullCharge,
+ writable: false,
+ enumerable: true
}
});
}
@@ -441,7 +441,7 @@ function SystemInfoBattery(data) {
//class SystemInfoCpu ////////////////////////////////////////////////////
function SystemInfoCpu(data) {
Object.defineProperties(this, {
- load : {
+ load: {
value: data.load,
writable: false,
enumerable: true
@@ -454,31 +454,34 @@ function SystemInfoStorageUnit(data) {
var _isRemovable = data.isRemovable;
Object.defineProperties(this, {
- type : {
+ type: {
value: data.type,
writable: false,
enumerable: true
},
- capacity : {
+ capacity: {
value: Converter_.toUnsignedLongLong(data.capacity),
writable: false,
enumerable: true
},
- availableCapacity : {
- value : Converter_.toUnsignedLongLong(data.availableCapacity),
- writable : false,
- enumerable : true
+ availableCapacity: {
+ value: Converter_.toUnsignedLongLong(data.availableCapacity),
+ writable: false,
+ enumerable: true
},
- isRemovable : {
- value : data.isRemovable,
- writable : false,
- enumerable : true
+ isRemovable: {
+ value: data.isRemovable,
+ writable: false,
+ enumerable: true
},
- isRemoveable : {
- enumerable : true,
+ isRemoveable: {
+ enumerable: true,
get: function() {
- privUtils_.warn('DEPRECATION WARNING: SystemInfoStorageUnit.isRemoveable is is deprecated and will be '
- + 'removed from next release. Use SystemInfoStorageUnit.isRemovable instead.');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: SystemInfoStorageUnit.isRemoveable is is ' +
+ 'deprecated and will be removed from next release. ' +
+ 'Use SystemInfoStorageUnit.isRemovable instead.'
+ );
return _isRemovable;
},
set: function() {}
@@ -494,7 +497,7 @@ function SystemInfoStorage(data) {
storageArray[i] = new SystemInfoStorageUnit(data.storages[i]);
}
Object.defineProperties(this, {
- units : {
+ units: {
value: storageArray,
writable: false,
enumerable: true
@@ -505,37 +508,37 @@ function SystemInfoStorage(data) {
//class SystemInfoDisplay ////////////////////////////////////////////////////
function SystemInfoDisplay(data) {
Object.defineProperties(this, {
- resolutionWidth : {
+ resolutionWidth: {
value: Converter_.toUnsignedLong(data.resolutionWidth),
writable: false,
enumerable: true
},
- resolutionHeight : {
+ resolutionHeight: {
value: Converter_.toUnsignedLong(data.resolutionHeight),
writable: false,
enumerable: true
},
- dotsPerInchWidth : {
+ dotsPerInchWidth: {
value: Converter_.toUnsignedLong(data.dotsPerInchWidth),
writable: false,
enumerable: true
},
- dotsPerInchHeight : {
+ dotsPerInchHeight: {
value: Converter_.toUnsignedLong(data.dotsPerInchHeight),
writable: false,
enumerable: true
},
- physicalWidth : {
+ physicalWidth: {
value: Number(data.physicalWidth),
writable: false,
enumerable: true
},
- physicalHeight : {
+ physicalHeight: {
value: Number(data.physicalHeight),
writable: false,
enumerable: true
},
- brightness : {
+ brightness: {
value: Number(data.brightness),
writable: false,
enumerable: true
@@ -546,73 +549,81 @@ function SystemInfoDisplay(data) {
//class SystemInfoDeviceOrientation ////////////////////////////////////////////////////
function SystemInfoDeviceOrientation(data) {
Object.defineProperties(this, {
- status : {value: data.status, writable: false, enumerable: true},
- isAutoRotation : {value: data.isAutoRotation, writable: false, enumerable: true}
+ status: { value: data.status, writable: false, enumerable: true },
+ isAutoRotation: { value: data.isAutoRotation, writable: false, enumerable: true }
});
}
//class SystemInfoBuild ////////////////////////////////////////////////////
function SystemInfoBuild(data) {
Object.defineProperties(this, {
- model : {value: data.model, writable: false, enumerable: true},
- manufacturer : {value: data.manufacturer, writable: false, enumerable: true},
- buildVersion : {value: data.buildVersion, writable: false, enumerable: true}
+ model: { value: data.model, writable: false, enumerable: true },
+ manufacturer: { value: data.manufacturer, writable: false, enumerable: true },
+ buildVersion: { value: data.buildVersion, writable: false, enumerable: true }
});
}
//class SystemInfoLocale ////////////////////////////////////////////////////
function SystemInfoLocale(data) {
Object.defineProperties(this, {
- language : {value: data.language, writable: false, enumerable: true},
- country : {value: data.country, writable: false, enumerable: true}
+ language: { value: data.language, writable: false, enumerable: true },
+ country: { value: data.country, writable: false, enumerable: true }
});
}
//class SystemInfoNetwork ////////////////////////////////////////////////////
function SystemInfoNetwork(data) {
Object.defineProperties(this, {
- networkType : {value: data.networkType, writable: false, enumerable: true}
+ networkType: { value: data.networkType, writable: false, enumerable: true }
});
}
//class SystemInfoWifiNetwork ////////////////////////////////////////////////////
function SystemInfoWifiNetwork(data) {
Object.defineProperties(this, {
- status : {value: data.status, writable: false, enumerable: true},
- ssid : {value: data.ssid, writable: false, enumerable: true},
- ipAddress : {value: data.ipAddress, writable: false, enumerable: true},
- ipv6Address : {value: data.ipv6Address, writable: false, enumerable: true},
- macAddress : {value: data.macAddress, writable: false, enumerable: true},
- signalStrength : {value: Number(data.signalStrength), writable: false, enumerable: true}
+ status: { value: data.status, writable: false, enumerable: true },
+ ssid: { value: data.ssid, writable: false, enumerable: true },
+ ipAddress: { value: data.ipAddress, writable: false, enumerable: true },
+ ipv6Address: { value: data.ipv6Address, writable: false, enumerable: true },
+ macAddress: { value: data.macAddress, writable: false, enumerable: true },
+ signalStrength: {
+ value: Number(data.signalStrength),
+ writable: false,
+ enumerable: true
+ }
});
}
//class SystemInfoEthernetNetwork ////////////////////////////////////////////////////
function SystemInfoEthernetNetwork(data) {
Object.defineProperties(this, {
- cable : {value: data.cable, writable: false, enumerable: true},
- status : {value: data.status, writable: false, enumerable: true},
- ipAddress : {value: data.ipAddress, writable: false, enumerable: true},
- ipv6Address : {value: data.ipv6Address, writable: false, enumerable: true},
- macAddress : {value: data.macAddress, writable: false, enumerable: true},
+ cable: { value: data.cable, writable: false, enumerable: true },
+ status: { value: data.status, writable: false, enumerable: true },
+ ipAddress: { value: data.ipAddress, writable: false, enumerable: true },
+ ipv6Address: { value: data.ipv6Address, writable: false, enumerable: true },
+ macAddress: { value: data.macAddress, writable: false, enumerable: true }
});
}
//class SystemInfoCellularNetwork ////////////////////////////////////////////////////
function SystemInfoCellularNetwork(data) {
Object.defineProperties(this, {
- status : {value: data.status, writable: false, enumerable: true},
- apn : {value: data.apn, writable: false, enumerable: true},
- ipAddress : {value: data.ipAddress, writable: false, enumerable: true},
- ipv6Address : {value: data.ipv6Address, writable: false, enumerable: true},
- mcc : {value: Number(data.mcc), writable: false, enumerable: true},
- mnc : {value: Number(data.mnc), writable: false, enumerable: true},
- cellId : {value: Number(data.cellId), writable: false, enumerable: true},
- lac : {value: Number(data.lac), writable: false, enumerable: true},
- isRoaming : {value: data.isRoaming, writable: false, enumerable: true},
- isFlightMode : {value: data.isFligthMode, writable: false, enumerable: true},
- imei : {
+ status: { value: data.status, writable: false, enumerable: true },
+ apn: { value: data.apn, writable: false, enumerable: true },
+ ipAddress: { value: data.ipAddress, writable: false, enumerable: true },
+ ipv6Address: { value: data.ipv6Address, writable: false, enumerable: true },
+ mcc: { value: Number(data.mcc), writable: false, enumerable: true },
+ mnc: { value: Number(data.mnc), writable: false, enumerable: true },
+ cellId: { value: Number(data.cellId), writable: false, enumerable: true },
+ lac: { value: Number(data.lac), writable: false, enumerable: true },
+ isRoaming: { value: data.isRoaming, writable: false, enumerable: true },
+ isFlightMode: { value: data.isFligthMode, writable: false, enumerable: true },
+ imei: {
get: function() {
- privUtils_.checkPrivilegeAccess4Ver("2.3.1", privilege_.TELEPHONY, privilege_.SYSTEMMANAGER);
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.3.1',
+ privilege_.TELEPHONY,
+ privilege_.SYSTEMMANAGER
+ );
return data.imei;
},
set: function() {},
@@ -624,14 +635,14 @@ function SystemInfoCellularNetwork(data) {
//class SystemInfoNetProxyNetwork ////////////////////////////////////////////////////
function SystemInfoNetProxyNetwork(data) {
Object.defineProperties(this, {
- status : {value: data.status, writable: false, enumerable: true},
+ status: { value: data.status, writable: false, enumerable: true }
});
}
//class SystemInfoSIM ////////////////////////////////////////////////////
function SystemInfoSIM(data) {
Object.defineProperties(this, {
- state : {
+ state: {
get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return data.state;
@@ -639,7 +650,7 @@ function SystemInfoSIM(data) {
set: function() {},
enumerable: true
},
- operatorName : {
+ operatorName: {
get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return data.operatorName;
@@ -647,15 +658,19 @@ function SystemInfoSIM(data) {
set: function() {},
enumerable: true
},
- msisdn : {
+ msisdn: {
get: function() {
- privUtils_.checkPrivilegeAccess4Ver("2.3.1", privilege_.TELEPHONY, privilege_.SYSTEMMANAGER);
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.3.1',
+ privilege_.TELEPHONY,
+ privilege_.SYSTEMMANAGER
+ );
return data.msisdn;
},
set: function() {},
enumerable: true
},
- iccid : {
+ iccid: {
get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return data.iccid;
@@ -663,7 +678,7 @@ function SystemInfoSIM(data) {
set: function() {},
enumerable: true
},
- mcc : {
+ mcc: {
get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return Number(data.mcc);
@@ -671,7 +686,7 @@ function SystemInfoSIM(data) {
set: function() {},
enumerable: true
},
- mnc : {
+ mnc: {
get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return Number(data.mnc);
@@ -679,92 +694,104 @@ function SystemInfoSIM(data) {
set: function() {},
enumerable: true
},
- msin : {
+ msin: {
get: function() {
- privUtils_.checkPrivilegeAccess4Ver("2.3.1", privilege_.TELEPHONY, privilege_.SYSTEMMANAGER);
+ privUtils_.checkPrivilegeAccess4Ver(
+ '2.3.1',
+ privilege_.TELEPHONY,
+ privilege_.SYSTEMMANAGER
+ );
return data.msin;
},
set: function() {},
enumerable: true
},
- spn : {
+ spn: {
get: function() {
privUtils_.checkPrivilegeAccess(privilege_.SYSTEM);
return data.spn;
},
set: function() {},
enumerable: true
- },
+ }
});
}
//class SystemInfoPeripheral ////////////////////////////////////////////////////
function SystemInfoPeripheral(data) {
Object.defineProperties(this, {
- isVideoOutputOn : {value: data.isVideoOutputOn, writable: false, enumerable: true}
+ isVideoOutputOn: {
+ value: data.isVideoOutputOn,
+ writable: false,
+ enumerable: true
+ }
});
}
//class SystemInfoMemory ////////////////////////////////////////////////////
function SystemInfoMemory(data) {
Object.defineProperties(this, {
- status : {value: data.state, writable: false, enumerable: true}
+ status: { value: data.state, writable: false, enumerable: true }
});
}
function SystemInfoCameraFlash(data) {
- var getBrightness = function() {
- var result = native_.callSync('SystemInfo_getBrightness', {});
- if (native_.isSuccess(result)) {
- return Converter_.toLong(native_.getResultObject(result)) / this.levels;
- }
- return null;
+ var getBrightness = function() {
+ var result = native_.callSync('SystemInfo_getBrightness', {});
+ if (native_.isSuccess(result)) {
+ return Converter_.toLong(native_.getResultObject(result)) / this.levels;
+ }
+ return null;
};
- var getLevels = function() {
- var result = native_.callSync('SystemInfo_getMaxBrightness', {});
- if (native_.isSuccess(result)) {
- return Converter_.toLong(native_.getResultObject(result));
- }
- return null;
+ var getLevels = function() {
+ var result = native_.callSync('SystemInfo_getMaxBrightness', {});
+ if (native_.isSuccess(result)) {
+ return Converter_.toLong(native_.getResultObject(result));
+ }
+ return null;
};
- Object.defineProperties(this, {
- brightness : {set : function(){}, get: getBrightness, enumerable: true},
- camera : {value: data.camera, enumerable: true},
- levels : {get: getLevels, enumerable: true},
+ Object.defineProperties(this, {
+ brightness: { set: function() {}, get: getBrightness, enumerable: true },
+ camera: { value: data.camera, enumerable: true },
+ levels: { get: getLevels, enumerable: true }
});
}
//class SystemInfoADS ////////////////////////////////////////////////////
function SystemInfoADS(data) {
Object.defineProperties(this, {
- id : {value: data.id, writable: false, enumerable: true},
+ id: { value: data.id, writable: false, enumerable: true }
});
}
SystemInfoCameraFlash.prototype.setBrightness = function(brightness) {
- var args = validator_.validateArgs(arguments, [
- {name: 'brightness', type: types_.DOUBLE}
- ]);
- if (args.brightness < 0 || args.brightness > 1)
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Value is not between 0 and 1');
- args.brightness = args.brightness * this.levels;
-
- var result = native_.callSync('SystemInfo_setBrightness', args);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- this.brightness = result;
+ var args = validator_.validateArgs(arguments, [
+ { name: 'brightness', type: types_.DOUBLE }
+ ]);
+ if (args.brightness < 0 || args.brightness > 1)
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Value is not between 0 and 1'
+ );
+ args.brightness = args.brightness * this.levels;
+
+ var result = native_.callSync('SystemInfo_setBrightness', args);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ this.brightness = result;
};
//class SystemInfo ////////////////////////////////////////////////////
-var SystemInfo = function() {
-};
+var SystemInfo = function() {};
SystemInfo.prototype.getCapabilities = function() {
- privUtils_.warn('DEPRECATION WARNING: getCapabilities() is deprecated and will be removed from next release. Use getCapability() instead.');
+ privUtils_.warn(
+ 'DEPRECATION WARNING: getCapabilities() is deprecated and will be removed ' +
+ 'from next release. Use getCapability() instead.'
+ );
var result = native_.callSync('SystemInfo_getCapabilities', {});
if (native_.isFailure(result)) {
@@ -776,13 +803,13 @@ SystemInfo.prototype.getCapabilities = function() {
SystemInfo.prototype.getCapability = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'key',
- type : types_.STRING
- }
- ]);
+ {
+ name: 'key',
+ type: types_.STRING
+ }
+ ]);
- var result = native_.callSync('SystemInfo_getCapability', {key: args.key});
+ var result = native_.callSync('SystemInfo_getCapability', { key: args.key });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
@@ -794,32 +821,41 @@ SystemInfo.prototype.getCapability = function() {
}
};
-
-var _createProperty = function (property, data) {
- if (_propertyContainer[property]){
+var _createProperty = function(property, data) {
+ if (_propertyContainer[property]) {
return new _propertyContainer[property].constructor(data);
} else {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Property with id: ' + property + ' is not supported.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Property with id: ' + property + ' is not supported.'
+ );
}
};
-var _createPropertyArray = function (property, data) {
+var _createPropertyArray = function(property, data) {
var jsonArray = data.array;
var propertyArray = [];
- if (_propertyContainer[property]){
+ if (_propertyContainer[property]) {
var arrayLength = jsonArray.length;
for (var i = 0; i < arrayLength; i++) {
- propertyArray.push(new _propertyContainer[property].constructor(jsonArray[i]));
+ propertyArray.push(
+ new _propertyContainer[property].constructor(jsonArray[i])
+ );
}
} else {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Property with id: ' + property + ' is not supported.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Property with id: ' + property + ' is not supported.'
+ );
}
return propertyArray;
};
-var _checkPropertySupported = function(property){
+var _checkPropertySupported = function(property) {
if (SystemInfoPropertyIdToFeature[property]) {
- var supported = tizen.systeminfo.getCapability(SystemInfoPropertyIdToFeature[property]);
+ var supported = tizen.systeminfo.getCapability(
+ SystemInfoPropertyIdToFeature[property]
+ );
if (!supported) {
return false;
}
@@ -829,37 +865,44 @@ var _checkPropertySupported = function(property){
var getPropertyFunction = function(cppLabel, objectCreateFunction) {
return function() {
- if (arguments[0] === "CELLULAR_NETWORK") {
- privUtils_.checkPrivilegeAccess4Ver("2.4", privilege_.TELEPHONY);
+ if (arguments[0] === 'CELLULAR_NETWORK') {
+ privUtils_.checkPrivilegeAccess4Ver('2.4', privilege_.TELEPHONY);
}
var args = validator_.validateArgs(arguments, [
- {
- name : 'property',
- type : types_.ENUM,
- values : T_.getValues(SystemInfoPropertyId)
- },
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
+ {
+ name: 'property',
+ type: types_.ENUM,
+ values: T_.getValues(SystemInfoPropertyId)
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
var propObject = _propertyContainer[args.property];
if (!propObject) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Property with id: ' + args.property + ' is not supported.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Property with id: ' + args.property + ' is not supported.'
+ );
}
if (_checkPropertySupported(args.property) === false) {
setTimeout(function() {
- native_.callIfPossible(args.errorCallback,
- new WebAPIException(WebAPIException.NOT_SUPPORTED_ERR,
- 'Property with id: ' + args.property + ' is not supported.'));
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.NOT_SUPPORTED_ERR,
+ 'Property with id: ' + args.property + ' is not supported.'
+ )
+ );
}, 0);
return;
}
@@ -867,23 +910,35 @@ var getPropertyFunction = function(cppLabel, objectCreateFunction) {
var callback = function(result) {
if (native_.isFailure(result)) {
setTimeout(function() {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ native_.callIfPossible(
+ args.errorCallback,
+ native_.getErrorObject(result)
+ );
}, 0);
} else {
- var resultProp = objectCreateFunction(args.property, native_.getResultObject(result));
+ var resultProp = objectCreateFunction(
+ args.property,
+ native_.getResultObject(result)
+ );
args.successCallback(resultProp);
}
};
- native_.call(cppLabel, {property: args.property}, callback);
+ native_.call(cppLabel, { property: args.property }, callback);
};
-}
+};
SystemInfo.prototype.getPropertyValue = function() {
- getPropertyFunction('SystemInfo_getPropertyValue', _createProperty).apply(this, arguments);
+ getPropertyFunction('SystemInfo_getPropertyValue', _createProperty).apply(
+ this,
+ arguments
+ );
};
SystemInfo.prototype.getPropertyValueArray = function() {
- getPropertyFunction('SystemInfo_getPropertyValueArray', _createPropertyArray).apply(this, arguments);
+ getPropertyFunction('SystemInfo_getPropertyValueArray', _createPropertyArray).apply(
+ this,
+ arguments
+ );
};
//SystemInfo helpers ///////////////////////////////////////////////////
@@ -906,7 +961,6 @@ var _cameraFlashStr = SystemInfoPropertyId.CAMERA_FLASH;
var _nextId = 0;
-
function _systeminfoBatteryListenerCallback(eventObj) {
var property = _batteryStr;
var callbacks = _propertyContainer[property].callbacks;
@@ -914,22 +968,32 @@ function _systeminfoBatteryListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
/*
* According to documentation, the condition should look like this:
*
- * (T_.isUndefined(listener.lowThreshold) && T_.isUndefined(listener.highThreshold)) ||
- * (!T_.isUndefined(listener.lowThreshold) && !T_.isUndefined(listener.highThreshold) && (propObj.level <= listener.lowThreshold || propObj.level >= listener.highThreshold)) ||
- * (!T_.isUndefined(listener.lowThreshold) && (propObj.level <= listener.lowThreshold)) ||
- * (!T_.isUndefined(listener.highThreshold) && (propObj.level >= listener.highThreshold))
+ * (T_.isUndefined(listener.lowThreshold) &&
+ * T_.isUndefined(listener.highThreshold)) ||
+ * (!T_.isUndefined(listener.lowThreshold) &&
+ * !T_.isUndefined(listener.highThreshold) &&
+ * (propObj.level <= listener.lowThreshold ||
+ * propObj.level >= listener.highThreshold)) ||
+ * (!T_.isUndefined(listener.lowThreshold) &&
+ * (propObj.level <= listener.lowThreshold)) ||
+ * (!T_.isUndefined(listener.highThreshold) &&
+ * (propObj.level >= listener.highThreshold))
*
* but it can be optimized like this:
*/
- var executeCall = (T_.isUndefined(listener.lowThreshold) && T_.isUndefined(listener.highThreshold)) ||
- (!T_.isUndefined(listener.lowThreshold) && propObj.level <= listener.lowThreshold) ||
- (!T_.isUndefined(listener.highThreshold) && propObj.level >= listener.highThreshold);
+ var executeCall =
+ (T_.isUndefined(listener.lowThreshold) &&
+ T_.isUndefined(listener.highThreshold)) ||
+ (!T_.isUndefined(listener.lowThreshold) &&
+ propObj.level <= listener.lowThreshold) ||
+ (!T_.isUndefined(listener.highThreshold) &&
+ propObj.level >= listener.highThreshold);
if (executeCall) {
listener.callback(propObj);
@@ -945,15 +1009,19 @@ function _systeminfoCpuListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
/*
* Optimized condition:
* */
- var executeCall = (T_.isUndefined(listener.lowThreshold) && T_.isUndefined(listener.highThreshold)) ||
- (!T_.isUndefined(listener.lowThreshold) && propObj.load <= listener.lowThreshold) ||
- (!T_.isUndefined(listener.highThreshold) && propObj.load >= listener.highThreshold);
+ var executeCall =
+ (T_.isUndefined(listener.lowThreshold) &&
+ T_.isUndefined(listener.highThreshold)) ||
+ (!T_.isUndefined(listener.lowThreshold) &&
+ propObj.load <= listener.lowThreshold) ||
+ (!T_.isUndefined(listener.highThreshold) &&
+ propObj.load >= listener.highThreshold);
if (executeCall) {
listener.callback(propObj);
}
@@ -968,9 +1036,9 @@ function _systeminfoStorageListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -983,15 +1051,19 @@ function _systeminfoDisplayListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
/*
* Optimized condition:
* */
- var executeCall = (T_.isUndefined(listener.lowThreshold) && T_.isUndefined(listener.highThreshold)) ||
- (!T_.isUndefined(listener.lowThreshold) && propObj.brightness <= listener.lowThreshold) ||
- (!T_.isUndefined(listener.highThreshold) && propObj.brightness >= listener.highThreshold);
+ var executeCall =
+ (T_.isUndefined(listener.lowThreshold) &&
+ T_.isUndefined(listener.highThreshold)) ||
+ (!T_.isUndefined(listener.lowThreshold) &&
+ propObj.brightness <= listener.lowThreshold) ||
+ (!T_.isUndefined(listener.highThreshold) &&
+ propObj.brightness >= listener.highThreshold);
if (executeCall) {
listener.callback(propObj);
}
@@ -1006,9 +1078,9 @@ function _systeminfoDeviceOrientationListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -1021,9 +1093,9 @@ function _systeminfoLocaleListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -1036,9 +1108,9 @@ function _systeminfoNetworkListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -1051,27 +1123,27 @@ function _systeminfoWifiNetworkListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
}
function _systeminfoEthernetNetworkListenerCallback(eventObj) {
- var property = _ethernetNetworkStr;
- var callbacks = _propertyContainer[property].callbacks;
-
- for (var watchId in callbacks) {
- if (callbacks.hasOwnProperty(watchId)) {
- var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
- callbacks[watchId].callback(propObj);
- }
- }
+ var property = _ethernetNetworkStr;
+ var callbacks = _propertyContainer[property].callbacks;
+
+ for (var watchId in callbacks) {
+ if (callbacks.hasOwnProperty(watchId)) {
+ var listener = callbacks[watchId];
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
+ callbacks[watchId].callback(propObj);
+ }
+ }
}
function _systeminfoCellularNetworkListenerCallback(eventObj) {
@@ -1081,14 +1153,17 @@ function _systeminfoCellularNetworkListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- if (!listener.isArrayType && eventObj.changedPropertyIndex != defaultListenerIndex) {
+ if (
+ !listener.isArrayType &&
+ eventObj.changedPropertyIndex != defaultListenerIndex
+ ) {
// if this is not arrayListener, ignore events of non-default SIM
return;
}
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -1101,9 +1176,9 @@ function _systeminfoNetProxyNetworkListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -1116,9 +1191,9 @@ function _systeminfoSimListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -1131,9 +1206,9 @@ function _systeminfoPeripheralListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
@@ -1146,132 +1221,132 @@ function _systeminfoMemoryListenerCallback(eventObj) {
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
}
-function _systeminfoCameraFlashListenerCallback(eventObj) {
+function _systeminfoCameraFlashListenerCallback(eventObj) {
var property = _cameraFlashStr;
var callbacks = _propertyContainer[property].callbacks;
for (var watchId in callbacks) {
if (callbacks.hasOwnProperty(watchId)) {
var listener = callbacks[watchId];
- var propObj = !listener.isArrayType ?
- _createProperty(property, eventObj.result.array[0]) :
- _createPropertyArray(property, eventObj.result);
+ var propObj = !listener.isArrayType
+ ? _createProperty(property, eventObj.result.array[0])
+ : _createPropertyArray(property, eventObj.result);
callbacks[watchId].callback(propObj);
}
}
}
var _propertyContainer = {
- 'BATTERY' : {
- callbacks : {},
- constructor : SystemInfoBattery,
- broadcastFunction : _systeminfoBatteryListenerCallback,
- signalLabel : 'SystemInfoBatteryChangeBroadcast'
- },
- 'CPU' : {
- callbacks : {},
- constructor : SystemInfoCpu,
- broadcastFunction : _systeminfoCpuListenerCallback,
- signalLabel : 'SystemInfoCpuChangeBroadcast'
- },
- 'STORAGE' : {
- callbacks : {},
- constructor : SystemInfoStorage,
- broadcastFunction : _systeminfoStorageListenerCallback,
- signalLabel : 'SystemInfoStorageChangeBroadcast'
- },
- 'DISPLAY' : {
- callbacks : {},
- constructor : SystemInfoDisplay,
- broadcastFunction : _systeminfoDisplayListenerCallback,
- signalLabel : 'SystemInfoDisplayChangeBroadcast'
- },
- 'DEVICE_ORIENTATION' : {
- callbacks : {},
- constructor : SystemInfoDeviceOrientation,
- broadcastFunction : _systeminfoDeviceOrientationListenerCallback,
- signalLabel : 'SystemInfoDeviceOrientationChangeBroadcast'
- },
- 'BUILD' : {
- callbacks : {}, //adding callbacks for build is not possible
- constructor : SystemInfoBuild,
- broadcastFunction : function(){},
- signalLabel : ''
- },
- 'LOCALE' : {
- callbacks : {},
- constructor : SystemInfoLocale,
- broadcastFunction : _systeminfoLocaleListenerCallback,
- signalLabel : 'SystemInfoLocaleChangeBroadcast'
- },
- 'NETWORK' : {
- callbacks : {},
- constructor : SystemInfoNetwork,
- broadcastFunction : _systeminfoNetworkListenerCallback,
- signalLabel : 'SystemInfoNetworkChangeBroadcast'
- },
- 'WIFI_NETWORK' : {
- callbacks : {},
- constructor : SystemInfoWifiNetwork,
- broadcastFunction : _systeminfoWifiNetworkListenerCallback,
- signalLabel : 'SystemInfoWifiNetworkChangeBroadcast'
- },
- 'ETHERNET_NETWORK' : {
- callbacks : {},
- constructor : SystemInfoEthernetNetwork,
- broadcastFunction : _systeminfoEthernetNetworkListenerCallback,
- signalLabel : 'SystemInfoEthernetNetworkChangeBroadcast'
- },
- 'CELLULAR_NETWORK' : {
- callbacks : {},
- constructor : SystemInfoCellularNetwork,
- broadcastFunction : _systeminfoCellularNetworkListenerCallback,
- signalLabel : 'SystemInfoCellularNetworkChangeBroadcast'
- },
- 'NET_PROXY_NETWORK' : {
- callbacks : {},
- constructor : SystemInfoNetProxyNetwork,
- broadcastFunction : _systeminfoNetProxyNetworkListenerCallback,
- signalLabel : 'SystemInfoNetProxyNetworkChangeBroadcast'
- },
- 'SIM' : {
- callbacks : {},
- constructor : SystemInfoSIM,
- broadcastFunction : _systeminfoSimListenerCallback,
- signalLabel : 'SystemInfoSimChangeBroadcast'
- },
- 'PERIPHERAL' : {
- callbacks : {},
- constructor : SystemInfoPeripheral,
- broadcastFunction : _systeminfoPeripheralListenerCallback,
- signalLabel : 'SystemInfoPeripheralChangeBroadcast'
- },
- 'MEMORY' : {
- callbacks : {},
- constructor : SystemInfoMemory,
- broadcastFunction : _systeminfoMemoryListenerCallback,
- signalLabel : 'SystemInfoMemoryChangeBroadcast'
- },
- 'CAMERA_FLASH' : {
- callbacks : {},
- constructor : SystemInfoCameraFlash,
- broadcastFunction : _systeminfoCameraFlashListenerCallback,
- signalLabel : 'SystemInfoCameraFlashChangeBroadcast'
- },
- 'ADS' : {
- callbacks : {}, //adding callbacks for ADS is not possible
- constructor : SystemInfoADS,
- broadcastFunction : function(){},
- signalLabel : ''
- }
+ BATTERY: {
+ callbacks: {},
+ constructor: SystemInfoBattery,
+ broadcastFunction: _systeminfoBatteryListenerCallback,
+ signalLabel: 'SystemInfoBatteryChangeBroadcast'
+ },
+ CPU: {
+ callbacks: {},
+ constructor: SystemInfoCpu,
+ broadcastFunction: _systeminfoCpuListenerCallback,
+ signalLabel: 'SystemInfoCpuChangeBroadcast'
+ },
+ STORAGE: {
+ callbacks: {},
+ constructor: SystemInfoStorage,
+ broadcastFunction: _systeminfoStorageListenerCallback,
+ signalLabel: 'SystemInfoStorageChangeBroadcast'
+ },
+ DISPLAY: {
+ callbacks: {},
+ constructor: SystemInfoDisplay,
+ broadcastFunction: _systeminfoDisplayListenerCallback,
+ signalLabel: 'SystemInfoDisplayChangeBroadcast'
+ },
+ DEVICE_ORIENTATION: {
+ callbacks: {},
+ constructor: SystemInfoDeviceOrientation,
+ broadcastFunction: _systeminfoDeviceOrientationListenerCallback,
+ signalLabel: 'SystemInfoDeviceOrientationChangeBroadcast'
+ },
+ BUILD: {
+ callbacks: {}, //adding callbacks for build is not possible
+ constructor: SystemInfoBuild,
+ broadcastFunction: function() {},
+ signalLabel: ''
+ },
+ LOCALE: {
+ callbacks: {},
+ constructor: SystemInfoLocale,
+ broadcastFunction: _systeminfoLocaleListenerCallback,
+ signalLabel: 'SystemInfoLocaleChangeBroadcast'
+ },
+ NETWORK: {
+ callbacks: {},
+ constructor: SystemInfoNetwork,
+ broadcastFunction: _systeminfoNetworkListenerCallback,
+ signalLabel: 'SystemInfoNetworkChangeBroadcast'
+ },
+ WIFI_NETWORK: {
+ callbacks: {},
+ constructor: SystemInfoWifiNetwork,
+ broadcastFunction: _systeminfoWifiNetworkListenerCallback,
+ signalLabel: 'SystemInfoWifiNetworkChangeBroadcast'
+ },
+ ETHERNET_NETWORK: {
+ callbacks: {},
+ constructor: SystemInfoEthernetNetwork,
+ broadcastFunction: _systeminfoEthernetNetworkListenerCallback,
+ signalLabel: 'SystemInfoEthernetNetworkChangeBroadcast'
+ },
+ CELLULAR_NETWORK: {
+ callbacks: {},
+ constructor: SystemInfoCellularNetwork,
+ broadcastFunction: _systeminfoCellularNetworkListenerCallback,
+ signalLabel: 'SystemInfoCellularNetworkChangeBroadcast'
+ },
+ NET_PROXY_NETWORK: {
+ callbacks: {},
+ constructor: SystemInfoNetProxyNetwork,
+ broadcastFunction: _systeminfoNetProxyNetworkListenerCallback,
+ signalLabel: 'SystemInfoNetProxyNetworkChangeBroadcast'
+ },
+ SIM: {
+ callbacks: {},
+ constructor: SystemInfoSIM,
+ broadcastFunction: _systeminfoSimListenerCallback,
+ signalLabel: 'SystemInfoSimChangeBroadcast'
+ },
+ PERIPHERAL: {
+ callbacks: {},
+ constructor: SystemInfoPeripheral,
+ broadcastFunction: _systeminfoPeripheralListenerCallback,
+ signalLabel: 'SystemInfoPeripheralChangeBroadcast'
+ },
+ MEMORY: {
+ callbacks: {},
+ constructor: SystemInfoMemory,
+ broadcastFunction: _systeminfoMemoryListenerCallback,
+ signalLabel: 'SystemInfoMemoryChangeBroadcast'
+ },
+ CAMERA_FLASH: {
+ callbacks: {},
+ constructor: SystemInfoCameraFlash,
+ broadcastFunction: _systeminfoCameraFlashListenerCallback,
+ signalLabel: 'SystemInfoCameraFlashChangeBroadcast'
+ },
+ ADS: {
+ callbacks: {}, //adding callbacks for ADS is not possible
+ constructor: SystemInfoADS,
+ broadcastFunction: function() {},
+ signalLabel: ''
+ }
};
/// It common function to be called when listener would be triggered
@@ -1281,18 +1356,21 @@ var _listenerFunction = function(msg) {
if (propertyId) {
_propertyContainer[propertyId].broadcastFunction(msg);
} else {
- privUtils_.log("No propertyId provided - ignoring");
+ privUtils_.log('No propertyId provided - ignoring');
}
-}
-native_.addListener("SysteminfoCommonListenerLabel", _listenerFunction);
+};
+native_.addListener('SysteminfoCommonListenerLabel', _listenerFunction);
-var _registerListener = function (property, listener, errorCallback) {
+var _registerListener = function(property, listener, errorCallback) {
var watchId;
- var result={};
+ var result = {};
var propObject = _propertyContainer[property];
if (!propObject) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Property with id: ' + property + ' is not supported.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Property with id: ' + property + ' is not supported.'
+ );
}
var callbackBroadcastFunction = propObject.broadcastFunction;
var signalLabel = propObject.signalLabel;
@@ -1301,9 +1379,9 @@ var _registerListener = function (property, listener, errorCallback) {
var fail = false;
if (T_.isEmptyObject(callbacksMap)) {
//registration in C++ layer
- result = native_.callSync(
- 'SystemInfo_addPropertyValueChangeListener',
- {property: Converter_.toString(property)});
+ result = native_.callSync('SystemInfo_addPropertyValueChangeListener', {
+ property: Converter_.toString(property)
+ });
fail = native_.isFailure(result);
if (native_.isFailure(result)) {
setTimeout(function() {
@@ -1311,7 +1389,7 @@ var _registerListener = function (property, listener, errorCallback) {
}, 0);
}
}
- if (!fail){
+ if (!fail) {
watchId = ++_nextId;
callbacksMap[watchId] = listener;
}
@@ -1319,16 +1397,19 @@ var _registerListener = function (property, listener, errorCallback) {
return Converter_.toUnsignedLong(watchId);
};
-var _identifyListener = function (watchId) {
+var _identifyListener = function(watchId) {
for (var p in _propertyContainer) {
if (_propertyContainer[p].callbacks[watchId]) {
return p;
}
}
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Listener with id: ' + watchId + ' does not exist.');
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Listener with id: ' + watchId + ' does not exist.'
+ );
};
-var _unregisterListener = function (watchId, isTimeout) {
+var _unregisterListener = function(watchId, isTimeout) {
var property = {};
try {
property = _identifyListener(watchId);
@@ -1342,7 +1423,7 @@ var _unregisterListener = function (watchId, isTimeout) {
}
var propObject = _propertyContainer[property];
- var result={};
+ var result = {};
var callbackBroadcastFunction = propObject.broadcastFunction;
var signalLabel = propObject.signalLabel;
@@ -1351,66 +1432,76 @@ var _unregisterListener = function (watchId, isTimeout) {
delete callbacksMap[Number(watchId)];
if (T_.isEmptyObject(callbacksMap)) {
//unregistration in C++ layer
- result = native_.callSync(
- 'SystemInfo_removePropertyValueChangeListener',
- {property: Converter_.toString(property)});
+ result = native_.callSync('SystemInfo_removePropertyValueChangeListener', {
+ property: Converter_.toString(property)
+ });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
}
};
-var getListenerFunction = function (isArray) {
+var getListenerFunction = function(isArray) {
return function() {
- if (arguments[0] === "CELLULAR_NETWORK") {
- privUtils_.checkPrivilegeAccess4Ver("2.4", privilege_.TELEPHONY);
+ if (arguments[0] === 'CELLULAR_NETWORK') {
+ privUtils_.checkPrivilegeAccess4Ver('2.4', privilege_.TELEPHONY);
}
var args = validator_.validateArgs(arguments, [
- {
- name : 'property',
- type : types_.ENUM,
- values : T_.getValues(SystemInfoPropertyId)
- },
- {
- name : 'successCallback',
- type : types_.FUNCTION
- },
- {
- name : 'options',
- type : types_.DICTIONARY,
- optional : true,
- nullable : true
- },
- {
- name : 'errorCallback',
- type : types_.FUNCTION,
- optional : true,
- nullable : true
- }
- ]);
+ {
+ name: 'property',
+ type: types_.ENUM,
+ values: T_.getValues(SystemInfoPropertyId)
+ },
+ {
+ name: 'successCallback',
+ type: types_.FUNCTION
+ },
+ {
+ name: 'options',
+ type: types_.DICTIONARY,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types_.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
if (_checkPropertySupported(args.property) === false) {
setTimeout(function() {
- native_.callIfPossible(args.errorCallback,
- new WebAPIException(WebAPIException.NOT_SUPPORTED_ERR,
- 'Property with id: ' + args.property + ' is not supported.'));
+ native_.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.NOT_SUPPORTED_ERR,
+ 'Property with id: ' + args.property + ' is not supported.'
+ )
+ );
}, 0);
return;
}
var listener = {
- callback : args.successCallback,
- isArrayType : isArray,
- highThreshold : !T_.isNullOrUndefined(args.options) ?
- args.options.highThreshold : undefined,
- lowThreshold : !T_.isNullOrUndefined(args.options) ?
- args.options.lowThreshold : undefined
+ callback: args.successCallback,
+ isArrayType: isArray,
+ highThreshold: !T_.isNullOrUndefined(args.options)
+ ? args.options.highThreshold
+ : undefined,
+ lowThreshold: !T_.isNullOrUndefined(args.options)
+ ? args.options.lowThreshold
+ : undefined
};
var watchId = _registerListener(args.property, listener, args.errorCallback);
- var timeout = !T_.isNullOrUndefined(args.options) ? args.options.timeout : undefined;
- if (!T_.isUndefined(timeout) ){
- setTimeout(function(){_unregisterListener(watchId, true);}, timeout);
+ var timeout = !T_.isNullOrUndefined(args.options)
+ ? args.options.timeout
+ : undefined;
+ if (!T_.isUndefined(timeout)) {
+ setTimeout(function() {
+ _unregisterListener(watchId, true);
+ }, timeout);
}
return watchId;
@@ -1423,11 +1514,11 @@ SystemInfo.prototype.addPropertyValueArrayChangeListener = getListenerFunction(t
SystemInfo.prototype.removePropertyValueChangeListener = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'watchId',
- type : types_.UNSIGNED_LONG
- }
- ]);
+ {
+ name: 'watchId',
+ type: types_.UNSIGNED_LONG
+ }
+ ]);
_unregisterListener(args.watchId, false);
};
@@ -1450,14 +1541,14 @@ SystemInfo.prototype.getAvailableMemory = function() {
SystemInfo.prototype.getCount = function() {
var args = validator_.validateArgs(arguments, [
- {
- name : 'property',
- type : types_.ENUM,
- values : T_.getValues(SystemInfoPropertyId)
- }
- ]);
-
- var result = native_.callSync('SystemInfo_getCount', {property: args.property});
+ {
+ name: 'property',
+ type: types_.ENUM,
+ values: T_.getValues(SystemInfoPropertyId)
+ }
+ ]);
+
+ var result = native_.callSync('SystemInfo_getCount', { property: args.property });
if (native_.isFailure(result)) {
throw native_.getErrorObject(result);
}
diff --git a/src/systemsetting/systemsetting_api.js b/src/systemsetting/systemsetting_api.js
index 1f432a93..630bb342 100644
--- a/src/systemsetting/systemsetting_api.js
+++ b/src/systemsetting/systemsetting_api.js
@@ -14,16 +14,19 @@
* limitations under the License.
*/
-
var validator_ = xwalk.utils.validator;
var type_ = xwalk.utils.type;
var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
-var SystemSettingTypeValues = ['HOME_SCREEN', 'LOCK_SCREEN', 'INCOMING_CALL', 'NOTIFICATION_EMAIL'];
+var SystemSettingTypeValues = [
+ 'HOME_SCREEN',
+ 'LOCK_SCREEN',
+ 'INCOMING_CALL',
+ 'NOTIFICATION_EMAIL'
+];
-function SystemSettingManager() {
-}
+function SystemSettingManager() {}
SystemSettingManager.prototype.getProperty = function() {
var args = validator_.validateArgs(arguments, [
@@ -35,11 +38,10 @@ SystemSettingManager.prototype.getProperty = function() {
var callback = function(result) {
if (native_.isFailure(result)) {
native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- }
- else {
+ } else {
args.successCallback(result.result.value);
}
- }
+ };
var callArgs = {
type: args.type
@@ -48,7 +50,7 @@ SystemSettingManager.prototype.getProperty = function() {
var result = native_.call('SystemSettingManager_getProperty', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
@@ -63,11 +65,10 @@ SystemSettingManager.prototype.setProperty = function() {
var callback = function(result) {
if (native_.isFailure(result)) {
native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- }
- else {
+ } else {
args.successCallback();
}
- }
+ };
var callArgs = {
type: args.type,
@@ -77,10 +78,9 @@ SystemSettingManager.prototype.setProperty = function() {
var result = native_.call('SystemSettingManager_setProperty', callArgs, callback);
if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ throw native_.getErrorObject(result);
}
};
// Exports
exports = new SystemSettingManager();
-
diff --git a/src/time/time_api.js b/src/time/time_api.js
index ba31ab89..9839b387 100644
--- a/src/time/time_api.js
+++ b/src/time/time_api.js
@@ -25,890 +25,920 @@ var _GMT_ID = 'GMT';
var _LOCAL_ID = '__local__';
function _createShiftedDate(tzDate) {
- return new Date(tzDate._shiftedTimestamp);
+ return new Date(tzDate._shiftedTimestamp);
}
function _createUTCDate(tzDate) {
- return new Date(tzDate._utcTimestamp);
+ return new Date(tzDate._utcTimestamp);
}
function _fill(date, tzDate) {
- tzDate._shiftedTimestamp = date.getTime();
- tzDate._utcTimestamp = Number(tzDate._shiftedTimestamp) - Number(tzDate._timezoneOffset);
+ tzDate._shiftedTimestamp = date.getTime();
+ tzDate._utcTimestamp =
+ Number(tzDate._shiftedTimestamp) - Number(tzDate._timezoneOffset);
}
function _fillWithUTC(date, tzDate) {
- tzDate._utcTimestamp = date.getTime();
- tzDate._shiftedTimestamp = Number(tzDate._utcTimestamp) + Number(tzDate._timezoneOffset);
+ tzDate._utcTimestamp = date.getTime();
+ tzDate._shiftedTimestamp =
+ Number(tzDate._utcTimestamp) + Number(tzDate._timezoneOffset);
}
function PrivateTZDate(timestamp, timezone, offset) {
- Object.defineProperties(this, {
- ts : {value: timestamp, writable: false, enumerable: false},
- tzId : {value: timezone, writable: false, enumerable: false},
- o : {value: offset, writable: false, enumerable: false}
- });
+ Object.defineProperties(this, {
+ ts: { value: timestamp, writable: false, enumerable: false },
+ tzId: { value: timezone, writable: false, enumerable: false },
+ o: { value: offset, writable: false, enumerable: false }
+ });
}
function _getTimezoneOffset(timestamp, tzName) {
- var callArgs = {
- timezone : converter_.toString(tzName),
- timestamp : converter_.toString(timestamp)
- };
- var result = native_.callSync('TZDate_getTimezoneOffset', callArgs);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- var res = {
- offset : converter_.toLong(native_.getResultObject(result).offset),
- modifier : converter_.toLong(native_.getResultObject(result).modifier)
- };
- return res;
+ var callArgs = {
+ timezone: converter_.toString(tzName),
+ timestamp: converter_.toString(timestamp)
+ };
+ var result = native_.callSync('TZDate_getTimezoneOffset', callArgs);
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ var res = {
+ offset: converter_.toLong(native_.getResultObject(result).offset),
+ modifier: converter_.toLong(native_.getResultObject(result).modifier)
+ };
+ return res;
}
function _getLocalTimezoneOffset(utcTimestamp) {
- return -1 * (new Date(utcTimestamp).getTimezoneOffset()) * 60 * 1000; // cast to milliseconds
+ // cast to milliseconds
+ return -1 * new Date(utcTimestamp).getTimezoneOffset() * 60 * 1000;
}
function _constructTZDate(obj, privateTZDate) {
- var utcTimestamp = privateTZDate.ts;
- var tzName = privateTZDate.tzId;
- var offset = privateTZDate.o;
+ var utcTimestamp = privateTZDate.ts;
+ var tzName = privateTZDate.tzId;
+ var offset = privateTZDate.o;
- switch (tzName) {
- case _LOCAL_ID:
- utils_.log('Entered _constructTZDate for local timezone');
+ switch (tzName) {
+ case _LOCAL_ID:
+ utils_.log('Entered _constructTZDate for local timezone');
- tzName = tizen.time.getLocalTimezone();
+ tzName = tizen.time.getLocalTimezone();
- if (T.isNullOrUndefined(offset)) {
- offset = _getLocalTimezoneOffset(utcTimestamp);
- }
- break;
+ if (T.isNullOrUndefined(offset)) {
+ offset = _getLocalTimezoneOffset(utcTimestamp);
+ }
+ break;
- case _GMT_ID:
- utils_.log('Entered _constructTZDate for GMT');
+ case _GMT_ID:
+ utils_.log('Entered _constructTZDate for GMT');
- if (T.isNullOrUndefined(offset)) {
- offset = 0;
- }
- break;
+ if (T.isNullOrUndefined(offset)) {
+ offset = 0;
+ }
+ break;
- default:
- utils_.log('Entered _constructTZDate for: ' + tzName);
- if (T.isNullOrUndefined(offset)) {
- // throws if tzName is invalid
- offset = _getTimezoneOffset(utcTimestamp, tzName).offset;
+ default:
+ utils_.log('Entered _constructTZDate for: ' + tzName);
+ if (T.isNullOrUndefined(offset)) {
+ // throws if tzName is invalid
+ offset = _getTimezoneOffset(utcTimestamp, tzName).offset;
+ }
+ break;
}
- break;
- }
- Object.defineProperties(obj, {
- _utcTimestamp : {value: utcTimestamp, writable: true, enumerable: false},
- _shiftedTimestamp : {value: utcTimestamp + offset, writable: true, enumerable: false},
- _timezoneName : {value: tzName, writable: true, enumerable: false},
- _timezoneOffset : {value: offset, writable: true, enumerable: false}
- });
+ Object.defineProperties(obj, {
+ _utcTimestamp: { value: utcTimestamp, writable: true, enumerable: false },
+ _shiftedTimestamp: {
+ value: utcTimestamp + offset,
+ writable: true,
+ enumerable: false
+ },
+ _timezoneName: { value: tzName, writable: true, enumerable: false },
+ _timezoneOffset: { value: offset, writable: true, enumerable: false }
+ });
}
//class TZDate ////////////////////////////////////////////////////
tizen.TZDate = function(p1, p2, day, hours, minutes, seconds, milliseconds, timezone) {
- utils_.log("Entered tizen.TZDate");
- validator_.validateConstructorCall(this, tizen.TZDate);
-
- var priv;
- //copy constructor section (should be only for private usage)
- if (p1 instanceof PrivateTZDate) {
- priv = p1;
- } else {
- //Public constructor section
- utils_.log('Entered TZDate constructor with: ' + arguments.length + ' attributes');
-
- var date;
-
- if (arguments.length < 3) {
- if (T.isDate(p1)) {
- date = p1;
- } else {
- date = new Date();
- }
- timezone = p2;
+ utils_.log('Entered tizen.TZDate');
+ validator_.validateConstructorCall(this, tizen.TZDate);
+
+ var priv;
+ //copy constructor section (should be only for private usage)
+ if (p1 instanceof PrivateTZDate) {
+ priv = p1;
} else {
- p1 = p1 ? p1 : 0;
- p2 = p2 ? p2 : 0;
- day = day ? day : 0;
- hours = hours ? hours : 0;
- minutes = minutes ? minutes : 0;
- seconds = seconds ? seconds : 0;
- milliseconds = milliseconds ? milliseconds : 0;
-
- date = new Date(p1, p2, day, hours, minutes, seconds, milliseconds);
- }
-
- var utcTimestamp = date.getTime();
- var offset = _getLocalTimezoneOffset(utcTimestamp);
- var tzName = _LOCAL_ID;
-
- if (!T.isNullOrUndefined(timezone)) {
- timezone = converter_.toString(timezone);
- var timezoneTimestamp = new Date(Date.UTC(date.getFullYear(),
- date.getMonth(),
- date.getDate(),
- date.getHours(),
- date.getMinutes(),
- date.getSeconds(),
- date.getMilliseconds())).getTime();
- try {
- var offsetObject = _getTimezoneOffset(timezoneTimestamp, timezone);
- offset = offsetObject.offset;
- utcTimestamp = timezoneTimestamp - offset;
- //correction of missing/extra hour on DST change
- var modifier = offsetObject.modifier;
- if (modifier > 0) {
- //this is for case when 2AM becomes 3AM (but offset must be corrected -
- //missing one hour)
- offset += modifier;
+ //Public constructor section
+ utils_.log(
+ 'Entered TZDate constructor with: ' + arguments.length + ' attributes'
+ );
+
+ var date;
+
+ if (arguments.length < 3) {
+ if (T.isDate(p1)) {
+ date = p1;
+ } else {
+ date = new Date();
+ }
+ timezone = p2;
} else {
- //this is for case when extra hour appers - prevents error of
- //unnecessary shift of hour when timezone changes
- offset -= modifier;
- utcTimestamp += modifier;
+ p1 = p1 ? p1 : 0;
+ p2 = p2 ? p2 : 0;
+ day = day ? day : 0;
+ hours = hours ? hours : 0;
+ minutes = minutes ? minutes : 0;
+ seconds = seconds ? seconds : 0;
+ milliseconds = milliseconds ? milliseconds : 0;
+
+ date = new Date(p1, p2, day, hours, minutes, seconds, milliseconds);
}
- tzName = timezone;
- } catch(e) {
- // in case of exception we fall back to local time zone
- }
- }
- priv = new PrivateTZDate(utcTimestamp, tzName, offset);
- }
+ var utcTimestamp = date.getTime();
+ var offset = _getLocalTimezoneOffset(utcTimestamp);
+ var tzName = _LOCAL_ID;
+
+ if (!T.isNullOrUndefined(timezone)) {
+ timezone = converter_.toString(timezone);
+ var timezoneTimestamp = new Date(
+ Date.UTC(
+ date.getFullYear(),
+ date.getMonth(),
+ date.getDate(),
+ date.getHours(),
+ date.getMinutes(),
+ date.getSeconds(),
+ date.getMilliseconds()
+ )
+ ).getTime();
+ try {
+ var offsetObject = _getTimezoneOffset(timezoneTimestamp, timezone);
+ offset = offsetObject.offset;
+ utcTimestamp = timezoneTimestamp - offset;
+ //correction of missing/extra hour on DST change
+ var modifier = offsetObject.modifier;
+ if (modifier > 0) {
+ //this is for case when 2AM becomes 3AM (but offset must be
+ //corrected - missing one hour)
+ offset += modifier;
+ } else {
+ //this is for case when extra hour appers - prevents error of
+ //unnecessary shift of hour when timezone changes
+ offset -= modifier;
+ utcTimestamp += modifier;
+ }
+ tzName = timezone;
+ } catch (e) {
+ // in case of exception we fall back to local time zone
+ }
+ }
+
+ priv = new PrivateTZDate(utcTimestamp, tzName, offset);
+ }
- _constructTZDate(this, priv);
+ _constructTZDate(this, priv);
};
tizen.TZDate.prototype.getDate = function() {
- utils_.log('Entered TZDate.getDate');
- //getters realized with pattern
- //---> use _shiftedTimestamp (_utcTimestamp (UTC) with added _timezoneOffset)
- //---> create Date instance
- //---> return d.getUTCDate() --- to avoid locale timezone impact of JS Date object
- return _createShiftedDate(this).getUTCDate();
+ utils_.log('Entered TZDate.getDate');
+ //getters realized with pattern
+ //---> use _shiftedTimestamp (_utcTimestamp (UTC) with added _timezoneOffset)
+ //---> create Date instance
+ //---> return d.getUTCDate() --- to avoid locale timezone impact of JS Date object
+ return _createShiftedDate(this).getUTCDate();
};
function _updateTZDate(tzdate, args, param, func) {
- var a = validator_.validateMethod(args, [
- {
- name : param,
- type : validator_.Types.LONG
- }
- ]);
-
- //setters realized with pattern
- //---> use _shiftedTimestamp (_utcTimestamp (UTC) with added _timezoneOffset)
- //---> create Date instance
- //---> setUTCDate of JS Date object
- //---> getTime of object to set _shiftedTimestmp (avoiding timezone of JS Date)
- //---> fix _utcTimestamp with subtraction of _timezoneOffset
- var date = _createShiftedDate(tzdate);
- date[func](a[param]);
- _fill(date, tzdate);
+ var a = validator_.validateMethod(args, [
+ {
+ name: param,
+ type: validator_.Types.LONG
+ }
+ ]);
+
+ //setters realized with pattern
+ //---> use _shiftedTimestamp (_utcTimestamp (UTC) with added _timezoneOffset)
+ //---> create Date instance
+ //---> setUTCDate of JS Date object
+ //---> getTime of object to set _shiftedTimestmp (avoiding timezone of JS Date)
+ //---> fix _utcTimestamp with subtraction of _timezoneOffset
+ var date = _createShiftedDate(tzdate);
+ date[func](a[param]);
+ _fill(date, tzdate);
}
function _updateTZDateUTC(tzdate, args, param, func) {
- var a = validator_.validateMethod(args, [
- {
- name : param,
- type : validator_.Types.LONG
- }
- ]);
- var date = _createUTCDate(tzdate);
- date[func](a[param]);
- _fillWithUTC(date, tzdate);
+ var a = validator_.validateMethod(args, [
+ {
+ name: param,
+ type: validator_.Types.LONG
+ }
+ ]);
+ var date = _createUTCDate(tzdate);
+ date[func](a[param]);
+ _fillWithUTC(date, tzdate);
}
tizen.TZDate.prototype.setDate = function() {
- utils_.log('Entered TZDate.setDate');
- _updateTZDate(this, arguments, 'date', 'setUTCDate');
+ utils_.log('Entered TZDate.setDate');
+ _updateTZDate(this, arguments, 'date', 'setUTCDate');
};
tizen.TZDate.prototype.getDay = function() {
- utils_.log('Entered TZDate.getDay');
- return _createShiftedDate(this).getUTCDay();
+ utils_.log('Entered TZDate.getDay');
+ return _createShiftedDate(this).getUTCDay();
};
tizen.TZDate.prototype.getFullYear = function() {
- utils_.log('Entered TZDate.getFullYear');
- return _createShiftedDate(this).getUTCFullYear();
+ utils_.log('Entered TZDate.getFullYear');
+ return _createShiftedDate(this).getUTCFullYear();
};
tizen.TZDate.prototype.setFullYear = function() {
- utils_.log('Entered TZDate.setFullYear');
- _updateTZDate(this, arguments, 'year', 'setUTCFullYear');
+ utils_.log('Entered TZDate.setFullYear');
+ _updateTZDate(this, arguments, 'year', 'setUTCFullYear');
};
tizen.TZDate.prototype.getHours = function() {
- utils_.log('Entered TZDate.getHours');
- return _createShiftedDate(this).getUTCHours();
+ utils_.log('Entered TZDate.getHours');
+ return _createShiftedDate(this).getUTCHours();
};
tizen.TZDate.prototype.setHours = function() {
- utils_.log('Entered TZDate.setHours');
- _updateTZDate(this, arguments, 'hours', 'setUTCHours');
+ utils_.log('Entered TZDate.setHours');
+ _updateTZDate(this, arguments, 'hours', 'setUTCHours');
};
tizen.TZDate.prototype.getMilliseconds = function() {
- utils_.log('Entered TZDate.getMilliseconds');
- return _createShiftedDate(this).getUTCMilliseconds();
+ utils_.log('Entered TZDate.getMilliseconds');
+ return _createShiftedDate(this).getUTCMilliseconds();
};
tizen.TZDate.prototype.setMilliseconds = function() {
- utils_.log('Entered TZDate.setMilliseconds');
- _updateTZDate(this, arguments, 'ms', 'setUTCMilliseconds');
+ utils_.log('Entered TZDate.setMilliseconds');
+ _updateTZDate(this, arguments, 'ms', 'setUTCMilliseconds');
};
tizen.TZDate.prototype.getMinutes = function() {
- utils_.log('Entered TZDate.getMinutes');
- return _createShiftedDate(this).getUTCMinutes();
+ utils_.log('Entered TZDate.getMinutes');
+ return _createShiftedDate(this).getUTCMinutes();
};
tizen.TZDate.prototype.setMinutes = function() {
- utils_.log('Entered TZDate.setMinutes');
- _updateTZDate(this, arguments, 'minutes', 'setUTCMinutes');
+ utils_.log('Entered TZDate.setMinutes');
+ _updateTZDate(this, arguments, 'minutes', 'setUTCMinutes');
};
tizen.TZDate.prototype.getMonth = function() {
- utils_.log('Entered TZDate.getMonth');
- return _createShiftedDate(this).getUTCMonth();
+ utils_.log('Entered TZDate.getMonth');
+ return _createShiftedDate(this).getUTCMonth();
};
tizen.TZDate.prototype.setMonth = function() {
- utils_.log('Entered TZDate.setMonth');
- _updateTZDate(this, arguments, 'month', 'setUTCMonth');
+ utils_.log('Entered TZDate.setMonth');
+ _updateTZDate(this, arguments, 'month', 'setUTCMonth');
};
tizen.TZDate.prototype.getSeconds = function() {
- utils_.log('Entered TZDate.getSeconds');
- return _createShiftedDate(this).getUTCSeconds();
+ utils_.log('Entered TZDate.getSeconds');
+ return _createShiftedDate(this).getUTCSeconds();
};
tizen.TZDate.prototype.setSeconds = function() {
- utils_.log('Entered TZDate.setSeconds');
- _updateTZDate(this, arguments, 'seconds', 'setUTCSeconds');
+ utils_.log('Entered TZDate.setSeconds');
+ _updateTZDate(this, arguments, 'seconds', 'setUTCSeconds');
};
tizen.TZDate.prototype.getUTCDate = function() {
- utils_.log('Entered TZDate.getUTCDate');
- return _createUTCDate(this).getUTCDate();
+ utils_.log('Entered TZDate.getUTCDate');
+ return _createUTCDate(this).getUTCDate();
};
tizen.TZDate.prototype.setUTCDate = function() {
- utils_.log('Entered TZDate.setUTCDate');
- _updateTZDateUTC(this, arguments, 'date', 'setUTCDate');
+ utils_.log('Entered TZDate.setUTCDate');
+ _updateTZDateUTC(this, arguments, 'date', 'setUTCDate');
};
tizen.TZDate.prototype.getUTCDay = function() {
- utils_.log('Entered TZDate.getUTCDay');
- return _createUTCDate(this).getUTCDay();
+ utils_.log('Entered TZDate.getUTCDay');
+ return _createUTCDate(this).getUTCDay();
};
tizen.TZDate.prototype.getUTCFullYear = function() {
- utils_.log('Entered TZDate.getUTCFullYear');
- return _createUTCDate(this).getUTCFullYear();
+ utils_.log('Entered TZDate.getUTCFullYear');
+ return _createUTCDate(this).getUTCFullYear();
};
tizen.TZDate.prototype.setUTCFullYear = function() {
- utils_.log('Entered TZDate.setUTCFullYear');
- _updateTZDateUTC(this, arguments, 'year', 'setUTCFullYear');
+ utils_.log('Entered TZDate.setUTCFullYear');
+ _updateTZDateUTC(this, arguments, 'year', 'setUTCFullYear');
};
tizen.TZDate.prototype.getUTCHours = function() {
- utils_.log('Entered TZDate.getUTCHours');
- return _createUTCDate(this).getUTCHours();
+ utils_.log('Entered TZDate.getUTCHours');
+ return _createUTCDate(this).getUTCHours();
};
tizen.TZDate.prototype.setUTCHours = function() {
- utils_.log('Entered TZDate.setUTCHours');
- _updateTZDateUTC(this, arguments, 'hours', 'setUTCHours');
+ utils_.log('Entered TZDate.setUTCHours');
+ _updateTZDateUTC(this, arguments, 'hours', 'setUTCHours');
};
tizen.TZDate.prototype.getUTCMilliseconds = function() {
- utils_.log('Entered TZDate.getUTCMilliseconds');
- return _createUTCDate(this).getUTCMilliseconds();
+ utils_.log('Entered TZDate.getUTCMilliseconds');
+ return _createUTCDate(this).getUTCMilliseconds();
};
tizen.TZDate.prototype.setUTCMilliseconds = function() {
- utils_.log('Entered TZDate.setUTCMilliseconds');
- _updateTZDateUTC(this, arguments, 'ms', 'setUTCMilliseconds');
+ utils_.log('Entered TZDate.setUTCMilliseconds');
+ _updateTZDateUTC(this, arguments, 'ms', 'setUTCMilliseconds');
};
tizen.TZDate.prototype.getUTCMinutes = function() {
- utils_.log('Entered TZDate.getUTCMinutes');
- return _createUTCDate(this).getUTCMinutes();
+ utils_.log('Entered TZDate.getUTCMinutes');
+ return _createUTCDate(this).getUTCMinutes();
};
tizen.TZDate.prototype.setUTCMinutes = function() {
- utils_.log('Entered TZDate.setUTCMinutes');
- _updateTZDateUTC(this, arguments, 'minutes', 'setUTCMinutes');
+ utils_.log('Entered TZDate.setUTCMinutes');
+ _updateTZDateUTC(this, arguments, 'minutes', 'setUTCMinutes');
};
tizen.TZDate.prototype.getUTCMonth = function() {
- utils_.log('Entered TZDate.getUTCMonth');
- return _createUTCDate(this).getUTCMonth();
+ utils_.log('Entered TZDate.getUTCMonth');
+ return _createUTCDate(this).getUTCMonth();
};
tizen.TZDate.prototype.setUTCMonth = function() {
- utils_.log('Entered TZDate.setUTCMonth');
- _updateTZDateUTC(this, arguments, 'month', 'setUTCMonth');
+ utils_.log('Entered TZDate.setUTCMonth');
+ _updateTZDateUTC(this, arguments, 'month', 'setUTCMonth');
};
tizen.TZDate.prototype.getUTCSeconds = function() {
- utils_.log('Entered TZDate.getUTCSeconds');
- return _createUTCDate(this).getUTCSeconds();
+ utils_.log('Entered TZDate.getUTCSeconds');
+ return _createUTCDate(this).getUTCSeconds();
};
tizen.TZDate.prototype.setUTCSeconds = function() {
- utils_.log('Entered TZDate.setUTCSeconds');
- _updateTZDateUTC(this, arguments, 'seconds', 'setUTCSeconds');
+ utils_.log('Entered TZDate.setUTCSeconds');
+ _updateTZDateUTC(this, arguments, 'seconds', 'setUTCSeconds');
};
tizen.TZDate.prototype.getTimezone = function() {
- utils_.log('Entered TZDate.getTimezone');
- return this._timezoneName;
+ utils_.log('Entered TZDate.getTimezone');
+ return this._timezoneName;
};
tizen.TZDate.prototype.toTimezone = function() {
- utils_.log('Entered TZDate.toTimezone');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'timezone',
- type : validator_.Types.STRING
- }
- ]);
- return new tizen.TZDate(new PrivateTZDate(this._utcTimestamp, args.timezone));
+ utils_.log('Entered TZDate.toTimezone');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'timezone',
+ type: validator_.Types.STRING
+ }
+ ]);
+ return new tizen.TZDate(new PrivateTZDate(this._utcTimestamp, args.timezone));
};
tizen.TZDate.prototype.toLocalTimezone = function() {
- utils_.log('Entered TZDate.toLocalTimezone');
- return new tizen.TZDate(new PrivateTZDate(this._utcTimestamp, _LOCAL_ID));
+ utils_.log('Entered TZDate.toLocalTimezone');
+ return new tizen.TZDate(new PrivateTZDate(this._utcTimestamp, _LOCAL_ID));
};
tizen.TZDate.prototype.toUTC = function() {
- utils_.log('Entered TZDate.toUTC');
- return new tizen.TZDate(new PrivateTZDate(this._utcTimestamp, _GMT_ID));
+ utils_.log('Entered TZDate.toUTC');
+ return new tizen.TZDate(new PrivateTZDate(this._utcTimestamp, _GMT_ID));
};
tizen.TZDate.prototype.difference = function() {
- utils_.log('Entered TZDate.difference');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TZDate
- }
- ]);
- var length = this._utcTimestamp - args.other._utcTimestamp;
- var type = _timeDurationUnit.MSECS;
- if (length % _timeDurationUnitValue.DAYS === 0) {
- length /= _timeDurationUnitValue.DAYS;
- type = _timeDurationUnit.DAYS;
- }
- return new tizen.TimeDuration(length, type);
+ utils_.log('Entered TZDate.difference');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TZDate
+ }
+ ]);
+ var length = this._utcTimestamp - args.other._utcTimestamp;
+ var type = _timeDurationUnit.MSECS;
+ if (length % _timeDurationUnitValue.DAYS === 0) {
+ length /= _timeDurationUnitValue.DAYS;
+ type = _timeDurationUnit.DAYS;
+ }
+ return new tizen.TimeDuration(length, type);
};
tizen.TZDate.prototype.equalsTo = function() {
- utils_.log('Entered TZDate.equalsTo');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TZDate
- }
- ]);
- return this._utcTimestamp === args.other._utcTimestamp;
+ utils_.log('Entered TZDate.equalsTo');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TZDate
+ }
+ ]);
+ return this._utcTimestamp === args.other._utcTimestamp;
};
tizen.TZDate.prototype.earlierThan = function() {
- utils_.log('Entered TZDate.earlierThan');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TZDate
- }
- ]);
- return this._utcTimestamp < args.other._utcTimestamp;
+ utils_.log('Entered TZDate.earlierThan');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TZDate
+ }
+ ]);
+ return this._utcTimestamp < args.other._utcTimestamp;
};
tizen.TZDate.prototype.laterThan = function() {
- utils_.log('Entered TZDate.laterThan');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TZDate
- }
- ]);
- return this._utcTimestamp > args.other._utcTimestamp;
+ utils_.log('Entered TZDate.laterThan');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TZDate
+ }
+ ]);
+ return this._utcTimestamp > args.other._utcTimestamp;
};
tizen.TZDate.prototype.addDuration = function() {
- utils_.log('Entered TZDate.addDuration');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'duration',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TimeDuration
- }
- ]);
- return new tizen.TZDate(new PrivateTZDate(this._utcTimestamp +
- _getLengthInMsecsUnit(args.duration.length, args.duration.unit),
- this._timezoneName));
+ utils_.log('Entered TZDate.addDuration');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'duration',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TimeDuration
+ }
+ ]);
+ return new tizen.TZDate(
+ new PrivateTZDate(
+ this._utcTimestamp +
+ _getLengthInMsecsUnit(args.duration.length, args.duration.unit),
+ this._timezoneName
+ )
+ );
};
tizen.TZDate.prototype.toLocaleDateString = function() {
- utils_.log('Entered TZDate.toLocaleDateString');
- var result = native_.callSync('TZDate_toLocaleDateString',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).string;
+ utils_.log('Entered TZDate.toLocaleDateString');
+ var result = native_.callSync('TZDate_toLocaleDateString', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).string;
};
tizen.TZDate.prototype.toLocaleTimeString = function() {
- utils_.log('Entered TZDate.toLocaleTimeString');
- var result = native_.callSync('TZDate_toLocaleTimeString',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).string;
+ utils_.log('Entered TZDate.toLocaleTimeString');
+ var result = native_.callSync('TZDate_toLocaleTimeString', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).string;
};
tizen.TZDate.prototype.toLocaleString = function() {
- utils_.log('Entered TZDate.toLocaleString');
- var result = native_.callSync('TZDate_toLocaleString',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).string;
+ utils_.log('Entered TZDate.toLocaleString');
+ var result = native_.callSync('TZDate_toLocaleString', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).string;
};
tizen.TZDate.prototype.toDateString = function() {
- utils_.log('Entered TZDate.toDateString');
- var result = native_.callSync('TZDate_toDateString',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).string;
+ utils_.log('Entered TZDate.toDateString');
+ var result = native_.callSync('TZDate_toDateString', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).string;
};
tizen.TZDate.prototype.toTimeString = function() {
- utils_.log('Entered TZDate.toTimeString');
- var result = native_.callSync('TZDate_toTimeString',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).string;
+ utils_.log('Entered TZDate.toTimeString');
+ var result = native_.callSync('TZDate_toTimeString', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).string;
};
tizen.TZDate.prototype.toString = function() {
- utils_.log('Entered TZDate.toString');
- var result = native_.callSync('TZDate_toString',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).string;
+ utils_.log('Entered TZDate.toString');
+ var result = native_.callSync('TZDate_toString', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).string;
};
tizen.TZDate.prototype.getTimezoneAbbreviation = function() {
- utils_.log('Entered TZDate.getTimezoneAbbreviation');
- utils_.warn('DEPRECATION WARNING: getTimezoneAbbreviation() is deprecated and will be removed from next release.');
-
- var result = native_.callSync('TZDate_getTimezoneAbbreviation',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).abbreviation;
+ utils_.log('Entered TZDate.getTimezoneAbbreviation');
+ utils_.warn(
+ 'DEPRECATION WARNING: getTimezoneAbbreviation() is deprecated and will be ' +
+ 'removed from next release.'
+ );
+
+ var result = native_.callSync('TZDate_getTimezoneAbbreviation', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).abbreviation;
};
tizen.TZDate.prototype.secondsFromUTC = function() {
- utils_.log('Entered TZDate.secondsFromUTC');
- return -this._timezoneOffset/1000;
+ utils_.log('Entered TZDate.secondsFromUTC');
+ return -this._timezoneOffset / 1000;
};
tizen.TZDate.prototype.isDST = function() {
- utils_.log('Entered TZDate.isDST');
- var result = native_.callSync('TZDate_isDST',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).isDST;
+ utils_.log('Entered TZDate.isDST');
+ var result = native_.callSync('TZDate_isDST', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).isDST;
};
tizen.TZDate.prototype.getPreviousDSTTransition = function() {
- utils_.log('Entered TZDate.getPreviousDSTTransition');
- var result = native_.callSync('TZDate_getPreviousDSTTransition',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ utils_.log('Entered TZDate.getPreviousDSTTransition');
+ var result = native_.callSync('TZDate_getPreviousDSTTransition', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return new tizen.TZDate(new PrivateTZDate(native_.getResultObject(result).prevDSTDate,
- this._timezoneName));
+ return new tizen.TZDate(
+ new PrivateTZDate(native_.getResultObject(result).prevDSTDate, this._timezoneName)
+ );
};
tizen.TZDate.prototype.getNextDSTTransition = function() {
- utils_.log('Entered TZDate.getNextDSTTransition');
- var result = native_.callSync('TZDate_getNextDSTTransition',
- {timezone: String(this._timezoneName),
- timestamp: String(this._utcTimestamp)});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ utils_.log('Entered TZDate.getNextDSTTransition');
+ var result = native_.callSync('TZDate_getNextDSTTransition', {
+ timezone: String(this._timezoneName),
+ timestamp: String(this._utcTimestamp)
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return new tizen.TZDate(new PrivateTZDate(native_.getResultObject(result).nextDSTDate,
- this._timezoneName));
+ return new tizen.TZDate(
+ new PrivateTZDate(native_.getResultObject(result).nextDSTDate, this._timezoneName)
+ );
};
//TimeUtil helpers ///////////////////////////////////////////////////
var _timeDurationUnit = {
MSECS: 'MSECS',
- SECS : 'SECS',
- MINS : 'MINS',
+ SECS: 'SECS',
+ MINS: 'MINS',
HOURS: 'HOURS',
- DAYS : 'DAYS'
+ DAYS: 'DAYS'
};
var _timeDurationUnitValue = {
MSECS: Number(1),
- SECS : Number(1000),
- MINS : Number(60*1000),
- HOURS: Number(60*60*1000),
- DAYS : Number(24*60*60*1000)
+ SECS: Number(1000),
+ MINS: Number(60 * 1000),
+ HOURS: Number(60 * 60 * 1000),
+ DAYS: Number(24 * 60 * 60 * 1000)
};
function _getLengthInMsecsUnit(length, unit) {
- if (unit === _timeDurationUnit.MSECS) {
- return length;
- } else if (unit === _timeDurationUnit.SECS) {
- return length * _timeDurationUnitValue.SECS;
- } else if (unit === _timeDurationUnit.MINS) {
- return length * _timeDurationUnitValue.MINS;
- } else if (unit === _timeDurationUnit.HOURS) {
- return length * _timeDurationUnitValue.HOURS;
- } else if (unit === _timeDurationUnit.DAYS) {
- return length * _timeDurationUnitValue.DAYS;
- } else {
- native_.throwTypeMismatch();
- }
+ if (unit === _timeDurationUnit.MSECS) {
+ return length;
+ } else if (unit === _timeDurationUnit.SECS) {
+ return length * _timeDurationUnitValue.SECS;
+ } else if (unit === _timeDurationUnit.MINS) {
+ return length * _timeDurationUnitValue.MINS;
+ } else if (unit === _timeDurationUnit.HOURS) {
+ return length * _timeDurationUnitValue.HOURS;
+ } else if (unit === _timeDurationUnit.DAYS) {
+ return length * _timeDurationUnitValue.DAYS;
+ } else {
+ native_.throwTypeMismatch();
+ }
}
function _convertMsecsToBiggestPossibleUnit(len) {
- var length;
- var unit;
- if (len % _timeDurationUnitValue.DAYS === 0) {
- length = len / _timeDurationUnitValue.DAYS;
- unit = _timeDurationUnit.DAYS;
- } else if (len % _timeDurationUnitValue.HOURS === 0) {
- length = len / _timeDurationUnitValue.HOURS;
- unit = _timeDurationUnit.HOURS;
- } else if (len % _timeDurationUnitValue.MINS === 0) {
- length = len / _timeDurationUnitValue.MINS;
- unit = _timeDurationUnit.MINS;
- } else if (len % _timeDurationUnitValue.SECS === 0) {
- length = len / _timeDurationUnitValue.SECS;
- unit = _timeDurationUnit.SECS;
- } else {
- length = len;
- unit = _timeDurationUnit.MSECS;
- }
- return new tizen.TimeDuration(length, unit);
+ var length;
+ var unit;
+ if (len % _timeDurationUnitValue.DAYS === 0) {
+ length = len / _timeDurationUnitValue.DAYS;
+ unit = _timeDurationUnit.DAYS;
+ } else if (len % _timeDurationUnitValue.HOURS === 0) {
+ length = len / _timeDurationUnitValue.HOURS;
+ unit = _timeDurationUnit.HOURS;
+ } else if (len % _timeDurationUnitValue.MINS === 0) {
+ length = len / _timeDurationUnitValue.MINS;
+ unit = _timeDurationUnit.MINS;
+ } else if (len % _timeDurationUnitValue.SECS === 0) {
+ length = len / _timeDurationUnitValue.SECS;
+ unit = _timeDurationUnit.SECS;
+ } else {
+ length = len;
+ unit = _timeDurationUnit.MSECS;
+ }
+ return new tizen.TimeDuration(length, unit);
}
//class tizen.TimeDuration ////////////////////////////////////////////////////
tizen.TimeDuration = function(length, unit) {
- utils_.log('Entered TimeDuration constructor');
- validator_.validateConstructorCall(this, tizen.TimeDuration);
- var l, u;
- if (arguments.length >= 2) {
- l = converter_.toLongLong(length);
- unit = converter_.toString(unit);
- if (T.hasProperty(_timeDurationUnit, unit)) {
- u = unit;
+ utils_.log('Entered TimeDuration constructor');
+ validator_.validateConstructorCall(this, tizen.TimeDuration);
+ var l, u;
+ if (arguments.length >= 2) {
+ l = converter_.toLongLong(length);
+ unit = converter_.toString(unit);
+ if (T.hasProperty(_timeDurationUnit, unit)) {
+ u = unit;
+ } else {
+ u = _timeDurationUnit.MSECS;
+ }
+ } else if (arguments.length === 1) {
+ l = converter_.toLongLong(length);
+ u = _timeDurationUnit.MSECS;
} else {
- u = _timeDurationUnit.MSECS;
- }
- } else if (arguments.length === 1) {
- l = converter_.toLongLong(length);
- u = _timeDurationUnit.MSECS;
- } else {
- l = undefined;
- u = undefined;
- }
- function lengthSetter(val) {
- if (!T.isNullOrUndefined(val)) {
- l = val;
- }
- }
- function unitSetter(val) {
- if (!T.isNullOrUndefined(val)) {
- u = val;
- }
- }
- Object.defineProperties(this, {
- length : {
- enumerable : true,
- set : lengthSetter,
- get : function() {
- return l;
- }
- },
- unit : {
- enumerable : true,
- set : unitSetter,
- get : function() {
- return u;
- }
- }
- });
-}
+ l = undefined;
+ u = undefined;
+ }
+ function lengthSetter(val) {
+ if (!T.isNullOrUndefined(val)) {
+ l = val;
+ }
+ }
+ function unitSetter(val) {
+ if (!T.isNullOrUndefined(val)) {
+ u = val;
+ }
+ }
+ Object.defineProperties(this, {
+ length: {
+ enumerable: true,
+ set: lengthSetter,
+ get: function() {
+ return l;
+ }
+ },
+ unit: {
+ enumerable: true,
+ set: unitSetter,
+ get: function() {
+ return u;
+ }
+ }
+ });
+};
tizen.TimeDuration.prototype.difference = function() {
- utils_.log('Entered TimeDuration.difference');
+ utils_.log('Entered TimeDuration.difference');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TimeDuration
- }
- ]);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TimeDuration
+ }
+ ]);
- if (this.unit === args.other.unit) {
- return new tizen.TimeDuration(this.length - args.other.length, this.unit);
- } else {
- var l1 = _getLengthInMsecsUnit(this.length, this.unit);
- var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
- return _convertMsecsToBiggestPossibleUnit(l1 - l2);
- }
+ if (this.unit === args.other.unit) {
+ return new tizen.TimeDuration(this.length - args.other.length, this.unit);
+ } else {
+ var l1 = _getLengthInMsecsUnit(this.length, this.unit);
+ var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
+ return _convertMsecsToBiggestPossibleUnit(l1 - l2);
+ }
};
tizen.TimeDuration.prototype.equalsTo = function() {
- utils_.log('Entered TimeDuration.equalsTo');
+ utils_.log('Entered TimeDuration.equalsTo');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TimeDuration
- }
- ]);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TimeDuration
+ }
+ ]);
- if (this.unit === args.other.unit) {
- return (this.length === args.other.length) ? true : false;
- } else {
- var l1 = _getLengthInMsecsUnit(this.length, this.unit);
- var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
- return (l1 === l2) ? true : false;
- }
+ if (this.unit === args.other.unit) {
+ return this.length === args.other.length ? true : false;
+ } else {
+ var l1 = _getLengthInMsecsUnit(this.length, this.unit);
+ var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
+ return l1 === l2 ? true : false;
+ }
};
tizen.TimeDuration.prototype.lessThan = function() {
- utils_.log('Entered TimeDuration.lessThan');
+ utils_.log('Entered TimeDuration.lessThan');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TimeDuration
- }
- ]);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TimeDuration
+ }
+ ]);
- if (this.unit === args.other.unit) {
- return (this.length < args.other.length) ? true : false;
- } else {
- var l1 = _getLengthInMsecsUnit(this.length, this.unit);
- var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
- return (l1 < l2) ? true : false;
- }
+ if (this.unit === args.other.unit) {
+ return this.length < args.other.length ? true : false;
+ } else {
+ var l1 = _getLengthInMsecsUnit(this.length, this.unit);
+ var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
+ return l1 < l2 ? true : false;
+ }
};
tizen.TimeDuration.prototype.greaterThan = function() {
- utils_.log('Entered TimeDuration.greaterThan');
+ utils_.log('Entered TimeDuration.greaterThan');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'other',
- type : validator_.Types.PLATFORM_OBJECT,
- values : tizen.TimeDuration
- }
- ]);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'other',
+ type: validator_.Types.PLATFORM_OBJECT,
+ values: tizen.TimeDuration
+ }
+ ]);
- if (this.unit === args.other.unit) {
- return (this.length > args.other.length) ? true : false;
- } else {
- var l1 = _getLengthInMsecsUnit(this.length, this.unit);
- var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
- return (l1 > l2) ? true : false;
- }
+ if (this.unit === args.other.unit) {
+ return this.length > args.other.length ? true : false;
+ } else {
+ var l1 = _getLengthInMsecsUnit(this.length, this.unit);
+ var l2 = _getLengthInMsecsUnit(args.other.length, args.other.unit);
+ return l1 > l2 ? true : false;
+ }
};
-
//class TimeUtil ////////////////////////////////////////////////////
exports.getCurrentDateTime = function() {
- utils_.log('Entered TimeUtil.getCurrentDateTime');
- return new tizen.TZDate();
+ utils_.log('Entered TimeUtil.getCurrentDateTime');
+ return new tizen.TZDate();
};
exports.getLocalTimezone = function() {
- utils_.log('Entered TimeUtil.getLocalTimezone');
- var result = native_.callSync('TZDate_getLocalTimezone', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).timezoneId;
+ utils_.log('Entered TimeUtil.getLocalTimezone');
+ var result = native_.callSync('TZDate_getLocalTimezone', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).timezoneId;
};
-var _availableTimezones = []; //an array for holding available timezones
+var _availableTimezones = []; //an array for holding available timezones
exports.getAvailableTimezones = function() {
- utils_.log('Entered TimeUtil.getAvailableTimezones');
- if (_availableTimezones.length === 0) {
- var result = native_.callSync('TimeUtil_getAvailableTimezones', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
+ utils_.log('Entered TimeUtil.getAvailableTimezones');
+ if (_availableTimezones.length === 0) {
+ var result = native_.callSync('TimeUtil_getAvailableTimezones', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ _availableTimezones = native_.getResultObject(result).availableTimezones;
}
- _availableTimezones = native_.getResultObject(result).availableTimezones;
- }
- return _availableTimezones.slice(0);
+ return _availableTimezones.slice(0);
};
exports.getDateFormat = function() {
- utils_.log('Entered TimeUtil.getDateFormat');
-
- var args = validator_.validateMethod(arguments, [
- {
- name : 'shortformat',
- type : validator_.Types.BOOLEAN,
- optional : true,
- nullable : true
- }
- ]);
+ utils_.log('Entered TimeUtil.getDateFormat');
+
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'shortformat',
+ type: validator_.Types.BOOLEAN,
+ optional: true,
+ nullable: true
+ }
+ ]);
- if (!args.has.shortformat || T.isNull(args.shortformat)) {
- args.shortformat = false;
- }
+ if (!args.has.shortformat || T.isNull(args.shortformat)) {
+ args.shortformat = false;
+ }
- var result = native_.callSync('TimeUtil_getDateFormat', {shortformat: args.shortformat});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).format;
+ var result = native_.callSync('TimeUtil_getDateFormat', {
+ shortformat: args.shortformat
+ });
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).format;
};
exports.getTimeFormat = function() {
- utils_.log('Entered TimeUtil.getTimeFormat');
- var result = native_.callSync('TimeUtil_getTimeFormat', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result).format;
+ utils_.log('Entered TimeUtil.getTimeFormat');
+ var result = native_.callSync('TimeUtil_getTimeFormat', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result).format;
};
exports.isLeapYear = function() {
- utils_.log('Entered TimeUtil.isLeapYear');
+ utils_.log('Entered TimeUtil.isLeapYear');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'year',
- type : validator_.Types.LONG
- }
- ]);
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'year',
+ type: validator_.Types.LONG
+ }
+ ]);
- // new Date(year, 1, 29).getMonth() === 1 <-- does not work for years 0-99
- return ((args.year % 4 === 0) && (args.year % 100 !== 0)) || (args.year % 400 === 0);
+ // new Date(year, 1, 29).getMonth() === 1 <-- does not work for years 0-99
+ return (args.year % 4 === 0 && args.year % 100 !== 0) || args.year % 400 === 0;
};
-
var _timeUtilDateTimeChangeListener;
function _timeChangedListenerCallback(eventObj) {
- utils_.log("_timeChangedListenerCallback");
- native_.callIfPossible(_timeUtilDateTimeChangeListener);
+ utils_.log('_timeChangedListenerCallback');
+ native_.callIfPossible(_timeUtilDateTimeChangeListener);
}
exports.setDateTimeChangeListener = function() {
- utils_.log('Entered TimeUtil.setDateTimeChangeListener');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'changeCallback',
- type : validator_.Types.FUNCTION
- }
- ]);
- var result = native_.callSync('TimeUtil_setDateTimeChangeListener', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- _timeUtilDateTimeChangeListener = args.changeCallback;
- native_.addListener("DateTimeChangeListener", _timeChangedListenerCallback);
+ utils_.log('Entered TimeUtil.setDateTimeChangeListener');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'changeCallback',
+ type: validator_.Types.FUNCTION
+ }
+ ]);
+ var result = native_.callSync('TimeUtil_setDateTimeChangeListener', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ _timeUtilDateTimeChangeListener = args.changeCallback;
+ native_.addListener('DateTimeChangeListener', _timeChangedListenerCallback);
};
exports.unsetDateTimeChangeListener = function() {
- utils_.log('Entered TimeUtil.unsetDateTimeChangeListener');
- var result = native_.callSync('TimeUtil_unsetDateTimeChangeListener', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- native_.removeListener('DateTimeChangeListener');
- _timeUtilDateTimeChangeListener = undefined;
+ utils_.log('Entered TimeUtil.unsetDateTimeChangeListener');
+ var result = native_.callSync('TimeUtil_unsetDateTimeChangeListener', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ native_.removeListener('DateTimeChangeListener');
+ _timeUtilDateTimeChangeListener = undefined;
};
var _timeUtilTimezoneChangeListener;
function _timezoneListenerCallback(eventObj) {
- utils_.log("_timezoneListenerCallback");
- native_.callIfPossible(_timeUtilTimezoneChangeListener);
+ utils_.log('_timezoneListenerCallback');
+ native_.callIfPossible(_timeUtilTimezoneChangeListener);
}
exports.setTimezoneChangeListener = function() {
- utils_.log('Entered TimeUtil.setTimezoneChangeListener');
- var args = validator_.validateMethod(arguments, [
- {
- name : 'changeCallback',
- type : validator_.Types.FUNCTION
- }
- ]);
- var result = native_.callSync('TimeUtil_setTimezoneChangeListener', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- _timeUtilTimezoneChangeListener = args.changeCallback;
- native_.addListener('TimezoneChangeListener',
- _timezoneListenerCallback);
-
+ utils_.log('Entered TimeUtil.setTimezoneChangeListener');
+ var args = validator_.validateMethod(arguments, [
+ {
+ name: 'changeCallback',
+ type: validator_.Types.FUNCTION
+ }
+ ]);
+ var result = native_.callSync('TimeUtil_setTimezoneChangeListener', {});
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ _timeUtilTimezoneChangeListener = args.changeCallback;
+ native_.addListener('TimezoneChangeListener', _timezoneListenerCallback);
};
exports.unsetTimezoneChangeListener = function() {
- utils_.log('Entered TimeUtil.unsetTimezoneChangeListener');
- native_.removeListener('TimezoneChangeListener');
- var result = native_.callSync('TimeUtil_unsetTimezoneChangeListener', {});
- _timeUtilTimezoneChangeListener = undefined;
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-}; \ No newline at end of file
+ utils_.log('Entered TimeUtil.unsetTimezoneChangeListener');
+ native_.removeListener('TimezoneChangeListener');
+ var result = native_.callSync('TimeUtil_unsetTimezoneChangeListener', {});
+ _timeUtilTimezoneChangeListener = undefined;
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+};
diff --git a/src/tizen/tizen_api.js b/src/tizen/tizen_api.js
index eaa502b3..5232c130 100644
--- a/src/tizen/tizen_api.js
+++ b/src/tizen/tizen_api.js
@@ -3,473 +3,469 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
+/*eslint-disable */
// Tizen API Specification:
-// https://developer.tizen.org/dev-guide/2.3.0/org.tizen.mobile.web.device.apireference/tizen/tizen.html
-
+//https://developer.tizen.org/dev-guide/2.3.0/org.tizen.mobile.web.device.apireference/tizen/tizen.html
+/*eslint-enable */
// WebAPIException and WebAPIError definition moved to src/utils/utils_api.js
// for compliance reasons. You can find more info there.
-
/**
* Filter match flags.
* @enum {string}
*/
var FilterMatchFlag = {
- EXACTLY: 'EXACTLY',
- FULLSTRING: 'FULLSTRING',
- CONTAINS: 'CONTAINS',
- STARTSWITH: 'STARTSWITH',
- ENDSWITH: 'ENDSWITH',
- EXISTS: 'EXISTS'
+ EXACTLY: 'EXACTLY',
+ FULLSTRING: 'FULLSTRING',
+ CONTAINS: 'CONTAINS',
+ STARTSWITH: 'STARTSWITH',
+ ENDSWITH: 'ENDSWITH',
+ EXISTS: 'EXISTS'
};
-
/**
* An enumerator that indicates the sorting order.
* @enum {string}
*/
var SortModeOrder = {
- ASC: 'ASC',
- DESC: 'DESC'
+ ASC: 'ASC',
+ DESC: 'DESC'
};
-
/**
* An enumerator that indicates the type of composite filter.
* @enum {string}
*/
var CompositeFilterType = {
- UNION: 'UNION',
- INTERSECTION: 'INTERSECTION'
+ UNION: 'UNION',
+ INTERSECTION: 'INTERSECTION'
};
// Tizen Filters
// either AttributeFilter, AttributeRangeFilter, or CompositeFilter
function is_tizen_filter(f) {
- return (f instanceof tizen.AttributeFilter) ||
- (f instanceof tizen.AttributeRangeFilter) ||
- (f instanceof tizen.CompositeFilter);
+ return (
+ f instanceof tizen.AttributeFilter ||
+ f instanceof tizen.AttributeRangeFilter ||
+ f instanceof tizen.CompositeFilter
+ );
}
//Extract property by string
function _extractProperty(obj, attributeName) {
- var props = attributeName.split('.');
- for (var i = 0; i < props.length; ++i) {
- if (obj instanceof Array) {
- var ret = [];
- for (var j = 0; j < obj.length; ++j)
- {
- ret.push(_extractProperty(obj[j], props.slice(i).join('.')));
- }
- return ret;
- }
- if (!obj.hasOwnProperty(props[i])) {
- if (i === props.length - 1) {
- throw new WebAPIException('InvalidValuesError', 'Property "' + attributeName +
- '" is not valid');
- }
- return null;
+ var props = attributeName.split('.');
+ for (var i = 0; i < props.length; ++i) {
+ if (obj instanceof Array) {
+ var ret = [];
+ for (var j = 0; j < obj.length; ++j) {
+ ret.push(_extractProperty(obj[j], props.slice(i).join('.')));
+ }
+ return ret;
+ }
+ if (!obj.hasOwnProperty(props[i])) {
+ if (i === props.length - 1) {
+ throw new WebAPIException(
+ 'InvalidValuesError',
+ 'Property "' + attributeName + '" is not valid'
+ );
+ }
+ return null;
+ }
+ obj = obj[props[i]];
}
- obj = obj[props[i]];
- }
- return obj;
+ return obj;
}
-
/**
* This is a common interface used by different types of object filters.
*/
var AbstractFilter = function() {};
-
/**
* Represents a set of filters.
*/
exports.AttributeFilter = function(attrName, matchFlag, matchValue) {
+ xwalk.utils.validator.isConstructorCall(this, exports.AttributeFilter);
+
+ var name_ = '';
+ var flag_ = 'EXACTLY';
+ var value_ = null;
+
+ function attributeNameSetter(name) {
+ name_ = String(name);
+ }
+
+ if (arguments.length > 0) attributeNameSetter(attrName);
+
+ function matchFlagSetter(flag) {
+ if (Object.keys(FilterMatchFlag).indexOf(flag) >= 0) flag_ = flag;
+ }
+
+ function matchValueSetter(value) {
+ value_ = value;
+ }
- xwalk.utils.validator.isConstructorCall(this, exports.AttributeFilter);
-
- var name_ = '';
- var flag_ = 'EXACTLY';
- var value_ = null;
-
- function attributeNameSetter(name) {
- name_ = String(name);
- }
-
- if (arguments.length > 0)
- attributeNameSetter(attrName);
-
- function matchFlagSetter(flag) {
- if (Object.keys(FilterMatchFlag).indexOf(flag) >= 0)
- flag_ = flag;
- }
-
- function matchValueSetter(value) {
- value_ = value;
- }
-
- if (arguments.length > 2) {
- matchFlagSetter(matchFlag);
- matchValueSetter(matchValue);
- } else if (arguments.length > 1) {
- // if matchValue is not used then matchFlag is set to 'EXISTS'.
- matchFlagSetter('EXISTS');
- }
-
- Object.defineProperties(this, {
- attributeName: {
- enumerable: true,
- set: attributeNameSetter,
- get: function() {
- return name_;
- }
- },
- matchFlag: {
- enumerable: true,
- set: matchFlagSetter,
- get: function() {
- return flag_;
- }
- },
- matchValue: {
- enumerable: true,
- set: matchValueSetter,
- get: function() {
- return value_;
- }
+ if (arguments.length > 2) {
+ matchFlagSetter(matchFlag);
+ matchValueSetter(matchValue);
+ } else if (arguments.length > 1) {
+ // if matchValue is not used then matchFlag is set to 'EXISTS'.
+ matchFlagSetter('EXISTS');
}
- });
+
+ Object.defineProperties(this, {
+ attributeName: {
+ enumerable: true,
+ set: attributeNameSetter,
+ get: function() {
+ return name_;
+ }
+ },
+ matchFlag: {
+ enumerable: true,
+ set: matchFlagSetter,
+ get: function() {
+ return flag_;
+ }
+ },
+ matchValue: {
+ enumerable: true,
+ set: matchValueSetter,
+ get: function() {
+ return value_;
+ }
+ }
+ });
};
exports.AttributeFilter.prototype = new AbstractFilter();
//TODO: Move filtering to native code
exports.AttributeFilter.prototype._filter = function(element) {
- var elemValue = _extractProperty(element, this.attributeName);
-
- if (!(elemValue instanceof Array)) {
- elemValue = [elemValue];
- }
-
- var ret = false;
- for (var i = 0; i < elemValue.length; ++i) {
- var elemValueStr = String(elemValue[i]);
- var elemValueStrU = elemValueStr.toUpperCase();
- var matchValueStr = String(this.matchValue);
- var matchValueStrU = matchValueStr.toUpperCase();
-
- switch (this.matchFlag) {
- case 'EXACTLY':
- ret = elemValue[i] === this.matchValue;
- break;
- case 'FULLSTRING':
- ret = elemValueStrU === matchValueStrU;
- break;
- case 'CONTAINS':
- ret = elemValueStrU.indexOf(matchValueStrU) > -1;
- break;
- case 'STARTSWITH':
- ret = elemValueStrU.indexOf(matchValueStrU) === 0;
- break;
- case 'ENDSWITH':
- ret = elemValueStrU.lastIndexOf(matchValueStrU) +
- matchValueStrU.length === elemValueStrU.length;
- break;
- case 'EXISTS':
- ret = elemValue[i] !== undefined;
- break;
+ var elemValue = _extractProperty(element, this.attributeName);
+
+ if (!(elemValue instanceof Array)) {
+ elemValue = [elemValue];
}
- if (ret) {
- return ret;
+
+ var ret = false;
+ for (var i = 0; i < elemValue.length; ++i) {
+ var elemValueStr = String(elemValue[i]);
+ var elemValueStrU = elemValueStr.toUpperCase();
+ var matchValueStr = String(this.matchValue);
+ var matchValueStrU = matchValueStr.toUpperCase();
+
+ switch (this.matchFlag) {
+ case 'EXACTLY':
+ ret = elemValue[i] === this.matchValue;
+ break;
+ case 'FULLSTRING':
+ ret = elemValueStrU === matchValueStrU;
+ break;
+ case 'CONTAINS':
+ ret = elemValueStrU.indexOf(matchValueStrU) > -1;
+ break;
+ case 'STARTSWITH':
+ ret = elemValueStrU.indexOf(matchValueStrU) === 0;
+ break;
+ case 'ENDSWITH':
+ ret =
+ elemValueStrU.lastIndexOf(matchValueStrU) + matchValueStrU.length ===
+ elemValueStrU.length;
+ break;
+ case 'EXISTS':
+ ret = elemValue[i] !== undefined;
+ break;
+ }
+ if (ret) {
+ return ret;
+ }
}
- }
- return ret;
+ return ret;
};
exports.AttributeFilter.prototype.constructor = exports.AttributeFilter;
-
/**
* Represents a filter based on an object attribute which has values that are
* within a particular range.
*/
exports.AttributeRangeFilter = function(attrName, start, end) {
+ xwalk.utils.validator.isConstructorCall(this, exports.AttributeRangeFilter);
+
+ var name_ = '';
+ var start_ = null;
+ var end_ = null;
- xwalk.utils.validator.isConstructorCall(this, exports.AttributeRangeFilter);
-
- var name_ = '';
- var start_ = null;
- var end_ = null;
-
- function attributeNameSetter(name) {
- name_ = String(name);
- }
-
- if (arguments.length > 0)
- attributeNameSetter(attrName);
-
- function initSetter(init) {
- start_ = init;
- }
-
- if (arguments.length > 1)
- initSetter(start);
-
- function endSetter(end) {
- end_ = end;
- }
-
- if (arguments.length > 2)
- endSetter(end);
-
- Object.defineProperties(this, {
- attributeName: {
- enumerable: true,
- set: attributeNameSetter,
- get: function() {
- return name_;
- }
- },
- initialValue: {
- enumerable: true,
- set: initSetter,
- get: function() {
- return start_;
- }
- },
- endValue: {
- enumerable: true,
- set: endSetter,
- get: function() {
- return end_;
- }
+ function attributeNameSetter(name) {
+ name_ = String(name);
}
- });
+
+ if (arguments.length > 0) attributeNameSetter(attrName);
+
+ function initSetter(init) {
+ start_ = init;
+ }
+
+ if (arguments.length > 1) initSetter(start);
+
+ function endSetter(end) {
+ end_ = end;
+ }
+
+ if (arguments.length > 2) endSetter(end);
+
+ Object.defineProperties(this, {
+ attributeName: {
+ enumerable: true,
+ set: attributeNameSetter,
+ get: function() {
+ return name_;
+ }
+ },
+ initialValue: {
+ enumerable: true,
+ set: initSetter,
+ get: function() {
+ return start_;
+ }
+ },
+ endValue: {
+ enumerable: true,
+ set: endSetter,
+ get: function() {
+ return end_;
+ }
+ }
+ });
};
exports.AttributeRangeFilter.prototype = new AbstractFilter();
//TODO: Move filtering to native code
exports.AttributeRangeFilter.prototype._filter = function(element) {
- var elemValue = _extractProperty(element, this.attributeName);
+ var elemValue = _extractProperty(element, this.attributeName);
- if (!(elemValue instanceof Array)) {
- elemValue = [elemValue];
- }
-
- for (var i = 0; i < elemValue.length; ++i) {
- var value = elemValue[i];
+ if (!(elemValue instanceof Array)) {
+ elemValue = [elemValue];
+ }
- if ((this.initialValue !== undefined && this.initialValue !== null) &&
- (this.endValue !== undefined && this.endValue !== null)) {
- if (value instanceof tizen.TZDate) {
- if (this.initialValue.earlierThan(value) && this.endValue.laterThan(value)) {
- return true;
- }
- } else {
- if (this.initialValue <= value && this.endValue > value) {
- return true;
- }
- }
- } else if ((this.initialValue !== undefined && this.initialValue !== null) &&
- (this.endValue === undefined || this.endValue === null)) {
- if (value instanceof tizen.TZDate) {
- if (this.initialValue.earlierThan(value)) {
- return true;
- }
- } else {
- if (this.initialValue <= value) {
- return true;
+ for (var i = 0; i < elemValue.length; ++i) {
+ var value = elemValue[i];
+
+ if (
+ this.initialValue !== undefined &&
+ this.initialValue !== null &&
+ (this.endValue !== undefined && this.endValue !== null)
+ ) {
+ if (value instanceof tizen.TZDate) {
+ if (
+ this.initialValue.earlierThan(value) &&
+ this.endValue.laterThan(value)
+ ) {
+ return true;
+ }
+ } else {
+ if (this.initialValue <= value && this.endValue > value) {
+ return true;
+ }
+ }
+ } else if (
+ this.initialValue !== undefined &&
+ this.initialValue !== null &&
+ (this.endValue === undefined || this.endValue === null)
+ ) {
+ if (value instanceof tizen.TZDate) {
+ if (this.initialValue.earlierThan(value)) {
+ return true;
+ }
+ } else {
+ if (this.initialValue <= value) {
+ return true;
+ }
+ }
+ } else if (
+ (this.initialValue === undefined || this.initialValue === null) &&
+ (this.endValue !== undefined && this.endValue !== null)
+ ) {
+ if (value instanceof tizen.TZDate) {
+ if (this.endValue.laterThan(value)) {
+ return true;
+ }
+ } else {
+ if (this.endValue > value) {
+ return true;
+ }
+ }
}
- }
- } else if ((this.initialValue === undefined || this.initialValue === null) &&
- (this.endValue !== undefined && this.endValue !== null)) {
- if (value instanceof tizen.TZDate) {
- if (this.endValue.laterThan(value)) {
- return true;
- }
- } else {
- if (this.endValue > value) {
- return true;
- }
- }
}
- }
- return false;
+ return false;
};
exports.AttributeRangeFilter.prototype.constructor = exports.AttributeRangeFilter;
-
/**
* Represents a set of filters.
*/
exports.CompositeFilter = function(type, filters) {
+ xwalk.utils.validator.isConstructorCall(this, exports.CompositeFilter);
- xwalk.utils.validator.isConstructorCall(this, exports.CompositeFilter);
+ var filterTypes = Object.keys(CompositeFilterType);
- var filterTypes = Object.keys(CompositeFilterType);
+ var type_ = filterTypes[0];
+ var filters_ = [];
- var type_ = filterTypes[0];
- var filters_ = [];
+ function typeSetter(filterType) {
+ if (filterTypes.indexOf(filterType) >= 0) type_ = filterType;
+ }
- function typeSetter(filterType) {
- if (filterTypes.indexOf(filterType) >= 0)
- type_ = filterType;
- }
+ if (arguments.length > 0) typeSetter(type);
- if (arguments.length > 0)
- typeSetter(type);
+ function filtersSetter(filterList) {
+ if (!(filterList instanceof Array)) return;
- function filtersSetter(filterList) {
- if (!(filterList instanceof Array))
- return;
+ for (var i in filterList) {
+ var valid = filterList[i] instanceof AbstractFilter;
+ if (!valid) return;
+ }
- for (var i in filterList) {
- var valid = (filterList[i] instanceof AbstractFilter);
- if (!valid)
- return;
+ filters_ = filterList.slice(0);
}
- filters_ = filterList.slice(0);
- }
-
- if (arguments.length > 1)
- filtersSetter(filters);
-
- Object.defineProperties(this, {
- type: {
- enumerable: true,
- set: typeSetter,
- get: function() {
- return type_;
- }
- },
- filters: {
- enumerable: true,
- set: filtersSetter,
- get: function() {
- return filters_;
- }
- }
- });
+ if (arguments.length > 1) filtersSetter(filters);
+
+ Object.defineProperties(this, {
+ type: {
+ enumerable: true,
+ set: typeSetter,
+ get: function() {
+ return type_;
+ }
+ },
+ filters: {
+ enumerable: true,
+ set: filtersSetter,
+ get: function() {
+ return filters_;
+ }
+ }
+ });
};
exports.CompositeFilter.prototype = new AbstractFilter();
//TODO: Move filtering to native code
exports.CompositeFilter.prototype._filter = function(element) {
- var filters = this.filters;
- if (this.type === 'UNION') {
- for (var i = 0; i < filters.length; ++i) {
- if (filters[i]._filter(element)) {
- return true;
- }
- }
- return false;
- } else if (this.type === 'INTERSECTION') {
- if (filters.length === 0)
- return false;
- for (var i = 0; i < filters.length; ++i) {
- if (!filters[i]._filter(element)) {
+ var filters = this.filters;
+ if (this.type === 'UNION') {
+ for (var i = 0; i < filters.length; ++i) {
+ if (filters[i]._filter(element)) {
+ return true;
+ }
+ }
return false;
- }
+ } else if (this.type === 'INTERSECTION') {
+ if (filters.length === 0) return false;
+ for (var i = 0; i < filters.length; ++i) {
+ if (!filters[i]._filter(element)) {
+ return false;
+ }
+ }
+ return true;
}
- return true;
- }
};
exports.CompositeFilter.prototype.constructor = exports.CompositeFilter;
-
/**
* SortMode is a common interface used for sorting of queried data.
*/
exports.SortMode = function(attrName, order) {
+ xwalk.utils.validator.isConstructorCall(this, exports.SortMode);
- xwalk.utils.validator.isConstructorCall(this, exports.SortMode);
-
- var sortModeOrder = Object.keys(SortModeOrder);
+ var sortModeOrder = Object.keys(SortModeOrder);
- var attributeName_ = '';
- var order_ = 'ASC';
+ var attributeName_ = '';
+ var order_ = 'ASC';
- function nameSetter(name) {
- attributeName_ = String(name);
- }
-
- if (arguments.length > 0)
- nameSetter(attrName);
-
- function orderSetter(sortOrder) {
- if (sortModeOrder.indexOf(sortOrder) >= 0)
- order_ = sortOrder;
- }
+ function nameSetter(name) {
+ attributeName_ = String(name);
+ }
- if (arguments.length > 1)
- orderSetter(order);
+ if (arguments.length > 0) nameSetter(attrName);
- Object.defineProperties(this, {
- attributeName: {
- enumerable: true, set: nameSetter, get: function() {
- return attributeName_;
- }
- },
- order: {
- enumerable: true, set: orderSetter, get: function() {
- return order_;
- }
+ function orderSetter(sortOrder) {
+ if (sortModeOrder.indexOf(sortOrder) >= 0) order_ = sortOrder;
}
- });
+
+ if (arguments.length > 1) orderSetter(order);
+
+ Object.defineProperties(this, {
+ attributeName: {
+ enumerable: true,
+ set: nameSetter,
+ get: function() {
+ return attributeName_;
+ }
+ },
+ order: {
+ enumerable: true,
+ set: orderSetter,
+ get: function() {
+ return order_;
+ }
+ }
+ });
};
exports.SortMode.prototype.constructor = exports.SortMode;
-
/**
* Represents a point (latitude and longitude) in the map coordinate system.
*/
exports.SimpleCoordinates = function(lat, lng) {
+ xwalk.utils.validator.isConstructorCall(this, exports.SimpleCoordinates);
- xwalk.utils.validator.isConstructorCall(this, exports.SimpleCoordinates);
+ var latitude = 0;
+ var longitude = 0;
- var latitude = 0;
- var longitude = 0;
+ function latSetter(lat) {
+ var tmp = Number(lat);
+ if (!isNaN(tmp)) {
+ if (tmp > 90) tmp = 90;
+ else if (tmp < -90) tmp = -90;
- function latSetter(lat) {
- var tmp = Number(lat);
- if (!isNaN(tmp)) {
- if (tmp > 90) tmp = 90;
- else if (tmp < -90) tmp = -90;
-
- latitude = tmp;
+ latitude = tmp;
+ }
}
- }
- latSetter(lat);
+ latSetter(lat);
- function lonSetter(lon) {
- var tmp = Number(lon);
- if (!isNaN(tmp)) {
- if (tmp > 180) tmp = 180;
- else if (tmp < -180) tmp = -180;
+ function lonSetter(lon) {
+ var tmp = Number(lon);
+ if (!isNaN(tmp)) {
+ if (tmp > 180) tmp = 180;
+ else if (tmp < -180) tmp = -180;
- longitude = tmp;
- }
- }
-
- lonSetter(lng);
-
- Object.defineProperties(this, {
- latitude: {
- enumerable: true, set: latSetter, get: function() {
- return latitude;
- }
- },
- longitude: {
- enumerable: true, set: lonSetter, get: function() {
- return longitude;
- }
+ longitude = tmp;
+ }
}
- });
+
+ lonSetter(lng);
+
+ Object.defineProperties(this, {
+ latitude: {
+ enumerable: true,
+ set: latSetter,
+ get: function() {
+ return latitude;
+ }
+ },
+ longitude: {
+ enumerable: true,
+ set: lonSetter,
+ get: function() {
+ return longitude;
+ }
+ }
+ });
};
exports.SimpleCoordinates.prototype.constructor = exports.SimpleCoordinates;
diff --git a/src/tvinputdevice/tvinputdevice_api.js b/src/tvinputdevice/tvinputdevice_api.js
index b2f34f1b..3c5580f2 100755
--- a/src/tvinputdevice/tvinputdevice_api.js
+++ b/src/tvinputdevice/tvinputdevice_api.js
@@ -18,240 +18,239 @@ var native = new xwalk.utils.NativeManager(extension);
var validator = xwalk.utils.validator;
var types = validator.Types;
var mandatoryMap = {
- "ArrowLeft" : {
- keyName : "Left",
- keyCode : 37
- },
- "ArrowUp" : {
- keyName : "Up",
- keyCode : 38
- },
- "ArrowRight" : {
- keyName : "Right",
- keyCode : 39
- },
- "ArrowDown" : {
- keyName : "Down",
- keyCode : 40
- },
- "Enter" : {
- keyName : "Return",
- keyCode : 13
- },
- "Back" : {
- keyName : "XF86Back",
- keyCode : 10009
- },
+ ArrowLeft: {
+ keyName: 'Left',
+ keyCode: 37
+ },
+ ArrowUp: {
+ keyName: 'Up',
+ keyCode: 38
+ },
+ ArrowRight: {
+ keyName: 'Right',
+ keyCode: 39
+ },
+ ArrowDown: {
+ keyName: 'Down',
+ keyCode: 40
+ },
+ Enter: {
+ keyName: 'Return',
+ keyCode: 13
+ },
+ Back: {
+ keyName: 'XF86Back',
+ keyCode: 10009
+ }
};
var map = {
- "VolumeUp": {
- keyName: "XF86AudioRaiseVolume",
- keyCode: 447
- },
- "VolumeDown": {
- keyName: "XF86AudioLowerVolume",
- keyCode: 448
- },
- "VolumeMute": {
- keyName: "XF86AudioMute",
- keyCode: 449
- },
- "ChannelUp": {
- keyName: "XF86RaiseChannel",
- keyCode: 427
- },
- "ChannelDown": {
- keyName: "XF86LowerChannel",
- keyCode: 428
- },
- "ColorF0Red": {
- keyName: "XF86Red",
- keyCode: 403
- },
- "ColorF1Green": {
- keyName: "XF86Green",
- keyCode: 404
- },
- "ColorF2Yellow": {
- keyName: "XF86Yellow",
- keyCode: 405
- },
- "ColorF3Blue": {
- keyName: "XF86Blue",
- keyCode: 406
- },
- "Menu": {
- keyName: "XF86SysMenu",
- keyCode: 10133
- },
- "Tools": {
- keyName: "XF86SimpleMenu",
- keyCode: 10135
- },
- "Info": {
- keyName: "XF86Info",
- keyCode: 457
- },
- "Exit": {
- keyName: "XF86Exit",
- keyCode: 10182
- },
- "Search": {
- keyName: "XF86Search",
- keyCode: 10225
- },
- "Guide": {
- keyName: "XF86ChannelGuide",
- keyCode: 458
- },
- "MediaRewind": {
- keyName: "XF86AudioRewind",
- keyCode: 412
- },
- "MediaPause": {
- keyName: "XF86AudioPause",
- keyCode: 19
- },
- "MediaFastForward": {
- keyName: "XF86AudioNext",
- keyCode: 417
- },
- "MediaRecord": {
- keyName: "XF86AudioRecord",
- keyCode: 416
- },
- "MediaPlay": {
- keyName: "XF86AudioPlay",
- keyCode: 415
- },
- "MediaStop": {
- keyName: "XF86AudioStop",
- keyCode: 413
- },
- "MediaPlayPause": {
- keyName: "XF86PlayBack",
- keyCode: 10252
- },
- "MediaTrackPrevious": {
- keyName: "XF86PreviousChapter",
- keyCode: 10232
- },
- "MediaTrackNext": {
- keyName: "XF86NextChapter",
- keyCode: 10233
- },
- "Source": {
- keyName: "XF86Display",
- keyCode: 10072
- },
- "PictureSize": {
- keyName: "XF86PictureSize",
- keyCode: 10140
- },
- "PreviousChannel": {
- keyName: "XF86PreviousChannel",
- keyCode: 10190
- },
- "ChannelList": {
- keyName: "XF86ChannelList",
- keyCode: 10073
- },
- "E-Manual": {
- keyName: "XF86EManual",
- keyCode: 10146
- },
- "MTS": {
- keyName: "XF86MTS",
- keyCode: 10195
- },
- "3D": {
- keyName: "XF863D",
- keyCode: 10199
- },
- "Soccer": {
- keyName: "XF86SoccerMode",
- keyCode: 10228
- },
- "Caption": {
- keyName: "XF86Caption",
- keyCode: 10221
- },
- "Teletext": {
- keyName: "XF86TTXMIX",
- keyCode: 10200
- },
- "Extra": {
- keyName: "XF86ExtraApp",
- keyCode: 10253
- },
- "0": {
- keyName: "0",
- keyCode: 48
- },
- "1": {
- keyName: "1",
- keyCode: 49
- },
- "2": {
- keyName: "2",
- keyCode: 50
- },
- "3": {
- keyName: "3",
- keyCode: 51
- },
- "4": {
- keyName: "4",
- keyCode: 52
- },
- "5": {
- keyName: "5",
- keyCode: 53
- },
- "6": {
- keyName: "6",
- keyCode: 54
- },
- "7": {
- keyName: "7",
- keyCode: 55
- },
- "8": {
- keyName: "8",
- keyCode: 56
- },
- "9": {
- keyName: "9",
- keyCode: 57
- },
- "Minus": {
- keyName: "minus",
- keyCode: 189
- },
+ VolumeUp: {
+ keyName: 'XF86AudioRaiseVolume',
+ keyCode: 447
+ },
+ VolumeDown: {
+ keyName: 'XF86AudioLowerVolume',
+ keyCode: 448
+ },
+ VolumeMute: {
+ keyName: 'XF86AudioMute',
+ keyCode: 449
+ },
+ ChannelUp: {
+ keyName: 'XF86RaiseChannel',
+ keyCode: 427
+ },
+ ChannelDown: {
+ keyName: 'XF86LowerChannel',
+ keyCode: 428
+ },
+ ColorF0Red: {
+ keyName: 'XF86Red',
+ keyCode: 403
+ },
+ ColorF1Green: {
+ keyName: 'XF86Green',
+ keyCode: 404
+ },
+ ColorF2Yellow: {
+ keyName: 'XF86Yellow',
+ keyCode: 405
+ },
+ ColorF3Blue: {
+ keyName: 'XF86Blue',
+ keyCode: 406
+ },
+ Menu: {
+ keyName: 'XF86SysMenu',
+ keyCode: 10133
+ },
+ Tools: {
+ keyName: 'XF86SimpleMenu',
+ keyCode: 10135
+ },
+ Info: {
+ keyName: 'XF86Info',
+ keyCode: 457
+ },
+ Exit: {
+ keyName: 'XF86Exit',
+ keyCode: 10182
+ },
+ Search: {
+ keyName: 'XF86Search',
+ keyCode: 10225
+ },
+ Guide: {
+ keyName: 'XF86ChannelGuide',
+ keyCode: 458
+ },
+ MediaRewind: {
+ keyName: 'XF86AudioRewind',
+ keyCode: 412
+ },
+ MediaPause: {
+ keyName: 'XF86AudioPause',
+ keyCode: 19
+ },
+ MediaFastForward: {
+ keyName: 'XF86AudioNext',
+ keyCode: 417
+ },
+ MediaRecord: {
+ keyName: 'XF86AudioRecord',
+ keyCode: 416
+ },
+ MediaPlay: {
+ keyName: 'XF86AudioPlay',
+ keyCode: 415
+ },
+ MediaStop: {
+ keyName: 'XF86AudioStop',
+ keyCode: 413
+ },
+ MediaPlayPause: {
+ keyName: 'XF86PlayBack',
+ keyCode: 10252
+ },
+ MediaTrackPrevious: {
+ keyName: 'XF86PreviousChapter',
+ keyCode: 10232
+ },
+ MediaTrackNext: {
+ keyName: 'XF86NextChapter',
+ keyCode: 10233
+ },
+ Source: {
+ keyName: 'XF86Display',
+ keyCode: 10072
+ },
+ PictureSize: {
+ keyName: 'XF86PictureSize',
+ keyCode: 10140
+ },
+ PreviousChannel: {
+ keyName: 'XF86PreviousChannel',
+ keyCode: 10190
+ },
+ ChannelList: {
+ keyName: 'XF86ChannelList',
+ keyCode: 10073
+ },
+ 'E-Manual': {
+ keyName: 'XF86EManual',
+ keyCode: 10146
+ },
+ MTS: {
+ keyName: 'XF86MTS',
+ keyCode: 10195
+ },
+ '3D': {
+ keyName: 'XF863D',
+ keyCode: 10199
+ },
+ Soccer: {
+ keyName: 'XF86SoccerMode',
+ keyCode: 10228
+ },
+ Caption: {
+ keyName: 'XF86Caption',
+ keyCode: 10221
+ },
+ Teletext: {
+ keyName: 'XF86TTXMIX',
+ keyCode: 10200
+ },
+ Extra: {
+ keyName: 'XF86ExtraApp',
+ keyCode: 10253
+ },
+ '0': {
+ keyName: '0',
+ keyCode: 48
+ },
+ '1': {
+ keyName: '1',
+ keyCode: 49
+ },
+ '2': {
+ keyName: '2',
+ keyCode: 50
+ },
+ '3': {
+ keyName: '3',
+ keyCode: 51
+ },
+ '4': {
+ keyName: '4',
+ keyCode: 52
+ },
+ '5': {
+ keyName: '5',
+ keyCode: 53
+ },
+ '6': {
+ keyName: '6',
+ keyCode: 54
+ },
+ '7': {
+ keyName: '7',
+ keyCode: 55
+ },
+ '8': {
+ keyName: '8',
+ keyCode: 56
+ },
+ '9': {
+ keyName: '9',
+ keyCode: 57
+ },
+ Minus: {
+ keyName: 'minus',
+ keyCode: 189
+ }
};
-
function TVInputDeviceKey(dict) {
- for (var key in dict) {
- if (dict.hasOwnProperty(key)) {
- Object.defineProperty(this, key, {
- value: dict[key],
- enumerable: true
- });
+ for (var key in dict) {
+ if (dict.hasOwnProperty(key)) {
+ Object.defineProperty(this, key, {
+ value: dict[key],
+ enumerable: true
+ });
+ }
}
- }
- Object.freeze(this);
+ Object.freeze(this);
}
-
/**
- * This class provides access to the API functionalities through the tizen.tvinputdevice interface.
+ * This class provides access to the API functionalities through
+ * the tizen.tvinputdevice interface.
* @constructor
*/
function TVInputDeviceManager() {
- if (!(this instanceof TVInputDeviceManager)) {
- throw new TypeError;
- }
+ if (!(this instanceof TVInputDeviceManager)) {
+ throw new TypeError();
+ }
}
/**
@@ -259,166 +258,209 @@ function TVInputDeviceManager() {
* @return {array} Array of keys
*/
TVInputDeviceManager.prototype.getSupportedKeys = function() {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
- var re = [];
- for (var key in map) {
- if (map.hasOwnProperty(key)) {
- re.push(new TVInputDeviceKey({name: key, code: map[key].keyCode}));
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
+ var re = [];
+ for (var key in map) {
+ if (map.hasOwnProperty(key)) {
+ re.push(new TVInputDeviceKey({ name: key, code: map[key].keyCode }));
+ }
}
- }
- return re;
+ return re;
};
-
/**
* Returns information about the key which has the given name.
* @param {!string} keyName The key name
* @return {object} Key object
*/
TVInputDeviceManager.prototype.getKey = function(keyName) {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
- var args = validator.validateArgs(arguments, [
- {name: 'keyName', type: types.STRING}
- ]);
-
- if (map[args.keyName]) {
- return new TVInputDeviceKey( { name: args.keyName, code: map[args.keyName].keyCode } );
- } else if (mandatoryMap[args.keyName]) {
- return new TVInputDeviceKey( { name: args.keyName, code: mandatoryMap[args.keyName].keyCode } );
- } else {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Parameter "keyName" is invalid.');
- }
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
+ var args = validator.validateArgs(arguments, [
+ { name: 'keyName', type: types.STRING }
+ ]);
+ if (map[args.keyName]) {
+ return new TVInputDeviceKey({
+ name: args.keyName,
+ code: map[args.keyName].keyCode
+ });
+ } else if (mandatoryMap[args.keyName]) {
+ return new TVInputDeviceKey({
+ name: args.keyName,
+ code: mandatoryMap[args.keyName].keyCode
+ });
+ } else {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Parameter "keyName" is invalid.'
+ );
+ }
};
-
/**
- * Registers an input device key to receive DOM keyboard event when it is pressed or released.
+ * Registers an input device key to receive DOM keyboard event when it is
+ * pressed or released.
* @param {!string} keyName The key name
*/
TVInputDeviceManager.prototype.registerKey = function(keyName) {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
- var args = validator.validateArgs(arguments, [
- {name: 'keyName', type: types.STRING}
- ]);
- if (!map[args.keyName]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Parameter "keyName" is invalid.');
- }
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
+ var args = validator.validateArgs(arguments, [
+ { name: 'keyName', type: types.STRING }
+ ]);
+ if (!map[args.keyName]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Parameter "keyName" is invalid.'
+ );
+ }
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/registerKey', map[args.keyName].keyName);
- if (ret === 'error') {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
- }
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/registerKey',
+ map[args.keyName].keyName
+ );
+ if (ret === 'error') {
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
+ }
};
-
/**
* Unregisters an input device key.
* @param {!string} keyName The key name
*/
TVInputDeviceManager.prototype.unregisterKey = function(keyName) {
- xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
- var args = validator.validateArgs(arguments, [
- {name: 'keyName', type: types.STRING}
- ]);
+ xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
+ var args = validator.validateArgs(arguments, [
+ { name: 'keyName', type: types.STRING }
+ ]);
- if (!map[args.keyName]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Parameter "keyName" is invalid.');
- }
+ if (!map[args.keyName]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Parameter "keyName" is invalid.'
+ );
+ }
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/unregisterKey', map[args.keyName].keyName);
- if (ret === 'error') {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
- }
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/unregisterKey',
+ map[args.keyName].keyName
+ );
+ if (ret === 'error') {
+ throw new WebAPIException(WebAPIException.UNKNOWN_ERR, 'UnknownError');
+ }
};
TVInputDeviceManager.prototype.registerKeyBatch = function() {
xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
var args = validator.validateMethod(arguments, [
- {
- name: 'keyNames',
- type: types.ARRAY,
- values: types.STRING
- },
- {
- name: 'successCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }
+ {
+ name: 'keyNames',
+ type: types.ARRAY,
+ values: types.STRING
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- var keysList = "";
+ var keysList = '';
for (var i = 0; i < args.keyNames.length; ++i) {
- if (!map[args.keyNames[i]]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid key name: "' + args.keyNames[i] + '"');
- }
- keysList += map[args.keyNames[i]].keyName + ((i < args.keyNames.length - 1) ? "," : "");
+ if (!map[args.keyNames[i]]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid key name: "' + args.keyNames[i] + '"'
+ );
+ }
+ keysList +=
+ map[args.keyNames[i]].keyName + (i < args.keyNames.length - 1 ? ',' : '');
}
- setTimeout(function() {
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/registerKeyBatch', keysList);
- if (ret === 'error') {
- native.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.UNKNOWN_ERR, 'Failed to register keys.'));
- } else {
- native.callIfPossible(args.successCallback);
- }
- }.bind(this), 0);
- };
+ setTimeout(
+ function() {
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/registerKeyBatch',
+ keysList
+ );
+ if (ret === 'error') {
+ native.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Failed to register keys.'
+ )
+ );
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ }.bind(this),
+ 0
+ );
+};
- TVInputDeviceManager.prototype.unregisterKeyBatch = function() {
+TVInputDeviceManager.prototype.unregisterKeyBatch = function() {
xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.TV_INPUT_DEVICE);
var args = validator.validateMethod(arguments, [
- {
- name: 'keyNames',
- type: types.ARRAY,
- values: types.STRING
- },
- {
- name: 'successCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: types.FUNCTION,
- optional: true,
- nullable: true
- }
+ {
+ name: 'keyNames',
+ type: types.ARRAY,
+ values: types.STRING
+ },
+ {
+ name: 'successCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
]);
- var keysList = "";
+ var keysList = '';
for (var i = 0; i < args.keyNames.length; ++i) {
- if (!map[args.keyNames[i]]) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
- 'Invalid key name: "' + args.keyNames[i] + '"');
- }
- keysList += map[args.keyNames[i]].keyName + ((i < args.keyNames.length - 1) ? "," : "");
+ if (!map[args.keyNames[i]]) {
+ throw new WebAPIException(
+ WebAPIException.INVALID_VALUES_ERR,
+ 'Invalid key name: "' + args.keyNames[i] + '"'
+ );
+ }
+ keysList +=
+ map[args.keyNames[i]].keyName + (i < args.keyNames.length - 1 ? ',' : '');
}
- setTimeout(function() {
- var ret = native.sendRuntimeSyncMessage('tizen://api/inputdevice/unregisterKeyBatch', keysList);
- if (ret === 'error') {
- native.callIfPossible(args.errorCallback, new WebAPIException(
- WebAPIException.UNKNOWN_ERR, 'Failed to unregister keys.'));
- } else {
- native.callIfPossible(args.successCallback);
- }
- }.bind(this), 0);
- };
+ setTimeout(
+ function() {
+ var ret = native.sendRuntimeSyncMessage(
+ 'tizen://api/inputdevice/unregisterKeyBatch',
+ keysList
+ );
+ if (ret === 'error') {
+ native.callIfPossible(
+ args.errorCallback,
+ new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Failed to unregister keys.'
+ )
+ );
+ } else {
+ native.callIfPossible(args.successCallback);
+ }
+ }.bind(this),
+ 0
+ );
+};
// Exports
exports = new TVInputDeviceManager();
diff --git a/src/utils/utils_api.js b/src/utils/utils_api.js
index 8550192c..1c5e9a9e 100644
--- a/src/utils/utils_api.js
+++ b/src/utils/utils_api.js
@@ -4,7 +4,7 @@
// found in the LICENSE file.
//Object xwalk.JSON - guaranteed to not being modified by the application programmer
-var JSON_ = {stringify: JSON.stringify, parse: JSON.parse};
+var JSON_ = { stringify: JSON.stringify, parse: JSON.parse };
Object.freeze(JSON_);
exports.JSON = JSON_;
@@ -12,564 +12,595 @@ var _enableJsLogs = false;
var _global = {};
if (typeof window != 'undefined') {
- _global = window;
-}
-else if (typeof global != 'undefined') {
- _global = global;
+ _global = window;
+} else if (typeof global != 'undefined') {
+ _global = global;
}
/**
* @deprecated Used only by validateArguments()
*/
var signature_to_type = {
- 'n': 'number',
- 'f': 'function',
- 'b': 'boolean',
- 's': 'string',
- 'o': 'object'
+ n: 'number',
+ f: 'function',
+ b: 'boolean',
+ s: 'string',
+ o: 'object'
};
var DateConverter = function() {};
DateConverter.prototype.toTZDate = function(v, isAllDay) {
- if (typeof v === 'number') {
- v = {
- UTCTimestamp: v
- };
- isAllDay = false;
- }
+ if (typeof v === 'number') {
+ v = {
+ UTCTimestamp: v
+ };
+ isAllDay = false;
+ }
- if (!(v instanceof _global.Object)) {
- return v;
- }
+ if (!(v instanceof _global.Object)) {
+ return v;
+ }
- if (isAllDay) {
- return new tizen.TZDate(v.year, v.month - 1, v.day,
- null, null, null, null, v.timezone || null);
- } else {
- return new tizen.TZDate(new Date(v.UTCTimestamp * 1000));
- }
+ if (isAllDay) {
+ return new tizen.TZDate(
+ v.year,
+ v.month - 1,
+ v.day,
+ null,
+ null,
+ null,
+ null,
+ v.timezone || null
+ );
+ } else {
+ return new tizen.TZDate(new Date(v.UTCTimestamp * 1000));
+ }
};
DateConverter.prototype.fromTZDate = function(v) {
- if (!tizen.TZDate || !(v instanceof tizen.TZDate)) {
- return v;
- }
-
- return {
- year: v.getFullYear(),
- month: v.getMonth(),
- day: v.getDate(),
- timezone: v.getTimezone(),
- UTCTimestamp: v._utcTimestamp / 1000
- };
+ if (!tizen.TZDate || !(v instanceof tizen.TZDate)) {
+ return v;
+ }
+ return {
+ year: v.getFullYear(),
+ month: v.getMonth(),
+ day: v.getDate(),
+ timezone: v.getTimezone(),
+ UTCTimestamp: v._utcTimestamp / 1000
+ };
};
var _dateConverter = new DateConverter();
/** @constructor */
function Utils() {
-
- /**
- * Cynara(since tizen 3.0) only support native privilege.
- * simply web privilege convert native privilege for checking access.
- */
- var privilege = {
- ACCOUNT_READ: 'http://tizen.org/privilege/account.read',
- ACCOUNT_WRITE: 'http://tizen.org/privilege/account.write',
- ALARM: 'http://tizen.org/privilege/alarm.get',
- APPLICATION_INFO: 'http://tizen.org/privilege/application.info',
- APPLICATION_LAUNCH: 'http://tizen.org/privilege/application.launch',
- APPMANAGER_CERTIFICATE: 'http://tizen.org/privilege/appmanager.certificate',
- APPMANAGER_KILL: 'http://tizen.org/privilege/appmanager.kill',
- BLUETOOTH_ADMIN: 'http://tizen.org/privilege/bluetooth.admin',
- BLUETOOTH_GAP: 'http://tizen.org/privilege/bluetooth.gap',
- BLUETOOTH_HEALTH: 'http://tizen.org/privilege/bluetooth.health',
- BLUETOOTH_SPP: 'http://tizen.org/privilege/bluetooth.spp',
- BLUETOOTHMANAGER: 'http://tizen.org/privilege/bluetoothmanager',
- BLUETOOTH: 'http://tizen.org/privilege/bluetooth',
- BOOKMARK_READ: 'http://tizen.org/privilege/bookmark.read',
- BOOKMARK_WRITE: 'http://tizen.org/privilege/bookmark.write',
- CALENDAR_READ: 'http://tizen.org/privilege/calendar.read',
- CALENDAR_WRITE: 'http://tizen.org/privilege/calendar.write',
- CALLHISTORY_READ: 'http://tizen.org/privilege/callhistory.read',
- CALLHISTORY_WRITE: 'http://tizen.org/privilege/callhistory.write',
- CONTACT_READ: 'http://tizen.org/privilege/contact.read',
- CONTACT_WRITE: 'http://tizen.org/privilege/contact.write',
- CONTENT_READ: 'http://tizen.org/privilege/content.write',
- CONTENT_WRITE: 'http://tizen.org/privilege/content.write',
- DATACONTROL_CONSUMER: 'http://tizen.org/privilege/datacontrol.consumer',
- DATASYNC: 'http://tizen.org/privilege/datasync',
- DOWNLOAD: 'http://tizen.org/privilege/download',
- FILESYSTEM_READ: 'http://tizen.org/privilege/filesystem.read',
- FILESYSTEM_WRITE: 'http://tizen.org/privilege/filesystem.write',
- HAPTIC: 'http://tizen.org/privilege/haptic',
- HEALTHINFO: 'http://tizen.org/privilege/healthinfo',
- INTERNET: 'http://tizen.org/privilege/internet',
- LED: 'http://tizen.org/privilege/led',
- LOCATION: 'http://tizen.org/privilege/location',
- MEDIACONTROLLER_SERVER: 'http://tizen.org/privilege/mediacontroller.server',
- MEDIACONTROLLER_CLIENT: 'http://tizen.org/privilege/mediacontroller.client',
- MESSAGING_READ: 'http://tizen.org/privilege/messaging.read',
- MESSAGING_WRITE: 'http://tizen.org/privilege/messaging.write',
- NETWORKBEARERSELECTION: 'http://tizen.org/privilege/networkbearerselection',
- NFC_ADMIN: 'http://tizen.org/privilege/nfc.admin',
- NFC_CARDEMULATION: 'http://tizen.org/privilege/nfc.cardemulation',
- NFC_COMMON: 'http://tizen.org/privilege/nfc.common',
- NFC_P2P: 'http://tizen.org/privilege/nfc.p2p',
- NFC_TAG: 'http://tizen.org/privilege/nfc.tag',
- NOTIFICATION: 'http://tizen.org/privilege/notification',
- PACKAGE_INFO: 'http://tizen.org/privilege/packagemanager.info',
- PACKAGEMANAGER_INSTALL: 'http://tizen.org/privilege/packagemanager.install',
- POWER: 'http://tizen.org/privilege/power',
- PUSH: 'http://tizen.org/privilege/push',
- SECUREELEMENT: 'http://tizen.org/privilege/secureelement',
- SETTING_ADMIN: 'http://tizen.org/privilege/systemsettings.admin',
- SETTING: 'http://tizen.org/privilege/setting',
- SYSTEM: 'http://tizen.org/privilege/system',
- SYSTEMMANAGER: 'http://tizen.org/privilege/systemmanager',
- TELEPHONY: 'http://tizen.org/privilege/telephony',
- VOLUME_SET: 'http://tizen.org/privilege/volume.set',
- WEBSETTING: 'http://tizen.org/privilege/websetting',
- TV_INPUT_DEVICE: 'http://tizen.org/privilege/tv.inputdevice'
- };
-
- Object.freeze(privilege);
-
- Object.defineProperty(this, 'privilege', {
- value: privilege,
- writable: false,
- enumerable: true,
- configurable: false
- });
+ /**
+ * Cynara(since tizen 3.0) only support native privilege.
+ * simply web privilege convert native privilege for checking access.
+ */
+ var privilege = {
+ ACCOUNT_READ: 'http://tizen.org/privilege/account.read',
+ ACCOUNT_WRITE: 'http://tizen.org/privilege/account.write',
+ ALARM: 'http://tizen.org/privilege/alarm.get',
+ APPLICATION_INFO: 'http://tizen.org/privilege/application.info',
+ APPLICATION_LAUNCH: 'http://tizen.org/privilege/application.launch',
+ APPMANAGER_CERTIFICATE: 'http://tizen.org/privilege/appmanager.certificate',
+ APPMANAGER_KILL: 'http://tizen.org/privilege/appmanager.kill',
+ BLUETOOTH_ADMIN: 'http://tizen.org/privilege/bluetooth.admin',
+ BLUETOOTH_GAP: 'http://tizen.org/privilege/bluetooth.gap',
+ BLUETOOTH_HEALTH: 'http://tizen.org/privilege/bluetooth.health',
+ BLUETOOTH_SPP: 'http://tizen.org/privilege/bluetooth.spp',
+ BLUETOOTHMANAGER: 'http://tizen.org/privilege/bluetoothmanager',
+ BLUETOOTH: 'http://tizen.org/privilege/bluetooth',
+ BOOKMARK_READ: 'http://tizen.org/privilege/bookmark.read',
+ BOOKMARK_WRITE: 'http://tizen.org/privilege/bookmark.write',
+ CALENDAR_READ: 'http://tizen.org/privilege/calendar.read',
+ CALENDAR_WRITE: 'http://tizen.org/privilege/calendar.write',
+ CALLHISTORY_READ: 'http://tizen.org/privilege/callhistory.read',
+ CALLHISTORY_WRITE: 'http://tizen.org/privilege/callhistory.write',
+ CONTACT_READ: 'http://tizen.org/privilege/contact.read',
+ CONTACT_WRITE: 'http://tizen.org/privilege/contact.write',
+ CONTENT_READ: 'http://tizen.org/privilege/content.write',
+ CONTENT_WRITE: 'http://tizen.org/privilege/content.write',
+ DATACONTROL_CONSUMER: 'http://tizen.org/privilege/datacontrol.consumer',
+ DATASYNC: 'http://tizen.org/privilege/datasync',
+ DOWNLOAD: 'http://tizen.org/privilege/download',
+ FILESYSTEM_READ: 'http://tizen.org/privilege/filesystem.read',
+ FILESYSTEM_WRITE: 'http://tizen.org/privilege/filesystem.write',
+ HAPTIC: 'http://tizen.org/privilege/haptic',
+ HEALTHINFO: 'http://tizen.org/privilege/healthinfo',
+ INTERNET: 'http://tizen.org/privilege/internet',
+ LED: 'http://tizen.org/privilege/led',
+ LOCATION: 'http://tizen.org/privilege/location',
+ MEDIACONTROLLER_SERVER: 'http://tizen.org/privilege/mediacontroller.server',
+ MEDIACONTROLLER_CLIENT: 'http://tizen.org/privilege/mediacontroller.client',
+ MESSAGING_READ: 'http://tizen.org/privilege/messaging.read',
+ MESSAGING_WRITE: 'http://tizen.org/privilege/messaging.write',
+ NETWORKBEARERSELECTION: 'http://tizen.org/privilege/networkbearerselection',
+ NFC_ADMIN: 'http://tizen.org/privilege/nfc.admin',
+ NFC_CARDEMULATION: 'http://tizen.org/privilege/nfc.cardemulation',
+ NFC_COMMON: 'http://tizen.org/privilege/nfc.common',
+ NFC_P2P: 'http://tizen.org/privilege/nfc.p2p',
+ NFC_TAG: 'http://tizen.org/privilege/nfc.tag',
+ NOTIFICATION: 'http://tizen.org/privilege/notification',
+ PACKAGE_INFO: 'http://tizen.org/privilege/packagemanager.info',
+ PACKAGEMANAGER_INSTALL: 'http://tizen.org/privilege/packagemanager.install',
+ POWER: 'http://tizen.org/privilege/power',
+ PUSH: 'http://tizen.org/privilege/push',
+ SECUREELEMENT: 'http://tizen.org/privilege/secureelement',
+ SETTING_ADMIN: 'http://tizen.org/privilege/systemsettings.admin',
+ SETTING: 'http://tizen.org/privilege/setting',
+ SYSTEM: 'http://tizen.org/privilege/system',
+ SYSTEMMANAGER: 'http://tizen.org/privilege/systemmanager',
+ TELEPHONY: 'http://tizen.org/privilege/telephony',
+ VOLUME_SET: 'http://tizen.org/privilege/volume.set',
+ WEBSETTING: 'http://tizen.org/privilege/websetting',
+ TV_INPUT_DEVICE: 'http://tizen.org/privilege/tv.inputdevice'
+ };
+
+ Object.freeze(privilege);
+
+ Object.defineProperty(this, 'privilege', {
+ value: privilege,
+ writable: false,
+ enumerable: true,
+ configurable: false
+ });
}
Utils.prototype.error = console.error.bind(console);
Utils.prototype.warn = console.warn.bind(console);
-Utils.prototype.log = _enableJsLogs ? console.log.bind(console) : function(){};
+Utils.prototype.log = _enableJsLogs ? console.log.bind(console) : function() {};
Utils.prototype.global = _global;
Utils.prototype.repackFilter = function(filter) {
- if (filter instanceof tizen.AttributeFilter) {
- return {
- filterType: 'AttributeFilter',
- attributeName: filter.attributeName,
- matchFlag: filter.matchFlag,
- matchValue: _dateConverter.fromTZDate(filter.matchValue)
- };
- }
- if (filter instanceof tizen.AttributeRangeFilter) {
- return {
- filterType: 'AttributeRangeFilter',
- attributeName: filter.attributeName,
- initialValue: _dateConverter.fromTZDate(filter.initialValue),
- endValue: _dateConverter.fromTZDate(filter.endValue)
- };
- }
- if (filter instanceof tizen.CompositeFilter) {
- var _f = [];
- var filters = filter.filters;
-
- for (var i = 0; i < filters.length; ++i) {
- _f.push(this.repackFilter(filters[i]));
+ if (filter instanceof tizen.AttributeFilter) {
+ return {
+ filterType: 'AttributeFilter',
+ attributeName: filter.attributeName,
+ matchFlag: filter.matchFlag,
+ matchValue: _dateConverter.fromTZDate(filter.matchValue)
+ };
}
+ if (filter instanceof tizen.AttributeRangeFilter) {
+ return {
+ filterType: 'AttributeRangeFilter',
+ attributeName: filter.attributeName,
+ initialValue: _dateConverter.fromTZDate(filter.initialValue),
+ endValue: _dateConverter.fromTZDate(filter.endValue)
+ };
+ }
+ if (filter instanceof tizen.CompositeFilter) {
+ var _f = [];
+ var filters = filter.filters;
- return {
- filterType: 'CompositeFilter',
- type: filter.type,
- filters: _f
- };
- }
+ for (var i = 0; i < filters.length; ++i) {
+ _f.push(this.repackFilter(filters[i]));
+ }
- return null;
+ return {
+ filterType: 'CompositeFilter',
+ type: filter.type,
+ filters: _f
+ };
+ }
+
+ return null;
};
/**
* @deprecated You should use xwalk.utils.validator.validateMethod() instead.
*/
Utils.prototype.validateArguments = function(signature, args) {
- var full_args = Array.prototype.slice.call(args);
+ var full_args = Array.prototype.slice.call(args);
- // After '?' everything is optional.
- var mandatory_len = signature.indexOf('?') === -1 ? signature.length : signature.indexOf('?');
+ // After '?' everything is optional.
+ var mandatory_len =
+ signature.indexOf('?') === -1 ? signature.length : signature.indexOf('?');
- if (full_args.length < mandatory_len)
- return false;
+ if (full_args.length < mandatory_len) return false;
- // Mandatory arguments.
- for (var i = 0; i < mandatory_len; i++) {
- if (typeof full_args[i] !== signature_to_type[signature[i]] || full_args[i] === null)
- return false;
- }
+ // Mandatory arguments.
+ for (var i = 0; i < mandatory_len; i++) {
+ if (
+ typeof full_args[i] !== signature_to_type[signature[i]] ||
+ full_args[i] === null
+ )
+ return false;
+ }
- // Optional args may be null.
- for (var i = mandatory_len; i < full_args.length && i < signature.length - 1; i++) {
- if (full_args[i] !== null && typeof full_args[i] !== signature_to_type[signature[i + 1]])
- return false;
- }
+ // Optional args may be null.
+ for (var i = mandatory_len; i < full_args.length && i < signature.length - 1; i++) {
+ if (
+ full_args[i] !== null &&
+ typeof full_args[i] !== signature_to_type[signature[i + 1]]
+ )
+ return false;
+ }
- return true;
+ return true;
};
Utils.prototype.validateObject = function(object, signature, attributes) {
- for (var i = 0; i < signature.length; i++) {
- if (object.hasOwnProperty(attributes[i]) &&
- typeof object[attributes[i]] !== signature_to_type[signature[i]]) {
- return false;
+ for (var i = 0; i < signature.length; i++) {
+ if (
+ object.hasOwnProperty(attributes[i]) &&
+ typeof object[attributes[i]] !== signature_to_type[signature[i]]
+ ) {
+ return false;
+ }
}
- }
- return true;
+ return true;
};
Utils.prototype.getPkgApiVersion = function() {
- var result = native_.callSync('Utils_getPkgApiVersion');
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- return native_.getResultObject(result);
+ var result = native_.callSync('Utils_getPkgApiVersion');
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ return native_.getResultObject(result);
};
Utils.prototype.checkPrivilegeAccess = function(privilege) {
- var result = native_.callSync('Utils_checkPrivilegeAccess', {
- privilege : _toString(privilege),
- });
-
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
-};
-
-Utils.prototype.isAppVersionEarlierThan= function(ver) {
- var app_ver = this.getPkgApiVersion();
-
- var arr_ver = ver.split("."); // reference version
- var arr_app_ver = app_ver.split("."); // application version
- var num_ver;
- var num_app;
-
- var i;
- var length = Math.min(arr_ver.length, arr_app_ver.length);
- for (i = 0; i < length; i++) {
- num_ver = parseInt(arr_ver[i]);
- num_app = parseInt(arr_app_ver[i]);
- if (num_app < num_ver) {
- return true;
- } else if (num_app > num_ver) {
- return false;
+ var result = native_.callSync('Utils_checkPrivilegeAccess', {
+ privilege: _toString(privilege)
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
}
- }
+};
- if (arr_ver.length > arr_app_ver.length) {
- return true;
- }
- return false;
-}
+Utils.prototype.isAppVersionEarlierThan = function(ver) {
+ var app_ver = this.getPkgApiVersion();
+
+ var arr_ver = ver.split('.'); // reference version
+ var arr_app_ver = app_ver.split('.'); // application version
+ var num_ver;
+ var num_app;
+
+ var i;
+ var length = Math.min(arr_ver.length, arr_app_ver.length);
+ for (i = 0; i < length; i++) {
+ num_ver = parseInt(arr_ver[i]);
+ num_app = parseInt(arr_app_ver[i]);
+ if (num_app < num_ver) {
+ return true;
+ } else if (num_app > num_ver) {
+ return false;
+ }
+ }
-Utils.prototype.checkPrivilegeAccess4Ver = function(new_ver, new_priv, old_priv) {
- if (!this.isAppVersionEarlierThan(new_ver)) {
- this.checkPrivilegeAccess(new_priv);
- } else if (old_priv != undefined) {
- this.checkPrivilegeAccess(old_priv);
- }
-}
+ if (arr_ver.length > arr_app_ver.length) {
+ return true;
+ }
+ return false;
+};
-Utils.prototype.checkBackwardCompabilityPrivilegeAccess = function(current_privilege, previous_privilege) {
- var result = native_.callSync('Utils_checkBackwardCompabilityPrivilegeAccess', {
- current_privilege : _toString(current_privilege),
- previous_privilege : _toString(previous_privilege),
- });
+Utils.prototype.checkPrivilegeAccess4Ver = function(new_ver, new_priv, old_priv) {
+ if (!this.isAppVersionEarlierThan(new_ver)) {
+ this.checkPrivilegeAccess(new_priv);
+ } else if (old_priv != undefined) {
+ this.checkPrivilegeAccess(old_priv);
+ }
+};
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+Utils.prototype.checkBackwardCompabilityPrivilegeAccess = function(
+ current_privilege,
+ previous_privilege
+) {
+ var result = native_.callSync('Utils_checkBackwardCompabilityPrivilegeAccess', {
+ current_privilege: _toString(current_privilege),
+ previous_privilege: _toString(previous_privilege)
+ });
+
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
Utils.prototype.checkProfile = function() {
- var result = native_.callSync('Utils_checkProfile', {});
+ var result = native_.callSync('Utils_checkProfile', {});
- return native_.getResultObject(result);
+ return native_.getResultObject(result);
};
-
/////////////////////////////////////////////////////////////////////////////
/** @constructor */
var Type = function() {};
Type.prototype.isBoolean = function(obj) {
- return typeof obj === 'boolean';
+ return typeof obj === 'boolean';
};
Type.prototype.isObject = function(obj) {
- return (null !== obj && typeof obj === 'object' && !this.isArray(obj));
+ return null !== obj && typeof obj === 'object' && !this.isArray(obj);
};
Type.prototype.isArray = function(obj) {
- return Array.isArray(obj);
+ return Array.isArray(obj);
};
Type.prototype.isFunction = function(obj) {
- return typeof obj === 'function';
+ return typeof obj === 'function';
};
Type.prototype.isNumber = function(obj) {
- return typeof obj === 'number';
+ return typeof obj === 'number';
};
Type.prototype.isString = function(obj) {
- return typeof obj === 'string';
+ return typeof obj === 'string';
};
Type.prototype.isDate = function(obj) {
- return obj instanceof Date;
+ return obj instanceof Date;
};
Type.prototype.isNull = function(obj) {
- return obj === null;
+ return obj === null;
};
Type.prototype.isNullOrUndefined = function(obj) {
- return (obj === null || obj === undefined);
+ return obj === null || obj === undefined;
};
Type.prototype.isUndefined = function(obj) {
- return obj === void 0;
+ return obj === void 0;
};
Type.prototype.isA = function(obj, type) {
- var clas = Object.prototype.toString.call(obj).slice(8, -1);
- return (obj !== undefined) && (obj !== null) && (clas === type);
+ var clas = Object.prototype.toString.call(obj).slice(8, -1);
+ return obj !== undefined && obj !== null && clas === type;
};
Type.prototype.isEmptyObject = function(obj) {
- for (var property in obj) {
- if (obj.hasOwnProperty(property)) {
- return false;
+ for (var property in obj) {
+ if (obj.hasOwnProperty(property)) {
+ return false;
+ }
}
- }
- return true;
+ return true;
};
Type.prototype.hasProperty = function(obj, prop) {
- return prop in obj;
+ return prop in obj;
};
Type.prototype.arrayContains = function(arr, value) {
- return (arr.indexOf(value) > -1);
+ return arr.indexOf(value) > -1;
};
Type.prototype.getValues = function(obj) {
- var ret = [];
- for (var key in obj) {
- if (obj.hasOwnProperty(key)) {
- ret.push(obj[key]);
+ var ret = [];
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key)) {
+ ret.push(obj[key]);
+ }
}
- }
- return ret;
+ return ret;
};
var _type = new Type();
-
-
/////////////////////////////////////////////////////////////////////////////
/** @constructor */
var Converter = function() {};
function _nullableGeneric(func, nullable, val) {
- if (_type.isNull(val) && nullable === true) {
- return val;
- } else {
- return func.apply(null, [].slice.call(arguments, 2));
- }
+ if (_type.isNull(val) && nullable === true) {
+ return val;
+ } else {
+ return func.apply(null, [].slice.call(arguments, 2));
+ }
}
function _toBoolean(val) {
- return Boolean(val);
+ return Boolean(val);
}
Converter.prototype.toBoolean = function(val, nullable) {
- return _nullableGeneric(_toBoolean, nullable, val);
+ return _nullableGeneric(_toBoolean, nullable, val);
};
function _toLong(val) {
- var ret = parseInt(val);
- return isNaN(ret) ? (val === true ? 1 : 0) : ret;
+ var ret = parseInt(val);
+ return isNaN(ret) ? (val === true ? 1 : 0) : ret;
}
Converter.prototype.toLong = function(val, nullable) {
- return _nullableGeneric(_toLong, nullable, val);
+ return _nullableGeneric(_toLong, nullable, val);
};
function _toLongLong(val) {
- // According to WebIDL specification this will not be a precise representation
- // of requested val. We're converting the val to signed long and then pass it
- // to C++ to get the value in required range.
- return native_.getResultObject(native_.callSync('Utils_toLongLong', {
- n : _toLong(val)
- }));
+ // According to WebIDL specification this will not be a precise representation
+ // of requested val. We're converting the val to signed long and then pass it
+ // to C++ to get the value in required range.
+ return native_.getResultObject(
+ native_.callSync('Utils_toLongLong', {
+ n: _toLong(val)
+ })
+ );
}
Converter.prototype.toLongLong = function(val, nullable) {
- return _nullableGeneric(_toLongLong, nullable, val);
+ return _nullableGeneric(_toLongLong, nullable, val);
};
function _toUnsignedLong(val) {
- return _toLong(val) >>> 0;
+ return _toLong(val) >>> 0;
}
Converter.prototype.toUnsignedLong = function(val, nullable) {
- return _nullableGeneric(_toUnsignedLong, nullable, val);
+ return _nullableGeneric(_toUnsignedLong, nullable, val);
};
function _toUnsignedLongLong(val) {
- // According to WebIDL specification this will not be a precise representation
- // of requested val. We're converting the val to signed long and then pass it
- // to C++ to get the value in required range.
- return native_.getResultObject(native_.callSync('Utils_toUnsignedLongLong', {
- n : _toLong(val)
- }));
+ // According to WebIDL specification this will not be a precise representation
+ // of requested val. We're converting the val to signed long and then pass it
+ // to C++ to get the value in required range.
+ return native_.getResultObject(
+ native_.callSync('Utils_toUnsignedLongLong', {
+ n: _toLong(val)
+ })
+ );
}
Converter.prototype.toUnsignedLongLong = function(val, nullable) {
- return _nullableGeneric(_toUnsignedLongLong, nullable, val);
+ return _nullableGeneric(_toUnsignedLongLong, nullable, val);
};
function _toShort(val) {
- return ((_toLong(val) + 32768) & 0xFFFF) - 32768;
+ return ((_toLong(val) + 32768) & 0xffff) - 32768;
}
Converter.prototype.toShort = function(val, nullable) {
- return _nullableGeneric(_toShort, nullable, val);
+ return _nullableGeneric(_toShort, nullable, val);
};
function _toUnsignedShort(val) {
- return (Math.abs(_toLong(val)) & 0xFFFF);
+ return Math.abs(_toLong(val)) & 0xffff;
}
Converter.prototype.toUnsignedShort = function(val, nullable) {
- return _nullableGeneric(_toUnsignedShort, nullable, val);
+ return _nullableGeneric(_toUnsignedShort, nullable, val);
};
function _toByte(val) {
- return ((_toLong(val) + 128) & 0xFF) - 128;
+ return ((_toLong(val) + 128) & 0xff) - 128;
}
Converter.prototype.toByte = function(val, nullable) {
- return _nullableGeneric(_toByte, nullable, val);
+ return _nullableGeneric(_toByte, nullable, val);
};
function _toOctet(val) {
- return _toLong(val) & 0xFF;
+ return _toLong(val) & 0xff;
}
Converter.prototype.toOctet = function(val, nullable) {
- return _nullableGeneric(_toOctet, nullable, val);
+ return _nullableGeneric(_toOctet, nullable, val);
};
function _toDouble(val) {
- var ret = Number(val);
- if (isNaN(ret) || !isFinite(ret)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Cannot convert ' + String(val) + ' to double.');
- }
- return ret;
+ var ret = Number(val);
+ if (isNaN(ret) || !isFinite(ret)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert ' + String(val) + ' to double.'
+ );
+ }
+ return ret;
}
Converter.prototype.toDouble = function(val, nullable) {
- return _nullableGeneric(_toDouble, nullable, val);
+ return _nullableGeneric(_toDouble, nullable, val);
};
function _toString(val) {
- return String(val);
+ return String(val);
}
Converter.prototype.toString = function(val, nullable) {
- return _nullableGeneric(_toString, nullable, val);
+ return _nullableGeneric(_toString, nullable, val);
};
function _toPlatformObject(val, types) {
- var t;
-
- if (_type.isArray(types)) {
- t = types;
- } else {
- t = [types];
- }
-
- if (_type.isArray(val)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Cannot convert ' + String(val) + ' to ' + String(t[0].name) + '.');
- }
-
- var match = false;
- for (var i = 0; i < t.length; ++i) {
- if (val instanceof t[i]) {
- return val;
+ var t;
+
+ if (_type.isArray(types)) {
+ t = types;
+ } else {
+ t = [types];
+ }
+
+ if (_type.isArray(val)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert ' + String(val) + ' to ' + String(t[0].name) + '.'
+ );
+ }
+
+ var match = false;
+ for (var i = 0; i < t.length; ++i) {
+ if (val instanceof t[i]) {
+ return val;
+ }
}
- }
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Cannot convert ' + String(val) + ' to ' + String(t[0].name) + '.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert ' + String(val) + ' to ' + String(t[0].name) + '.'
+ );
}
Converter.prototype.toPlatformObject = function(val, types, nullable) {
- return _nullableGeneric(_toPlatformObject, nullable, val, types);
+ return _nullableGeneric(_toPlatformObject, nullable, val, types);
};
function _toFunction(val) {
- if (_type.isFunction(val)) {
- return val;
- }
+ if (_type.isFunction(val)) {
+ return val;
+ }
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Cannot convert ' + String(val) + ' to function.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert ' + String(val) + ' to function.'
+ );
}
Converter.prototype.toFunction = function(val, nullable) {
- return _nullableGeneric(_toFunction, nullable, val);
+ return _nullableGeneric(_toFunction, nullable, val);
};
function _toArray(val) {
- if (_type.isArray(val)) {
- return val;
- }
+ if (_type.isArray(val)) {
+ return val;
+ }
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Cannot convert ' + String(val) + ' to array.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert ' + String(val) + ' to array.'
+ );
}
Converter.prototype.toArray = function(val, nullable) {
- return _nullableGeneric(_toArray, nullable, val);
+ return _nullableGeneric(_toArray, nullable, val);
};
function _toDictionary(val) {
- if (_type.isObject(val) || _type.isFunction(val)) {
- return val;
- }
+ if (_type.isObject(val) || _type.isFunction(val)) {
+ return val;
+ }
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Cannot convert ' + String(val) + ' to dictionary.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert ' + String(val) + ' to dictionary.'
+ );
}
Converter.prototype.toDictionary = function(val, nullable) {
- return _nullableGeneric(_toDictionary, nullable, val);
+ return _nullableGeneric(_toDictionary, nullable, val);
};
function _toEnum(val, e) {
- var v = _toString(val);
- if (_type.arrayContains(e, v)) {
- return v;
- }
+ var v = _toString(val);
+ if (_type.arrayContains(e, v)) {
+ return v;
+ }
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Cannot convert ' + v + ' to enum.');
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert ' + v + ' to enum.'
+ );
}
Converter.prototype.toEnum = function(val, e, nullable) {
- return _nullableGeneric(_toEnum, nullable, val, e);
+ return _nullableGeneric(_toEnum, nullable, val, e);
};
var _converter = new Converter();
@@ -577,28 +608,27 @@ var _converter = new Converter();
/////////////////////////////////////////////////////////////////////////////
/** @constructor */
var Validator = function() {
- this.Types = {
- BOOLEAN: 'BOOLEAN',
- LONG: 'LONG',
- LONG_LONG: 'LONG_LONG',
- UNSIGNED_LONG: 'UNSIGNED_LONG',
- UNSIGNED_LONG_LONG: 'UNSIGNED_LONG_LONG',
- BYTE: 'BYTE',
- OCTET: 'OCTET',
- DOUBLE: 'DOUBLE',
- STRING: 'STRING',
- FUNCTION: 'FUNCTION',
- DICTIONARY: 'DICTIONARY',
- PLATFORM_OBJECT: 'PLATFORM_OBJECT',
- LISTENER: 'LISTENER',
- ARRAY: 'ARRAY',
- ENUM: 'ENUM',
- FILE_REFERENCE: 'FILE_REFERENCE',
- SIMPLE_TYPE: 'SIMPLE_TYPE' // Boolean, Number or String
- };
+ this.Types = {
+ BOOLEAN: 'BOOLEAN',
+ LONG: 'LONG',
+ LONG_LONG: 'LONG_LONG',
+ UNSIGNED_LONG: 'UNSIGNED_LONG',
+ UNSIGNED_LONG_LONG: 'UNSIGNED_LONG_LONG',
+ BYTE: 'BYTE',
+ OCTET: 'OCTET',
+ DOUBLE: 'DOUBLE',
+ STRING: 'STRING',
+ FUNCTION: 'FUNCTION',
+ DICTIONARY: 'DICTIONARY',
+ PLATFORM_OBJECT: 'PLATFORM_OBJECT',
+ LISTENER: 'LISTENER',
+ ARRAY: 'ARRAY',
+ ENUM: 'ENUM',
+ FILE_REFERENCE: 'FILE_REFERENCE',
+ SIMPLE_TYPE: 'SIMPLE_TYPE' // Boolean, Number or String
+ };
};
-
/**
* Verifies if arguments passed to function are valid.
*
@@ -615,7 +645,8 @@ var Validator = function() {
* - values - required in case of some objects, value depends on type
* - validator - function which accepts a single parameter and returns true or false;
* if this property is present, this function will be executed,
- * argument converted to expected type is going to be passed to this function
+ * argument converted to expected type is going to be passed to this
+ * function
*
* @param {Array} a - arguments of a method
* @param {Array} d - description of expected arguments
@@ -692,7 +723,8 @@ var Validator = function() {
* {
* name: 'first',
* type: Validator.Types.ARRAY,
- * values: Validator.Types.DOUBLE // converts elements, only primitive types are supported
+ * values: Validator.Types.DOUBLE // converts elements, only primitive types are
+ * supported
* }
* ]
* @code
@@ -705,198 +737,223 @@ var Validator = function() {
* ]
*/
Validator.prototype.validateArgs = function(a, d) {
- var args = {has: {}};
-
- for (var i = 0; i < d.length; ++i) {
- var name = d[i].name;
- args.has[name] = (i < a.length);
-
- var optional = d[i].optional;
- var nullable = d[i].nullable;
- var val = a[i];
-
- if (args.has[name] || !optional) {
- var type = d[i].type;
- var values = d[i].values;
-
- switch (type) {
- case this.Types.BOOLEAN:
- val = _converter.toBoolean(val, nullable);
- break;
-
- case this.Types.LONG:
- val = _converter.toLong(val, nullable);
- break;
-
- case this.Types.LONG_LONG:
- val = _converter.toLongLong(val, nullable);
- break;
-
- case this.Types.UNSIGNED_LONG:
- val = _converter.toUnsignedLong(val, nullable);
- break;
-
- case this.Types.UNSIGNED_LONG_LONG:
- val = _converter.toUnsignedLongLong(val, nullable);
- break;
-
- case this.Types.BYTE:
- val = _converter.toByte(val, nullable);
- break;
-
- case this.Types.OCTET:
- val = _converter.toOctet(val, nullable);
- break;
-
- case this.Types.DOUBLE:
- val = _converter.toDouble(val, nullable);
- break;
-
- case this.Types.STRING:
- val = _converter.toString(val, nullable);
- break;
-
- case this.Types.FUNCTION:
- val = _converter.toFunction(val, nullable);
- break;
-
- case this.Types.DICTIONARY:
- val = _converter.toDictionary(val, nullable);
- break;
-
- case this.Types.PLATFORM_OBJECT:
- val = _converter.toPlatformObject(val, values, nullable);
- break;
-
- case this.Types.LISTENER:
- if (_type.isNull(val)) {
- if (!nullable) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "' + name + '" cannot be null.');
- }
- } else {
- if (!_type.isObject(val)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "' + name + '" should be an object.');
- }
- for (var ii = 0; ii < values.length; ++ii) {
- if (_type.hasProperty(val, values[ii])) {
- val[values[ii]] = _converter.toFunction(val[values[ii]], false);
- }
- }
- }
- break;
+ var args = { has: {} };
+
+ for (var i = 0; i < d.length; ++i) {
+ var name = d[i].name;
+ args.has[name] = i < a.length;
+
+ var optional = d[i].optional;
+ var nullable = d[i].nullable;
+ var val = a[i];
- case this.Types.ARRAY:
- val = _converter.toArray(val, nullable);
- if (!_type.isNull(val) && values) {
- var func;
+ if (args.has[name] || !optional) {
+ var type = d[i].type;
+ var values = d[i].values;
+
+ switch (type) {
+ case this.Types.BOOLEAN:
+ val = _converter.toBoolean(val, nullable);
+ break;
+
+ case this.Types.LONG:
+ val = _converter.toLong(val, nullable);
+ break;
+
+ case this.Types.LONG_LONG:
+ val = _converter.toLongLong(val, nullable);
+ break;
+
+ case this.Types.UNSIGNED_LONG:
+ val = _converter.toUnsignedLong(val, nullable);
+ break;
+
+ case this.Types.UNSIGNED_LONG_LONG:
+ val = _converter.toUnsignedLongLong(val, nullable);
+ break;
+
+ case this.Types.BYTE:
+ val = _converter.toByte(val, nullable);
+ break;
+
+ case this.Types.OCTET:
+ val = _converter.toOctet(val, nullable);
+ break;
- switch (values) {
- case this.Types.BOOLEAN:
- func = _converter.toBoolean;
+ case this.Types.DOUBLE:
+ val = _converter.toDouble(val, nullable);
break;
- case this.Types.LONG:
- func = _converter.toLong;
+ case this.Types.STRING:
+ val = _converter.toString(val, nullable);
break;
- case this.Types.LONG_LONG:
- func = _converter.toLongLong;
+ case this.Types.FUNCTION:
+ val = _converter.toFunction(val, nullable);
break;
- case this.Types.UNSIGNED_LONG:
- func = _converter.toUnsignedLong;
+ case this.Types.DICTIONARY:
+ val = _converter.toDictionary(val, nullable);
break;
- case this.Types.UNSIGNED_LONG_LONG:
- func = _converter.toUnsignedLongLong;
+ case this.Types.PLATFORM_OBJECT:
+ val = _converter.toPlatformObject(val, values, nullable);
break;
- case this.Types.BYTE:
- func = _converter.toByte;
+ case this.Types.LISTENER:
+ if (_type.isNull(val)) {
+ if (!nullable) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "' + name + '" cannot be null.'
+ );
+ }
+ } else {
+ if (!_type.isObject(val)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "' + name + '" should be an object.'
+ );
+ }
+ for (var ii = 0; ii < values.length; ++ii) {
+ if (_type.hasProperty(val, values[ii])) {
+ val[values[ii]] = _converter.toFunction(
+ val[values[ii]],
+ false
+ );
+ }
+ }
+ }
break;
- case this.Types.OCTET:
- func = _converter.toOctet;
+ case this.Types.ARRAY:
+ val = _converter.toArray(val, nullable);
+ if (!_type.isNull(val) && values) {
+ var func;
+
+ switch (values) {
+ case this.Types.BOOLEAN:
+ func = _converter.toBoolean;
+ break;
+
+ case this.Types.LONG:
+ func = _converter.toLong;
+ break;
+
+ case this.Types.LONG_LONG:
+ func = _converter.toLongLong;
+ break;
+
+ case this.Types.UNSIGNED_LONG:
+ func = _converter.toUnsignedLong;
+ break;
+
+ case this.Types.UNSIGNED_LONG_LONG:
+ func = _converter.toUnsignedLongLong;
+ break;
+
+ case this.Types.BYTE:
+ func = _converter.toByte;
+ break;
+
+ case this.Types.OCTET:
+ func = _converter.toOctet;
+ break;
+
+ case this.Types.DOUBLE:
+ func = _converter.toDouble;
+ break;
+
+ case this.Types.STRING:
+ func = _converter.toString;
+ break;
+
+ default:
+ func = function(val) {
+ if (!(val instanceof values)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Items of array "' +
+ name +
+ '" should be of type: ' +
+ values +
+ '.'
+ );
+ }
+ return val;
+ };
+ }
+
+ for (var j = 0; j < val.length; ++j) {
+ val[j] = func(val[j]);
+ }
+ }
break;
- case this.Types.DOUBLE:
- func = _converter.toDouble;
+ case this.Types.ENUM:
+ val = _converter.toEnum(val, values, nullable);
break;
- case this.Types.STRING:
- func = _converter.toString;
+ case this.Types.FILE_REFERENCE:
+ if (
+ _type.isObject(val) &&
+ 'File' === val.constructor.name &&
+ val.fullPath
+ ) {
+ val = val.fullPath;
+ }
+ val = _converter.toString(val, nullable);
break;
- default:
- func = function(val) {
- if (!(val instanceof values)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Items of array "' + name + '" should be of type: ' + values + '.');
- }
- return val;
- };
+ case this.Types.SIMPLE_TYPE:
+ if (optional && _type.isUndefined(val)) {
+ break;
+ }
+ if (nullable && _type.isNull(val)) {
+ break;
+ }
+ if (
+ !_type.isBoolean(val) &&
+ !_type.isNumber(val) &&
+ !_type.isString(val)
+ ) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "' + name + '" should be boolean, number or string.'
+ );
+ }
+ break;
+
+ default:
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Unknown type: "' + type + '".'
+ );
}
- for (var j = 0; j < val.length; ++j) {
- val[j] = func(val[j]);
+ var _validator = d[i].validator;
+
+ if (_type.isFunction(_validator) && !_validator(val)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Argument "' + name + '" did not pass additional validation.'
+ );
}
- }
- break;
-
- case this.Types.ENUM:
- val = _converter.toEnum(val, values, nullable);
- break;
-
- case this.Types.FILE_REFERENCE:
- if (_type.isObject(val) && 'File' === val.constructor.name && val.fullPath) {
- val = val.fullPath;
- }
- val = _converter.toString(val, nullable);
- break;
-
- case this.Types.SIMPLE_TYPE:
- if (optional && _type.isUndefined(val)) {
- break;
- }
- if (nullable && _type.isNull(val)) {
- break;
- }
- if (!_type.isBoolean(val) && !_type.isNumber(val) && !_type.isString(val)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "' + name + '" should be boolean, number or string.');
- }
- break;
-
- default:
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Unknown type: "' + type + '".');
- }
-
- var _validator = d[i].validator;
-
- if (_type.isFunction(_validator) && !_validator(val)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "' + name + '" did not pass additional validation.');
- }
-
- args[name] = val;
+
+ args[name] = val;
+ }
}
- }
- return args;
+ return args;
};
-
/**
* @deprecated Use validateArgs() instead.
*/
Validator.prototype.validateMethod = function(a, d) {
- return this.validateArgs(a, d);
+ return this.validateArgs(a, d);
};
-
/**
* Use this helper to ensure that constructor is invoked by "new" operator.
*
@@ -904,340 +961,369 @@ Validator.prototype.validateMethod = function(a, d) {
* @param {Function} instance
*/
Validator.prototype.isConstructorCall = function(obj, instance) {
- if (!(obj instanceof instance) || obj._previouslyConstructed) {
- // There is no TypeError exception in Tizen 2.3.0 API spec but it's required by current TCTs.
- // For Tizen compliance it's wrapped into WebAPIException.
- throw new WebAPIException('TypeError', 'Constructor cannot be called as function.');
- }
+ if (!(obj instanceof instance) || obj._previouslyConstructed) {
+ // There is no TypeError exception in Tizen 2.3.0 API spec but it's required by
+ // current TCTs.
+ // For Tizen compliance it's wrapped into WebAPIException.
+ throw new WebAPIException(
+ 'TypeError',
+ 'Constructor cannot be called as function.'
+ );
+ }
- Object.defineProperty(obj, '_previouslyConstructed', {
- value: true,
- writable: false,
- enumerable: false
- });
+ Object.defineProperty(obj, '_previouslyConstructed', {
+ value: true,
+ writable: false,
+ enumerable: false
+ });
};
-
/**
* @deprecated Use isConstructorCall() instead.
*/
Validator.prototype.validateConstructorCall = function(obj, instance) {
- this.isConstructorCall(obj, instance);
+ this.isConstructorCall(obj, instance);
};
var _validator = new Validator();
-
-
/////////////////////////////////////////////////////////////////////////////
/** @constructor */
var NativeManager = function(extension) {
-
- /**
- * @type {string}
- * @const
- */
- this.CALLBACK_ID_KEY = 'callbackId';
-
- /**
- * @type {string}
- * @const
- */
- this.LISTENER_ID_KEY = 'listenerId';
-
- /**
- * @type {Object}
- * @private
- */
- var extension_ = extension;
-
- /**
- * @type {number}
- * @private
- */
- var replyId_ = 0;
-
- /**
- * Map of async reply callbacks.
- *
- * @type {Object.<number, function>}
- * @protected
- */
- this.callbacks_ = {};
-
- /**
- * Map of registered listeners.
- *
- * @type {Object.<string, function>}
- * @protected
- */
- this.listeners_ = {};
-
- _validator.isConstructorCall(this, NativeManager);
-
- // TODO: Remove mockup if WRT implements sendRuntimeMessage
- // This is temporary mockup!
- extension.sendRuntimeMessage = extension.sendRuntimeMessage || function() {
- xwalk.utils.error('Runtime did not implement extension.sendRuntimeMessage!');
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR,
- 'Runtime did not implement extension.sendRuntimeMessage!');
- };
-
- extension.sendRuntimeAsyncMessage = extension.sendRuntimeAsyncMessage || function() {
- xwalk.utils.error('Runtime did not implement extension.sendRuntimeAsyncMessage!');
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR,
- 'Runtime did not implement extension.sendRuntimeAsyncMessage!');
- };
-
- extension.sendRuntimeSyncMessage = extension.sendRuntimeSyncMessage || function() {
- xwalk.utils.error('Runtime did not implement extension.sendRuntimeSyncMessage!');
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR,
- 'Runtime did not implement extension.sendRuntimeSyncMessage!');
- };
-
- // check extension prototype
- if (!extension || !extension.internal ||
- !_type.isFunction(extension.postMessage) ||
- !_type.isFunction(extension.internal.sendSyncMessage) ||
- !_type.isFunction(extension.sendRuntimeMessage) ||
- !_type.isFunction(extension.sendRuntimeAsyncMessage) ||
- !_type.isFunction(extension.sendRuntimeSyncMessage) ||
- !_type.isFunction(extension.setMessageListener)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR,
- 'Wrong extension object passed');
- }
-
- Object.defineProperties(this, {
- nextReplyId: {
- get: function() {
- return ++replyId_;
- },
- enumerable: false
- },
- extension: {
- get: function() {
- return extension_;
- },
- enumerable: true
- }
- });
-
- extension_.setMessageListener(function(json) {
- try {
- var msg = JSON_.parse(json);
- } catch (error) {
- // Because of special handling of power lock in chromium, the special signals:
- // - __DisableChromiumInternalPowerLock
- // - __EnableChromiumInternalPowerLock
- // could occur. In such cases we are silently ignroing those messages.
- // TODO This is workaround for missing patch in chromium-efl package which should handle
- // this special message and don't forward it to webapi JS. After chromium-efl will
- // be updated, below checking should be removed.
- if (json.substring(0,2) === '__') {
- return;
- }
- xwalk.utils.error('Ignoring message - Invalid JSON received: ' + json);
- return;
- }
- var id;
-
- if (msg.hasOwnProperty(this.CALLBACK_ID_KEY)) {
- id = msg[this.CALLBACK_ID_KEY];
- delete msg[this.CALLBACK_ID_KEY];
-
- if (!_type.isFunction(this.callbacks_[id])) {
- xwalk.utils.error('Wrong callback identifier. Ignoring message.');
- return;
- }
-
- var f = this.callbacks_[id];
- setTimeout(function() {
- try {
- f(msg);
- } catch (e) {
- xwalk.utils.error('########## exception');
- xwalk.utils.error(e);
- }
- }, 0);
- delete this.callbacks_[id];
-
- return;
+ /**
+ * @type {string}
+ * @const
+ */
+ this.CALLBACK_ID_KEY = 'callbackId';
+
+ /**
+ * @type {string}
+ * @const
+ */
+ this.LISTENER_ID_KEY = 'listenerId';
+
+ /**
+ * @type {Object}
+ * @private
+ */
+ var extension_ = extension;
+
+ /**
+ * @type {number}
+ * @private
+ */
+ var replyId_ = 0;
+
+ /**
+ * Map of async reply callbacks.
+ *
+ * @type {Object.<number, function>}
+ * @protected
+ */
+ this.callbacks_ = {};
+
+ /**
+ * Map of registered listeners.
+ *
+ * @type {Object.<string, function>}
+ * @protected
+ */
+ this.listeners_ = {};
+
+ _validator.isConstructorCall(this, NativeManager);
+
+ // TODO: Remove mockup if WRT implements sendRuntimeMessage
+ // This is temporary mockup!
+ extension.sendRuntimeMessage =
+ extension.sendRuntimeMessage ||
+ function() {
+ xwalk.utils.error('Runtime did not implement extension.sendRuntimeMessage!');
+ throw new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Runtime did not implement extension.sendRuntimeMessage!'
+ );
+ };
+
+ extension.sendRuntimeAsyncMessage =
+ extension.sendRuntimeAsyncMessage ||
+ function() {
+ xwalk.utils.error(
+ 'Runtime did not implement extension.sendRuntimeAsyncMessage!'
+ );
+ throw new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Runtime did not implement extension.sendRuntimeAsyncMessage!'
+ );
+ };
+
+ extension.sendRuntimeSyncMessage =
+ extension.sendRuntimeSyncMessage ||
+ function() {
+ xwalk.utils.error(
+ 'Runtime did not implement extension.sendRuntimeSyncMessage!'
+ );
+ throw new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Runtime did not implement extension.sendRuntimeSyncMessage!'
+ );
+ };
+
+ // check extension prototype
+ if (
+ !extension ||
+ !extension.internal ||
+ !_type.isFunction(extension.postMessage) ||
+ !_type.isFunction(extension.internal.sendSyncMessage) ||
+ !_type.isFunction(extension.sendRuntimeMessage) ||
+ !_type.isFunction(extension.sendRuntimeAsyncMessage) ||
+ !_type.isFunction(extension.sendRuntimeSyncMessage) ||
+ !_type.isFunction(extension.setMessageListener)
+ ) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Wrong extension object passed'
+ );
}
- if (msg.hasOwnProperty(this.LISTENER_ID_KEY)) {
- id = msg[this.LISTENER_ID_KEY];
- delete msg[this.LISTENER_ID_KEY];
-
- if (!_type.isFunction(this.listeners_[id])) {
- xwalk.utils.error('Wrong listener identifier. Ignoring message.');
- return;
- }
-
- var f = this.listeners_[id];
- setTimeout(function() {
- try {
- f(msg);
- } catch (e) {
- xwalk.utils.error('########## exception');
- xwalk.utils.error(e);
+ Object.defineProperties(this, {
+ nextReplyId: {
+ get: function() {
+ return ++replyId_;
+ },
+ enumerable: false
+ },
+ extension: {
+ get: function() {
+ return extension_;
+ },
+ enumerable: true
}
- }, 0);
-
- return;
- }
+ });
+
+ extension_.setMessageListener(
+ function(json) {
+ try {
+ var msg = JSON_.parse(json);
+ } catch (error) {
+ // Because of special handling of power lock in chromium, the special
+ // signals:
+ // - __DisableChromiumInternalPowerLock
+ // - __EnableChromiumInternalPowerLock
+ // could occur. In such cases we are silently ignroing those messages.
+ // TODO This is workaround for missing patch in chromium-efl package
+ // which should handle this special message and don't forward it to
+ // webapi JS. After chromium-efl will be updated, below checking should
+ // be removed.
+ if (json.substring(0, 2) === '__') {
+ return;
+ }
+ xwalk.utils.error('Ignoring message - Invalid JSON received: ' + json);
+ return;
+ }
+ var id;
+
+ if (msg.hasOwnProperty(this.CALLBACK_ID_KEY)) {
+ id = msg[this.CALLBACK_ID_KEY];
+ delete msg[this.CALLBACK_ID_KEY];
+
+ if (!_type.isFunction(this.callbacks_[id])) {
+ xwalk.utils.error('Wrong callback identifier. Ignoring message.');
+ return;
+ }
+
+ var f = this.callbacks_[id];
+ setTimeout(function() {
+ try {
+ f(msg);
+ } catch (e) {
+ xwalk.utils.error('########## exception');
+ xwalk.utils.error(e);
+ }
+ }, 0);
+ delete this.callbacks_[id];
+
+ return;
+ }
- xwalk.utils.error('Missing callback or listener identifier. Ignoring message.');
+ if (msg.hasOwnProperty(this.LISTENER_ID_KEY)) {
+ id = msg[this.LISTENER_ID_KEY];
+ delete msg[this.LISTENER_ID_KEY];
+
+ if (!_type.isFunction(this.listeners_[id])) {
+ xwalk.utils.error('Wrong listener identifier. Ignoring message.');
+ return;
+ }
+
+ var f = this.listeners_[id];
+ setTimeout(function() {
+ try {
+ f(msg);
+ } catch (e) {
+ xwalk.utils.error('########## exception');
+ xwalk.utils.error(e);
+ }
+ }, 0);
+
+ return;
+ }
- }.bind(this));
+ xwalk.utils.error(
+ 'Missing callback or listener identifier. Ignoring message.'
+ );
+ }.bind(this)
+ );
};
NativeManager.prototype.call = function(cmd, args, callback) {
- args = args || {};
+ args = args || {};
- var replyId = this.nextReplyId;
- args[this.CALLBACK_ID_KEY] = replyId;
- this.callbacks_[replyId] = callback;
+ var replyId = this.nextReplyId;
+ args[this.CALLBACK_ID_KEY] = replyId;
+ this.callbacks_[replyId] = callback;
- return this.callSync(cmd, args);
+ return this.callSync(cmd, args);
};
NativeManager.prototype.callSync = function(cmd, args) {
- var request = JSON_.stringify({
- cmd: cmd,
- args: args || {}
- });
-
- var response = this.extension.internal.sendSyncMessage(request);
- if( response === undefined ) {
- /* C++ extension didn't set sync response using Instance::SendSyncReply */
- throw new WebAPIException(WebAPIException.ABORT_ERR, "Internal error");
- }
- return JSON_.parse(response);
+ var request = JSON_.stringify({
+ cmd: cmd,
+ args: args || {}
+ });
+
+ var response = this.extension.internal.sendSyncMessage(request);
+ if (response === undefined) {
+ /* C++ extension didn't set sync response using Instance::SendSyncReply */
+ throw new WebAPIException(WebAPIException.ABORT_ERR, 'Internal error');
+ }
+ return JSON_.parse(response);
};
NativeManager.prototype.sendRuntimeMessage = function(msg, body) {
- return this.extension.sendRuntimeMessage(msg, body || '');
+ return this.extension.sendRuntimeMessage(msg, body || '');
};
NativeManager.prototype.sendRuntimeAsyncMessage = function(msg, body, callback) {
- var handler = function(response) {
- if (_type.isFunction(callback)) {
- var result = {};
- if ('success' === response.toLowerCase()) {
- result.status = 'success';
- } else {
- result.status = 'error';
- result.error = new WebAPIException(WebAPIException.UNKNOWN_ERR,
- 'Runtime message failure');
- }
- callback(result);
- }
- };
- return this.extension.sendRuntimeAsyncMessage(msg, body || '', handler);
+ var handler = function(response) {
+ if (_type.isFunction(callback)) {
+ var result = {};
+ if ('success' === response.toLowerCase()) {
+ result.status = 'success';
+ } else {
+ result.status = 'error';
+ result.error = new WebAPIException(
+ WebAPIException.UNKNOWN_ERR,
+ 'Runtime message failure'
+ );
+ }
+ callback(result);
+ }
+ };
+ return this.extension.sendRuntimeAsyncMessage(msg, body || '', handler);
};
NativeManager.prototype.sendRuntimeSyncMessage = function(msg, body) {
- return this.extension.sendRuntimeSyncMessage(msg, body || '');
+ return this.extension.sendRuntimeSyncMessage(msg, body || '');
};
NativeManager.prototype.addListener = function(name, callback) {
- if (!_type.isString(name) || !name.length) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
- }
+ if (!_type.isString(name) || !name.length) {
+ throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR);
+ }
- this.listeners_[name] = callback;
+ this.listeners_[name] = callback;
};
NativeManager.prototype.removeListener = function(name) {
- if (this.listeners_.hasOwnProperty(name)) {
- delete this.listeners_[name];
- }
+ if (this.listeners_.hasOwnProperty(name)) {
+ delete this.listeners_[name];
+ }
};
NativeManager.prototype.isListenerSet = function(name) {
- return this.listeners_.hasOwnProperty(name);
+ return this.listeners_.hasOwnProperty(name);
};
NativeManager.prototype.isSuccess = function(result) {
- return (result.status !== 'error');
+ return result.status !== 'error';
};
NativeManager.prototype.isFailure = function(result) {
- return !this.isSuccess(result);
+ return !this.isSuccess(result);
};
NativeManager.prototype.getResultObject = function(result) {
- return result.result;
+ return result.result;
};
NativeManager.prototype.getErrorObject = function(result) {
- return new WebAPIException(result.error);
+ return new WebAPIException(result.error);
};
NativeManager.prototype.callIfPossible = function(callback) {
- if (!_type.isNullOrUndefined(callback)) {
- callback.apply(callback, [].slice.call(arguments, 1));
- }
+ if (!_type.isNullOrUndefined(callback)) {
+ callback.apply(callback, [].slice.call(arguments, 1));
+ }
};
// WebAPIException and WebAPIError definition moved to Utils for compliance
// reasons with blink-wrt environment.
-// In blink-wrt the original Tizen module is loaded, which is not providing exception constructor.
+// In blink-wrt the original Tizen module is loaded, which is not providing
+// exception constructor.
// As modules needs exceptions internally so they are loaded here for now.
// See http://168.219.209.56/gerrit/#/c/23472/ for more details.
// In future exception definition could be moved back to Tizen module.
function __isObject(object) {
- return object instanceof _global.Object;
+ return object instanceof _global.Object;
}
function __isUndefined(object) {
- return object === void 0;
+ return object === void 0;
}
function __isNumber(object) {
- return typeof object === 'number';
+ return typeof object === 'number';
}
// WARNING! This list should be in sync with the equivalent enum
// located at tizen.h. Remember to update tizen.h if you change
// something here.
var errors = {
- NO_ERROR: 0,
- UNKNOWN_ERR: -1,
-
- INDEX_SIZE_ERR: 1,
- DOMSTRING_SIZE_ERR: 2,
- HIERARCHY_REQUEST_ERR: 3,
- WRONG_DOCUMENT_ERR: 4,
- INVALID_CHARACTER_ERR: 5,
- NO_DATA_ALLOWED_ERR: 6,
- NO_MODIFICATION_ALLOWED_ERR: 7,
- NOT_FOUND_ERR: 8,
- NOT_SUPPORTED_ERR: 9,
- INUSE_ATTRIBUTE_ERR: 10,
- INVALID_STATE_ERR: 11,
- SYNTAX_ERR: 12,
- INVALID_MODIFICATION_ERR: 13,
- NAMESPACE_ERR: 14,
- INVALID_ACCESS_ERR: 15,
- VALIDATION_ERR: 16,
- TYPE_MISMATCH_ERR: 17,
- SECURITY_ERR: 18,
- NETWORK_ERR: 19,
- ABORT_ERR: 20,
- URL_MISMATCH_ERR: 21,
- QUOTA_EXCEEDED_ERR: 22,
- TIMEOUT_ERR: 23,
- INVALID_NODE_TYPE_ERR: 24,
- DATA_CLONE_ERR: 25,
-
- // Error codes for these errors are not really defined anywhere.
- INVALID_VALUES_ERR: 100,
- IO_ERR: 101,
- PERMISSION_DENIED_ERR: 102,
- SERVICE_NOT_AVAILABLE_ERR: 103,
- DATABASE_ERR: 104,
- VERIFICATION_ERR: 105
+ NO_ERROR: 0,
+ UNKNOWN_ERR: -1,
+
+ INDEX_SIZE_ERR: 1,
+ DOMSTRING_SIZE_ERR: 2,
+ HIERARCHY_REQUEST_ERR: 3,
+ WRONG_DOCUMENT_ERR: 4,
+ INVALID_CHARACTER_ERR: 5,
+ NO_DATA_ALLOWED_ERR: 6,
+ NO_MODIFICATION_ALLOWED_ERR: 7,
+ NOT_FOUND_ERR: 8,
+ NOT_SUPPORTED_ERR: 9,
+ INUSE_ATTRIBUTE_ERR: 10,
+ INVALID_STATE_ERR: 11,
+ SYNTAX_ERR: 12,
+ INVALID_MODIFICATION_ERR: 13,
+ NAMESPACE_ERR: 14,
+ INVALID_ACCESS_ERR: 15,
+ VALIDATION_ERR: 16,
+ TYPE_MISMATCH_ERR: 17,
+ SECURITY_ERR: 18,
+ NETWORK_ERR: 19,
+ ABORT_ERR: 20,
+ URL_MISMATCH_ERR: 21,
+ QUOTA_EXCEEDED_ERR: 22,
+ TIMEOUT_ERR: 23,
+ INVALID_NODE_TYPE_ERR: 24,
+ DATA_CLONE_ERR: 25,
+
+ // Error codes for these errors are not really defined anywhere.
+ INVALID_VALUES_ERR: 100,
+ IO_ERR: 101,
+ PERMISSION_DENIED_ERR: 102,
+ SERVICE_NOT_AVAILABLE_ERR: 103,
+ DATABASE_ERR: 104,
+ VERIFICATION_ERR: 105
};
var code_to_name = {};
@@ -1278,100 +1364,99 @@ code_to_name[errors['VERIFICATION_ERR']] = 'VerificationError';
var name_to_code = {};
Object.keys(errors).forEach(function(key) {
- name_to_code[code_to_name[errors[key]]] = errors[key];
+ name_to_code[code_to_name[errors[key]]] = errors[key];
});
-
/**
* Generic exception interface.
*
* @param {number} code 16-bit error code.
- * @param {string} message An error message that describes the details of an encountered error.
+ * @param {string} message An error message that describes the details of
+ * an encountered error.
* @param {string} name An error type.
*/
var WebAPIException = function(code, message, name) {
- var code_ = 0;
- var name_ = code_to_name[code];
- var message_ = 'Unknown error';
+ var code_ = 0;
+ var name_ = code_to_name[code];
+ var message_ = 'Unknown error';
- switch (arguments.length) {
+ switch (arguments.length) {
case 1:
- var error = arguments[0];
- if (__isObject(error)) {
- code_ = error.code;
- name_ = error.name;
- message_ = error.message;
- if (__isUndefined(code_) && !__isUndefined(name_))
- code_ = name_to_code[name_];
- if (__isUndefined(name_) && !__isUndefined(code_))
- name_ = code_to_name[code_];
- } else if (__isNumber(error)) {
- // backward compatibility with crosswalk implementation
- code_ = error;
- name_ = code_to_name[code];
- message_ = name_;
- }
- break;
- case 2:
- if (__isNumber(arguments[0])) {
- code_ = arguments[0];
- if (!__isUndefined(code_to_name[code_])) {
- name_ = code_to_name[code_];
+ var error = arguments[0];
+ if (__isObject(error)) {
+ code_ = error.code;
+ name_ = error.name;
+ message_ = error.message;
+ if (__isUndefined(code_) && !__isUndefined(name_))
+ code_ = name_to_code[name_];
+ if (__isUndefined(name_) && !__isUndefined(code_))
+ name_ = code_to_name[code_];
+ } else if (__isNumber(error)) {
+ // backward compatibility with crosswalk implementation
+ code_ = error;
+ name_ = code_to_name[code];
+ message_ = name_;
}
- } else {
- name_ = String(arguments[0]);
- if (!__isUndefined(name_to_code[name_])) {
- code_ = name_to_code[name_];
+ break;
+ case 2:
+ if (__isNumber(arguments[0])) {
+ code_ = arguments[0];
+ if (!__isUndefined(code_to_name[code_])) {
+ name_ = code_to_name[code_];
+ }
+ } else {
+ name_ = String(arguments[0]);
+ if (!__isUndefined(name_to_code[name_])) {
+ code_ = name_to_code[name_];
+ }
}
- }
- message_ = String(arguments[1]);
- break;
+ message_ = String(arguments[1]);
+ break;
case 3:
- // backward compatibility with crosswalk implementation
- code_ = Number(arguments[0]);
- message_ = String(arguments[1]);
- name_ = String(arguments[2]);
- break;
+ // backward compatibility with crosswalk implementation
+ code_ = Number(arguments[0]);
+ message_ = String(arguments[1]);
+ name_ = String(arguments[2]);
+ break;
default:
- return;
- }
+ return;
+ }
- if (code_ > errors.DATA_CLONE_ERR) {
- code_ = 0;
- }
+ if (code_ > errors.DATA_CLONE_ERR) {
+ code_ = 0;
+ }
- // attributes
- Object.defineProperties(this, {
- code: {value: code_, writable: false, enumerable: true},
- name: {value: name_, writable: false, enumerable: true},
- message: {value: message_, writable: false, enumerable: true}
- });
+ // attributes
+ Object.defineProperties(this, {
+ code: { value: code_, writable: false, enumerable: true },
+ name: { value: name_, writable: false, enumerable: true },
+ message: { value: message_, writable: false, enumerable: true }
+ });
- this.constructor.prototype.__proto__ = Error.prototype;
- Error.captureStackTrace && Error.captureStackTrace(this, this.constructor); // V8-specific code
+ this.constructor.prototype.__proto__ = Error.prototype;
+ Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
+ // V8-specific code
};
WebAPIException.prototype.toString = function() {
- return this.name + ': ' + this.message;
+ return this.name + ': ' + this.message;
};
-
var error_constants = {};
for (var prop in errors) {
- error_constants[prop] = {value: errors[prop], writable: false, enumerable: true};
+ error_constants[prop] = { value: errors[prop], writable: false, enumerable: true };
}
Object.defineProperties(WebAPIException, error_constants);
Object.defineProperties(WebAPIException.prototype, error_constants);
-
// Export WebAPIException and WebAPIError into global scope.
// For compliance reasons their constructors should not be exported in tizen namespace,
// but should be available internally to allow throwing exceptions from modules.
var scope;
if (typeof window !== 'undefined') {
- scope = window;
-} else if(typeof global !== 'undefined') {
- scope = global;
+ scope = window;
+} else if (typeof global !== 'undefined') {
+ scope = global;
}
scope = scope || {};
scope.WebAPIException = WebAPIException;
@@ -1391,4 +1476,3 @@ Object.freeze(exports);
Object.freeze(exports.utils);
Object.freeze(Utils.prototype);
Object.freeze(NativeManager.prototype);
-
diff --git a/src/voicecontrol/voicecontrol_api.js b/src/voicecontrol/voicecontrol_api.js
index 6a588bfc..a0ab77a1 100755
--- a/src/voicecontrol/voicecontrol_api.js
+++ b/src/voicecontrol/voicecontrol_api.js
@@ -14,7 +14,6 @@
* limitations under the License.
*/
-
var utils_ = xwalk.utils;
var type_ = utils_.type;
var converter_ = utils_.converter;
@@ -23,219 +22,252 @@ var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
function ListenerManager(native, listenerName, handle) {
- this.listeners = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
- this.handle = handle || function (msg, listener, watchId) {};
+ this.listeners = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
+ this.handle = handle || function(msg, listener, watchId) {};
}
-ListenerManager.prototype.addListener = function (callback, nativeCall, data) {
- var id = this.nextId;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, function (msg) {
- for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId)) {
- this.handle(msg, this.listeners[watchId], watchId);
+ListenerManager.prototype.addListener = function(callback, nativeCall, data) {
+ var id = this.nextId;
+ if (!this.nativeSet) {
+ this.native.addListener(
+ this.listenerName,
+ function(msg) {
+ for (var watchId in this.listeners) {
+ if (this.listeners.hasOwnProperty(watchId)) {
+ this.handle(msg, this.listeners[watchId], watchId);
+ }
+ }
+ }.bind(this)
+ );
+ var result = this.native.callSync(nativeCall, data || {});
+ if (this.native.isFailure(result)) {
+ throw this.native.getErrorObject(result);
}
- }
- }.bind(this));
- var result = this.native.callSync(nativeCall, data || {});
- if (this.native.isFailure(result)) {
- throw this.native.getErrorObject(result);
+ this.nativeSet = true;
}
- this.nativeSet = true;
- }
- this.listeners[id] = callback;
- ++this.nextId;
+ this.listeners[id] = callback;
+ ++this.nextId;
- return id;
+ return id;
};
-ListenerManager.prototype.removeListener = function (watchId, nativeCall) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- }
+ListenerManager.prototype.removeListener = function(watchId, nativeCall) {
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ }
- if (this.nativeSet && type_.isEmptyObject(this.listeners)) {
- this.native.callSync(nativeCall);
- this.native.removeListener(this.listenerName);
- this.nativeSet = false;
- }
+ if (this.nativeSet && type_.isEmptyObject(this.listeners)) {
+ this.native.callSync(nativeCall);
+ this.native.removeListener(this.listenerName);
+ this.nativeSet = false;
+ }
};
-ListenerManager.prototype.removeAllListeners = function () {
- this.native.removeListener(this.listenerName);
- this.listeners = {};
- this.nativeSet = false;
+ListenerManager.prototype.removeAllListeners = function() {
+ this.native.removeListener(this.listenerName);
+ this.listeners = {};
+ this.nativeSet = false;
};
-var VcResultListener = new ListenerManager(native_, 'onresult', function(result, listener) {
- listener(result.event, result.list, result.results);
+var VcResultListener = new ListenerManager(native_, 'onresult', function(
+ result,
+ listener
+) {
+ listener(result.event, result.list, result.results);
});
-var VcLangListener = new ListenerManager(native_, 'onlanguagechanged', function(result, listener) {
- listener(result.previous, result.current);
+var VcLangListener = new ListenerManager(native_, 'onlanguagechanged', function(
+ result,
+ listener
+) {
+ listener(result.previous, result.current);
});
var VoiceControlResultEvent = {
- SUCCESS: 'SUCCESS',
- FAILURE: 'FAILURE'
+ SUCCESS: 'SUCCESS',
+ FAILURE: 'FAILURE'
};
var VoiceControlCommandType = {
- FOREGROUND: 'FOREGROUND'
+ FOREGROUND: 'FOREGROUND'
};
-function VoiceControlClientManager() {
-}
+function VoiceControlClientManager() {}
-VoiceControlClientManager.prototype.getVoiceControlClient = function () {
- var result = native_.callSync('VoiceControlClientManager_getVoiceControlClient', {});
+VoiceControlClientManager.prototype.getVoiceControlClient = function() {
+ var result = native_.callSync('VoiceControlClientManager_getVoiceControlClient', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return new VoiceControlClient();
+ return new VoiceControlClient();
};
-function VoiceControlClient() {
-}
+function VoiceControlClient() {}
-VoiceControlClient.prototype.getCurrentLanguage = function () {
- var result = native_.callSync('VoiceControlClient_getCurrentLanguage', {});
+VoiceControlClient.prototype.getCurrentLanguage = function() {
+ var result = native_.callSync('VoiceControlClient_getCurrentLanguage', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
- return native_.getResultObject(result);
+ return native_.getResultObject(result);
};
-VoiceControlClient.prototype.setCommandList = function (list, type) {
- var args = validator_.validateArgs(arguments, [
- {name: 'list', type: types_.ARRAY, values: VoiceControlCommand},
- {name: 'type', type: types_.ENUM, values: type_.getValues(VoiceControlCommandType), optional: true, nullable: true}
- ]);
+VoiceControlClient.prototype.setCommandList = function(list, type) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'list', type: types_.ARRAY, values: VoiceControlCommand },
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(VoiceControlCommandType),
+ optional: true,
+ nullable: true
+ }
+ ]);
- if (type_.isNullOrUndefined(args.type)) {
- args.type = VoiceControlCommandType.FOREGROUND;
- }
+ if (type_.isNullOrUndefined(args.type)) {
+ args.type = VoiceControlCommandType.FOREGROUND;
+ }
- var data = {
- list: args.list,
- type: args.type
- };
+ var data = {
+ list: args.list,
+ type: args.type
+ };
- var result = native_.callSync('VoiceControlClient_setCommandList', data);
+ var result = native_.callSync('VoiceControlClient_setCommandList', data);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
-VoiceControlClient.prototype.unsetCommandList = function (type) {
- var args = validator_.validateArgs(arguments, [
- {name: 'type', type: types_.ENUM, values: type_.getValues(VoiceControlCommandType), optional: true, nullable: true}
- ]);
+VoiceControlClient.prototype.unsetCommandList = function(type) {
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'type',
+ type: types_.ENUM,
+ values: type_.getValues(VoiceControlCommandType),
+ optional: true,
+ nullable: true
+ }
+ ]);
- if (type_.isNullOrUndefined(args.type)) {
- args.type = VoiceControlCommandType.FOREGROUND;
- }
+ if (type_.isNullOrUndefined(args.type)) {
+ args.type = VoiceControlCommandType.FOREGROUND;
+ }
- var result = native_.callSync('VoiceControlClient_unsetCommandList', {type: args.type});
+ var result = native_.callSync('VoiceControlClient_unsetCommandList', {
+ type: args.type
+ });
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
};
-VoiceControlClient.prototype.addResultListener = function (listener) {
- var args = validator_.validateArgs(arguments, [
- {name: 'listener', type: types_.FUNCTION}
- ]);
+VoiceControlClient.prototype.addResultListener = function(listener) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'listener', type: types_.FUNCTION }
+ ]);
- return VcResultListener.addListener(args.listener, 'VoiceControlClient_addResultListener');
+ return VcResultListener.addListener(
+ args.listener,
+ 'VoiceControlClient_addResultListener'
+ );
};
-VoiceControlClient.prototype.removeResultListener = function (id) {
- if (!type_.isNumber(id)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Cannot convert id to int.');
- }
+VoiceControlClient.prototype.removeResultListener = function(id) {
+ if (!type_.isNumber(id)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert id to int.'
+ );
+ }
- var args = validator_.validateArgs(arguments, [
- {name: 'id', type: types_.LONG}
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'id', type: types_.LONG }]);
- VcResultListener.removeListener(args.id, 'VoiceControlClient_removeResultListener');
+ VcResultListener.removeListener(args.id, 'VoiceControlClient_removeResultListener');
};
-VoiceControlClient.prototype.addLanguageChangeListener = function (listener) {
- var args = validator_.validateArgs(arguments, [
- {name: 'listener', type: types_.FUNCTION}
- ]);
+VoiceControlClient.prototype.addLanguageChangeListener = function(listener) {
+ var args = validator_.validateArgs(arguments, [
+ { name: 'listener', type: types_.FUNCTION }
+ ]);
- return VcLangListener.addListener(args.listener, 'VoiceControlClient_addLanguageChangeListener');
+ return VcLangListener.addListener(
+ args.listener,
+ 'VoiceControlClient_addLanguageChangeListener'
+ );
};
-VoiceControlClient.prototype.removeLanguageChangeListener = function (id) {
- if (!type_.isNumber(id)) {
- throw new WebAPIException(WebAPIException.TYPE_MISMATCH_ERR, 'Cannot convert id to int.');
- }
+VoiceControlClient.prototype.removeLanguageChangeListener = function(id) {
+ if (!type_.isNumber(id)) {
+ throw new WebAPIException(
+ WebAPIException.TYPE_MISMATCH_ERR,
+ 'Cannot convert id to int.'
+ );
+ }
- var args = validator_.validateArgs(arguments, [
- {name: 'id', type: types_.LONG}
- ]);
+ var args = validator_.validateArgs(arguments, [{ name: 'id', type: types_.LONG }]);
- VcLangListener.removeListener(args.id, 'VoiceControlClient_removeLanguageChangeListener');
+ VcLangListener.removeListener(
+ args.id,
+ 'VoiceControlClient_removeLanguageChangeListener'
+ );
};
-VoiceControlClient.prototype.release = function () {
- var result = native_.callSync('VoiceControlClient_release', {});
+VoiceControlClient.prototype.release = function() {
+ var result = native_.callSync('VoiceControlClient_release', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
- VcLangListener.removeAllListeners();
- VcResultListener.removeAllListeners();
+ if (native_.isFailure(result)) {
+ throw native_.getErrorObject(result);
+ }
+ VcLangListener.removeAllListeners();
+ VcResultListener.removeAllListeners();
};
// Constructor of VoiceControlCommand
function VoiceControlCommand(command, type) {
- validator_.isConstructorCall(this, VoiceControlCommand);
+ validator_.isConstructorCall(this, VoiceControlCommand);
- var _command = command;
- var _type = type;
+ var _command = command;
+ var _type = type;
- if (type_.isNullOrUndefined(_type)) {
- _type = VoiceControlCommandType.FOREGROUND;
- }
+ if (type_.isNullOrUndefined(_type)) {
+ _type = VoiceControlCommandType.FOREGROUND;
+ }
- Object.defineProperties(this,
- {
- command: {
- enumerable: true,
- get: function () {
- return _command;
- },
- set: function (value) {
- _command = value;
- }
- },
- type: {
- enumerable: true,
- get: function () {
- return _type;
+ Object.defineProperties(this, {
+ command: {
+ enumerable: true,
+ get: function() {
+ return _command;
+ },
+ set: function(value) {
+ _command = value;
+ }
},
- set: function (value) {
- if (type_.arrayContains(type_.getValues(VoiceControlCommandType), value)) {
- _type = value;
- }
+ type: {
+ enumerable: true,
+ get: function() {
+ return _type;
+ },
+ set: function(value) {
+ if (
+ type_.arrayContains(type_.getValues(VoiceControlCommandType), value)
+ ) {
+ _type = value;
+ }
+ }
}
- }
});
}
diff --git a/src/websetting/websetting_api.js b/src/websetting/websetting_api.js
index 017c1735..c1c9a1e3 100644
--- a/src/websetting/websetting_api.js
+++ b/src/websetting/websetting_api.js
@@ -18,61 +18,61 @@ var validator_ = xwalk.utils.validator;
var native_ = new xwalk.utils.NativeManager(extension);
exports.setUserAgentString = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'userAgent',
- type: validator_.Types.STRING,
- optional: false,
- nullable: false
- },
- {
- name: 'successCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'userAgent',
+ type: validator_.Types.STRING,
+ optional: false,
+ nullable: false
+ },
+ {
+ name: 'successCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback);
- }
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback);
+ }
+ };
- native_.sendRuntimeAsyncMessage('tizen://changeUA', args.userAgent, callback);
+ native_.sendRuntimeAsyncMessage('tizen://changeUA', args.userAgent, callback);
};
exports.removeAllCookies = function() {
- var args = validator_.validateArgs(arguments, [
- {
- name: 'successCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
- },
- {
- name: 'errorCallback',
- type: validator_.Types.FUNCTION,
- optional: true,
- nullable: true
- }
- ]);
+ var args = validator_.validateArgs(arguments, [
+ {
+ name: 'successCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'errorCallback',
+ type: validator_.Types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
- var callback = function(result) {
- if (native_.isFailure(result)) {
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback);
- }
- };
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ } else {
+ native_.callIfPossible(args.successCallback);
+ }
+ };
- native_.sendRuntimeAsyncMessage('tizen://deleteAllCookies', '', callback);
+ native_.sendRuntimeAsyncMessage('tizen://deleteAllCookies', '', callback);
};
diff --git a/src/widgetservice/widgetservice_api.js b/src/widgetservice/widgetservice_api.js
index e09d3fb0..00ba1d79 100644
--- a/src/widgetservice/widgetservice_api.js
+++ b/src/widgetservice/widgetservice_api.js
@@ -21,463 +21,496 @@ var T = xwalk.utils.type;
var native = new xwalk.utils.NativeManager(extension);
var WidgetSizeType = {
- S_1x1 : '1x1',
- S_2x1 : '2x1',
- S_2x2 : '2x2',
- S_4x1 : '4x1',
- S_4x2 : '4x2',
- S_4x3 : '4x3',
- S_4x4 : '4x4',
- S_4x5 : '4x5',
- S_4x6 : '4x6',
- EASY_1x1 : 'EASY_1x1',
- EASY_3x1 : 'EASY_3x1',
- EASY_3x3 : 'EASY_3x3',
- FULL : 'FULL',
+ S_1x1: '1x1',
+ S_2x1: '2x1',
+ S_2x2: '2x2',
+ S_4x1: '4x1',
+ S_4x2: '4x2',
+ S_4x3: '4x3',
+ S_4x4: '4x4',
+ S_4x5: '4x5',
+ S_4x6: '4x6',
+ EASY_1x1: 'EASY_1x1',
+ EASY_3x1: 'EASY_3x1',
+ EASY_3x3: 'EASY_3x3',
+ FULL: 'FULL'
};
function createObjects(data, func, widget) {
- var array = [];
- var objects = native.getResultObject(data);
+ var array = [];
+ var objects = native.getResultObject(data);
- objects.forEach(function (d) {
- array.push(new func(d, widget));
- });
+ objects.forEach(function(d) {
+ array.push(new func(d, widget));
+ });
- return array;
-};
+ return array;
+}
function WidgetSize(data) {
- Object.defineProperties(this, {
- width: {
- value: data.width,
- writable: false,
- enumerable: true
- },
- height: {
- value: data.height,
- writable: false,
- enumerable: true
- },
- });
-};
+ Object.defineProperties(this, {
+ width: {
+ value: data.width,
+ writable: false,
+ enumerable: true
+ },
+ height: {
+ value: data.height,
+ writable: false,
+ enumerable: true
+ }
+ });
+}
function WidgetVariant(data) {
- Object.defineProperties(this, {
- sizeType: {
- value: data.sizeType,
- writable: false,
- enumerable: true
- },
- width: {
- value: data.width,
- writable: false,
- enumerable: true
- },
- height: {
- value: data.height,
- writable: false,
- enumerable: true
- },
- previewImagePath: {
- value: data.previewImagePath,
- writable: false,
- enumerable: true
- },
- needsMouseEvents: {
- value: data.needsMouseEvents,
- writable: false,
- enumerable: true
- },
- needsTouchEffect: {
- value: data.needsTouchEffect,
- writable: false,
- enumerable: true
- },
- needsFrame: {
- value: data.needsFrame,
- writable: false,
- enumerable: true
- },
- });
-};
+ Object.defineProperties(this, {
+ sizeType: {
+ value: data.sizeType,
+ writable: false,
+ enumerable: true
+ },
+ width: {
+ value: data.width,
+ writable: false,
+ enumerable: true
+ },
+ height: {
+ value: data.height,
+ writable: false,
+ enumerable: true
+ },
+ previewImagePath: {
+ value: data.previewImagePath,
+ writable: false,
+ enumerable: true
+ },
+ needsMouseEvents: {
+ value: data.needsMouseEvents,
+ writable: false,
+ enumerable: true
+ },
+ needsTouchEffect: {
+ value: data.needsTouchEffect,
+ writable: false,
+ enumerable: true
+ },
+ needsFrame: {
+ value: data.needsFrame,
+ writable: false,
+ enumerable: true
+ }
+ });
+}
function WidgetInstance(data, widget) {
- Object.defineProperties(this, {
- widget: {
- value: widget,
- writable: false,
- enumerable: true
- },
- id: {
- value: data.id,
- writable: false,
- enumerable: true
- },
- });
-};
+ Object.defineProperties(this, {
+ widget: {
+ value: widget,
+ writable: false,
+ enumerable: true
+ },
+ id: {
+ value: data.id,
+ writable: false,
+ enumerable: true
+ }
+ });
+}
WidgetInstance.prototype.changeUpdatePeriod = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'seconds',
- type : types.DOUBLE,
- }]);
-
- var callArgs = {};
- callArgs.widgetId = this.widget.id;
- callArgs.instanceId = this.id;
- callArgs.seconds = args.seconds;
-
- var ret = native.callSync('WidgetInstance_changeUpdatePeriod', callArgs);
-
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'seconds',
+ type: types.DOUBLE
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.widgetId = this.widget.id;
+ callArgs.instanceId = this.id;
+ callArgs.seconds = args.seconds;
+
+ var ret = native.callSync('WidgetInstance_changeUpdatePeriod', callArgs);
+
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
};
WidgetInstance.prototype.sendContent = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'data',
- type: types.DICTIONARY,
- }, {
- name : 'updateIfPaused',
- type : types.BOOLEAN,
- }]);
-
- var callArgs = {};
- callArgs.widgetId = this.widget.id;
- callArgs.instanceId = this.id;
- callArgs.data = args.data;
- callArgs.updateIfPaused = args.updateIfPaused;
-
- var ret = native.callSync('WidgetInstance_sendContent', callArgs);
-
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'data',
+ type: types.DICTIONARY
+ },
+ {
+ name: 'updateIfPaused',
+ type: types.BOOLEAN
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.widgetId = this.widget.id;
+ callArgs.instanceId = this.id;
+ callArgs.data = args.data;
+ callArgs.updateIfPaused = args.updateIfPaused;
+
+ var ret = native.callSync('WidgetInstance_sendContent', callArgs);
+
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ }
};
WidgetInstance.prototype.getContent = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'successCallback',
- type : types.FUNCTION,
- }, {
- name : 'errorCallback',
- type : types.FUNCTION,
- }]);
-
- var callArgs = {};
- callArgs.widgetId = this.widget.id;
- callArgs.instanceId = this.id;
-
- var callback = function(result) {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.widgetId = this.widget.id;
+ callArgs.instanceId = this.id;
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ args.errorCallback(native.getErrorObject(result));
+ } else {
+ args.successCallback(native.getResultObject(result));
+ }
+ };
+
+ var result = native.call('WidgetInstance_getContent', callArgs, callback);
if (native.isFailure(result)) {
- args.errorCallback(native.getErrorObject(result));
- } else {
- args.successCallback(native.getResultObject(result));
+ throw native.getErrorObject(result);
}
- };
-
- var result = native.call('WidgetInstance_getContent', callArgs, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
};
function Widget(data) {
- Object.defineProperties(this, {
- id: {
- value: data.id,
- writable: false,
- enumerable: true
- },
- applicationId: {
- value: data.applicationId,
- writable: false,
- enumerable: true
- },
- setupApplicationId: {
- value: data.setupApplicationId ? data.setupApplicationId : null,
- writable: false,
- enumerable: true
- },
- packageId: {
- value: data.packageId,
- writable: false,
- enumerable: true
- },
- noDisplay: {
- value: data.noDisplay,
- writable: false,
- enumerable: true
- },
- });
-};
+ Object.defineProperties(this, {
+ id: {
+ value: data.id,
+ writable: false,
+ enumerable: true
+ },
+ applicationId: {
+ value: data.applicationId,
+ writable: false,
+ enumerable: true
+ },
+ setupApplicationId: {
+ value: data.setupApplicationId ? data.setupApplicationId : null,
+ writable: false,
+ enumerable: true
+ },
+ packageId: {
+ value: data.packageId,
+ writable: false,
+ enumerable: true
+ },
+ noDisplay: {
+ value: data.noDisplay,
+ writable: false,
+ enumerable: true
+ }
+ });
+}
Widget.prototype.getName = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'locale',
- type : types.STRING,
- optional : true,
- nullable : true
- }]);
-
- var callArgs = {};
- callArgs.widgetId = this.id;
-
- if (args.locale) {
- callArgs.locale = args.locale;
- }
-
- var ret = native.callSync('Widget_getName', callArgs);
-
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- } else {
- return native.getResultObject(ret);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'locale',
+ type: types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.widgetId = this.id;
+
+ if (args.locale) {
+ callArgs.locale = args.locale;
+ }
+
+ var ret = native.callSync('Widget_getName', callArgs);
+
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ } else {
+ return native.getResultObject(ret);
+ }
};
Widget.prototype.getInstances = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'successCallback',
- type : types.FUNCTION,
- }, {
- name : 'errorCallback',
- type : types.FUNCTION,
- optional : true,
- nullable : true
- }]);
-
- var callback = function(result) {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var instances = createObjects(result, WidgetInstance, this);
+ args.successCallback(instances);
+ }
+ }.bind(this);
+
+ var callArgs = {};
+ callArgs.widgetId = this.id;
+
+ var result = native.call('Widget_getInstances', callArgs, callback);
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var instances = createObjects(result, WidgetInstance, this);
- args.successCallback(instances);
+ throw native.getErrorObject(result);
}
- }.bind(this);
-
- var callArgs = {};
- callArgs.widgetId = this.id;
-
- var result = native.call('Widget_getInstances', callArgs, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
};
Widget.prototype.getVariant = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'sizeType',
- type: types.ENUM,
- values: T.getValues(WidgetSizeType)
- }]);
-
- var callArgs = {};
- callArgs.widgetId = this.id;
- callArgs.sizeType = args.sizeType;
-
- var ret = native.callSync('Widget_getVariant', callArgs);
-
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- } else {
- return new WidgetVariant(native.getResultObject(ret));
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'sizeType',
+ type: types.ENUM,
+ values: T.getValues(WidgetSizeType)
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.widgetId = this.id;
+ callArgs.sizeType = args.sizeType;
+
+ var ret = native.callSync('Widget_getVariant', callArgs);
+
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ } else {
+ return new WidgetVariant(native.getResultObject(ret));
+ }
};
Widget.prototype.getVariants = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'successCallback',
- type : types.FUNCTION,
- }, {
- name : 'errorCallback',
- type : types.FUNCTION,
- optional : true,
- nullable : true
- }]);
-
- var callback = function(result) {
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var variants = createObjects(result, WidgetVariant);
+ args.successCallback(variants);
+ }
+ };
+
+ var callArgs = {};
+ callArgs.widgetId = this.id;
+
+ var result = native.call('Widget_getVariants', callArgs, callback);
if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var variants = createObjects(result, WidgetVariant);
- args.successCallback(variants);
+ throw native.getErrorObject(result);
}
- };
-
- var callArgs = {};
- callArgs.widgetId = this.id;
-
- var result = native.call('Widget_getVariants', callArgs, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
};
function ListenerManager(native, listenerName) {
- this.listeners = {};
- this.nextId = 1;
- this.nativeSet = false;
- this.native = native;
- this.listenerName = listenerName;
-};
+ this.listeners = {};
+ this.nextId = 1;
+ this.nativeSet = false;
+ this.native = native;
+ this.listenerName = listenerName;
+}
ListenerManager.prototype.onListenerCalled = function(msg) {
- for (var watchId in this.listeners) {
- if (this.listeners.hasOwnProperty(watchId) ) {
- this.listeners[watchId](this.native.getResultObject(msg));
+ for (var watchId in this.listeners) {
+ if (this.listeners.hasOwnProperty(watchId)) {
+ this.listeners[watchId](this.native.getResultObject(msg));
+ }
}
- }
};
ListenerManager.prototype.addListener = function(callback) {
- var id = this.nextId;
- if (!this.nativeSet) {
- this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
- this.nativeSet = true;
- }
- this.listeners[id] = callback;
- ++this.nextId;
- return id;
+ var id = this.nextId;
+ if (!this.nativeSet) {
+ this.native.addListener(this.listenerName, this.onListenerCalled.bind(this));
+ this.nativeSet = true;
+ }
+ this.listeners[id] = callback;
+ ++this.nextId;
+ return id;
};
ListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- }
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ }
};
var WIDGET_STATE_CHANGE_LISTENER = 'WidgetStateChangeCallback';
var widgetStateChangeListener = new ListenerManager(native, WIDGET_STATE_CHANGE_LISTENER);
Widget.prototype.addStateChangeListener = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'eventCallback',
- type : types.FUNCTION,
- }]);
-
- var result = native.callSync('Widget_addStateChangeListener', {widgetId : this.id});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
-
- var func = function(msg) {
- if (msg.widgetId === this.id) {
- args.eventCallback(new WidgetInstance(msg, this), msg.event);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'eventCallback',
+ type: types.FUNCTION
+ }
+ ]);
+
+ var result = native.callSync('Widget_addStateChangeListener', { widgetId: this.id });
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
}
- }.bind(this);
- return widgetStateChangeListener.addListener(func);
+ var func = function(msg) {
+ if (msg.widgetId === this.id) {
+ args.eventCallback(new WidgetInstance(msg, this), msg.event);
+ }
+ }.bind(this);
+
+ return widgetStateChangeListener.addListener(func);
};
Widget.prototype.removeStateChangeListener = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'watchId',
- type : types.LONG,
- }]);
-
- widgetStateChangeListener.removeListener(args.watchId);
-
- var result = native.callSync('Widget_removeStateChangeListener', {widgetId : this.id});
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'watchId',
+ type: types.LONG
+ }
+ ]);
+
+ widgetStateChangeListener.removeListener(args.watchId);
+
+ var result = native.callSync('Widget_removeStateChangeListener', {
+ widgetId: this.id
+ });
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
-function WidgetServiceManager() {
-};
+function WidgetServiceManager() {}
WidgetServiceManager.prototype.getWidget = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'widgetId',
- type : types.STRING,
- }]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'widgetId',
+ type: types.STRING
+ }
+ ]);
- var callArgs = {};
- callArgs.widgetId = args.widgetId;
+ var callArgs = {};
+ callArgs.widgetId = args.widgetId;
- var ret = native.callSync('WidgetServiceManager_getWidget', callArgs);
+ var ret = native.callSync('WidgetServiceManager_getWidget', callArgs);
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- } else {
- return new Widget(native.getResultObject(ret));
- }
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ } else {
+ return new Widget(native.getResultObject(ret));
+ }
};
WidgetServiceManager.prototype.getWidgets = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'successCallback',
- type : types.FUNCTION,
- }, {
- name : 'errorCallback',
- type : types.FUNCTION,
- optional : true,
- nullable : true
- }, {
- name : 'packageId',
- type : types.STRING,
- optional : true,
- nullable : true
- }]);
-
- var callback = function(result) {
- if (native.isFailure(result)) {
- native.callIfPossible(args.errorCallback, native.getErrorObject(result));
- } else {
- var widgets = createObjects(result, Widget);
- args.successCallback(widgets);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'successCallback',
+ type: types.FUNCTION
+ },
+ {
+ name: 'errorCallback',
+ type: types.FUNCTION,
+ optional: true,
+ nullable: true
+ },
+ {
+ name: 'packageId',
+ type: types.STRING,
+ optional: true,
+ nullable: true
+ }
+ ]);
+
+ var callback = function(result) {
+ if (native.isFailure(result)) {
+ native.callIfPossible(args.errorCallback, native.getErrorObject(result));
+ } else {
+ var widgets = createObjects(result, Widget);
+ args.successCallback(widgets);
+ }
+ };
+
+ var callArgs = {};
+ if (args.packageId) {
+ callArgs.packageId = args.packageId;
}
- };
-
- var callArgs = {};
- if (args.packageId) {
- callArgs.packageId = args.packageId;
- }
- var result = native.call('WidgetServiceManager_getWidgets', callArgs, callback);
- if (native.isFailure(result)) {
- throw native.getErrorObject(result);
- }
+ var result = native.call('WidgetServiceManager_getWidgets', callArgs, callback);
+ if (native.isFailure(result)) {
+ throw native.getErrorObject(result);
+ }
};
WidgetServiceManager.prototype.getPrimaryWidgetId = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'id',
- type : types.STRING,
- }]);
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'id',
+ type: types.STRING
+ }
+ ]);
- var callArgs = {};
- callArgs.id = args.id;
+ var callArgs = {};
+ callArgs.id = args.id;
- var ret = native.callSync('WidgetServiceManager_getPrimaryWidgetId', callArgs);
+ var ret = native.callSync('WidgetServiceManager_getPrimaryWidgetId', callArgs);
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- } else {
- return native.getResultObject(ret);
- }
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ } else {
+ return native.getResultObject(ret);
+ }
};
WidgetServiceManager.prototype.getSize = function() {
- var args = validator.validateMethod(arguments, [{
- name : 'sizeType',
- type: types.ENUM,
- values: T.getValues(WidgetSizeType)
- }]);
-
- var callArgs = {};
- callArgs.sizeType = args.sizeType;
-
- var ret = native.callSync('WidgetServiceManager_getSize', callArgs);
-
- if (native.isFailure(ret)) {
- throw native.getErrorObject(ret);
- } else {
- return new WidgetSize(native.getResultObject(ret));
- }
+ var args = validator.validateMethod(arguments, [
+ {
+ name: 'sizeType',
+ type: types.ENUM,
+ values: T.getValues(WidgetSizeType)
+ }
+ ]);
+
+ var callArgs = {};
+ callArgs.sizeType = args.sizeType;
+
+ var ret = native.callSync('WidgetServiceManager_getSize', callArgs);
+
+ if (native.isFailure(ret)) {
+ throw native.getErrorObject(ret);
+ } else {
+ return new WidgetSize(native.getResultObject(ret));
+ }
};
//Exports