code
stringlengths
1
2.08M
language
stringclasses
1 value
jasmine.HtmlReporter = function(_doc) { var self = this; var doc = _doc || window.document; var reporterView; var dom = {}; // Jasmine Reporter Public Interface self.logRunningSpecs = false; self.reportRunnerStarting = function(runner) { var specs = runner.specs() || []; if (specs.length == 0) { return; } createReporterDom(runner.env.versionString()); doc.body.appendChild(dom.reporter); reporterView = new jasmine.HtmlReporter.ReporterView(dom); reporterView.addSpecs(specs, self.specFilter); }; self.reportRunnerResults = function(runner) { reporterView && reporterView.complete(); }; self.reportSuiteResults = function(suite) { reporterView.suiteComplete(suite); }; self.reportSpecStarting = function(spec) { if (self.logRunningSpecs) { self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); } }; self.reportSpecResults = function(spec) { reporterView.specComplete(spec); }; self.log = function() { var console = jasmine.getGlobal().console; if (console && console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { console.log(arguments); // ie fix: console.log.apply doesn't exist on ie } } }; self.specFilter = function(spec) { if (!focusedSpecName()) { return true; } return spec.getFullName().indexOf(focusedSpecName()) === 0; }; return self; function focusedSpecName() { var specName; (function memoizeFocusedSpec() { if (specName) { return; } var paramMap = []; var params = doc.location.search.substring(1).split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); } specName = paramMap.spec; })(); return specName; } function createReporterDom(version) { dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, dom.banner = self.createDom('div', { className: 'banner' }, self.createDom('span', { className: 'title' }, "Jasmine "), self.createDom('span', { className: 'version' }, version)), dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), dom.alert = self.createDom('div', {className: 'alert'}), dom.results = self.createDom('div', {className: 'results'}, dom.summary = self.createDom('div', { className: 'summary' }), dom.details = self.createDom('div', { id: 'details' })) ); } }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter);
JavaScript
/* @deprecated Use jasmine.HtmlReporter instead */ jasmine.TrivialReporter = function(doc) { this.document = doc || document; this.suiteDivs = {}; this.logRunningSpecs = false; }; jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { var el = document.createElement(type); for (var i = 2; i < arguments.length; i++) { var child = arguments[i]; if (typeof child === 'string') { el.appendChild(document.createTextNode(child)); } else { if (child) { el.appendChild(child); } } } for (var attr in attrs) { if (attr == "className") { el[attr] = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } } return el; }; jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { var showPassed, showSkipped; this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, this.createDom('div', { className: 'banner' }, this.createDom('div', { className: 'logo' }, this.createDom('span', { className: 'title' }, "Jasmine"), this.createDom('span', { className: 'version' }, runner.env.versionString())), this.createDom('div', { className: 'options' }, "Show ", showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") ) ), this.runnerDiv = this.createDom('div', { className: 'runner running' }, this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), this.runnerMessageSpan = this.createDom('span', {}, "Running..."), this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) ); this.document.body.appendChild(this.outerDiv); var suites = runner.suites(); for (var i = 0; i < suites.length; i++) { var suite = suites[i]; var suiteDiv = this.createDom('div', { className: 'suite' }, this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); this.suiteDivs[suite.id] = suiteDiv; var parentDiv = this.outerDiv; if (suite.parentSuite) { parentDiv = this.suiteDivs[suite.parentSuite.id]; } parentDiv.appendChild(suiteDiv); } this.startedAt = new Date(); var self = this; showPassed.onclick = function(evt) { if (showPassed.checked) { self.outerDiv.className += ' show-passed'; } else { self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); } }; showSkipped.onclick = function(evt) { if (showSkipped.checked) { self.outerDiv.className += ' show-skipped'; } else { self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); } }; }; jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { var results = runner.results(); var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; this.runnerDiv.setAttribute("class", className); //do it twice for IE this.runnerDiv.setAttribute("className", className); var specs = runner.specs(); var specCount = 0; for (var i = 0; i < specs.length; i++) { if (this.specFilter(specs[i])) { specCount++; } } var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); }; jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { var results = suite.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.totalCount === 0) { // todo: change this to check results.skipped status = 'skipped'; } this.suiteDivs[suite.id].className += " " + status; }; jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { if (this.logRunningSpecs) { this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); } }; jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { var results = spec.results(); var status = results.passed() ? 'passed' : 'failed'; if (results.skipped) { status = 'skipped'; } var specDiv = this.createDom('div', { className: 'spec ' + status }, this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(spec.getFullName()), title: spec.getFullName() }, spec.description)); var resultItems = results.getItems(); var messagesDiv = this.createDom('div', { className: 'messages' }); for (var i = 0; i < resultItems.length; i++) { var result = resultItems[i]; if (result.type == 'log') { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); } else if (result.type == 'expect' && result.passed && !result.passed()) { messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); if (result.trace.stack) { messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); } } } if (messagesDiv.childNodes.length > 0) { specDiv.appendChild(messagesDiv); } this.suiteDivs[spec.suite.id].appendChild(specDiv); }; jasmine.TrivialReporter.prototype.log = function() { var console = jasmine.getGlobal().console; if (console && console.log) { if (console.log.apply) { console.log.apply(console, arguments); } else { console.log(arguments); // ie fix: console.log.apply doesn't exist on ie } } }; jasmine.TrivialReporter.prototype.getLocation = function() { return this.document.location; }; jasmine.TrivialReporter.prototype.specFilter = function(spec) { var paramMap = {}; var params = this.getLocation().search.substring(1).split('&'); for (var i = 0; i < params.length; i++) { var p = params[i].split('='); paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); } if (!paramMap.spec) { return true; } return spec.getFullName().indexOf(paramMap.spec) === 0; };
JavaScript
jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { this.suite = suite; this.dom = dom; this.views = views; this.element = this.createDom('div', { className: 'suite' }, this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(this.suite.getFullName()) }, this.suite.description) ); this.appendToSummary(this.suite, this.element); }; jasmine.HtmlReporter.SuiteView.prototype.status = function() { return this.getSpecStatus(this.suite); }; jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { this.element.className += " " + this.status(); }; jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ if (window.sessionStorage != null) { window.sessionStorage.clear(); } // Timeout is 2 seconds to allow physical devices enough // time to query the response. This is important for some // Android devices. var Tests = function() {}; Tests.TEST_TIMEOUT = 7500; // Creates a spy that will fail if called. function createDoNotCallSpy(name, opt_extraMessage) { return jasmine.createSpy().andCallFake(function() { var errorMessage = name + ' should not have been called.'; if (arguments.length) { errorMessage += ' Got args: ' + JSON.stringify(arguments); } if (opt_extraMessage) { errorMessage += '\n' + opt_extraMessage; } expect(false).toBe(true, errorMessage); }); } // Waits for any of the given spys to be called. // Last param may be a custom timeout duration. function waitsForAny() { var spys = [].slice.call(arguments); var timeout = Tests.TEST_TIMEOUT; if (typeof spys[spys.length - 1] == 'number') { timeout = spys.pop(); } waitsFor(function() { for (var i = 0; i < spys.length; ++i) { if (spys[i].wasCalled) { return true; } } return false; }, "Expecting callbacks to be called.", timeout); }
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ describe('Plugin object (window.plugins)', function () { it("should exist", function() { expect(window.plugins).toBeDefined(); }); it("should contain a pushNotification object", function() { expect(window.plugins.pushNotification).toBeDefined(); expect(typeof window.plugins.pushNotification == 'object').toBe(true); }); it("should contain a register function", function() { expect(window.plugins.pushNotification.register).toBeDefined(); expect(typeof window.plugins.pushNotification.register == 'function').toBe(true); }); it("should contain an unregister function", function() { expect(window.plugins.pushNotification.unregister).toBeDefined(); expect(typeof window.plugins.pushNotification.unregister == 'function').toBe(true); }); it("should contain a setApplicationIconBadgeNumber function", function() { expect(window.plugins.pushNotification.setApplicationIconBadgeNumber).toBeDefined(); expect(typeof window.plugins.pushNotification.setApplicationIconBadgeNumber == 'function').toBe(true); }); });
JavaScript
var PushNotification = function() { }; // Call this to register for push notifications. Content of [options] depends on whether we are working with APNS (iOS) or GCM (Android) PushNotification.prototype.register = function(successCallback, errorCallback, options) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.register failure: failure parameter not a function"); return; } if (typeof successCallback != "function") { console.log("PushNotification.register failure: success callback parameter must be a function"); return; } cordova.exec(successCallback, errorCallback, "PushPlugin", "register", [options]); }; // Call this to unregister for push notifications PushNotification.prototype.unregister = function(successCallback, errorCallback) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.unregister failure: failure parameter not a function"); return; } if (typeof successCallback != "function") { console.log("PushNotification.unregister failure: success callback parameter must be a function"); return; } cordova.exec(successCallback, errorCallback, "PushPlugin", "unregister", []); }; // Call this to set the application icon badge PushNotification.prototype.setApplicationIconBadgeNumber = function(successCallback, badge) { if (errorCallback == null) { errorCallback = function() {}} if (typeof errorCallback != "function") { console.log("PushNotification.setApplicationIconBadgeNumber failure: failure parameter not a function"); return; } if (typeof successCallback != "function") { console.log("PushNotification.setApplicationIconBadgeNumber failure: success callback parameter must be a function"); return; } cordova.exec(successCallback, successCallback, "PushPlugin", "setApplicationIconBadgeNumber", [{badge: badge}]); }; //------------------------------------------------------------------- if(!window.plugins) { window.plugins = {}; } if (!window.plugins.pushNotification) { window.plugins.pushNotification = new PushNotification(); }
JavaScript
// Client ID and Client Secret received from ADM // For more info, see: https://developer.amazon.com/public/apis/engage/device-messaging/tech-docs/02-obtaining-adm-credentials var CLIENT_ID = "amzn1.application-oa2-client.8e838f6629554e26ae3f43a6c663cd60"; var CLIENT_SECRET = "0af96083320f5d70dc4f358cc783ac65a22e78b297ba257df34d5f723f24543f"; // Registration ID, received on device after it registers with ADM server var REGISTRATION_IDS = ["amzn1.adm-registration.v2.Y29tLmFtYXpvbi5EZXZpY2VNZXNzYWdpbmcuUmVnaXN0cmF0aW9uSWRFbmNyeXB0aW9uS2V5ITEhOE9rZ2h5TXlhVEFFczg2ejNWL3JMcmhTa255Uk5BclhBbE1XMFZzcnU1aFF6cTlvdU5FbVEwclZmdk5oTFBVRXVDN1luQlRSNnRVRUViREdQSlBvSzRNaXVRRUlyUy9NYWZCYS9VWTJUaGZwb3ZVTHhlRTM0MGhvampBK01hVktsMEhxakdmQStOSXRjUXBTQUhNU1NlVVVUVkFreVRhRTBCYktaQ2ZkUFdqSmIwcHgzRDhMQnllVXdxQ2EwdHNXRmFVNklYL0U4UXovcHg0K3Jjb25VbVFLRUVVOFVabnh4RDhjYmtIcHd1ZThiekorbGtzR2taMG95cC92Y3NtZytrcTRPNjhXUUpiZEk3QzFvQThBRTFWWXM2NHkyMjdYVGV5RlhhMWNHS0k9IW5GNEJMSXNleC9xbWpHSU52NnczY0E9PQ"]; // Message payload to be sent to client var payload = { data: { message: "PushPlugin works!!", sound: "beep.wav", url: "http://www.amazon.com", timeStamp: new Date().toISOString(), foo: "baz" }, consolidationKey: "my app", expiresAfter: 3600 }; //********************************* var https = require("https"); var querystring = require("querystring"); if(CLIENT_ID == "" || CLIENT_SECRET == "" || REGISTRATION_IDS.length == 0){ console.log("******************\nSetup Error: \nYou need to edit the pushADM.js file and enter your ADM credentials and device registration ID(s).\n******************"); process.exit(1); } // Get access token from server, and use it to post message to device getAccessToken(function(accessToken){ for(var i = 0; i < REGISTRATION_IDS.length; i++){ var registrationID = REGISTRATION_IDS[i]; postMessage(accessToken, registrationID, payload); } }); // Query OAuth server for access token // For more info, see: https://developer.amazon.com/public/apis/engage/device-messaging/tech-docs/05-requesting-an-access-token function getAccessToken(callback){ console.log("Requesting access token from server..."); var credentials = { scope: "messaging:push", grant_type: "client_credentials", client_id: CLIENT_ID, client_secret: CLIENT_SECRET } var post_data = querystring.stringify(credentials); var post_options = { host: "api.amazon.com", port: "443", path: "/auth/O2/token", method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8" } }; var req = https.request(post_options, function(res) { var data = ""; res.on("data", function (chunk) { data += chunk; }); res.on("end", function() { console.log("\nAccess token response:", data); var accessToken = JSON.parse(data).access_token; callback(accessToken); }); }); req.on("error", function(e) { console.log("\nProblem with access token request: ", e.message); }); req.write(post_data); req.end(); } // Post message payload to ADM server // For more info, see: https://developer.amazon.com/public/apis/engage/device-messaging/tech-docs/06-sending-a-message function postMessage(accessToken, registrationID, payload){ if(accessToken == undefined || registrationID == undefined || payload == undefined){ return; } console.log("\nSending message..."); var post_data = JSON.stringify(payload); var api_path = "/messaging/registrations/" + registrationID + "/messages"; var post_options = { host: "api.amazon.com", port: "443", path: api_path, method: "POST", headers: { "Authorization": "Bearer " + accessToken, "X-Amzn-Type-Version": "com.amazon.device.messaging.ADMMessage@1.0", "X-Amzn-Accept-Type" : "com.amazon.device.messaging.ADMSendResult@1.0", "Content-Type": "application/json", "Accept": "application/json", } }; var req = https.request(post_options, function(res) { var data = ""; res.on("data", function (chunk) { data += chunk; }); res.on("end", function() { console.log("\nSend message response: ", data); }); }); req.on("error", function(e) { console.log("\nProblem with send message request: ", e.message); }); req.write(post_data); req.end(); }
JavaScript
function Flashlight() { // track flashlight state this._isSwitchedOn = false; } Flashlight.prototype = { available: function (callback) { cordova.exec(function (avail) { callback(avail ? true : false); }, null, "Flashlight", "available", []); }, switchOn: function (successCallback, errorCallback) { this._isSwitchedOn = true; cordova.exec(successCallback, errorCallback, "Flashlight", "switchOn", []); }, switchOff: function (successCallback, errorCallback) { this._isSwitchedOn = false; cordova.exec(successCallback, errorCallback, "Flashlight", "switchOff", []); }, toggle: function (successCallback, errorCallback) { if (this._isSwitchedOn) { this.switchOff(successCallback, errorCallback); } else { this.switchOn(successCallback, errorCallback); } } }; Flashlight.install = function () { if (!window.plugins) { window.plugins = {}; } window.plugins.flashlight = new Flashlight(); return window.plugins.flashlight; }; cordova.addConstructor(Flashlight.install);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'); var mediaObjects = {}; /** * This class provides access to the device media, interfaces to both sound and video * * @constructor * @param src The file name or url to play * @param successCallback The callback to be called when the file is done playing or recording. * successCallback() * @param errorCallback The callback to be called if there is an error. * errorCallback(int errorCode) - OPTIONAL * @param statusCallback The callback to be called when media status has changed. * statusCallback(int statusCode) - OPTIONAL */ var Media = function(src, successCallback, errorCallback, statusCallback) { argscheck.checkArgs('SFFF', 'Media', arguments); this.id = utils.createUUID(); mediaObjects[this.id] = this; this.src = src; this.successCallback = successCallback; this.errorCallback = errorCallback; this.statusCallback = statusCallback; this._duration = -1; this._position = -1; exec(null, this.errorCallback, "Media", "create", [this.id, this.src]); }; // Media messages Media.MEDIA_STATE = 1; Media.MEDIA_DURATION = 2; Media.MEDIA_POSITION = 3; Media.MEDIA_ERROR = 9; // Media states Media.MEDIA_NONE = 0; Media.MEDIA_STARTING = 1; Media.MEDIA_RUNNING = 2; Media.MEDIA_PAUSED = 3; Media.MEDIA_STOPPED = 4; Media.MEDIA_MSG = ["None", "Starting", "Running", "Paused", "Stopped"]; // "static" function to return existing objs. Media.get = function(id) { return mediaObjects[id]; }; /** * Start or resume playing audio file. */ Media.prototype.play = function(options) { exec(null, null, "Media", "startPlayingAudio", [this.id, this.src, options]); }; /** * Stop playing audio file. */ Media.prototype.stop = function() { var me = this; exec(function() { me._position = 0; }, this.errorCallback, "Media", "stopPlayingAudio", [this.id]); }; /** * Seek or jump to a new time in the track.. */ Media.prototype.seekTo = function(milliseconds) { var me = this; exec(function(p) { me._position = p; }, this.errorCallback, "Media", "seekToAudio", [this.id, milliseconds]); }; /** * Pause playing audio file. */ Media.prototype.pause = function() { exec(null, this.errorCallback, "Media", "pausePlayingAudio", [this.id]); }; /** * Get duration of an audio file. * The duration is only set for audio that is playing, paused or stopped. * * @return duration or -1 if not known. */ Media.prototype.getDuration = function() { return this._duration; }; /** * Get position of audio. */ Media.prototype.getCurrentPosition = function(success, fail) { var me = this; exec(function(p) { me._position = p; success(p); }, fail, "Media", "getCurrentPositionAudio", [this.id]); }; /** * Start recording audio file. */ Media.prototype.startRecord = function() { exec(null, this.errorCallback, "Media", "startRecordingAudio", [this.id, this.src]); }; /** * Stop recording audio file. */ Media.prototype.stopRecord = function() { exec(null, this.errorCallback, "Media", "stopRecordingAudio", [this.id]); }; /** * Release the resources. */ Media.prototype.release = function() { exec(null, this.errorCallback, "Media", "release", [this.id]); }; /** * Adjust the volume. */ Media.prototype.setVolume = function(volume) { exec(null, null, "Media", "setVolume", [this.id, volume]); }; /** * Audio has status update. * PRIVATE * * @param id The media object id (string) * @param msgType The 'type' of update this is * @param value Use of value is determined by the msgType */ Media.onStatus = function(id, msgType, value) { var media = mediaObjects[id]; if(media) { switch(msgType) { case Media.MEDIA_STATE : media.statusCallback && media.statusCallback(value); if(value == Media.MEDIA_STOPPED) { media.successCallback && media.successCallback(); } break; case Media.MEDIA_DURATION : media._duration = value; break; case Media.MEDIA_ERROR : media.errorCallback && media.errorCallback(value); break; case Media.MEDIA_POSITION : media._position = Number(value); break; default : console.error && console.error("Unhandled Media.onStatus :: " + msgType); break; } } else { console.error && console.error("Received Media.onStatus callback for unknown media :: " + id); } }; module.exports = Media;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * This class contains information about any Media errors. */ /* According to :: http://dev.w3.org/html5/spec-author-view/video.html#mediaerror We should never be creating these objects, we should just implement the interface which has 1 property for an instance, 'code' instead of doing : errorCallbackFunction( new MediaError(3,'msg') ); we should simply use a literal : errorCallbackFunction( {'code':3} ); */ var _MediaError = window.MediaError; if(!_MediaError) { window.MediaError = _MediaError = function(code, msg) { this.code = (typeof code != 'undefined') ? code : null; this.message = msg || ""; // message is NON-standard! do not use! }; } _MediaError.MEDIA_ERR_NONE_ACTIVE = _MediaError.MEDIA_ERR_NONE_ACTIVE || 0; _MediaError.MEDIA_ERR_ABORTED = _MediaError.MEDIA_ERR_ABORTED || 1; _MediaError.MEDIA_ERR_NETWORK = _MediaError.MEDIA_ERR_NETWORK || 2; _MediaError.MEDIA_ERR_DECODE = _MediaError.MEDIA_ERR_DECODE || 3; _MediaError.MEDIA_ERR_NONE_SUPPORTED = _MediaError.MEDIA_ERR_NONE_SUPPORTED || 4; // TODO: MediaError.MEDIA_ERR_NONE_SUPPORTED is legacy, the W3 spec now defines it as below. // as defined by http://dev.w3.org/html5/spec-author-view/video.html#error-codes _MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = _MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED || 4; module.exports = _MediaError;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ exports.defineAutoTests = function () { var failed = function (done, msg, error) { var info = typeof msg == 'undefined' ? 'Unexpected error callback' : msg; expect(true).toFailWithMessage(info + '\n' + JSON.stringify(error)); done(); }; var succeed = function (done, msg) { var info = typeof msg == 'undefined' ? 'Unexpected success callback' : msg; expect(true).toFailWithMessage(info); done(); }; describe('Media', function () { beforeEach(function () { // Custom Matcher jasmine.Expectation.addMatchers({ toFailWithMessage : function () { return { compare : function (error, message) { var pass = false; return { pass : pass, message : message }; } }; } }); }); it("media.spec.1 should exist", function () { expect(Media).toBeDefined(); expect(typeof Media).toBe("function"); }); it("media.spec.2 should have the following properties", function () { var media1 = new Media("dummy"); expect(media1.id).toBeDefined(); expect(media1.src).toBeDefined(); expect(media1._duration).toBeDefined(); expect(media1._position).toBeDefined(); media1.release(); }); it("media.spec.3 should define constants for Media status", function () { expect(Media).toBeDefined(); expect(Media.MEDIA_NONE).toBe(0); expect(Media.MEDIA_STARTING).toBe(1); expect(Media.MEDIA_RUNNING).toBe(2); expect(Media.MEDIA_PAUSED).toBe(3); expect(Media.MEDIA_STOPPED).toBe(4); }); it("media.spec.4 should define constants for Media errors", function () { expect(MediaError).toBeDefined(); expect(MediaError.MEDIA_ERR_NONE_ACTIVE).toBe(0); expect(MediaError.MEDIA_ERR_ABORTED).toBe(1); expect(MediaError.MEDIA_ERR_NETWORK).toBe(2); expect(MediaError.MEDIA_ERR_DECODE).toBe(3); expect(MediaError.MEDIA_ERR_NONE_SUPPORTED).toBe(4); }); it("media.spec.5 should contain a play function", function () { var media1 = new Media(); expect(media1.play).toBeDefined(); expect(typeof media1.play).toBe('function'); media1.release(); }); it("media.spec.6 should contain a stop function", function () { var media1 = new Media(); expect(media1.stop).toBeDefined(); expect(typeof media1.stop).toBe('function'); media1.release(); }); it("media.spec.7 should contain a seekTo function", function () { var media1 = new Media(); expect(media1.seekTo).toBeDefined(); expect(typeof media1.seekTo).toBe('function'); media1.release(); }); it("media.spec.8 should contain a pause function", function () { var media1 = new Media(); expect(media1.pause).toBeDefined(); expect(typeof media1.pause).toBe('function'); media1.release(); }); it("media.spec.9 should contain a getDuration function", function () { var media1 = new Media(); expect(media1.getDuration).toBeDefined(); expect(typeof media1.getDuration).toBe('function'); media1.release(); }); it("media.spec.10 should contain a getCurrentPosition function", function () { var media1 = new Media(); expect(media1.getCurrentPosition).toBeDefined(); expect(typeof media1.getCurrentPosition).toBe('function'); media1.release(); }); it("media.spec.11 should contain a startRecord function", function () { var media1 = new Media(); expect(media1.startRecord).toBeDefined(); expect(typeof media1.startRecord).toBe('function'); media1.release(); }); it("media.spec.12 should contain a stopRecord function", function () { var media1 = new Media(); expect(media1.stopRecord).toBeDefined(); expect(typeof media1.stopRecord).toBe('function'); media1.release(); }); it("media.spec.13 should contain a release function", function () { var media1 = new Media(); expect(media1.release).toBeDefined(); expect(typeof media1.release).toBe('function'); media1.release(); }); it("media.spec.14 should contain a setVolume function", function () { var media1 = new Media(); expect(media1.setVolume).toBeDefined(); expect(typeof media1.setVolume).toBe('function'); media1.release(); }); it("media.spec.15 should return MediaError for bad filename", function (done) { var fileName = 'invalid.file.name'; //Error callback it has an unexpected behavior under Windows Phone, //it enters to the error callback several times, instead of just one walk-through //JIRA issue related with all details: CB-7092 //the conditional statement should be removed once the issue is fixed. //bb10 dialog pops up, preventing tests from running if (cordova.platformId === 'blackberry10' || cordova.platformId === 'windowsphone') { expect(true).toFailWithMessage('Platform does not support this feature'); done(); } else { var badMedia = null; badMedia = new Media(fileName, succeed.bind(null, done, ' badMedia = new Media , Unexpected succees callback, it should not create Media object with invalid file name'), function (result) { expect(result).toBeDefined(); expect(result.code).toBe(MediaError.MEDIA_ERR_ABORTED); badMedia.release(); done(); }); badMedia.play(); } }); it("media.spec.16 position should be set properly", function (done) { var mediaFile = 'http://cordova.apache.org/downloads/BlueZedEx.mp3', mediaState = Media.MEDIA_STOPPED, successCallback, flag = true, statusChange = function (statusCode) { if (statusCode == Media.MEDIA_RUNNING && flag) { //flag variable used to ensure an extra security statement to ensure that the callback is processed only once, //in case for some reason the statusChange callback is reached more than one time with the same status code. //Some information about this kind of behavior it can be found at JIRA: CB-7099 flag = false; setTimeout(function () { media1.getCurrentPosition(function (position) { expect(position).toBeGreaterThan(0.0); media1.stop(); media1.release(); done(); }, failed.bind(null, done, 'media1.getCurrentPosition - Error getting media current position')); }, 1000); } }; media1 = new Media(mediaFile, successCallback, failed.bind(null, done, 'media1 = new Media - Error creating Media object. Media file: ' + mediaFile), statusChange); media1.play(); }); it("media.spec.17 duration should be set properly", function (done) { if (cordova.platformId === 'blackberry10') { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); } var mediaFile = 'http://cordova.apache.org/downloads/BlueZedEx.mp3', mediaState = Media.MEDIA_STOPPED, successCallback, flag = true, statusChange = function (statusCode) { if (statusCode == Media.MEDIA_RUNNING && flag) { //flag variable used to ensure an extra security statement to ensure that the callback is processed only once, //in case for some reason the statusChange callback is reached more than one time with the same status code. //Some information about this kind of behavior it can be found at JIRA: CB-7099. flag = false; setTimeout(function () { expect(media1.getDuration()).toBeGreaterThan(0.0); media1.stop(); media1.release(); done(); }, 1000); } }, media1 = new Media(mediaFile, successCallback, failed.bind(null, done, 'media1 = new Media - Error creating Media object. Media file: ' + mediaFile), statusChange); media1.play(); }); }); }; //****************************************************************************************** //***************************************Manual Tests*************************************** //****************************************************************************************** exports.defineManualTests = function (contentEl, createActionButton) { //------------------------------------------------------------------------- // Audio player //------------------------------------------------------------------------- var media1 = null; var media1Timer = null; var audioSrc = null; var defaultaudio = "http://cordova.apache.org/downloads/BlueZedEx.mp3"; //Play audio function function playAudio(url) { console.log("playAudio()"); console.log(" -- media=" + media1); var src = defaultaudio; if (url) { src = url; } // Stop playing if src is different from currently playing source if (src !== audioSrc) { if (media1 !== null) { stopAudio(); media1 = null; } } if (media1 === null) { // TEST STREAMING AUDIO PLAYBACK //var src = "http://nunzioweb.com/misc/Bon_Jovi-Crush_Mystery_Train.mp3"; // works //var src = "http://nunzioweb.com/misc/Bon_Jovi-Crush_Mystery_Train.m3u"; // doesn't work //var src = "http://www.wav-sounds.com/cartoon/bugsbunny1.wav"; // works //var src = "http://www.angelfire.com/fl5/html-tutorial/a/couldyou.mid"; // doesn't work //var src = "MusicSearch/mp3/train.mp3"; // works //var src = "bryce.mp3"; // works //var src = "/android_asset/www/bryce.mp3"; // works media1 = new Media(src, function () { console.log("playAudio():Audio Success"); }, function (err) { console.log("playAudio():Audio Error: " + err.code); setAudioStatus("Error: " + err.code); }, function (status) { console.log("playAudio():Audio Status: " + status); setAudioStatus(Media.MEDIA_MSG[status]); // If stopped, then stop getting current position if (Media.MEDIA_STOPPED == status) { clearInterval(media1Timer); media1Timer = null; setAudioPosition("0 sec"); } }); } audioSrc = src; document.getElementById('durationValue').innerHTML = ""; // Play audio media1.play(); if (media1Timer === null && media1.getCurrentPosition) { media1Timer = setInterval( function () { media1.getCurrentPosition( function (position) { if (position >= 0.0) { setAudioPosition(position + " sec"); } }, function (e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); }); }, 1000); } // Get duration var counter = 0; var timerDur = setInterval( function () { counter = counter + 100; if (counter > 2000) { clearInterval(timerDur); } var dur = media1.getDuration(); if (dur > 0) { clearInterval(timerDur); document.getElementById('durationValue').innerHTML = dur + " sec"; } }, 100); } //Pause audio playback function pauseAudio() { console.log("pauseAudio()"); if (media1) { media1.pause(); } } //Stop audio function stopAudio() { console.log("stopAudio()"); if (media1) { media1.stop(); } clearInterval(media1Timer); media1Timer = null; } //Release audio function releaseAudio() { console.log("releaseAudio()"); if (media1) { media1.stop(); //imlied stop of playback, resets timer media1.release(); } } //Set audio status function setAudioStatus(status) { document.getElementById('statusValue').innerHTML = status; } //Set audio position function setAudioPosition(position) { document.getElementById('positionValue').innerHTML = position; } //Seek audio function seekAudio(mode) { var time = document.getElementById("seekInput").value; if (time === "") { time = 5000; } else { time = time * 1000; //we expect the input to be in seconds } if (media1 === null) { console.log("seekTo requested while media1 is null"); if (audioSrc === null) { audioSrc = defaultaudio; } media1 = new Media(audioSrc, function () { console.log("seekToAudio():Audio Success"); }, function (err) { console.log("seekAudio():Audio Error: " + err.code); setAudioStatus("Error: " + err.code); }, function (status) { console.log("seekAudio():Audio Status: " + status); setAudioStatus(Media.MEDIA_MSG[status]); // If stopped, then stop getting current position if (Media.MEDIA_STOPPED == status) { clearInterval(media1Timer); media1Timer = null; setAudioPosition("0 sec"); } }); } media1.getCurrentPosition( function (position) { var deltat = time; if (mode === "by") { deltat = time + position * 1000; } media1.seekTo(deltat, function () { console.log("seekAudioTo():Audio Success"); //force an update on the position display updatePosition(); }, function (err) { console.log("seekAudioTo():Audio Error: " + err.code); }); }, function (e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); }); } //for forced updates of position after a successful seek function updatePosition() { media1.getCurrentPosition( function (position) { if (position >= 0.0) { setAudioPosition(position + " sec"); } }, function (e) { console.log("Error getting pos=" + e); setAudioPosition("Error: " + e); }); } //------------------------------------------------------------------------- // Audio recorder //------------------------------------------------------------------------- var mediaRec = null; var recTime = 0; var recordSrc = "myRecording.mp3"; //Record audio function recordAudio() { console.log("recordAudio()"); console.log(" -- media=" + mediaRec); if (mediaRec == null) { var src = recordSrc; mediaRec = new Media(src, function () { console.log("recordAudio():Audio Success"); }, function (err) { console.log("recordAudio():Audio Error: " + err.code); setAudioStatus("Error: " + err.code); }, function (status) { console.log("recordAudio():Audio Status: " + status); setAudioStatus(Media.MEDIA_MSG[status]); }); } // Record audio mediaRec.startRecord(); // Stop recording after 10 sec recTime = 0; var recInterval = setInterval(function () { recTime = recTime + 1; setAudioPosition(recTime + " sec"); if (recTime >= 10) { clearInterval(recInterval); if (mediaRec.stopAudioRecord) { mediaRec.stopAudioRecord(); } else { mediaRec.stopRecord(); } console.log("recordAudio(): stop"); } }, 1000); } //Play back recorded audio function playRecording() { playAudio(recordSrc); } //Function to create a file for iOS recording function getRecordSrc() { var fsFail = function (error) { console.log("error creating file for iOS recording"); }; var gotFile = function (file) { recordSrc = file.fullPath; //console.log("recording Src: " + recordSrc); }; var gotFS = function (fileSystem) { fileSystem.root.getFile("iOSRecording.wav", { create : true }, gotFile, fsFail); }; window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, fsFail); } //Function to create a file for BB recording function getRecordSrcBB() { var fsFail = function (error) { console.log("error creating file for BB recording"); }; var gotFile = function (file) { recordSrc = file.fullPath; }; var gotFS = function (fileSystem) { fileSystem.root.getFile("BBRecording.amr", { create : true }, gotFile, fsFail); }; window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, gotFS, fsFail); } //Function to create a file for Windows recording function getRecordSrcWin() { var fsFail = function (error) { console.log("error creating file for Win recording"); }; var gotFile = function (file) { recordSrc = file.fullPath.replace(/\//g, '\\'); }; var gotFS = function (fileSystem) { fileSystem.root.getFile("WinRecording.m4a", { create: true }, gotFile, fsFail); }; window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fsFail); } //Generate Dynamic Table function generateTable(tableId, rows, cells, elements) { var table = document.createElement('table'); for (var r = 0; r < rows; r++) { var row = table.insertRow(r); for (var c = 0; c < cells; c++) { var cell = row.insertCell(c); cell.setAttribute("align", "center"); for (var e in elements) { if (elements[e].position.row == r && elements[e].position.cell == c) { var htmlElement = document.createElement(elements[e].tag); var content; if (elements[e].content !== "") { content = document.createTextNode(elements[e].content); htmlElement.appendChild(content); } if (elements[e].type) { htmlElement.type = elements[e].type; } htmlElement.setAttribute("id", elements[e].id); cell.appendChild(htmlElement); } } } } table.setAttribute("align", "center"); table.setAttribute("id", tableId); return table; } //Audio && Record Elements var elementsResultsAudio= [{ id : "statusTag", content : "Status:", tag : "div", position : { row : 0, cell : 0 } }, { id : "statusValue", content : "", tag : "div", position : { row : 0, cell : 2 } }, { id : "durationTag", content : "Duration:", tag : "div", position : { row : 1, cell : 0 } }, { id : "durationValue", content : "", tag : "div", position : { row : 1, cell : 2 } }, { id : "positionTag", content : "Position:", tag : "div", position : { row : 2, cell : 0 } }, { id : "positionValue", content : "", tag : "div", position : { row : 2, cell : 2 } }], elementsAudio = [{ id : "playBtn", content : "", tag : "div", position : { row : 0, cell : 0 } }, { id : "pauseBtn", content : "", tag : "div", position : { row : 0, cell : 1 } }, { id : "stopBtn", content : "", tag : "div", position : { row : 1, cell : 0 } }, { id : "releaseBtn", content : "", tag : "div", position : { row : 1, cell : 1 } }, { id : "seekByBtn", content : "", tag : "div", position : { row : 2, cell : 0 } }, { id : "seekToBtn", content : "", tag : "div", position : { row : 2, cell : 1 } }, { id : "seekInput", content : "", tag : "input", type : "number", position : { row : 2, cell : 2 } } ], elementsRecord = [{ id : "recordbtn", content : "", tag : "div", position : { row : 1, cell : 0 } }, { id : "recordplayBtn", content : "", tag : "div", position : { row : 1, cell : 1 } }, { id : "recordpauseBtn", content : "", tag : "div", position : { row : 2, cell : 0 } }, { id : "recordstopBtn", content : "", tag : "div", position : { row : 2, cell : 1 } } ]; //Title audio results var div = document.createElement('h2'); div.appendChild(document.createTextNode('Audio')); div.setAttribute("align", "center"); contentEl.appendChild(div); //Generate and add results table contentEl.appendChild(generateTable('info', 3, 3, elementsResultsAudio)); //Title audio actions div = document.createElement('h2'); div.appendChild(document.createTextNode('Actions')); div.setAttribute("align", "center"); contentEl.appendChild(div); //Generate and add buttons table contentEl.appendChild(generateTable('audioActions', 3, 3, elementsAudio)); createActionButton('Play', function () { playAudio(); }, 'playBtn'); createActionButton('Pause', function () { pauseAudio(); }, 'pauseBtn'); createActionButton('Stop', function () { stopAudio(); }, 'stopBtn'); createActionButton('Release', function () { releaseAudio(); }, 'releaseBtn'); createActionButton('Seek By', function () { seekAudio('by'); }, 'seekByBtn'); createActionButton('Seek To', function () { seekAudio('to'); }, 'seekToBtn'); //get Special path to record if iOS || Blackberry if (cordova.platformId === 'ios') getRecordSrc(); else if (cordova.platformId === 'blackberry') getRecordSrcBB(); else if (cordova.platformId === 'windows' || cordova.platformId === 'windows8') getRecordSrcWin(); //testing process and details function addItemToList(_list, _text) { var item = document.createElement('li'); item.appendChild(document.createTextNode(_text)); _list.appendChild(item); } div = document.createElement('h4'); div.appendChild(document.createTextNode('Recommended Test Procedure')); contentEl.appendChild(div); var list = document.createElement('ol'); addItemToList(list, 'Press play - Will start playing audio. Status: Running, Duration: 61.333 sec, Position: Current position of audio track'); addItemToList(list, 'Press pause - Will pause the audio. Status: Paused, Duration: 61.333 sec, Position: Position where track was paused'); addItemToList(list, 'Press play - Will begin playing where track left off from the pause'); addItemToList(list, 'Press stop - Will stop the audio. Status: Stopped, Duration: 61.333 sec, Position: 0 sec'); addItemToList(list, 'Press play - Will begin playing the audio track from the beginning'); addItemToList(list, 'Press release - Will stop the audio. Status: Stopped, Duration: 61.333 sec, Position: 0 sec'); addItemToList(list, 'Press play - Will begin playing the audio track from the beginning'); addItemToList(list, 'Type 10 in the text box beside Seek To button'); addItemToList(list, 'Press seek by - Will jump 10 seconds ahead in the audio track. Position: should jump by 10 sec'); addItemToList(list, 'Press stop if track is not already stopped'); addItemToList(list, 'Type 30 in the text box beside Seek To button'); addItemToList(list, 'Press play then seek to - Should jump to Position 30 sec'); addItemToList(list, 'Press stop'); addItemToList(list, 'Type 5 in the text box beside Seek To button'); addItemToList(list, 'Press play, let play past 10 seconds then press seek to - should jump back to position 5 sec'); div = document.createElement('div'); div.setAttribute("style", "background:#B0C4DE;border:1px solid #FFA07A;margin:15px 6px 0px;min-width:295px;max-width:97%;padding:4px 0px 2px 10px;min-height:160px;max-height:200px;overflow:auto"); div.appendChild(list); contentEl.appendChild(div); //Title Record Audio div = document.createElement('h2'); div.appendChild(document.createTextNode('Record Audio')); div.setAttribute("align", "center"); contentEl.appendChild(div); //Generate and add Record buttons table contentEl.appendChild(generateTable('recordContent', 3, 3, elementsRecord)); createActionButton('Record Audio \n 10 sec', function () { recordAudio(); }, 'recordbtn'); createActionButton('Play', function () { playRecording(); }, 'recordplayBtn'); createActionButton('Pause', function () { pauseAudio(); }, 'recordpauseBtn'); createActionButton('Stop', function () { stopAudio(); }, 'recordstopBtn'); //testing process and details div = document.createElement('h4'); div.appendChild(document.createTextNode('Recommended Test Procedure')); contentEl.appendChild(div); list = document.createElement('ol'); addItemToList(list, 'Press Record Audio 10 sec - Will start recording audio for 10 seconds. Status: Running, Position: number of seconds recorded (will stop at 10)'); addItemToList(list, 'Status will change to Stopped when finished recording'); addItemToList(list, 'Press play - Will begin playing the recording. Status: Running, Duration: # of seconds of recording, Position: Current position of recording'); addItemToList(list, 'Press stop - Will stop playing the recording. Status: Stopped, Duration: # of seconds of recording, Position: 0 sec'); addItemToList(list, 'Press play - Will begin playing the recording from the beginning'); addItemToList(list, 'Press pause - Will pause the playback of the recording. Status: Paused, Duration: # of seconds of recording, Position: Position where recording was paused'); addItemToList(list, 'Press play - Will begin playing the recording from where it was paused'); div = document.createElement('div'); div.setAttribute("style", "background:#B0C4DE;border:1px solid #FFA07A;margin:15px 6px 0px;min-width:295px;max-width:97%;padding:4px 0px 2px 10px;min-height:160px;max-height:200px;overflow:auto"); div.appendChild(list); contentEl.appendChild(div); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var cordova = require('cordova'), Media = require('org.apache.cordova.media.Media'); var MediaError = require('org.apache.cordova.media.MediaError'), audioObjects = {}; module.exports = { // Initiates the audio file create:function(successCallback, errorCallback, args) { var id = args[0], src = args[1]; console.log("media::create() - id =" + id + ", src =" + src); audioObjects[id] = new Audio(src); audioObjects[id].onStalledCB = function () { console.log("media::onStalled()"); audioObjects[id].timer = window.setTimeout( function () { audioObjects[id].pause(); if (audioObjects[id].currentTime !== 0) audioObjects[id].currentTime = 0; console.log("media::onStalled() - MEDIA_ERROR -> " + MediaError.MEDIA_ERR_ABORTED); var err = new MediaError(MediaError.MEDIA_ERR_ABORTED, "Stalled"); Media.onStatus(id, Media.MEDIA_ERROR, err); }, 2000); }; audioObjects[id].onEndedCB = function () { console.log("media::onEndedCB() - MEDIA_STATE -> MEDIA_STOPPED"); Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED); }; audioObjects[id].onErrorCB = function () { console.log("media::onErrorCB() - MEDIA_ERROR -> " + event.srcElement.error); Media.onStatus(id, Media.MEDIA_ERROR, event.srcElement.error); }; audioObjects[id].onPlayCB = function () { console.log("media::onPlayCB() - MEDIA_STATE -> MEDIA_STARTING"); Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STARTING); }; audioObjects[id].onPlayingCB = function () { console.log("media::onPlayingCB() - MEDIA_STATE -> MEDIA_RUNNING"); Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING); }; audioObjects[id].onDurationChangeCB = function () { console.log("media::onDurationChangeCB() - MEDIA_DURATION -> " + audioObjects[id].duration); Media.onStatus(id, Media.MEDIA_DURATION, audioObjects[id].duration); }; audioObjects[id].onTimeUpdateCB = function () { console.log("media::onTimeUpdateCB() - MEDIA_POSITION -> " + audioObjects[id].currentTime); Media.onStatus(id, Media.MEDIA_POSITION, audioObjects[id].currentTime); }; audioObjects[id].onCanPlayCB = function () { console.log("media::onCanPlayCB()"); window.clearTimeout(audioObjects[id].timer); audioObjects[id].play(); }; }, // Start playing the audio startPlayingAudio:function(successCallback, errorCallback, args) { var id = args[0], src = args[1], options = args[2]; console.log("media::startPlayingAudio() - id =" + id + ", src =" + src + ", options =" + options); audioObjects[id].addEventListener('canplay', audioObjects[id].onCanPlayCB); audioObjects[id].addEventListener('ended', audioObjects[id].onEndedCB); audioObjects[id].addEventListener('timeupdate', audioObjects[id].onTimeUpdateCB); audioObjects[id].addEventListener('durationchange', audioObjects[id].onDurationChangeCB); audioObjects[id].addEventListener('playing', audioObjects[id].onPlayingCB); audioObjects[id].addEventListener('play', audioObjects[id].onPlayCB); audioObjects[id].addEventListener('error', audioObjects[id].onErrorCB); audioObjects[id].addEventListener('stalled', audioObjects[id].onStalledCB); audioObjects[id].play(); }, // Stops the playing audio stopPlayingAudio:function(successCallback, errorCallback, args) { var id = args[0]; window.clearTimeout(audioObjects[id].timer); audioObjects[id].pause(); if (audioObjects[id].currentTime !== 0) audioObjects[id].currentTime = 0; console.log("media::stopPlayingAudio() - MEDIA_STATE -> MEDIA_STOPPED"); Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED); audioObjects[id].removeEventListener('canplay', audioObjects[id].onCanPlayCB); audioObjects[id].removeEventListener('ended', audioObjects[id].onEndedCB); audioObjects[id].removeEventListener('timeupdate', audioObjects[id].onTimeUpdateCB); audioObjects[id].removeEventListener('durationchange', audioObjects[id].onDurationChangeCB); audioObjects[id].removeEventListener('playing', audioObjects[id].onPlayingCB); audioObjects[id].removeEventListener('play', audioObjects[id].onPlayCB); audioObjects[id].removeEventListener('error', audioObjects[id].onErrorCB); audioObjects[id].removeEventListener('error', audioObjects[id].onStalledCB); }, // Seeks to the position in the audio seekToAudio:function(successCallback, errorCallback, args) { var id = args[0], milliseconds = args[1]; console.log("media::seekToAudio()"); audioObjects[id].currentTime = milliseconds; successCallback( audioObjects[id].currentTime); }, // Pauses the playing audio pausePlayingAudio:function(successCallback, errorCallback, args) { var id = args[0]; console.log("media::pausePlayingAudio() - MEDIA_STATE -> MEDIA_PAUSED"); audioObjects[id].pause(); Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_PAUSED); }, // Gets current position in the audio getCurrentPositionAudio:function(successCallback, errorCallback, args) { var id = args[0]; console.log("media::getCurrentPositionAudio()"); successCallback(audioObjects[id].currentTime); }, // Start recording audio startRecordingAudio:function(successCallback, errorCallback, args) { var id = args[0], src = args[1]; console.log("media::startRecordingAudio() - id =" + id + ", src =" + src); function gotStreamCB(stream) { audioObjects[id].src = webkitURL.createObjectURL(stream); console.log("media::startRecordingAudio() - stream CB"); } function gotStreamFailedCB(error) { console.log("media::startRecordingAudio() - error CB:" + error.toString()); } if (navigator.webkitGetUserMedia) { audioObjects[id] = new Audio(); navigator.webkitGetUserMedia('audio', gotStreamCB, gotStreamFailedCB); } else { console.log("webkitGetUserMedia not supported"); } successCallback(); }, // Stop recording audio stopRecordingAudio:function(successCallback, errorCallback, args) { var id = args[0]; console.log("media::stopRecordingAudio() - id =" + id); audioObjects[id].pause(); successCallback(); }, // Release the media object release:function(successCallback, errorCallback, args) { var id = args[0]; window.clearTimeout(audioObjects[id].timer); console.log("media::release()"); }, setVolume:function(successCallback, errorCallback, args) { var id = args[0], volume = args[1]; console.log("media::setVolume()"); audioObjects[id].volume = volume; } }; require("cordova/tizen/commandProxy").add("Media", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var audioObjects = {}, mediaErrorsHandled = false; // There is a bug in the webplatform handling of media error // dialogs prior to 10.2. This function needs to be run once // on the webview which plays audio to prevent freezing. function handleMediaErrors() { var webview = qnx.webplatform.getWebViews()[0], handler = webview.onDialogRequested; if (!mediaErrorsHandled) { webview.allowWebEvent("DialogRequested"); webview.onDialogRequested = undefined; webview.onDialogRequested = function (eventArgs) { var parsedArgs = JSON.parse(eventArgs); if (parsedArgs.dialogType === 'MediaError') { return '{"setPreventDefault": true}'; } handler(eventArgs); }; mediaErrorsHandled = true; } } module.exports = { create: function (success, fail, args, env) { var result = new PluginResult(args, env), id; if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } id = JSON.parse(decodeURIComponent(args[0])); if (!args[1]){ audioObjects[id] = new Audio(); } else { audioObjects[id] = new Audio(JSON.parse(decodeURIComponent(args[1]))); } handleMediaErrors(); result.ok(); }, startPlayingAudio: function (success, fail, args, env) { var audio, id, result = new PluginResult(args, env); if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } id = JSON.parse(decodeURIComponent(args[0])); audio = audioObjects[id]; if (!audio) { result.error("Audio object has not been initialized"); } else { audio.play(); result.ok(); } }, stopPlayingAudio: function (success, fail, args, env) { var audio, id, result = new PluginResult(args, env); if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } id = JSON.parse(decodeURIComponent(args[0])); audio = audioObjects[id]; if (!audio) { result.error("Audio Object has not been initialized"); return; } audio.pause(); audio.currentTime = 0; result.ok(); }, seekToAudio: function (success, fail, args, env) { var audio, result = new PluginResult(args, env); if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } audio = audioObjects[JSON.parse(decodeURIComponent(args[0]))]; if (!audio) { result.error("Audio Object has not been initialized"); } else if (!args[1]) { result.error("Media seek time argument not found"); } else { try { audio.currentTime = JSON.parse(decodeURIComponent(args[1])) / 1000; result.ok(); } catch (e) { result.error("Error seeking audio: " + e); } } }, pausePlayingAudio: function (success, fail, args, env) { var audio, result = new PluginResult(args, env); if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } audio = audioObjects[JSON.parse(decodeURIComponent(args[0]))]; if (!audio) { result.error("Audio Object has not been initialized"); return; } audio.pause(); }, getCurrentPositionAudio: function (success, fail, args, env) { var audio, result = new PluginResult(args, env); if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } audio = audioObjects[JSON.parse(decodeURIComponent(args[0]))]; if (!audio) { result.error("Audio Object has not been initialized"); return; } result.ok(audio.currentTime); }, getDuration: function (success, fail, args, env) { var audio, result = new PluginResult(args, env); if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } audio = audioObjects[JSON.parse(decodeURIComponent(args[0]))]; if (!audio) { result.error("Audio Object has not been initialized"); return; } result.ok(audio.duration); }, startRecordingAudio: function (success, fail, args, env) { var result = new PluginResult(args, env); result.error("Not supported"); }, stopRecordingAudio: function (success, fail, args, env) { var result = new PluginResult(args, env); result.error("Not supported"); }, release: function (success, fail, args, env) { var audio, id, result = new PluginResult(args, env); if (!args[0]) { result.error("Media Object id was not sent in arguments"); return; } id = JSON.parse(decodeURIComponent(args[0])); audio = audioObjects[id]; if (audio) { if(audio.src !== ""){ audio.src = undefined; } audioObjects[id] = undefined; } result.ok(); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /*global Windows:true */ var cordova = require('cordova'), Media = require('org.apache.cordova.media.Media'); var MediaError = require('org.apache.cordova.media.MediaError'); var recordedFile; module.exports = { mediaCaptureMrg:null, // Initiates the audio file create:function(win, lose, args) { var id = args[0]; var src = args[1]; var thisM = Media.get(id); Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STARTING); Media.prototype.node = null; var fn = src.split('.').pop(); // gets the file extension if (thisM.node === null) { if (fn === 'mp3' || fn === 'wma' || fn === 'wav' || fn === 'cda' || fn === 'adx' || fn === 'wm' || fn === 'm3u' || fn === 'wmx' || fn === 'm4a') { thisM.node = new Audio(src); thisM.node.load(); var getDuration = function () { var dur = thisM.node.duration; if (isNaN(dur)) { dur = -1; } Media.onStatus(id, Media.MEDIA_DURATION, dur); }; thisM.node.onloadedmetadata = getDuration; getDuration(); } else { lose && lose({code:MediaError.MEDIA_ERR_ABORTED}); } } }, // Start playing the audio startPlayingAudio:function(win, lose, args) { var id = args[0]; //var src = args[1]; //var options = args[2]; var thisM = Media.get(id); // if Media was released, then node will be null and we need to create it again if (!thisM.node) { module.exports.create(win, lose, args); } Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_RUNNING); thisM.node.play(); }, // Stops the playing audio stopPlayingAudio:function(win, lose, args) { var id = args[0]; try { (Media.get(id)).node.pause(); (Media.get(id)).node.currentTime = 0; Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_STOPPED); win(); } catch (err) { lose("Failed to stop: "+err); } }, // Seeks to the position in the audio seekToAudio:function(win, lose, args) { var id = args[0]; var milliseconds = args[1]; try { (Media.get(id)).node.currentTime = milliseconds / 1000; win(); } catch (err) { lose("Failed to seek: "+err); } }, // Pauses the playing audio pausePlayingAudio:function(win, lose, args) { var id = args[0]; var thisM = Media.get(id); try { thisM.node.pause(); Media.onStatus(id, Media.MEDIA_STATE, Media.MEDIA_PAUSED); } catch (err) { lose("Failed to pause: "+err); } }, // Gets current position in the audio getCurrentPositionAudio:function(win, lose, args) { var id = args[0]; try { var p = (Media.get(id)).node.currentTime; Media.onStatus(id, Media.MEDIA_POSITION, p); win(p); } catch (err) { lose(err); } }, // Start recording audio startRecordingAudio:function(win, lose, args) { var id = args[0]; var src = args[1]; var normalizedSrc = src.replace(/\//g, '\\'); var destPath = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\')); var destFileName = normalizedSrc.replace(destPath + '\\', ''); // Initialize device Media.prototype.mediaCaptureMgr = null; var thisM = (Media.get(id)); var captureInitSettings = new Windows.Media.Capture.MediaCaptureInitializationSettings(); captureInitSettings.streamingCaptureMode = Windows.Media.Capture.StreamingCaptureMode.audio; thisM.mediaCaptureMgr = new Windows.Media.Capture.MediaCapture(); thisM.mediaCaptureMgr.addEventListener("failed", lose); thisM.mediaCaptureMgr.initializeAsync(captureInitSettings).done(function (result) { thisM.mediaCaptureMgr.addEventListener("recordlimitationexceeded", lose); thisM.mediaCaptureMgr.addEventListener("failed", lose); // Start recording Windows.Storage.ApplicationData.current.temporaryFolder.createFileAsync(destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(function (newFile) { recordedFile = newFile; var encodingProfile = null; switch (newFile.fileType) { case '.m4a': encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createM4a(Windows.Media.MediaProperties.AudioEncodingQuality.auto); break; case '.mp3': encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createMp3(Windows.Media.MediaProperties.AudioEncodingQuality.auto); break; case '.wma': encodingProfile = Windows.Media.MediaProperties.MediaEncodingProfile.createWma(Windows.Media.MediaProperties.AudioEncodingQuality.auto); break; default: lose("Invalid file type for record"); break; } thisM.mediaCaptureMgr.startRecordToStorageFileAsync(encodingProfile, newFile).done(win, lose); }, lose); }, lose); }, // Stop recording audio stopRecordingAudio:function(win, lose, args) { var id = args[0]; var thisM = Media.get(id); var normalizedSrc = thisM.src.replace(/\//g, '\\'); var destPath = normalizedSrc.substr(0, normalizedSrc.lastIndexOf('\\')); var destFileName = normalizedSrc.replace(destPath + '\\', ''); thisM.mediaCaptureMgr.stopRecordAsync().done(function () { if (destPath) { Windows.Storage.StorageFolder.getFolderFromPathAsync(destPath).done(function(destFolder) { recordedFile.copyAsync(destFolder, destFileName, Windows.Storage.CreationCollisionOption.replaceExisting).done(win, lose); }, lose); } else { // if path is not defined, we leave recorded file in temporary folder (similar to iOS) win(); } }, lose); }, // Release the media object release:function(win, lose, args) { var id = args[0]; var thisM = Media.get(id); try { delete thisM.node; } catch (err) { lose("Failed to release: "+err); } }, setVolume:function(win, lose, args) { var id = args[0]; var volume = args[1]; var thisM = Media.get(id); thisM.volume = volume; } }; require("cordova/exec/proxy").add("Media",module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var argscheck = require('cordova/argscheck'), channel = require('cordova/channel'), utils = require('cordova/utils'), exec = require('cordova/exec'), cordova = require('cordova'); channel.createSticky('onCordovaInfoReady'); // Tell cordova channel to wait on the CordovaInfoReady event channel.waitForInitialization('onCordovaInfoReady'); /** * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the * phone, etc. * @constructor */ function Device() { this.available = false; this.platform = null; this.version = null; this.uuid = null; this.cordova = null; this.model = null; var me = this; channel.onCordovaReady.subscribe(function() { me.getInfo(function(info) { //ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js //TODO: CB-5105 native implementations should not return info.cordova var buildLabel = cordova.version; me.available = true; me.platform = info.platform; me.version = info.version; me.uuid = info.uuid; me.cordova = buildLabel; me.model = info.model; channel.onCordovaInfoReady.fire(); },function(e) { me.available = false; utils.alert("[ERROR] Error initializing Cordova: " + e); }); }); } /** * Get device info * * @param {Function} successCallback The function to call when the heading data is available * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL) */ Device.prototype.getInfo = function(successCallback, errorCallback) { argscheck.checkArgs('fF', 'Device.getInfo', arguments); exec(successCallback, errorCallback, "Device", "getDeviceInfo", []); }; module.exports = new Device();
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var tizen = require('cordova/platform'); var cordova = require('cordova'); module.exports = { getDeviceInfo: function(success, error) { setTimeout(function () { success({ cordova: tizen.cordovaVersion, platform: 'tizen', model: null, version: null, uuid: null }); }, 0); } }; require("cordova/tizen/commandProxy").add("Device", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ //example UA String for Firefox OS //Mozilla/5.0 (Mobile; rv:26.0) Gecko/26.0 Firefox/26.0 var firefoxos = require('cordova/platform'); var cordova = require('cordova'); //UA parsing not recommended but currently this is the only way to get the Firefox OS version //https://developer.mozilla.org/en-US/docs/Gecko_user_agent_string_reference //Should be replaced when better conversion to Firefox OS Version is available function convertVersionNumber(ver) { var hashVersion = { '18.0': '1.0.1', '18.1': '1.1', '26.0': '1.2', '28.0': '1.3', '30.0': '1.4', '32.0': '2.0' }; var rver = ver; var sStr = ver.substring(0, 4); if (hashVersion[sStr]) { rver = hashVersion[sStr]; } return (rver); } function getVersion() { if (navigator.userAgent.match(/(mobile|tablet)/i)) { var ffVersionArray = (navigator.userAgent.match(/Firefox\/([\d]+\.[\w]?\.?[\w]+)/)); if (ffVersionArray.length === 2) { return (convertVersionNumber(ffVersionArray[1])); } } return (null); } function getModel() { var uaArray = navigator.userAgent.split(/\s*[;)(]\s*/); if (navigator.userAgent.match(/(mobile|tablet)/i)) { if (uaArray.length === 5) { return (uaArray[2]); } } return (null); } module.exports = { getDeviceInfo: function (success, error) { setTimeout(function () { success({ cordova: firefoxos.cordovaVersion, platform: 'firefoxos', model: getModel(), version: getVersion(), uuid: null }); }, 0); } }; require("cordova/firefoxos/commandProxy").add("Device", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ function getModelName () { var modelName = window.qnx.webplatform.device.modelName; //Pre 10.2 (meaning Z10 or Q10) if (typeof modelName === "undefined") { if (window.screen.height === 720 && window.screen.width === 720) { if ( window.matchMedia("(-blackberry-display-technology: -blackberry-display-oled)").matches) { modelName = "Q10"; } else { modelName = "Q5"; } } else if ((window.screen.height === 1280 && window.screen.width === 768) || (window.screen.height === 768 && window.screen.width === 1280)) { modelName = "Z10"; } else { modelName = window.qnx.webplatform.deviceName; } } return modelName; } function getUUID () { var uuid = ""; try { //Must surround by try catch because this will throw if the app is missing permissions uuid = window.qnx.webplatform.device.devicePin; } catch (e) { //DO Nothing } return uuid; } module.exports = { getDeviceInfo: function (success, fail, args, env) { var result = new PluginResult(args, env), modelName = getModelName(), uuid = getUUID(), info = { platform: "blackberry10", version: window.qnx.webplatform.device.scmBundle, model: modelName, uuid: uuid }; result.ok(info); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var cordova = require('cordova'); var exec = require('cordova/exec'); module.exports = { getInfo:function(win,fail,args) { Cordova.exec(function (model, cordova, platform, uuid, version) { win({name: name, model: model, cordova: cordova, platform: platform, uuid: uuid, version: version}); }, null, "com.cordova.Device", "getInfo", []); } }; require("cordova/exec/proxy").add("Device", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var cordova = require('cordova'); var utils = require('cordova/utils'); module.exports = { getDeviceInfo:function(win,fail,args) { // deviceId aka uuid, stored in Windows.Storage.ApplicationData.current.localSettings.values.deviceId var deviceId; var localSettings = Windows.Storage.ApplicationData.current.localSettings; if (localSettings.values.deviceId) { deviceId = localSettings.values.deviceId; } else { deviceId = localSettings.values.deviceId = utils.createUUID(); } setTimeout(function () { win({ platform: "windows8", version: "8", uuid: deviceId, model: window.clientInformation.platform }); }, 0); } }; require("cordova/exec/proxy").add("Device", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'); /** * Provides Android enhanced notification API. */ module.exports = { activityStart : function(title, message) { // If title and message not specified then mimic Android behavior of // using default strings. if (typeof title === "undefined" && typeof message == "undefined") { title = "Busy"; message = 'Please wait...'; } exec(null, null, 'Notification', 'activityStart', [ title, message ]); }, /** * Close an activity dialog */ activityStop : function() { exec(null, null, 'Notification', 'activityStop', []); }, /** * Display a progress dialog with progress bar that goes from 0 to 100. * * @param {String} * title Title of the progress dialog. * @param {String} * message Message to display in the dialog. */ progressStart : function(title, message) { exec(null, null, 'Notification', 'progressStart', [ title, message ]); }, /** * Close the progress dialog. */ progressStop : function() { exec(null, null, 'Notification', 'progressStop', []); }, /** * Set the progress dialog value. * * @param {Number} * value 0-100 */ progressValue : function(value) { exec(null, null, 'Notification', 'progressValue', [ value ]); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ module.exports = function (quantity) { var count = 0, beepObj, play = function () { //create new object every time due to strage playback behaviour beepObj = new Audio('local:///chrome/plugin/org.apache.cordova.dialogs/notification-beep.wav'); beepObj.addEventListener("ended", callback); beepObj.play(); }, callback = function () { if (--count > 0) { play(); } else { delete beepObj; } }; count += quantity || 1; if (count > 0) { play(); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'); var platform = require('cordova/platform'); /** * Provides access to notifications on the device. */ module.exports = { /** * Open a native alert dialog, with a customizable title and button text. * * @param {String} message Message to print in the body of the alert * @param {Function} completeCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Alert) * @param {String} buttonLabel Label of the close button (default: OK) */ alert: function(message, completeCallback, title, buttonLabel) { var _title = (title || "Alert"); var _buttonLabel = (buttonLabel || "OK"); exec(completeCallback, null, "Notification", "alert", [message, _title, _buttonLabel]); }, /** * Open a native confirm dialog, with a customizable title and button text. * The result that the user selects is returned to the result callback. * * @param {String} message Message to print in the body of the alert * @param {Function} resultCallback The callback that is called when user clicks on a button. * @param {String} title Title of the alert dialog (default: Confirm) * @param {Array} buttonLabels Array of the labels of the buttons (default: ['OK', 'Cancel']) */ confirm: function(message, resultCallback, title, buttonLabels) { var _title = (title || "Confirm"); var _buttonLabels = (buttonLabels || ["OK", "Cancel"]); // Strings are deprecated! if (typeof _buttonLabels === 'string') { console.log("Notification.confirm(string, function, string, string) is deprecated. Use Notification.confirm(string, function, string, array)."); } // Some platforms take an array of button label names. // Other platforms take a comma separated list. // For compatibility, we convert to the desired type based on the platform. if (platform.id == "amazon-fireos" || platform.id == "android" || platform.id == "ios" || platform.id == "windowsphone" || platform.id == "firefoxos" || platform.id == "ubuntu") { if (typeof _buttonLabels === 'string') { var buttonLabelString = _buttonLabels; _buttonLabels = _buttonLabels.split(","); // not crazy about changing the var type here } } else { if (Array.isArray(_buttonLabels)) { var buttonLabelArray = _buttonLabels; _buttonLabels = buttonLabelArray.toString(); } } exec(resultCallback, null, "Notification", "confirm", [message, _title, _buttonLabels]); }, /** * Open a native prompt dialog, with a customizable title and button text. * The following results are returned to the result callback: * buttonIndex Index number of the button selected. * input1 The text entered in the prompt dialog box. * * @param {String} message Dialog message to display (default: "Prompt message") * @param {Function} resultCallback The callback that is called when user clicks on a button. * @param {String} title Title of the dialog (default: "Prompt") * @param {Array} buttonLabels Array of strings for the button labels (default: ["OK","Cancel"]) * @param {String} defaultText Textbox input value (default: empty string) */ prompt: function(message, resultCallback, title, buttonLabels, defaultText) { var _message = (message || "Prompt message"); var _title = (title || "Prompt"); var _buttonLabels = (buttonLabels || ["OK","Cancel"]); var _defaultText = (defaultText || ""); exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]); }, /** * Causes the device to beep. * On Android, the default notification ringtone is played "count" times. * * @param {Integer} count The number of beeps. */ beep: function(count) { var defaultedCount = count || 1; exec(null, null, "Notification", "beep", [ defaultedCount ]); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var modulemapper = require('cordova/modulemapper'); var origOpenFunc = modulemapper.getOriginalSymbol(window, 'window.open'); function _empty() {} function modal(message, callback, title, buttonLabels, domObjects) { var mainWindow = window; var modalWindow = origOpenFunc(); var modalDocument = modalWindow.document; modalDocument.write( '<html><head>' + '<link rel="stylesheet" type="text/css" href="/css/index.css" />' + '<link rel="stylesheet" type="text/css" href="/css/notification.css" />' + '</head><body></body></html>'); var box = modalDocument.createElement('form'); box.setAttribute('role', 'dialog'); // prepare and append empty section var section = modalDocument.createElement('section'); box.appendChild(section); // add title var boxtitle = modalDocument.createElement('h1'); boxtitle.appendChild(modalDocument.createTextNode(title)); section.appendChild(boxtitle); // add message var boxMessage = modalDocument.createElement('p'); boxMessage.appendChild(modalDocument.createTextNode(message)); section.appendChild(boxMessage); // inject what's needed if (domObjects) { section.appendChild(domObjects); } // add buttons and assign callbackButton on click var menu = modalDocument.createElement('menu'); box.appendChild(menu); for (var index = 0; index < buttonLabels.length; index++) { addButton(buttonLabels[index], index, (index === 0)); } modalDocument.body.appendChild(box); function addButton(label, index, recommended) { var thisButtonCallback = makeCallbackButton(index + 1); var button = modalDocument.createElement('button'); button.appendChild(modalDocument.createTextNode(label)); button.addEventListener('click', thisButtonCallback, false); if (recommended) { // TODO: default one listens to Enter key button.classList.add('recommend'); } menu.appendChild(button); } // TODO: onUnload listens to the cancel key function onUnload() { var result = 0; if (modalDocument.getElementById('prompt-input')) { result = { input1: '', buttonIndex: 0 } } mainWindow.setTimeout(function() { callback(result); }, 10); }; modalWindow.addEventListener('unload', onUnload, false); // call callback and destroy modal function makeCallbackButton(labelIndex) { return function() { if (modalWindow) { modalWindow.removeEventListener('unload', onUnload, false); modalWindow.close(); } // checking if prompt var promptInput = modalDocument.getElementById('prompt-input'); var response; if (promptInput) { response = { input1: promptInput.value, buttonIndex: labelIndex }; } response = response || labelIndex; callback(response); } } } var Notification = { vibrate: function(milliseconds) { navigator.vibrate(milliseconds); }, alert: function(successCallback, errorCallback, args) { var message = args[0]; var title = args[1]; var _buttonLabels = [args[2]]; var _callback = (successCallback || _empty); modal(message, _callback, title, _buttonLabels); }, confirm: function(successCallback, errorCallback, args) { var message = args[0]; var title = args[1]; var buttonLabels = args[2]; var _callback = (successCallback || _empty); modal(message, _callback, title, buttonLabels); }, prompt: function(successCallback, errorCallback, args) { var message = args[0]; var title = args[1]; var buttonLabels = args[2]; var defaultText = args[3]; var inputParagraph = document.createElement('p'); inputParagraph.classList.add('input'); var inputElement = document.createElement('input'); inputElement.setAttribute('type', 'text'); inputElement.id = 'prompt-input'; if (defaultText) { inputElement.setAttribute('placeholder', defaultText); } inputParagraph.appendChild(inputElement); modal(message, successCallback, title, buttonLabels, inputParagraph); } }; module.exports = Notification; require('cordova/exec/proxy').add('Notification', Notification);
JavaScript
/* * Copyright 2013 Research In Motion Limited. * * 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. */ function showDialog(args, dialogType, result) { //Unpack and map the args var msg = JSON.parse(decodeURIComponent(args[0])), title = JSON.parse(decodeURIComponent(args[1])), btnLabel = JSON.parse(decodeURIComponent(args[2])); if (!Array.isArray(btnLabel)) { //Converts to array for (string) and (string,string, ...) cases btnLabel = btnLabel.split(","); } if (msg && typeof msg === "string") { msg = msg.replace(/^"|"$/g, "").replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } else { result.error("message is undefined"); return; } var messageObj = { title : title, htmlmessage : msg, dialogType : dialogType, optionalButtons : btnLabel }; //TODO replace with getOverlayWebview() when available in webplatform qnx.webplatform.getWebViews()[2].dialog.show(messageObj, function (data) { if (typeof data === "number") { //Confirm dialog call back needs to be called with one-based indexing [1,2,3 etc] result.callbackOk(++data, false); } else { //Prompt dialog callback expects object result.callbackOk({ buttonIndex: data.ok ? 1 : 0, input1: (data.oktext) ? decodeURIComponent(data.oktext) : "" }, false); } }); result.noResult(true); } module.exports = { alert: function (success, fail, args, env) { var result = new PluginResult(args, env); if (Object.keys(args).length < 3) { result.error("Notification action - alert arguments not found."); } else { showDialog(args, "CustomAsk", result); } }, confirm: function (success, fail, args, env) { var result = new PluginResult(args, env); if (Object.keys(args).length < 3) { result.error("Notification action - confirm arguments not found."); } else { showDialog(args, "CustomAsk", result); } }, prompt: function (success, fail, args, env) { var result = new PluginResult(args, env); if (Object.keys(args).length < 3) { result.error("Notification action - prompt arguments not found."); } else { showDialog(args, "JavaScriptPrompt", result); } } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /*global Windows:true */ var cordova = require('cordova'); var isAlertShowing = false; var alertStack = []; module.exports = { alert:function(win, loseX, args) { if (isAlertShowing) { var later = function () { module.exports.alert(win, loseX, args); }; alertStack.push(later); return; } isAlertShowing = true; var message = args[0]; var _title = args[1]; var _buttonLabel = args[2]; var md = new Windows.UI.Popups.MessageDialog(message, _title); md.commands.append(new Windows.UI.Popups.UICommand(_buttonLabel)); md.showAsync().then(function() { isAlertShowing = false; win && win(); if (alertStack.length) { setTimeout(alertStack.shift(), 0); } }); }, confirm:function(win, loseX, args) { if (isAlertShowing) { var later = function () { module.exports.confirm(win, loseX, args); }; alertStack.push(later); return; } isAlertShowing = true; var message = args[0]; var _title = args[1]; var _buttonLabels = args[2]; var result; var btnList = []; function commandHandler (command) { result = btnList[command.label]; } var md = new Windows.UI.Popups.MessageDialog(message, _title); var button = _buttonLabels.split(','); for (var i = 0; i<button.length; i++) { btnList[button[i]] = i+1; md.commands.append(new Windows.UI.Popups.UICommand(button[i],commandHandler)); } md.showAsync().then(function() { isAlertShowing = false; win && win(result); if (alertStack.length) { setTimeout(alertStack.shift(), 0); } }); }, beep:function(winX, loseX, args) { // set a default args if it is not set args = args && args.length ? args : ["1"]; var snd = new Audio('ms-winsoundevent:Notification.Default'); var count = parseInt(args[0]) || 1; snd.msAudioCategory = "Alerts"; var onEvent = function () { if (count > 0) { snd.play(); } else { snd.removeEventListener("ended", onEvent); snd = null; winX && winX(); // notification.js just sends null, but this is future friendly } count--; }; snd.addEventListener("ended", onEvent); onEvent(); } }; require("cordova/exec/proxy").add("Notification",module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * FileError */ function FileError(error) { this.code = error || null; } // File error codes // Found in DOMException FileError.NOT_FOUND_ERR = 1; FileError.SECURITY_ERR = 2; FileError.ABORT_ERR = 3; // Added by File API specification FileError.NOT_READABLE_ERR = 4; FileError.ENCODING_ERR = 5; FileError.NO_MODIFICATION_ALLOWED_ERR = 6; FileError.INVALID_STATE_ERR = 7; FileError.SYNTAX_ERR = 8; FileError.INVALID_MODIFICATION_ERR = 9; FileError.QUOTA_EXCEEDED_ERR = 10; FileError.TYPE_MISMATCH_ERR = 11; FileError.PATH_EXISTS_ERR = 12; module.exports = FileError;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * FileUploadResult * @constructor */ module.exports = function FileUploadResult(size, code, content) { this.bytesSent = size; this.responseCode = code; this.response = content; };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'), FileError = require('./FileError') ; /** * An interface that lists the files and directories in a directory. */ function DirectoryReader(localURL) { this.localURL = localURL || null; this.hasReadEntries = false; } /** * Returns a list of entries from a directory. * * @param {Function} successCallback is called with a list of entries * @param {Function} errorCallback is called with a FileError */ DirectoryReader.prototype.readEntries = function(successCallback, errorCallback) { // If we've already read and passed on this directory's entries, return an empty list. if (this.hasReadEntries) { successCallback([]); return; } var reader = this; var win = typeof successCallback !== 'function' ? null : function(result) { var retVal = []; for (var i=0; i<result.length; i++) { var entry = null; if (result[i].isDirectory) { entry = new (require('./DirectoryEntry'))(); } else if (result[i].isFile) { entry = new (require('./FileEntry'))(); } entry.isDirectory = result[i].isDirectory; entry.isFile = result[i].isFile; entry.name = result[i].name; entry.fullPath = result[i].fullPath; entry.filesystem = new (require('./FileSystem'))(result[i].filesystemName); entry.nativeURL = result[i].nativeURL; retVal.push(entry); } reader.hasReadEntries = true; successCallback(retVal); }; var fail = typeof errorCallback !== 'function' ? null : function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "readEntries", [this.localURL]); }; module.exports = DirectoryReader;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ FILESYSTEM_PROTOCOL = "cdvfile"; module.exports = { __format__: function(fullPath) { if (this.name === 'content') { return 'content:/' + fullPath; } var path = ('/'+this.name+(fullPath[0]==='/'?'':'/')+encodeURI(fullPath)).replace('//','/'); return FILESYSTEM_PROTOCOL + '://localhost' + path; } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var argscheck = require('cordova/argscheck'), exec = require('cordova/exec'), FileError = require('./FileError'), Metadata = require('./Metadata'); /** * Represents a file or directory on the local file system. * * @param isFile * {boolean} true if Entry is a file (readonly) * @param isDirectory * {boolean} true if Entry is a directory (readonly) * @param name * {DOMString} name of the file or directory, excluding the path * leading to it (readonly) * @param fullPath * {DOMString} the absolute full path to the file or directory * (readonly) * @param fileSystem * {FileSystem} the filesystem on which this entry resides * (readonly) * @param nativeURL * {DOMString} an alternate URL which can be used by native * webview controls, for example media players. * (optional, readonly) */ function Entry(isFile, isDirectory, name, fullPath, fileSystem, nativeURL) { this.isFile = !!isFile; this.isDirectory = !!isDirectory; this.name = name || ''; this.fullPath = fullPath || ''; this.filesystem = fileSystem || null; this.nativeURL = nativeURL || null; } /** * Look up the metadata of the entry. * * @param successCallback * {Function} is called with a Metadata object * @param errorCallback * {Function} is called with a FileError */ Entry.prototype.getMetadata = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'Entry.getMetadata', arguments); var success = successCallback && function(entryMetadata) { var metadata = new Metadata({ size: entryMetadata.size, modificationTime: entryMetadata.lastModifiedDate }); successCallback(metadata); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(success, fail, "File", "getFileMetadata", [this.toInternalURL()]); }; /** * Set the metadata of the entry. * * @param successCallback * {Function} is called with a Metadata object * @param errorCallback * {Function} is called with a FileError * @param metadataObject * {Object} keys and values to set */ Entry.prototype.setMetadata = function(successCallback, errorCallback, metadataObject) { argscheck.checkArgs('FFO', 'Entry.setMetadata', arguments); exec(successCallback, errorCallback, "File", "setMetadata", [this.toInternalURL(), metadataObject]); }; /** * Move a file or directory to a new location. * * @param parent * {DirectoryEntry} the directory to which to move this entry * @param newName * {DOMString} new name of the entry, defaults to the current name * @param successCallback * {Function} called with the new DirectoryEntry object * @param errorCallback * {Function} called with a FileError */ Entry.prototype.moveTo = function(parent, newName, successCallback, errorCallback) { argscheck.checkArgs('oSFF', 'Entry.moveTo', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; var filesystem = this.filesystem, srcURL = this.toInternalURL(), // entry name name = newName || this.name, success = function(entry) { if (entry) { if (successCallback) { // create appropriate Entry object var newFSName = entry.filesystemName || (entry.filesystem && entry.filesystem.name); var fs = newFSName ? new FileSystem(newFSName, { name: "", fullPath: "/" }) : new FileSystem(parent.filesystem.name, { name: "", fullPath: "/" }); var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('org.apache.cordova.file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL); successCallback(result); } } else { // no Entry object returned fail && fail(FileError.NOT_FOUND_ERR); } }; // copy exec(success, fail, "File", "moveTo", [srcURL, parent.toInternalURL(), name]); }; /** * Copy a directory to a different location. * * @param parent * {DirectoryEntry} the directory to which to copy the entry * @param newName * {DOMString} new name of the entry, defaults to the current name * @param successCallback * {Function} called with the new Entry object * @param errorCallback * {Function} called with a FileError */ Entry.prototype.copyTo = function(parent, newName, successCallback, errorCallback) { argscheck.checkArgs('oSFF', 'Entry.copyTo', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; var filesystem = this.filesystem, srcURL = this.toInternalURL(), // entry name name = newName || this.name, // success callback success = function(entry) { if (entry) { if (successCallback) { // create appropriate Entry object var newFSName = entry.filesystemName || (entry.filesystem && entry.filesystem.name); var fs = newFSName ? new FileSystem(newFSName, { name: "", fullPath: "/" }) : new FileSystem(parent.filesystem.name, { name: "", fullPath: "/" }); var result = (entry.isDirectory) ? new (require('./DirectoryEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL) : new (require('org.apache.cordova.file.FileEntry'))(entry.name, entry.fullPath, fs, entry.nativeURL); successCallback(result); } } else { // no Entry object returned fail && fail(FileError.NOT_FOUND_ERR); } }; // copy exec(success, fail, "File", "copyTo", [srcURL, parent.toInternalURL(), name]); }; /** * Return a URL that can be passed across the bridge to identify this entry. */ Entry.prototype.toInternalURL = function() { if (this.filesystem && this.filesystem.__format__) { return this.filesystem.__format__(this.fullPath); } }; /** * Return a URL that can be used to identify this entry. * Use a URL that can be used to as the src attribute of a <video> or * <audio> tag. If that is not possible, construct a cdvfile:// URL. */ Entry.prototype.toURL = function() { if (this.nativeURL) { return this.nativeURL; } // fullPath attribute may contain the full URL in the case that // toInternalURL fails. return this.toInternalURL() || "file://localhost" + this.fullPath; }; /** * Backwards-compatibility: In v1.0.0 - 1.0.2, .toURL would only return a * cdvfile:// URL, and this method was necessary to obtain URLs usable by the * webview. * See CB-6051, CB-6106, CB-6117, CB-6152, CB-6199, CB-6201, CB-6243, CB-6249, * and CB-6300. */ Entry.prototype.toNativeURL = function() { console.log("DEPRECATED: Update your code to use 'toURL'"); return this.toURL(); }; /** * Returns a URI that can be used to identify this entry. * * @param {DOMString} mimeType for a FileEntry, the mime type to be used to interpret the file, when loaded through this URI. * @return uri */ Entry.prototype.toURI = function(mimeType) { console.log("DEPRECATED: Update your code to use 'toURL'"); return this.toURL(); }; /** * Remove a file or directory. It is an error to attempt to delete a * directory that is not empty. It is an error to attempt to delete a * root directory of a file system. * * @param successCallback {Function} called with no parameters * @param errorCallback {Function} called with a FileError */ Entry.prototype.remove = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'Entry.remove', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(successCallback, fail, "File", "remove", [this.toInternalURL()]); }; /** * Look up the parent DirectoryEntry of this entry. * * @param successCallback {Function} called with the parent DirectoryEntry object * @param errorCallback {Function} called with a FileError */ Entry.prototype.getParent = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'Entry.getParent', arguments); var fs = this.filesystem; var win = successCallback && function(result) { var DirectoryEntry = require('./DirectoryEntry'); var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL); successCallback(entry); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getParent", [this.toInternalURL()]); }; module.exports = Entry;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * Constructor. * name {DOMString} name of the file, without path information * fullPath {DOMString} the full path of the file, including the name * type {DOMString} mime type * lastModifiedDate {Date} last modified date * size {Number} size of the file in bytes */ var File = function(name, localURL, type, lastModifiedDate, size){ this.name = name || ''; this.localURL = localURL || null; this.type = type || null; this.lastModified = lastModifiedDate || null; // For backwards compatibility, store the timestamp in lastModifiedDate as well this.lastModifiedDate = lastModifiedDate || null; this.size = size || 0; // These store the absolute start and end for slicing the file. this.start = 0; this.end = this.size; }; /** * Returns a "slice" of the file. Since Cordova Files don't contain the actual * content, this really returns a File with adjusted start and end. * Slices of slices are supported. * start {Number} The index at which to start the slice (inclusive). * end {Number} The index at which to end the slice (exclusive). */ File.prototype.slice = function(start, end) { var size = this.end - this.start; var newStart = 0; var newEnd = size; if (arguments.length) { if (start < 0) { newStart = Math.max(size + start, 0); } else { newStart = Math.min(size, start); } } if (arguments.length >= 2) { if (end < 0) { newEnd = Math.max(size + end, 0); } else { newEnd = Math.min(end, size); } } var newFile = new File(this.name, this.localURL, this.type, this.lastModified, this.size); newFile.start = this.start + newStart; newFile.end = this.start + newEnd; return newFile; }; module.exports = File;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var utils = require('cordova/utils'), exec = require('cordova/exec'), Entry = require('./Entry'), FileWriter = require('./FileWriter'), File = require('./File'), FileError = require('./FileError'); /** * An interface representing a file on the file system. * * {boolean} isFile always true (readonly) * {boolean} isDirectory always false (readonly) * {DOMString} name of the file, excluding the path leading to it (readonly) * {DOMString} fullPath the absolute full path to the file (readonly) * {FileSystem} filesystem on which the file resides (readonly) */ var FileEntry = function(name, fullPath, fileSystem, nativeURL) { FileEntry.__super__.constructor.apply(this, [true, false, name, fullPath, fileSystem, nativeURL]); }; utils.extend(FileEntry, Entry); /** * Creates a new FileWriter associated with the file that this FileEntry represents. * * @param {Function} successCallback is called with the new FileWriter * @param {Function} errorCallback is called with a FileError */ FileEntry.prototype.createWriter = function(successCallback, errorCallback) { this.file(function(filePointer) { var writer = new FileWriter(filePointer); if (writer.localURL === null || writer.localURL === "") { errorCallback && errorCallback(new FileError(FileError.INVALID_STATE_ERR)); } else { successCallback && successCallback(writer); } }, errorCallback); }; /** * Returns a File that represents the current state of the file that this FileEntry represents. * * @param {Function} successCallback is called with the new File object * @param {Function} errorCallback is called with a FileError */ FileEntry.prototype.file = function(successCallback, errorCallback) { var localURL = this.toInternalURL(); var win = successCallback && function(f) { var file = new File(f.name, localURL, f.type, f.lastModifiedDate, f.size); successCallback(file); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getFileMetadata", [localURL]); }; module.exports = FileEntry;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ FILESYSTEM_PREFIX = "cdvfile://"; module.exports = { __format__: function(fullPath) { return (FILESYSTEM_PREFIX + this.name + (fullPath[0] === '/' ? '' : '/') + encodeURI(fullPath)); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'), FileError = require('./FileError'), ProgressEvent = require('./ProgressEvent'); /** * This class writes to the mobile device file system. * * For Android: * The root directory is the root of the file system. * To write to the SD card, the file name is "sdcard/my_file.txt" * * @constructor * @param file {File} File object containing file properties * @param append if true write to the end of the file, otherwise overwrite the file */ var FileWriter = function(file) { this.fileName = ""; this.length = 0; if (file) { this.localURL = file.localURL || file; this.length = file.size || 0; } // default is to write at the beginning of the file this.position = 0; this.readyState = 0; // EMPTY this.result = null; // Error this.error = null; // Event handlers this.onwritestart = null; // When writing starts this.onprogress = null; // While writing the file, and reporting partial file data this.onwrite = null; // When the write has successfully completed. this.onwriteend = null; // When the request has completed (either in success or failure). this.onabort = null; // When the write has been aborted. For instance, by invoking the abort() method. this.onerror = null; // When the write has failed (see errors). }; // States FileWriter.INIT = 0; FileWriter.WRITING = 1; FileWriter.DONE = 2; /** * Abort writing file. */ FileWriter.prototype.abort = function() { // check for invalid state if (this.readyState === FileWriter.DONE || this.readyState === FileWriter.INIT) { throw new FileError(FileError.INVALID_STATE_ERR); } // set error this.error = new FileError(FileError.ABORT_ERR); this.readyState = FileWriter.DONE; // If abort callback if (typeof this.onabort === "function") { this.onabort(new ProgressEvent("abort", {"target":this})); } // If write end callback if (typeof this.onwriteend === "function") { this.onwriteend(new ProgressEvent("writeend", {"target":this})); } }; /** * Writes data to the file * * @param data text or blob to be written */ FileWriter.prototype.write = function(data) { var that=this; var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined'); var isBinary; // Check to see if the incoming data is a blob if (data instanceof File || (supportsBinary && data instanceof Blob)) { var fileReader = new FileReader(); fileReader.onload = function() { // Call this method again, with the arraybuffer as argument FileWriter.prototype.write.call(that, this.result); }; if (supportsBinary) { fileReader.readAsArrayBuffer(data); } else { fileReader.readAsText(data); } return; } // Mark data type for safer transport over the binary bridge isBinary = supportsBinary && (data instanceof ArrayBuffer); if (isBinary && ['windowsphone', 'windows8'].indexOf(cordova.platformId) >= 0) { // create a plain array, using the keys from the Uint8Array view so that we can serialize it data = Array.apply(null, new Uint8Array(data)); } // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw new FileError(FileError.INVALID_STATE_ERR); } // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart === "function") { me.onwritestart(new ProgressEvent("writestart", {"target":me})); } // Write file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // position always increases by bytes written because file would be extended me.position += r; // The length of the file is now where we are done writing. me.length = me.position; // DONE state me.readyState = FileWriter.DONE; // If onwrite callback if (typeof me.onwrite === "function") { me.onwrite(new ProgressEvent("write", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // DONE state me.readyState = FileWriter.DONE; // Save error me.error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, "File", "write", [this.localURL, data, this.position, isBinary]); }; /** * Moves the file pointer to the location specified. * * If the offset is a negative number the position of the file * pointer is rewound. If the offset is greater than the file * size the position is set to the end of the file. * * @param offset is the location to move the file pointer to. */ FileWriter.prototype.seek = function(offset) { // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw new FileError(FileError.INVALID_STATE_ERR); } if (!offset && offset !== 0) { return; } // See back from end of file. if (offset < 0) { this.position = Math.max(offset + this.length, 0); } // Offset is bigger than file size so set position // to the end of the file. else if (offset > this.length) { this.position = this.length; } // Offset is between 0 and file size so set the position // to start writing. else { this.position = offset; } }; /** * Truncates the file to the size specified. * * @param size to chop the file at. */ FileWriter.prototype.truncate = function(size) { // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw new FileError(FileError.INVALID_STATE_ERR); } // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart === "function") { me.onwritestart(new ProgressEvent("writestart", {"target":this})); } // Write file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // DONE state me.readyState = FileWriter.DONE; // Update the length of the file me.length = r; me.position = Math.min(me.position, r); // If onwrite callback if (typeof me.onwrite === "function") { me.onwrite(new ProgressEvent("write", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // DONE state me.readyState = FileWriter.DONE; // Save error me.error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, "File", "truncate", [this.localURL, size]); }; module.exports = FileWriter;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'); var channel = require('cordova/channel'); exports.file = { // Read-only directory where the application is installed. applicationDirectory: null, // Root of app's private writable storage applicationStorageDirectory: null, // Where to put app-specific data files. dataDirectory: null, // Cached files that should survive app restarts. // Apps should not rely on the OS to delete files in here. cacheDirectory: null, // Android: the application space on external storage. externalApplicationStorageDirectory: null, // Android: Where to put app-specific data files on external storage. externalDataDirectory: null, // Android: the application cache on external storage. externalCacheDirectory: null, // Android: the external storage (SD card) root. externalRootDirectory: null, // iOS: Temp directory that the OS can clear at will. tempDirectory: null, // iOS: Holds app-specific files that should be synced (e.g. to iCloud). syncedDataDirectory: null, // iOS: Files private to the app, but that are meaningful to other applciations (e.g. Office files) documentsDirectory: null, // BlackBerry10: Files globally available to all apps sharedDirectory: null }; channel.waitForInitialization('onFileSystemPathsReady'); channel.onCordovaReady.subscribe(function() { function after(paths) { for (var k in paths) { exports.file[k] = paths[k]; } channel.initializationComplete('onFileSystemPathsReady'); } exec(after, null, 'File', 'requestAllPaths', []); });
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * remove * * IN: * args * 0 - URL of Entry to remove * OUT: * success - (no args) * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], onSuccess = function (data) { if (typeof success === 'function') { success(data); } }, onFail = function (error) { if (typeof fail === 'function') { if (error && error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { if (fs.fullPath === '/') { onFail(FileError.NO_MODIFICATION_ALLOWED_ERR); } else { fs.nativeEntry.remove(onSuccess, onFail); } }); }, fail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * getFile * * IN: * args * 0 - local filesytem URI for the base directory to search * 1 - file to be created/returned; may be absolute path or relative path * 2 - options object * OUT: * success - FileEntry * fail - FileError code */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'); module.exports = function (success, fail, args) { var uri = args[0] === "/" ? "" : args[0] + "/" + args[1], options = args[2], onSuccess = function (entry) { if (typeof(success) === 'function') { success(entry); } }, onFail = function (code) { if (typeof(fail) === 'function') { fail(code); } }; resolve(function (entry) { if (!entry.isFile) { onFail(FileError.TYPE_MISMATCH_ERR); } else { onSuccess(entry); } }, onFail, [uri, options]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * copyTo * * IN: * args * 0 - URL of entry to copy * 1 - URL of the directory into which to copy/move the entry * 2 - the new name of the entry, defaults to the current name * move - if true, delete the entry which was copied * OUT: * success - entry for the copied file or directory * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args, move) { var uri = args[0], destination = args[1], fileName = args[2], copiedEntry, onSuccess = function () { resolve( function (entry) { if (typeof(success) === 'function') { success(entry); } }, onFail, [destination + copiedEntry.name] ); }, onFail = function (error) { if (typeof(fail) === 'function') { if (error && error.code) { //set error codes expected by mobile spec if (uri === destination) { fail(FileError.INVALID_MODIFICATION_ERR); } else if (error.code === FileError.SECURITY_ERR) { fail(FileError.INVALID_MODIFICATION_ERR); } else { fail(error.code); } } else { fail(error); } } }, writeFile = function (fileEntry, blob, entry) { copiedEntry = fileEntry; fileEntry.createWriter(function (fileWriter) { fileWriter.onwriteend = function () { if (move) { entry.nativeEntry.remove(onSuccess, function () { console.error("Move operation failed. Files may exist at both source and destination"); }); } else { onSuccess(); } }; fileWriter.onerror = onFail; fileWriter.write(blob); }, onFail); }, copyFile = function (entry) { if (entry.nativeEntry.file) { entry.nativeEntry.file(function (file) { var reader = new FileReader()._realReader; reader.onloadend = function (e) { var contents = new Uint8Array(this.result), blob = new Blob([contents]); resolve(function (destEntry) { requestAnimationFrame(function () { destEntry.nativeEntry.getFile(fileName, {create: true}, function (fileEntry) { writeFile(fileEntry, blob, entry); }, onFail); }); }, onFail, [destination]); }; reader.onerror = onFail; reader.readAsArrayBuffer(file); }, onFail); } else { onFail(FileError.INVALID_MODIFICATION_ERR); } }, copyDirectory = function (entry) { resolve(function (destEntry) { if (entry.filesystemName !== destEntry.filesystemName) { console.error("Copying directories between filesystems is not supported on BB10"); onFail(FileError.INVALID_MODIFICATION_ERR); } else { entry.nativeEntry.copyTo(destEntry.nativeEntry, fileName, function () { resolve(function (copiedDir) { copiedEntry = copiedDir; if (move) { entry.nativeEntry.removeRecursively(onSuccess, onFail); } else { onSuccess(); } }, onFail, [destination + fileName]); }, onFail); } }, onFail, [destination]); }; if (destination + fileName === uri) { onFail(FileError.INVALID_MODIFICATION_ERR); } else if (fileName.indexOf(':') > -1) { onFail(FileError.ENCODING_ERR); } else { resolve(function (entry) { if (entry.isDirectory) { copyDirectory(entry); } else { copyFile(entry); } }, onFail, [uri]); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * getFileMetadata * * IN: * args * 0 - local filesytem URI * OUT: * success - file * - name * - type * - lastModifiedDate * - size * fail - FileError code */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], onSuccess = function (entry) { if (typeof(success) === 'function') { success(entry); } }, onFail = function (error) { if (typeof(fail) === 'function') { if (error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (entry) { requestAnimationFrame(function () { if (entry.nativeEntry.file) { entry.nativeEntry.file(onSuccess, onFail); } else { entry.nativeEntry.getMetadata(onSuccess, onFail); } }); }, onFail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * moveTo * * IN: * args * 0 - URL of entry to move * 1 - URL of the directory into which to move the entry * 2 - the new name of the entry, defaults to the current name * OUT: * success - entry for the copied file or directory * fail - FileError */ var copy = cordova.require('org.apache.cordova.file.copyToProxy'); module.exports = function (success, fail, args) { copy(success, fail, args, true); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * readAsBinaryString * * IN: * args * 0 - URL of file to read * 1 - start position * 2 - end position * OUT: * success - BinaryString contents of file * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], start = args[1], end = args[2], onSuccess = function (data) { if (typeof success === 'function') { success(data); } }, onFail = function (error) { if (typeof fail === 'function') { if (error && error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { fs.nativeEntry.file(function (file) { var reader = new FileReader()._realReader; reader.onloadend = function () { onSuccess(this.result.substring(start, end)); }; reader.onerror = onFail; reader.readAsBinaryString(file); }, onFail); }); }, fail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * readAsDataURL * * IN: * args * 0 - URL of file to read * OUT: * success - DataURL representation of file contents * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], onSuccess = function (data) { if (typeof success === 'function') { success(data); } }, onFail = function (error) { if (typeof fail === 'function') { if (error && error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { fs.nativeEntry.file(function (file) { var reader = new FileReader()._realReader; reader.onloadend = function () { onSuccess(this.result); }; reader.onerror = onFail; reader.readAsDataURL(file); }, onFail); }); }, fail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * requestAnimationFrame * * This is used throughout the BB10 File implementation to wrap * native webkit calls. There is a bug in the webkit implementation * which causes callbacks to never return when multiple file system * APIs are called in sequence. This should also make the UI more * responsive during file operations. * * Supported on BB10 OS > 10.1 */ var requestAnimationFrame = window.requestAnimationFrame; if (typeof(requestAnimationFrame) !== 'function') { requestAnimationFrame = function (cb) { cb(); }; } module.exports = requestAnimationFrame;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * readAsText * * IN: * args * 0 - URL of file to read * 1 - encoding * 2 - start position * 3 - end position * OUT: * success - text contents of file * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], start = args[2], end = args[3], onSuccess = function (data) { if (typeof success === 'function') { success(data); } }, onFail = function (error) { if (typeof fail === 'function') { if (error && error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { fs.nativeEntry.file(function (file) { var reader = new FileReader()._realReader; reader.onloadend = function () { var contents = new Uint8Array(this.result).subarray(start, end), blob = new Blob([contents]), textReader = new FileReader()._realReader; textReader.onloadend = function () { onSuccess(this.result); }; textReader.onerror = onFail; textReader.readAsText(blob); }; reader.onerror = onFail; reader.readAsArrayBuffer(file); }, onFail); }); }, fail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * truncate * * IN: * args * 0 - URL of file to truncate * 1 - start position * OUT: * success - new length of file * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], length = args[1], onSuccess = function (data) { if (typeof success === 'function') { success(data.loaded); } }, onFail = function (error) { if (typeof fail === 'function') { if (error && error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { fs.nativeEntry.file(function (file) { var reader = new FileReader()._realReader; reader.onloadend = function () { var contents = new Uint8Array(this.result).subarray(0, length); blob = new Blob([contents]); window.requestAnimationFrame(function () { fs.nativeEntry.createWriter(function (fileWriter) { fileWriter.onwriteend = onSuccess; fileWriter.onerror = onFail; fileWriter.write(blob); }, onFail); }); }; reader.onerror = onFail; reader.readAsArrayBuffer(file); }, onFail); }); }, onFail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * write * * IN: * args * 0 - URL of file to write * 1 - data to write * 2 - offset * 3 - isBinary * OUT: * success - bytes written * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], data = args[1], offset = args[2], isBinary = args[3], onSuccess = function (data) { if (typeof success === 'function') { success(data.loaded); } }, onFail = function (error) { if (typeof fail === 'function') { if (error && error.code) { fail(error.code); } else if (error && error.target && error.target.code) { fail(error.target.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { fs.nativeEntry.createWriter(function (writer) { var blob = new Blob([data]); if (offset) { writer.seek(offset); } writer.onwriteend = onSuccess; writer.onerror = onFail; writer.write(blob); }, onFail); }); }, fail, [uri, { create: true }]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * readEntries * * IN: * args * 0 - URL of directory to list * OUT: * success - Array of Entry objects * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), info = require('org.apache.cordova.file.bb10FileSystemInfo'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'), createEntryFromNative = cordova.require('org.apache.cordova.file.bb10CreateEntryFromNative'); module.exports = function (success, fail, args) { var uri = args[0], onSuccess = function (data) { if (typeof success === 'function') { success(data); } }, onFail = function (error) { if (typeof fail === 'function') { if (error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { var reader = fs.nativeEntry.createReader(), entries = [], readEntries = function() { reader.readEntries(function (results) { if (!results.length) { onSuccess(entries.sort().map(createEntryFromNative)); } else { entries = entries.concat(Array.prototype.slice.call(results || [], 0)); readEntries(); } }, onFail); }; readEntries(); }); }, fail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * getParent * * IN: * args * 0 - local filesytem URI * OUT: * success - DirectoryEntry of parent * fail - FileError code */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], onSuccess = function (entry) { if (typeof(success) === 'function') { success(entry); } }, onFail = function (error) { if (typeof(fail) === 'function') { if (error && error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (entry) { requestAnimationFrame(function () { entry.nativeEntry.getParent(onSuccess, onFail); }); }, onFail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * removeRecursively * * IN: * args * 0 - URL of DirectoryEntry to remove recursively * OUT: * success - (no args) * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], onSuccess = function (data) { if (typeof success === 'function') { success(data); } }, onFail = function (error) { if (typeof fail === 'function') { if (error.code) { if (error.code === FileError.INVALID_MODIFICATION_ERR) { //mobile-spec expects this error code fail(FileError.NO_MODIFICATION_ALLOWED_ERR); } else { fail(error.code); } } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { fs.nativeEntry.removeRecursively(onSuccess, onFail); }); }, fail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * createEntryFromNative * * IN * native - webkit Entry * OUT * returns Cordova entry */ var info = require('org.apache.cordova.file.bb10FileSystemInfo'), fileSystems = require('org.apache.cordova.file.fileSystems'); module.exports = function (native) { var entry = { nativeEntry: native, isDirectory: !!native.isDirectory, isFile: !!native.isFile, name: native.name, fullPath: native.fullPath, filesystemName: native.filesystem.name, nativeURL: native.toURL() }, persistentPath = info.persistentPath.substring(7), temporaryPath = info.temporaryPath.substring(7); //fix bb10 webkit incorrect nativeURL if (native.filesystem.name === 'root') { entry.nativeURL = 'file:///' + native.fullPath; } else if (entry.nativeURL.indexOf('filesystem:local:///persistent/') === 0) { entry.nativeURL = info.persistentPath + native.fullPath; } else if (entry.nativeURL.indexOf('filesystem:local:///temporary') === 0) { entry.nativeURL = info.temporaryPath + native.fullPath; } //translate file system name from bb10 webkit if (entry.filesystemName === 'local__0:Persistent' || entry.fullPath.indexOf(persistentPath) !== -1) { entry.filesystemName = 'persistent'; } else if (entry.filesystemName === 'local__0:Temporary' || entry.fullPath.indexOf(temporaryPath) !== -1) { entry.filesystemName = 'temporary'; } //add file system property (will be called sync) fileSystems.getFs(entry.filesystemName, function (fs) { entry.filesystem = fs; }); //set root on fullPath for persistent / temporary locations entry.fullPath = entry.fullPath.replace(persistentPath, ""); entry.fullPath = entry.fullPath.replace(temporaryPath, ""); //set trailing slash on directory if (entry.isDirectory && entry.fullPath.substring(entry.fullPath.length - 1) !== '/') { entry.fullPath += '/'; } if (entry.isDirectory && entry.nativeURL.substring(entry.nativeURL.length - 1) !== '/') { entry.nativeURL += '/'; } //encode URL entry.nativeURL = window.encodeURI(entry.nativeURL); return entry; };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * requestAllFileSystems * * IN - no arguments * OUT * success - Array of FileSystems * - filesystemName * - fullPath * - name * - nativeURL */ var info = require('org.apache.cordova.file.bb10FileSystemInfo'); module.exports = function (success, fail, args) { success([ { filesystemName: 'persistent', name: 'persistent', fullPath: '/', nativeURL: info.persistentPath + '/' }, { filesystemName: 'temporary', name: 'temporary', fullPath: '/', nativeURL: info.temporaryPath + '/' }, { filesystemName: 'root', name: 'root', fullPath: '/', nativeURL: 'file:///' } ]); }
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * getDirectory * * IN: * args * 0 - local filesytem URI for the base directory to search * 1 - directory to be created/returned; may be absolute path or relative path * 2 - options object * OUT: * success - DirectoryEntry * fail - FileError code */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0] === "/" ? "" : args[0], dir = args[1], options = args[2], onSuccess = function (entry) { if (typeof(success) === 'function') { success(entry); } }, onFail = function (error) { if (typeof(fail) === 'function') { if (error && error.code) { //set error codes expected by mobile-spec tests if (error.code === FileError.INVALID_MODIFICATION_ERR && options.exclusive) { fail(FileError.PATH_EXISTS_ERR); } else if ( error.code === FileError.NOT_FOUND_ERR && dir.indexOf(':') > 0) { fail(FileError.ENCODING_ERR); } else { fail(error.code); } } else { fail(error); } } }; resolve(function (entry) { requestAnimationFrame(function () { entry.nativeEntry.getDirectory(dir, options, function (nativeEntry) { resolve(function (entry) { onSuccess(entry); }, onFail, [uri + "/" + dir]); }, onFail); }); }, onFail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * FileSystem * * Translate temporary / persistent / root file paths */ var info = require("org.apache.cordova.file.bb10FileSystemInfo"); module.exports = { __format__: function(fullPath) { switch (this.name) { case 'temporary': path = info.temporaryPath + fullPath; break; case 'persistent': path = info.persistentPath + fullPath; break; case 'root': path = 'file://' + fullPath; break; } return window.encodeURI(path); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * readAsArrayBuffer * * IN: * args * 0 - URL of file to read * 1 - start position * 2 - end position * OUT: * success - ArrayBuffer of file * fail - FileError */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'); module.exports = function (success, fail, args) { var uri = args[0], start = args[1], end = args[2], onSuccess = function (data) { if (typeof success === 'function') { success(data); } }, onFail = function (error) { if (typeof fail === 'function') { if (error && error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (fs) { requestAnimationFrame(function () { fs.nativeEntry.file(function (file) { var reader = new FileReader()._realReader; reader.onloadend = function () { onSuccess(this.result.slice(start, end)); }; reader.onerror = onFail; reader.readAsArrayBuffer(file); }, onFail); }); }, fail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * FileProxy * * Register all File exec calls to be handled by proxy */ module.exports = { copyTo: require('org.apache.cordova.file.copyToProxy'), getDirectory: require('org.apache.cordova.file.getDirectoryProxy'), getFile: require('org.apache.cordova.file.getFileProxy'), getFileMetadata: require('org.apache.cordova.file.getFileMetadataProxy'), getMetadata: require('org.apache.cordova.file.getMetadataProxy'), getParent: require('org.apache.cordova.file.getParentProxy'), moveTo: require('org.apache.cordova.file.moveToProxy'), readAsArrayBuffer: require('org.apache.cordova.file.readAsArrayBufferProxy'), readAsBinaryString: require('org.apache.cordova.file.readAsBinaryStringProxy'), readAsDataURL: require('org.apache.cordova.file.readAsDataURLProxy'), readAsText: require('org.apache.cordova.file.readAsTextProxy'), readEntries: require('org.apache.cordova.file.readEntriesProxy'), remove: require('org.apache.cordova.file.removeProxy'), removeRecursively: require('org.apache.cordova.file.removeRecursivelyProxy'), resolveLocalFileSystemURI: require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'), requestAllFileSystems: require('org.apache.cordova.file.requestAllFileSystemsProxy'), requestFileSystem: require('org.apache.cordova.file.requestFileSystemProxy'), setMetadata: require('org.apache.cordova.file.setMetadataProxy'), truncate: require('org.apache.cordova.file.truncateProxy'), write: require('org.apache.cordova.file.writeProxy') }; require('cordova/exec/proxy').add('File', module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * info * * persistentPath - full path to app sandboxed persistent storage * temporaryPath - full path to app sandboxed temporary storage * localPath - full path to app source (www dir) * MAX_SIZE - maximum size for filesystem request */ var info = { persistentPath: "", temporaryPath: "", localPath: "", MAX_SIZE: 64 * 1024 * 1024 * 1024 }; cordova.exec( function (path) { info.persistentPath = 'file://' + path + '/webviews/webfs/persistent/local__0'; info.temporaryPath = 'file://' + path + '/webviews/webfs/temporary/local__0'; info.localPath = path.replace('/data', '/app/native'); }, function () { console.error('Unable to determine local storage file path'); }, 'File', 'getHomePath', false ); module.exports = info;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * resolveLocalFileSystemURI * * IN * args * 0 - escaped local filesystem URI * 1 - options (standard HTML5 file system options) * 2 - size * OUT * success - Entry object * - isDirectory * - isFile * - name * - fullPath * - nativeURL * - fileSystemName * fail - FileError code */ var info = require('org.apache.cordova.file.bb10FileSystemInfo'), requestAnimationFrame = cordova.require('org.apache.cordova.file.bb10RequestAnimationFrame'), createEntryFromNative = require('org.apache.cordova.file.bb10CreateEntryFromNative'), SANDBOXED = true, UNSANDBOXED = false; module.exports = function (success, fail, args) { var request = args[0], options = args[1], size = args[2]; if (request) { request = decodeURIComponent(request); if (request.indexOf('?') > -1) { //bb10 does not support params; strip them off request = request.substring(0, request.indexOf('?')); } if (request.indexOf('file://localhost/') === 0) { //remove localhost prefix request = request.replace('file://localhost/', 'file:///'); } //requests to sandboxed locations should use cdvfile request = request.replace(info.persistentPath, 'cdvfile://localhost/persistent'); request = request.replace(info.temporaryPath, 'cdvfile://localhost/temporary'); //pick appropriate handler if (request.indexOf('file:///') === 0) { resolveFile(success, fail, request, options); } else if (request.indexOf('cdvfile://localhost/') === 0) { resolveCdvFile(success, fail, request, options, size); } else if (request.indexOf('local:///') === 0) { resolveLocal(success, fail, request, options); } else { fail(FileError.ENCODING_ERR); } } else { fail(FileError.NOT_FOUND_ERR); } }; //resolve file:/// function resolveFile(success, fail, request, options) { var path = request.substring(7); resolve(success, fail, path, window.PERSISTENT, UNSANDBOXED, options); } //resolve cdvfile://localhost/filesystemname/ function resolveCdvFile(success, fail, request, options, size) { var components = /cdvfile:\/\/localhost\/([^\/]+)\/(.*)/.exec(request), fsType = components[1], path = components[2]; if (fsType === 'persistent') { resolve(success, fail, path, window.PERSISTENT, SANDBOXED, options, size); } else if (fsType === 'temporary') { resolve(success, fail, path, window.TEMPORARY, SANDBOXED, options, size); } else if (fsType === 'root') { resolve(success, fail, path, window.PERSISTENT, UNSANDBOXED, options); } else { fail(FileError.NOT_FOUND_ERR); } } //resolve local:/// function resolveLocal(success, fail, request, options) { var path = localPath + request.substring(8); resolve(success, fail, path, window.PERSISTENT, UNSANDBOXED, options); } //validate parameters and set sandbox function resolve(success, fail, path, fsType, sandbox, options, size) { options = options || { create: false }; size = size || info.MAX_SIZE; if (size > info.MAX_SIZE) { //bb10 does not respect quota; fail at unreasonably large size fail(FileError.QUOTA_EXCEEDED_ERR); } else if (path.indexOf(':') > -1) { //files with : character are not valid in Cordova apps fail(FileError.ENCODING_ERR); } else { requestAnimationFrame(function () { cordova.exec(function () { requestAnimationFrame(function () { resolveNative(success, fail, path, fsType, options, size); }); }, fail, 'File', 'setSandbox', [sandbox], false); }); } } //find path using webkit file system function resolveNative(success, fail, path, fsType, options, size) { window.webkitRequestFileSystem( fsType, size, function (fs) { if (path === '') { //no path provided, call success with root file system success(createEntryFromNative(fs.root)); } else { //otherwise attempt to resolve as file fs.root.getFile( path, options, function (entry) { success(createEntryFromNative(entry)); }, function (fileError) { //file not found, attempt to resolve as directory fs.root.getDirectory( path, options, function (entry) { success(createEntryFromNative(entry)); }, function (dirError) { //path cannot be resolved if (fileError.code === FileError.INVALID_MODIFICATION_ERR && options.exclusive) { //mobile-spec expects this error code fail(FileError.PATH_EXISTS_ERR); } else { fail(FileError.NOT_FOUND_ERR); } } ); } ); } } ); }
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * getMetadata * * IN: * args * 0 - local filesytem URI * OUT: * success - metadata * fail - FileError code */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'); module.exports = function (success, fail, args) { var uri = args[0], onSuccess = function (entry) { if (typeof(success) === 'function') { success(entry); } }, onFail = function (error) { if (typeof(fail) === 'function') { if (error.code) { fail(error.code); } else { fail(error); } } }; resolve(function (entry) { entry.nativeEntry.getMetadata(onSuccess, onFail); }, onFail, [uri]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * setMetadata * * BB10 OS does not support setting file metadata via HTML5 File System */ module.exports = function (success, fail, args) { console.error("setMetadata not supported on BB10", arguments); if (typeof(fail) === 'function') { fail(); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /* * requestFileSystem * * IN: * args * 0 - type (TEMPORARY = 0, PERSISTENT = 1) * 1 - size * OUT: * success - FileSystem object * - name - the human readable directory name * - root - DirectoryEntry object * - isDirectory * - isFile * - name * - fullPath * fail - FileError code */ var resolve = cordova.require('org.apache.cordova.file.resolveLocalFileSystemURIProxy'); module.exports = function (success, fail, args) { var fsType = args[0] === 0 ? 'temporary' : 'persistent', size = args[1], onSuccess = function (fs) { var directory = { name: fsType, root: fs }; success(directory); }; resolve(onSuccess, fail, ['cdvfile://localhost/' + fsType + '/', undefined, size]); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * Options to customize the HTTP request used to upload files. * @constructor * @param fileKey {String} Name of file request parameter. * @param fileName {String} Filename to be used by the server. Defaults to image.jpg. * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg. * @param params {Object} Object with key: value params to send to the server. */ var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers, httpMethod) { this.fileKey = fileKey || null; this.fileName = fileName || null; this.mimeType = mimeType || null; this.headers = headers || null; this.httpMethod = httpMethod || null; if(params && typeof params != typeof "") { var arrParams = []; for(var v in params) { arrParams.push(v + "=" + params[v]); } this.params = encodeURIComponent(arrParams.join("&")); } else { this.params = params || null; } }; module.exports = FileUploadOptions;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * Information about the state of the file or directory * * {Date} modificationTime (readonly) */ var Metadata = function(metadata) { if (typeof metadata == "object") { this.modificationTime = new Date(metadata.modificationTime); this.size = metadata.size || 0; } else if (typeof metadata == "undefined") { this.modificationTime = null; this.size = 0; } else { /* Backwards compatiblity with platforms that only return a timestamp */ this.modificationTime = new Date(metadata); } }; module.exports = Metadata;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var DirectoryEntry = require('./DirectoryEntry'); /** * An interface representing a file system * * @constructor * {DOMString} name the unique name of the file system (readonly) * {DirectoryEntry} root directory of the file system (readonly) */ var FileSystem = function(name, root) { this.name = name; if (root) { this.root = new DirectoryEntry(root.name, root.fullPath, this, root.nativeURL); } else { this.root = new DirectoryEntry(this.name, '/', this); } }; FileSystem.prototype.__format__ = function(fullPath) { return fullPath; }; FileSystem.prototype.toJSON = function() { return "<FileSystem: " + this.name + ">"; }; module.exports = FileSystem;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'), FileError = require('./FileError'), ProgressEvent = require('./ProgressEvent'); function write(data) { var that=this; var supportsBinary = (typeof window.Blob !== 'undefined' && typeof window.ArrayBuffer !== 'undefined'); var isBinary; // Check to see if the incoming data is a blob if (data instanceof File || (supportsBinary && data instanceof Blob)) { var fileReader = new FileReader(); fileReader.onload = function() { // Call this method again, with the arraybuffer as argument FileWriter.prototype.write.call(that, this.result); }; if (supportsBinary) { fileReader.readAsArrayBuffer(data); } else { fileReader.readAsText(data); } return; } // Mark data type for safer transport over the binary bridge isBinary = supportsBinary && (data instanceof ArrayBuffer); // Throw an exception if we are already writing a file if (this.readyState === FileWriter.WRITING) { throw new FileError(FileError.INVALID_STATE_ERR); } // WRITING state this.readyState = FileWriter.WRITING; var me = this; // If onwritestart callback if (typeof me.onwritestart === "function") { me.onwritestart(new ProgressEvent("writestart", {"target":me})); } if (data instanceof ArrayBuffer || data.buffer instanceof ArrayBuffer) { data = new Uint8Array(data); var binary = ""; for (var i = 0; i < data.byteLength; i++) { binary += String.fromCharCode(data[i]); } data = binary; } var prefix = "file://localhost"; var path = this.localURL; if (path.substr(0, prefix.length) == prefix) { path = path.substr(prefix.length); } // Write file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // position always increases by bytes written because file would be extended me.position += r; // The length of the file is now where we are done writing. me.length = me.position; // DONE state me.readyState = FileWriter.DONE; // If onwrite callback if (typeof me.onwrite === "function") { me.onwrite(new ProgressEvent("write", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me.readyState === FileWriter.DONE) { return; } // DONE state me.readyState = FileWriter.DONE; // Save error me.error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {"target":me})); } // If onwriteend callback if (typeof me.onwriteend === "function") { me.onwriteend(new ProgressEvent("writeend", {"target":me})); } }, "File", "write", [path, data, this.position, isBinary]); }; module.exports = { write: write }; require("cordova/exec/proxy").add("FileWriter", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ FILESYSTEM_PROTOCOL = "cdvfile"; module.exports = { __format__: function(fullPath) { if (this.name === 'content') { return 'content:/' + fullPath; } var path = ('/' + this.name + (fullPath[0] === '/' ? '' : '/') + encodeURI(fullPath)).replace('//','/'); return FILESYSTEM_PROTOCOL + '://localhost' + path; } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var fsMap = null; var FileSystem = require('./FileSystem'); var LocalFileSystem = require('./LocalFileSystem'); var exec = require('cordova/exec'); var requestFileSystem = function(type, size, successCallback) { var success = function(file_system) { if (file_system) { if (successCallback) { fs = new FileSystem(file_system.name, file_system.root); successCallback(fs); } } }; exec(success, null, "File", "requestFileSystem", [type, size]); }; require('./fileSystems').getFs = function(name, callback) { if (fsMap) { callback(fsMap[name]); } else { requestFileSystem(LocalFileSystem.PERSISTENT, 1, function(fs) { requestFileSystem(LocalFileSystem.TEMPORARY, 1, function(tmp) { fsMap = {}; fsMap[tmp.name] = tmp; fsMap[fs.name] = fs; callback(fsMap[name]); }); }); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ // If ProgressEvent exists in global context, use it already, otherwise use our own polyfill // Feature test: See if we can instantiate a native ProgressEvent; // if so, use that approach, // otherwise fill-in with our own implementation. // // NOTE: right now we always fill in with our own. Down the road would be nice if we can use whatever is native in the webview. var ProgressEvent = (function() { /* var createEvent = function(data) { var event = document.createEvent('Events'); event.initEvent('ProgressEvent', false, false); if (data) { for (var i in data) { if (data.hasOwnProperty(i)) { event[i] = data[i]; } } if (data.target) { // TODO: cannot call <some_custom_object>.dispatchEvent // need to first figure out how to implement EventTarget } } return event; }; try { var ev = createEvent({type:"abort",target:document}); return function ProgressEvent(type, data) { data.type = type; return createEvent(data); }; } catch(e){ */ return function ProgressEvent(type, dict) { this.type = type; this.bubbles = false; this.cancelBubble = false; this.cancelable = false; this.lengthComputable = false; this.loaded = dict && dict.loaded ? dict.loaded : 0; this.total = dict && dict.total ? dict.total : 0; this.target = dict && dict.target ? dict.target : null; }; //} })(); module.exports = ProgressEvent;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var argscheck = require('cordova/argscheck'), DirectoryEntry = require('./DirectoryEntry'), FileEntry = require('./FileEntry'), FileError = require('./FileError'), exec = require('cordova/exec'); var fileSystems = require('./fileSystems'); /** * Look up file system Entry referred to by local URI. * @param {DOMString} uri URI referring to a local file or directory * @param successCallback invoked with Entry object corresponding to URI * @param errorCallback invoked if error occurs retrieving file system entry */ module.exports.resolveLocalFileSystemURL = function(uri, successCallback, errorCallback) { argscheck.checkArgs('sFF', 'resolveLocalFileSystemURI', arguments); // error callback var fail = function(error) { errorCallback && errorCallback(new FileError(error)); }; // sanity check for 'not:valid:filename' or '/not:valid:filename' // file.spec.12 window.resolveLocalFileSystemURI should error (ENCODING_ERR) when resolving invalid URI with leading /. if(!uri || uri.split(":").length > 2) { setTimeout( function() { fail(FileError.ENCODING_ERR); },0); return; } // if successful, return either a file or directory entry var success = function(entry) { if (entry) { if (successCallback) { // create appropriate Entry object var fsName = entry.filesystemName || (entry.filesystem && entry.filesystem.name) || (entry.filesystem == window.PERSISTENT ? 'persistent' : 'temporary'); fileSystems.getFs(fsName, function(fs) { if (!fs) { fs = new FileSystem(fsName, {name:"", fullPath:"/"}); } var result = (entry.isDirectory) ? new DirectoryEntry(entry.name, entry.fullPath, fs, entry.nativeURL) : new FileEntry(entry.name, entry.fullPath, fs, entry.nativeURL); successCallback(result); }); } } else { // no Entry object returned fail(FileError.NOT_FOUND_ERR); } }; exec(success, fail, "File", "resolveLocalFileSystemURI", [uri]); }; module.exports.resolveLocalFileSystemURI = function() { console.log("resolveLocalFileSystemURI is deprecated. Please call resolveLocalFileSystemURL instead."); module.exports.resolveLocalFileSystemURL.apply(this, arguments); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * Options to customize the HTTP request used to upload files. * @constructor * @param fileKey {String} Name of file request parameter. * @param fileName {String} Filename to be used by the server. Defaults to image.jpg. * @param mimeType {String} Mimetype of the uploaded file. Defaults to image/jpeg. * @param params {Object} Object with key: value params to send to the server. * @param headers {Object} Keys are header names, values are header values. Multiple * headers of the same name are not supported. */ var FileUploadOptions = function(fileKey, fileName, mimeType, params, headers, httpMethod) { this.fileKey = fileKey || null; this.fileName = fileName || null; this.mimeType = mimeType || null; this.params = params || null; this.headers = headers || null; this.httpMethod = httpMethod || null; }; module.exports = FileUploadOptions;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ exports.TEMPORARY = 0; exports.PERSISTENT = 1;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ /** * Supplies arguments to methods that lookup or create files and directories. * * @param create * {boolean} file or directory if it doesn't exist * @param exclusive * {boolean} used with create; if true the command will fail if * target path exists */ function Flags(create, exclusive) { this.create = create || false; this.exclusive = exclusive || false; } module.exports = Flags;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ // Overridden by Android, BlackBerry 10 and iOS to populate fsMap. module.exports.getFs = function(name, callback) { callback(null); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'), Entry = require('./Entry'), FileError = require('./FileError'), DirectoryReader = require('./DirectoryReader'); /** * An interface representing a directory on the file system. * * {boolean} isFile always false (readonly) * {boolean} isDirectory always true (readonly) * {DOMString} name of the directory, excluding the path leading to it (readonly) * {DOMString} fullPath the absolute full path to the directory (readonly) * {FileSystem} filesystem on which the directory resides (readonly) */ var DirectoryEntry = function(name, fullPath, fileSystem, nativeURL) { // add trailing slash if it is missing if ((fullPath) && !/\/$/.test(fullPath)) { fullPath += "/"; } // add trailing slash if it is missing if (nativeURL && !/\/$/.test(nativeURL)) { nativeURL += "/"; } DirectoryEntry.__super__.constructor.call(this, false, true, name, fullPath, fileSystem, nativeURL); }; utils.extend(DirectoryEntry, Entry); /** * Creates a new DirectoryReader to read entries from this directory */ DirectoryEntry.prototype.createReader = function() { return new DirectoryReader(this.toInternalURL()); }; /** * Creates or looks up a directory * * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a directory * @param {Flags} options to create or exclusively create the directory * @param {Function} successCallback is called with the new entry * @param {Function} errorCallback is called with a FileError */ DirectoryEntry.prototype.getDirectory = function(path, options, successCallback, errorCallback) { argscheck.checkArgs('sOFF', 'DirectoryEntry.getDirectory', arguments); var fs = this.filesystem; var win = successCallback && function(result) { var entry = new DirectoryEntry(result.name, result.fullPath, fs, result.nativeURL); successCallback(entry); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getDirectory", [this.toInternalURL(), path, options]); }; /** * Deletes a directory and all of it's contents * * @param {Function} successCallback is called with no parameters * @param {Function} errorCallback is called with a FileError */ DirectoryEntry.prototype.removeRecursively = function(successCallback, errorCallback) { argscheck.checkArgs('FF', 'DirectoryEntry.removeRecursively', arguments); var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(successCallback, fail, "File", "removeRecursively", [this.toInternalURL()]); }; /** * Creates or looks up a file * * @param {DOMString} path either a relative or absolute path from this directory in which to look up or create a file * @param {Flags} options to create or exclusively create the file * @param {Function} successCallback is called with the new entry * @param {Function} errorCallback is called with a FileError */ DirectoryEntry.prototype.getFile = function(path, options, successCallback, errorCallback) { argscheck.checkArgs('sOFF', 'DirectoryEntry.getFile', arguments); var fs = this.filesystem; var win = successCallback && function(result) { var FileEntry = require('./FileEntry'); var entry = new FileEntry(result.name, result.fullPath, fs, result.nativeURL); successCallback(entry); }; var fail = errorCallback && function(code) { errorCallback(new FileError(code)); }; exec(win, fail, "File", "getFile", [this.toInternalURL(), path, options]); }; module.exports = DirectoryEntry;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'), modulemapper = require('cordova/modulemapper'), utils = require('cordova/utils'), File = require('./File'), FileError = require('./FileError'), ProgressEvent = require('./ProgressEvent'), origFileReader = modulemapper.getOriginalSymbol(window, 'FileReader'); /** * This class reads the mobile device file system. * * For Android: * The root directory is the root of the file system. * To read from the SD card, the file name is "sdcard/my_file.txt" * @constructor */ var FileReader = function() { this._readyState = 0; this._error = null; this._result = null; this._localURL = ''; this._realReader = origFileReader ? new origFileReader() : {}; }; // States FileReader.EMPTY = 0; FileReader.LOADING = 1; FileReader.DONE = 2; utils.defineGetter(FileReader.prototype, 'readyState', function() { return this._localURL ? this._readyState : this._realReader.readyState; }); utils.defineGetter(FileReader.prototype, 'error', function() { return this._localURL ? this._error: this._realReader.error; }); utils.defineGetter(FileReader.prototype, 'result', function() { return this._localURL ? this._result: this._realReader.result; }); function defineEvent(eventName) { utils.defineGetterSetter(FileReader.prototype, eventName, function() { return this._realReader[eventName] || null; }, function(value) { this._realReader[eventName] = value; }); } defineEvent('onloadstart'); // When the read starts. defineEvent('onprogress'); // While reading (and decoding) file or fileBlob data, and reporting partial file data (progress.loaded/progress.total) defineEvent('onload'); // When the read has successfully completed. defineEvent('onerror'); // When the read has failed (see errors). defineEvent('onloadend'); // When the request has completed (either in success or failure). defineEvent('onabort'); // When the read has been aborted. For instance, by invoking the abort() method. function initRead(reader, file) { // Already loading something if (reader.readyState == FileReader.LOADING) { throw new FileError(FileError.INVALID_STATE_ERR); } reader._result = null; reader._error = null; reader._readyState = FileReader.LOADING; if (typeof file.localURL == 'string') { reader._localURL = file.localURL; } else { reader._localURL = ''; return true; } reader.onloadstart && reader.onloadstart(new ProgressEvent("loadstart", {target:reader})); } /** * Abort reading file. */ FileReader.prototype.abort = function() { if (origFileReader && !this._localURL) { return this._realReader.abort(); } this._result = null; if (this._readyState == FileReader.DONE || this._readyState == FileReader.EMPTY) { return; } this._readyState = FileReader.DONE; // If abort callback if (typeof this.onabort === 'function') { this.onabort(new ProgressEvent('abort', {target:this})); } // If load end callback if (typeof this.onloadend === 'function') { this.onloadend(new ProgressEvent('loadend', {target:this})); } }; /** * Read text file. * * @param file {File} File object containing file properties * @param encoding [Optional] (see http://www.iana.org/assignments/character-sets) */ FileReader.prototype.readAsText = function(file, encoding) { if (initRead(this, file)) { return this._realReader.readAsText(file, encoding); } // Default encoding is UTF-8 var enc = encoding ? encoding : "UTF-8"; var me = this; var execArgs = [this._localURL, enc, file.start, file.end]; // Read file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; // Save result me._result = r; // If onload callback if (typeof me.onload === "function") { me.onload(new ProgressEvent("load", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; // null result me._result = null; // Save error me._error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, "File", "readAsText", execArgs); }; /** * Read file and return data as a base64 encoded data url. * A data url is of the form: * data:[<mediatype>][;base64],<data> * * @param file {File} File object containing file properties */ FileReader.prototype.readAsDataURL = function(file) { if (initRead(this, file)) { return this._realReader.readAsDataURL(file); } var me = this; var execArgs = [this._localURL, file.start, file.end]; // Read file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; // Save result me._result = r; // If onload callback if (typeof me.onload === "function") { me.onload(new ProgressEvent("load", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; me._result = null; // Save error me._error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, "File", "readAsDataURL", execArgs); }; /** * Read file and return data as a binary data. * * @param file {File} File object containing file properties */ FileReader.prototype.readAsBinaryString = function(file) { if (initRead(this, file)) { return this._realReader.readAsBinaryString(file); } var me = this; var execArgs = [this._localURL, file.start, file.end]; // Read file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; me._result = r; // If onload callback if (typeof me.onload === "function") { me.onload(new ProgressEvent("load", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; me._result = null; // Save error me._error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, "File", "readAsBinaryString", execArgs); }; /** * Read file and return data as a binary data. * * @param file {File} File object containing file properties */ FileReader.prototype.readAsArrayBuffer = function(file) { if (initRead(this, file)) { return this._realReader.readAsArrayBuffer(file); } var me = this; var execArgs = [this._localURL, file.start, file.end]; // Read file exec( // Success callback function(r) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; me._result = r; // If onload callback if (typeof me.onload === "function") { me.onload(new ProgressEvent("load", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, // Error callback function(e) { // If DONE (cancelled), then don't do anything if (me._readyState === FileReader.DONE) { return; } // DONE state me._readyState = FileReader.DONE; me._result = null; // Save error me._error = new FileError(e); // If onerror callback if (typeof me.onerror === "function") { me.onerror(new ProgressEvent("error", {target:me})); } // If onloadend callback if (typeof me.onloadend === "function") { me.onloadend(new ProgressEvent("loadend", {target:me})); } }, "File", "readAsArrayBuffer", execArgs); }; module.exports = FileReader;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ FILESYSTEM_PROTOCOL = "cdvfile"; module.exports = { __format__: function(fullPath) { var path = ('/'+this.name+(fullPath[0]==='/'?'':'/')+encodeURI(fullPath)).replace('//','/'); return FILESYSTEM_PROTOCOL + '://localhost' + path; } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var argscheck = require('cordova/argscheck'), FileError = require('./FileError'), FileSystem = require('./FileSystem'), exec = require('cordova/exec'); var fileSystems = require('./fileSystems'); /** * Request a file system in which to store application data. * @param type local file system type * @param size indicates how much storage space, in bytes, the application expects to need * @param successCallback invoked with a FileSystem object * @param errorCallback invoked if error occurs retrieving file system */ var requestFileSystem = function(type, size, successCallback, errorCallback) { argscheck.checkArgs('nnFF', 'requestFileSystem', arguments); var fail = function(code) { errorCallback && errorCallback(new FileError(code)); }; if (type < 0) { fail(FileError.SYNTAX_ERR); } else { // if successful, return a FileSystem object var success = function(file_system) { if (file_system) { if (successCallback) { fileSystems.getFs(file_system.name, function(fs) { if (!fs) { fs = new FileSystem(file_system.name, file_system.root); } successCallback(fs); }); } } else { // no FileSystem object returned fail(FileError.NOT_FOUND_ERR); } }; exec(success, fail, "File", "requestFileSystem", [type, size]); } }; module.exports = requestFileSystem;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ // Map of fsName -> FileSystem. var fsMap = null; var FileSystem = require('./FileSystem'); var exec = require('cordova/exec'); // Overridden by Android, BlackBerry 10 and iOS to populate fsMap. require('./fileSystems').getFs = function(name, callback) { if (fsMap) { callback(fsMap[name]); } else { exec(success, null, "File", "requestAllFileSystems", []); function success(response) { fsMap = {}; for (var i = 0; i < response.length; ++i) { var fsRoot = response[i]; var fs = new FileSystem(fsRoot.filesystemName, fsRoot); fsMap[fs.name] = fs; } callback(fsMap[name]); } } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ exports.defineAutoTests = function () { describe('File API', function () { // Adding a Jasmine helper matcher, to report errors when comparing to FileError better. var fileErrorMap = { 1 : 'NOT_FOUND_ERR', 2 : 'SECURITY_ERR', 3 : 'ABORT_ERR', 4 : 'NOT_READABLE_ERR', 5 : 'ENCODING_ERR', 6 : 'NO_MODIFICATION_ALLOWED_ERR', 7 : 'INVALID_STATE_ERR', 8 : 'SYNTAX_ERR', 9 : 'INVALID_MODIFICATION_ERR', 10 : 'QUOTA_EXCEEDED_ERR', 11 : 'TYPE_MISMATCH_ERR', 12 : 'PATH_EXISTS_ERR' }, root, temp_root, persistent_root; beforeEach(function (done) { // Custom Matchers jasmine.Expectation.addMatchers({ toBeFileError : function () { return { compare : function (error, code) { var pass = error.code == code; return { pass : pass, message : 'Expected FileError with code ' + fileErrorMap[error.code] + ' (' + error.code + ') to be ' + fileErrorMap[code] + '(' + code + ')' }; } }; }, toCanonicallyMatch : function () { return { compare : function (currentPath, path) { var a = path.split("/").join("").split("\\").join(""), b = currentPath.split("/").join("").split("\\").join(""), pass = a == b; return { pass : pass, message : 'Expected paths to match : ' + path + ' should be ' + currentPath }; } }; }, toFailWithMessage : function () { return { compare : function (error, message) { var pass = false; return { pass : pass, message : message }; } }; } }); //Define global variables var onError = function (e) { console.log('[ERROR] Problem setting up root filesystem for test running! Error to follow.'); console.log(JSON.stringify(e)); }; window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fileSystem) { root = fileSystem.root; // set in file.tests.js persistent_root = root; window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function (fileSystem) { temp_root = fileSystem.root; // set in file.tests.js done(); }, onError); }, onError); }); // HELPER FUNCTIONS // deletes specified file or directory var deleteEntry = function (name, success, error) { // deletes entry, if it exists window.resolveLocalFileSystemURL(root.toURL() + '/' + name, function (entry) { if (entry.isDirectory === true) { entry.removeRecursively(success, error); } else { entry.remove(success, error); } }, success); }; // deletes file, if it exists, then invokes callback var deleteFile = function (fileName, callback) { root.getFile(fileName, null, // remove file system entry function (entry) { entry.remove(callback, function () { console.log('[ERROR] deleteFile cleanup method invoked fail callback.'); }); }, // doesn't exist callback); }; // deletes and re-creates the specified file var createFile = function (fileName, success, error) { deleteEntry(fileName, function () { root.getFile(fileName, { create : true }, success, error); }, error); }; // deletes and re-creates the specified directory var createDirectory = function (dirName, success, error) { deleteEntry(dirName, function () { root.getDirectory(dirName, { create : true }, success, error); }, error); }; var failed = function (done, msg, error) { var info = typeof msg == 'undefined' ? 'Unexpected error callback' : msg; expect(true).toFailWithMessage(info + '\n' + JSON.stringify(error)); done(); }; var succeed = function (done, msg) { var info = typeof msg == 'undefined' ? 'Unexpected success callback' : msg; expect(true).toFailWithMessage(info); done(); }; var joinURL = function (base, extension) { if (base.charAt(base.length - 1) !== '/' && extension.charAt(0) !== '/') { return base + '/' + extension; } if (base.charAt(base.length - 1) === '/' && extension.charAt(0) === '/') { return base + exension.substring(1); } return base + extension; }; describe('FileError object', function () { it("file.spec.1 should define FileError constants", function () { expect(FileError.NOT_FOUND_ERR).toBe(1); expect(FileError.SECURITY_ERR).toBe(2); expect(FileError.ABORT_ERR).toBe(3); expect(FileError.NOT_READABLE_ERR).toBe(4); expect(FileError.ENCODING_ERR).toBe(5); expect(FileError.NO_MODIFICATION_ALLOWED_ERR).toBe(6); expect(FileError.INVALID_STATE_ERR).toBe(7); expect(FileError.SYNTAX_ERR).toBe(8); expect(FileError.INVALID_MODIFICATION_ERR).toBe(9); expect(FileError.QUOTA_EXCEEDED_ERR).toBe(10); expect(FileError.TYPE_MISMATCH_ERR).toBe(11); expect(FileError.PATH_EXISTS_ERR).toBe(12); }); }); describe('LocalFileSystem', function () { it("file.spec.2 should define LocalFileSystem constants", function () { expect(LocalFileSystem.TEMPORARY).toBe(0); expect(LocalFileSystem.PERSISTENT).toBe(1); }); describe('window.requestFileSystem', function () { it("file.spec.3 should be defined", function () { expect(window.requestFileSystem).toBeDefined(); }); it("file.spec.4 should be able to retrieve a PERSISTENT file system", function (done) { var win = function (fileSystem) { expect(fileSystem).toBeDefined(); expect(fileSystem.name).toBeDefined(); expect(fileSystem.name).toBe("persistent"); expect(fileSystem.root).toBeDefined(); expect(fileSystem.root.filesystem).toBeDefined(); // Shouldn't use cdvfile by default. expect(fileSystem.root.toURL()).not.toMatch(/^cdvfile:/); // All DirectoryEntry URLs should always have a trailing slash. expect(fileSystem.root.toURL()).toMatch(/\/$/); done(); }; // retrieve PERSISTENT file system window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, win, failed.bind(null, done, 'window.requestFileSystem - Error retrieving PERSISTENT file system')); }); it("file.spec.5 should be able to retrieve a TEMPORARY file system", function (done) { var win = function (fileSystem) { expect(fileSystem).toBeDefined(); expect(fileSystem.name).toBeDefined(); expect(fileSystem.name).toBe("temporary"); expect(fileSystem.root).toBeDefined(); expect(fileSystem.root.filesystem).toBeDefined(); expect(fileSystem.root.filesystem).toBe(fileSystem); done(); }; //retrieve TEMPORARY file system window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, win, failed.bind(null, done, 'window.requestFileSystem - Error retrieving TEMPORARY file system')); }); it("file.spec.6 should error if you request a file system that is too large", function (done) { var fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.QUOTA_EXCEEDED_ERR); done(); }; //win = createWin('window.requestFileSystem'); // Request the file system window.requestFileSystem(LocalFileSystem.TEMPORARY, 1000000000000000, failed.bind(null, done, 'window.requestFileSystem - Error retrieving TEMPORARY file system'), fail); }); it("file.spec.7 should error out if you request a file system that does not exist", function (done) { var fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.SYNTAX_ERR); done(); }; // Request the file system window.requestFileSystem(-1, 0, succeed.bind(null, done, 'window.requestFileSystem'), fail); }); }); describe('window.resolveLocalFileSystemURL', function () { it("file.spec.8 should be defined", function () { expect(window.resolveLocalFileSystemURL).toBeDefined(); }); it("file.spec.9 should resolve a valid file name", function (done) { var fileName = 'file.spec.9'; var win = function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.name).toCanonicallyMatch(fileName); expect(fileEntry.toURL()).not.toMatch(/^cdvfile:/, 'should not use cdvfile URL'); expect(fileEntry.toURL()).not.toMatch(/\/$/, 'URL should not end with a slash'); // Clean-up deleteEntry(fileName); //End done(); }; createFile(fileName, function (entry) { window.resolveLocalFileSystemURL(entry.toURL(), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving file URL: ' + entry.toURL())); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName), failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.9.5 should resolve a directory", function (done) { var fileName = 'file.spec.9.5'; var win = function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.name).toCanonicallyMatch(fileName); expect(fileEntry.toURL()).not.toMatch(/^cdvfile:/, 'should not use cdvfile URL'); expect(fileEntry.toURL()).toMatch(/\/$/, 'URL end with a slash'); // cleanup deleteEntry(fileName); done(); }; function gotDirectory(entry) { // lookup file system entry window.resolveLocalFileSystemURL(entry.toURL(), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving directory URL: ' + entry.toURL())); } createDirectory(fileName, gotDirectory, failed.bind(null, done, 'createDirectory - Error creating directory: ' + fileName), failed.bind(null, done, 'createDirectory - Error creating directory: ' + fileName)); }); it("file.spec.10 resolve valid file name with parameters", function (done) { var fileName = "resolve.file.uri.params", win = function (fileEntry) { expect(fileEntry).toBeDefined(); if (fileEntry.toURL().toLowerCase().substring(0, 10) === "cdvfile://") { expect(fileEntry.fullPath).toBe("/" + fileName + "?1234567890"); } expect(fileEntry.name).toBe(fileName); // cleanup deleteEntry(fileName); done(); }; // create a new file entry createFile(fileName, function (entry) { window.resolveLocalFileSystemURL(entry.toURL() + "?1234567890", win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving file URI: ' + entry.toURL())); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.11 should error (NOT_FOUND_ERR) when resolving (non-existent) invalid file name", function (done) { var fileName = cordova.platformId === 'windowsphone' ? root.toURL() + "/" + "this.is.not.a.valid.file.txt" : joinURL(root.toURL(), "this.is.not.a.valid.file.txt"); fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }; // lookup file system entry window.resolveLocalFileSystemURL(fileName, succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Error unexpected callback resolving file URI: ' + fileName), fail); }); it("file.spec.12 should error (ENCODING_ERR) when resolving invalid URI with leading /", function (done) { var fileName = "/this.is.not.a.valid.url", fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.ENCODING_ERR); done(); }; // lookup file system entry window.resolveLocalFileSystemURL(fileName, succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Error unexpected callback resolving file URI: ' + fileName), fail); }); }); }); //LocalFileSystem describe('Metadata interface', function () { it("file.spec.13 should exist and have the right properties", function () { var metadata = new Metadata(); expect(metadata).toBeDefined(); expect(metadata.modificationTime).toBeDefined(); }); }); describe('Flags interface', function () { it("file.spec.14 should exist and have the right properties", function () { var flags = new Flags(false, true); expect(flags).toBeDefined(); expect(flags.create).toBeDefined(); expect(flags.create).toBe(false); expect(flags.exclusive).toBeDefined(); expect(flags.exclusive).toBe(true); }); }); describe('FileSystem interface', function () { it("file.spec.15 should have a root that is a DirectoryEntry", function (done) { var win = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(false); expect(entry.isDirectory).toBe(true); expect(entry.name).toBeDefined(); expect(entry.fullPath).toBeDefined(); expect(entry.getMetadata).toBeDefined(); expect(entry.moveTo).toBeDefined(); expect(entry.copyTo).toBeDefined(); expect(entry.toURL).toBeDefined(); expect(entry.remove).toBeDefined(); expect(entry.getParent).toBeDefined(); expect(entry.createReader).toBeDefined(); expect(entry.getFile).toBeDefined(); expect(entry.getDirectory).toBeDefined(); expect(entry.removeRecursively).toBeDefined(); done(); }; window.resolveLocalFileSystemURL(root.toURL(), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving file URI: ' + root.toURL())); }); }); describe('DirectoryEntry', function () { it("file.spec.16 getFile: get Entry for file that does not exist", function (done) { var fileName = "de.no.file", filePath = joinURL(root.fullPath, fileName), fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }; // create:false, exclusive:false, file does not exist root.getFile(fileName, { create : false }, succeed.bind(null, done, 'root.getFile - Error unexpected callback, file should not exists: ' + fileName), fail); }); it("file.spec.17 getFile: create new file", function (done) { var fileName = "de.create.file", filePath = joinURL(root.fullPath, fileName), win = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(fileName); expect(entry.fullPath).toCanonicallyMatch(filePath); // cleanup entry.remove(null, null); done(); }; // create:true, exclusive:false, file does not exist root.getFile(fileName, { create : true }, win, succeed.bind(null, done, 'root.getFile - Error unexpected callback, file should not exists: ' + fileName)); }); it("file.spec.18 getFile: create new file (exclusive)", function (done) { var fileName = "de.create.exclusive.file", filePath = joinURL(root.fullPath, fileName), win = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toBe(fileName); expect(entry.fullPath).toCanonicallyMatch(filePath); // cleanup entry.remove(null, null); done(); }; // create:true, exclusive:true, file does not exist root.getFile(fileName, { create : true, exclusive : true }, win, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); }); it("file.spec.19 getFile: create file that already exists", function (done) { var fileName = "de.create.existing.file", filePath = joinURL(root.fullPath, fileName), getFile = function (file) { // create:true, exclusive:false, file exists root.getFile(fileName, { create : true }, win, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); }, win = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(fileName); expect(entry.fullPath).toCanonicallyMatch(filePath); // cleanup entry.remove(null, fail); done(); }; // create file to kick off it root.getFile(fileName, { create : true }, getFile, fail); }); it("file.spec.20 getFile: create file that already exists (exclusive)", function (done) { var fileName = "de.create.exclusive.existing.file", filePath = joinURL(root.fullPath, fileName), existingFile, getFile = function (file) { existingFile = file; // create:true, exclusive:true, file exists root.getFile(fileName, { create : true, exclusive : true }, succeed.bind(null, done, 'root.getFile - getFile function - Error unexpected callback, file should exists: ' + fileName), fail); }, fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.PATH_EXISTS_ERR); // cleanup existingFile.remove(null, null); done(); }; // create file to kick off it root.getFile(fileName, { create : true }, getFile, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); }); it("file.spec.21 DirectoryEntry.getFile: get Entry for existing file", function (done) { var fileName = "de.get.file", filePath = joinURL(root.fullPath, fileName), win = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(fileName); expect(entry.fullPath).toCanonicallyMatch(filePath); expect(entry.filesystem).toBeDefined(); expect(entry.filesystem).toBe(root.filesystem); //clean up entry.remove(null, null); done(); }, getFile = function (file) { // create:false, exclusive:false, file exists root.getFile(fileName, { create : false }, win, failed.bind(null, done, 'root.getFile - Error getting file entry: ' + fileName)); }; // create file to kick off it root.getFile(fileName, { create : true }, getFile, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); }); it("file.spec.22 DirectoryEntry.getFile: get FileEntry for invalid path", function (done) { var fileName = "de:invalid:path", fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.ENCODING_ERR); done(); }; // create:false, exclusive:false, invalid path root.getFile(fileName, { create : false }, succeed.bind(null, done, 'root.getFile - Error unexpected callback, file should not exists: ' + fileName), fail); }); it("file.spec.23 DirectoryEntry.getDirectory: get Entry for directory that does not exist", function (done) { var dirName = "de.no.dir", dirPath = joinURL(root.fullPath, dirName), fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }; // create:false, exclusive:false, directory does not exist root.getDirectory(dirName, { create : false }, succeed.bind(null, done, 'root.getDirectory - Error unexpected callback, directory should not exists: ' + dirName), fail); }); it("file.spec.24 DirectoryEntry.getDirectory: create new dir with space then resolveLocalFileSystemURL", function (done) { var dirName = "de create dir", dirPath = joinURL(root.fullPath, encodeURIComponent(dirName)), getDir = function (dirEntry) { expect(dirEntry.filesystem).toBeDefined(); expect(dirEntry.filesystem).toBe(root.filesystem); var dirURI = dirEntry.toURL(); // now encode URI and try to resolve window.resolveLocalFileSystemURL(dirURI, win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - getDir function - Error resolving directory: ' + dirURI)); }, win = function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.name).toCanonicallyMatch(dirName); expect(directory.fullPath).toCanonicallyMatch(joinURL(root.fullPath, dirName)); // cleanup directory.remove(null, null); done(); }; // create:true, exclusive:false, directory does not exist root.getDirectory(dirName, { create : true }, getDir, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); // This test is excluded, and should probably be removed. Filesystem // should always be properly encoded URLs, and *not* raw paths, and it // doesn't make sense to double-encode the URLs and expect that to be // handled by the implementation. // If a particular platform uses paths internally rather than URLs, // then that platform should careful to pass them correctly to its // backend. xit("file.spec.25 DirectoryEntry.getDirectory: create new dir with space resolveLocalFileSystemURL with encoded URI", function (done) { var dirName = "de create dir2", dirPath = joinURL(root.fullPath, dirName), getDir = function (dirEntry) { var dirURI = dirEntry.toURL(); // now encode URI and try to resolve window.resolveLocalFileSystemURL(encodeURI(dirURI), win, failed.bind(null, done, 'window.resolveLocalFileSystemURL - getDir function - Error resolving directory: ' + dirURI)); }, win = function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.name).toCanonicallyMatch(dirName); expect(directory.fullPath).toCanonicallyMatch(dirPath); // cleanup directory.remove(null, null); done(); }; // create:true, exclusive:false, directory does not exist root.getDirectory(dirName, { create : true }, getDir, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.26 DirectoryEntry.getDirectory: create new directory", function (done) { var dirName = "de.create.dir", dirPath = joinURL(root.fullPath, dirName), win = function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.name).toCanonicallyMatch(dirName); expect(directory.fullPath).toCanonicallyMatch(dirPath); expect(directory.filesystem).toBeDefined(); expect(directory.filesystem).toBe(root.filesystem); // cleanup directory.remove(null, null); done(); }; // create:true, exclusive:false, directory does not exist root.getDirectory(dirName, { create : true }, win, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.27 DirectoryEntry.getDirectory: create new directory (exclusive)", function (done) { var dirName = "de.create.exclusive.dir", dirPath = joinURL(root.fullPath, dirName), win = function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.name).toCanonicallyMatch(dirName); expect(directory.fullPath).toCanonicallyMatch(dirPath); expect(directory.filesystem).toBeDefined(); expect(directory.filesystem).toBe(root.filesystem); // cleanup directory.remove(null, null); done(); }; // create:true, exclusive:true, directory does not exist root.getDirectory(dirName, { create : true, exclusive : true }, win, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.28 DirectoryEntry.getDirectory: create directory that already exists", function (done) { var dirName = "de.create.existing.dir", dirPath = joinURL(root.fullPath, dirName), win = function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.name).toCanonicallyMatch(dirName); expect(directory.fullPath).toCanonicallyMatch(dirPath); // cleanup directory.remove(null, null); done(); }; // create directory to kick off it root.getDirectory(dirName, { create : true }, function () { root.getDirectory(dirName, { create : true }, win, failed.bind(null, done, 'root.getDirectory - Error creating existent second directory : ' + dirName)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.29 DirectoryEntry.getDirectory: create directory that already exists (exclusive)", function (done) { var dirName = "de.create.exclusive.existing.dir", dirPath = joinURL(root.fullPath, dirName), existingDir, fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.PATH_EXISTS_ERR); // cleanup existingDir.remove(null, null); done(); }; // create directory to kick off it root.getDirectory(dirName, { create : true }, function (directory) { existingDir = directory; // create:true, exclusive:true, directory exists root.getDirectory(dirName, { create : true, exclusive : true }, failed.bind(null, done, 'root.getDirectory - Unexpected success callback, second directory should not be created : ' + dirName), fail); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.30 DirectoryEntry.getDirectory: get Entry for existing directory", function (done) { var dirName = "de.get.dir", dirPath = joinURL(root.fullPath, dirName), win = function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.name).toCanonicallyMatch(dirName); expect(directory.fullPath).toCanonicallyMatch(dirPath); // cleanup directory.remove(null, null); done(); }; // create directory to kick it off root.getDirectory(dirName, { create : true }, function () { root.getDirectory(dirName, { create : false }, win, failed.bind(null, done, 'root.getDirectory - Error getting directory entry : ' + dirName)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.31 DirectoryEntry.getDirectory: get DirectoryEntry for invalid path", function (done) { var dirName = "de:invalid:path", fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.ENCODING_ERR); done(); }; // create:false, exclusive:false, invalid path root.getDirectory(dirName, { create : false }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory should not exists: ' + dirName), fail); }); it("file.spec.32 DirectoryEntry.getDirectory: get DirectoryEntry for existing file", function (done) { var fileName = "de.existing.file", existingFile, filePath = joinURL(root.fullPath, fileName), fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.TYPE_MISMATCH_ERR); // cleanup existingFile.remove(null, null); done(); }; // create file to kick off it root.getFile(fileName, { create : true }, function (file) { existingFile = file; root.getDirectory(fileName, { create : false }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory should not exists: ' + fileName), fail); }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); }); it("file.spec.33 DirectoryEntry.getFile: get FileEntry for existing directory", function (done) { var dirName = "de.existing.dir", existingDir, dirPath = joinURL(root.fullPath, dirName), fail = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.TYPE_MISMATCH_ERR); // cleanup existingDir.remove(null, null); done(); }; // create directory to kick off it root.getDirectory(dirName, { create : true }, function (directory) { existingDir = directory; root.getFile(dirName, { create : false }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, file should not exists: ' + dirName), fail); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.34 DirectoryEntry.removeRecursively on directory", function (done) { var dirName = "de.removeRecursively", subDirName = "dir", dirPath = joinURL(root.fullPath, dirName), subDirPath = joinURL(dirPath, subDirName), dirExists = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }; // create a new directory entry to kick off it root.getDirectory(dirName, { create : true }, function (entry) { entry.getDirectory(subDirName, { create : true }, function (dir) { entry.removeRecursively(function () { root.getDirectory(dirName, { create : false }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory should not exists: ' + dirName), dirExists); }, failed.bind(null, done, 'entry.removeRecursively - Error removing directory recursively : ' + dirName)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + subDirName)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.35 createReader: create reader on existing directory", function () { // create reader for root directory var reader = root.createReader(); expect(reader).toBeDefined(); expect(typeof reader.readEntries).toBe('function'); }); it("file.spec.36 removeRecursively on root file system", function (done) { var remove = function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NO_MODIFICATION_ALLOWED_ERR); done(); }; // remove root file system root.removeRecursively(succeed.bind(null, done, 'root.removeRecursively - Unexpected success callback, root cannot be removed'), remove); }); }); describe('DirectoryReader interface', function () { describe("readEntries", function () { it("file.spec.37 should read contents of existing directory", function (done) { var reader, win = function (entries) { expect(entries).toBeDefined(); expect(entries instanceof Array).toBe(true); done(); }; // create reader for root directory reader = root.createReader(); // read entries reader.readEntries(win, failed.bind(null, done, 'reader.readEntries - Error reading entries')); }); it("file.spec.37.1 should read contents of existing directory", function (done) { var dirName = 'readEntries.dir', fileName = 'readeEntries.file'; root.getDirectory(dirName, { create : true }, function (directory) { directory.getFile(fileName, { create : true }, function (fileEntry) { var reader = directory.createReader(); reader.readEntries(function (entries) { expect(entries).toBeDefined(); expect(entries instanceof Array).toBe(true); expect(entries.length).toBe(1); expect(entries[0].fullPath).toCanonicallyMatch(fileEntry.fullPath); expect(entries[0].filesystem).not.toBe(null); expect(entries[0].filesystem instanceof FileSystem).toBe(true); // cleanup directory.removeRecursively(null, null); done(); }, failed.bind(null, done, 'reader.readEntries - Error reading entries from directory: ' + dirName)); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + fileName)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); it("file.spec.109 should return an empty entry list on the second call", function (done) { var reader, fileName = 'test109.txt'; // Add a file to ensure the root directory is non-empty and then read the contents of the directory. root.getFile(fileName, { create : true }, function (entry) { reader = root.createReader(); //First read reader.readEntries(function (entries) { expect(entries).toBeDefined(); expect(entries instanceof Array).toBe(true); expect(entries.length).not.toBe(0); //Second read reader.readEntries(function (entries_) { expect(entries_).toBeDefined(); expect(entries_ instanceof Array).toBe(true); expect(entries_.length).toBe(0); //Clean up entry.remove(); done(); }, failed.bind(null, done, 'reader.readEntries - Error during SECOND reading of entries from [root] directory')); }, failed.bind(null, done, 'reader.readEntries - Error during FIRST reading of entries from [root] directory')); }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); }); }); it("file.spec.38 should read contents of directory that has been removed", function (done) { var dirName = "de.createReader.notfound", dirPath = joinURL(root.fullPath, dirName); // create a new directory entry to kick off it root.getDirectory(dirName, { create : true }, function (directory) { directory.removeRecursively(function () { var reader = directory.createReader(); reader.readEntries(succeed.bind(null, done, 'reader.readEntries - Unexpected success callback, it should not read entries from deleted dir: ' + dirName), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); root.getDirectory(dirName, { create : false }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, it should not get deleted directory: ' + dirName), function (err) { expect(err).toBeDefined(); expect(err).toBeFileError(FileError.NOT_FOUND_ERR); done(); }); }); }, failed.bind(null, done, 'directory.removeRecursively - Error removing directory recursively : ' + dirName)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dirName)); }); }); //DirectoryReader interface describe('File', function () { it("file.spec.39 constructor should be defined", function () { expect(File).toBeDefined(); expect(typeof File).toBe('function'); }); it("file.spec.40 should be define File attributes", function () { var file = new File(); expect(file.name).toBeDefined(); expect(file.type).toBeDefined(); expect(file.lastModifiedDate).toBeDefined(); expect(file.size).toBeDefined(); }); }); //File describe('FileEntry', function () { it("file.spec.41 should be define FileEntry methods", function (done) { var fileName = "fe.methods", testFileEntry = function (fileEntry) { expect(fileEntry).toBeDefined(); expect(typeof fileEntry.createWriter).toBe('function'); expect(typeof fileEntry.file).toBe('function'); // cleanup fileEntry.remove(null, null); done(); }; // create a new file entry to kick off it root.getFile(fileName, { create : true }, testFileEntry, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); }); it("file.spec.42 createWriter should return a FileWriter object", function (done) { var fileName = "fe.createWriter", testFile, testWriter = function (writer) { expect(writer).toBeDefined(); expect(writer instanceof FileWriter).toBe(true); // cleanup testFile.remove(null, null); done(); }; // create a new file entry to kick off it root.getFile(fileName, { create : true }, function (fileEntry) { testFile = fileEntry; fileEntry.createWriter(testWriter, failed.bind(null, done, 'fileEntry.createWriter - Error creating Writer from entry')); }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); }); it("file.spec.43 file should return a File object", function (done) { var fileName = "fe.file", newFile, testFile = function (file) { expect(file).toBeDefined(); expect(file instanceof File).toBe(true); // cleanup newFile.remove(null, null); done(); }; // create a new file entry to kick off it root.getFile(fileName, { create : true }, function (fileEntry) { newFile = fileEntry; fileEntry.file(testFile, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); }); it("file.spec.44 file: on File that has been removed", function (done) { var fileName = "fe.no.file"; // create a new file entry to kick off it root.getFile(fileName, { create : true }, function (fileEntry) { fileEntry.remove(function () { fileEntry.file(succeed.bind(null, done, 'fileEntry.file - Unexpected success callback, file it should not be created from removed entry'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }); }, failed.bind(null, done, 'fileEntry.remove - Error removing entry : ' + fileName)); }, failed.bind(null, done, 'root.getFile - Error creating file : ' + fileName)); }); }); //FileEntry describe('Entry', function () { it("file.spec.45 Entry object", function (done) { var fileName = "entry", fullPath = joinURL(root.fullPath, fileName), winEntry = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(fileName); expect(entry.fullPath).toCanonicallyMatch(fullPath); expect(typeof entry.getMetadata).toBe('function'); expect(typeof entry.setMetadata).toBe('function'); expect(typeof entry.moveTo).toBe('function'); expect(typeof entry.copyTo).toBe('function'); expect(typeof entry.toURL).toBe('function'); expect(typeof entry.remove).toBe('function'); expect(typeof entry.getParent).toBe('function'); expect(typeof entry.createWriter).toBe('function'); expect(typeof entry.file).toBe('function'); // Clean up deleteEntry(fileName); done(); }; // create a new file entry createFile(fileName, winEntry, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); }); it("file.spec.46 Entry.getMetadata on file", function (done) { var fileName = "entry.metadata.file"; // create a new file entry createFile(fileName, function (entry) { entry.getMetadata(function (metadata) { expect(metadata).toBeDefined(); expect(metadata.modificationTime instanceof Date).toBe(true); expect(typeof metadata.size).toBe("number"); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'entry.getMetadata - Error getting metadata from entry : ' + fileName)); }, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); }); it("file.spec.47 Entry.getMetadata on directory", function (done) { var dirName = "entry.metadata.dir"; // create a new directory entry createDirectory(dirName, function (entry) { entry.getMetadata(function (metadata) { expect(metadata).toBeDefined(); expect(metadata.modificationTime instanceof Date).toBe(true); expect(typeof metadata.size).toBe("number"); expect(metadata.size).toBe(0); // cleanup deleteEntry(dirName); done(); }, failed.bind(null, done, 'entry.getMetadata - Error getting metadata from entry : ' + dirName)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); }); it("file.spec.48 Entry.getParent on file in root file system", function (done) { var fileName = "entry.parent.file", rootPath = root.fullPath; // create a new file entry createFile(fileName, function (entry) { entry.getParent(function (parent) { expect(parent).toBeDefined(); expect(parent.fullPath).toCanonicallyMatch(rootPath); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'entry.getParent - Error getting parent directory of file : ' + fileName)); }, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); }); it("file.spec.49 Entry.getParent on directory in root file system", function (done) { var dirName = "entry.parent.dir", rootPath = root.fullPath; // create a new directory entry createDirectory(dirName, function (entry) { entry.getParent(function (parent) { expect(parent).toBeDefined(); expect(parent.fullPath).toCanonicallyMatch(rootPath); // cleanup deleteEntry(dirName); done(); }, failed.bind(null, done, 'entry.getParent - Error getting parent directory of directory : ' + dirName)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); }); it("file.spec.50 Entry.getParent on root file system", function (done) { var rootPath = root.fullPath, winParent = function (parent) { expect(parent).toBeDefined(); expect(parent.fullPath).toCanonicallyMatch(rootPath); done(); }; // create a new directory entry root.getParent(winParent, failed.bind(null, done, 'root.getParent - Error getting parent directory of root')); }); it("file.spec.51 Entry.toURL on file", function (done) { var fileName = "entry.uri.file", rootPath = root.fullPath, winURI = function (entry) { var uri = entry.toURL(); expect(uri).toBeDefined(); expect(uri.indexOf(rootPath)).not.toBe(-1); // cleanup deleteEntry(fileName); done(); }; // create a new file entry createFile(fileName, winURI, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); }); it("file.spec.52 Entry.toURL on directory", function (done) { var dirName_1 = "num 1", dirName_2 = "num 2", rootPath = root.fullPath; createDirectory(dirName_1, function (entry) { entry.getDirectory(dirName_2, { create : true }, function (entryFile) { var uri = entryFile.toURL(); expect(uri).toBeDefined(); expect(uri).toContain('/num%201/num%202/'); expect(uri.indexOf(rootPath)).not.toBe(-1); // cleanup deleteEntry(dirName_1); done(); }, failed.bind(null, done, 'entry.getDirectory - Error creating directory : ' + dirName_2)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName_1)); }); it("file.spec.53 Entry.remove on file", function (done) { var fileName = "entr .rm.file"; // create a new file entry createFile(fileName, function (entry) { expect(entry).toBeDefined(); entry.remove(function () { root.getFile(fileName, null, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get deleted file : ' + fileName), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(fileName); done(); }); }, failed.bind(null, done, 'entry.remove - Error removing entry : ' + fileName)); }, failed.bind(null, done, 'createFile - Error creating file : ' + fileName)); }); it("file.spec.54 remove on empty directory", function (done) { var dirName = "entry.rm.dir"; // create a new directory entry createDirectory(dirName, function (entry) { expect(entry).toBeDefined(); entry.remove(function () { root.getDirectory(dirName, null, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, it should not get deleted directory : ' + dirName), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(dirName); done(); }); }, failed.bind(null, done, 'entry.remove - Error removing entry : ' + dirName)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); }); it("file.spec.55 remove on non-empty directory", function (done) { var dirName = "ent y.rm.dir.not.empty", fileName = "re ove.txt", fullPath = joinURL(root.fullPath, dirName); // create a new directory entry createDirectory(dirName, function (entry) { entry.getFile(fileName, { create : true }, function (fileEntry) { entry.remove(succeed.bind(null, done, 'entry.remove - Unexpected success callback, it should not remove a directory that contains files : ' + dirName), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); root.getDirectory(dirName, null, function (entry) { expect(entry).toBeDefined(); expect(entry.fullPath).toCanonicallyMatch(fullPath); // cleanup deleteEntry(dirName); done(); }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + dirName)); }); }, failed.bind(null, done, 'entry.getFile - Error creating file : ' + fileName + ' inside of ' + dirName)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); }); it("file.spec.56 remove on root file system", function (done) { // remove entry that doesn't exist root.remove(succeed.bind(null, done, 'entry.remove - Unexpected success callback, it should not remove entry that it does not exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NO_MODIFICATION_ALLOWED_ERR); done(); }); }); it("file.spec.57 copyTo: file", function (done) { var file1 = "entry copy.file1", file2 = "entry copy.file2", fullPath = joinURL(root.fullPath, file2); // create a new file entry to kick off it deleteEntry(file2, function () { createFile(file1, function (fileEntry) { // copy file1 to file2 fileEntry.copyTo(root, file2, function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.fullPath).toCanonicallyMatch(fullPath); expect(entry.name).toCanonicallyMatch(file2); root.getFile(file2, { create : false }, function (entry2) { expect(entry2).toBeDefined(); expect(entry2.isFile).toBe(true); expect(entry2.isDirectory).toBe(false); expect(entry2.fullPath).toCanonicallyMatch(fullPath); expect(entry2.name).toCanonicallyMatch(file2); // cleanup deleteEntry(file1); deleteEntry(file2); done(); }, failed.bind(null, done, 'root.getFile - Error getting copied file : ' + file2)); }, failed.bind(null, done, 'fileEntry.copyTo - Error copying file : ' + file2)); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'deleteEntry - Error removing file : ' + file2)); }); it("file.spec.58 copyTo: file onto itself", function (done) { var file1 = "entry.copy.fos.file1"; // create a new file entry to kick off it createFile(file1, function (entry) { // copy file1 onto itself entry.copyTo(root, null, succeed.bind(null, done, 'entry.copyTo - Unexpected success callback, it should not copy a null file'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // cleanup deleteEntry(file1); done(); }); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }); it("file.spec.59 copyTo: directory", function (done) { var file1 = "file1", srcDir = "entry.copy.srcDir", dstDir = "entry.copy.dstDir", dstPath = joinURL(root.fullPath, dstDir), filePath = joinURL(dstPath, file1); // create a new directory entry to kick off it deleteEntry(dstDir, function () { createDirectory(srcDir, function (directory) { // create a file within new directory directory.getFile(file1, { create : true }, function () { directory.copyTo(root, dstDir, function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.fullPath).toCanonicallyMatch(dstPath); expect(directory.name).toCanonicallyMatch(dstDir); root.getDirectory(dstDir, { create : false }, function (dirEntry) { expect(dirEntry).toBeDefined(); expect(dirEntry.isFile).toBe(false); expect(dirEntry.isDirectory).toBe(true); expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); expect(dirEntry.name).toCanonicallyMatch(dstDir); dirEntry.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.isFile).toBe(true); expect(fileEntry.isDirectory).toBe(false); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); expect(fileEntry.name).toCanonicallyMatch(file1); // cleanup deleteEntry(srcDir); deleteEntry(dstDir); done(); }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1)); }, failed.bind(null, done, 'root.getDirectory - Error getting copied directory : ' + dstDir)); }, failed.bind(null, done, 'directory.copyTo - Error copying directory : ' + srcDir + ' to :' + dstDir)); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.60 copyTo: directory to backup at same root directory", function (done) { var file1 = "file1", srcDir = "entry.copy srcDirSame", dstDir = "entry.copy srcDirSame-backup", dstPath = joinURL(root.fullPath, dstDir), filePath = joinURL(dstPath, file1); // create a new directory entry to kick off it deleteEntry(dstDir, function () { createDirectory(srcDir, function (directory) { directory.getFile(file1, { create : true }, function () { directory.copyTo(root, dstDir, function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.fullPath).toCanonicallyMatch(dstPath); expect(directory.name).toCanonicallyMatch(dstDir); root.getDirectory(dstDir, { create : false }, function (dirEntry) { expect(dirEntry).toBeDefined(); expect(dirEntry.isFile).toBe(false); expect(dirEntry.isDirectory).toBe(true); expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); expect(dirEntry.name).toCanonicallyMatch(dstDir); dirEntry.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.isFile).toBe(true); expect(fileEntry.isDirectory).toBe(false); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); expect(fileEntry.name).toCanonicallyMatch(file1); // cleanup deleteEntry(srcDir); deleteEntry(dstDir); done(); }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1)); }, failed.bind(null, done, 'root.getDirectory - Error getting copied directory : ' + dstDir)); }, failed.bind(null, done, 'directory.copyTo - Error copying directory : ' + srcDir + ' to :' + dstDir)); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.61 copyTo: directory onto itself", function (done) { var file1 = "file1", srcDir = "entry.copy.dos.srcDir", srcPath = joinURL(root.fullPath, srcDir), filePath = joinURL(srcPath, file1); // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // create a file within new directory directory.getFile(file1, { create : true }, function (fileEntry) { // copy srcDir onto itself directory.copyTo(root, null, succeed.bind(null, done, 'directory.copyTo - Unexpected success callback, it should not copy file: ' + srcDir + ' to a null destination'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); root.getDirectory(srcDir, { create : false }, function (dirEntry) { expect(dirEntry).toBeDefined(); expect(dirEntry.fullPath).toCanonicallyMatch(srcPath); dirEntry.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // cleanup deleteEntry(srcDir); done(); }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1)); }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + srcDir)); }); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }); it("file.spec.62 copyTo: directory into itself", function (done) { var srcDir = "entry.copy.dis.srcDir", dstDir = "entry.copy.dis.dstDir", srcPath = joinURL(root.fullPath, srcDir); // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // copy source directory into itself directory.copyTo(directory, dstDir, succeed.bind(null, done, 'directory.copyTo - Unexpected success callback, it should not copy a directory ' + srcDir + ' into itself'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); root.getDirectory(srcDir, { create : false }, function (dirEntry) { // returning confirms existence so just check fullPath entry expect(dirEntry).toBeDefined(); expect(dirEntry.fullPath).toCanonicallyMatch(srcPath); // cleanup deleteEntry(srcDir); done(); }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + srcDir)); }); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }); it("file.spec.63 copyTo: directory that does not exist", function (done) { var file1 = "entry.copy.dnf.file1", dirName = 'dir-foo'; createFile(file1, function (fileEntry) { createDirectory(dirName, function (dirEntry) { dirEntry.remove(function () { fileEntry.copyTo(dirEntry, null, succeed.bind(null, done, 'fileEntry.copyTo - Unexpected success callback, it should not copy a file ' + file1 + ' into a removed directory'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }); }, failed.bind(null, done, 'dirEntry.remove - Error removing directory : ' + dirName)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + dirName)); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }); it("file.spec.64 copyTo: invalid target name", function (done) { var file1 = "entry.copy.itn.file1", file2 = "bad:file:name"; // create a new file entry createFile(file1, function (entry) { // copy file1 to file2 entry.copyTo(root, file2, succeed.bind(null, done, 'entry.copyTo - Unexpected success callback, it should not copy a file ' + file1 + ' to an invalid file name: ' + file2), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.ENCODING_ERR); // cleanup deleteEntry(file1); done(); }); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }); it("file.spec.65 moveTo: file to same parent", function (done) { var file1 = "entry.move.fsp.file1", file2 = "entry.move.fsp.file2", dstPath = joinURL(root.fullPath, file2); // create a new file entry to kick off it createFile(file1, function (entry) { // move file1 to file2 entry.moveTo(root, file2, function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.fullPath).toCanonicallyMatch(dstPath); expect(entry.name).toCanonicallyMatch(file2); root.getFile(file2, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(dstPath); root.getFile(file1, { create : false }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { //expect(navigator.fileMgr.testFileExists(srcPath) === false, "original file should not exist."); expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(file1); deleteEntry(file2); done(); }); }, failed.bind(null, done, 'root.getFile - Error getting file : ' + file2)); }, failed.bind(null, done, 'entry.moveTo - Error moving file : ' + file1 + ' to root as: ' + file2)); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }); it("file.spec.66 moveTo: file to new parent", function (done) { var file1 = "entry.move.fnp.file1", dir = "entry.move.fnp.dir", dstPath = joinURL(joinURL(root.fullPath, dir), file1); // ensure destination directory is cleaned up first deleteEntry(dir, function () { // create a new file entry to kick off it createFile(file1, function (entry) { // create a parent directory to move file to root.getDirectory(dir, { create : true }, function (directory) { // move file1 to new directory // move the file entry.moveTo(directory, null, function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.fullPath).toCanonicallyMatch(dstPath); expect(entry.name).toCanonicallyMatch(file1); // test the moved file exists directory.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(dstPath); root.getFile(file1, { create : false }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(file1); deleteEntry(dir); done(); }); }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + dir)); }, failed.bind(null, done, 'entry.moveTo - Error moving file : ' + file1 + ' to: ' + dir + ' with the same name')); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dir)); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dir)); }); it("file.spec.67 moveTo: directory to same parent", function (done) { var file1 = "file1", srcDir = "entry.move.dsp.srcDir", dstDir = "entry.move.dsp.dstDir", srcPath = joinURL(root.fullPath, srcDir), dstPath = joinURL(root.fullPath, dstDir), filePath = joinURL(dstPath, file1); // ensure destination directory is cleaned up before it deleteEntry(dstDir, function () { // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // create a file within directory directory.getFile(file1, { create : true }, function () { // move srcDir to dstDir directory.moveTo(root, dstDir, function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.fullPath).toCanonicallyMatch(dstPath); expect(directory.name).toCanonicallyMatch(dstDir); // test that moved file exists in destination dir directory.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // check that the moved file no longer exists in original dir root.getFile(file1, { create : false }, succeed.bind(null, done, 'directory.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(srcDir); deleteEntry(dstDir); done(); }); }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + srcDir)); }, failed.bind(null, done, 'entry.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.68 moveTo: directory to same parent with same name", function (done) { var file1 = "file1", srcDir = "entry.move.dsp.srcDir", dstDir = "entry.move.dsp.srcDir-backup", srcPath = joinURL(root.fullPath, srcDir), dstPath = joinURL(root.fullPath, dstDir), filePath = joinURL(dstPath, file1); // ensure destination directory is cleaned up before it deleteEntry(dstDir, function () { // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // create a file within directory directory.getFile(file1, { create : true }, function () { // move srcDir to dstDir directory.moveTo(root, dstDir, function (directory) { expect(directory).toBeDefined(); expect(directory.isFile).toBe(false); expect(directory.isDirectory).toBe(true); expect(directory.fullPath).toCanonicallyMatch(dstPath); expect(directory.name).toCanonicallyMatch(dstDir); // check that moved file exists in destination dir directory.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // check that the moved file no longer exists in original dir root.getFile(file1, { create : false }, succeed.bind(null, done, 'directory.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(srcDir); deleteEntry(dstDir); done(); }); }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + srcDir)); }, failed.bind(null, done, 'entry.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.69 moveTo: directory to new parent", function (done) { var file1 = "file1", srcDir = "entry.move.dnp.srcDir", dstDir = "entry.move.dnp.dstDir", srcPath = joinURL(root.fullPath, srcDir), dstPath = joinURL(root.fullPath, dstDir), filePath = joinURL(dstPath, file1); // ensure destination directory is cleaned up before it deleteEntry(dstDir, function () { // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // create a file within directory directory.getFile(file1, { create : true }, function () { // move srcDir to dstDir directory.moveTo(root, dstDir, function (dirEntry) { expect(dirEntry).toBeDefined(); expect(dirEntry.isFile).toBe(false); expect(dirEntry.isDirectory).toBe(true); expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); expect(dirEntry.name).toCanonicallyMatch(dstDir); // test that moved file exists in destination dir dirEntry.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // test that the moved file no longer exists in original dir root.getFile(file1, { create : false }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not get invalid or moved file: ' + file1), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(srcDir); deleteEntry(dstDir); done(); }); }, failed.bind(null, done, 'directory.getFile - Error getting file : ' + file1 + ' from: ' + dstDir)); }, failed.bind(null, done, 'directory.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.70 moveTo: directory onto itself", function (done) { var file1 = "file1", srcDir = "entry.move.dos.srcDir", srcPath = joinURL(root.fullPath, srcDir), filePath = joinURL(srcPath, file1); // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // create a file within new directory directory.getFile(file1, { create : true }, function () { // move srcDir onto itself directory.moveTo(root, null, succeed.bind(null, done, 'directory.moveTo - Unexpected success callback, it should not move directory to invalid path'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // test that original dir still exists root.getDirectory(srcDir, { create : false }, function (dirEntry) { // returning confirms existence so just check fullPath entry expect(dirEntry).toBeDefined(); expect(dirEntry.fullPath).toCanonicallyMatch(srcPath); dirEntry.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // cleanup deleteEntry(srcDir); done(); }, failed.bind(null, done, 'dirEntry.getFile - Error getting file : ' + file1 + ' from: ' + srcDir)); }, failed.bind(null, done, 'root.getDirectory - Error getting directory : ' + srcDir)); }); }, failed.bind(null, done, 'directory.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }); it("file.spec.71 moveTo: directory into itself", function (done) { var srcDir = "entry.move.dis.srcDir", dstDir = "entry.move.dis.dstDir", srcPath = joinURL(root.fullPath, srcDir); // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // move source directory into itself directory.moveTo(directory, dstDir, succeed.bind(null, done, 'directory.moveTo - Unexpected success callback, it should not move a directory into itself: ' + srcDir), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // make sure original directory still exists root.getDirectory(srcDir, { create : false }, function (entry) { expect(entry).toBeDefined(); expect(entry.fullPath).toCanonicallyMatch(srcPath); // cleanup deleteEntry(srcDir); done(); }, failed.bind(null, done, 'root.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); }); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }); it("file.spec.72 moveTo: file onto itself", function (done) { var file1 = "entry.move.fos.file1", filePath = joinURL(root.fullPath, file1); // create a new file entry to kick off it createFile(file1, function (entry) { // move file1 onto itself entry.moveTo(root, null, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not move a file: ' + file1 + ' into the same parent'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); //test that original file still exists root.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // cleanup deleteEntry(file1); done(); }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); }); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }); it("file.spec.73 moveTo: file onto existing directory", function (done) { var file1 = "entry.move.fod.file1", dstDir = "entry.move.fod.dstDir", subDir = "subDir", dirPath = joinURL(joinURL(root.fullPath, dstDir), subDir), filePath = joinURL(root.fullPath, file1); // ensure destination directory is cleaned up before it deleteEntry(dstDir, function () { // create a new file entry to kick off it createFile(file1, function (entry) { // create top level directory root.getDirectory(dstDir, { create : true }, function (directory) { // create sub-directory directory.getDirectory(subDir, { create : true }, function (subDirectory) { // move file1 onto sub-directory entry.moveTo(directory, subDir, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not move a file: ' + file1 + ' into directory: ' + dstDir + '\n' + subDir + ' directory already exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // check that original dir still exists directory.getDirectory(subDir, { create : false }, function (dirEntry) { expect(dirEntry).toBeDefined(); expect(dirEntry.fullPath).toCanonicallyMatch(dirPath); // check that original file still exists root.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // cleanup deleteEntry(file1); deleteEntry(dstDir); done(); }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); }, failed.bind(null, done, 'directory.getDirectory - Error getting directory, making sure that original directory still exists: ' + subDir)); }); }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + subDir)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory : ' + dstDir)); }, failed.bind(null, done, 'createFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.74 moveTo: directory onto existing file", function (done) { var file1 = "entry.move.dof.file1", srcDir = "entry.move.dof.srcDir", dirPath = joinURL(root.fullPath, srcDir), filePath = joinURL(root.fullPath, file1); // create a new directory entry to kick off it createDirectory(srcDir, function (entry) { // create file root.getFile(file1, { create : true }, function (fileEntry) { // move directory onto file entry.moveTo(root, file1, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not move : \n' + srcDir + ' into root directory renamed as ' + file1 + '\n' + file1 + ' file already exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // test that original directory exists root.getDirectory(srcDir, { create : false }, function (dirEntry) { // returning confirms existence so just check fullPath entry expect(dirEntry).toBeDefined(); expect(dirEntry.fullPath).toCanonicallyMatch(dirPath); // test that original file exists root.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // cleanup deleteEntry(file1); deleteEntry(srcDir); done(); }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); }, failed.bind(null, done, 'directory.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); }); }, failed.bind(null, done, 'root.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }); it("file.spec.75 copyTo: directory onto existing file", function (done) { var file1 = "entry.copy.dof.file1", srcDir = "entry.copy.dof.srcDir", dirPath = joinURL(root.fullPath, srcDir), filePath = joinURL(root.fullPath, file1); // create a new directory entry to kick off it createDirectory(srcDir, function (entry) { // create file root.getFile(file1, { create : true }, function () { // copy directory onto file entry.copyTo(root, file1, succeed.bind(null, done, 'entry.copyTo - Unexpected success callback, it should not copy : \n' + srcDir + ' into root directory renamed as ' + file1 + '\n' + file1 + ' file already exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); //check that original dir still exists root.getDirectory(srcDir, { create : false }, function (dirEntry) { // returning confirms existence so just check fullPath entry expect(dirEntry).toBeDefined(); expect(dirEntry.fullPath).toCanonicallyMatch(dirPath); // test that original file still exists root.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // cleanup deleteEntry(file1); deleteEntry(srcDir); done(); }, failed.bind(null, done, 'root.getFile - Error getting file, making sure that original file still exists: ' + file1)); }, failed.bind(null, done, 'root.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); }); }, failed.bind(null, done, 'root.getFile - Error creating file : ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }); it("file.spec.76 moveTo: directory onto directory that is not empty", function (done) { var srcDir = "entry.move.dod.srcDir", dstDir = "entry.move.dod.dstDir", subDir = "subDir", srcPath = joinURL(root.fullPath, srcDir), dstPath = joinURL(joinURL(root.fullPath, dstDir), subDir); // ensure destination directory is cleaned up before it deleteEntry(dstDir, function () { // create a new file entry to kick off it createDirectory(srcDir, function (entry) { // create top level directory root.getDirectory(dstDir, { create : true }, function (directory) { // create sub-directory directory.getDirectory(subDir, { create : true }, function () { // move srcDir onto dstDir (not empty) entry.moveTo(root, dstDir, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, it should not copy : \n' + srcDir + ' into root directory renamed as ' + dstDir + '\n' + dstDir + ' directory already exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.INVALID_MODIFICATION_ERR); // making sure destination directory still exists directory.getDirectory(subDir, { create : false }, function (dirEntry) { // returning confirms existence so just check fullPath entry expect(dirEntry).toBeDefined(); expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); // making sure source directory exists root.getDirectory(srcDir, { create : false }, function (srcEntry) { expect(srcEntry).toBeDefined(); expect(srcEntry.fullPath).toCanonicallyMatch(srcPath); // cleanup deleteEntry(srcDir); deleteEntry(dstDir); done(); }, failed.bind(null, done, 'root.getDirectory - Error getting directory, making sure that original directory still exists: ' + srcDir)); }, failed.bind(null, done, 'directory.getDirectory - Error getting directory, making sure that original directory still exists: ' + subDir)); }); }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + subDir)); }, failed.bind(null, done, 'directory.getDirectory - Error creating directory : ' + subDir)); }, failed.bind(null, done, 'createDirectory - Error creating directory : ' + srcDir)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.77 moveTo: file replace existing file", function (done) { var file1 = "entry.move.frf.file1", file2 = "entry.move.frf.file2", file1Path = joinURL(root.fullPath, file1), file2Path = joinURL(root.fullPath, file2); // create a new directory entry to kick off it createFile(file1, function (entry) { // create file root.getFile(file2, { create : true }, function () { // replace file2 with file1 entry.moveTo(root, file2, function (entry2) { expect(entry2).toBeDefined(); expect(entry2.isFile).toBe(true); expect(entry2.isDirectory).toBe(false); expect(entry2.fullPath).toCanonicallyMatch(file2Path); expect(entry2.name).toCanonicallyMatch(file2); // old file should not exists root.getFile(file1, { create : false }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, file: ' + file1 + ' should not exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // test that new file exists root.getFile(file2, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(file2Path); // cleanup deleteEntry(file1); deleteEntry(file2); done(); }, failed.bind(null, done, 'root.getFile - Error getting moved file: ' + file2)); }); }, failed.bind(null, done, 'entry.moveTo - Error moving file : ' + file1 + ' to root as: ' + file2)); }, failed.bind(null, done, 'root.getFile - Error creating file: ' + file2)); }, failed.bind(null, done, 'createFile - Error creating file: ' + file1)); }); it("file.spec.78 moveTo: directory replace empty directory", function (done) { var file1 = "file1", srcDir = "entry.move.drd.srcDir", dstDir = "entry.move.drd.dstDir", srcPath = joinURL(root.fullPath, srcDir), dstPath = joinURL(root.fullPath, dstDir), filePath = dstPath + '/' + file1; // ensure destination directory is cleaned up before it deleteEntry(dstDir, function () { // create a new directory entry to kick off it createDirectory(srcDir, function (directory) { // create a file within source directory directory.getFile(file1, { create : true }, function () { // create destination directory root.getDirectory(dstDir, { create : true }, function () { // move srcDir to dstDir directory.moveTo(root, dstDir, function (dirEntry) { expect(dirEntry).toBeDefined(); expect(dirEntry.isFile).toBe(false); expect(dirEntry.isDirectory).toBe(true); expect(dirEntry.fullPath).toCanonicallyMatch(dstPath); expect(dirEntry.name).toCanonicallyMatch(dstDir); // check that old directory contents have been moved dirEntry.getFile(file1, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.fullPath).toCanonicallyMatch(filePath); // check that old directory no longer exists root.getDirectory(srcDir, { create : false }, succeed.bind(null, done, 'root.getDirectory - Unexpected success callback, directory: ' + srcDir + ' should not exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(srcDir); deleteEntry(dstDir); done(); }); }, failed.bind(null, done, 'dirEntry.getFile - Error getting moved file: ' + file1)); }, failed.bind(null, done, 'entry.moveTo - Error moving directory : ' + srcDir + ' to root as: ' + dstDir)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory: ' + dstDir)); }, failed.bind(null, done, 'root.getFile - Error creating file: ' + file1)); }, failed.bind(null, done, 'createDirectory - Error creating directory: ' + srcDir)); }, failed.bind(null, done, 'deleteEntry - Error removing directory : ' + dstDir)); }); it("file.spec.79 moveTo: directory that does not exist", function (done) { var file1 = "entry.move.dnf.file1", dstDir = "entry.move.dnf.dstDir", dstPath = joinURL(root.fullPath, dstDir); // create a new file entry to kick off it createFile(file1, function (entry) { // move file to directory that does not exist directory = new DirectoryEntry(); directory.filesystem = root.filesystem; directory.fullPath = dstPath; entry.moveTo(directory, null, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, parent directory: ' + dstPath + ' should not exists'), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); // cleanup deleteEntry(file1); done(); }); }, failed.bind(null, done, 'createFile - Error creating file: ' + file1)); }); it("file.spec.80 moveTo: invalid target name", function (done) { var file1 = "entry.move.itn.file1", file2 = "bad:file:name"; // create a new file entry to kick off it createFile(file1, function (entry) { // move file1 to file2 entry.moveTo(root, file2, succeed.bind(null, done, 'entry.moveTo - Unexpected success callback, : ' + file1 + ' to root as: ' + file2), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.ENCODING_ERR); // cleanup deleteEntry(file1); done(); }); }, failed.bind(null, done, 'createFile - Error creating file: ' + file1)); }); }); //Entry describe('FileReader', function () { it("file.spec.81 should have correct methods", function () { var reader = new FileReader(); expect(reader).toBeDefined(); expect(typeof reader.readAsBinaryString).toBe('function'); expect(typeof reader.readAsDataURL).toBe('function'); expect(typeof reader.readAsText).toBe('function'); expect(typeof reader.readAsArrayBuffer).toBe('function'); expect(typeof reader.abort).toBe('function'); }); }); //FileReader describe('Read method', function () { it("file.spec.82 should error out on non-existent file", function (done) { var fileName = cordova.platformId === 'windowsphone' ? root.toURL() + "/" + "somefile.txt" : "somefile.txt", verifier = function (evt) { expect(evt).toBeDefined(); expect(evt.target.error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }; root.getFile(fileName, { create : true }, function (entry) { entry.file(function (file) { deleteEntry(fileName, function () { //Create FileReader var reader = new FileReader(); reader.onerror = verifier; reader.onload = succeed.bind(null, done, 'reader.onload - Unexpected success callback, file: ' + fileName + ' it should not exists'); reader.readAsText(file); }, failed.bind(null, done, 'deleteEntry - Error removing file: ' + fileName)); }, failed.bind(null, done, 'entry.file - Error reading file: ' + fileName)); }, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); }); it("file.spec.83 should be able to read native blob objects", function (done) { // Skip test if blobs are not supported (e.g.: Android 2.3). if (typeof window.Blob == 'undefined' || typeof window.Uint8Array == 'undefined') { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); } var contents = 'asdf'; var uint8Array = new Uint8Array(contents.length); for (var i = 0; i < contents.length; ++i) { uint8Array[i] = contents.charCodeAt(i); } var Builder = window.BlobBuilder || window.WebKitBlobBuilder; var blob; if (Builder) { var builder = new Builder(); builder.append(uint8Array.buffer); builder.append(contents); blob = builder.getBlob("text/plain"); } else { try { // iOS 6 does not support Views, so pass in the buffer. blob = new Blob([uint8Array.buffer, contents]); } catch (e) { // Skip the test if we can't create a blob (e.g.: iOS 5). if (e instanceof TypeError) { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); } throw e; } } var verifier = function (evt) { expect(evt).toBeDefined(); expect(evt.target.result).toBe('asdfasdf'); done(); }; var reader = new FileReader(); reader.onloadend = verifier; reader.onerror = failed.bind(null, done, 'reader.onerror - Error reading file: ' + blob); reader.readAsText(blob); }); function writeDummyFile(writeBinary, callback, done) { var fileName = "dummy.txt", fileEntry = null, fileData = '\u20AC\xEB - There is an exception to every rule. Except this one.', fileDataAsBinaryString = '\xe2\x82\xac\xc3\xab - There is an exception to every rule. Except this one.', createWriter = function (fe) { fileEntry = fe; fileEntry.createWriter(writeFile, failed.bind(null, done, 'fileEntry.createWriter - Error reading file: ' + fileName)); }, // writes file and reads it back in writeFile = function (writer) { writer.onwriteend = function () { fileEntry.file(function (f) { callback(fileEntry, f, fileData, fileDataAsBinaryString); }, failed.bind(null, done, 'writer.onwriteend - Error writing data on file: ' + fileName)); }; writer.write(fileData); }; fileData += writeBinary ? 'bin:\x01\x00' : ''; fileDataAsBinaryString += writeBinary ? 'bin:\x01\x00' : ''; // create a file, write to it, and read it in again createFile(fileName, createWriter, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); } function runReaderTest(funcName, writeBinary, done, verifierFunc, sliceStart, sliceEnd) { writeDummyFile(writeBinary, function (fileEntry, file, fileData, fileDataAsBinaryString) { var verifier = function (evt) { expect(evt).toBeDefined(); verifierFunc(evt, fileData, fileDataAsBinaryString); }; var reader = new FileReader(); reader.onload = verifier; reader.onerror = failed.bind(null, done, 'reader.onerror - Error reading file: ' + file + ' using function: ' + funcName); if (sliceEnd !== undefined) { file = file.slice(sliceStart, sliceEnd); } else if (sliceStart !== undefined) { file = file.slice(sliceStart); } reader[funcName](file); }, done); } function arrayBufferEqualsString(ab, str) { var buf = new Uint8Array(ab); var match = buf.length == str.length; for (var i = 0; match && i < buf.length; i++) { match = buf[i] == str.charCodeAt(i); } return match; } it("file.spec.84 should read file properly, readAsText", function (done) { runReaderTest('readAsText', false, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result).toBe(fileData); done(); }); }); it("file.spec.85 should read file properly, Data URI", function (done) { runReaderTest('readAsDataURL', true, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result.substr(0, 23)).toBe("data:text/plain;base64,"); //The atob function it is completely ignored during mobilespec execution, besides the returned object: evt //it is encoded and the atob function is aimed to decode a string. Even with btoa (encode) the function it gets stucked //because of the Unicode characters that contains the fileData object. //Issue reported at JIRA with all the details: CB-7095 //expect(evt.target.result.slice(23)).toBe(atob(fileData)); done(); }); }); it("file.spec.86 should read file properly, readAsBinaryString", function (done) { runReaderTest('readAsBinaryString', true, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result).toBe(fileDataAsBinaryString); done(); }); }); it("file.spec.87 should read file properly, readAsArrayBuffer", function (done) { // Skip test if ArrayBuffers are not supported (e.g.: Android 2.3). if (typeof window.ArrayBuffer == 'undefined') { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); } runReaderTest('readAsArrayBuffer', true, done, function (evt, fileData, fileDataAsBinaryString) { expect(arrayBufferEqualsString(evt.target.result, fileDataAsBinaryString)).toBe(true); done(); }); }); it("file.spec.88 should read sliced file: readAsText", function (done) { runReaderTest('readAsText', false, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result).toBe(fileDataAsBinaryString.slice(10, 40)); done(); }, 10, 40); }); it("file.spec.89 should read sliced file: slice past eof", function (done) { runReaderTest('readAsText', false, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result).toBe(fileData.slice(-5, 9999)); done(); }, -5, 9999); }); it("file.spec.90 should read sliced file: slice to eof", function (done) { runReaderTest('readAsText', false, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result).toBe(fileData.slice(-5)); done(); }, -5); }); it("file.spec.91 should read empty slice", function (done) { runReaderTest('readAsText', false, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result).toBe(''); done(); }, 0, 0); }); it("file.spec.92 should read sliced file properly, readAsDataURL", function (done) { runReaderTest('readAsDataURL', true, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result.slice(0, 23)).toBe("data:text/plain;base64,"); //The atob function it is completely ignored during mobilespec execution, besides the returned object: evt //it is encoded and the atob function is aimed to decode a string. Even with btoa (encode) the function it gets stucked //because of the Unicode characters that contains the fileData object. //Issue reported at JIRA with all the details: CB-7095 //expect(evt.target.result.slice(23)).toBe(atob(fileDataAsBinaryString.slice(10, -3))); done(); }, 10, -3); }); it("file.spec.93 should read sliced file properly, readAsBinaryString", function (done) { runReaderTest('readAsBinaryString', true, done, function (evt, fileData, fileDataAsBinaryString) { expect(evt.target.result).toBe(fileDataAsBinaryString.slice(-10, -5)); done(); }, -10, -5); }); it("file.spec.94 should read sliced file properly, readAsArrayBuffer", function (done) { // Skip test if ArrayBuffers are not supported (e.g.: Android 2.3). if (typeof window.ArrayBuffer == 'undefined') { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); } runReaderTest('readAsArrayBuffer', true, done, function (evt, fileData, fileDataAsBinaryString) { expect(arrayBufferEqualsString(evt.target.result, fileDataAsBinaryString.slice(0, -1))).toBe(true); done(); }, 0, -1); }); }); //Read method describe('FileWriter', function () { it("file.spec.95 should have correct methods", function (done) { // retrieve a FileWriter object var fileName = "writer.methods"; // FileWriter root.getFile(fileName, { create : true }, function (fileEntry) { fileEntry.createWriter(function (writer) { expect(writer).toBeDefined(); expect(typeof writer.write).toBe('function'); expect(typeof writer.seek).toBe('function'); expect(typeof writer.truncate).toBe('function'); expect(typeof writer.abort).toBe('function'); // cleanup deleteFile(fileName); done(); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); }); it("file.spec.96 should be able to write and append to file, createWriter", function (done) { var fileName = "writer.append.createWriter", // file content content = "There is an exception to every rule.", // for checkin file length length = content.length; // create file, then write and append to it createFile(fileName, function (fileEntry) { // writes initial file content fileEntry.createWriter(function (writer) { //Verifiers declaration var verifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // Append some more data var exception = " Except this one."; writer.onwriteend = secondVerifier; length += exception.length; writer.seek(writer.length); writer.write(exception); }, secondVerifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.97 should be able to write and append to file, File object", function (done) { var fileName = "writer.append.File", // file content content = "There is an exception to every rule.", // for checking file length length = content.length; root.getFile(fileName, { create : true }, function (fileEntry) { fileEntry.createWriter(function (writer) { //Verifiers declaration var verifier = function () { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // Append some more data var exception = " Except this one."; writer.onwriteend = secondVerifier; length += exception.length; writer.seek(writer.length); writer.write(exception); }, secondVerifier = function () { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'root.getFile - Error creating file: ' + fileName)); }); it("file.spec.98 should be able to seek to the middle of the file and write more data than file.length", function (done) { var fileName = "writer.seek.write", // file content content = "This is our sentence.", // for checking file length length = content.length; // create file, then write and append to it createFile(fileName, function (fileEntry) { fileEntry.createWriter(function (writer) { //Verifiers declaration var verifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // Append some more data var exception = "newer sentence."; writer.onwriteend = secondVerifier; length = 12 + exception.length; writer.seek(12); writer.write(exception); }, secondVerifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.99 should be able to seek to the middle of the file and write less data than file.length", function (done) { var fileName = "writer.seek.write2", // file content content = "This is our sentence.", // for checking file length length = content.length; // create file, then write and append to it createFile(fileName, function (fileEntry) { fileEntry.createWriter(function (writer) { // Verifiers declaration var verifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // Append some more data var exception = "new."; writer.onwriteend = secondVerifier; length = 8 + exception.length; writer.seek(8); writer.write(exception); }, secondVerifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.100 should be able to write XML data", function (done) { var fileName = "writer.xml", // file content content = '<?xml version="1.0" encoding="UTF-8"?>\n<test prop="ack">\nData\n</test>\n', // for testing file length length = content.length; // creates file, then write XML data createFile(fileName, function (fileEntry) { fileEntry.createWriter(function (writer) { //Verifier content var verifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.101 should be able to write JSON data", function (done) { var fileName = "writer.json", // file content content = '{ "name": "Guy Incognito", "email": "here@there.com" }', // for testing file length length = content.length; // creates file, then write JSON content createFile(fileName, function (fileEntry) { fileEntry.createWriter(function (writer) { //Verifier declaration var verifier = function (evt) { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.102 should be able to seek", function (done) { var fileName = "writer.seek", // file content content = "There is an exception to every rule. Except this one.", // for testing file length length = content.length; // creates file, then write JSON content createFile(fileName, function (fileEntry) { // writes file content and tests writer.seek fileEntry.createWriter(function (writer) { //Verifier declaration var verifier = function () { expect(writer.position).toBe(length); writer.seek(-5); expect(writer.position).toBe(length - 5); writer.seek(length + 100); expect(writer.position).toBe(length); writer.seek(10); expect(writer.position).toBe(10); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.seek(-100); expect(writer.position).toBe(0); writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.103 should be able to truncate", function (done) { var fileName = "writer.truncate", content = "There is an exception to every rule. Except this one."; // creates file, writes to it, then truncates it createFile(fileName, function (fileEntry) { fileEntry.createWriter(function (writer) { // Verifier declaration var verifier = function () { expect(writer.length).toBe(36); expect(writer.position).toBe(36); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = function () { //Truncate process after write writer.onwriteend = verifier; writer.truncate(36); }; writer.write(content); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.104 should be able to write binary data from an ArrayBuffer", function (done) { // Skip test if ArrayBuffers are not supported (e.g.: Android 2.3). if (typeof window.ArrayBuffer == 'undefined') { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); return; } var fileName = "bufferwriter.bin", // file content data = new ArrayBuffer(32), dataView = new Int8Array(data), // for verifying file length length = 32; for (i = 0; i < dataView.length; i++) { dataView[i] = i; } // creates file, then write content createFile(fileName, function (fileEntry) { // writes file content fileEntry.createWriter(function (writer) { //Verifier declaration var verifier = function () { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(data); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.105 should be able to write binary data from a Blob", function (done) { // Skip test if Blobs are not supported (e.g.: Android 2.3). if ((typeof window.Blob == 'undefined' && typeof window.WebKitBlobBuilder == 'undefined') || typeof window.ArrayBuffer == 'undefined') { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); return; } var fileName = "blobwriter.bin", // file content data = new ArrayBuffer(32), dataView = new Int8Array(data), blob, // for verifying file length length = 32; for (i = 0; i < dataView.length; i++) { dataView[i] = i; } try { // Mobile Safari: Use Blob constructor blob = new Blob([data], { "type" : "application/octet-stream" }); } catch (e) { if (window.WebKitBlobBuilder) { // Android Browser: Use deprecated BlobBuilder var builder = new WebKitBlobBuilder(); builder.append(data); blob = builder.getBlob('application/octet-stream'); } else { // We have no way defined to create a Blob, so fail fail(); } } if (typeof blob !== 'undefined') { // creates file, then write content createFile(fileName, function (fileEntry) { fileEntry.createWriter(function (writer) { //Verifier declaration var verifier = function () { expect(writer.length).toBe(length); expect(writer.position).toBe(length); // cleanup deleteFile(fileName); done(); }; //Write process writer.onwriteend = verifier; writer.write(blob); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); } }); it("file.spec.106 should be able to write a File to a FileWriter", function (done) { var dummyFileName = 'dummy.txt', outputFileName = 'verify.txt', dummyFileText = 'This text should be written to two files', verifier = function (outputFileWriter) { expect(outputFileWriter.length).toBe(dummyFileText.length); expect(outputFileWriter.position).toBe(dummyFileText.length); deleteFile(outputFileName); done(); }, writeFile = function (fileName, fileData, win) { var theWriter, filePath = joinURL(root.fullPath, fileName), // writes file content to new file write_file = function (fileEntry) { writerEntry = fileEntry; fileEntry.createWriter(function (writer) { theWriter = writer; writer.onwriteend = function (ev) { if (typeof fileData.length !== "undefined") { expect(theWriter.length).toBe(fileData.length); expect(theWriter.position).toBe(fileData.length); } win(theWriter); }; writer.onerror = failed.bind(null, done, 'writer.onerror - Error writing content on file: ' + fileName); writer.write(fileData); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }; createFile(fileName, write_file, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }, openFile = function (fileName, callback) { root.getFile(fileName, { create : false }, function (fileEntry) { fileEntry.file(callback, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'root.getFile - Error getting file: ' + fileName)); }; writeFile(dummyFileName, dummyFileText, function (dummyFileWriter) { openFile(dummyFileName, function (file) { writeFile(outputFileName, file, verifier); }); }); }); it("file.spec.107 should be able to write a sliced File to a FileWriter", function (done) { var dummyFileName = 'dummy2.txt', outputFileName = 'verify2.txt', dummyFileText = 'This text should be written to two files', verifier = function (outputFileWriter) { expect(outputFileWriter.length).toBe(10); expect(outputFileWriter.position).toBe(10); deleteFile(outputFileName); done(); }, writeFile = function (fileName, fileData, win) { var theWriter, filePath = joinURL(root.fullPath, fileName), // writes file content to new file write_file = function (fileEntry) { writerEntry = fileEntry; fileEntry.createWriter(function (writer) { theWriter = writer; writer.onwriteend = function (ev) { if (typeof fileData.length !== "undefined") { expect(theWriter.length).toBe(fileData.length); expect(theWriter.position).toBe(fileData.length); } win(theWriter); }; writer.onerror = failed.bind(null, done, 'writer.onerror - Error writing content on file: ' + fileName); writer.write(fileData); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }; createFile(fileName, write_file, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }, openFile = function (fileName, callback) { root.getFile(fileName, { create : false }, function (fileEntry) { fileEntry.file(callback, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'root.getFile - Error getting file: ' + fileName)); }; writeFile(dummyFileName, dummyFileText, function (dummyFileWriter) { openFile(dummyFileName, function (file) { writeFile(outputFileName, file.slice(10, 20), verifier); }); }); }); it("file.spec.108 should be able to write binary data from a File", function (done) { // Skip test if Blobs are not supported (e.g.: Android 2.3). if (typeof window.Blob == 'undefined' && typeof window.WebKitBlobBuilder == 'undefined') { expect(true).toFailWithMessage('Platform does not supported this feature'); done(); } var dummyFileName = "blobwriter.bin", outputFileName = 'verify.bin', // file content data = new ArrayBuffer(32), dataView = new Int8Array(data), blob, // for verifying file length length = 32, verifier = function (outputFileWriter) { expect(outputFileWriter.length).toBe(length); expect(outputFileWriter.position).toBe(length); // cleanup deleteFile(outputFileName); done(); }, writeFile = function (fileName, fileData, win) { var theWriter, filePath = joinURL(root.fullPath, fileName), // writes file content to new file write_file = function (fileEntry) { writerEntry = fileEntry; fileEntry.createWriter(function (writer) { theWriter = writer; writer.onwriteend = function (ev) { if (typeof fileData.length !== "undefined") { expect(theWriter.length).toBe(fileData.length); expect(theWriter.position).toBe(fileData.length); } win(theWriter); }; writer.onerror = failed.bind(null, done, 'writer.onerror - Error writing content on file: ' + fileName); writer.write(fileData); }, failed.bind(null, done, 'fileEntry.createWriter - Error creating writer using fileEntry: ' + fileEntry.name)); }; createFile(fileName, write_file, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }, openFile = function (fileName, callback) { root.getFile(fileName, { create : false }, function (fileEntry) { fileEntry.file(callback, failed.bind(null, done, 'fileEntry.file - Error reading file using fileEntry: ' + fileEntry.name)); }, failed.bind(null, done, 'root.getFile - Error getting file: ' + fileName)); }; for (i = 0; i < dataView.length; i++) { dataView[i] = i; } try { // Mobile Safari: Use Blob constructor blob = new Blob([data], { "type" : "application/octet-stream" }); } catch (e) { if (window.WebKitBlobBuilder) { // Android Browser: Use deprecated BlobBuilder var builder = new WebKitBlobBuilder(); builder.append(data); blob = builder.getBlob('application/octet-stream'); } else { // We have no way defined to create a Blob, so fail fail(); } } if (typeof blob !== 'undefined') { // creates file, then write content writeFile(dummyFileName, blob, function (dummyFileWriter) { openFile(dummyFileName, function (file) { writeFile(outputFileName, file, verifier); }); }); } }); }); //FileWritter describe('Backwards compatibility', function () { /* These specs exist to test that the File plugin can still recognize file:/// * URLs, and can resolve them to FileEntry and DirectoryEntry objects. * They rely on an undocumented interface to File which provides absolute file * paths, which are not used internally anymore. * If that interface is not present, then these tests will silently succeed. */ it("file.spec.109 should be able to resolve a file:/// URL", function (done) { var localFilename = 'file.txt'; var originalEntry; root.getFile(localFilename, { create : true }, function (entry) { originalEntry = entry; /* This is an undocumented interface to File which exists only for testing * backwards compatibilty. By obtaining the raw filesystem path of the download * location, we can pass that to ft.download() to make sure that previously-stored * paths are still valid. */ cordova.exec(function (localPath) { window.resolveLocalFileSystemURL("file://" + encodeURI(localPath), function (fileEntry) { expect(fileEntry.toURL()).toEqual(originalEntry.toURL()); // cleanup deleteFile(localFilename); done(); }, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving URI: file://' + encodeURI(localPath))); }, done, 'File', '_getLocalFilesystemPath', [entry.toURL()]); }, failed.bind(null, done, 'root.getFile - Error creating file: ' + localFilename)); }); }); //Backwards Compatibility describe('Parent References', function () { /* These specs verify that paths with parent references i("..") in them * work correctly, and do not cause the application to crash. */ it("file.spec.110 should not throw exception resolving parent refefences", function (done) { /* This is a direct copy of file.spec.9, with the filename changed, * as reported in CB-5721. */ var fileName = "resolve.file.uri"; // create a new file entry createFile("../" + fileName, function (entry) { // lookup file system entry window.resolveLocalFileSystemURL(entry.toURL(), function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.name).toCanonicallyMatch(fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'window.resolveLocalFileSystemURL - Error resolving URI: ' + entry.toURL())); }, failed.bind(null, done, 'createFile - Error creating file: ../' + fileName)); }); it("file.spec.111 should not traverse above above the root directory", function (done) { var fileName = "traverse.file.uri"; // create a new file entry createFile(fileName, function (entry) { // lookup file system entry root.getFile('../' + fileName, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.name).toBe(fileName); expect(fileEntry.fullPath).toCanonicallyMatch('/' + fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'root.getFile - Error getting file: ../' + fileName)); }, failed.bind(null, done, 'createFile - Error creating file: ../' + fileName)); }); it("file.spec.112 should traverse above above the current directory", function (done) { var fileName = "traverse2.file.uri", dirName = "traverse2.subdir"; // create a new directory and a file entry createFile(fileName, function () { createDirectory(dirName, function (entry) { // lookup file system entry entry.getFile('../' + fileName, { create : false }, function (fileEntry) { expect(fileEntry).toBeDefined(); expect(fileEntry.name).toBe(fileName); expect(fileEntry.fullPath).toCanonicallyMatch('/' + fileName); // cleanup deleteEntry(fileName); deleteEntry(dirName); done(); }, failed.bind(null, done, 'entry.getFile - Error getting file: ' + fileName + ' recently created above: ' + dirName)); }, failed.bind(null, done, 'createDirectory - Error creating directory: ' + dirName)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.113 getFile: get Entry should error for missing file above root directory", function (done) { var fileName = "../missing.file"; // create:false, exclusive:false, file does not exist root.getFile(fileName, { create : false }, succeed.bind(null, done, 'root.getFile - Unexpected success callback, it should not locate nonexistent file: ' + fileName), function (error) { expect(error).toBeDefined(); expect(error).toBeFileError(FileError.NOT_FOUND_ERR); done(); }); }); }); //Parent References describe('toNativeURL interface', function () { /* These specs verify that FileEntries have a toNativeURL method * which appears to be sane. */ var pathExpect = cordova.platformId === 'windowsphone' ? "//nativ" : "file://"; it("file.spec.114 fileEntry should have a toNativeURL method", function (done) { var fileName = "native.file.uri"; // create a new file entry createFile(fileName, function (entry) { expect(entry.toNativeURL).toBeDefined(); expect(entry.name).toCanonicallyMatch(fileName); expect(typeof entry.toNativeURL).toBe('function'); var nativeURL = entry.toNativeURL(); expect(typeof nativeURL).toBe("string"); expect(nativeURL.substring(0, 7)).toEqual(pathExpect); expect(nativeURL.substring(nativeURL.length - fileName.length)).toEqual(fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.115 DirectoryReader should return entries with toNativeURL method", function (done) { var dirName = 'nativeEntries.dir', fileName = 'nativeEntries.file', checkEntries = function (entries) { expect(entries).toBeDefined(); expect(entries instanceof Array).toBe(true); expect(entries.length).toBe(1); expect(entries[0].toNativeURL).toBeDefined(); expect(typeof entries[0].toNativeURL).toBe('function'); var nativeURL = entries[0].toNativeURL(); expect(typeof nativeURL).toBe("string"); expect(nativeURL.substring(0, 7)).toEqual(pathExpect); expect(nativeURL.substring(nativeURL.length - fileName.length)).toEqual(fileName); // cleanup directory.removeRecursively(null, null); done(); }; // create a new file entry root.getDirectory(dirName, { create : true }, function (directory) { directory.getFile(fileName, { create : true }, function (fileEntry) { var reader = directory.createReader(); reader.readEntries(checkEntries, failed.bind(null, done, 'reader.readEntries - Error reading entries from directory: ' + dirName)); }, failed.bind(null, done, 'directory.getFile - Error creating file: ' + fileName)); }, failed.bind(null, done, 'root.getDirectory - Error creating directory: ' + dirName)); }); it("file.spec.116 resolveLocalFileSystemURL should return entries with toNativeURL method", function (done) { var fileName = "native.resolve.uri"; // create a new file entry createFile(fileName, function (entry) { resolveLocalFileSystemURL(entry.toURL(), function (entry) { expect(entry.toNativeURL).toBeDefined(); expect(entry.name).toCanonicallyMatch(fileName); expect(typeof entry.toNativeURL).toBe('function'); var nativeURL = entry.toNativeURL(); expect(typeof nativeURL).toBe("string"); expect(nativeURL.substring(0, 7)).toEqual(pathExpect); expect(nativeURL.substring(nativeURL.length - fileName.length)).toEqual(fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + entry.toURL())); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); }); //toNativeURL interface describe('resolveLocalFileSystemURL on file://', function () { /* These specs verify that window.resolveLocalFileSystemURL works correctly on file:// URLs */ it("file.spec.117 should not resolve native URLs outside of FS roots", function (done) { // lookup file system entry window.resolveLocalFileSystemURL("file:///this.is.an.invalid.url", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file:///this.is.an.invalid.url'), function (error) { expect(error).toBeDefined(); done(); }); }); it("file.spec.118 should not resolve native URLs outside of FS roots", function (done) { // lookup file system entry window.resolveLocalFileSystemURL("file://localhost/this.is.an.invalid.url", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file://localhost/this.is.an.invalid.url'), function (error) { expect(error).toBeDefined(); done(); }); }); it("file.spec.119 should not resolve invalid native URLs", function (done) { // lookup file system entry window.resolveLocalFileSystemURL("file://localhost", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file://localhost'), function (error) { expect(error).toBeDefined(); done(); }); }); it("file.spec.120 should not resolve invalid native URLs with query strings", function (done) { // lookup file system entry window.resolveLocalFileSystemURL("file://localhost?test/test", succeed.bind(null, done, 'window.resolveLocalFileSystemURL - Unexpected success callback, it should not resolve invalid URL: file://localhost?test/test'), function (error) { expect(error).toBeDefined(); done(); }); }); it("file.spec.121 should resolve native URLs returned by API", function (done) { var fileName = "native.resolve.uri1"; // create a new file entry createFile(fileName, function (entry) { resolveLocalFileSystemURL(entry.toNativeURL(), function (fileEntry) { expect(fileEntry.fullPath).toCanonicallyMatch("/" + fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + entry.toNativeURL())); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.122 should resolve native URLs returned by API with localhost", function (done) { var fileName = "native.resolve.uri2"; // create a new file entry createFile(fileName, function (entry) { var url = entry.toNativeURL(); url = url.replace("///", "//localhost/"); resolveLocalFileSystemURL(url, function (fileEntry) { expect(fileEntry.fullPath).toCanonicallyMatch("/" + fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + url)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.123 should resolve native URLs returned by API with query string", function (done) { var fileName = "native.resolve.uri3"; // create a new file entry createFile(fileName, function (entry) { var url = entry.toNativeURL(); url = url + "?test/test"; resolveLocalFileSystemURL(url, function (fileEntry) { expect(fileEntry.fullPath).toCanonicallyMatch("/" + fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + url)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); it("file.spec.124 should resolve native URLs returned by API with localhost and query string", function (done) { var fileName = "native.resolve.uri4"; // create a new file entry createFile(fileName, function (entry) { var url = entry.toNativeURL(); url = url.replace("///", "//localhost/") + "?test/test"; resolveLocalFileSystemURL(url, function (fileEntry) { expect(fileEntry.fullPath).toCanonicallyMatch("/" + fileName); // cleanup deleteEntry(fileName); done(); }, failed.bind(null, done, 'resolveLocalFileSystemURL - Error resolving file URL: ' + url)); }, failed.bind(null, done, 'createFile - Error creating file: ' + fileName)); }); }); //resolveLocalFileSystemURL on file:// describe('cross-file-system copy and move', function () { /* These specs verify that Entry.copyTo and Entry.moveTo work correctly * when crossing filesystem boundaries. */ it("file.spec.125 copyTo: temporary -> persistent", function (done) { var file1 = "entry.copy.file1a", file2 = "entry.copy.file2a", sourceEntry, fullPath = joinURL(root.fullPath, file2), validateFile = function (entry) { // a bit redundant since copy returned this entry already expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(file2); expect(entry.fullPath).toCanonicallyMatch(fullPath); expect(entry.filesystem).toBeDefined(); expect(entry.filesystem.name).toEqual("persistent"); // cleanup entry.remove(); sourceEntry.remove(); done(); }, createSourceAndTransfer = function () { temp_root.getFile(file1, { create : true }, function (entry) { expect(entry.filesystem).toBeDefined(); expect(entry.filesystem.name).toEqual("temporary"); sourceEntry = entry; // Save for later cleanup entry.copyTo(persistent_root, file2, validateFile, failed.bind(null, done, 'entry.copyTo - Error copying file: ' + file1 + ' to PERSISTENT root as: ' + file2)); }, failed.bind(null, done, 'temp_root.getFile - Error creating file: ' + file1 + 'at TEMPORAL root')); }; // Delete any existing file to start things off persistent_root.getFile(file2, {}, function (entry) { entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); }, createSourceAndTransfer); }); it("file.spec.126 copyTo: persistent -> temporary", function (done) { var file1 = "entry.copy.file1b", file2 = "entry.copy.file2b", sourceEntry, fullPath = joinURL(temp_root.fullPath, file2), validateFile = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(file2); expect(entry.fullPath).toCanonicallyMatch(fullPath); expect(entry.filesystem.name).toEqual("temporary"); // cleanup entry.remove(); sourceEntry.remove(); done(); }, createSourceAndTransfer = function () { persistent_root.getFile(file1, { create : true }, function (entry) { expect(entry).toBeDefined(); expect(entry.filesystem).toBeDefined(); expect(entry.filesystem.name).toEqual("persistent"); sourceEntry = entry; // Save for later cleanup entry.copyTo(temp_root, file2, validateFile, failed.bind(null, done, 'entry.copyTo - Error copying file: ' + file1 + ' to TEMPORAL root as: ' + file2)); }, failed.bind(null, done, 'persistent_root.getFile - Error creating file: ' + file1 + 'at PERSISTENT root')); }; // Delete any existing file to start things off temp_root.getFile(file2, {}, function (entry) { entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); }, createSourceAndTransfer); }); it("file.spec.127 moveTo: temporary -> persistent", function (done) { var file1 = "entry.copy.file1a", file2 = "entry.copy.file2a", sourceEntry, fullPath = joinURL(root.fullPath, file2), validateFile = function (entry) { // a bit redundant since copy returned this entry already expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(file2); expect(entry.fullPath).toCanonicallyMatch(fullPath); expect(entry.filesystem).toBeDefined(); expect(entry.filesystem.name).toEqual("persistent"); // cleanup entry.remove(); sourceEntry.remove(); done(); }, createSourceAndTransfer = function () { temp_root.getFile(file1, { create : true }, function (entry) { expect(entry.filesystem).toBeDefined(); expect(entry.filesystem.name).toEqual("temporary"); sourceEntry = entry; // Save for later cleanup entry.moveTo(persistent_root, file2, validateFile, failed.bind(null, done, 'entry.moveTo - Error moving file: ' + file1 + ' to PERSISTENT root as: ' + file2)); }, failed.bind(null, done, 'temp_root.getFile - Error creating file: ' + file1 + 'at TEMPORAL root')); }; // Delete any existing file to start things off persistent_root.getFile(file2, {}, function (entry) { entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); }, createSourceAndTransfer); }); it("file.spec.128 moveTo: persistent -> temporary", function (done) { var file1 = "entry.copy.file1b", file2 = "entry.copy.file2b", sourceEntry, fullPath = joinURL(temp_root.fullPath, file2), validateFile = function (entry) { expect(entry).toBeDefined(); expect(entry.isFile).toBe(true); expect(entry.isDirectory).toBe(false); expect(entry.name).toCanonicallyMatch(file2); expect(entry.fullPath).toCanonicallyMatch(fullPath); expect(entry.filesystem.name).toEqual("temporary"); // cleanup entry.remove(); sourceEntry.remove(); done(); }, createSourceAndTransfer = function () { persistent_root.getFile(file1, { create : true }, function (entry) { expect(entry).toBeDefined(); expect(entry.filesystem).toBeDefined(); expect(entry.filesystem.name).toEqual("persistent"); sourceEntry = entry; // Save for later cleanup entry.moveTo(temp_root, file2, validateFile, failed.bind(null, done, 'entry.moveTo - Error moving file: ' + file1 + ' to TEMPORAL root as: ' + file2)); }, failed.bind(null, done, 'persistent_root.getFile - Error creating file: ' + file1 + 'at PERSISTENT root')); }; // Delete any existing file to start things off temp_root.getFile(file2, {}, function (entry) { entry.remove(createSourceAndTransfer, failed.bind(null, done, 'entry.remove - Error removing file: ' + file2)); }, createSourceAndTransfer); }); it("file.spec.129 cordova.file.*Directory are set", function () { var expectedPaths = ['applicationDirectory', 'applicationStorageDirectory', 'dataDirectory', 'cacheDirectory']; if (cordova.platformId == 'android' || cordova.platformId == 'amazon-fireos') { expectedPaths.push('externalApplicationStorageDirectory', 'externalRootDirectory', 'externalCacheDirectory', 'externalDataDirectory'); } else if (cordova.platformId == 'blackberry10') { expectedPaths.push('externalRootDirectory', 'sharedDirectory'); } else if (cordova.platformId == 'ios') { expectedPaths.push('syncedDataDirectory', 'documentsDirectory', 'tempDirectory'); } else { console.log('Skipping test due on unsupported platform.'); return; } for (var i = 0; i < expectedPaths.length; ++i) { expect(typeof cordova.file[expectedPaths[i]]).toBe('string'); expect(cordova.file[expectedPaths[i]]).toMatch(/\/$/, 'Path should end with a slash'); } }); }); //cross-file-system copy and move }); //File API describe }; //****************************************************************************************** //***************************************Manual Tests*************************************** //****************************************************************************************** exports.defineManualTests = function (contentEl, createActionButton) { function resolveFs(fsname) { var fsURL = "cdvfile://localhost/" + fsname + "/"; logMessage("Resolving URL: " + fsURL); resolveLocalFileSystemURL(fsURL, function (entry) { logMessage("Success", 'green'); logMessage(entry.toURL(), 'blue'); logMessage(entry.toInternalURL(), 'blue'); logMessage("Resolving URL: " + entry.toURL()); resolveLocalFileSystemURL(entry.toURL(), function (entry2) { logMessage("Success", 'green'); logMessage(entry2.toURL(), 'blue'); logMessage(entry2.toInternalURL(), 'blue'); }, logError("resolveLocalFileSystemURL")); }, logError("resolveLocalFileSystemURL")); } function testPrivateURL() { requestFileSystem(TEMPORARY, 0, function (fileSystem) { logMessage("Temporary root is at " + fileSystem.root.toNativeURL()); fileSystem.root.getFile("testfile", { create : true }, function (entry) { logMessage("Temporary file is at " + entry.toNativeURL()); if (entry.toNativeURL().substring(0, 12) == "file:///var/") { logMessage("File starts with /var/, trying /private/var"); var newURL = "file://localhost/private/var/" + entry.toNativeURL().substring(12) + "?and=another_thing"; //var newURL = entry.toNativeURL(); logMessage(newURL, 'blue'); resolveLocalFileSystemURL(newURL, function (newEntry) { logMessage("Successfully resolved.", 'green'); logMessage(newEntry.toURL(), 'blue'); logMessage(newEntry.toNativeURL(), 'blue'); }, logError("resolveLocalFileSystemURL")); } }, logError("getFile")); }, logError("requestFileSystem")); } function clearLog() { var log = document.getElementById("info"); log.innerHTML = ""; } function logMessage(message, color) { var log = document.getElementById("info"); var logLine = document.createElement('div'); if (color) { logLine.style.color = color; } logLine.innerHTML = message; log.appendChild(logLine); } function logError(serviceName) { return function (err) { logMessage("ERROR: " + serviceName + " " + JSON.stringify(err), "red"); }; } var fsRoots = { "ios" : "library,library-nosync,documents,documents-nosync,cache,bundle,root,private", "android" : "files,files-external,documents,sdcard,cache,cache-external,root", "amazon-fireos" : "files,files-external,documents,sdcard,cache,cache-external,root" }; //Add title and align to content var div = document.createElement('h2'); div.appendChild(document.createTextNode('File Systems')); div.setAttribute("align", "center"); contentEl.appendChild(div); div = document.createElement('h3'); div.appendChild(document.createTextNode('Results are displayed in yellow status box below with expected results noted under that')); div.setAttribute("align", "center"); contentEl.appendChild(div); div = document.createElement('div'); div.setAttribute("id", "button"); div.setAttribute("align", "center"); contentEl.appendChild(div); if (fsRoots.hasOwnProperty(cordova.platformId)) { (fsRoots[cordova.platformId].split(',')).forEach(function (fs) { if (cordova.platformId === 'ios' && fs === 'private') { createActionButton("Test private URL (iOS)", function () { clearLog(); testPrivateURL(); }, 'button'); } else { createActionButton(fs, function () { clearLog(); resolveFs(fs); }, 'button'); } }); } div = document.createElement('div'); div.setAttribute("id", "info"); div.setAttribute("align", "center"); contentEl.appendChild(div); div = document.createElement('h3'); div.appendChild(document.createTextNode('For each test above, file or directory should be successfully found. ' + 'Status box should say Resolving URL was Success. The first URL resolved is the internal URL. ' + 'The second URL resolved is the absolute URL. Blue URLs must match.')); contentEl.appendChild(div); div = document.createElement('h3'); div.appendChild(document.createTextNode('For Test private URL (iOS), the private URL (first blue URL in status box) ' + 'should be successfully resolved. Status box should say Successfully resolved. Both blue URLs below ' + 'that should match.')); contentEl.appendChild(div); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var LocalFileSystem = require('./LocalFileSystem'), FileSystem = require('./FileSystem'), FileEntry = require('./FileEntry'), FileError = require('./FileError'), DirectoryEntry = require('./DirectoryEntry'), File = require('./File'); /* QUIRKS: Does not fail when removing non-empty directories Does not support metadata for directories Does not support requestAllFileSystems Does not support resolveLocalFileSystemURI Methods copyTo and moveTo do not support directories Heavily based on https://github.com/ebidel/idb.filesystem.js */ (function(exports, global) { var indexedDB = global.indexedDB || global.mozIndexedDB; if (!indexedDB) { throw "Firefox OS File plugin: indexedDB not supported"; } var fs_ = null; var idb_ = {}; idb_.db = null; var FILE_STORE_ = 'entries'; var DIR_SEPARATOR = '/'; var DIR_OPEN_BOUND = String.fromCharCode(DIR_SEPARATOR.charCodeAt(0) + 1); var pathsPrefix = { // Read-only directory where the application is installed. applicationDirectory: location.origin + "/", // Where to put app-specific data files. dataDirectory: 'file:///persistent/', // Cached files that should survive app restarts. // Apps should not rely on the OS to delete files in here. cacheDirectory: 'file:///temporary/', }; /*** Exported functionality ***/ exports.requestFileSystem = function(successCallback, errorCallback, args) { var type = args[0]; var size = args[1]; if (type !== LocalFileSystem.TEMPORARY && type !== LocalFileSystem.PERSISTENT) { errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR); return; } var name = type === LocalFileSystem.TEMPORARY ? 'temporary' : 'persistent'; var storageName = (location.protocol + location.host).replace(/:/g, '_'); var root = new DirectoryEntry('', DIR_SEPARATOR); fs_ = new FileSystem(name, root); idb_.open(storageName, function() { successCallback(fs_); }, errorCallback); }; require('./fileSystems').getFs = function(name, callback) { callback(new FileSystem(name, fs_.root)); }; // list a directory's contents (files and folders). exports.readEntries = function(successCallback, errorCallback, args) { var fullPath = args[0]; if (!successCallback) { throw Error('Expected successCallback argument.'); } var path = resolveToFullPath_(fullPath); idb_.getAllEntries(path.fullPath, path.storagePath, function(entries) { successCallback(entries); }, errorCallback); }; exports.getFile = function(successCallback, errorCallback, args) { var fullPath = args[0]; var path = args[1]; var options = args[2] || {}; // Create an absolute path if we were handed a relative one. path = resolveToFullPath_(fullPath, path); idb_.get(path.storagePath, function(fileEntry) { if (options.create === true && options.exclusive === true && fileEntry) { // If create and exclusive are both true, and the path already exists, // getFile must fail. if (errorCallback) { errorCallback(FileError.PATH_EXISTS_ERR); } } else if (options.create === true && !fileEntry) { // If create is true, the path doesn't exist, and no other error occurs, // getFile must create it as a zero-length file and return a corresponding // FileEntry. var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); newFileEntry.file_ = new MyFile({ size: 0, name: newFileEntry.name, lastModifiedDate: new Date(), storagePath: path.storagePath }); idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback); } else if (options.create === true && fileEntry) { if (fileEntry.isFile) { // Overwrite file, delete then create new. idb_['delete'](path.storagePath, function() { var newFileEntry = new FileEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); newFileEntry.file_ = new MyFile({ size: 0, name: newFileEntry.name, lastModifiedDate: new Date(), storagePath: path.storagePath }); idb_.put(newFileEntry, path.storagePath, successCallback, errorCallback); }, errorCallback); } else { if (errorCallback) { errorCallback(FileError.INVALID_MODIFICATION_ERR); } } } else if ((!options.create || options.create === false) && !fileEntry) { // If create is not true and the path doesn't exist, getFile must fail. if (errorCallback) { errorCallback(FileError.NOT_FOUND_ERR); } } else if ((!options.create || options.create === false) && fileEntry && fileEntry.isDirectory) { // If create is not true and the path exists, but is a directory, getFile // must fail. if (errorCallback) { errorCallback(FileError.INVALID_MODIFICATION_ERR); } } else { // Otherwise, if no other error occurs, getFile must return a FileEntry // corresponding to path. successCallback(fileEntryFromIdbEntry(fileEntry)); } }, errorCallback); }; exports.getFileMetadata = function(successCallback, errorCallback, args) { var fullPath = args[0]; exports.getFile(function(fileEntry) { successCallback(new File(fileEntry.file_.name, fileEntry.fullPath, '', fileEntry.file_.lastModifiedDate, fileEntry.file_.size)); }, errorCallback, [fullPath, null]); }; exports.getMetadata = function(successCallback, errorCallback, args) { exports.getFile(function (fileEntry) { successCallback( { modificationTime: fileEntry.file_.lastModifiedDate, size: fileEntry.file_.lastModifiedDate }); }, errorCallback, args); }; exports.setMetadata = function(successCallback, errorCallback, args) { var fullPath = args[0]; var metadataObject = args[1]; exports.getFile(function (fileEntry) { fileEntry.file_.lastModifiedDate = metadataObject.modificationTime; }, errorCallback, [fullPath, null]); }; exports.write = function(successCallback, errorCallback, args) { var fileName = args[0], data = args[1], position = args[2], isBinary = args[3]; if (!data) { errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR); return; } exports.getFile(function(fileEntry) { var blob_ = fileEntry.file_.blob_; if (!blob_) { blob_ = new Blob([data], {type: data.type}); } else { // Calc the head and tail fragments var head = blob_.slice(0, position); var tail = blob_.slice(position + data.byteLength); // Calc the padding var padding = position - head.size; if (padding < 0) { padding = 0; } // Do the "write". In fact, a full overwrite of the Blob. blob_ = new Blob([head, new Uint8Array(padding), data, tail], {type: data.type}); } // Set the blob we're writing on this file entry so we can recall it later. fileEntry.file_.blob_ = blob_; fileEntry.file_.lastModifiedDate = data.lastModifiedDate || null; fileEntry.file_.size = blob_.size; fileEntry.file_.name = blob_.name; fileEntry.file_.type = blob_.type; idb_.put(fileEntry, fileEntry.file_.storagePath, function() { successCallback(data.byteLength); }, errorCallback); }, errorCallback, [fileName, null]); }; exports.readAsText = function(successCallback, errorCallback, args) { var fileName = args[0], enc = args[1], startPos = args[2], endPos = args[3]; readAs('text', fileName, enc, startPos, endPos, successCallback, errorCallback); }; exports.readAsDataURL = function(successCallback, errorCallback, args) { var fileName = args[0], startPos = args[1], endPos = args[2]; readAs('dataURL', fileName, null, startPos, endPos, successCallback, errorCallback); }; exports.readAsBinaryString = function(successCallback, errorCallback, args) { var fileName = args[0], startPos = args[1], endPos = args[2]; readAs('binaryString', fileName, null, startPos, endPos, successCallback, errorCallback); }; exports.readAsArrayBuffer = function(successCallback, errorCallback, args) { var fileName = args[0], startPos = args[1], endPos = args[2]; readAs('arrayBuffer', fileName, null, startPos, endPos, successCallback, errorCallback); }; exports.removeRecursively = exports.remove = function(successCallback, errorCallback, args) { var fullPath = args[0]; // TODO: This doesn't protect against directories that have content in it. // Should throw an error instead if the dirEntry is not empty. idb_['delete'](fullPath, function() { successCallback(); }, errorCallback); }; exports.getDirectory = function(successCallback, errorCallback, args) { var fullPath = args[0]; var path = args[1]; var options = args[2]; // Create an absolute path if we were handed a relative one. path = resolveToFullPath_(fullPath, path); idb_.get(path.storagePath, function(folderEntry) { if (!options) { options = {}; } if (options.create === true && options.exclusive === true && folderEntry) { // If create and exclusive are both true, and the path already exists, // getDirectory must fail. if (errorCallback) { errorCallback(FileError.INVALID_MODIFICATION_ERR); } } else if (options.create === true && !folderEntry) { // If create is true, the path doesn't exist, and no other error occurs, // getDirectory must create it as a zero-length file and return a corresponding // MyDirectoryEntry. var dirEntry = new DirectoryEntry(path.fileName, path.fullPath, new FileSystem(path.fsName, fs_.root)); idb_.put(dirEntry, path.storagePath, successCallback, errorCallback); } else if (options.create === true && folderEntry) { if (folderEntry.isDirectory) { // IDB won't save methods, so we need re-create the MyDirectoryEntry. successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.fileSystem)); } else { if (errorCallback) { errorCallback(FileError.INVALID_MODIFICATION_ERR); } } } else if ((!options.create || options.create === false) && !folderEntry) { // Handle root special. It should always exist. if (path.fullPath === DIR_SEPARATOR) { successCallback(fs_.root); return; } // If create is not true and the path doesn't exist, getDirectory must fail. if (errorCallback) { errorCallback(FileError.NOT_FOUND_ERR); } } else if ((!options.create || options.create === false) && folderEntry && folderEntry.isFile) { // If create is not true and the path exists, but is a file, getDirectory // must fail. if (errorCallback) { errorCallback(FileError.INVALID_MODIFICATION_ERR); } } else { // Otherwise, if no other error occurs, getDirectory must return a // MyDirectoryEntry corresponding to path. // IDB won't' save methods, so we need re-create MyDirectoryEntry. successCallback(new DirectoryEntry(folderEntry.name, folderEntry.fullPath, folderEntry.fileSystem)); } }, errorCallback); }; exports.getParent = function(successCallback, errorCallback, args) { var fullPath = args[0]; if (fullPath === DIR_SEPARATOR) { successCallback(fs_.root); return; } var pathArr = fullPath.split(DIR_SEPARATOR); pathArr.pop(); var namesa = pathArr.pop(); var path = pathArr.join(DIR_SEPARATOR); exports.getDirectory(successCallback, errorCallback, [path, namesa, {create: false}]); }; exports.copyTo = function(successCallback, errorCallback, args) { var srcPath = args[0]; var parentFullPath = args[1]; var name = args[2]; // Read src file exports.getFile(function(srcFileEntry) { // Create dest file exports.getFile(function(dstFileEntry) { exports.write(function() { successCallback(dstFileEntry); }, errorCallback, [dstFileEntry.file_.storagePath, srcFileEntry.file_.blob_, 0]); }, errorCallback, [parentFullPath, name, {create: true}]); }, errorCallback, [srcPath, null]); }; exports.moveTo = function(successCallback, errorCallback, args) { var srcPath = args[0]; var parentFullPath = args[1]; var name = args[2]; exports.copyTo(function (fileEntry) { exports.remove(function () { successCallback(fileEntry); }, errorCallback, [srcPath]); }, errorCallback, args); }; exports.resolveLocalFileSystemURI = function(successCallback, errorCallback, args) { var path = args[0]; // Ignore parameters if (path.indexOf('?') !== -1) { path = String(path).split("?")[0]; } // support for encodeURI if (/\%5/g.test(path)) { path = decodeURI(path); } if (path.indexOf(pathsPrefix.dataDirectory) === 0) { path = path.substring(pathsPrefix.dataDirectory.length - 1); exports.requestFileSystem(function(fs) { fs.root.getFile(path, {create: false}, successCallback, function() { fs.root.getDirectory(path, {create: false}, successCallback, errorCallback); }); }, errorCallback, [LocalFileSystem.PERSISTENT]); } else if (path.indexOf(pathsPrefix.cacheDirectory) === 0) { path = path.substring(pathsPrefix.cacheDirectory.length - 1); exports.requestFileSystem(function(fs) { fs.root.getFile(path, {create: false}, successCallback, function() { fs.root.getDirectory(path, {create: false}, successCallback, errorCallback); }); }, errorCallback, [LocalFileSystem.TEMPORARY]); } else if (path.indexOf(pathsPrefix.applicationDirectory) === 0) { path = path.substring(pathsPrefix.applicationDirectory.length); var xhr = new XMLHttpRequest(); xhr.open("GET", path, true); xhr.onreadystatechange = function () { if (xhr.status === 200 && xhr.readyState === 4) { exports.requestFileSystem(function(fs) { fs.name = location.hostname; fs.root.getFile(path, {create: true}, writeFile, errorCallback); }, errorCallback, [LocalFileSystem.PERSISTENT]); } }; xhr.onerror = function () { errorCallback && errorCallback(FileError.NOT_READABLE_ERR); }; xhr.send(); } else { errorCallback && errorCallback(FileError.NOT_FOUND_ERR); } function writeFile(entry) { entry.createWriter(function (fileWriter) { fileWriter.onwriteend = function (evt) { if (!evt.target.error) { entry.filesystemName = location.hostname; successCallback(entry); } }; fileWriter.onerror = function () { errorCallback && errorCallback(FileError.NOT_READABLE_ERR); }; fileWriter.write(new Blob([xhr.response])); }, errorCallback); } }; exports.requestAllPaths = function(successCallback) { successCallback(pathsPrefix); }; /*** Helpers ***/ /** * Interface to wrap the native File interface. * * This interface is necessary for creating zero-length (empty) files, * something the Filesystem API allows you to do. Unfortunately, File's * constructor cannot be called directly, making it impossible to instantiate * an empty File in JS. * * @param {Object} opts Initial values. * @constructor */ function MyFile(opts) { var blob_ = new Blob(); this.size = opts.size || 0; this.name = opts.name || ''; this.type = opts.type || ''; this.lastModifiedDate = opts.lastModifiedDate || null; this.storagePath = opts.storagePath || ''; // Need some black magic to correct the object's size/name/type based on the // blob that is saved. Object.defineProperty(this, 'blob_', { enumerable: true, get: function() { return blob_; }, set: function(val) { blob_ = val; this.size = blob_.size; this.name = blob_.name; this.type = blob_.type; this.lastModifiedDate = blob_.lastModifiedDate; }.bind(this) }); } MyFile.prototype.constructor = MyFile; // When saving an entry, the fullPath should always lead with a slash and never // end with one (e.g. a directory). Also, resolve '.' and '..' to an absolute // one. This method ensures path is legit! function resolveToFullPath_(cwdFullPath, path) { path = path || ''; var fullPath = path; var prefix = ''; cwdFullPath = cwdFullPath || DIR_SEPARATOR; if (cwdFullPath.indexOf(FILESYSTEM_PREFIX) === 0) { prefix = cwdFullPath.substring(0, cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length)); cwdFullPath = cwdFullPath.substring(cwdFullPath.indexOf(DIR_SEPARATOR, FILESYSTEM_PREFIX.length)); } var relativePath = path[0] !== DIR_SEPARATOR; if (relativePath) { fullPath = cwdFullPath; if (cwdFullPath != DIR_SEPARATOR) { fullPath += DIR_SEPARATOR + path; } else { fullPath += path; } } // Adjust '..'s by removing parent directories when '..' flows in path. var parts = fullPath.split(DIR_SEPARATOR); for (var i = 0; i < parts.length; ++i) { var part = parts[i]; if (part == '..') { parts[i - 1] = ''; parts[i] = ''; } } fullPath = parts.filter(function(el) { return el; }).join(DIR_SEPARATOR); // Add back in leading slash. if (fullPath[0] !== DIR_SEPARATOR) { fullPath = DIR_SEPARATOR + fullPath; } // Replace './' by current dir. ('./one/./two' -> one/two) fullPath = fullPath.replace(/\.\//g, DIR_SEPARATOR); // Replace '//' with '/'. fullPath = fullPath.replace(/\/\//g, DIR_SEPARATOR); // Replace '/.' with '/'. fullPath = fullPath.replace(/\/\./g, DIR_SEPARATOR); // Remove '/' if it appears on the end. if (fullPath[fullPath.length - 1] == DIR_SEPARATOR && fullPath != DIR_SEPARATOR) { fullPath = fullPath.substring(0, fullPath.length - 1); } return { storagePath: prefix + fullPath, fullPath: fullPath, fileName: fullPath.split(DIR_SEPARATOR).pop(), fsName: prefix.split(DIR_SEPARATOR).pop() }; } function fileEntryFromIdbEntry(fileEntry) { // IDB won't save methods, so we need re-create the FileEntry. var clonedFileEntry = new FileEntry(fileEntry.name, fileEntry.fullPath, fileEntry.fileSystem); clonedFileEntry.file_ = fileEntry.file_; return clonedFileEntry; } function readAs(what, fullPath, encoding, startPos, endPos, successCallback, errorCallback) { exports.getFile(function(fileEntry) { var fileReader = new FileReader(), blob = fileEntry.file_.blob_.slice(startPos, endPos); fileReader.onload = function(e) { successCallback(e.target.result); }; fileReader.onerror = errorCallback; switch (what) { case 'text': fileReader.readAsText(blob, encoding); break; case 'dataURL': fileReader.readAsDataURL(blob); break; case 'arrayBuffer': fileReader.readAsArrayBuffer(blob); break; case 'binaryString': fileReader.readAsBinaryString(blob); break; } }, errorCallback, [fullPath, null]); } /*** Core logic to handle IDB operations ***/ idb_.open = function(dbName, successCallback, errorCallback) { var self = this; // TODO: FF 12.0a1 isn't liking a db name with : in it. var request = indexedDB.open(dbName.replace(':', '_')/*, 1 /*version*/); request.onerror = errorCallback || onError; request.onupgradeneeded = function(e) { // First open was called or higher db version was used. // console.log('onupgradeneeded: oldVersion:' + e.oldVersion, // 'newVersion:' + e.newVersion); self.db = e.target.result; self.db.onerror = onError; if (!self.db.objectStoreNames.contains(FILE_STORE_)) { var store = self.db.createObjectStore(FILE_STORE_/*,{keyPath: 'id', autoIncrement: true}*/); } }; request.onsuccess = function(e) { self.db = e.target.result; self.db.onerror = onError; successCallback(e); }; request.onblocked = errorCallback || onError; }; idb_.close = function() { this.db.close(); this.db = null; }; idb_.get = function(fullPath, successCallback, errorCallback) { if (!this.db) { errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR); return; } var tx = this.db.transaction([FILE_STORE_], 'readonly'); //var request = tx.objectStore(FILE_STORE_).get(fullPath); var range = IDBKeyRange.bound(fullPath, fullPath + DIR_OPEN_BOUND, false, true); var request = tx.objectStore(FILE_STORE_).get(range); tx.onabort = errorCallback || onError; tx.oncomplete = function(e) { successCallback(request.result); }; }; idb_.getAllEntries = function(fullPath, storagePath, successCallback, errorCallback) { if (!this.db) { errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR); return; } var results = []; if (storagePath[storagePath.length - 1] === DIR_SEPARATOR) { storagePath = storagePath.substring(0, storagePath.length - 1); } range = IDBKeyRange.bound( storagePath + DIR_SEPARATOR, storagePath + DIR_OPEN_BOUND, false, true); var tx = this.db.transaction([FILE_STORE_], 'readonly'); tx.onabort = errorCallback || onError; tx.oncomplete = function(e) { results = results.filter(function(val) { var valPartsLen = val.fullPath.split(DIR_SEPARATOR).length; var fullPathPartsLen = fullPath.split(DIR_SEPARATOR).length; if (fullPath === DIR_SEPARATOR && valPartsLen < fullPathPartsLen + 1) { // Hack to filter out entries in the root folder. This is inefficient // because reading the entires of fs.root (e.g. '/') returns ALL // results in the database, then filters out the entries not in '/'. return val; } else if (fullPath !== DIR_SEPARATOR && valPartsLen === fullPathPartsLen + 1) { // If this a subfolder and entry is a direct child, include it in // the results. Otherwise, it's not an entry of this folder. return val; } }); successCallback(results); }; var request = tx.objectStore(FILE_STORE_).openCursor(range); request.onsuccess = function(e) { var cursor = e.target.result; if (cursor) { var val = cursor.value; results.push(val.isFile ? fileEntryFromIdbEntry(val) : new DirectoryEntry(val.name, val.fullPath, val.fileSystem)); cursor['continue'](); } }; }; idb_['delete'] = function(fullPath, successCallback, errorCallback) { if (!this.db) { errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR); return; } var tx = this.db.transaction([FILE_STORE_], 'readwrite'); tx.oncomplete = successCallback; tx.onabort = errorCallback || onError; //var request = tx.objectStore(FILE_STORE_).delete(fullPath); var range = IDBKeyRange.bound( fullPath, fullPath + DIR_OPEN_BOUND, false, true); tx.objectStore(FILE_STORE_)['delete'](range); }; idb_.put = function(entry, storagePath, successCallback, errorCallback) { if (!this.db) { errorCallback && errorCallback(FileError.INVALID_MODIFICATION_ERR); return; } var tx = this.db.transaction([FILE_STORE_], 'readwrite'); tx.onabort = errorCallback || onError; tx.oncomplete = function(e) { // TODO: Error is thrown if we pass the request event back instead. successCallback(entry); }; tx.objectStore(FILE_STORE_).put(entry, storagePath); }; // Global error handler. Errors bubble from request, to transaction, to db. function onError(e) { switch (e.target.errorCode) { case 12: console.log('Error - Attempt to open db with a lower version than the ' + 'current one.'); break; default: console.log('errorCode: ' + e.target.errorCode); } console.log(e, e.code, e.message); } // Clean up. // TODO: Is there a place for this? // global.addEventListener('beforeunload', function(e) { // idb_.db && idb_.db.close(); // }, false); })(module.exports, window); require("cordova/exec/proxy").add("File", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ module.exports = { setSandbox : function (success, fail, args, env) { require("lib/webview").setSandbox(JSON.parse(decodeURIComponent(args[0]))); new PluginResult(args, env).ok(); }, getHomePath: function (success, fail, args, env) { var homeDir = window.qnx.webplatform.getApplication().getEnv("HOME"); new PluginResult(args, env).ok(homeDir); }, requestAllPaths: function (success, fail, args, env) { var homeDir = 'file://' + window.qnx.webplatform.getApplication().getEnv("HOME").replace('/data', ''), paths = { applicationDirectory: homeDir + '/app/native/', applicationStorageDirectory: homeDir + '/', dataDirectory: homeDir + '/data/webviews/webfs/persistent/local__0/', cacheDirectory: homeDir + '/data/webviews/webfs/temporary/local__0/', externalRootDirectory: 'file:///accounts/1000/removable/sdcard/', sharedDirectory: homeDir + '/shared/' }; success(paths); } };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var cordova = require('cordova'); var Entry = require('./Entry'), File = require('./File'), FileEntry = require('./FileEntry'), FileError = require('./FileError'), DirectoryEntry = require('./DirectoryEntry'), Flags = require('./Flags'), FileSystem = require('./FileSystem'), LocalFileSystem = require('./LocalFileSystem'); // Some private helper functions, hidden by the module function cordovaPathToNative(path) { // turn / into \\ var cleanPath = path.replace(/\//g, '\\'); // turn \\ into \ cleanPath = cleanPath.replace(/\\\\/g, '\\'); // strip end \\ characters cleanPath = cleanPath.replace(/\\+$/g, ''); return cleanPath; }; function nativePathToCordova(path) { var cleanPath = path.replace(/\\/g, '/'); return cleanPath; }; function getFilesystemFromPath(path) { var storageFolderPermanent = Windows.Storage.ApplicationData.current.localFolder.path, storageFolderTemporary = Windows.Storage.ApplicationData.current.temporaryFolder.path, fs = null; if (path.indexOf(storageFolderPermanent) === 0) { fs = new FileSystem('persistent', { name: 'persistent', fullPath: storageFolderPermanent }); } else if (path.indexOf(storageFolderTemporary) === 0) { fs = new FileSystem('temporary', { name: 'temporary', fullPath: storageFolderTemporary }); } return fs; }; var getFolderFromPathAsync = Windows.Storage.StorageFolder.getFolderFromPathAsync; var getFileFromPathAsync = Windows.Storage.StorageFile.getFileFromPathAsync; module.exports = { getFileMetadata: function (success, fail, args) { module.exports.getMetadata(success, fail, args); }, getMetadata: function (success, fail, args) { var fullPath = cordovaPathToNative(args[0]); var getMetadataForFile = function (storageFile) { storageFile.getBasicPropertiesAsync().then( function (basicProperties) { success(new File(storageFile.name, storageFile.path, storageFile.fileType, basicProperties.dateModified, basicProperties.size)); }, function () { fail(FileError.NOT_READABLE_ERR); } ); }; var getMetadataForFolder = function (storageFolder) { storageFolder.getBasicPropertiesAsync().then( function (basicProperties) { var metadata = { size: basicProperties.size, lastModifiedDate: basicProperties.dateModified }; success(metadata); }, function () { fail(FileError.NOT_READABLE_ERR); } ); }; getFileFromPathAsync(fullPath).then(getMetadataForFile, function () { getFolderFromPathAsync(fullPath).then(getMetadataForFolder, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, getParent: function (win, fail, args) { // ["fullPath"] var fullPath = cordovaPathToNative(args[0]); var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder; var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder; if (fullPath == storageFolderPer.path) { win(new DirectoryEntry(storageFolderPer.name, storageFolderPer.path, getFilesystemFromPath(storageFolderPer.path))); return; } else if (fullPath == storageFolderTem.path) { win(new DirectoryEntry(storageFolderTem.name, storageFolderTem.path, getFilesystemFromPath(storageFolderTem.path))); return; } var splitArr = fullPath.split(new RegExp(/\/|\\/g)); var popItem = splitArr.pop(); var resultPath = fullPath.substr(0, fullPath.length - popItem.length - 1); var result = new DirectoryEntry(popItem, resultPath, getFilesystemFromPath(resultPath)); getFolderFromPathAsync(result.fullPath).done( function () { win(result); }, function () { fail(FileError.INVALID_STATE_ERR); } ); }, readAsText: function (win, fail, args) { var fileName = cordovaPathToNative(args[0]), enc = args[1], startPos = args[2], endPos = args[3]; var encoding = Windows.Storage.Streams.UnicodeEncoding.utf8; if (enc == 'Utf16LE' || enc == 'utf16LE') { encoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE; } else if (enc == 'Utf16BE' || enc == 'utf16BE') { encoding = Windows.Storage.Streams.UnicodeEncoding.utf16BE; } getFileFromPathAsync(fileName).then(function(file) { return file.openReadAsync(); }).then(function (stream) { startPos = (startPos < 0) ? Math.max(stream.size + startPos, 0) : Math.min(stream.size, startPos); endPos = (endPos < 0) ? Math.max(endPos + stream.size, 0) : Math.min(stream.size, endPos); stream.seek(startPos); var readSize = endPos - startPos, buffer = new Windows.Storage.Streams.Buffer(readSize); return stream.readAsync(buffer, readSize, Windows.Storage.Streams.InputStreamOptions.none); }).done(function(buffer) { win(Windows.Security.Cryptography.CryptographicBuffer.convertBinaryToString(encoding, buffer)); },function() { fail(FileError.NOT_FOUND_ERR); }); }, readAsBinaryString:function(win,fail,args) { var fileName = cordovaPathToNative(args[0]), startPos = args[1], endPos = args[2]; getFileFromPathAsync(fileName).then( function (storageFile) { Windows.Storage.FileIO.readBufferAsync(storageFile).done( function (buffer) { var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer); // var fileContent = dataReader.readString(buffer.length); var byteArray = new Uint8Array(buffer.length), byteString = ""; dataReader.readBytes(byteArray); dataReader.close(); for (var i = 0; i < byteArray.length; i++) { var charByte = byteArray[i]; // var charRepresentation = charByte <= 127 ? String.fromCharCode(charByte) : charByte.toString(16); var charRepresentation = String.fromCharCode(charByte); byteString += charRepresentation; } win(byteString.slice(startPos, endPos)); } ); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, readAsArrayBuffer:function(win,fail,args) { var fileName =cordovaPathToNative(args[0]); getFileFromPathAsync(fileName).then( function (storageFile) { var blob = MSApp.createFileFromStorageFile(storageFile); var url = URL.createObjectURL(blob, { oneTimeOnly: true }); var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = 'arraybuffer'; xhr.onload = function () { var resultArrayBuffer = xhr.response; // get start and end position of bytes in buffer to be returned var startPos = args[1] || 0, endPos = args[2] || resultArrayBuffer.length; // if any of them is specified, we'll slice output array if (startPos !== 0 || endPos !== resultArrayBuffer.length) { // slice method supported only on Windows 8.1, so we need to check if it's available // see http://msdn.microsoft.com/en-us/library/ie/dn641192(v=vs.94).aspx if (resultArrayBuffer.slice) { resultArrayBuffer = resultArrayBuffer.slice(startPos, endPos); } else { // if slice isn't available, we'll use workaround method var tempArray = new Uint8Array(resultArrayBuffer), resBuffer = new ArrayBuffer(endPos - startPos), resArray = new Uint8Array(resBuffer); for (var i = 0; i < resArray.length; i++) { resArray[i] = tempArray[i + startPos]; } resultArrayBuffer = resBuffer; } } win(resultArrayBuffer); }; xhr.send(); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, readAsDataURL: function (win, fail, args) { var fileName = cordovaPathToNative(args[0]); getFileFromPathAsync(fileName).then( function (storageFile) { Windows.Storage.FileIO.readBufferAsync(storageFile).done( function (buffer) { var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer); //the method encodeToBase64String will add "77u/" as a prefix, so we should remove it if(String(strBase64).substr(0,4) == "77u/") { strBase64 = strBase64.substr(4); } var mediaType = storageFile.contentType; var result = "data:" + mediaType + ";base64," + strBase64; win(result); } ); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, getDirectory: function (win, fail, args) { var fullPath = cordovaPathToNative(args[0]); var path = cordovaPathToNative(args[1]); var options = args[2]; var flag = ""; if (options) { flag = new Flags(options.create, options.exclusive); } else { flag = new Flags(false, false); } getFolderFromPathAsync(fullPath).then( function (storageFolder) { if (flag.create === true && flag.exclusive === true) { storageFolder.createFolderAsync(path, Windows.Storage.CreationCollisionOption.failIfExists).done( function (storageFolder) { win(new DirectoryEntry(storageFolder.name, nativePathToCordova(storageFolder.path), getFilesystemFromPath(storageFolder.path))); }, function (err) { fail(FileError.PATH_EXISTS_ERR); } ); } else if (flag.create === true && flag.exclusive === false) { storageFolder.createFolderAsync(path, Windows.Storage.CreationCollisionOption.openIfExists).done( function (storageFolder) { win(new DirectoryEntry(storageFolder.name, storageFolder.path + "/", getFilesystemFromPath(storageFolder.path + "/"))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); } ); } else if (flag.create === false) { if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) { fail(FileError.ENCODING_ERR); return; } storageFolder.getFolderAsync(path).done( function (storageFolder) { win(new DirectoryEntry(storageFolder.name, storageFolder.path, getFilesystemFromPath(storageFolder.path))); }, function () { // check if path actually points to a file storageFolder.getFileAsync(path).done( function () { fail(FileError.TYPE_MISMATCH_ERR); }, function() { fail(FileError.NOT_FOUND_ERR); }); } ); } }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, remove: function (win, fail, args) { var fullPath = cordovaPathToNative(args[0]); getFileFromPathAsync(fullPath).then( function (sFile) { getFileFromPathAsync(fullPath).done(function (storageFile) { storageFile.deleteAsync().done(win, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }); }, function () { getFolderFromPathAsync(fullPath).then( function (sFolder) { var removeEntry = function () { var storageFolderTop = null; getFolderFromPathAsync(fullPath).then( function (storageFolder) { // FileSystem root can't be removed! var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder; var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder; if (fullPath == storageFolderPer.path || fullPath == storageFolderTem.path) { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); return; } storageFolderTop = storageFolder; return storageFolder.getFilesAsync(); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); } // check sub-files. ).then(function (fileList) { if (fileList) { if (fileList.length === 0) { return storageFolderTop.getFoldersAsync(); } else { fail(FileError.INVALID_MODIFICATION_ERR); } } // check sub-folders. }).then(function (folderList) { if (folderList) { if (folderList.length === 0) { storageFolderTop.deleteAsync().done(win, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); } else { fail(FileError.INVALID_MODIFICATION_ERR); } } }); }; removeEntry(); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, removeRecursively: function (successCallback, fail, args) { var fullPath = cordovaPathToNative(args[0]); getFolderFromPathAsync(fullPath).done(function (storageFolder) { var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder; var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder; if (storageFolder.path == storageFolderPer.path || storageFolder.path == storageFolderTem.path) { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); return; } storageFolder.deleteAsync().done(function (res) { successCallback(res); }, function (err) { fail(err); }); }, function () { fail(FileError.FILE_NOT_FOUND_ERR); }); }, getFile: function (win, fail, args) { //not sure why, but it won't work with normal slashes... var fullPath = cordovaPathToNative(args[0]); var path = cordovaPathToNative(args[1]); var options = args[2]; var completePath = fullPath + '\\' + path; //handles trailing slash and leading slash, or just one or the other completePath = completePath.replace(/\\\\\\/g, '/').replace(/\\\\/g, '\\'); var fileName = completePath.substring(completePath.lastIndexOf('\\')); //final adjustment fullPath = completePath.substring(0, completePath.lastIndexOf('\\')); path = fileName.replace(/\\/g, ''); var flag = ""; if (options !== null) { flag = new Flags(options.create, options.exclusive); } else { flag = new Flags(false, false); } getFolderFromPathAsync(fullPath).then( function (storageFolder) { if (flag.create === true && flag.exclusive === true) { storageFolder.createFileAsync(path, Windows.Storage.CreationCollisionOption.failIfExists).done( function (storageFile) { win(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { fail(FileError.PATH_EXISTS_ERR); } ); } else if (flag.create === true && flag.exclusive === false) { storageFolder.createFileAsync(path, Windows.Storage.CreationCollisionOption.openIfExists).done( function (storageFile) { win(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); } ); } else if (flag.create === false) { if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) { fail(FileError.ENCODING_ERR); return; } storageFolder.getFileAsync(path).done( function (storageFile) { win(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { // check if path actually points to a folder storageFolder.getFolderAsync(path).done( function () { fail(FileError.TYPE_MISMATCH_ERR); }, function () { fail(FileError.NOT_FOUND_ERR); }); } ); } }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, readEntries: function (win, fail, args) { // ["fullPath"] var path = cordovaPathToNative(args[0]); var result = []; getFolderFromPathAsync(path).then(function (storageFolder) { var promiseArr = []; var index = 0; promiseArr[index++] = storageFolder.getFilesAsync().then(function (fileList) { if (fileList !== null) { for (var i = 0; i < fileList.length; i++) { result.push(new FileEntry(fileList[i].name, fileList[i].path, getFilesystemFromPath (fileList[i].path))); } } }); promiseArr[index++] = storageFolder.getFoldersAsync().then(function (folderList) { if (folderList !== null) { for (var j = 0; j < folderList.length; j++) { result.push(new DirectoryEntry(folderList[j].name, folderList[j].path, getFilesystemFromPath(folderList[j].path))); } } }); WinJS.Promise.join(promiseArr).then(function () { win(result); }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }, write: function (win, fail, args) { var fileName = cordovaPathToNative(args[0]), data = args[1], position = args[2], isBinary = args[3]; if (data instanceof ArrayBuffer) { data = Array.apply(null, new Uint8Array(data)); } var writePromise = isBinary ? Windows.Storage.FileIO.writeBytesAsync : Windows.Storage.FileIO.writeTextAsync; fileName = fileName.split("/").join("\\"); // split path to folder and file name var path = fileName.substring(0, fileName.lastIndexOf('\\')), file = fileName.split('\\').pop(); getFolderFromPathAsync(path).done( function(storageFolder) { storageFolder.createFileAsync(file, Windows.Storage.CreationCollisionOption.openIfExists).done( function(storageFile) { writePromise(storageFile, data). done(function () { win(data.length); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function() { fail(FileError.INVALID_MODIFICATION_ERR); } ); }, function() { fail(FileError.NOT_FOUND_ERR); }); }, truncate: function (win, fail, args) { // ["fileName","size"] var fileName = cordovaPathToNative(args[0]); var size = args[1]; getFileFromPathAsync(fileName).done(function(storageFile){ //the current length of the file. var leng = 0; storageFile.getBasicPropertiesAsync().then(function (basicProperties) { leng = basicProperties.size; if (Number(size) >= leng) { win(this.length); return; } if (Number(size) >= 0) { Windows.Storage.FileIO.readTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.utf8).then(function (fileContent) { fileContent = fileContent.substr(0, size); var fullPath = storageFile.path; var name = storageFile.name; var entry = new Entry(true, false, name, fullPath, getFilesystemFromPath(fullPath)); var parentPath = ""; var successCallBack = function (entry) { parentPath = entry.fullPath; storageFile.deleteAsync().then(function () { return getFolderFromPathAsync(parentPath); }).then(function (storageFolder) { storageFolder.createFileAsync(name).then(function (newStorageFile) { Windows.Storage.FileIO.writeTextAsync(newStorageFile, fileContent).done(function () { win(String(fileContent).length); }, function () { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); }); }, function() { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); }); }); }; entry.getParent(successCallBack, null); }, function () { fail(FileError.NOT_FOUND_ERR); }); } }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }, copyTo: function (success, fail, args) { // ["fullPath","parent", "newName"] var srcPath = cordovaPathToNative(args[0]); var parentFullPath = cordovaPathToNative(args[1]); var name = args[2]; //name can't be invalid if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) { fail(FileError.ENCODING_ERR); return; } // copy var copyFiles = ""; getFileFromPathAsync(srcPath).then( function (sFile) { copyFiles = function (srcPath, parentPath) { var storageFileTop = null; getFileFromPathAsync(srcPath).then(function (storageFile) { storageFileTop = storageFile; return getFolderFromPathAsync(parentPath); }, function () { fail(FileError.NOT_FOUND_ERR); }).then(function (storageFolder) { storageFileTop.copyAsync(storageFolder, name, Windows.Storage.NameCollisionOption.failIfExists).then(function (storageFile) { success(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }; var copyFinish = function (srcPath, parentPath) { copyFiles(srcPath, parentPath); }; copyFinish(srcPath, parentFullPath); }, function () { getFolderFromPathAsync(srcPath).then( function (sFolder) { copyFiles = function (srcPath, parentPath) { var coreCopy = function (storageFolderTop, complete) { storageFolderTop.getFoldersAsync().then(function (folderList) { var folderPromiseArr = []; if (folderList.length === 0) { complete(); } else { getFolderFromPathAsync(parentPath).then(function (storageFolderTarget) { var tempPromiseArr = []; var index = 0; for (var j = 0; j < folderList.length; j++) { tempPromiseArr[index++] = storageFolderTarget.createFolderAsync(folderList[j].name).then(function (targetFolder) { folderPromiseArr.push(copyFiles(folderList[j].path, targetFolder.path)); }); } WinJS.Promise.join(tempPromiseArr).then(function () { WinJS.Promise.join(folderPromiseArr).then(complete); }); }); } }); }; return new WinJS.Promise(function (complete) { var storageFolderTop = null; var filePromiseArr = []; var fileListTop = null; getFolderFromPathAsync(srcPath).then(function (storageFolder) { storageFolderTop = storageFolder; return storageFolder.getFilesAsync(); }).then(function (fileList) { fileListTop = fileList; if (fileList) { return getFolderFromPathAsync(parentPath); } }).then(function (targetStorageFolder) { for (var i = 0; i < fileListTop.length; i++) { filePromiseArr.push(fileListTop[i].copyAsync(targetStorageFolder)); } WinJS.Promise.join(filePromiseArr).done(function () { coreCopy(storageFolderTop, complete); }, function() { fail(FileError.INVALID_MODIFICATION_ERR); }); }); }); }; var copyFinish = function (srcPath, parentPath) { getFolderFromPathAsync(parentPath).then(function (storageFolder) { storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists).then(function (newStorageFolder) { //can't copy onto itself if (srcPath == newStorageFolder.path) { fail(FileError.INVALID_MODIFICATION_ERR); return; } //can't copy into itself if (srcPath == parentPath) { fail(FileError.INVALID_MODIFICATION_ERR); return; } copyFiles(srcPath, newStorageFolder.path).then(function () { getFolderFromPathAsync(newStorageFolder.path).done( function (storageFolder) { success(new DirectoryEntry(storageFolder.name, nativePathToCordova(storageFolder.path), getFilesystemFromPath(storageFolder.path))); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }; copyFinish(srcPath, parentFullPath); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, moveTo: function (success, fail, args) { var srcPath = cordovaPathToNative(args[0]); var parentFullPath = cordovaPathToNative(args[1]); var name = args[2]; //name can't be invalid if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) { fail(FileError.ENCODING_ERR); return; } var moveFiles = ""; getFileFromPathAsync(srcPath).then( function (sFile) { moveFiles = function (srcPath, parentPath) { var storageFileTop = null; getFileFromPathAsync(srcPath).then(function (storageFile) { storageFileTop = storageFile; return getFolderFromPathAsync(parentPath); }, function () { fail(FileError.NOT_FOUND_ERR); }).then(function (storageFolder) { storageFileTop.moveAsync(storageFolder, name, Windows.Storage.NameCollisionOption.replaceExisting).then(function () { success(new FileEntry(name, nativePathToCordova(storageFileTop.path), getFilesystemFromPath(storageFolder.path))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }; var moveFinish = function (srcPath, parentPath) { //can't copy onto itself if (srcPath == parentPath + "\\" + name) { fail(FileError.INVALID_MODIFICATION_ERR); return; } moveFiles(srcPath, parentFullPath); }; moveFinish(srcPath, parentFullPath); }, function () { getFolderFromPathAsync(srcPath).then( function (sFolder) { moveFiles = function (srcPath, parentPath) { var coreMove = function (storageFolderTop, complete) { storageFolderTop.getFoldersAsync().then(function (folderList) { var folderPromiseArr = []; if (folderList.length === 0) { // If failed, we must cancel the deletion of folders & files.So here wo can't delete the folder. complete(); } else { getFolderFromPathAsync(parentPath).then(function (storageFolderTarget) { var tempPromiseArr = []; var index = 0; for (var j = 0; j < folderList.length; j++) { tempPromiseArr[index++] = storageFolderTarget.createFolderAsync(folderList[j].name).then(function (targetFolder) { folderPromiseArr.push(moveFiles(folderList[j].path, targetFolder.path)); }); } WinJS.Promise.join(tempPromiseArr).then(function () { WinJS.Promise.join(folderPromiseArr).then(complete); }); }); } }); }; return new WinJS.Promise(function (complete) { var storageFolderTop = null; getFolderFromPathAsync(srcPath).then(function (storageFolder) { storageFolderTop = storageFolder; return storageFolder.getFilesAsync(); }).then(function (fileList) { var filePromiseArr = []; getFolderFromPathAsync(parentPath).then(function (dstStorageFolder) { if (fileList) { for (var i = 0; i < fileList.length; i++) { filePromiseArr.push(fileList[i].moveAsync(dstStorageFolder)); } } WinJS.Promise.join(filePromiseArr).then(function () { coreMove(storageFolderTop, complete); }, function () { }); }); }); }); }; var moveFinish = function (srcPath, parentPath) { var originFolderTop = null; getFolderFromPathAsync(srcPath).then(function (originFolder) { originFolderTop = originFolder; return getFolderFromPathAsync(parentPath); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }).then(function (storageFolder) { return storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }).then(function (newStorageFolder) { //can't move onto directory that is not empty newStorageFolder.getFilesAsync().then(function (fileList) { newStorageFolder.getFoldersAsync().then(function (folderList) { if (fileList.length !== 0 || folderList.length !== 0) { fail(FileError.INVALID_MODIFICATION_ERR); return; } //can't copy onto itself if (srcPath == newStorageFolder.path) { fail(FileError.INVALID_MODIFICATION_ERR); return; } //can't copy into itself if (srcPath == parentPath) { fail(FileError.INVALID_MODIFICATION_ERR); return; } moveFiles(srcPath, newStorageFolder.path).then(function () { var successCallback = function () { success(new DirectoryEntry(name, nativePathToCordova(newStorageFolder.path), getFilesystemFromPath(newStorageFolder.path))); }; originFolderTop.deleteAsync().done(successCallback, fail); }, function () { console.log("error!"); }); }); }); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }; moveFinish(srcPath, parentFullPath); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, tempFileSystem:null, persistentFileSystem:null, requestFileSystem: function (win, fail, args) { var type = args[0]; var size = args[1]; var filePath = ""; var result = null; var fsTypeName = ""; switch (type) { case LocalFileSystem.TEMPORARY: filePath = Windows.Storage.ApplicationData.current.temporaryFolder.path; fsTypeName = "temporary"; break; case LocalFileSystem.PERSISTENT: filePath = Windows.Storage.ApplicationData.current.localFolder.path; fsTypeName = "persistent"; break; } var MAX_SIZE = 10000000000; if (size > MAX_SIZE) { fail(FileError.QUOTA_EXCEEDED_ERR); return; } var fileSystem = new FileSystem(fsTypeName, new DirectoryEntry(fsTypeName, nativePathToCordova(filePath))); result = fileSystem; win(result); }, resolveLocalFileSystemURI: function (success, fail, args) { var uri = args[0]; var path = cordovaPathToNative(uri); // support for file name with parameters if (/\?/g.test(path)) { path = String(path).split("?")[0]; } // support for encodeURI if (/\%5/g.test(path)) { path = decodeURI(path); } var msappdataLocalPrefix = 'ms-appdata:///local/', msappdataTempPrefix = 'ms-appdata:///temp/', msappdataLocalPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\', msappdataTempPath = Windows.Storage.ApplicationData.current.temporaryFolder.path + '\\'; // support for special path start with file:/// or ms-appdata:// if (uri.indexOf("file:///") === 0 ) { path = msappdataLocalPath + uri.substr(8).replace('/', '\\'); } else if (uri.indexOf(msappdataLocalPrefix) === 0) { path = msappdataLocalPath + uri.replace(msappdataLocalPrefix, '').replace('/', '\\'); } else if (uri.indexOf(msappdataTempPrefix) === 0) { path = msappdataTempPath + uri.replace(msappdataTempPrefix, '').replace('/', '\\'); } else { // method should not let read files outside of the [APP HASH]/Local or [APP HASH]/temp folders if (path.indexOf(msappdataTempPath) != 0 && path.indexOf(msappdataLocalPath) != 0) { fail(FileError.NOT_FOUND_ERR); return; } } getFileFromPathAsync(path).then( function (storageFile) { success(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { getFolderFromPathAsync(path).then( function (storageFolder) { var cordovaPath = nativePathToCordova(storageFolder.path); success(new DirectoryEntry(storageFolder.name, cordovaPath, getFilesystemFromPath(storageFolder.path), cordovaPath)); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); } }; require("cordova/exec/proxy").add("File",module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var cordova = require('cordova'); var Entry = require('./Entry'), File = require('./File'), FileEntry = require('./FileEntry'), FileError = require('./FileError'), DirectoryEntry = require('./DirectoryEntry'), Flags = require('./Flags'), FileSystem = require('./FileSystem'), LocalFileSystem = require('./LocalFileSystem'); // Some private helper functions, hidden by the module function cordovaPathToNative(path) { // turn / into \\ var cleanPath = path.replace(/\//g, '\\'); // turn \\ into \ cleanPath = cleanPath.replace(/\\\\/g, '\\'); // strip end \\ characters cleanPath = cleanPath.replace(/\\+$/g, ''); return cleanPath; }; function nativePathToCordova(path) { var cleanPath = path.replace(/\\/g, '/'); return cleanPath; }; function getFilesystemFromPath(path) { var storageFolderPermanent = Windows.Storage.ApplicationData.current.localFolder.path, storageFolderTemporary = Windows.Storage.ApplicationData.current.temporaryFolder.path, fs = null; if (path.indexOf(storageFolderPermanent) === 0) { fs = new FileSystem('persistent', { name: 'persistent', fullPath: storageFolderPermanent }); } else if (path.indexOf(storageFolderTemporary) === 0) { fs = new FileSystem('temporary', { name: 'temporary', fullPath: storageFolderTemporary }); } return fs; }; var getFolderFromPathAsync = Windows.Storage.StorageFolder.getFolderFromPathAsync; var getFileFromPathAsync = Windows.Storage.StorageFile.getFileFromPathAsync; module.exports = { getFileMetadata: function (success, fail, args) { module.exports.getMetadata(success, fail, args); }, getMetadata: function (success, fail, args) { var fullPath = cordovaPathToNative(args[0]); var getMetadataForFile = function (storageFile) { storageFile.getBasicPropertiesAsync().then( function (basicProperties) { success(new File(storageFile.name, storageFile.path, storageFile.fileType, basicProperties.dateModified, basicProperties.size)); }, function () { fail(FileError.NOT_READABLE_ERR); } ); }; var getMetadataForFolder = function (storageFolder) { storageFolder.getBasicPropertiesAsync().then( function (basicProperties) { var metadata = { size: basicProperties.size, lastModifiedDate: basicProperties.dateModified }; success(metadata); }, function () { fail(FileError.NOT_READABLE_ERR); } ); }; getFileFromPathAsync(fullPath).then(getMetadataForFile, function () { getFolderFromPathAsync(fullPath).then(getMetadataForFolder, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, getParent: function (win, fail, args) { // ["fullPath"] var fullPath = cordovaPathToNative(args[0]); var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder; var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder; if (fullPath == storageFolderPer.path) { win(new DirectoryEntry(storageFolderPer.name, storageFolderPer.path, getFilesystemFromPath(storageFolderPer.path))); return; } else if (fullPath == storageFolderTem.path) { win(new DirectoryEntry(storageFolderTem.name, storageFolderTem.path, getFilesystemFromPath(storageFolderTem.path))); return; } var splitArr = fullPath.split(new RegExp(/\/|\\/g)); var popItem = splitArr.pop(); var resultPath = fullPath.substr(0, fullPath.length - popItem.length - 1); var result = new DirectoryEntry(popItem, resultPath, getFilesystemFromPath(resultPath)); getFolderFromPathAsync(result.fullPath).done( function () { win(result); }, function () { fail(FileError.INVALID_STATE_ERR); } ); }, readAsText: function (win, fail, args) { var fileName = cordovaPathToNative(args[0]), enc = args[1], startPos = args[2], endPos = args[3]; var encoding = Windows.Storage.Streams.UnicodeEncoding.utf8; if (enc == 'Utf16LE' || enc == 'utf16LE') { encoding = Windows.Storage.Streams.UnicodeEncoding.utf16LE; } else if (enc == 'Utf16BE' || enc == 'utf16BE') { encoding = Windows.Storage.Streams.UnicodeEncoding.utf16BE; } getFileFromPathAsync(fileName).then(function(file) { return file.openReadAsync(); }).then(function (stream) { startPos = (startPos < 0) ? Math.max(stream.size + startPos, 0) : Math.min(stream.size, startPos); endPos = (endPos < 0) ? Math.max(endPos + stream.size, 0) : Math.min(stream.size, endPos); stream.seek(startPos); var readSize = endPos - startPos, buffer = new Windows.Storage.Streams.Buffer(readSize); return stream.readAsync(buffer, readSize, Windows.Storage.Streams.InputStreamOptions.none); }).done(function(buffer) { win(Windows.Security.Cryptography.CryptographicBuffer.convertBinaryToString(encoding, buffer)); },function() { fail(FileError.NOT_FOUND_ERR); }); }, readAsBinaryString:function(win,fail,args) { var fileName = cordovaPathToNative(args[0]), startPos = args[1], endPos = args[2]; getFileFromPathAsync(fileName).then( function (storageFile) { Windows.Storage.FileIO.readBufferAsync(storageFile).done( function (buffer) { var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer); // var fileContent = dataReader.readString(buffer.length); var byteArray = new Uint8Array(buffer.length), byteString = ""; dataReader.readBytes(byteArray); dataReader.close(); for (var i = 0; i < byteArray.length; i++) { var charByte = byteArray[i]; // var charRepresentation = charByte <= 127 ? String.fromCharCode(charByte) : charByte.toString(16); var charRepresentation = String.fromCharCode(charByte); byteString += charRepresentation; } win(byteString.slice(startPos, endPos)); } ); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, readAsArrayBuffer:function(win,fail,args) { var fileName =cordovaPathToNative(args[0]); getFileFromPathAsync(fileName).then( function (storageFile) { var blob = MSApp.createFileFromStorageFile(storageFile); var url = URL.createObjectURL(blob, { oneTimeOnly: true }); var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = 'arraybuffer'; xhr.onload = function () { var resultArrayBuffer = xhr.response; // get start and end position of bytes in buffer to be returned var startPos = args[1] || 0, endPos = args[2] || resultArrayBuffer.length; // if any of them is specified, we'll slice output array if (startPos !== 0 || endPos !== resultArrayBuffer.length) { // slice method supported only on Windows 8.1, so we need to check if it's available // see http://msdn.microsoft.com/en-us/library/ie/dn641192(v=vs.94).aspx if (resultArrayBuffer.slice) { resultArrayBuffer = resultArrayBuffer.slice(startPos, endPos); } else { // if slice isn't available, we'll use workaround method var tempArray = new Uint8Array(resultArrayBuffer), resBuffer = new ArrayBuffer(endPos - startPos), resArray = new Uint8Array(resBuffer); for (var i = 0; i < resArray.length; i++) { resArray[i] = tempArray[i + startPos]; } resultArrayBuffer = resBuffer; } } win(resultArrayBuffer); }; xhr.send(); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, readAsDataURL: function (win, fail, args) { var fileName = cordovaPathToNative(args[0]); getFileFromPathAsync(fileName).then( function (storageFile) { Windows.Storage.FileIO.readBufferAsync(storageFile).done( function (buffer) { var strBase64 = Windows.Security.Cryptography.CryptographicBuffer.encodeToBase64String(buffer); //the method encodeToBase64String will add "77u/" as a prefix, so we should remove it if(String(strBase64).substr(0,4) == "77u/") { strBase64 = strBase64.substr(4); } var mediaType = storageFile.contentType; var result = "data:" + mediaType + ";base64," + strBase64; win(result); } ); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, getDirectory: function (win, fail, args) { var fullPath = cordovaPathToNative(args[0]); var path = cordovaPathToNative(args[1]); var options = args[2]; var flag = ""; if (options) { flag = new Flags(options.create, options.exclusive); } else { flag = new Flags(false, false); } getFolderFromPathAsync(fullPath).then( function (storageFolder) { if (flag.create === true && flag.exclusive === true) { storageFolder.createFolderAsync(path, Windows.Storage.CreationCollisionOption.failIfExists).done( function (storageFolder) { win(new DirectoryEntry(storageFolder.name, storageFolder.path, getFilesystemFromPath(storageFolder.path))); }, function () { fail(FileError.PATH_EXISTS_ERR); } ); } else if (flag.create === true && flag.exclusive === false) { storageFolder.createFolderAsync(path, Windows.Storage.CreationCollisionOption.openIfExists).done( function (storageFolder) { win(new DirectoryEntry(storageFolder.name, storageFolder.path + "/", getFilesystemFromPath(storageFolder.path + "/"))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); } ); } else if (flag.create === false) { if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) { fail(FileError.ENCODING_ERR); return; } storageFolder.getFolderAsync(path).done( function (storageFolder) { win(new DirectoryEntry(storageFolder.name, storageFolder.path, getFilesystemFromPath(storageFolder.path))); }, function () { // check if path actually points to a file storageFolder.getFileAsync(path).done( function () { fail(FileError.TYPE_MISMATCH_ERR); }, function() { fail(FileError.NOT_FOUND_ERR); }); } ); } }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, remove: function (win, fail, args) { var fullPath = cordovaPathToNative(args[0]); getFileFromPathAsync(fullPath).then( function (sFile) { getFileFromPathAsync(fullPath).done(function (storageFile) { storageFile.deleteAsync().done(win, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }); }, function () { getFolderFromPathAsync(fullPath).then( function (sFolder) { var removeEntry = function () { var storageFolderTop = null; getFolderFromPathAsync(fullPath).then( function (storageFolder) { // FileSystem root can't be removed! var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder; var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder; if (fullPath == storageFolderPer.path || fullPath == storageFolderTem.path) { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); return; } storageFolderTop = storageFolder; return storageFolder.createFileQuery().getFilesAsync(); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); } // check sub-files. ).then(function (fileList) { if (fileList) { if (fileList.length === 0) { return storageFolderTop.createFolderQuery().getFoldersAsync(); } else { fail(FileError.INVALID_MODIFICATION_ERR); } } // check sub-folders. }).then(function (folderList) { if (folderList) { if (folderList.length === 0) { storageFolderTop.deleteAsync().done(win, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); } else { fail(FileError.INVALID_MODIFICATION_ERR); } } }); }; removeEntry(); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, removeRecursively: function (successCallback, fail, args) { var fullPath = cordovaPathToNative(args[0]); getFolderFromPathAsync(fullPath).done(function (storageFolder) { var storageFolderPer = Windows.Storage.ApplicationData.current.localFolder; var storageFolderTem = Windows.Storage.ApplicationData.current.temporaryFolder; if (storageFolder.path == storageFolderPer.path || storageFolder.path == storageFolderTem.path) { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); return; } storageFolder.deleteAsync().done(function (res) { successCallback(res); }, function (err) { fail(err); }); }, function () { fail(FileError.FILE_NOT_FOUND_ERR); }); }, getFile: function (win, fail, args) { //not sure why, but it won't work with normal slashes... var fullPath = cordovaPathToNative(args[0]); var path = cordovaPathToNative(args[1]); var options = args[2]; var completePath = fullPath + '\\' + path; //handles trailing slash and leading slash, or just one or the other completePath = completePath.replace(/\\\\\\/g, '/').replace(/\\\\/g, '\\'); var fileName = completePath.substring(completePath.lastIndexOf('\\')); //final adjustment fullPath = completePath.substring(0, completePath.lastIndexOf('\\')); path = fileName.replace(/\\/g, ''); var flag = ""; if (options !== null) { flag = new Flags(options.create, options.exclusive); } else { flag = new Flags(false, false); } getFolderFromPathAsync(fullPath).then( function (storageFolder) { if (flag.create === true && flag.exclusive === true) { storageFolder.createFileAsync(path, Windows.Storage.CreationCollisionOption.failIfExists).done( function (storageFile) { win(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { fail(FileError.PATH_EXISTS_ERR); } ); } else if (flag.create === true && flag.exclusive === false) { storageFolder.createFileAsync(path, Windows.Storage.CreationCollisionOption.openIfExists).done( function (storageFile) { win(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); } ); } else if (flag.create === false) { if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(path)) { fail(FileError.ENCODING_ERR); return; } storageFolder.getFileAsync(path).done( function (storageFile) { win(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { // check if path actually points to a folder storageFolder.getFolderAsync(path).done( function () { fail(FileError.TYPE_MISMATCH_ERR); }, function () { fail(FileError.NOT_FOUND_ERR); }); } ); } }, function () { fail(FileError.NOT_FOUND_ERR); } ); }, readEntries: function (win, fail, args) { // ["fullPath"] var path = cordovaPathToNative(args[0]); var result = []; getFolderFromPathAsync(path).then(function (storageFolder) { var promiseArr = []; var index = 0; promiseArr[index++] = storageFolder.createFileQuery().getFilesAsync().then(function (fileList) { if (fileList !== null) { for (var i = 0; i < fileList.length; i++) { result.push(new FileEntry(fileList[i].name, fileList[i].path, getFilesystemFromPath (fileList[i].path))); } } }); promiseArr[index++] = storageFolder.createFolderQuery().getFoldersAsync().then(function (folderList) { if (folderList !== null) { for (var j = 0; j < folderList.length; j++) { result.push(new DirectoryEntry(folderList[j].name, folderList[j].path, getFilesystemFromPath(folderList[j].path))); } } }); WinJS.Promise.join(promiseArr).then(function () { win(result); }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }, write: function (win, fail, args) { var fileName = cordovaPathToNative(args[0]), data = args[1], position = args[2], isBinary = args[3]; if (data instanceof ArrayBuffer) { data = Array.apply(null, new Uint8Array(data)); } var writePromise = isBinary ? Windows.Storage.FileIO.writeBytesAsync : Windows.Storage.FileIO.writeTextAsync; fileName = fileName.split("/").join("\\"); // split path to folder and file name var path = fileName.substring(0, fileName.lastIndexOf('\\')), file = fileName.split('\\').pop(); getFolderFromPathAsync(path).done( function(storageFolder) { storageFolder.createFileAsync(file, Windows.Storage.CreationCollisionOption.openIfExists).done( function(storageFile) { writePromise(storageFile, data). done(function () { win(data.length); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function() { fail(FileError.INVALID_MODIFICATION_ERR); } ); }, function() { fail(FileError.NOT_FOUND_ERR); }); }, truncate: function (win, fail, args) { // ["fileName","size"] var fileName = cordovaPathToNative(args[0]); var size = args[1]; getFileFromPathAsync(fileName).done(function(storageFile){ //the current length of the file. var leng = 0; storageFile.getBasicPropertiesAsync().then(function (basicProperties) { leng = basicProperties.size; if (Number(size) >= leng) { win(this.length); return; } if (Number(size) >= 0) { Windows.Storage.FileIO.readTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.utf8).then(function (fileContent) { fileContent = fileContent.substr(0, size); var fullPath = storageFile.path; var name = storageFile.name; var entry = new Entry(true, false, name, fullPath, getFilesystemFromPath(fullPath)); var parentPath = ""; var successCallBack = function (entry) { parentPath = entry.fullPath; storageFile.deleteAsync().then(function () { return getFolderFromPathAsync(parentPath); }).then(function (storageFolder) { storageFolder.createFileAsync(name).then(function (newStorageFile) { Windows.Storage.FileIO.writeTextAsync(newStorageFile, fileContent).done(function () { win(String(fileContent).length); }, function () { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); }); }, function() { fail(FileError.NO_MODIFICATION_ALLOWED_ERR); }); }); }; entry.getParent(successCallBack, null); }, function () { fail(FileError.NOT_FOUND_ERR); }); } }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }, copyTo: function (success, fail, args) { // ["fullPath","parent", "newName"] var srcPath = cordovaPathToNative(args[0]); var parentFullPath = cordovaPathToNative(args[1]); var name = args[2]; //name can't be invalid if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) { fail(FileError.ENCODING_ERR); return; } // copy var copyFiles = ""; getFileFromPathAsync(srcPath).then( function (sFile) { copyFiles = function (srcPath, parentPath) { var storageFileTop = null; getFileFromPathAsync(srcPath).then(function (storageFile) { storageFileTop = storageFile; return getFolderFromPathAsync(parentPath); }, function () { fail(FileError.NOT_FOUND_ERR); }).then(function (storageFolder) { storageFileTop.copyAsync(storageFolder, name, Windows.Storage.NameCollisionOption.failIfExists).then(function (storageFile) { success(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }; var copyFinish = function (srcPath, parentPath) { copyFiles(srcPath, parentPath); }; copyFinish(srcPath, parentFullPath); }, function () { getFolderFromPathAsync(srcPath).then( function (sFolder) { copyFiles = function (srcPath, parentPath) { var coreCopy = function (storageFolderTop, complete) { storageFolderTop.createFolderQuery().getFoldersAsync().then(function (folderList) { var folderPromiseArr = []; if (folderList.length === 0) { complete(); } else { getFolderFromPathAsync(parentPath).then(function (storageFolderTarget) { var tempPromiseArr = []; var index = 0; for (var j = 0; j < folderList.length; j++) { tempPromiseArr[index++] = storageFolderTarget.createFolderAsync(folderList[j].name).then(function (targetFolder) { folderPromiseArr.push(copyFiles(folderList[j].path, targetFolder.path)); }); } WinJS.Promise.join(tempPromiseArr).then(function () { WinJS.Promise.join(folderPromiseArr).then(complete); }); }); } }); }; return new WinJS.Promise(function (complete) { var storageFolderTop = null; var filePromiseArr = []; var fileListTop = null; getFolderFromPathAsync(srcPath).then(function (storageFolder) { storageFolderTop = storageFolder; return storageFolder.createFileQuery().getFilesAsync(); }).then(function (fileList) { fileListTop = fileList; if (fileList) { return getFolderFromPathAsync(parentPath); } }).then(function (targetStorageFolder) { for (var i = 0; i < fileListTop.length; i++) { filePromiseArr.push(fileListTop[i].copyAsync(targetStorageFolder)); } WinJS.Promise.join(filePromiseArr).done(function () { coreCopy(storageFolderTop, complete); }, function() { fail(FileError.INVALID_MODIFICATION_ERR); }); }); }); }; var copyFinish = function (srcPath, parentPath) { getFolderFromPathAsync(parentPath).then(function (storageFolder) { storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists).then(function (newStorageFolder) { //can't copy onto itself if (srcPath == newStorageFolder.path) { fail(FileError.INVALID_MODIFICATION_ERR); return; } //can't copy into itself if (srcPath == parentPath) { fail(FileError.INVALID_MODIFICATION_ERR); return; } copyFiles(srcPath, newStorageFolder.path).then(function () { getFolderFromPathAsync(newStorageFolder.path).done( function (storageFolder) { success(new DirectoryEntry(storageFolder.name, nativePathToCordova(storageFolder.path), getFilesystemFromPath(storageFolder.path))); }, function () { fail(FileError.NOT_FOUND_ERR); } ); }); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }; copyFinish(srcPath, parentFullPath); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, moveTo: function (success, fail, args) { var srcPath = cordovaPathToNative(args[0]); var parentFullPath = cordovaPathToNative(args[1]); var name = args[2]; //name can't be invalid if (/\?|\\|\*|\||\"|<|>|\:|\//g.test(name)) { fail(FileError.ENCODING_ERR); return; } var moveFiles = ""; getFileFromPathAsync(srcPath).then( function (sFile) { moveFiles = function (srcPath, parentPath) { var storageFileTop = null; getFileFromPathAsync(srcPath).then(function (storageFile) { storageFileTop = storageFile; return getFolderFromPathAsync(parentPath); }, function () { fail(FileError.NOT_FOUND_ERR); }).then(function (storageFolder) { storageFileTop.moveAsync(storageFolder, name, Windows.Storage.NameCollisionOption.replaceExisting).then(function () { success(new FileEntry(name, nativePathToCordova(storageFileTop.path), getFilesystemFromPath(storageFolder.path))); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }, function () { fail(FileError.NOT_FOUND_ERR); }); }; var moveFinish = function (srcPath, parentPath) { //can't copy onto itself if (srcPath == parentPath + "\\" + name) { fail(FileError.INVALID_MODIFICATION_ERR); return; } moveFiles(srcPath, parentFullPath); }; moveFinish(srcPath, parentFullPath); }, function () { getFolderFromPathAsync(srcPath).then( function (sFolder) { moveFiles = function (srcPath, parentPath) { var coreMove = function (storageFolderTop, complete) { storageFolderTop.createFolderQuery().getFoldersAsync().then(function (folderList) { var folderPromiseArr = []; if (folderList.length === 0) { // If failed, we must cancel the deletion of folders & files.So here wo can't delete the folder. complete(); } else { getFolderFromPathAsync(parentPath).then(function (storageFolderTarget) { var tempPromiseArr = []; var index = 0; for (var j = 0; j < folderList.length; j++) { tempPromiseArr[index++] = storageFolderTarget.createFolderAsync(folderList[j].name).then(function (targetFolder) { folderPromiseArr.push(moveFiles(folderList[j].path, targetFolder.path)); }); } WinJS.Promise.join(tempPromiseArr).then(function () { WinJS.Promise.join(folderPromiseArr).then(complete); }); }); } }); }; return new WinJS.Promise(function (complete) { var storageFolderTop = null; getFolderFromPathAsync(srcPath).then(function (storageFolder) { storageFolderTop = storageFolder; return storageFolder.createFileQuery().getFilesAsync(); }).then(function (fileList) { var filePromiseArr = []; getFolderFromPathAsync(parentPath).then(function (dstStorageFolder) { if (fileList) { for (var i = 0; i < fileList.length; i++) { filePromiseArr.push(fileList[i].moveAsync(dstStorageFolder)); } } WinJS.Promise.join(filePromiseArr).then(function () { coreMove(storageFolderTop, complete); }, function () { }); }); }); }); }; var moveFinish = function (srcPath, parentPath) { var originFolderTop = null; getFolderFromPathAsync(srcPath).then(function (originFolder) { originFolderTop = originFolder; return getFolderFromPathAsync(parentPath); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }).then(function (storageFolder) { return storageFolder.createFolderAsync(name, Windows.Storage.CreationCollisionOption.openIfExists); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }).then(function (newStorageFolder) { //can't move onto directory that is not empty newStorageFolder.createFileQuery().getFilesAsync().then(function (fileList) { newStorageFolder.createFolderQuery().getFoldersAsync().then(function (folderList) { if (fileList.length !== 0 || folderList.length !== 0) { fail(FileError.INVALID_MODIFICATION_ERR); return; } //can't copy onto itself if (srcPath == newStorageFolder.path) { fail(FileError.INVALID_MODIFICATION_ERR); return; } //can't copy into itself if (srcPath == parentPath) { fail(FileError.INVALID_MODIFICATION_ERR); return; } moveFiles(srcPath, newStorageFolder.path).then(function () { var successCallback = function () { success(new DirectoryEntry(name, nativePathToCordova(newStorageFolder.path), getFilesystemFromPath(newStorageFolder.path))); }; originFolderTop.deleteAsync().done(successCallback, fail); }, function () { console.log("error!"); }); }); }); }, function () { fail(FileError.INVALID_MODIFICATION_ERR); }); }; moveFinish(srcPath, parentFullPath); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); }, tempFileSystem:null, persistentFileSystem:null, requestFileSystem: function (win, fail, args) { var type = args[0]; var size = args[1]; var filePath = ""; var result = null; var fsTypeName = ""; switch (type) { case LocalFileSystem.TEMPORARY: filePath = Windows.Storage.ApplicationData.current.temporaryFolder.path; fsTypeName = "temporary"; break; case LocalFileSystem.PERSISTENT: filePath = Windows.Storage.ApplicationData.current.localFolder.path; fsTypeName = "persistent"; break; } var MAX_SIZE = 10000000000; if (size > MAX_SIZE) { fail(FileError.QUOTA_EXCEEDED_ERR); return; } var fileSystem = new FileSystem(fsTypeName, new DirectoryEntry(fsTypeName, nativePathToCordova(filePath))); result = fileSystem; win(result); }, resolveLocalFileSystemURI: function (success, fail, args) { var uri = cordovaPathToNative(args[0]); var path = uri; // support for file name with parameters if (/\?/g.test(path)) { path = String(path).split("?")[0]; } // support for encodeURI if (/\%5/g.test(path)) { path = decodeURI(path); } // support for special path start with file:/// if (path.substr(0, 8) == "file:///") { path = Windows.Storage.ApplicationData.current.localFolder.path + "\\" + String(path).substr(8); } else { // method should not let read files outside of the [APP HASH]/Local or [APP HASH]/temp folders if (path.indexOf(Windows.Storage.ApplicationData.current.temporaryFolder.path) != 0 && path.indexOf(Windows.Storage.ApplicationData.current.localFolder.path) != 0) { fail(FileError.NOT_FOUND_ERR); return; } } getFileFromPathAsync(path).then( function (storageFile) { success(new FileEntry(storageFile.name, nativePathToCordova(storageFile.path), getFilesystemFromPath(storageFile.path))); }, function () { getFolderFromPathAsync(path).then( function (storageFolder) { var cordovaPath = nativePathToCordova(storageFolder.path); success(new DirectoryEntry(storageFolder.name, cordovaPath, getFilesystemFromPath(storageFolder.path), cordovaPath)); }, function () { fail(FileError.NOT_FOUND_ERR); } ); } ); } }; require("cordova/exec/proxy").add("File",module.exports);
JavaScript
var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'); var Keyboard = function() { }; Keyboard.hideKeyboardAccessoryBar = function(hide) { exec(null, null, "Keyboard", "hideKeyboardAccessoryBar", [hide]); }; Keyboard.close = function() { exec(null, null, "Keyboard", "close", []); }; Keyboard.disableScroll = function(disable) { exec(null, null, "Keyboard", "disableScroll", [disable]); }; /* Keyboard.styleDark = function(dark) { exec(null, null, "Keyboard", "styleDark", [dark]); }; */ Keyboard.isVisible = false; module.exports = Keyboard;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var vibrate = function(duration) { navigator.vibrate(duration); }; module.exports = vibrate;
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var exec = require('cordova/exec'); /** * Provides access to the vibration mechanism on the device. */ module.exports = { /** * Vibrates the device for a given amount of time or for a given pattern or immediately cancels any ongoing vibrations (depending on the parameter). * * @param {Integer} param The number of milliseconds to vibrate (if 0, cancels vibration) * * * @param {Array of Integer} param Pattern with which to vibrate the device. * Pass in an array of integers that * are the durations for which to * turn on or off the vibrator in * milliseconds. The FIRST value * indicates the * number of milliseconds for which * to keep the vibrator ON before * turning it off. The NEXT value indicates the * number of milliseconds for which * to keep the vibrator OFF before * turning it on. Subsequent values * alternate between durations in * milliseconds to turn the vibrator * off or to turn the vibrator on. * (if empty, cancels vibration) */ vibrate: function(param) { /* Aligning with w3c spec */ //vibrate if ((typeof param == 'number') && param != 0) exec(null, null, "Vibration", "vibrate", [param]); //vibrate with array ( i.e. vibrate([3000]) ) else if ((typeof param == 'object') && param.length == 1) { //cancel if vibrate([0]) if (param[0] == 0) exec(null, null, "Vibration", "cancelVibration", []); //else vibrate else exec(null, null, "Vibration", "vibrate", [param[0]]); } //vibrate with a pattern else if ((typeof param == 'object') && param.length > 1) { var repeat = -1; //no repeat exec(null, null, "Vibration", "vibrateWithPattern", [param, repeat]); } //cancel vibration (param = 0 or []) else exec(null, null, "Vibration", "cancelVibration", []); }, /** * Vibrates the device with a given pattern. * * @param {Array of Integer} pattern Pattern with which to vibrate the device. * Pass in an array of integers that * are the durations for which to * turn on or off the vibrator in * milliseconds. The first value * indicates the number of milliseconds * to wait before turning the vibrator * on. The next value indicates the * number of milliseconds for which * to keep the vibrator on before * turning it off. Subsequent values * alternate between durations in * milliseconds to turn the vibrator * off or to turn the vibrator on. * * @param {Integer} repeat Optional index into the pattern array at which * to start repeating (will repeat until canceled), * or -1 for no repetition (default). */ vibrateWithPattern: function(pattern, repeat) { repeat = (typeof repeat !== "undefined") ? repeat : -1; pattern.unshift(0); //add a 0 at beginning for backwards compatibility from w3c spec exec(null, null, "Vibration", "vibrateWithPattern", [pattern, repeat]); }, /** * Immediately cancels any currently running vibration. */ cancelVibration: function() { exec(null, null, "Vibration", "cancelVibration", []); }, };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ exports.defineAutoTests = function () { describe('Vibration (navigator.notification.vibrate)', function () { it("navigator.notification should exist", function () { expect(navigator.notification).toBeDefined(); }); it("should contain a vibrate function", function () { expect(typeof navigator.notification.vibrate).toBeDefined(); expect(typeof navigator.notification.vibrate).toBe("function"); }); }); }; exports.defineManualTests = function (contentEl, createActionButton) { var logMessage = function (message, color) { var log = document.getElementById('info'); var logLine = document.createElement('div'); if (color) { logLine.style.color = color; } logLine.innerHTML = message; log.appendChild(logLine); } var clearLog = function () { var log = document.getElementById('info'); log.innerHTML = ''; } //------------------------------------------------------------------------- // Vibrations //------------------------------------------------------------------------- //old vibrate call var vibrateOld = function(){ clearLog(); navigator.notification.vibrate(2500); logMessage("navigator.notification.vibrate(2500)", "green"); }; //old vibrate with pattern call var vibrateWithPatternOld = function(){ clearLog(); navigator.notification.vibrateWithPattern([1000, 3000, 2000, 5000]); logMessage("navigator.notification.vibrateWithPattern([1000, 3000, 2000, 5000])", "green"); }; //old cancel vibrate call var cancelOld = function(){ clearLog(); navigator.notification.cancelVibration(); logMessage("navigator.notification.cancelVibration()", "green"); }; //new standard vibrate call that aligns to w3c spec with param long var vibrateWithInt = function() { clearLog(); navigator.vibrate(3000); logMessage("navigator.vibrate(3000)", "green"); }; //new standard vibrate call that aligns to w3c spec with param array var vibrateWithArray = function() { clearLog(); navigator.vibrate([3000]); logMessage("navigator.vibrate([3000])", "green"); }; //vibrate with a pattern using w3c spec var vibrateWithPattern = function() { clearLog(); navigator.vibrate([1000, 2000, 3000, 2000, 5000]); logMessage("navigator.vibrate([1000, 2000, 3000, 2000, 5000])", "green"); }; //cancel existing vibration using w3c spec navigator.vibrate(0) var cancelWithZero = function() { clearLog(); navigator.vibrate(0); logMessage("navigator.vibrate(0)", "green"); }; //cancel existing vibration using w3c spec navigator.vibrate([]) var cancelWithEmpty = function() { clearLog(); navigator.vibrate([]); logMessage("navigator.vibrate([])", "green"); }; //reference to the timeout variable var timeout; //special long vibrate used to test cancel var longVibrate = function() { clearLog(); navigator.vibrate(60000); vibrateOn = true; logMessage("navigator.vibrate(60000)", "green"); timeout = setTimeout(resetVibrateOn, 60000); //if user doesn't cancel vibrate, reset vibrateOn var after 60 seconds }; //special long vibrate with pattern used to test cancel var longVibrateWithPattern = function() { clearLog(); navigator.vibrate([1000, 2000, 3000, 2000, 5000, 2000, 30000]); vibrateOn = true; logMessage("navigator.vibrate([1000, 2000, 3000, 2000, 5000, 2000, 30000])", "green"); timeout = setTimeout(resetVibrateOn, 45000); //if user doesn't cancel vibrate, reset vibrateOn var after 45 seconds }; //initiate two vibrations to test cancel var multipleVibrations = function() { clearLog(); navigator.vibrate(20000); navigator.vibrate(45000); vibrateOn = true; logMessage("navigator.vibrate(15000)\nnavigator.vibrate(45000)", "green"); timeout = setTimeout(resetVibrateOn, 45000); //if user doesn't cancel vibrate, reset vibrateOn var after 45 seconds } function resetVibrateOn() { vibrateOn = false; } //check whether there is an ongoing vibration var vibrateOn = false; var vibrate_tests = '<h1>Vibrate Tests</h1>' + '<h3>Starred tests only work for Android and Windows. </h3>' + '<h3>iOS ignores the time given for a vibrate </h3>' + '<div id="vibrate_old"></div>' + 'Expected result: Vibrate once for 2.5 seconds.' + '<p/> <div id="vibrateWithPattern_old"></div>' + 'Expected result: Pause for 1s, vibrate for 3s, pause for 2s, vibrate for 5s.' + '<p/> <div id="cancelVibrate_old"></div>' + 'Expected result: Press once to initiate vibrate for 60 seconds. Press again to cancel vibrate immediately.' + '<p/> <div id="cancelVibrateWithPattern_old"></div>' + 'Expected result: Press once to initiate vibrate with pattern for 45s. Press again to cancel vibrate immediately.' + '<p/> <div id="vibrate_int"></div>' + 'Expected result: Vibrate once for 3 seconds.' + '<p/> <div id="vibrate_array"></div>' + 'Expected result: Vibrate once for 3 seconds.' + '<p/> <div id="vibrate_with_pattern"></div>' + 'Expected result: Vibrate for 1s, pause for 2s, vibrate for 3s, pause for 2s, vibrate for 5s.' + '<p/> <div id="cancel_zero"></div>' + 'Expected result: Press once to initiate vibrate for 60 seconds. Press again to cancel vibrate immediately.' + '<p/><div id="cancel_array"></div>' + 'Expected result: Press once to initiate vibrate for 60 seconds. Press again to cancel vibrate immediately.' + '<p/> <div id="cancelWithPattern_zero"></div>' + 'Expected result: Press once to initiate vibrate with pattern for 45s. Press again to cancel vibrate immediately.' + '<p/> <div id="cancelWithPattern_array"></div>' + 'Expected result: Press once to initiate vibrate with pattern for 45s. Press again to cancel vibrate immediately.' + '<p/> <div id="cancelMultipleVibrations"></div>' + 'Expected result: Press once to initiate two vibrations simultaneously (one for 20s the other for 45s so total of 45s). Press again to cancel both vibrations immediately.'; contentEl.innerHTML = '<div id="info"></div>' + vibrate_tests; //standard vibrate with old call createActionButton('Vibrate (Old)', function () { vibrateOld(); }, 'vibrate_old'); //vibrate with pattern with old call createActionButton('* Vibrate with a pattern (Old)', function () { vibrateWithPatternOld(); }, 'vibrateWithPattern_old'); //cancel vibrate with old call createActionButton('* Cancel vibration (Old)', function() { if (!vibrateOn) { longVibrate(); } else { cancelOld(); resetVibrateOn(); clearTimeout(timeout); //clear the timeout since user has canceled the vibrate } }, 'cancelVibrate_old'); //cancel vibrate with pattern with old call createActionButton('* Cancel vibration with pattern (Old)', function() { if (!vibrateOn) { longVibrateWithPattern(); } else { cancelOld(); resetVibrateOn(); clearTimeout(timeout); //clear the timeout since user has canceled the vibrate } }, 'cancelVibrateWithPattern_old'); //standard vibrate with new call param int createActionButton('Vibrate with int', function() { vibrateWithInt(); }, 'vibrate_int'); //standard vibrate with new call param array createActionButton('Vibrate with array', function() { vibrateWithArray(); }, 'vibrate_array'); //vibrate with a pattern createActionButton('* Vibrate with a pattern', function() { vibrateWithPattern(); }, 'vibrate_with_pattern'); //cancel any existing vibrations with param 0 createActionButton('* Cancel vibration with 0', function() { if (!vibrateOn) { longVibrate(); } else { cancelWithZero(); resetVibrateOn(); clearTimeout(timeout); //clear the timeout since user has canceled the vibrate } }, 'cancel_zero'); //cancel any existing vibrations with param [] createActionButton('* Cancel vibration with []', function() { if (!vibrateOn) { longVibrate(); } else { cancelWithEmpty(); resetVibrateOn(); clearTimeout(timeout); //clear the timeout since user has canceled the vibrate } }, 'cancel_array'); //cancel vibration with pattern with param 0 createActionButton('* Cancel vibration with pattern with 0', function() { if (!vibrateOn) { longVibrateWithPattern(); } else { cancelWithZero(); resetVibrateOn(); clearTimeout(timeout); //clear the timeout since user has canceled the vibrate } }, 'cancelWithPattern_zero'); //cancel vibration with pattern with param [] createActionButton('* Cancel vibration with pattern with []', function() { if (!vibrateOn) { longVibrateWithPattern(); } else { cancelWithEmpty(); resetVibrateOn(); clearTimeout(timeout); //clear the timeout since user has canceled the vibrate } }, 'cancelWithPattern_array'); //cancel multiple vibrations createActionButton('* Cancel multiple vibrations', function() { if (!vibrateOn) { multipleVibrations(); } else { cancelWithZero(); resetVibrateOn(); clearTimeout(timeout); //clear the timeout since user has canceled the vibrate } }, 'cancelMultipleVibrations'); };
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ module.exports = { vibrate: function(milliseconds) { if (navigator.vibrate) { navigator.vibrate(milliseconds); } } }; require("cordova/tizen/commandProxy").add("Vibration", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var cordova = require('cordova'); module.exports = { vibrate: function(success, fail, milliseconds) { if (navigator.notification.vibrate) { navigator.vibrate(milliseconds); } else { console.log ("cordova/plugin/firefoxos/vibration, vibrate API does not exist"); } } }; require("cordova/exec/proxy").add("Vibration", module.exports);
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ var vibration; module.exports = { vibrate: function (success, fail, args, env) { var result = new PluginResult(args, env), duration = args[0], response = vibration.getInstance().vibrate(duration); result.ok(response, false); } }; /////////////////////////////////////////////////////////////////// // JavaScript wrapper for JNEXT plugin /////////////////////////////////////////////////////////////////// JNEXT.Vibration = function () { var self = this, hasInstance = false; self.vibrate = function (duration) { //This is how Javascript calls into native return JNEXT.invoke(self.m_id, "vibrate " + duration); }; self.init = function () { //Checks that the jnext library is present and loads it if (!JNEXT.require("libVibration")) { return false; } //Creates the native object that this interface will call self.m_id = JNEXT.createObject("libVibration.Vibration"); if (self.m_id === "") { return false; } //Registers for the JNEXT event loop JNEXT.registerEvents(self); }; self.m_id = ""; //Used by JNEXT library to get the ID self.getId = function () { return self.m_id; }; //Not truly required but useful for instance management self.getInstance = function () { if (!hasInstance) { self.init(); hasInstance = true; } return self; }; }; vibration = new JNEXT.Vibration();
JavaScript
/** * The MIT License * * Copyright (c) 2011-2013 * Colin Turner (github.com/koolspin) * Guillaume Charhon (github.com/poiuytrez) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * */ /** * constructor */ function SpeechRecognizer() { } /** * Recognize speech and return a list of matches * * @param successCallback * @param errorCallback * @param reqCode User-defined integer request code which will be returned when recognition is complete * @param maxMatches The maximum number of matches to return. 0 means the service decides how many to return. * @param promptString An optional string to prompt the user during recognition */ SpeechRecognizer.prototype.startRecognize = function(successCallback, errorCallback, maxMatches, promptString, language) { return cordova.exec(successCallback, errorCallback, "SpeechRecognizer", "startRecognize", [maxMatches, promptString, language]); }; /** * Get the list of the supported languages in IETF BCP 47 format * * @param successCallback * @param errorCallback * * Returns an array of codes in the success callback */ SpeechRecognizer.prototype.getSupportedLanguages = function(successCallback, errorCallback) { return cordova.exec(successCallback, errorCallback, "SpeechRecognizer", "getSupportedLanguages", []); }; /** * Export */ module.exports = new SpeechRecognizer();
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ //------------------------------------------------------------------------------ var logger = require("./logger"); var utils = require("cordova/utils"); //------------------------------------------------------------------------------ // object that we're exporting //------------------------------------------------------------------------------ var console = module.exports; //------------------------------------------------------------------------------ // copy of the original console object //------------------------------------------------------------------------------ var WinConsole = window.console; //------------------------------------------------------------------------------ // whether to use the logger //------------------------------------------------------------------------------ var UseLogger = false; //------------------------------------------------------------------------------ // Timers //------------------------------------------------------------------------------ var Timers = {}; //------------------------------------------------------------------------------ // used for unimplemented methods //------------------------------------------------------------------------------ function noop() {} //------------------------------------------------------------------------------ // used for unimplemented methods //------------------------------------------------------------------------------ console.useLogger = function (value) { if (arguments.length) UseLogger = !!value; if (UseLogger) { if (logger.useConsole()) { throw new Error("console and logger are too intertwingly"); } } return UseLogger; }; //------------------------------------------------------------------------------ console.log = function() { if (logger.useConsole()) return; logger.log.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.error = function() { if (logger.useConsole()) return; logger.error.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.warn = function() { if (logger.useConsole()) return; logger.warn.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.info = function() { if (logger.useConsole()) return; logger.info.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.debug = function() { if (logger.useConsole()) return; logger.debug.apply(logger, [].slice.call(arguments)); }; //------------------------------------------------------------------------------ console.assert = function(expression) { if (expression) return; var message = logger.format.apply(logger.format, [].slice.call(arguments, 1)); console.log("ASSERT: " + message); }; //------------------------------------------------------------------------------ console.clear = function() {}; //------------------------------------------------------------------------------ console.dir = function(object) { console.log("%o", object); }; //------------------------------------------------------------------------------ console.dirxml = function(node) { console.log(node.innerHTML); }; //------------------------------------------------------------------------------ console.trace = noop; //------------------------------------------------------------------------------ console.group = console.log; //------------------------------------------------------------------------------ console.groupCollapsed = console.log; //------------------------------------------------------------------------------ console.groupEnd = noop; //------------------------------------------------------------------------------ console.time = function(name) { Timers[name] = new Date().valueOf(); }; //------------------------------------------------------------------------------ console.timeEnd = function(name) { var timeStart = Timers[name]; if (!timeStart) { console.warn("unknown timer: " + name); return; } var timeElapsed = new Date().valueOf() - timeStart; console.log(name + ": " + timeElapsed + "ms"); }; //------------------------------------------------------------------------------ console.timeStamp = noop; //------------------------------------------------------------------------------ console.profile = noop; //------------------------------------------------------------------------------ console.profileEnd = noop; //------------------------------------------------------------------------------ console.count = noop; //------------------------------------------------------------------------------ console.exception = console.log; //------------------------------------------------------------------------------ console.table = function(data, columns) { console.log("%o", data); }; //------------------------------------------------------------------------------ // return a new function that calls both functions passed as args //------------------------------------------------------------------------------ function wrappedOrigCall(orgFunc, newFunc) { return function() { var args = [].slice.call(arguments); try { orgFunc.apply(WinConsole, args); } catch (e) {} try { newFunc.apply(console, args); } catch (e) {} }; } //------------------------------------------------------------------------------ // For every function that exists in the original console object, that // also exists in the new console object, wrap the new console method // with one that calls both //------------------------------------------------------------------------------ for (var key in console) { if (typeof WinConsole[key] == "function") { console[key] = wrappedOrigCall(WinConsole[key], console[key]); } }
JavaScript
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ //------------------------------------------------------------------------------ // The logger module exports the following properties/functions: // // LOG - constant for the level LOG // ERROR - constant for the level ERROR // WARN - constant for the level WARN // INFO - constant for the level INFO // DEBUG - constant for the level DEBUG // logLevel() - returns current log level // logLevel(value) - sets and returns a new log level // useConsole() - returns whether logger is using console // useConsole(value) - sets and returns whether logger is using console // log(message,...) - logs a message at level LOG // error(message,...) - logs a message at level ERROR // warn(message,...) - logs a message at level WARN // info(message,...) - logs a message at level INFO // debug(message,...) - logs a message at level DEBUG // logLevel(level,message,...) - logs a message specified level // //------------------------------------------------------------------------------ var logger = exports; var exec = require('cordova/exec'); var utils = require('cordova/utils'); var UseConsole = false; var UseLogger = true; var Queued = []; var DeviceReady = false; var CurrentLevel; var originalConsole = console; /** * Logging levels */ var Levels = [ "LOG", "ERROR", "WARN", "INFO", "DEBUG" ]; /* * add the logging levels to the logger object and * to a separate levelsMap object for testing */ var LevelsMap = {}; for (var i=0; i<Levels.length; i++) { var level = Levels[i]; LevelsMap[level] = i; logger[level] = level; } CurrentLevel = LevelsMap.WARN; /** * Getter/Setter for the logging level * * Returns the current logging level. * * When a value is passed, sets the logging level to that value. * The values should be one of the following constants: * logger.LOG * logger.ERROR * logger.WARN * logger.INFO * logger.DEBUG * * The value used determines which messages get printed. The logging * values above are in order, and only messages logged at the logging * level or above will actually be displayed to the user. E.g., the * default level is WARN, so only messages logged with LOG, ERROR, or * WARN will be displayed; INFO and DEBUG messages will be ignored. */ logger.level = function (value) { if (arguments.length) { if (LevelsMap[value] === null) { throw new Error("invalid logging level: " + value); } CurrentLevel = LevelsMap[value]; } return Levels[CurrentLevel]; }; /** * Getter/Setter for the useConsole functionality * * When useConsole is true, the logger will log via the * browser 'console' object. */ logger.useConsole = function (value) { if (arguments.length) UseConsole = !!value; if (UseConsole) { if (typeof console == "undefined") { throw new Error("global console object is not defined"); } if (typeof console.log != "function") { throw new Error("global console object does not have a log function"); } if (typeof console.useLogger == "function") { if (console.useLogger()) { throw new Error("console and logger are too intertwingly"); } } } return UseConsole; }; /** * Getter/Setter for the useLogger functionality * * When useLogger is true, the logger will log via the * native Logger plugin. */ logger.useLogger = function (value) { // Enforce boolean if (arguments.length) UseLogger = !!value; return UseLogger; }; /** * Logs a message at the LOG level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.log = function(message) { logWithArgs("LOG", arguments); }; /** * Logs a message at the ERROR level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.error = function(message) { logWithArgs("ERROR", arguments); }; /** * Logs a message at the WARN level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.warn = function(message) { logWithArgs("WARN", arguments); }; /** * Logs a message at the INFO level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.info = function(message) { logWithArgs("INFO", arguments); }; /** * Logs a message at the DEBUG level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.debug = function(message) { logWithArgs("DEBUG", arguments); }; // log at the specified level with args function logWithArgs(level, args) { args = [level].concat([].slice.call(args)); logger.logLevel.apply(logger, args); } // return the correct formatString for an object function formatStringForMessage(message) { return (typeof message === "string") ? "" : "%o"; } /** * Logs a message at the specified level. * * Parameters passed after message are used applied to * the message with utils.format() */ logger.logLevel = function(level /* , ... */) { // format the message with the parameters var formatArgs = [].slice.call(arguments, 1); var fmtString = formatStringForMessage(formatArgs[0]); if (fmtString.length > 0){ formatArgs.unshift(fmtString); // add formatString } var message = logger.format.apply(logger.format, formatArgs); if (LevelsMap[level] === null) { throw new Error("invalid logging level: " + level); } if (LevelsMap[level] > CurrentLevel) return; // queue the message if not yet at deviceready if (!DeviceReady && !UseConsole) { Queued.push([level, message]); return; } // Log using the native logger if that is enabled if (UseLogger) { exec(null, null, "Console", "logLevel", [level, message]); } // Log using the console if that is enabled if (UseConsole) { // make sure console is not using logger if (console.useLogger()) { throw new Error("console and logger are too intertwingly"); } // log to the console switch (level) { case logger.LOG: originalConsole.log(message); break; case logger.ERROR: originalConsole.log("ERROR: " + message); break; case logger.WARN: originalConsole.log("WARN: " + message); break; case logger.INFO: originalConsole.log("INFO: " + message); break; case logger.DEBUG: originalConsole.log("DEBUG: " + message); break; } } }; /** * Formats a string and arguments following it ala console.log() * * Any remaining arguments will be appended to the formatted string. * * for rationale, see FireBug's Console API: * http://getfirebug.com/wiki/index.php/Console_API */ logger.format = function(formatString, args) { return __format(arguments[0], [].slice.call(arguments,1)).join(' '); }; //------------------------------------------------------------------------------ /** * Formats a string and arguments following it ala vsprintf() * * format chars: * %j - format arg as JSON * %o - format arg as JSON * %c - format arg as '' * %% - replace with '%' * any other char following % will format it's * arg via toString(). * * Returns an array containing the formatted string and any remaining * arguments. */ function __format(formatString, args) { if (formatString === null || formatString === undefined) return [""]; if (arguments.length == 1) return [formatString.toString()]; if (typeof formatString != "string") formatString = formatString.toString(); var pattern = /(.*?)%(.)(.*)/; var rest = formatString; var result = []; while (args.length) { var match = pattern.exec(rest); if (!match) break; var arg = args.shift(); rest = match[3]; result.push(match[1]); if (match[2] == '%') { result.push('%'); args.unshift(arg); continue; } result.push(__formatted(arg, match[2])); } result.push(rest); var remainingArgs = [].slice.call(args); remainingArgs.unshift(result.join('')); return remainingArgs; } function __formatted(object, formatChar) { try { switch(formatChar) { case 'j': case 'o': return JSON.stringify(object); case 'c': return ''; } } catch (e) { return "error JSON.stringify()ing argument: " + e; } if ((object === null) || (object === undefined)) { return Object.prototype.toString.call(object); } return object.toString(); } //------------------------------------------------------------------------------ // when deviceready fires, log queued messages logger.__onDeviceReady = function() { if (DeviceReady) return; DeviceReady = true; for (var i=0; i<Queued.length; i++) { var messageArgs = Queued[i]; logger.logLevel(messageArgs[0], messageArgs[1]); } Queued = null; }; // add a deviceready event to log queued messages document.addEventListener("deviceready", logger.__onDeviceReady, false);
JavaScript
var gulp = require('gulp'); var gutil = require('gulp-util'); var bower = require('bower'); var concat = require('gulp-concat'); var sass = require('gulp-sass'); var minifyCss = require('gulp-minify-css'); var rename = require('gulp-rename'); var sh = require('shelljs'); var paths = { sass: ['./scss/**/*.scss'] }; gulp.task('default', ['sass']); gulp.task('sass', function(done) { gulp.src('./scss/ionic.app.scss') .pipe(sass()) .pipe(gulp.dest('./www/css/')) .pipe(minifyCss({ keepSpecialComments: 0 })) .pipe(rename({ extname: '.min.css' })) .pipe(gulp.dest('./www/css/')) .on('end', done); }); gulp.task('watch', function() { gulp.watch(paths.sass, ['sass']); }); gulp.task('install', ['git-check'], function() { return bower.commands.install() .on('log', function(data) { gutil.log('bower', gutil.colors.cyan(data.id), data.message); }); }); gulp.task('git-check', function(done) { if (!sh.which('git')) { console.log( ' ' + gutil.colors.red('Git is not installed.'), '\n Git, the version control system, is required to download Ionic.', '\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.', '\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.' ); process.exit(1); } done(); });
JavaScript
// global variables var acListTotal = 0; var acListCurrent = -1; var acDelay = 500; var acURL = null; var acSearchId = null; var acResultsId = null; var acSearchField = null; var acResultsDiv = null; function setAutoComplete(field_id, results_id, get_url) { // initialize vars acSearchId = "#" + field_id; acResultsId = "#" + results_id; acURL = get_url; // create the results div $("#auto").append('<div id="' + results_id + '"></div>'); // register mostly used vars acSearchField = $(acSearchId); acResultsDiv = $(acResultsId); // reposition div repositionResultsDiv(); // on blur listener acSearchField.blur(function(){ setTimeout("clearAutoComplete()", 200) }); // on key up listener acSearchField.keyup(function (e) { // get keyCode (window.event is for IE) var keyCode = e.keyCode || window.event.keyCode; var lastVal = acSearchField.val(); // check an treat up and down arrows if(updownArrow(keyCode)){ return; } // check for an ENTER or ESC if(keyCode == 13 || keyCode == 27){ clearAutoComplete(); return; } // if is text, call with delay setTimeout(function () {autoComplete(lastVal)}, acDelay); }); } // treat the auto-complete action (delayed function) function autoComplete(lastValue) { // get the field value var part = acSearchField.val(); // if it's empty clear the resuts box and return if(part == ''){ clearAutoComplete(); return; } // if it's equal the value from the time of the call, allow if(lastValue != part){ return; } // get remote data as JSON $.getJSON(acURL + part, function(json){ // get the total of results var ansLength = acListTotal = json.length; // if there are results populate the results div if(ansLength > 0){ var newData = ''; // create a div for each result for(i=0; i < ansLength; i++) { newData += '<div class="unselected">' + json[i] + '</div>'; } // update the results div acResultsDiv.html(newData); acResultsDiv.css("display","block"); // for all divs in results var divs = $(acResultsId + " > div"); // on mouse over clean previous selected and set a new one divs.mouseover( function() { divs.each(function(){ this.className = "unselected"; }); this.className = "selected"; }) // on click copy the result text to the search field and hide divs.click( function() { acSearchField.val(this.childNodes[0].nodeValue); clearAutoComplete(); }); } else { clearAutoComplete(); } }); } // clear auto complete box function clearAutoComplete() { acResultsDiv.html(''); acResultsDiv.css("display","none"); } // reposition the results div accordingly to the search field function repositionResultsDiv() { // get the field position var sf_pos = acSearchField.offset(); var sf_top = sf_pos.top; var sf_left = sf_pos.left; // get the field size var sf_height = acSearchField.height(); var sf_width = acSearchField.width(); // apply the css styles - optimized for Firefox acResultsDiv.css("position","absolute"); acResultsDiv.css("left", sf_left - 2); acResultsDiv.css("top", sf_top + sf_height + 5); acResultsDiv.css("width", sf_width - 2); } // treat up and down key strokes defining the next selected element function updownArrow(keyCode) { if(keyCode == 40 || keyCode == 38){ if(keyCode == 38){ // keyUp if(acListCurrent == 0 || acListCurrent == -1){ acListCurrent = acListTotal-1; }else{ acListCurrent--; } }else { // keyDown if(acListCurrent == acListTotal-1){ acListCurrent = 0; }else { acListCurrent++; } } // loop through each result div applying the correct style acResultsDiv.children().each(function(i){ if(i == acListCurrent){ acSearchField.val(this.childNodes[0].nodeValue); this.className = "selected"; } else { this.className = "unselected"; } }); return true; } else { // reset acListCurrent = -1; return false; } }
JavaScript
var operation = { getClient: function(type) { $.getJSON('user?action=getClient',{flag: type}, function(response) { return response; }); } }; function getClient(type) { return $.getJSON('user?action=getClient',{flag: type}); } function delClient(id, callback) { $.post('/user?action=delClient', {clientid: id}, function(response) { callback(response); }, "json"); } function clientCheckIn(id, callback) { $.post('/user?action=clientCheckIn', {clientid: id}, function(response) { callback(response); }, "json"); } function assignTable(id, tableType, callback) { $.post('/user?action=assignTable', {clientid: id, table: tableType}, function(response) { callback(response); }, "json"); } function finishedEating(id, callback) { $.post('/user?action=finishedEating', {clientid: id}, function(response) { callback(response); }, "json"); } function clientNotify(id, callback) { $.post('/user?action=clientNotify', {clientid: id}, function(response) { callback(response); }, "json"); } function getShopState(time) { $.getJSON('/user?action=getShopState', function(response) { $('#maxOrderNum').text(response.maxNum); $('#currentOrderNum').text(response.cuttentNum); }); time = (time == null)?60000:time; console.log(time); setTimeout("getShopState(" + time + ")", time); } function shopSwitch(flag, callback) { $.post('/user?action=shopSwitch', {switch: flag}, function(response) { callback(response); }, "json"); }
JavaScript
/** * Creates a new level control. * @constructor * @param {IoMap} iomap the IO map controller. * @param {Array.<string>} levels the levels to create switchers for. */ function LevelControl(iomap, levels) { var that = this; this.iomap_ = iomap; this.el_ = this.initDom_(levels); google.maps.event.addListener(iomap, 'level_changed', function() { that.changeLevel_(iomap.get('level')); }); } /** * Gets the DOM element for the control. * @return {Element} */ LevelControl.prototype.getElement = function() { return this.el_; }; /** * Creates the necessary DOM for the control. * @return {Element} */ LevelControl.prototype.initDom_ = function(levelDefinition) { var controlDiv = document.createElement('DIV'); controlDiv.setAttribute('id', 'levels-wrapper'); var levels = document.createElement('DIV'); levels.setAttribute('id', 'levels'); controlDiv.appendChild(levels); var levelSelect = this.levelSelect_ = document.createElement('DIV'); levelSelect.setAttribute('id', 'level-select'); levels.appendChild(levelSelect); this.levelDivs_ = []; var that = this; for (var i = 0, level; level = levelDefinition[i]; i++) { var div = document.createElement('DIV'); div.innerHTML = 'Level ' + level; div.setAttribute('id', 'level-' + level); div.className = 'level'; levels.appendChild(div); this.levelDivs_.push(div); google.maps.event.addDomListener(div, 'click', function(e) { var id = e.currentTarget.getAttribute('id'); var level = parseInt(id.replace('level-', ''), 10); that.iomap_.setHash('level' + level); }); } controlDiv.index = 1; return controlDiv; }; /** * Changes the highlighted level in the control. * @param {number} level the level number to select. */ LevelControl.prototype.changeLevel_ = function(level) { if (this.currentLevelDiv_) { this.currentLevelDiv_.className = this.currentLevelDiv_.className.replace(' level-selected', ''); } var h = 25; if (window['ioEmbed']) { h = (window.screen.availWidth > 600) ? 34 : 24; } this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px'; var div = this.levelDivs_[level - 1]; div.className += ' level-selected'; this.currentLevelDiv_ = div; };
JavaScript
// Copyright 2011 Google /** * 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. */ /** * The Google IO Map * @constructor */ var IoMap = function() { var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025); /** @type {Node} */ this.mapDiv_ = document.getElementById(this.MAP_ID); var ioStyle = [ { 'featureType': 'road', stylers: [ { hue: '#00aaff' }, { gamma: 1.67 }, { saturation: -24 }, { lightness: -38 } ] },{ 'featureType': 'road', 'elementType': 'labels', stylers: [ { invert_lightness: true } ] }]; /** @type {boolean} */ this.ready_ = false; /** @type {google.maps.Map} */ this.map_ = new google.maps.Map(this.mapDiv_, { zoom: 18, center: moscone, navigationControl: true, mapTypeControl: false, scaleControl: true, mapTypeId: 'io', streetViewControl: false }); var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle)); this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style)); google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['onMapReady'](); } }); /** @type {Array.<Floor>} */ this.floors_ = []; for (var i = 0; i < this.LEVELS_.length; i++) { this.floors_.push(new Floor(this.map_)); } this.addLevelControl_(); this.addMapOverlay_(); this.loadMapContent_(); this.initLocationHashWatcher_(); if (!document.location.hash) { this.showLevel(1, true); } } IoMap.prototype = new google.maps.MVCObject; /** * The id of the Element to add the map to. * * @type {string} * @const */ IoMap.prototype.MAP_ID = 'map-canvas'; /** * The levels of the Moscone Center. * * @type {Array.<string>} * @private */ IoMap.prototype.LEVELS_ = ['1', '2', '3']; /** * Location where the tiles are hosted. * * @type {string} * @private */ IoMap.prototype.BASE_TILE_URL_ = 'http://www.gstatic.com/io2010maps/tiles/5/'; /** * The minimum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MIN_ZOOM_ = 16; /** * The maximum zoom level to show the overlay. * * @type {number} * @private */ IoMap.prototype.MAX_ZOOM_ = 20; /** * The template for loading tiles. Replace {L} with the level, {Z} with the * zoom level, {X} and {Y} with respective tile coordinates. * * @type {string} * @private */ IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + 'L{L}_{Z}_{X}_{Y}.png'; /** * @type {string} * @private */ IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png'; /** * The extent of the overlay at certain zoom levels. * * @type {Object.<string, Array.<Array.<number>>>} * @private */ IoMap.prototype.RESOLUTION_BOUNDS_ = { 16: [[10484, 10485], [25328, 25329]], 17: [[20969, 20970], [50657, 50658]], 18: [[41939, 41940], [101315, 101317]], 19: [[83878, 83881], [202631, 202634]], 20: [[167757, 167763], [405263, 405269]] }; /** * The previous hash to compare against. * * @type {string?} * @private */ IoMap.prototype.prevHash_ = null; /** * Initialise the location hash watcher. * * @private */ IoMap.prototype.initLocationHashWatcher_ = function() { var that = this; if ('onhashchange' in window) { window.addEventListener('hashchange', function() { that.parseHash_(); }, true); } else { var that = this window.setInterval(function() { that.parseHash_(); }, 100); } this.parseHash_(); }; /** * Called from Android. * * @param {Number} x A percentage to pan left by. */ IoMap.prototype.panLeft = function(x) { var div = this.map_.getDiv(); var left = div.clientWidth * x; this.map_.panBy(left, 0); }; IoMap.prototype['panLeft'] = IoMap.prototype.panLeft; /** * Adds the level switcher to the top left of the map. * * @private */ IoMap.prototype.addLevelControl_ = function() { var control = new LevelControl(this, this.LEVELS_).getElement(); this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control); }; /** * Shows a floor based on the content of location.hash. * * @private */ IoMap.prototype.parseHash_ = function() { var hash = document.location.hash; if (hash == this.prevHash_) { return; } this.prevHash_ = hash; var level = 1; if (hash) { var match = hash.match(/level(\d)(?:\:([\w-]+))?/); if (match && match[1]) { level = parseInt(match[1], 10); } } this.showLevel(level, true); }; /** * Updates location.hash based on the currently shown floor. * * @param {string?} opt_hash */ IoMap.prototype.setHash = function(opt_hash) { var hash = document.location.hash.substring(1); if (hash == opt_hash) { return; } if (opt_hash) { document.location.hash = opt_hash; } else { document.location.hash = 'level' + this.get('level'); } }; IoMap.prototype['setHash'] = IoMap.prototype.setHash; /** * Called from spreadsheets. */ IoMap.prototype.loadSandboxCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.companyName = entry['gsx$companyname']['$t']; item.companyUrl = entry['gsx$companyurl']['$t']; var p = entry['gsx$companypod']['$t']; item.pod = p; p = p.toLowerCase().replace(/\s+/, ''); item.sessionRoom = p; contentItems.push(item); }; this.sandboxItems_ = contentItems; this.ready_ = true; this.addMapContent_(); }; /** * Called from spreadsheets. * * @param {Object} json The json feed from the spreadsheet. */ IoMap.prototype.loadSessionsCallback = function(json) { var updated = json['feed']['updated']['$t']; var contentItems = []; var ids = {}; var entries = json['feed']['entry']; for (var i = 0, entry; entry = entries[i]; i++) { var item = {}; item.sessionDate = entry['gsx$sessiondate']['$t']; item.sessionAbstract = entry['gsx$sessionabstract']['$t']; item.sessionHashtag = entry['gsx$sessionhashtag']['$t']; item.sessionLevel = entry['gsx$sessionlevel']['$t']; item.sessionTitle = entry['gsx$sessiontitle']['$t']; item.sessionTrack = entry['gsx$sessiontrack']['$t']; item.sessionUrl = entry['gsx$sessionurl']['$t']; item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t']; item.sessionTime = entry['gsx$sessiontime']['$t']; item.sessionRoom = entry['gsx$sessionroom']['$t']; item.sessionTags = entry['gsx$sessiontags']['$t']; item.sessionSpeakers = entry['gsx$sessionspeakers']['$t']; if (item.sessionDate.indexOf('10') != -1) { item.sessionDay = 10; } else { item.sessionDay = 11; } var timeParts = item.sessionTime.split('-'); item.sessionStart = this.convertTo24Hour_(timeParts[0]); item.sessionEnd = this.convertTo24Hour_(timeParts[1]); contentItems.push(item); } this.sessionItems_ = contentItems; }; /** * Converts the time in the spread sheet to 24 hour time. * * @param {string} time The time like 10:42am. */ IoMap.prototype.convertTo24Hour_ = function(time) { var pm = time.indexOf('pm') != -1; time = time.replace(/[am|pm]/ig, ''); if (pm) { var bits = time.split(':'); var hr = parseInt(bits[0], 10); if (hr < 12) { time = (hr + 12) + ':' + bits[1]; } } return time; }; /** * Loads the map content from Google Spreadsheets. * * @private */ IoMap.prototype.loadMapContent_ = function() { // Initiate a JSONP request. var that = this; // Add a exposed call back function window['loadSessionsCallback'] = function(json) { that.loadSessionsCallback(json); } // Add a exposed call back function window['loadSandboxCallback'] = function(json) { that.loadSandboxCallback(json); } var key = 'tmaLiaNqIWYYtuuhmIyG0uQ'; var worksheetIDs = { sessions: 'od6', sandbox: 'od4' }; var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sessions + '/public/values' + '?alt=json-in-script&callback=loadSessionsCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' + key + '/' + worksheetIDs.sandbox + '/public/values' + '?alt=json-in-script&callback=loadSandboxCallback'; var script = document.createElement('script'); script.setAttribute('src', jsonpUrl); script.setAttribute('type', 'text/javascript'); document.documentElement.firstChild.appendChild(script); }; /** * Called from Android. * * @param {string} roomId The id of the room to load. */ IoMap.prototype.showLocationById = function(roomId) { var locations = this.LOCATIONS_; for (var level in locations) { var levelId = level.replace('LEVEL', ''); for (var loc in locations[level]) { var room = locations[level][loc]; if (loc == roomId) { var pos = new google.maps.LatLng(room.lat, room.lng); this.map_.panTo(pos); this.map_.setZoom(19); this.showLevel(levelId); if (room.marker_) { room.marker_.setAnimation(google.maps.Animation.BOUNCE); // Disable the animation after 5 seconds. window.setTimeout(function() { room.marker_.setAnimation(); }, 5000); } return; } } } }; IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById; /** * Called when the level is changed. Hides and shows floors. */ IoMap.prototype['level_changed'] = function() { var level = this.get('level'); if (this.infoWindow_) { this.infoWindow_.setMap(null); } for (var i = 1, floor; floor = this.floors_[i - 1]; i++) { if (i == level) { floor.show(); } else { floor.hide(); } } this.setHash('level' + level); }; /** * Shows a particular floor. * * @param {string} level The level to show. * @param {boolean=} opt_force if true, changes the floor even if it's already * the current floor. */ IoMap.prototype.showLevel = function(level, opt_force) { if (!opt_force && level == this.get('level')) { return; } this.set('level', level); }; IoMap.prototype['showLevel'] = IoMap.prototype.showLevel; /** * Create a marker with the content item's correct icon. * * @param {Object} item The content item for the marker. * @return {google.maps.Marker} The new marker. * @private */ IoMap.prototype.createContentMarker_ = function(item) { if (!item.icon) { item.icon = 'generic'; } var image; var shadow; switch(item.icon) { case 'generic': case 'info': case 'media': var image = new google.maps.MarkerImage( 'marker-' + item.icon + '.png', new google.maps.Size(30, 28), new google.maps.Point(0, 0), new google.maps.Point(13, 26)); var shadow = new google.maps.MarkerImage( 'marker-shadow.png', new google.maps.Size(30, 28), new google.maps.Point(0,0), new google.maps.Point(13, 26)); break; case 'toilets': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(35, 35), new google.maps.Point(0, 0), new google.maps.Point(17, 17)); break; case 'elevator': var image = new google.maps.MarkerImage( item.icon + '.png', new google.maps.Size(48, 26), new google.maps.Point(0, 0), new google.maps.Point(24, 13)); break; } var inactive = item.type == 'inactive'; var latLng = new google.maps.LatLng(item.lat, item.lng); var marker = new SmartMarker({ position: latLng, shadow: shadow, icon: image, title: item.title, minZoom: inactive ? 19 : 18, clickable: !inactive }); marker['type_'] = item.type; if (!inactive) { var that = this; google.maps.event.addListener(marker, 'click', function() { that.openContentInfo_(item); }); } return marker; }; /** * Create a label with the content item's title atribute, if it exists. * * @param {Object} item The content item for the marker. * @return {MapLabel?} The new label. * @private */ IoMap.prototype.createContentLabel_ = function(item) { if (!item.title || item.suppressLabel) { return null; } var latLng = new google.maps.LatLng(item.lat, item.lng); return new MapLabel({ 'text': item.title, 'position': latLng, 'minZoom': item.labelMinZoom || 18, 'align': item.labelAlign || 'center', 'fontColor': item.labelColor, 'fontSize': item.labelSize || 12 }); } /** * Open a info window a content item. * * @param {Object} item A content item with content and a marker. */ IoMap.prototype.openContentInfo_ = function(item) { if (window['MAP_CONTAINER'] !== undefined) { window['MAP_CONTAINER']['openContentInfo'](item.room); return; } var sessionBase = 'http://www.google.com/events/io/2011/sessions.html'; var now = new Date(); var may11 = new Date('May 11, 2011'); var day = now < may11 ? 10 : 11; var type = item.type; var id = item.id; var title = item.title; var content = ['<div class="infowindow">']; var sessions = []; var empty = true; if (item.type == 'session') { if (day == 10) { content.push('<h3>' + title + ' - Tuesday May 10</h3>'); } else { content.push('<h3>' + title + ' - Wednesday May 11</h3>'); } for (var i = 0, session; session = this.sessionItems_[i]; i++) { if (session.sessionRoom == item.room && session.sessionDay == day) { sessions.push(session); empty = false; } } sessions.sort(this.sortSessions_); for (var i = 0, session; session = sessions[i]; i++) { content.push('<div class="session"><div class="session-time">' + session.sessionTime + '</div><div class="session-title"><a href="' + session.sessionUrl + '">' + session.sessionTitle + '</a></div></div>'); } } if (item.type == 'sandbox') { var sandboxName; for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) { if (sandbox.sessionRoom == item.room) { if (!sandboxName) { sandboxName = sandbox.pod; content.push('<h3>' + sandbox.pod + '</h3>'); content.push('<div class="sandbox">'); } content.push('<div class="sandbox-items"><a href="http://' + sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>'); empty = false; } } content.push('</div>'); empty = false; } if (empty) { return; } content.push('</div>'); var pos = new google.maps.LatLng(item.lat, item.lng); if (!this.infoWindow_) { this.infoWindow_ = new google.maps.InfoWindow(); } this.infoWindow_.setContent(content.join('')); this.infoWindow_.setPosition(pos); this.infoWindow_.open(this.map_); }; /** * A custom sort function to sort the sessions by start time. * * @param {string} a SessionA<enter description here>. * @param {string} b SessionB. * @return {boolean} True if sessionA is after sessionB. */ IoMap.prototype.sortSessions_ = function(a, b) { var aStart = parseInt(a.sessionStart.replace(':', ''), 10); var bStart = parseInt(b.sessionStart.replace(':', ''), 10); return aStart > bStart; }; /** * Adds all overlays (markers, labels) to the map. */ IoMap.prototype.addMapContent_ = function() { if (!this.ready_) { return; } for (var i = 0, level; level = this.LEVELS_[i]; i++) { var floor = this.floors_[i]; var locations = this.LOCATIONS_['LEVEL' + level]; for (var roomId in locations) { var room = locations[roomId]; if (room.room == undefined) { room.room = roomId; } if (room.type != 'label') { var marker = this.createContentMarker_(room); floor.addOverlay(marker); room.marker_ = marker; } var label = this.createContentLabel_(room); floor.addOverlay(label); } } }; /** * Gets the correct tile url for the coordinates and zoom. * * @param {google.maps.Point} coord The coordinate of the tile. * @param {Number} zoom The current zoom level. * @return {string} The url to the tile. */ IoMap.prototype.getTileUrl = function(coord, zoom) { // Ensure that the requested resolution exists for this tile layer. if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) { return ''; } // Ensure that the requested tile x,y exists. if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x || coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) || (this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y || coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) { return ''; } var template = this.TILE_TEMPLATE_URL_; if (16 <= zoom && zoom <= 17) { template = this.SIMPLE_TILE_TEMPLATE_URL_; } return template .replace('{L}', /** @type string */(this.get('level'))) .replace('{Z}', /** @type string */(zoom)) .replace('{X}', /** @type string */(coord.x)) .replace('{Y}', /** @type string */(coord.y)); }; /** * Add the floor overlay to the map. * * @private */ IoMap.prototype.addMapOverlay_ = function() { var that = this; var overlay = new google.maps.ImageMapType({ getTileUrl: function(coord, zoom) { return that.getTileUrl(coord, zoom); }, tileSize: new google.maps.Size(256, 256) }); google.maps.event.addListener(this, 'level_changed', function() { var overlays = that.map_.overlayMapTypes; if (overlays.length) { overlays.removeAt(0); } overlays.push(overlay); }); }; /** * All the features of the map. * @type {Object.<string, Object.<string, Object.<string, *>>>} */ IoMap.prototype.LOCATIONS_ = { 'LEVEL1': { 'northentrance': { lat: 37.78381535905965, lng: -122.40362226963043, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'eastentrance': { lat: 37.78328434094279, lng: -122.40319311618805, title: 'Entrance', type: 'label', labelColor: '#006600', labelAlign: 'left', labelSize: 10 }, 'lunchroom': { lat: 37.783112633669575, lng: -122.40407556295395, title: 'Lunch Room' }, 'restroom1a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator1a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'gearpickup': { lat: 37.78367863020862, lng: -122.4037617444992, title: 'Gear Pickup', type: 'label' }, 'checkin': { lat: 37.78334369645064, lng: -122.40335404872894, title: 'Check In', type: 'label' }, 'escalators1': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' } }, 'LEVEL2': { 'escalators2': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left', labelMinZoom: 19 }, 'press': { lat: 37.78316774962791, lng: -122.40360751748085, title: 'Press Room', type: 'label' }, 'restroom2a': { lat: 37.7835334217721, lng: -122.40386635065079, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom2b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator2a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, '1': { lat: 37.78346240732338, lng: -122.40415401756763, icon: 'media', title: 'Room 1', type: 'session', room: '1' }, '2': { lat: 37.78335005596647, lng: -122.40431495010853, icon: 'media', title: 'Room 2', type: 'session', room: '2' }, '3': { lat: 37.783215446097124, lng: -122.404490634799, icon: 'media', title: 'Room 3', type: 'session', room: '3' }, '4': { lat: 37.78332461789977, lng: -122.40381203591824, icon: 'media', title: 'Room 4', type: 'session', room: '4' }, '5': { lat: 37.783186828219335, lng: -122.4039850383997, icon: 'media', title: 'Room 5', type: 'session', room: '5' }, '6': { lat: 37.783013000871364, lng: -122.40420497953892, icon: 'media', title: 'Room 6', type: 'session', room: '6' }, '7': { lat: 37.7828783903882, lng: -122.40438133478165, icon: 'media', title: 'Room 7', type: 'session', room: '7' }, '8': { lat: 37.78305009820564, lng: -122.40378588438034, icon: 'media', title: 'Room 8', type: 'session', room: '8' }, '9': { lat: 37.78286673120095, lng: -122.40402393043041, icon: 'media', title: 'Room 9', type: 'session', room: '9' }, '10': { lat: 37.782719401312626, lng: -122.40420028567314, icon: 'media', title: 'Room 10', type: 'session', room: '10' }, 'appengine': { lat: 37.783362774996625, lng: -122.40335941314697, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'App Engine' }, 'chrome': { lat: 37.783730566003555, lng: -122.40378990769386, type: 'sandbox', icon: 'generic', title: 'Chrome' }, 'googleapps': { lat: 37.783303419504094, lng: -122.40320384502411, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Apps' }, 'geo': { lat: 37.783365954753805, lng: -122.40314483642578, type: 'sandbox', icon: 'generic', labelMinZoom: 19, title: 'Geo' }, 'accessibility': { lat: 37.783414711013485, lng: -122.40342646837234, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Accessibility' }, 'developertools': { lat: 37.783457107734876, lng: -122.40347877144814, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Dev Tools' }, 'commerce': { lat: 37.78349102509448, lng: -122.40351900458336, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'Commerce' }, 'youtube': { lat: 37.783537661438515, lng: -122.40358605980873, type: 'sandbox', icon: 'generic', labelMinZoom: 19, labelAlign: 'right', title: 'YouTube' }, 'officehoursfloor2a': { lat: 37.78249045644304, lng: -122.40410104393959, title: 'Office Hours', type: 'label' }, 'officehoursfloor2': { lat: 37.78266852473624, lng: -122.40387573838234, title: 'Office Hours', type: 'label' }, 'officehoursfloor2b': { lat: 37.782844472747406, lng: -122.40365579724312, title: 'Office Hours', type: 'label' } }, 'LEVEL3': { 'escalators3': { lat: 37.78353872135503, lng: -122.40336209535599, title: 'Escalators', type: 'label', labelAlign: 'left' }, 'restroom3a': { lat: 37.78372420652042, lng: -122.40396961569786, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'restroom3b': { lat: 37.78250317562106, lng: -122.40423113107681, icon: 'toilets', type: 'inactive', title: 'Restroom', suppressLabel: true }, 'elevator3a': { lat: 37.783669090977035, lng: -122.40389987826347, icon: 'elevator', type: 'inactive', title: 'Elevators', suppressLabel: true }, 'keynote': { lat: 37.783250423488326, lng: -122.40417748689651, icon: 'media', title: 'Keynote', type: 'label' }, '11': { lat: 37.78283069370135, lng: -122.40408763289452, icon: 'media', title: 'Room 11', type: 'session', room: '11' }, 'googletv': { lat: 37.7837125474666, lng: -122.40362092852592, type: 'sandbox', icon: 'generic', title: 'Google TV' }, 'android': { lat: 37.783530242022124, lng: -122.40358874201775, type: 'sandbox', icon: 'generic', title: 'Android' }, 'officehoursfloor3': { lat: 37.782843412820846, lng: -122.40365579724312, title: 'Office Hours', type: 'label' }, 'officehoursfloor3a': { lat: 37.78267170452323, lng: -122.40387842059135, title: 'Office Hours', type: 'label' } } }; google.maps.event.addDomListener(window, 'load', function() { window['IoMap'] = new IoMap(); });
JavaScript
/** * Creates a new Floor. * @constructor * @param {google.maps.Map=} opt_map */ function Floor(opt_map) { /** * @type Array.<google.maps.MVCObject> */ this.overlays_ = []; /** * @type boolean */ this.shown_ = true; if (opt_map) { this.setMap(opt_map); } } /** * @param {google.maps.Map} map */ Floor.prototype.setMap = function(map) { this.map_ = map; }; /** * @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel. * Requires a setMap method. */ Floor.prototype.addOverlay = function(overlay) { if (!overlay) return; this.overlays_.push(overlay); overlay.setMap(this.shown_ ? this.map_ : null); }; /** * Sets the map on all the overlays * @param {google.maps.Map} map The map to set. */ Floor.prototype.setMapAll_ = function(map) { this.shown_ = !!map; for (var i = 0, overlay; overlay = this.overlays_[i]; i++) { overlay.setMap(map); } }; /** * Hides the floor and all associated overlays. */ Floor.prototype.hide = function() { this.setMapAll_(null); }; /** * Shows the floor and all associated overlays. */ Floor.prototype.show = function() { this.setMapAll_(this.map_); };
JavaScript
/** * @license * * Copyright 2011 Google Inc. * * 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. */ /** * @fileoverview SmartMarker. * * @author Chris Broadfoot (cbro@google.com) */ /** * A google.maps.Marker that has some smarts about the zoom levels it should be * shown. * * Options are the same as google.maps.Marker, with the addition of minZoom and * maxZoom. These zoom levels are inclusive. That is, a SmartMarker with * a minZoom and maxZoom of 13 will only be shown at zoom level 13. * @constructor * @extends google.maps.Marker * @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom. */ function SmartMarker(opts) { var marker = new google.maps.Marker; // default min/max Zoom - shows the marker all the time. marker.setValues({ 'minZoom': 0, 'maxZoom': Infinity }); // the current listener (if any), triggered on map zoom_changed var mapZoomListener; google.maps.event.addListener(marker, 'map_changed', function() { if (mapZoomListener) { google.maps.event.removeListener(mapZoomListener); } var map = marker.getMap(); if (map) { var listener = SmartMarker.newZoomListener_(marker); mapZoomListener = google.maps.event.addListener(map, 'zoom_changed', listener); // Call the listener straight away. The map may already be initialized, // so it will take user input for zoom_changed to be fired. listener(); } }); marker.setValues(opts); return marker; } window['SmartMarker'] = SmartMarker; /** * Creates a new listener to be triggered on 'zoom_changed' event. * Hides and shows the target Marker based on the map's zoom level. * @param {google.maps.Marker} marker The target marker. * @return Function */ SmartMarker.newZoomListener_ = function(marker) { var map = marker.getMap(); return function() { var zoom = map.getZoom(); var minZoom = Number(marker.get('minZoom')); var maxZoom = Number(marker.get('maxZoom')); marker.setVisible(zoom >= minZoom && zoom <= maxZoom); }; };
JavaScript