Example #1
0
cordova.define("com.byhook.cordova.chromelauncher.ChromeLauncher", function(require, exports, module) { /*
 * 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'),
    cordova = require('cordova'),
    channel = require('cordova/channel'),
    utils = require('cordova/utils');

channel.createSticky('onCordovaInfoReady');
// Tell cordova channel to wait on the CordovaInfoReady event
channel.waitForInitialization('onCordovaInfoReady');


function ChromeLauncher() {
	
	var self = this;
	this.isInstalled = false;
	
    channel.onCordovaReady.subscribe(function() {
		self.checkInstall(function(result) {
			self.isInstalled = true;
            channel.onCordovaInfoReady.fire();
		}, function() {
			self.isInstalled = false;
            channel.onCordovaInfoReady.fire();
		});
	});
}

ChromeLauncher.prototype.open = function(url, successCallback, errorCallback) {
	exec(successCallback, errorCallback, "ChromeLauncher", "open", [url]);
};

ChromeLauncher.prototype.checkInstall = function(successCallback, errorCallback) {
	exec(successCallback, errorCallback, "ChromeLauncher", "checkInstall", []);
};

ChromeLauncher.prototype.openStore = function(successCallback, errorCallback) {
	exec(successCallback, errorCallback, "ChromeLauncher", "openStore", []);
};

module.exports = new ChromeLauncher();
});
cordova.define("tw.com.mobilogics.sdk.barcode.plugins.phonegap.MobilogicsScanner", function(require, exports, module) {
/*
 * Licensed to Creative Commons Attribution-ShareAlike 4.0
 * International. Please see the LICENSE.pdf.
 * You may obtain a copy of the License at
 *
 * http://creativecommons.org/licenses/by-sa/4.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');

/**
 * Constructor
 **/
function MobilogicsScanner () {
  this.available = false;
  var me = this;

  channel.onCordovaReady.subscribe(function() {
    me.start(function(info) {
               me.available = true;
               channel.onCordovaInfoReady.fire();
             },function(e) {
               me.available = false;
               utils.alert("[ERROR] Error initializing Cordova: " + e);
             });
  });
}

MobilogicsScanner.prototype.start = function(successCallback, errorCallback) {
               //  argscheck.checkArgs('fF', 'MobilogicsScanner.start', arguments);
  exec(successCallback, errorCallback, "MobilogicsScanner", "start", []);
};

MobilogicsScanner.prototype.scan = function(successCallback, errorCallback) {
  exec(successCallback, errorCallback, "MobilogicsScanner", "scan", []);
};

MobilogicsScanner.prototype.monitor = function(successCallback, errorCallback) {
  exec(successCallback, errorCallback, "MobilogicsScanner", "monitorConnection", []);
};

module.exports = new MobilogicsScanner();
});
Example #3
0
cordova.define("org.apache.cordova.cardflight.cardFlight", function(require, exports, module) {var argscheck = require('cordova/argscheck'),
  channel = require('cordova/channel'),
  utils = require('cordova/utils'),
  exec = require('cordova/exec'),
  cordova = require('cordova');

channel.createSticky('onCordovaCardFlightReady');
// Tell cordova channel to wait on the CordovaInfoReady event
channel.waitForInitialization('onCordovaCardFlightReady');

function CardFlight() {
    this.available = false;
    this.platform = null;
    this.cordova = null;
    this.config = null;

    var _this = this;

    channel.onCordovaReady.subscribe(function() {
      // ADD INITIALIZATION HERE
    });
}

CardFlight.prototype.configure = function(options) {
  var successCallback = function() {
    console.log("SUCCESSFULLY SET TOKENS");
  };
  var errorCallback = function() {
    console.log("ERROR SETTING TOKENS");
}
  this.setApiTokens(successCallback, errorCallback, options);
}


CardFlight.prototype.setApiTokens = function(successCallback, errorCallback, options) {
    exec(successCallback, errorCallback, "CDVCardFlight", "setApiTokens", [options.apiToken, options.accountToken]);
};

CardFlight.prototype.beginSwipe = function(successCallback, errorCallback) {
    exec(successCallback, errorCallback, "CDVCardFlight", "swipeCard", []);
};
               
module.exports = new CardFlight();
});
Example #4
0
cordova.define('cordova-plugin-file.fileSystemPaths', function(require, exports, module) {
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 applications (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', []);
});
});
define("cordova/plugin/firefoxos/device", function(require, exports, module) {

var channel = require('cordova/channel'),
    cordova = require('cordova');

// Tell cordova channel to wait on the CordovaInfoReady event
channel.waitForInitialization('onCordovaInfoReady');

module.exports = {
    getDeviceInfo : function(win, fail, args){
        win({
            platform: "Firefox OS",
            version: "0.0.1",
            model: "Beta Phone",
            name: "Beta Phone", // deprecated: please use device.model
            uuid: "somestring",
            cordova: CORDOVA_JS_BUILD_LABEL
        });
    }
};

});
Example #6
0
cordova.define("cordova-plugin-background-app.backgroundapp", function(require, exports, module) {
// Copyright (c) 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var exec = require('cordova/exec');
var cordova = require('cordova');
var channel = require('cordova/channel');

// Refer to README for possible values.
exports.resumeType = '';

exports.show = cordova.platformId == 'android' ? function() {
    exec(null, null, 'BackgroundPlugin', 'show', []);
} : null;

channel.createSticky('onBackgroundAppReady');
channel.waitForInitialization('onBackgroundAppReady');
channel.onCordovaReady.subscribe(function() {
  exec(function(msg) {
    if (msg.type == 'startup') {
      if (!msg.value) {
        exports.resumeType = 'launch';
      }
      channel.initializationComplete('onBackgroundAppReady');
    } else {
      var firstResume = !exports.resumeType;
      exports.resumeType = msg.value; // 'normal' or 'programmatic'.
      if (firstResume) {
          exports.resumeType += '-launch';
      }
    }
  }, undefined, 'BackgroundPlugin', 'messageChannel', []);
});


});
/**
 * Get connection info
 *
 * @param {Function} successCallback The function to call when the Connection data is available
 * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
 */
NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) {
    exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []);
};

var me = new NetworkConnection();
var timerId = null;
var timeout = 500;

channel.createSticky('onCordovaConnectionReady');
channel.waitForInitialization('onCordovaConnectionReady');

