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
- },
++ 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: '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 };
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
- }
+ { 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
},
}
};
-
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
- }
+ { 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
},
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.'
++ ' Please consider using other constructors or other ' +
++ 'type of an alarm.'
+ );
}
}
}
},
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.'
++ '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.'
++ 'long period) is deprecated, thus period attribute ' +
++ 'should not be used.'
+ );
}
if (_edit.canEdit && v) {
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. ' +
++ '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. ' +
++ '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) {
// 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;
- //TODO: type should come from native site
+ 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 native_ = new xwalk.utils.NativeManager(extension);
var privUtils_ = xwalk.utils;
- function CommonFS() {};
+ function CommonFS() {}
CommonFS.cacheVirtualToReal = {};
+CommonFS.isCacheReady = false;
+CommonFS.listenerRegistered = false;
+
+function clearCache() {
+ CommonFS.cacheVirtualToReal = {};
+ CommonFS.isCacheReady = false;
+}
function _initializeCache() {
- try {
- var result = native_.callSync('Archive_fetchVirtualRoots', {});
+ if (CommonFS.isCacheReady) {
+ return;
+ }
+ var result = native_.callSync('Archive_fetchStorages', {});
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+ 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;
+ }
- result = native_.getResultObject(result);
- for (var i = 0; i < result.length; ++i) {
- CommonFS.cacheVirtualToReal[result[i].name] = {
- path: result[i].path
- };
+ result = native_.getResultObject(result);
+ for (var i = 0; i < result.length; ++i) {
+ CommonFS.cacheVirtualToReal[result[i].name] = {
+ path: result[i].path
+ };
+ }
+ 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
++ );
}
- } catch (e) {
- privUtils_.log('Exception while getting widget paths was thrown: ' + e);
}
}
_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];
};
CommonFS.isVirtualPath = function(aPath) {
- var root = aPath.split("/")[0];
+ var root = aPath.split('/')[0];
-
+ _initializeCache();
return this.cacheVirtualToReal[root] != undefined;
};
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.
++ * 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.
*/
/**
* 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: '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 = {
/**
* 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: '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;
}
/**
* 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: '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) {
};
/**
- * Retrieves information about ArchiveFileEntry with the specified name in ArchiveFile.
- * 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) {
};
}
-
- 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.
++ * 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;
}
});
};
- //class tizen.BluetoothLEServiceData ////////////////////////////////////////////////////
-//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 //////////////////////
++//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 //////////////////////
++//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 //////////////////////
++// class BluetoothClass //////////////////////////
var BluetoothClass = function(data) {
var services = [];
if (data) {
return BluetoothClass_hasService.apply(this, arguments);
};
- // class BluetoothSocket ////////////////////////////////////////////////////
-// class BluetoothSocket //////////////////////
++// class BluetoothSocket //////////////////////////
var _BLUETOOTH_SOCKET_STATE_CLOSED = 'CLOSED';
function BluetoothSocketListeners() {
}
};
- //class BluetoothLEDevice ////////////////////////////////////////////////////
-//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, {
_bleConnectChangeListener.removeListener(args.watchID);
};
- // class BluetoothDevice ////////////////////////////////////////////////////
-// class BluetoothDevice //////////////////////
++// class BluetoothDevice //////////////////////////
var BluetoothDevice = function(data) {
var self = this;
function _getter(field) {
}
};
- // class BluetoothServiceHandler ////////////////////////////////////////////////////
-// 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);
_bluetoothServiceListeners.removeListener(this.uuid);
};
- // class BluetoothHealthApplication ////////////////////////////////////////////////////
-// 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];
_bluetoothHealthApplicationListeners.removeListener(this._id);
};
- // class BluetoothProfileHandler ////////////////////////////////////////////////////
-// class BluetoothProfileHandler //////////////////////
++// class BluetoothProfileHandler //////////////////////////
var _BluetoothProfileType = {
- HEALTH : 'HEALTH'
+ HEALTH: 'HEALTH'
};
var BluetoothProfileHandler = function(data) {
}
};
- // class BluetoothHealthProfileHandler ////////////////////////////////////////////////////
-// class BluetoothHealthProfileHandler //////////////////////
++// class BluetoothHealthProfileHandler //////////////////////////
var BluetoothHealthProfileHandler = function(data) {
BluetoothProfileHandler.call(this, data);
};
}
};
- // class BluetoothHealthChannel ////////////////////////////////////////////////////
-// 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
* 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 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 //////////////////////
++//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() {
};
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 //////////////////////
++//class BluetoothGATTService //////////////////////////
var BluetoothGATTService = function(data, address) {
var handle_ = data.handle;
var uuid_ = data.uuid;
return d;
};
- //class BluetoothGATTCharacteristic ////////////////////////////////////////////////////
-//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() {
'BluetoothLEDevice_removeConnectStateChangeListener'
);
- //class BluetoothGATTDescriptor ////////////////////////////////////////////////////
-//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 //////////////////////
++// class BluetoothAdapter //////////////////////////
var BluetoothAdapter = function() {
function nameGetter() {
var result = native.callSync('BluetoothAdapter_getName', {});
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.'
++ '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, [
{
// 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.'
++ '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, [
{
}
};
- // class BluetoothManager ////////////////////////////////////////////////////
-// class BluetoothManager //////////////////////
++// class BluetoothManager //////////////////////////
var BluetoothManager = function() {
Object.defineProperties(this, {
- deviceMajor : {
+ deviceMajor: {
value: new BluetoothClassDeviceMajor(),
writable: false,
enumerable: true
privUtils_.log('Entered BluetoothManager.getLEAdapter()');
return BluetoothManager_getLEAdapter();
};
- // exports ///////////////////////////////////////////////////////////////////
-// exports /////////////////////////////////////
++// exports /////////////////////////////////////////
exports = new BluetoothManager();
};
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
++ // @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() {
};
var EventAvailability = {
- BUSY: 'BUSY', //default for CalendarEvent
- FREE: 'FREE',
- BUSY_UNAVAILABLE: 'BUSY_UNAVAILABLE',
- BUSY_TENTATIVE: 'BUSY_TENTATIVE'
+ BUSY: 'BUSY', //default for CalendarEvent
- FREE: 'FREE'
++ FREE: 'FREE',
++ BUSY_UNAVAILABLE: 'BUSY_UNAVAILABLE',
++ BUSY_TENTATIVE: 'BUSY_TENTATIVE'
};
var CalendarEventId = function(uid, rid) {
// 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.
- */
++ //@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() {
*/
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.
++ // 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 /////////////////////////////////////////////////////
*/
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: true,
++ 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.
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();
};
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.'
++ '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.'
++ '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) {
* 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
++ //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
++ //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
++ //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);
- }
};
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();
+ }
+
- // read only property
- SetReadOnlyProperty(returnObject, 'type', args.type);
- // read only property
- SetReadOnlyProperty(returnObject, 'providerId', args.providerId);
- // read only property
- SetReadOnlyProperty(returnObject, 'dataId', args.dataId);
++ 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() {
}
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);
- 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 (!_isValidAbsoluteURI(args.exifInfo.uri)) {
++ 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);
- }
- native_.call('ExifManager_saveExifInfo', json, callback);
++ 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);
+ }
+ };
+
- native_.call('ExifManager_getThumbnail', { uri: args.uri }, _callback);
++ 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() {
+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 args = validator_.validateArgs(arguments, [
- {
- name: 'ExifInitDict',
- type: validator_.Types.DICTIONARY,
- optional: true,
- nullable: false
- }
- ]);
-
- var uri_ = null,
++ 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;
+
- var exifInitDict = args.ExifInitDict;
- if (exifInitDict) {
- if (exifInitDict.uri === null) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Parameter "uri" is required.'
- );
- }
- }
-
+ 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) {
++ 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) {
++ 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();
};
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) }
+ ]);
- return callNative('FeedbackManager_isPatternSupported', args);
+
- 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);
- }
- callNative('FeedbackManager_play', nativeParam);
- return;
++ 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);
- }
- callNative('FeedbackManager_stop', args);
- return;
++ var result = native_.callSync('FeedbackManager_stop', args);
++ if (native_.isFailure(result)) {
++ throw native_.getErrorObject(result);
++ }
};
exports = new FeedbackManager();
var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
- var len = str.length;
- var output = new type(len);
- for (var i = 0; i < len; i++) {
- output[i] = str.charCodeAt(i);
- }
- return output;
+/*
+ * Create new array-like object of numbers: UTF-16 char codes from string.
+ * As type pass Array, Uint8Array, etc.
+ * Useful for passing data through crosswalk.
+ */
+function StringToArray(str, type) {
- 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 len = str.length;
++ var output = new type(len);
++ for (var i = 0; i < len; i++) {
++ output[i] = str.charCodeAt(i);
++ }
++ return output;
+}
+
+/*
+ * Pass array-like object of numbers (Array, Uint8Array, etc.), returns string.
+ * Each char has codepoint equal to value from array cropped with & 0xFF
+ * 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;
+}
+
function SetReadOnlyProperty(obj, n, v) {
- Object.defineProperty(obj, n, {value: v, writable: false});
- 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 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 = {
- r: 'r',
- rw: 'rw',
- w: 'w',
- a: 'a'
-};
++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';
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;
+ }
- // this line makes that '.' and '..' is supported in paths,
- // but each method handle those cases
- // and return error (see commonFS_.checkPathWithoutDots() method)
++ // 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
- };
++ 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
++ getAllStorages: getAllStorages,
++ mergeMultipleSlashes: mergeMultipleSlashes
+ };
})();
}
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() {
};
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');
++ return new RegExp(_regString + '$', 'i');
+ }
- // single '\' sign is not visible in JS string,
- // escaping % wildcard need to be done by '\\%'
++ // 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
++ // 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) {
}
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 = {
}
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);
};
--- /dev/null
-
+/*
+ * Copyright (c) 2018 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
- 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}
- });
+function FileHandle(_id, _path, _mode) {
- 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);
++ 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: '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: '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() {
- native_.callIfPossible(args.successCallback, native_.getResultObject(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 {
- };
++ 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 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 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: '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: '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 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);
++ 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_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);
++ }
+ }
- 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);
- };
+};
+
+FileHandle.prototype.writeString = function() {
- 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) {
++ 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);
+
- native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
- } else {
- native_.callIfPossible(args.successCallback, native_.getResultObject(result));
+ if (native_.isFailure(result)) {
- };
++ throw native_.getErrorObject(result);
+ }
- var result = native_.call('FileHandle_writeString', data, callback);
++ return 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);
++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);
++ }
+ }
- 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.readBlob = 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: '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 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);
++ 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 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);
++ }
+ }
- 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;
+};
+
+function blobToUint8Array(b) {
- 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 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},
- {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 }
++ ]);
++ 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 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;
- }
++ 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);
+
- 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);
++ // 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: '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: '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 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);
++ 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 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);
++ }
+ }
- 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.writeData = 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 }
++ ]);
++ 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 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);
- }
++ var encodedData = ArrayToString(args.data);
+
- 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);
- }
++ 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() {
- 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));
++ 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 result = native_.call('FileHandle_flush', data, callback);
++ var data = { id: this.id, blocking: false };
+
- // 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 callback = function(result) {
++ if (native_.isFailure(result)) {
++ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
++ } else {
++ native_.callIfPossible(args.successCallback, native_.getResultObject(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);
- }
++ 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() {
- 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));
++ 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;
+ }
- var result = native_.call('FileHandle_sync', data, callback);
++ 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));
++ }
++ };
+
- // 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_sync', data, callback);
+
- 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);
- }
++ // 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() {
- 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));
++ 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 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);
- }
++ 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_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);
++ }
+};
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
- },
- _rewrite: {
- value: mode === 'w' ? true : false,
++ _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) {
}
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() {
}
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.');
+ }
}
-/* returns array of numbers */
-function string_to_array(str) {
- var output = [];
- var len = str.length;
- for (var i = 0; i < len; i++) {
- output.push(str.charCodeAt(i));
- }
- return output;
-}
-
-/* receives array of numbers, returns string */
-function array_to_string(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;
-}
-
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
- }
++ { 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() {
};
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
- }
++ { 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 = string_to_array(native_.getResultObject(result));
++ 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) {
}
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
- }
++ { 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,
- rewrite: this._rewrite
++ 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._rewrite = false;
++ this._truncate = false;
}
FileStream.prototype.write = function() {
};
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
- array_to_string for performance */
++ 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: array_to_string(args.byteData),
- rewrite: this._rewrite
++ 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._rewrite = 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
- }
++ { name: 'base64Data', type: types_.STRING }
+ ]);
+
+ _checkClosed(this);
+ _checkWriteAccess(this._mode);
+
+ var data = {
+ location: commonFS_.toRealPath(this._file.fullPath),
+ offset: this.position,
+ data: args.base64Data,
- rewrite: this._rewrite
++ 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._rewrite = false;
++ this._truncate = false;
}
FileStream.prototype.writeBase64 = function() {
*/
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 PATH_MAX = 4096;
+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, {
- maxPathLength: { value: PATH_MAX, writable: false, enumerable: true }
++ maxNameLength: { value: limits[0], writable: false, enumerable: true },
++ maxPathLength: { value: limits[1], writable: false, enumerable: true }
+ });
}
- 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.openFile = 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: '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() {
- if (!args.has.makeParents) {
- args.makeParents = 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;
++ }
+
- 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) {
++ 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));
++ }
++ };
+
- 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_createDirectory', data, callback);
+ if (native_.isFailure(result)) {
- };
-
- var result = native_.call('FileSystemManager_createDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
++ throw native_.getErrorObject(result);
+ }
- 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)};
+};
+
+FileSystemManager.prototype.deleteFile = function() {
- 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,
++ 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
++ );
++ }
+
- var callback = function(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));
++ }
++ };
+
- 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_deleteFile', data, callback);
+ if (native_.isFailure(result)) {
- };
-
- var result = native_.call('FileSystemManager_deleteFile', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
++ throw native_.getErrorObject(result);
+ }
- 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}
- ]);
+};
+
+FileSystemManager.prototype.deleteDirectory = function() {
- if (!args.has.recursive) {
- args.recursive = 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;
++ }
+
- 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) {
++ 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));
++ }
++ };
+
- 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_deleteDirectory', data, callback);
+ if (native_.isFailure(result)) {
- };
-
- var result = native_.call('FileSystemManager_deleteDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
++ throw native_.getErrorObject(result);
+ }
- 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);
- }
+};
+
+FileSystemManager.prototype.copyFile = function() {
- 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 }
++ ]);
++
++ 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 result = native_.call('FileSystemManager_copyFile', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+
- 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 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 result = native_.call('FileSystemManager_copyDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+
- 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 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.');
+ }
- var result = native_.call('FileSystemManager_moveFile', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+
- 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));
++ 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 result = native_.call('FileSystemManager_moveDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+
- 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 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() {
- if ((-1 !== args.newName.indexOf('/')) || (-1 !== args.newName.indexOf('\x00'))) {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR, 'newName contains invalid character.');
- }
++ 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.'
++ );
++ }
+
- 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) {
++ 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));
++ }
++ };
+
- 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_rename', data, callback);
+ if (native_.isFailure(result)) {
- };
-
- var result = native_.call('FileSystemManager_rename', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
++ throw native_.getErrorObject(result);
+ }
- if (argument instanceof Date) {
- return true;
- }
- throw new WebAPIException(
- WebAPIException.TYPE_MISMATCH_ERR,
- 'Argument "' + name + '" in a filter is not of type Date.');
+};
+
+function throwIfNotDate(argument, name) {
- 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);
- }
++ 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 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 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 result = native_.call('FileSystemManager_listDirectory', data, callback);
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
+
- var args = validator_.validateArgs(arguments, [{name: 'path', type: types_.STRING}]);
++ 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() {
- // 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);
++ var args = validator_.validateArgs(arguments, [
++ { name: 'path', type: types_.STRING }
++ ]);
+
- if (!realPath) {
- throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid 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);
+
- return 'file://' + realPath;
++ if (!realPath) {
++ throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR, 'Invalid path.');
++ }
+
- 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);
- }
++ 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_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_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_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_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}]);
- 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 }
++ ]);
++ // 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;
+};
+
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,
- 'Specified virtual root does not exist.'
- )
++ 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 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() {
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_MONITOR: 'SLEEP_MONITOR',
++ SLEEP_DETECTOR: 'SLEEP_DETECTOR',
++ STRESS_MONITOR: 'STRESS_MONITOR'
};
var HumanActivityRecorderType = {
};
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) {
}
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);
}
- 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 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
++ }
++ });
++}
+
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) {
};
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
++ // if it's another call to startListener() overwrite the old one
+ native_.addListener(listenerId, listener);
}
function checkPrivilegesForMethod(method, type) {
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)
+ );
+ }
+ };
+
- GPSListener = callback;
++ 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() {
};
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);
};
- this.listeners = {};
- this.nextId = 1;
- };
+function StressMonitorListenerManager() {
-
- 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);
++ this.listeners = {};
++ this.nextId = 1;
++}
+
+StressMonitorListenerManager.prototype.onListener = function(data) {
- }
- _listener.lastStressScore = score;
++ 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;
+ }
- }
+ }
- StressMonitorListenerManager.prototype.addListener = function(ranges, listener, errorCallback) {
-
- var id = this.nextId++;
-
- this.listeners[id] = {
- ranges: ranges,
- listener: listener,
- lastStressScore: -1
- };
+};
+
- return id;
++StressMonitorListenerManager.prototype.addListener = function(
++ ranges,
++ listener,
++ errorCallback
++) {
++ var id = this.nextId++;
++
++ this.listeners[id] = {
++ ranges: ranges,
++ listener: listener,
++ lastStressScore: -1
++ };
+
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- }
++ return id;
+};
+
+StressMonitorListenerManager.prototype.removeListener = function(watchId) {
- 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);
++ if (this.listeners.hasOwnProperty(watchId)) {
++ delete this.listeners[watchId];
++ }
+};
+
+var stressMonitorListener = new StressMonitorListenerManager();
+
+HumanActivityMonitorManager.prototype.addStressMonitorChangeListener = function() {
- HumanActivityMonitorManager.prototype.removeStressMonitorChangeListener = function() {
- var args = validator_.validateMethod(arguments, [{
- name : 'watchId',
- type : types_.LONG,
- }]);
++ 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);
+};
+
- stressMonitorListener.removeListener(args.watchId);
++HumanActivityMonitorManager.prototype.removeStressMonitorChangeListener = function() {
++ var args = validator_.validateMethod(arguments, [
++ {
++ name: 'watchId',
++ type: types_.LONG
++ }
++ ]);
+
++ 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();
HumanActivitySleepMonitorData.prototype = new HumanActivityData();
HumanActivitySleepMonitorData.prototype.constructor = HumanActivitySleepMonitorData;
- SetReadOnlyProperty(this, 'status', data.status);
+function HumanActivitySleepDetectorData(data) {
- SetReadOnlyProperty(this, 'stressScore', data.stressScore);
++ SetReadOnlyProperty(this, 'status', data.status);
+}
+
+HumanActivitySleepDetectorData.prototype = new HumanActivityData();
+HumanActivitySleepDetectorData.prototype.constructor = HumanActivitySleepMonitorData;
+
+function HumanActivityStressMonitorData(data) {
- HumanActivityStressMonitorData.prototype.constructor = HumanActivityStressMonitorData
++ SetReadOnlyProperty(this, 'stressScore', data.stressScore);
+}
+
+HumanActivityStressMonitorData.prototype = new HumanActivityData();
++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) {
}
HumanActivityRecorderPressureData.prototype = new HumanActivityRecorderData();
- HumanActivityRecorderPressureData.prototype.constructor = HumanActivityRecorderPressureData;
+ // prettier-ignore
+ HumanActivityRecorderPressureData.prototype.constructor =
+ HumanActivityRecorderPressureData;
+tizen.StressMonitorDataRange = StressMonitorDataRange;
+
exports = new HumanActivityMonitorManager();
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.
++ * This class provides access to the API functionalities through the
++ * tizen.tvinputdevice interface.
* @constructor
*/
function InputDeviceManager() {
* @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.
++ * 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 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) {
}
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,
- replyId: msg.replyId,
++ 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 (msg.replyId === watchId) {
- listener(msg.data);
++ 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() {
};
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() {
};
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 nativeData = {
- command: args.command,
- data: args.data,
- name: this.name
- };
-
- var replyId = ReplyCommandListener.addListener(successCallback);
-
- nativeData.replyId = replyId;
- nativeData.listenerId = ReplyCommandListener.listenerName;
+ var callback = function(result) {
+ if (native_.isFailure(result)) {
+ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
+ return;
+ }
- args.successCallback(native_.getResultObject(result));
++ native_.callIfPossible(
++ args.successCallback,
++ native_.getResultObject(result).data
++ );
+ };
- var replyListenerId = ReplyCommandListener.addListener(callback);
- var result = native_.callSync('MediaControllerServerInfo_sendCommand', nativeData);
- native_.call('MediaControllerServerInfo_sendCommand', nativeData, callback);
++ 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) {
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+
-var JSON_ = xwalk.JSON;
var validator_ = xwalk.utils.validator;
var types_ = validator_.Types;
var type_ = xwalk.utils.type;
var callbacks = {};
var ports = [];
-extension.setMessageListener(function(json) {
- var msg = JSON_.parse(json);
- var listeners = callbacks[msg['local_port_id']];
+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;
+
- privUtils_.log('Listeners length:' + listeners.length);
-
+ 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++;
}
-var ExceptionMap = {
- UnknownError: WebAPIException.UNKNOWN_ERR,
- TypeMismatchError: WebAPIException.TYPE_MISMATCH_ERR,
- InvalidValuesError: WebAPIException.INVALID_VALUES_ERR,
- IOError: WebAPIException.IO_ERR,
- ServiceNotAvailableError: WebAPIException.SERVICE_NOT_AVAILABLE_ERR,
- SecurityError: WebAPIException.SECURITY_ERR,
- NetworkError: WebAPIException.NETWORK_ERR,
- NotSupportedError: WebAPIException.NOT_SUPPORTED_ERR,
- NotFoundError: WebAPIException.NOT_FOUND_ERR,
- InvalidAccessError: WebAPIException.INVALID_ACCESS_ERR,
- AbortError: WebAPIException.ABORT_ERR,
- QuotaExceededError: WebAPIException.QUOTA_EXCEEDED_ERR
-};
-
-function callNative(cmd, args) {
- var json = { cmd: cmd, args: args };
- var argjson = JSON_.stringify(json);
- var resultString = extension.internal.sendSyncMessage(argjson);
- var result = JSON_.parse(resultString);
-
- if (typeof result !== 'object') {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
- }
-
- if (result['status'] == 'success') {
- if (result['result']) {
- return result['result'];
- }
- return true;
- } else if (result['status'] == 'error') {
- var err = result['error'];
- if (err) {
- if (ExceptionMap[err.name]) {
- throw new WebAPIException(ExceptionMap[err.name], err.message);
- } else {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR, err.message);
- }
- }
- return false;
- }
-}
-
-function callNativeWithCallback(cmd, args, callback) {
- if (callback) {
- var id = nextCallbackId();
- args['callbackId'] = id;
- callbacks[id] = callback;
- }
-
- return callNative(cmd, args);
-}
-
-function SetReadOnlyProperty(obj, n, v) {
- Object.defineProperty(obj, n, { value: v, writable: false });
-}
-
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;
++ var localPortId; // TODO remove
+ var nativeParam = {
+ localMessagePortName: args.localMessagePortName
+ };
- var result = native_.callSync('MessagePortManager_requestTrustedLocalMessagePort', nativeParam);
- try {
- localPortId = callNative(
- 'MessagePortManager_requestLocalMessagePort',
- nativeParam
- );
- } catch (e) {
- throw e;
- }
++ 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);
- }
- var returnObject = new LocalMessagePort(args.localMessagePortName, false);
- ports[nativeParam.localMessagePortName] = localPortId;
++ 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);
- }
- try {
- var localPortId = callNative(
- 'MessagePortManager_requestTrustedLocalMessagePort',
- nativeParam
- );
- } catch (e) {
- throw e;
- }
++ var result = native_.callSync(
++ 'MessagePortManager_requestTrustedLocalMessagePort',
++ nativeParam
++ );
- var returnObject = new RemoteMessagePort(args.remoteMessagePortName, args.appId, false);
- var returnObject = new LocalMessagePort(args.localMessagePortName, true);
- ports[nativeParam.localMessagePortName] = localPortId;
++ 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
+ };
+
- try {
- var syncResult = callNative(
- 'MessagePortManager_requestRemoteMessagePort',
- nativeParam
- );
- } catch (e) {
- throw e;
++ 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
+ };
+
- try {
- var syncResult = callNative(
- 'MessagePortManager_requestTrustedRemoteMessagePort',
- nativeParam
- );
- } catch (e) {
- throw e;
++ 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) {
}
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 filtered_data = new Array(args.data.length);
- var unique_data_key = {};
- var data_length = args.data.length;
- for (var i = 0; i < data_length; i++) {
++ 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 === unique_data_key[key]) {
++ 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)) {
- filtered_data[i] = { key: key, value: value, valueType: 'stringValueType' };
++ 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'
+ );
+ }
+ }
- filtered_data[i] = {
++ 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'
+ );
+ }
- filtered_data[i] = {
++ 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'
+ );
+ }
+ }
- filtered_data[i] = {
++ filteredData[i] = {
+ key: key,
+ value: value,
+ valueType: 'byteStreamArrayValueType'
+ };
+ }
+ } else {
+ // convert any other value to string -> backward compatibility
- filtered_data[i] = {
++ filteredData[i] = {
+ key: key,
+ value: converter_.toString(value),
+ valueType: 'stringValueType'
+ };
+ }
- unique_data_key[key] = true;
++ uniqueDataKey[key] = true;
+ }
+
+ var nativeParam = {
+ appId: this.appId,
+ messagePortName: this.messagePortName,
- data: filtered_data,
++ data: filteredData,
+ trusted: this.isTrusted,
- local_port_id: args.localMessagePort
++ localPortId: args.localMessagePort
+ ? ports[args.localMessagePort.messagePortName]
+ : -1
+ };
+
- var syncResult = callNative('RemoteMessagePort_sendMessage', nativeParam);
++ 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();
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;
- }
++ 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_) {
++ 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_) {
++ 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)) {
};
// 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;
- }
++ 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 = {};
};
// 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;
- }
++ 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.
++ * @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)) {
//////////////////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.'
++ '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 callbackId = 0;
var callbacks = {};
-var infoEventListenerId = -1;
-
-function invokeListener(result) {
- if (result.listener === 'infoEvent') {
- var listener = callbacks[infoEventListenerId];
- listener(result);
+var listener;
+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);
+ }
}
-extension.setMessageListener(function(json) {
- var result = JSON_.parse(json);
-
- if (result.hasOwnProperty('listener')) {
- setTimeout(function() {
- invokeListener(result);
- }, 0);
- } else {
- var callback = callbacks[result['callbackId']];
- setTimeout(function() {
- callback(result);
- }, 0);
- }
-});
-
-function nextCallbackId() {
- return callbackId++;
-}
-
-function callNative(cmd, args) {
- var json = { cmd: cmd, args: args };
- var argjson = JSON_.stringify(json);
- var resultString = extension.internal.sendSyncMessage(argjson);
- var result = JSON_.parse(resultString);
-
- if (typeof result !== 'object') {
- throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
- }
-
- if (result['status'] == 'success') {
- if (undefined !== result['result']) {
- return result['result'];
- }
- return true;
- } else if (result['status'] == 'error') {
+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) {
- throw new WebAPIException(err);
++ callbacks[result['progressCallbackId']].errorCallback(
++ new WebAPIException(err)
++ );
++ delete callbacks[result['progressCallbackId']];
++ native_.removeListener(
++ PACKAGE_PROGRESS_LISTENER_ID + result['progressCallbackId']
++ );
+ }
- return false;
}
- }
}
-function callNativeWithCallback(cmd, args, callback) {
- if (callback) {
- var id = nextCallbackId();
- args['callbackId'] = id;
- callbacks[id] = callback;
- }
-
- return callNative(cmd, args);
+function nextCallbackId() {
- return callbackId++;
++ return callbackId++;
}
function SetReadOnlyProperty(obj, n, v) {
}
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) {
- try {
- totalSize = callNative('PackageManager_getTotalSize', {
- id: this.id
- });
- } catch (e) {
++ 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) {
- try {
- dataSize = callNative('PackageManager_getDataSize', { id: this.id });
- } catch (e) {
++ 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() {
}
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
++ packageFileURI: args.packageFileURI,
++ progressCallbackId: progressCallbackId
+ };
+
- try {
- var syncResult = callNativeWithCallback(
- 'PackageManager_install',
- nativeParam,
- function(result) {
- if (result.status == 'progress') {
- if (args.progressCallback.onprogress) {
- args.progressCallback.onprogress(result.id, result.progress);
- }
- } else if (result.status == 'complete') {
- if (args.progressCallback.oncomplete) {
- args.progressCallback.oncomplete(result.id);
- }
- } else if (result.status == 'error') {
- var err = result['error'];
- if (err) {
- args.errorCallback(new WebAPIException(err));
- return;
- }
- }
++ 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 (result.status == 'complete' || result.status == 'error') {
- delete callbacks[result['callbackId']];
- }
- }
- );
- } catch (e) {
- throw e;
+ 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) {
};
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 nativeParam = {
- id: args.id
- };
++ var progressCallbackId = nextCallbackId();
++ callbacks[progressCallbackId] = args;
- var nativeParam = {'id': args.id, 'progressCallbackId': progressCallbackId};
- try {
- var syncResult = callNativeWithCallback(
- 'PackageManager_uninstall',
- nativeParam,
- function(result) {
- if (result.status == 'progress') {
- if (args.progressCallback.onprogress) {
- args.progressCallback.onprogress(result.id, result.progress);
- }
- } else if (result.status == 'complete') {
- if (args.progressCallback.oncomplete) {
- args.progressCallback.oncomplete(result.id);
- }
- } else if (result.status == 'error') {
- var err = result['error'];
- if (err) {
- args.errorCallback(new WebAPIException(err));
- return;
- }
- }
++ var nativeParam = { id: args.id, progressCallbackId: progressCallbackId };
+
- if (result.status == 'complete' || result.status == 'error') {
- delete callbacks[result['callbackId']];
- }
- }
- );
- } catch (e) {
- throw e;
++ 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) {
};
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 nativeParam = {};
-
- try {
- var syncMsg = callNativeWithCallback(
- 'PackageManager_getPackagesInfo',
- nativeParam,
- function(result) {
- if (result.status == 'success') {
- for (var i = 0; i < result.informationArray.length; i++) {
- result.informationArray[i] = new PackageInformation(
- result.informationArray[i]
- );
- }
- args.successCallback(result.informationArray);
- } else if (result.status == 'error') {
- var err = result['error'];
- if (err) {
- args.errorCallback(new WebAPIException(err));
- return;
- }
- }
-
- delete callbacks[result['callbackId']];
++ 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]
++ );
+ }
- );
- } catch (e) {
- throw e;
++ 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;
+ }
+
- try {
- var syncResult = callNative('PackageManager_getPackageInfo', nativeParam);
- return new PackageInformation(syncResult);
- } catch (e) {
- throw e;
++ 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 nativeParam = {};
++ var result = native_.callSync('PackageManager_setPackageInfoEventListener', {});
+
- try {
- var syncResult = callNativeWithCallback(
- 'PackageManager_setPackageInfoEventListener',
- nativeParam,
- function(result) {
- if (result.status == 'installed') {
- args.eventCallback.oninstalled(new PackageInformation(result.info));
- } else if (result.status == 'updated') {
- args.eventCallback.onupdated(new PackageInformation(result.info));
- } else if (result.status == 'uninstalled') {
- args.eventCallback.onuninstalled(result.id);
- }
- }
- );
++ if (native_.isFailure(result)) {
++ throw native_.getErrorObject(result);
++ }
+
- if (infoEventListenerId === -1) {
- infoEventListenerId = nativeParam.callbackId;
- } else {
- delete callbacks[infoEventListenerId];
- infoEventListenerId = nativeParam.callbackId;
- }
- } catch (e) {
- throw e;
++ 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);
- try {
- var syncResult = callNative(
- 'PackageManager_unsetPackageInfoEventListener',
- nativeParam
- );
- if (syncResult === true) {
- delete callbacks[infoEventListenerId];
- infoEventListenerId = -1;
- }
- } catch (e) {
- throw e;
++ 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();
* 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.'
++ '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);
+ }
};
/**
* 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.'
++ '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.'
++ '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();
+ exports = new PowerManager();
var types_ = validator_.Types;
var native_ = new xwalk.utils.NativeManager(extension);
- function PPMManager() {
- }
+ function PPMManager() {}
- privilege : {value: privilege, writable: false},
- result : {value: result_, writable: false}
+function RequestStatus(privilege, result_) {
+ Object.defineProperties(this, {
- };
++ 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);
};
- var args = validator_.validateArgs(arguments, [
- { name: 'privileges', type: types_.ARRAY, values: types_.STRING }
- ]);
+PPMManager.prototype.checkPermissions = function() {
- var callArgs = {
- privileges: args.privileges
- };
++ var args = validator_.validateArgs(arguments, [
++ { name: 'privileges', type: types_.ARRAY, values: types_.STRING }
++ ]);
+
- var result = native_.callSync('PPMManager_checkPermissions', callArgs);
++ var callArgs = {
++ privileges: args.privileges
++ };
+
- var data = [];
++ var result = native_.callSync('PPMManager_checkPermissions', callArgs);
+
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- } else {
- var obj = native_.getResultObject(result);
++ var data = [];
+
- obj.forEach(function (o) {
- data.push({'privilege':o.privilege, 'type':o.type});
- });
- }
++ if (native_.isFailure(result)) {
++ throw native_.getErrorObject(result);
++ } else {
++ var obj = native_.getResultObject(result);
+
- return data;
++ obj.forEach(function(o) {
++ data.push({ privilege: o.privilege, type: o.type });
++ });
++ }
+
++ return data;
+};
+
PPMManager.prototype.requestPermission = function() {
var args = validator_.validateArgs(arguments, [
{ name: 'privilege', type: types_.STRING },
}
};
- 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);
+PPMManager.prototype.requestPermissions = function() {
- obj.forEach(function (o) {
- data.push(new RequestStatus(o.privilege, o.result));
- });
- args.successCallback(data);
- }
- };
++ 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 callArgs = {
- privileges: args.privileges
- };
++ var callback = function(result) {
++ if (native_.isFailure(result)) {
++ native_.callIfPossible(args.errorCallback, native_.getErrorObject(result));
++ } else {
++ var data = [];
++ var obj = native_.getResultObject(result);
+
- var result = native_.call('PPMManager_requestPermissions', callArgs, callback);
++ obj.forEach(function(o) {
++ data.push(new RequestStatus(o.privilege, o.result));
++ });
++ args.successCallback(data);
++ }
++ };
+
- if (native_.isFailure(result)) {
- throw native_.getErrorObject(result);
- }
++ var callArgs = {
++ privileges: args.privileges
++ };
++
++ var result = native_.call('PPMManager_requestPermissions', callArgs, callback);
+
++ if (native_.isFailure(result)) {
++ throw native_.getErrorObject(result);
++ }
+};
+
// Exports
- exports = new PPMManager();
+ exports = new PPMManager();
}
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.'
++ '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() {
};
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.'
++ '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() {
};
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.'
++ '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) {
};
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.'
++ '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() {
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
- }
- ]);
+
-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)
- );
--};
++ _sensorListeners[this.sensorType].getData(
++ args.successCallback,
++ errorWrapper.bind(args)
++ );
++ };
//// LinearAccelerationSensor
var LinearAccelerationSensor = function(data) {
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/////////////////////////////
++////////////////////// Sensor Data classes//////////////////////////
////Base SensorData class
- var SensorData = function () {
- };
+ var SensorData = function() {};
//// SensorLightData
var SensorLightData = function(data) {
};
ListenerManager.prototype.removeListener = function(watchId) {
- if (!this.listeners.hasOwnProperty(watchId)) {
- return;
- }
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- } else {
- throw new WebAPIException(
- WebAPIException.INVALID_VALUES_ERR,
- 'Listener with id: ' + watchId + ' does not exist.'
- );
++ 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 _soundModeChangeListener;
+var _currentSoundMode;
+var _isFirstSoundModeChange = true;
+// Native side sometimes fires sound change callback two times in a row
+// with different values of sound mode. One of this value is only transitional
+// 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);
- }
- native_.callIfPossible(_soundModeChangeListener, native_.getResultObject(result));
++ _currentSoundMode = result;
++ if (_isFirstSoundModeChange) {
++ _isFirstSoundModeChange = false;
++ setTimeout(function() {
++ _isFirstSoundModeChange = true;
++ native_.callIfPossible(
++ _soundModeChangeListener,
++ native_.getResultObject(_currentSoundMode)
++ );
++ }, 100);
++ }
}
SoundManager.prototype.setSoundModeChangeListener = function(callback) {
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 ' +
++ 'DEPRECATION WARNING: SystemInfoStorageUnit.isRemoveable is is ' +
+ 'deprecated and will be removed from next release. ' +
+ 'Use SystemInfoStorageUnit.isRemovable instead.'
+ );
return _isRemovable;
},
set: function() {}
/*
* 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.highThreshold) &&
++ * (propObj.level <= listener.lowThreshold ||
++ * propObj.level >= listener.highThreshold)) ||
+ * (!T_.isUndefined(listener.lowThreshold) &&
- * (propObj.level <= listener.lowThreshold)) ||
++ * (propObj.level <= listener.lowThreshold)) ||
+ * (!T_.isUndefined(listener.highThreshold) &&
- * (propObj.level >= listener.highThreshold))
++ * (propObj.level >= listener.highThreshold))
*
* but it can be optimized like this:
*/
}
function _getLocalTimezoneOffset(utcTimestamp) {
- return -1 * (new Date(utcTimestamp).getTimezoneOffset()) * 60 * 1000; // cast to milliseconds
- // casting to milliseconds
++ // cast to milliseconds
+ return -1 * new Date(utcTimestamp).getTimezoneOffset() * 60 * 1000;
}
function _constructTZDate(obj, privateTZDate) {
//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
++ //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)
++ //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
++ //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() {
};
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.'
++ '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() {
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-/* eslint-disable */
++/*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.web.apireference/org.tizen.mobile.web.device.apireference/index.html
-/* eslint-enable */
++//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.
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.
++ * This class provides access to the API functionalities through
++ * the tizen.tvinputdevice interface.
* @constructor
*/
function TVInputDeviceManager() {
* @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.
++ * 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) {
};
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 v;
+ var t;
- if (_type.isArray(val)) {
- v = val;
- } else {
- v = [val];
- }
+
+ 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) {
- for (var j = 0; j < v.length; ++j) {
- match = match || v[j] instanceof t[i];
++ if (val instanceof t[i]) {
++ return val;
+ }
}
- }
- if (match) {
- 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) {
* - 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
++ * 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
* {
* 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
++ * values: Validator.Types.DOUBLE // converts elements, only primitive types are
++ * supported
* }
* ]
* @code
* @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.
++ // 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.
*/
/////////////////////////////////////////////////////////////////////////////
/** @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) {
// 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.
++// 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.
* @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;
- // V8-specific code
+ Error.captureStackTrace && Error.captureStackTrace(this, this.constructor);
++ // V8-specific code
};
WebAPIException.prototype.toString = function() {
};
ListenerManager.prototype.removeListener = function(watchId) {
- if (this.listeners.hasOwnProperty(watchId)) {
- delete this.listeners[watchId];
- }
- if (this.listeners[watchId] === null || this.listeners[watchId] === undefined) {
- throw new WebAPIException(0, 'Watch id not found.', 'NotFoundError');
- }
-
+ if (this.listeners.hasOwnProperty(watchId)) {
+ delete this.listeners[watchId];
+ }
};
var WIDGET_STATE_CHANGE_LISTENER = 'WidgetStateChangeCallback';