channel.onCordovaReady.subscribe(function() {
    me.getInfo(function(info) {
        me.type = info;
        if (info === "none") {
            // set a timer if still offline at the end of timer send the offline event
            timerId = setTimeout(function(){
                cordova.fireDocumentEvent("offline");
                timerId = null;
            }, timeout);
        } else {
            // If there is a current offline event pending clear it
            if (timerId !== null) {
                clearTimeout(timerId);
                timerId = null;
Example #8
0
cordova.define("org.apache.cordova.networkinformation.network", function(require, exports, module) {
	
var exec = require('cordova/exec'),
    cordova = require('cordova'),
    channel = require('cordova/channel'),
    utils = require('cordova/utils');

// Link the onLine property with the Cordova-supplied network info.
// This works because we clobber the naviagtor object with our own
// object in bootstrap.js.
if (typeof navigator != 'undefined') {
    utils.defineGetter(navigator, 'onLine', function() {
        return this.connection.type != 'none';
    });
}

function NetworkConnection() {
    this.type = 'unknown';
}

/**
 * Get connection info
 *
 * @param {Function} successCallback The function to call when the Connection data is available
 * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
 */
NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) {
    exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []);
};

var me = new NetworkConnection();
var timerId = null;
var timeout = 500;

channel.createSticky('onCordovaConnectionReady');
channel.waitForInitialization('onCordovaConnectionReady');

channel.onCordovaReady.subscribe(function() {
    me.getInfo(function(info) {
        me.type = info;
        if (info === "none") {
            // set a timer if still offline at the end of timer send the offline event
            timerId = setTimeout(function(){
                cordova.fireDocumentEvent("offline");
                timerId = null;
            }, timeout);
        } else {
            // If there is a current offline event pending clear it
            if (timerId !== null) {
                clearTimeout(timerId);
                timerId = null;
            }
            cordova.fireDocumentEvent("online");
        }

        // should only fire this once
        if (channel.onCordovaConnectionReady.state !== 2) {
            channel.onCordovaConnectionReady.fire();
        }
    },
    function (e) {
        // If we can't get the network info we should still tell Cordova
        // to fire the deviceready event.
        if (channel.onCordovaConnectionReady.state !== 2) {
            channel.onCordovaConnectionReady.fire();
        }
        console.log("Error initializing Network Connection: " + e);
    });
});

module.exports = me;
});
Example #9
0
define("cordova/channel", function(require, exports, module) {

var utils = require('cordova/utils'),
    nextGuid = 1;

/**
 * Custom pub-sub "channel" that can have functions subscribed to it
 * This object is used to define and control firing of events for
 * cordova initialization, as well as for custom events thereafter.
 *
 * The order of events during page load and Cordova startup is as follows:
 *
 * onDOMContentLoaded*         Internal event that is received when the web page is loaded and parsed.
 * onNativeReady*              Internal event that indicates the Cordova native side is ready.
 * onCordovaReady*             Internal event fired when all Cordova JavaScript objects have been created.
 * onDeviceReady*              User event fired to indicate that Cordova is ready
 * onResume                    User event fired to indicate a start/resume lifecycle event
 * onPause                     User event fired to indicate a pause lifecycle event
 * onDestroy*                  Internal event fired when app is being destroyed (User should use window.onunload event, not this one).
 *
 * The events marked with an * are sticky. Once they have fired, they will stay in the fired state.
 * All listeners that subscribe after the event is fired will be executed right away.
 *
 * The only Cordova events that user code should register for are:
 *      deviceready           Cordova native code is initialized and Cordova APIs can be called from JavaScript
 *      pause                 App has moved to background
 *      resume                App has returned to foreground
 *
 * Listeners can be registered as:
 *      document.addEventListener("deviceready", myDeviceReadyListener, false);
 *      document.addEventListener("resume", myResumeListener, false);
 *      document.addEventListener("pause", myPauseListener, false);
 *
 * The DOM lifecycle events should be used for saving and restoring state
 *      window.onload
 *      window.onunload
 *
 */

/**
 * Channel
 * @constructor
 * @param type  String the channel name
 */
var Channel = function(type, sticky) {
    this.type = type;
    // Map of guid -> function.
    this.handlers = {};
    // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired.
    this.state = sticky ? 1 : 0;
    // Used in sticky mode to remember args passed to fire().
    this.fireArgs = null;
    // Used by onHasSubscribersChange to know if there are any listeners.
    this.numHandlers = 0;
    // Function that is called when the first listener is subscribed, or when
    // the last listener is unsubscribed.
    this.onHasSubscribersChange = null;
},
    channel = {
        /**
         * Calls the provided function only after all of the channels specified
         * have been fired. All channels must be sticky channels.
         */
        join: function(h, c) {
            var len = c.length,
                i = len,
                f = function() {
                    if (!(--i)) h();
                };
            for (var j=0; j<len; j++) {
                if (c[j].state === 0) {
                    throw Error('Can only use join with sticky channels.');
                }
                c[j].subscribe(f);
            }
            if (!len) h();
        },
        create: function(type) {
            return channel[type] = new Channel(type, false);
        },
        createSticky: function(type) {
            return channel[type] = new Channel(type, true);
        },

        /**
         * cordova Channels that must fire before "deviceready" is fired.
         */
        deviceReadyChannelsArray: [],
        deviceReadyChannelsMap: {},

        /**
         * Indicate that a feature needs to be initialized before it is ready to be used.
         * This holds up Cordova's "deviceready" event until the feature has been initialized
         * and Cordova.initComplete(feature) is called.
         *
         * @param feature {String}     The unique feature name
         */
        waitForInitialization: function(feature) {
            if (feature) {
                var c = channel[feature] || this.createSticky(feature);
                this.deviceReadyChannelsMap[feature] = c;
                this.deviceReadyChannelsArray.push(c);
            }
        },

        /**
         * Indicate that initialization code has completed and the feature is ready to be used.
         *
         * @param feature {String}     The unique feature name
         */
        initializationComplete: function(feature) {
            var c = this.deviceReadyChannelsMap[feature];
            if (c) {
                c.fire();
            }
        }
    };

function forceFunction(f) {
    if (typeof f != 'function') throw "Function required as first argument!";
}

/**
 * Subscribes the given function to the channel. Any time that
 * Channel.fire is called so too will the function.
 * Optionally specify an execution context for the function
 * and a guid that can be used to stop subscribing to the channel.
 * Returns the guid.
 */
Channel.prototype.subscribe = function(f, c) {
    // need a function to call
    forceFunction(f);
    if (this.state == 2) {
        f.apply(c || this, this.fireArgs);
        return;
    }

    var func = f,
        guid = f.observer_guid;
    if (typeof c == "object") { func = utils.close(c, f); }

    if (!guid) {
        // first time any channel has seen this subscriber
        guid = '' + nextGuid++;
    }
    func.observer_guid = guid;
    f.observer_guid = guid;

    // Don't add the same handler more than once.
    if (!this.handlers[guid]) {
        this.handlers[guid] = func;
        this.numHandlers++;
        if (this.numHandlers == 1) {
            this.onHasSubscribersChange && this.onHasSubscribersChange();
        }
    }
};

/**
 * Unsubscribes the function with the given guid from the channel.
 */
Channel.prototype.unsubscribe = function(f) {
    // need a function to unsubscribe
    forceFunction(f);

    var guid = f.observer_guid,
        handler = this.handlers[guid];
    if (handler) {
        delete this.handlers[guid];
        this.numHandlers--;
        if (this.numHandlers === 0) {
            this.onHasSubscribersChange && this.onHasSubscribersChange();
        }
    }
};

/**
 * Calls all functions subscribed to this channel.
 */
Channel.prototype.fire = function(e) {
    var fail = false,
        fireArgs = Array.prototype.slice.call(arguments);
    // Apply stickiness.
    if (this.state == 1) {
        this.state = 2;
        this.fireArgs = fireArgs;
    }
    if (this.numHandlers) {
        // Copy the values first so that it is safe to modify it from within
        // callbacks.
        var toCall = [];
        for (var item in this.handlers) {
            toCall.push(this.handlers[item]);
        }
        for (var i = 0; i < toCall.length; ++i) {
            toCall[i].apply(this, fireArgs);
        }
        if (this.state == 2 && this.numHandlers) {
            this.numHandlers = 0;
            this.handlers = {};
            this.onHasSubscribersChange && this.onHasSubscribersChange();
        }
    }
};


// defining them here so they are ready super fast!
// DOM event that is received when the web page is loaded and parsed.
channel.createSticky('onDOMContentLoaded');

// Event to indicate the Cordova native side is ready.
channel.createSticky('onNativeReady');

// Event to indicate that all Cordova JavaScript objects have been created
// and it's time to run plugin constructors.
channel.createSticky('onCordovaReady');

// Event to indicate that all automatically loaded JS plugins are loaded and ready.
channel.createSticky('onPluginsReady');

// Event to indicate that Cordova is ready
channel.createSticky('onDeviceReady');

// Event to indicate a resume lifecycle event
channel.create('onResume');

// Event to indicate a pause lifecycle event
channel.create('onPause');

// Event to indicate a destroy lifecycle event
channel.createSticky('onDestroy');

// Channels that must fire before "deviceready" is fired.
channel.waitForInitialization('onCordovaReady');
channel.waitForInitialization('onDOMContentLoaded');

module.exports = channel;

});
Example #10
0
        }
    }
    else {
         console.error && console.error("Received Media.onStatus callback for unknown media :: " + id);
    }

};

module.exports = Media;

function onMessageFromNative(msg) {
    if (msg.action == 'status') {
        Media.onStatus(msg.status.id, msg.status.msgType, msg.status.value);
    } else {
        throw new Error('Unknown media action' + msg.action);
    }
}

if (cordova.platformId === 'android' || cordova.platformId === 'amazon-fireos' || cordova.platformId === 'windowsphone') {

    var channel = require('cordova/channel');

    channel.createSticky('onMediaPluginReady');
    channel.waitForInitialization('onMediaPluginReady');

    channel.onCordovaReady.subscribe(function() {
        exec(onMessageFromNative, undefined, 'Media', 'messageChannel', []);
        channel.initializationComplete('onMediaPluginReady');
    });
}
Example #11
0
cordova.define("cordova-plugin-device.device", function(require, exports, module) {
/*
 *
 * 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;
               this.manufacturer = null;
               this.isVirtual = null;
               this.serial = null;
               this.name = 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;
                                                           me.isVirtual = info.isVirtual;
                                                           me.manufacturer = info.manufacturer || 'unknown';
                                                           me.serial = info.serial || 'unknown';
                                                           me.name = info.name || 'unknown';
                                                           me.width = info.width || 0;
                                                           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();
               
               });
Example #12
0
cordova.define("org.apache.cordova.media.Media", function(require, exports, module) { /*
 *
 * 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;

function onMessageFromNative(msg) {
    if (msg.action == 'status') {
        Media.onStatus(msg.status.id, msg.status.msgType, msg.status.value);
    } else {
        throw new Error('Unknown media action' + msg.action);
    }
}

if (cordova.platformId === 'android' || cordova.platformId === 'amazon-fireos') {

    var channel = require('cordova/channel');

    channel.createSticky('onMediaPluginReady');
    channel.waitForInitialization('onMediaPluginReady');

    channel.onCordovaReady.subscribe(function() {
        exec(onMessageFromNative, undefined, 'Media', 'messageChannel', []);
        channel.initializationComplete('onMediaPluginReady');
    });
}

});
var exec=require("cordova/exec"),channel=require("cordova/channel");exports.file={applicationDirectory:null,applicationStorageDirectory:null,dataDirectory:null,cacheDirectory:null,externalApplicationStorageDirectory:null,externalDataDirectory:null,externalCacheDirectory:null,externalRootDirectory:null,tempDirectory:null,syncedDataDirectory:null,documentsDirectory:null,sharedDirectory:null},channel.waitForInitialization("onFileSystemPathsReady"),channel.onCordovaReady.subscribe(function(){function e(e){for(var l in e)exports.file[l]=e[l];channel.initializationComplete("onFileSystemPathsReady")}exec(e,null,"File","requestAllPaths",[])});
Example #14
0
(function(){var CORDOVA_JS_BUILD_LABEL="3.1.0";var require,define;(function(){var modules={},requireStack=[],inProgressModules={},SEPERATOR=".";function build(module){var factory=module.factory,localRequire=function(id){var resultantId=id;if(id.charAt(0)==="."){resultantId=module.id.slice(0,module.id.lastIndexOf(SEPERATOR))+SEPERATOR+id.slice(2)}return require(resultantId)};module.exports={};delete module.factory;factory(localRequire,module.exports,module);return module.exports}require=function(id){if(!modules[id]){throw"module "+id+" not found"}else{if(id in inProgressModules){var cycle=requireStack.slice(inProgressModules[id]).join("->")+"->"+id;throw"Cycle in require graph: "+cycle}}if(modules[id].factory){try{inProgressModules[id]=requireStack.length;requireStack.push(id);return build(modules[id])}finally{delete inProgressModules[id];requireStack.pop()}}return modules[id].exports};define=function(id,factory){if(modules[id]){throw"module "+id+" already defined"}modules[id]={id:id,factory:factory}};define.remove=function(id){delete modules[id]};define.moduleMap=modules})();if(typeof module==="object"&&typeof require==="function"){module.exports.require=require;module.exports.define=define}define("cordova",function(require,exports,module){var channel=require("cordova/channel");var platform=require("cordova/platform");var m_document_addEventListener=document.addEventListener;var m_document_removeEventListener=document.removeEventListener;var m_window_addEventListener=window.addEventListener;var m_window_removeEventListener=window.removeEventListener;var documentEventHandlers={},windowEventHandlers={};document.addEventListener=function(evt,handler,capture){var e=evt.toLowerCase();if(typeof documentEventHandlers[e]!="undefined"){documentEventHandlers[e].subscribe(handler)}else{m_document_addEventListener.call(document,evt,handler,capture)}};window.addEventListener=function(evt,handler,capture){var e=evt.toLowerCase();if(typeof windowEventHandlers[e]!="undefined"){windowEventHandlers[e].subscribe(handler)}else{m_window_addEventListener.call(window,evt,handler,capture)}};document.removeEventListener=function(evt,handler,capture){var e=evt.toLowerCase();if(typeof documentEventHandlers[e]!="undefined"){documentEventHandlers[e].unsubscribe(handler)}else{m_document_removeEventListener.call(document,evt,handler,capture)}};window.removeEventListener=function(evt,handler,capture){var e=evt.toLowerCase();if(typeof windowEventHandlers[e]!="undefined"){windowEventHandlers[e].unsubscribe(handler)}else{m_window_removeEventListener.call(window,evt,handler,capture)}};function createEvent(type,data){var event=document.createEvent("Events");event.initEvent(type,false,false);if(data){for(var i in data){if(data.hasOwnProperty(i)){event[i]=data[i]}}}return event}var cordova={define:define,require:require,version:CORDOVA_JS_BUILD_LABEL,platformId:platform.id,addWindowEventHandler:function(event){return(windowEventHandlers[event]=channel.create(event))},addStickyDocumentEventHandler:function(event){return(documentEventHandlers[event]=channel.createSticky(event))},addDocumentEventHandler:function(event){return(documentEventHandlers[event]=channel.create(event))},removeWindowEventHandler:function(event){delete windowEventHandlers[event]},removeDocumentEventHandler:function(event){delete documentEventHandlers[event]},getOriginalHandlers:function(){return{document:{addEventListener:m_document_addEventListener,removeEventListener:m_document_removeEventListener},window:{addEventListener:m_window_addEventListener,removeEventListener:m_window_removeEventListener}}},fireDocumentEvent:function(type,data,bNoDetach){var evt=createEvent(type,data);if(typeof documentEventHandlers[type]!="undefined"){if(bNoDetach){documentEventHandlers[type].fire(evt)}else{setTimeout(function(){if(type=="deviceready"){document.dispatchEvent(evt)}documentEventHandlers[type].fire(evt)},0)}}else{document.dispatchEvent(evt)}},fireWindowEvent:function(type,data){var evt=createEvent(type,data);if(typeof windowEventHandlers[type]!="undefined"){setTimeout(function(){windowEventHandlers[type].fire(evt)},0)}else{window.dispatchEvent(evt)}},callbackId:Math.floor(Math.random()*2000000000),callbacks:{},callbackStatus:{NO_RESULT:0,OK:1,CLASS_NOT_FOUND_EXCEPTION:2,ILLEGAL_ACCESS_EXCEPTION:3,INSTANTIATION_EXCEPTION:4,MALFORMED_URL_EXCEPTION:5,IO_EXCEPTION:6,INVALID_ACTION:7,JSON_EXCEPTION:8,ERROR:9},callbackSuccess:function(callbackId,args){try{cordova.callbackFromNative(callbackId,true,args.status,[args.message],args.keepCallback)}catch(e){console.log("Error in error callback: "+callbackId+" = "+e)}},callbackError:function(callbackId,args){try{cordova.callbackFromNative(callbackId,false,args.status,[args.message],args.keepCallback)}catch(e){console.log("Error in error callback: "+callbackId+" = "+e)}},callbackFromNative:function(callbackId,success,status,args,keepCallback){var callback=cordova.callbacks[callbackId];if(callback){if(success&&status==cordova.callbackStatus.OK){callback.success&&callback.success.apply(null,args)}else{if(!success){callback.fail&&callback.fail.apply(null,args)}}if(!keepCallback){delete cordova.callbacks[callbackId]}}},addConstructor:function(func){channel.onCordovaReady.subscribe(function(){try{func()}catch(e){console.log("Failed to run constructor: "+e)}})}};module.exports=cordova});define("cordova/android/nativeapiprovider",function(require,exports,module){var nativeApi=this._cordovaNative||require("cordova/android/promptbasednativeapi");var currentApi=nativeApi;module.exports={get:function(){return currentApi},setPreferPrompt:function(value){currentApi=value?require("cordova/android/promptbasednativeapi"):nativeApi},set:function(value){currentApi=value}}});define("cordova/android/promptbasednativeapi",function(require,exports,module){module.exports={exec:function(service,action,callbackId,argsJson){return prompt(argsJson,"gap:"+JSON.stringify([service,action,callbackId]))},setNativeToJsBridgeMode:function(value){prompt(value,"gap_bridge_mode:")},retrieveJsMessages:function(fromOnlineEvent){return prompt(+fromOnlineEvent,"gap_poll:")}}});define("cordova/argscheck",function(require,exports,module){var exec=require("cordova/exec");var utils=require("cordova/utils");var moduleExports=module.exports;var typeMap={A:"Array",D:"Date",N:"Number",S:"String",F:"Function",O:"Object"};function extractParamName(callee,argIndex){return(/.*?\((.*?)\)/).exec(callee)[1].split(", ")[argIndex]}function checkArgs(spec,functionName,args,opt_callee){if(!moduleExports.enableChecks){return}var errMsg=null;var typeName;for(var i=0;i<spec.length;++i){var c=spec.charAt(i),cUpper=c.toUpperCase(),arg=args[i];if(c=="*"){continue}typeName=utils.typeName(arg);if((arg===null||arg===undefined)&&c==cUpper){continue}if(typeName!=typeMap[cUpper]){errMsg="Expected "+typeMap[cUpper];break}}if(errMsg){errMsg+=", but got "+typeName+".";errMsg='Wrong type for parameter "'+extractParamName(opt_callee||args.callee,i)+'" of '+functionName+": "+errMsg;if(typeof jasmine=="undefined"){console.error(errMsg)}throw TypeError(errMsg)}}function getValue(value,defaultValue){return value===undefined?defaultValue:value}moduleExports.checkArgs=checkArgs;moduleExports.getValue=getValue;moduleExports.enableChecks=true});define("cordova/base64",function(require,exports,module){var base64=exports;base64.fromArrayBuffer=function(arrayBuffer){var array=new Uint8Array(arrayBuffer);return uint8ToBase64(array)};var b64_6bit="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var b64_12bit;var b64_12bitTable=function(){b64_12bit=[];for(var i=0;i<64;i++){for(var j=0;j<64;j++){b64_12bit[i*64+j]=b64_6bit[i]+b64_6bit[j]}}b64_12bitTable=function(){return b64_12bit};return b64_12bit};function uint8ToBase64(rawData){var numBytes=rawData.byteLength;var output="";var segment;var table=b64_12bitTable();for(var i=0;i<numBytes-2;i+=3){segment=(rawData[i]<<16)+(rawData[i+1]<<8)+rawData[i+2];output+=table[segment>>12];output+=table[segment&4095]}if(numBytes-i==2){segment=(rawData[i]<<16)+(rawData[i+1]<<8);output+=table[segment>>12];output+=b64_6bit[(segment&4095)>>6];output+="="}else{if(numBytes-i==1){segment=(rawData[i]<<16);output+=table[segment>>12];output+="=="}}return output}});define("cordova/builder",function(require,exports,module){var utils=require("cordova/utils");function each(objects,func,context){for(var prop in objects){if(objects.hasOwnProperty(prop)){func.apply(context,[objects[prop],prop])}}}function clobber(obj,key,value){exports.replaceHookForTesting(obj,key);obj[key]=value;if(obj[key]!==value){utils.defineGetter(obj,key,function(){return value})}}function assignOrWrapInDeprecateGetter(obj,key,value,message){if(message){utils.defineGetter(obj,key,function(){console.log(message);delete obj[key];clobber(obj,key,value);return value})}else{clobber(obj,key,value)}}function include(parent,objects,clobber,merge){each(objects,function(obj,key){try{var result=obj.path?require(obj.path):{};if(clobber){if(typeof parent[key]==="undefined"){assignOrWrapInDeprecateGetter(parent,key,result,obj.deprecated)}else{if(typeof obj.path!=="undefined"){if(merge){recursiveMerge(parent[key],result)}else{assignOrWrapInDeprecateGetter(parent,key,result,obj.deprecated)}}}result=parent[key]}else{if(typeof parent[key]=="undefined"){assignOrWrapInDeprecateGetter(parent,key,result,obj.deprecated)}else{result=parent[key]}}if(obj.children){include(result,obj.children,clobber,merge)}}catch(e){utils.alert("Exception building cordova JS globals: "+e+' for key "'+key+'"')}})}function recursiveMerge(target,src){for(var prop in src){if(src.hasOwnProperty(prop)){if(target.prototype&&target.prototype.constructor===target){clobber(target.prototype,prop,src[prop])}else{if(typeof src[prop]==="object"&&typeof target[prop]==="object"){recursiveMerge(target[prop],src[prop])}else{clobber(target,prop,src[prop])}}}}}exports.buildIntoButDoNotClobber=function(objects,target){include(target,objects,false,false)};exports.buildIntoAndClobber=function(objects,target){include(target,objects,true,false)};exports.buildIntoAndMerge=function(objects,target){include(target,objects,true,true)};exports.recursiveMerge=recursiveMerge;exports.assignOrWrapInDeprecateGetter=assignOrWrapInDeprecateGetter;exports.replaceHookForTesting=function(){}});define("cordova/channel",function(require,exports,module){var utils=require("cordova/utils"),nextGuid=1;var Channel=function(type,sticky){this.type=type;this.handlers={};this.state=sticky?1:0;this.fireArgs=null;this.numHandlers=0;this.onHasSubscribersChange=null},channel={join:function(h,c){var len=c.length,i=len,f=function(){if(!(--i)){h()}};for(var j=0;j<len;j++){if(c[j].state===0){throw Error("Can only use join with sticky channels.")}c[j].subscribe(f)}if(!len){h()}},create:function(type){return channel[type]=new Channel(type,false)},createSticky:function(type){return channel[type]=new Channel(type,true)},deviceReadyChannelsArray:[],deviceReadyChannelsMap:{},waitForInitialization:function(feature){if(feature){var c=channel[feature]||this.createSticky(feature);this.deviceReadyChannelsMap[feature]=c;this.deviceReadyChannelsArray.push(c)}},initializationComplete:function(feature){var c=this.deviceReadyChannelsMap[feature];if(c){c.fire()}}};function forceFunction(f){if(typeof f!="function"){throw"Function required as first argument!"}}Channel.prototype.subscribe=function(f,c){forceFunction(f);if(this.state==2){f.apply(c||this,this.fireArgs);return}var func=f,guid=f.observer_guid;if(typeof c=="object"){func=utils.close(c,f)}if(!guid){guid=""+nextGuid++}func.observer_guid=guid;f.observer_guid=guid;if(!this.handlers[guid]){this.handlers[guid]=func;this.numHandlers++;if(this.numHandlers==1){this.onHasSubscribersChange&&this.onHasSubscribersChange()}}};Channel.prototype.unsubscribe=function(f){forceFunction(f);var guid=f.observer_guid,handler=this.handlers[guid];if(handler){delete this.handlers[guid];this.numHandlers--;if(this.numHandlers===0){this.onHasSubscribersChange&&this.onHasSubscribersChange()}}};Channel.prototype.fire=function(e){var fail=false,fireArgs=Array.prototype.slice.call(arguments);if(this.state==1){this.state=2;this.fireArgs=fireArgs}if(this.numHandlers){var toCall=[];for(var item in this.handlers){toCall.push(this.handlers[item])}for(var i=0;i<toCall.length;++i){toCall[i].apply(this,fireArgs)}if(this.state==2&&this.numHandlers){this.numHandlers=0;this.handlers={};this.onHasSubscribersChange&&this.onHasSubscribersChange()}}};channel.createSticky("onDOMContentLoaded");channel.createSticky("onNativeReady");channel.createSticky("onCordovaReady");channel.createSticky("onPluginsReady");channel.createSticky("onDeviceReady");channel.create("onResume");channel.create("onPause");channel.createSticky("onDestroy");channel.waitForInitialization("onCordovaReady");channel.waitForInitialization("onDOMContentLoaded");module.exports=channel});define("cordova/exec",function(require,exports,module){var cordova=require("cordova"),nativeApiProvider=require("cordova/android/nativeapiprovider"),utils=require("cordova/utils"),base64=require("cordova/base64"),jsToNativeModes={PROMPT:0,JS_OBJECT:1,LOCATION_CHANGE:2},nativeToJsModes={POLLING:0,LOAD_URL:1,ONLINE_EVENT:2,PRIVATE_API:3},jsToNativeBridgeMode,nativeToJsBridgeMode=nativeToJsModes.ONLINE_EVENT,pollEnabled=false,messagesFromNative=[];function androidExec(success,fail,service,action,args){if(jsToNativeBridgeMode===undefined){androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT)}for(var i=0;i<args.length;i++){if(utils.typeName(args[i])=="ArrayBuffer"){args[i]=base64.fromArrayBuffer(args[i])}}var callbackId=service+cordova.callbackId++,argsJson=JSON.stringify(args);if(success||fail){cordova.callbacks[callbackId]={success:success,fail:fail}}if(jsToNativeBridgeMode==jsToNativeModes.LOCATION_CHANGE){window.location="http://cdv_exec/"+service+"#"+action+"#"+callbackId+"#"+argsJson}else{var messages=nativeApiProvider.get().exec(service,action,callbackId,argsJson);if(jsToNativeBridgeMode==jsToNativeModes.JS_OBJECT&&messages==="@Null arguments."){androidExec.setJsToNativeBridgeMode(jsToNativeModes.PROMPT);androidExec(success,fail,service,action,args);androidExec.setJsToNativeBridgeMode(jsToNativeModes.JS_OBJECT);return}else{androidExec.processMessages(messages)}}}function pollOnceFromOnlineEvent(){pollOnce(true)}function pollOnce(opt_fromOnlineEvent){var msg=nativeApiProvider.get().retrieveJsMessages(!!opt_fromOnlineEvent);androidExec.processMessages(msg)}function pollingTimerFunc(){if(pollEnabled){pollOnce();setTimeout(pollingTimerFunc,50)}}function hookOnlineApis(){function proxyEvent(e){cordova.fireWindowEvent(e.type)}window.addEventListener("online",pollOnceFromOnlineEvent,false);window.addEventListener("offline",pollOnceFromOnlineEvent,false);cordova.addWindowEventHandler("online");cordova.addWindowEventHandler("offline");document.addEventListener("online",proxyEvent,false);document.addEventListener("offline",proxyEvent,false)}hookOnlineApis();androidExec.jsToNativeModes=jsToNativeModes;androidExec.nativeToJsModes=nativeToJsModes;androidExec.setJsToNativeBridgeMode=function(mode){if(mode==jsToNativeModes.JS_OBJECT&&!window._cordovaNative){console.log("Falling back on PROMPT mode since _cordovaNative is missing. Expected for Android 3.2 and lower only.");mode=jsToNativeModes.PROMPT}nativeApiProvider.setPreferPrompt(mode==jsToNativeModes.PROMPT);jsToNativeBridgeMode=mode};androidExec.setNativeToJsBridgeMode=function(mode){if(mode==nativeToJsBridgeMode){return}if(nativeToJsBridgeMode==nativeToJsModes.POLLING){pollEnabled=false}nativeToJsBridgeMode=mode;nativeApiProvider.get().setNativeToJsBridgeMode(mode);if(mode==nativeToJsModes.POLLING){pollEnabled=true;setTimeout(pollingTimerFunc,1)}};function processMessage(message){try{var firstChar=message.charAt(0);if(firstChar=="J"){eval(message.slice(1))}else{if(firstChar=="S"||firstChar=="F"){var success=firstChar=="S";var keepCallback=message.charAt(1)=="1";var spaceIdx=message.indexOf(" ",2);var status=+message.slice(2,spaceIdx);var nextSpaceIdx=message.indexOf(" ",spaceIdx+1);var callbackId=message.slice(spaceIdx+1,nextSpaceIdx);var payloadKind=message.charAt(nextSpaceIdx+1);var payload;if(payloadKind=="s"){payload=message.slice(nextSpaceIdx+2)}else{if(payloadKind=="t"){payload=true}else{if(payloadKind=="f"){payload=false}else{if(payloadKind=="N"){payload=null}else{if(payloadKind=="n"){payload=+message.slice(nextSpaceIdx+2)}else{if(payloadKind=="A"){var data=message.slice(nextSpaceIdx+2);var bytes=window.atob(data);var arraybuffer=new Uint8Array(bytes.length);for(var i=0;i<bytes.length;i++){arraybuffer[i]=bytes.charCodeAt(i)}payload=arraybuffer.buffer}else{if(payloadKind=="S"){payload=window.atob(message.slice(nextSpaceIdx+2))}else{payload=JSON.parse(message.slice(nextSpaceIdx+1))}}}}}}}cordova.callbackFromNative(callbackId,success,status,[payload],keepCallback)}else{console.log("processMessage failed: invalid message:"+message)}}}catch(e){console.log("processMessage failed: Message: "+message);console.log("processMessage failed: Error: "+e);console.log("processMessage failed: Stack: "+e.stack)}}androidExec.processMessages=function(messages){if(messages){messagesFromNative.push(messages);if(messagesFromNative.length>1){return}while(messagesFromNative.length){messages=messagesFromNative[0];if(messages=="*"){messagesFromNative.shift();window.setTimeout(pollOnce,0);return}var spaceIdx=messages.indexOf(" ");var msgLen=+messages.slice(0,spaceIdx);var message=messages.substr(spaceIdx+1,msgLen);messages=messages.slice(spaceIdx+msgLen+1);processMessage(message);if(messages){messagesFromNative[0]=messages}else{messagesFromNative.shift()}}}};module.exports=androidExec});define("cordova/init",function(require,exports,module){var channel=require("cordova/channel");var cordova=require("cordova");var modulemapper=require("cordova/modulemapper");var platform=require("cordova/platform");var pluginloader=require("cordova/pluginloader");var platformInitChannelsArray=[channel.onNativeReady,channel.onPluginsReady];function logUnfiredChannels(arr){for(var i=0;i<arr.length;++i){if(arr[i].state!=2){console.log("Channel not fired: "+arr[i].type)}}}window.setTimeout(function(){if(channel.onDeviceReady.state!=2){console.log("deviceready has not fired after 5 seconds.");logUnfiredChannels(platformInitChannelsArray);logUnfiredChannels(channel.deviceReadyChannelsArray)}},5000);function replaceNavigator(origNavigator){var CordovaNavigator=function(){};CordovaNavigator.prototype=origNavigator;var newNavigator=new CordovaNavigator();if(CordovaNavigator.bind){for(var key in origNavigator){if(typeof origNavigator[key]=="function"){newNavigator[key]=origNavigator[key].bind(origNavigator)}}}return newNavigator}if(window.navigator){window.navigator=replaceNavigator(window.navigator)}if(!window.console){window.console={log:function(){}}}if(!window.console.warn){window.console.warn=function(msg){this.log("warn: "+msg)}}channel.onPause=cordova.addDocumentEventHandler("pause");channel.onResume=cordova.addDocumentEventHandler("resume");channel.onDeviceReady=cordova.addStickyDocumentEventHandler("deviceready");if(document.readyState=="complete"||document.readyState=="interactive"){channel.onDOMContentLoaded.fire()}else{document.addEventListener("DOMContentLoaded",function(){channel.onDOMContentLoaded.fire()},false)}if(window._nativeReady){channel.onNativeReady.fire()}modulemapper.clobbers("cordova","cordova");modulemapper.clobbers("cordova/exec","cordova.exec");modulemapper.clobbers("cordova/exec","Cordova.exec");platform.bootstrap&&platform.bootstrap();pluginloader.load(function(){channel.onPluginsReady.fire()});channel.join(function(){modulemapper.mapModules(window);platform.initialize&&platform.initialize();channel.onCordovaReady.fire();channel.join(function(){require("cordova").fireDocumentEvent("deviceready")},channel.deviceReadyChannelsArray)},platformInitChannelsArray)});define("cordova/modulemapper",function(require,exports,module){var builder=require("cordova/builder"),moduleMap=define.moduleMap,symbolList,deprecationMap;exports.reset=function(){symbolList=[];deprecationMap={}};function addEntry(strategy,moduleName,symbolPath,opt_deprecationMessage){if(!(moduleName in moduleMap)){throw new Error("Module "+moduleName+" does not exist.")}symbolList.push(strategy,moduleName,symbolPath);if(opt_deprecationMessage){deprecationMap[symbolPath]=opt_deprecationMessage}}exports.clobbers=function(moduleName,symbolPath,opt_deprecationMessage){addEntry("c",moduleName,symbolPath,opt_deprecationMessage)};exports.merges=function(moduleName,symbolPath,opt_deprecationMessage){addEntry("m",moduleName,symbolPath,opt_deprecationMessage)};exports.defaults=function(moduleName,symbolPath,opt_deprecationMessage){addEntry("d",moduleName,symbolPath,opt_deprecationMessage)};exports.runs=function(moduleName){addEntry("r",moduleName,null)};function prepareNamespace(symbolPath,context){if(!symbolPath){return context}var parts=symbolPath.split(".");var cur=context;for(var i=0,part;part=parts[i];++i){cur=cur[part]=cur[part]||{}}return cur}exports.mapModules=function(context){var origSymbols={};context.CDV_origSymbols=origSymbols;for(var i=0,len=symbolList.length;i<len;i+=3){var strategy=symbolList[i];var moduleName=symbolList[i+1];var module=require(moduleName);if(strategy=="r"){continue}var symbolPath=symbolList[i+2];var lastDot=symbolPath.lastIndexOf(".");var namespace=symbolPath.substr(0,lastDot);var lastName=symbolPath.substr(lastDot+1);var deprecationMsg=symbolPath in deprecationMap?"Access made to deprecated symbol: "+symbolPath+". "+deprecationMsg:null;var parentObj=prepareNamespace(namespace,context);var target=parentObj[lastName];if(strategy=="m"&&target){builder.recursiveMerge(target,module)}else{if((strategy=="d"&&!target)||(strategy!="d")){if(!(symbolPath in origSymbols)){origSymbols[symbolPath]=target}builder.assignOrWrapInDeprecateGetter(parentObj,lastName,module,deprecationMsg)}}}};exports.getOriginalSymbol=function(context,symbolPath){var origSymbols=context.CDV_origSymbols;if(origSymbols&&(symbolPath in origSymbols)){return origSymbols[symbolPath]}var parts=symbolPath.split(".");var obj=context;for(var i=0;i<parts.length;++i){obj=obj&&obj[parts[i]]}return obj};exports.reset()});define("cordova/platform",function(require,exports,module){module.exports={id:"android",bootstrap:function(){var channel=require("cordova/channel"),cordova=require("cordova"),exec=require("cordova/exec"),modulemapper=require("cordova/modulemapper");exec(null,null,"PluginManager","startup",[]);channel.onNativeReady.fire();modulemapper.clobbers("cordova/plugin/android/app","navigator.app");var backButtonChannel=cordova.addDocumentEventHandler("backbutton");backButtonChannel.onHasSubscribersChange=function(){exec(null,null,"App","overrideBackbutton",[this.numHandlers==1])};cordova.addDocumentEventHandler("menubutton");cordova.addDocumentEventHandler("searchbutton");channel.onCordovaReady.subscribe(function(){exec(null,null,"App","show",[])})}}});define("cordova/plugin/android/app",function(require,exports,module){var exec=require("cordova/exec");module.exports={clearCache:function(){exec(null,null,"App","clearCache",[])},loadUrl:function(url,props){exec(null,null,"App","loadUrl",[url,props])},cancelLoadUrl:function(){exec(null,null,"App","cancelLoadUrl",[])},clearHistory:function(){exec(null,null,"App","clearHistory",[])},backHistory:function(){exec(null,null,"App","backHistory",[])},overrideBackbutton:function(override){exec(null,null,"App","overrideBackbutton",[override])},exitApp:function(){return exec(null,null,"App","exitApp",[])}}});define("cordova/pluginloader",function(require,exports,module){var modulemapper=require("cordova/modulemapper");function injectScript(url,onload,onerror){var script=document.createElement("script");script.onload=onload;script.onerror=onerror||onload;script.src=url;document.head.appendChild(script)}function onScriptLoadingComplete(moduleList,finishPluginLoading){for(var i=0,module;module=moduleList[i];i++){if(module){try{if(module.clobbers&&module.clobbers.length){for(var j=0;j<module.clobbers.length;j++){modulemapper.clobbers(module.id,module.clobbers[j])}}if(module.merges&&module.merges.length){for(var k=0;k<module.merges.length;k++){modulemapper.merges(module.id,module.merges[k])}}if(module.runs&&!(module.clobbers&&module.clobbers.length)&&!(module.merges&&module.merges.length)){modulemapper.runs(module.id)}}catch(err){}}}finishPluginLoading()}function handlePluginsObject(path,moduleList,finishPluginLoading){var scriptCounter=moduleList.length;if(!scriptCounter){finishPluginLoading();return}function scriptLoadedCallback(){if(!--scriptCounter){onScriptLoadingComplete(moduleList,finishPluginLoading)}}for(var i=0;i<moduleList.length;i++){injectScript(path+moduleList[i].file,scriptLoadedCallback)}}function injectPluginScript(pathPrefix,finishPluginLoading){injectScript(pathPrefix+"cordova_plugins.js",function(){try{var moduleList=require("cordova/plugin_list");handlePluginsObject(pathPrefix,moduleList,finishPluginLoading)}catch(e){finishPluginLoading()}},finishPluginLoading)}function findCordovaPath(){var path=null;var scripts=document.getElementsByTagName("script");var term="cordova.js";for(var n=scripts.length-1;n>-1;n--){var src=scripts[n].src;if(src.indexOf(term)==(src.length-term.length)){path=src.substring(0,src.length-term.length);break}}return path}exports.load=function(callback){var pathPrefix=findCordovaPath();if(pathPrefix===null){console.log("Could not find cordova.js script tag. Plugin loading may fail.");pathPrefix=""}injectPluginScript(pathPrefix,callback)}});define("cordova/urlutil",function(require,exports,module){var urlutil=exports;var anchorEl=document.createElement("a");urlutil.makeAbsolute=function(url){anchorEl.href=url;return anchorEl.href}});define("cordova/utils",function(require,exports,module){var utils=exports;utils.defineGetterSetter=function(obj,key,getFunc,opt_setFunc){if(Object.defineProperty){var desc={get:getFunc,configurable:true};if(opt_setFunc){desc.set=opt_setFunc}Object.defineProperty(obj,key,desc)}else{obj.__defineGetter__(key,getFunc);if(opt_setFunc){obj.__defineSetter__(key,opt_setFunc)}}};utils.defineGetter=utils.defineGetterSetter;utils.arrayIndexOf=function(a,item){if(a.indexOf){return a.indexOf(item)}var len=a.length;for(var i=0;i<len;++i){if(a[i]==item){return i}}return -1};utils.arrayRemove=function(a,item){var index=utils.arrayIndexOf(a,item);if(index!=-1){a.splice(index,1)}return index!=-1};utils.typeName=function(val){return Object.prototype.toString.call(val).slice(8,-1)};utils.isArray=function(a){return utils.typeName(a)=="Array"};utils.isDate=function(d){return utils.typeName(d)=="Date"};utils.clone=function(obj){if(!obj||typeof obj=="function"||utils.isDate(obj)||typeof obj!="object"){return obj}var retVal,i;if(utils.isArray(obj)){retVal=[];for(i=0;i<obj.length;++i){retVal.push(utils.clone(obj[i]))}return retVal}retVal={};for(i in obj){if(!(i in retVal)||retVal[i]!=obj[i]){retVal[i]=utils.clone(obj[i])}}return retVal};utils.close=function(context,func,params){if(typeof params=="undefined"){return function(){return func.apply(context,arguments)}}else{return function(){return func.apply(context,params)}}};utils.createUUID=function(){return UUIDcreatePart(4)+"-"+UUIDcreatePart(2)+"-"+UUIDcreatePart(2)+"-"+UUIDcreatePart(2)+"-"+UUIDcreatePart(6)};utils.extend=(function(){var F=function(){};return function(Child,Parent){F.prototype=Parent.prototype;Child.prototype=new F();Child.__super__=Parent.prototype;Child.prototype.constructor=Child}}());utils.alert=function(msg){if(window.alert){window.alert(msg)}else{if(console&&console.log){console.log(msg)}}};function UUIDcreatePart(length){var uuidpart="";for(var i=0;i<length;i++){var uuidchar=parseInt((Math.random()*256),10).toString(16);if(uuidchar.length==1){uuidchar="0"+uuidchar}uuidpart+=uuidchar}return uuidpart}});window.cordova=require("cordova");require("cordova/init")})();
Example #15
0
function Device(){this.available=!1,this.platform=null,this.version=null,this.uuid=null,this.cordova=null,this.model=null;var e=this;channel.onCordovaReady.subscribe(function(){e.getInfo(function(o){var a=cordova.version;e.available=!0,e.platform=o.platform,e.version=o.version,e.uuid=o.uuid,e.cordova=a,e.model=o.model,channel.onCordovaInfoReady.fire()},function(o){e.available=!1,utils.alert("[ERROR] Error initializing Cordova: "+o)})})}var argscheck=require("cordova/argscheck"),channel=require("cordova/channel"),utils=require("cordova/utils"),exec=require("cordova/exec"),cordova=require("cordova");channel.createSticky("onCordovaInfoReady"),channel.waitForInitialization("onCordovaInfoReady"),Device.prototype.getInfo=function(e,o){argscheck.checkArgs("fF","Device.getInfo",arguments),exec(e,o,"Device","getDeviceInfo",[])},module.exports=new Device;
        eventsToFireOnStartUp.push(msg);
    } else {
        processMessage(msg);
    }
}

function processMessage(msg) {
    var action = msg.action;
    if (action == 'switchforeground') {
        exports.onSwitchToForeground.fire();
    } else {
        throw new Error('Unknown background app action: ' + msg.action);
    }
}

if (platform.id == 'android') {
  channel.createSticky('onBackgroundAppReady');
  channel.waitForInitialization('onBackgroundAppReady');
  channel.onCordovaReady.subscribe(function() {
    exec(onMessageFromNative, undefined, 'BackgroundPlugin', 'messageChannel', []);
    helpers.runAtStartUp(function() {
        if (eventsToFireOnStartUp.length) {
            helpers.queueLifeCycleEvent(firePendingEvents);
        } else {
            eventsToFireOnStartUp = null;
        }
    });
    channel.initializationComplete('onBackgroundAppReady');
  });
}
/*
Copyright 2015 Intel Corporation

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
*/

var channel = require('cordova/channel'),
    utils = require('cordova/utils');

channel.createSticky('IntelXDKGeolocation');
channel.waitForInitialization('IntelXDKGeolocation');
channel.onCordovaReady.subscribe(function() {
    if (typeof(intel) != "object") intel = {};
    if (typeof(intel.xdk) != "object") intel.xdk = {};
    intel.xdk.geolocation = navigator.geolocation;
    channel.IntelXDKGeolocation.fire();
});
Example #18
0
            }
            clearTimeout(alarms[name].timeoutId);
            var periodInMillis = alarms[name].periodInMinutes*60000;
            scheduledTime += Math.ceil((Date.now() - scheduledTime)/periodInMillis)*periodInMillis;
        }
        var alarmCreateInfo = {'when':scheduledTime};
        if ('periodInMinutes' in alarms[name]) {
            alarmCreateInfo.periodInMinutes = alarms[name].periodInMinutes;
        }
        delete alarms[name];
        exports.create(name, alarmCreateInfo);
    });
}

channel.createSticky('onChromeAlarmsReady');
channel.waitForInitialization('onChromeAlarmsReady');
channel.onCordovaReady.subscribe(function() {
    storage.internal.get('alarms', function(values) {
        if (!values.alarms) {
            channel.initializationComplete('onChromeAlarmsReady');
            return;
        }
        alarms = values.alarms;
        alarms.__proto__ = null;
        channel.initializationComplete('onChromeAlarmsReady');
        if (bootstrap) {
            bootstrap.onBackgroundPageLoaded.subscribe(reregisterAlarms);
        } else {
            reregisterAlarms();
        }
    });
Example #19
0
	},

	removeVirtualPage : function(){
		exec(null, null, "IntelXDKDevice", "removeVirtualPage", []);
	},

	copyToClipboard : function(text){
		exec(null, null, "IntelXDKDevice", "copyToClipboard", [text]);
	},

	init: function () {
		exec(null, null, "IntelXDKDevice", "initialize", []);
	},
}

var me = module.exports;

channel.createSticky('IntelXDKDevice');
channel.waitForInitialization('IntelXDKDevice');

channel.onCordovaReady.subscribe(function () {
    me.init();
});

//Event intel.xdk.device.init will be fired once properties have been bound to intel.xdk.device.
document.addEventListener('intel.xdk.device.init',function(){
	intel.xdk.device.phonegapversion = cordova.version;
	channel.IntelXDKDevice.fire();
});

    // 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
};

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', []);
});

Example #21
0
cordova.define("io.jxcore.node.jxcore", function(require, exports, module) { // See the LICENSE file

var channel = require('cordova/channel'),
  utils = require('cordova/utils'),
  exec = require('cordova/exec'),
  cordova = require('cordova');

channel.createSticky('onJXcoreReady');
channel.waitForInitialization('onJXcoreReady');
var jxcore_device = {
  ios: (navigator.userAgent.match(/iPad/i))  == "iPad" || (navigator.userAgent.match(/iPhone/i))  == "iPhone",
  android: (navigator.userAgent.match(/Android/i)) == "Android"
};

if (!jxcore_device.ios && !jxcore_device.android) {
  var counter = 0, errmsg = 'JXcore plugin: Device type is unkown. Defaulting to Android';
  var inter = setInterval(function(){
    if (typeof log != "undefined") {
      log(errmsg, 'red');
    } else if (++counter > 400) {
      if (typeof console != "undefined") {
        console.log(errmsg);
      }
    } else {
      return;
    }
    clearInterval(inter);
  },5);
  jxcore_device.android = true;
}

function callNative(name, args, callback) {
  exec(
    function cb(data) {
      if (data === null) return;
      if (callback) {
        if (!Array.isArray(data)) {
          data = [data];
        } else {
          if (!jxcore_device.android) {
            try {
              data = JSON.parse(data);
            } catch (e) {
              log("Error:", e.message);
              return;
            }
            if (!Array.isArray(data)) {
              data = [data];
            }
          }
        }

        callback.apply(null, data);
      }
    },
    function errorHandler(err) {
      if (callback) callback(null, err);
    },
    'JXcore',
    name,
    args
  );
}

channel.onCordovaReady.subscribe(function () {
  callNative("onResume", null, function () {
    channel.onJXcoreReady.fire();
  });
});

function jxcore(x) {
  if (!(this instanceof jxcore)) {
    return new jxcore(x);
  }
  this.name = x;
}

var initialized = false;
jxcore.isReady = function (callback) {
  if (initialized) return;
  callNative("isReady", [], function (ret) {
    if (ret) {
      initialized = true;
      callback();
    } else {
      setTimeout(function () {
        jxcore.isReady(callback);
      }, 5);
    }
  });
};

var isFunction = function (__$) {
  var _$ = {};
  return __$ && _$.toString.call(__$) === '[object Function]';
};

var callFunction = function (name, params, callback) {
  var args = {};
  args.methodName = name;
  args.params = params;

  callNative("Evaluate", ["cordova.executeJSON(" + JSON.stringify(args)], callback);
};

jxcore.prototype.call = function () {
  var ln = arguments.length;
  var methodName = this.name;
  var callback = null;
  var args = [];

  if (ln) {
    ln -= isFunction(arguments[ln - 1]) ? 1 : 0;
    for (var i = 0; i < ln; i++) {
      args[i] = arguments[i];
    }
    if (ln != arguments.length)
      callback = arguments[ln];
  }

  callFunction(methodName, args, callback);
  return this;
};

jxcore.prototype.register = function (callback) {
  if (!isFunction(callback)) {
    throw new TypeError("callback needs to be a function");
  }

  callFunction("registerUIMethod", [this.name], callback);
  return this;
};

jxcore.prototype.loadMainFile = function (callback) {
  callFunction("loadMainFile", [this.name], callback);
  return this;
};

module.exports = jxcore;

function onPause() {
  callNative("onPause");
}

document.addEventListener("pause", onPause, false);

function onResume() {
  callNative("onResume");
}

document.addEventListener("resume", onResume, false);
});
Example #22
0
cordova.define("cordova-plugin-ajmide-header.AjmideHeader", function(require, exports, module) {

var exec = require('cordova/exec');
var setting;
var AjmideHeader = function(){

};
AjmideHeader.setSetting=function(setting)
{
              
      this.setting=setting;
      exec(function(e){},  function(e){}, "AjmideHeader", "setSetting", [JSON.stringify(AjmideHeader.setting)]);
               
              
}
 
AjmideHeader.hideHeader=function(){
               
   exec(function(e){},  function(e){}, "AjmideHeader", "hideHeader", []);
        
}
AjmideHeader.showHeader=function(){
    
    exec(function(e){},  function(e){}, "AjmideHeader", "showHeader", []);
}
AjmideHeader.onSelect=function(tag,position,item){
           
            if(tag=="left")
            {
             this.setting.left[position].event() ;
            }else{
             if(item==-1)
               {
               this.setting.right[position].event() ;
               }else{
               this.setting.right[position].list[item].event() ;
               }
               
           }
            
              
}
module.exports = AjmideHeader;


function onMessageFromNative(msg) {
              
    if (msg.action == 'onSelect') {
               
       AjmideHeader.onSelect(msg.onSelect.tag, msg.onSelect.position,msg.onSelect.item);
    }
    else
    {
        throw new Error('Unknown media action' + msg.action);
    }
}

if (cordova.platformId === 'android' || cordova.platformId === 'amazon-fireos' || cordova.platformId === 'windowsphone') {

    var channel = require('cordova/channel');

    channel.createSticky('onAjmideHeaderPluginReady');
    channel.waitForInitialization('onAjmideHeaderPluginReady');

    channel.onCordovaReady.subscribe(function() {
        exec(onMessageFromNative, undefined, 'AjmideHeader', 'messageChannel', []);
        channel.initializationComplete('onAjmideHeaderPluginReady');
    });
}




});
Example #23
0
cordova.define("org.apache.cordova.file.fileSystemPaths", function(require, exports, module) {/*
 *
 * 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
};

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', []);
});

});
Example #24
0
cordova.define("coocaa-plugin-coocaaosapi.coocaaosapi", function(require, exports, module) {

   var argscheck = require('cordova/argscheck'),
           channel = require('cordova/channel'),
           exec = require('cordova/exec'),
           cordova = require('cordova'),
           startapp = require('com.lampa.startapp.startapp'),
           brocaster = require('cordova-plugin-broadcaster.broadcaster');

           channel.createSticky('onCoocaaOsInitReady');
           channel.waitForInitialization('onCoocaaOsInitReady');

     //   console.log(JSON.stringify(config));
       function CoocaaOSApi(){
            var thiz = this;
             channel.onCordovaReady.subscribe(function(){
                thiz.waitForCoocaaOSInitReady(function(message){
                    console.log('success CoocaaOSInitReady ' +message);
                    channel.onCoocaaOsInitReady.fire();
                 },function(message){
                    console.log('error : ' + message);

                   });
             });
       }

       CoocaaOSApi.prototype.waitForCoocaaOSInitReady = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.waitForCoocaaOSInitReady',arguments);
            exec(success,error,'CoocaaOSApi','waitForOSReady',[]);
        }

/*************************************内置应用相关*************************************************/
/*
* 启动本地媒体
*/
    CoocaaOSApi.prototype.startLocalMedia = function(success,error){
        argscheck.checkArgs('ff','CoocaaOSApi.startLocalMedia',arguments);
        startapp.check("com.tianci.localmedia", function(message) { /* success */
           startapp.start([["com.tianci.localmedia", "com.tianci.localmedia.MainActivity"]], success,error);
        },
        error);
    }

/*
*启动电视设置
*/
     CoocaaOSApi.prototype.startTVSetting = function(success,error){
     argscheck.checkArgs('ff','CoocaaOSApi.startTVSetting',arguments);
             startapp.check("com.tianci.setting", function(message) { /* success */
                startapp.start([["com.tianci.setting", "com.tianci.setting.TianciSetting"]], success,error);
             },
             error);
     }

/*
*启动信号源
*/
     CoocaaOSApi.prototype.startSourceList = function(success,error){
         argscheck.checkArgs('ff','CoocaaOSApi.startSourceList',arguments);
         exec(success,error,'CoocaaOSApi','launchSourceList',[]);
      }

/*
*启动二维码
*/
    CoocaaOSApi.prototype.startQRCode = function(success,error){
        argscheck.checkArgs('ff','CoocaaOSApi.startTVSetting',arguments);
         startapp.check("com.tianci.qrcode", function(message) { /* success */
         startapp.start([["com.tianci.qrcode", "com.tianci.qrcode.SkyQrcode"]], success,error);
          },
          error);
      }

/*
*启动影视历史
*/
     CoocaaOSApi.prototype.startMovieHistory = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.startMovieHistory',arguments);
             startapp.start([["action", "coocaa.intent.movie.history"]], success,error);
     }

/*
*启动我的游戏
*/
      CoocaaOSApi.prototype.startMyGames = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.startMyGames',arguments);
             startapp.start([["action", "coocaa.intent.action.GAME_CENTER_MYGAME"]], success,error);
      }


/*
* 启动我的应用
* mode: child / 其他,代表启动的是哪个模式下的程序
*/
      CoocaaOSApi.prototype.startMyApps = function(mode,success,error){
            argscheck.checkArgs('sff','CoocaaOSApi.startMyApps',arguments);
            if(mode=='child')
            {
                startapp.start([["action", "coocaa.intent.action.MYAPP_CHILD_MODEL"]], success,error);
            }
            else
            {
                startapp.start([["action", "coocaa.intent.action.APP_STORE_MYAPPS"]], success,error);
            }
      }

/*
*启动用户设置
*/
      CoocaaOSApi.prototype.startUserSetting = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.startUserSetting',arguments);
             startapp.start([["action", "android.settings.ADD_ACCOUNT_SETTINGS"]], success,error);
      }

/*
*启动网络设置
*/
      CoocaaOSApi.prototype.startNetSetting = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.startNetSetting',arguments);
             startapp.start([["action", "android.settings.NETWORK_OPERATOR_SETTINGS"]], success,error);
      }

/*
*启动蓝牙设置
*/
      CoocaaOSApi.prototype.startBlueToothSetting = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.startBlueToothSetting',arguments);
             startapp.start([["action", "android.settings.BLUETOOTH_SETTINGS"]], success,error);
      }

/*
*启动消息盒子
*/
      CoocaaOSApi.prototype.startMessageBox = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.startMessageBox',arguments);
            startapp.start([["action", "com.coocaa.action.MESSAGEBOX"]], success,error);
      }

/*
* 启动升级界面
*/
     CoocaaOSApi.prototype.startSystemUpgrade = function(success,error){
          argscheck.checkArgs('ff','CoocaaOSApi.startSystemUpgrade',arguments);
          startapp.start([["action", "android.settings.SYSTEM_UPGRADE"]], success,error);
      }

/*******************************************影视相关***********************************************/

    function MovieItem(){
        var thiz = this;
    }

/*
* 启动影视列表页
*/
  CoocaaOSApi.prototype.startMovieList = function(listid,success,error){
           argscheck.checkArgs('sff','CoocaaOSApi.startMovieList',arguments);
           startapp.start([["action", "coocaa.intent.movie.list"],[{'id':listid}]], success,error);
      }
/*
* 启动影视详情页
*/
  CoocaaOSApi.prototype.startMovieDetail = function(detailid,success,error){
            argscheck.checkArgs('sff','CoocaaOSApi.startMovieDetail',arguments);
            startapp.start([["action", "ccoocaa.intent.movie.detailinfo"],[{'id':detailid}]], success,error);
      }

/*
*启动影视专题页
*/
  CoocaaOSApi.prototype.startMovieTopic = function(topicid,success,error){
            argscheck.checkArgs('sff','CoocaaOSApi.startMovieTopic',arguments);
            startapp.start([["action", "coocaa.intent.movie.special"],[{'id':topicid}]], success,error);
      }

/*
*启动影视会员中心
*/
   CoocaaOSApi.prototype.startMovieMemberCenter = function(success,error){
        argscheck.checkArgs('ff','CoocaaOSApi.startMovieMemberCenter',arguments);
        startapp.start([["action", "coocaa.intent.vip.center "]], success,error);
   }

/*
*  启动播放器
*  最小集合
*  needparse: 需要传递'true'|'false',默认传递false
*/
   CoocaaOSApi.prototype.playOnlineMovie = function(url,name,needparse,success,error){
        argscheck.checkArgs('sssff','CoocaaOSApi.playOnlineMovier',arguments);
        exec(success,error,'CoocaaOSApi','startOnLinePlayer',[{'url':url},{'name':name},{'needparse':needparse}]);
   }

/*******************************************应用相关***********************************************/

/*
*启动应用商城
*/
    CoocaaOSApi.prototype.startAppStore = function(success,error){
        argscheck.checkArgs('ff','CoocaaOSApi.startAppStore',arguments);
        startapp.start([["action", "coocaa.intent.action.APP_STORE_HOME"]], success,error);
    }

/*
*启动应用商城榜单页
*/
   CoocaaOSApi.prototype.startAppStoreBD = function(success,error){
         argscheck.checkArgs('ff','CoocaaOSApi.startAppStoreBD',arguments);
         startapp.start([["action", "coocaa.intent.action.APP_STORE_BD"]], success,error);
     }

/*
*启动应用商城分类页
*/
    CoocaaOSApi.prototype.startAppStoreSort = function(sortid,success,error){
        argscheck.checkArgs('sff','CoocaaOSApi.startAppStoreSort',arguments);
        startapp.start([["action", "coocaa.intent.action.APP_STORE_SORT"],[{'sortid':sortid}]], success,error);
    }

/*
*启动应用商城列表页
*/
    CoocaaOSApi.prototype.startAppStoreList = function(listid,success,error){
        argscheck.checkArgs('sff','CoocaaOSApi.startAppStoreList',arguments);
        startapp.start([["action", "coocaa.intent.action.APP_STORE_LIST"],[{'listId':listid}]], success,error);
    }

/*
*启动应用商城详情页
*可以传递pkg或者id
*/
    CoocaaOSApi.prototype.startAppStoreDetail = function(idorpgk,success,error){
        argscheck.checkArgs('sff','CoocaaOSApi.startAppStoreDetail',arguments);
        startapp.start([["action", "coocaa.intent.action.APP_STORE_DETAIL"],[{'id':idorpgk}]], success,error);
    }

/*
*启动应用商城专题页
*/
    CoocaaOSApi.prototype.startAppStoreZone = function(zoneid,success,error){
        argscheck.checkArgs('sff','CoocaaOSApi.startAppStoreZone',arguments);
        startapp.start([["action", "coocaa.intent.action.ZONEPAGE"],[{'id':zoneid}]], success,error);
    }

    /**
         * 启动应用程序,如果程序存在直接启动,否则就创建应用下载任务
         * @param url 下载地址
         * @param md5 md5校验值,如果不存在则传空字符串 ''
         * @param title 下载的任务名字
         * @param packageName 应用包名
         * @param appID 应用的appID,由应用圈的后台接口给出
         * @param iconUrl 应用iconURL
         *
         * @return (success)
            function (message){
                console.log("taskid " + message.tasid); //任务id
                console.log("status " + message.status); //任务状态
                       public static final int STATUS_ON_DEFAULT = 0;
                       public static final int STATUS_TO_START = 1;
                       public static final int STATUS_TO_START_NOW = 2;
                       public static final int STATUS_TO_REMOVE = 3;
                       public static final int STATUS_TO_PAUSE = 4;
                       public static final int STATUS_ON_DOWNLOADING = 5;
                       public static final int STATUS_ON_PAUSED = 6;
                       public static final int STATUS_ON_STOPPED = 7;
                       public static final int STATUS_ON_COMPLETE = 8;
                       public static final int STATUS_ON_REMOVED = 9;
                       public static final int STATUS_ON_STARTING = 10;
                console.log("name " + message.name); //名称
                 console.log("url " + message.url); //下载地址
                  console.log("progress " + message.progress); //进度
                   console.log("createtime " + message.createtime); //创建时间
                   console.log("code " + message.code); //额外code
                    console.log("extra " + message.extra); //额外附带信息
            }
         */
    CoocaaOSApi.prototype.startOrCreateDownloadTask = function(downloadurl,md5, title,packageName,appID,iconUrl,success,error){
         argscheck.checkArgs('ssssssff','CoocaaOSApi.startOrCreateDownloadTask',arguments);
          startapp.check(packageName,function(checksuccess){
            startapp.start(packageName,success,error);
          },function(checkerror){
                console.log(checkerror);
                exec(success,error,'CoocaaOSApi','createDownloadTask',[{'url':downloadurl},{'md5':md5},{'title':title},{'pkg':packageName},{'appid':appID},{'icon':iconUrl}]);
          }
          );

    }

/*
* 恢复下载接口
* 传递taskid。
*
*/
    CoocaaOSApi.prototype.resumeDownloadTask = function(taskid,success,error){
         argscheck.checkArgs('sff','CoocaaOSApi.resumeDownloadTask',arguments);
         exec(success,error,'CoocaaOSApi','resumeDownloadTask',[{'taskid':taskid}]);
    }

/*
* 暂停下载接口
* 传递taskid。
*
*/
    CoocaaOSApi.prototype.pauseDownloadTask = function(taskid,success,error){
         argscheck.checkArgs('sff','CoocaaOSApi.pauseDownloadTask',arguments);
         exec(success,error,'CoocaaOSApi','pauseDownloadTask',[{'taskid':taskid}]);
    }

/*
* 继续下载接口
* 传递taskid。
*/
    CoocaaOSApi.prototype.deleteDownloadTask = function(taskid,success,error){
         argscheck.checkArgs('sff','CoocaaOSApi.deleteDownloadTask',arguments);
        exec(success,error,'CoocaaOSApi','deleteDownloadTask',[{'taskid':taskid}]);
    }

/*******************************************游戏相关***********************************************/
/*
* 启动酷游吧
*/
 CoocaaOSApi.prototype.startGameCenter = function(success,error){
        argscheck.checkArgs('ff','CoocaaOSApi.startGameCenter',arguments);
        startapp.start([["action", "coocaa.intent.action.GAME_CENTER_HOME"]], success,error);
    }

/*
*启动酷游吧游戏详情页
*可以传递pkg或者id
*/
    CoocaaOSApi.prototype.startGameCenterDetail = function(idorpgk,success,error){
        argscheck.checkArgs('sff','CoocaaOSApi.startGameCenterDetail',arguments);
        startapp.start([["action", "coocaa.intent.action.GAME_CENTER_DETAIL"],[{'id':idorpgk}]], success,error);
    }

/*
*启动酷游吧游戏列表页
*/
    CoocaaOSApi.prototype.startGameCenterList = function(id,title,success,error){
        argscheck.checkArgs('ssff','CoocaaOSApi.startGameCenterList',arguments);
        startapp.start([["action", "coocaa.intent.action.GAME_CENTER_LIST"],[{'id':id,'title':title}]], success,error);
    }

/*
*启动酷游吧游戏专题页
*/
    CoocaaOSApi.prototype.startGameCenterZone = function(id,success,error){
        argscheck.checkArgs('sff','CoocaaOSApi.startGameZone',arguments);
        startapp.start([["action", "coocaa.intent.action.GAME_CENTER_ZONE"],[{'id':id}]], success,error);
    }

/*
*启动军火库
*/
    CoocaaOSApi.prototype.startGameArsenal = function(success,error){
            argscheck.checkArgs('ff','CoocaaOSApi.startGameArsenal',arguments);
            startapp.start([["action", "coocaa.intent.action.GAME_CENTER_ARSENAL"]], success,error);
        }

/*******************************************系统相关***********************************************/
/*
* 判断当前是否有用户登录
/*function (message){
                console.log("haslogin " + message.haslogin);
            }
   return:
   true: 已经登录
   false: 未登录
*/
CoocaaOSApi.prototype.hasCoocaaUserLogin = function(success,error){
        argscheck.checkArgs('ff','CoocaaOSApi.hasCoocaaUserLogin',arguments);
        exec(success,error,'CoocaaOSApi','hasCoocaaUserLogin',[]);
   }

/*
* 获取当前用户信息
* 主要的信息是open_id
*
/*function (message){
                console.log("address " + message.address);
                console.log("avatar " + message.avatar);
                console.log("avatars " + message.avatars);
                console.log("birthday " + message.birthday);
                console.log("city " + message.city);
                console.log("corp " + message.corp);
                console.log("district " + message.district);
                console.log("education_grade " + message.education_grade);
                console.log("email " + message.email);
                console.log("gender " + message.gender);
                console.log("idcard " + message.idcard);
                console.log("line " + message.line);
                console.log("mobile " + message.mobile);
                console.log("nick_name " + message.nick_name);
                console.log("occupation " + message.occupation);
                console.log("open_id " + message.open_id);
                console.log("oss_id " + message.oss_id);
                console.log("postcode " + message.postcode);
                console.log("province " + message.province);
                console.log("qq " + message.qq);
                console.log("region " + message.region);
                console.log("region_id " + message.region_id);
                console.log("revenue " + message.revenue);
                 console.log("score " + message.score);
                 console.log("sky_id " + message.sky_id);
                 console.log("skype " + message.skype);
                 console.log("slogan " + message.slogan);
                 console.log("tel1 " + message.tel1);
                 console.log("tel2 " + message.tel2);
                 console.log("visit_num " + message.visit_num);
                 console.log("wechat " + message.wechat);
                 console.log("weibo " + message.weibo);
                 console.log("balance " + message.balance);
                 console.log("third_account " + message.third_account);
                 console.log("external_info " + message.external_info);
            }
*/
CoocaaOSApi.prototype.getUserInfo = function(success,error){
        argscheck.checkArgs('ff','CoocaaOSApi.getUserInfo',arguments);
        exec(success,error,'CoocaaOSApi','getUserInfo',[]);
   }

/*
* 获取当前设备信息
* message {"pennel","version","model","type","mac","chip"}
/*function (message){
                console.log("panel " + message.panel);
                console.log("version " + message.version);
                console.log("model " + message.model);
                 console.log("type " + message.type);
                  console.log("mac " + message.mac);
                  console.log("chip " + message.chip);
                  console.log("androidsdk " + message.androidsdk);
            }
   return:
   panel:屏幕尺寸
   version:酷开TV系统版本号
   model:生产机芯
   type:生产机型
   mac:设备mac(有线)
   chip:芯片
   androidsdk:android版本号
   devid:设备唯一id
   activeid:设备激活id/联网之后由后台分配
*/
CoocaaOSApi.prototype.getDeviceInfo = function(success,error){
    argscheck.checkArgs('ff','CoocaaOSApi.getDeviceInfo',arguments);
    exec(success,error,'CoocaaOSApi','getDeviceInfo',[]);
}

/*
* 判断网络是否连接
/*function (message){
                console.log("isnetworking " + message.isnetworking);
            }
   return:
   true: 联网
   false:未联网
*/
CoocaaOSApi.prototype.isNetConnected = function(success,error){
    argscheck.checkArgs('ff','CoocaaOSApi.isNetConnected',arguments);
            exec(success,error,'CoocaaOSApi','isNetConnected',[]);
}

/*
* 获取当前网络类型
/*function (message){
                console.log("nettype " + message.nettype);
            }
   return:
     ETHERNET:有线网络
     WIFI:wifi网络
     PPPOE:以太网络,小区网络
     UNKNOW:未知
*/
CoocaaOSApi.prototype.getNetType = function(success,error){
    argscheck.checkArgs('ff','CoocaaOSApi.getNetType',arguments);
    exec(success,error,'CoocaaOSApi','getNetType',[]);
}

/*
* 获取当前网络ip地址的信息
/*function (message){
                console.log("dns0 " + message.dns0);
                console.log("dns1 " + message.dns0);
                console.log("gateway " + message.dns0);
                console.log("ip " + message.dns0);
                console.log("mac " + message.dns0);
                console.log("netmask " + message.dns0);
            }
return:
  ip:ip地址
  gateway:默认网关
  netmask:子网掩码
  dns0:主dns
  dns1:备用dns
  mac:mac地址
*/
CoocaaOSApi.prototype.getIpInfo= function(success,error){
    argscheck.checkArgs('ff','CoocaaOSApi.getIpAddress',arguments);
    exec(success,error,'CoocaaOSApi','getIpInfo',[]);
}

/*
* 获取当前城市,设备所在地址
* 获取到的message.contury,message.city,...
* 可以根据当前ip调用其他接口获取当前电视的城市位置,精准到城市是可以的
/*function (message){
                console.log("location " + message.location);
            }
return:
  location:位置信息,可能为两级或三级地址信息,比如:"广东省,深圳市,"。
*/
CoocaaOSApi.prototype.getDeviceLocation = function(success,error){
    argscheck.checkArgs('ff','CoocaaOSApi.getDeviceLocation',arguments);
    exec(success,error,'CoocaaOSApi','getDeviceLocation',[]);
}

/*
* 增加网络广播事件监听
/* function( message ) {
        {"nettype":"ethnet|wifi","netevent":"changged event"}
        }

        ethnet: /**
                        * Description: 网络已连接成功
                       EVENT_ETH_CONNECT_SUCCEEDED,
                       /**
                        * Description: 网络连接失败
                       EVENT_ETH_CONNECT_FAILD,
                       /**
                        * Description: 网线已插上
                       EVENT_ETH_CABLE_CONNECTED,
                       /**
                        * Description: 网线已断开
                       EVENT_ETH_CABLE_DISCONNECTED,
                       /**
                        * Description: 未知
                       EVENT_ETH_UNKNOW,
                       /**
                        * Description: 连接初始化失败
                       EVENT_ETH_CONNECT_INIT_FAIL,
                       /**
                        * Description: 由于网线未连接导致连接失败
                       EVENT_ETH_CONNECT_FAILD_BY_CABLE_NOT_CONNECT,
                       /**
                        * Description: 连接以太网超时
                       EVENT_ETH_CONNECT_FAILD_BY_TIMEOUT

       wifi:
         /**
                 * Description: 网络已连接成功
                EVENT_WIFI_CONNECT_SUCCEEDED,
                /**
                 * Description: 网络连接中
                EVENT_WIFI_CONNECT_CONNECTING,
                /**
                 * Description: 无线已断开
                EVENT_WIFI_CONNECT_DISCONNECTED,
                /**
                 * Description: 无线断开中
                EVENT_WIFI_CONNECT_DISCONNECTING,
                /**
                 * Description: 无线连接失败
                EVENT_WIFI_CONNECT_FAILD,
                /**
                 * Description: 未知状态
                EVENT_WIFI_CONNECT_UNKNOW,
                /**
                 * @Description : WIFI强度变化
                EVENT_WIFI_RSSI_CHANGED,
                /**
                 * @Description : WIFI请求搜索出现失败
                EVENT_WIFI_SCAN_FAIL
*/
CoocaaOSApi.prototype.addNetChangedListener = function(listener)
{
    argscheck.checkArgs('f','CoocaaOSApi.addNetChangedListener',arguments);
    brocaster.addEventListener( "NET_CHANGGED", listener);
}

/*
* 添加外部磁盘拔插广播
/* function( message ) {
        {"usbmount":"false","mountpath":"file:///mnt/usb/sda1"}
        console.log( "USB_CHANGGED received! ismount: " + message.usbmount  );
        console.log( "USB_CHANGGED received! mountpath: " + message.mountpath  );
    }
*/
CoocaaOSApi.prototype.addUSBChangedListener = function(listener)
{
    argscheck.checkArgs('f','CoocaaOSApi.addUSBChangedListener',arguments);
    brocaster.addEventListener( "USB_CHANGGED",listener);
}

/*
* 添加应用下载的广播监听
/*  @return (success)
               function (message){
                   console.log("taskid " + message.tasid); //任务id
                   console.log("status " + message.status); //任务状态
                          public static final int STATUS_ON_DEFAULT = 0;
                          public static final int STATUS_TO_START = 1;
                          public static final int STATUS_TO_START_NOW = 2;
                          public static final int STATUS_TO_REMOVE = 3;
                          public static final int STATUS_TO_PAUSE = 4;
                          public static final int STATUS_ON_DOWNLOADING = 5;
                          public static final int STATUS_ON_PAUSED = 6;
                          public static final int STATUS_ON_STOPPED = 7;
                          public static final int STATUS_ON_COMPLETE = 8;
                          public static final int STATUS_ON_REMOVED = 9;
                          public static final int STATUS_ON_STARTING = 10;
                   console.log("name " + message.name); //名称
                    console.log("url " + message.url); //下载地址
                     console.log("progress " + message.progress); //进度
                      console.log("createtime " + message.createtime); //创建时间
                      console.log("code " + message.code); //额外code
                       console.log("extra " + message.extra); //额外附带信息
               }
*/
CoocaaOSApi.prototype.addAppTaskListener = function(listener)
{
    argscheck.checkArgs('f','CoocaaOSApi.addAppTaskListener',arguments);
    brocaster.addEventListener( "APP_TASK_CALLBACK",listener);
}


   module.exports = new CoocaaOSApi();
});
Example #25
0
var channel = require('cordova/channel'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec');

// 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.name = null;
    this.uuid = null;
    this.cordova = null;

    var me = this;

    channel.onCordovaReady.subscribeOnce(function() {
        me.getInfo(function(info) {
            me.available = true;
            me.platform = info.platform;
            me.version = info.version;
            me.name = info.name;
            me.uuid = info.uuid;
            me.cordova = info.cordova;
            channel.onCordovaInfoReady.fire();
Example #26
0
cordova.define("org.apache.cordova.media.Media", function(require, exports, module) {
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]);
};

/**
 * Pause recording audio file.
 */
Media.prototype.pauseRecord = function() {
    exec(null, this.errorCallback, "Media", "pauseRecordingAudio", [this.id]);
};

/**
* Resume recording audio file.
*/
Media.prototype.resumeRecord = function() {
    exec(null, this.errorCallback, "Media", "resumeRecordingAudio", [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]);
};

/**
 * Adjust the playback rate.
 */
Media.prototype.setRate = function(rate) {
    if (cordova.platformId === 'ios'){
        exec(null, null, "Media", "setRate", [this.id, rate]);
    } else {
        console.warn('media.setRate method is currently not supported for', cordova.platformId, 'platform.');
    }
};

/**
 * Get amplitude of audio.
 */
Media.prototype.getCurrentAmplitude = function(success, fail) {
    exec(function(p) {
        success(p);
    }, fail, "Media", "getCurrentAmplitudeAudio", [this.id]);
};

/**
 * 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 :
                if (media.statusCallback) {
                    media.statusCallback(value);
                }
                if (value == Media.MEDIA_STOPPED) {
                    if (media.successCallback) {
                        media.successCallback();
                    }
                }
                break;
            case Media.MEDIA_DURATION :
                media._duration = value;
                break;
            case Media.MEDIA_ERROR :
                if (media.errorCallback) {
                    media.errorCallback(value);
                }
                break;
            case Media.MEDIA_POSITION :
                media._position = Number(value);
                break;
            default :
                if (console.error) {
                    console.error("Unhandled Media.onStatus :: " + msgType);
                }
                break;
        }
    } else if (console.error) {
        console.error("Received Media.onStatus callback for unknown media :: " + id);
    }

};

module.exports = Media;

function onMessageFromNative(msg) {
    if (msg.action == 'status') {
        Media.onStatus(msg.status.id, msg.status.msgType, msg.status.value);
    } else {
        throw new Error('Unknown media action' + msg.action);
    }
}

if (cordova.platformId === 'android' || cordova.platformId === 'amazon-fireos' || cordova.platformId === 'windowsphone') {

    var channel = require('cordova/channel');

    channel.createSticky('onMediaPluginReady');
    channel.waitForInitialization('onMediaPluginReady');

    channel.onCordovaReady.subscribe(function() {
        exec(onMessageFromNative, undefined, 'Media', 'messageChannel', []);
        channel.initializationComplete('onMediaPluginReady');
    });
}
});
}

exports.triggerOnButtonClicked = function(notificationId, buttonIndex) {
    exports.onButtonClicked.fire(notificationId, buttonIndex);
}

exports.onClosed = new Event('onClosed');
exports.onClicked = new Event('onClicked');
exports.onButtonClicked = new Event('onButtonClicked');

function fireStartupEvents() {
    exec(undefined, undefined, 'ChromeNotifications', 'fireStartupEvents', []);
}

channel.createSticky('onChromeNotificationsReady');
channel.waitForInitialization('onChromeNotificationsReady');
channel.onCordovaReady.subscribe(function() {
    storage.internal.get('notifications', function(values) {
        if (values.notifications) {
            notifications = values.notifications;
            notifications.__proto__ = null;
        }
        channel.initializationComplete('onChromeNotificationsReady');
        if (bootstrap) {
            bootstrap.onBackgroundPageLoaded.subscribe(fireStartupEvents);
        } else {
            setTimeout(fireStartupEvents, 0);
        }
    });
});
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.
*/

var argscheck = require('cordova/argscheck'),
    channel = require('cordova/channel'),
    utils = require('cordova/utils'),
    exec = require('cordova/exec'),
    cordova = require('cordova');

channel.createSticky('onAppInfoReady');
// Tell cordova channel to wait on the AppInfoReady event
channel.waitForInitialization('onAppInfoReady');

/**
 * This represents the app, and provides properties for inspecting the app info.
 * phone, etc.
 * @constructor
 */
function AppInfo() {
    this.available = false;
    this.name = null;
    this.version = null;
    this.build = null;
    this.identifier = null;
    this.compileDate = null;
    this.isHardwareAccelerated = null;
    this.isDebuggable = null;
Example #29
0
cordova.define("org.apache.cordova.network-information.network", function(require, exports, module) { /*
 * 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'),
    cordova = require('cordova'),
    channel = require('cordova/channel'),
    utils = require('cordova/utils');

// Link the onLine property with the Cordova-supplied network info.
// This works because we clobber the naviagtor object with our own
// object in bootstrap.js.
if (typeof navigator != 'undefined') {
    utils.defineGetter(navigator, 'onLine', function() {
        return this.connection.type != 'none';
    });
}

function NetworkConnection() {
    this.type = 'unknown';
}

/**
 * Get connection info
 *
 * @param {Function} successCallback The function to call when the Connection data is available
 * @param {Function} errorCallback The function to call when there is an error getting the Connection data. (OPTIONAL)
 */
NetworkConnection.prototype.getInfo = function(successCallback, errorCallback) {
    exec(successCallback, errorCallback, "NetworkStatus", "getConnectionInfo", []);
};

var me = new NetworkConnection();
var timerId = null;
var timeout = 500;

channel.createSticky('onCordovaConnectionReady');
channel.waitForInitialization('onCordovaConnectionReady');

channel.onCordovaReady.subscribe(function() {
    me.getInfo(function(info) {
        me.type = info;
        if (info === "none") {
            // set a timer if still offline at the end of timer send the offline event
            timerId = setTimeout(function(){
                cordova.fireDocumentEvent("offline");
                timerId = null;
            }, timeout);
        } else {
            // If there is a current offline event pending clear it
            if (timerId !== null) {
                clearTimeout(timerId);
                timerId = null;
            }
            cordova.fireDocumentEvent("online");
        }

        // should only fire this once
        if (channel.onCordovaConnectionReady.state !== 2) {
            channel.onCordovaConnectionReady.fire();
        }
    },
    function (e) {
        // If we can't get the network info we should still tell Cordova
        // to fire the deviceready event.
        if (channel.onCordovaConnectionReady.state !== 2) {
            channel.onCordovaConnectionReady.fire();
        }
        console.log("Error initializing Network Connection: " + e);
    });
});

module.exports = me;

});
Example #30
0
var exec = require('cordova/exec');
var cordova = require('cordova');
var channel = require('cordova/channel');
var utils = require('cordova/utils');

channel.createSticky('onCordovaXGPushReady');
channel.waitForInitialization('onCordovaXGPushReady');

function XGPush() {

    var context = this;

    this.channels = {
        'click': channel.create('click'),
        'message': channel.create('message'),
        'register': channel.create('register'),
        'unRegister': channel.create('unRegister'),
        'show': channel.create('show'),
        'deleteTag': channel.create('deleteTag'),
        'setTag': channel.create('setTag')
    };

    this.on = function (type, func) {
        if (type in context.channels) {
            context.channels[type].subscribe(func);
        }
    };

    this.un = function (type, func) {
        if (type in this.channels) {
            context.channels[type].unsubscribe(func);