diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8079ae2 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain \ No newline at end of file diff --git a/platforms/ios/Emby.xcodeproj/project.pbxproj b/platforms/ios/Emby.xcodeproj/project.pbxproj index 4ca707a..ef243f3 100644 --- a/platforms/ios/Emby.xcodeproj/project.pbxproj +++ b/platforms/ios/Emby.xcodeproj/project.pbxproj @@ -5,10 +5,8 @@ }; objectVersion = 46; objects = { - /* Begin PBXBuildFile section */ 04F6FC7527FA4B6682BB9587 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = F56589A630DC417D9D78FCD1 /* CFNetwork.framework */; }; - 0693067B697E40ED8F4B9125 /* CDVConnection.m in Sources */ = {isa = PBXBuildFile; fileRef = C40BB7DB6F0A4E25978AA560 /* CDVConnection.m */; }; 07305E4BC6304C299222C84F /* CDVLocalFilesystem.m in Sources */ = {isa = PBXBuildFile; fileRef = 605ADD74614449D6B701A998 /* CDVLocalFilesystem.m */; }; 0C1D2EB896FC40B8BF2C0CDC /* DeviceScannerDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = FFF6BD34834D4D8B89C4FF2C /* DeviceScannerDelegate.m */; }; 0F917A2703AB41E387067F7E /* ActionSheet.m in Sources */ = {isa = PBXBuildFile; fileRef = E9358E49698E4BAB980D5205 /* ActionSheet.m */; }; @@ -72,7 +70,6 @@ 7E7966E51810823500FA85AD /* icon-76@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966DB1810823500FA85AD /* icon-76@2x.png */; }; 7E7966E61810823500FA85AD /* icon-small.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966DC1810823500FA85AD /* icon-small.png */; }; 7E7966E71810823500FA85AD /* icon-small@2x.png in Resources */ = {isa = PBXBuildFile; fileRef = 7E7966DD1810823500FA85AD /* icon-small@2x.png */; }; - 8CB79D171E4848D6A69CAFFA /* Launcher.m in Sources */ = {isa = PBXBuildFile; fileRef = E8B0D7710AD54D1A93E25CC9 /* Launcher.m */; }; 8EEF0700C07D44F084A80265 /* ImageIO.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 05DA4705271F494CAE647F27 /* ImageIO.framework */; settings = {ATTRIBUTES = (Weak, ); }; }; 93953DFD1C00480AADAD091A /* MainViewController+RemoteControls.m in Sources */ = {isa = PBXBuildFile; fileRef = 8E83E1B43DBE472B896D7240 /* MainViewController+RemoteControls.m */; }; 9AA7A4671E7A49FBBA638914 /* libstdc++.6.0.9.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 500661F9C5DA4578BA9B65FB /* libstdc++.6.0.9.dylib */; }; @@ -89,7 +86,6 @@ A3F135851C0CFAB20010885D /* libc++.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = A3F135841C0CFAB20010885D /* libc++.tbd */; }; A3F135871C0CFACD0010885D /* AVFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A3F135861C0CFACD0010885D /* AVFoundation.framework */; }; A3F3C52B1BA0B14100B1DE6D /* MediaPlayer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C2C374D3F2B74479A84498C2 /* MediaPlayer.framework */; }; - A531A8461C0B46BBB09FB2DA /* CDVReachability.m in Sources */ = {isa = PBXBuildFile; fileRef = 8F23067EAAAE45D890E44B4D /* CDVReachability.m */; }; AE4CC7A1D77540A283EA2059 /* InAppPurchase.m in Sources */ = {isa = PBXBuildFile; fileRef = EEE8787A3C12489297CEBD93 /* InAppPurchase.m */; }; B40F3BFFEB2C408EA34A2AA8 /* libicucore.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 4330620717C0471DB4E477AC /* libicucore.dylib */; }; B5BACF4ED8274178BEE337D4 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3F14394E959548C7B6B7754D /* SystemConfiguration.framework */; }; @@ -212,7 +208,6 @@ 8D68CE608662442481449857 /* CDVSound.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVSound.m; path = "cordova-plugin-media/CDVSound.m"; sourceTree = ""; }; 8D778FC389C448C7A12A67BF /* NSString+URLEncoding.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "NSString+URLEncoding.h"; path = "cordova-plugin-x-socialsharing/NSString+URLEncoding.h"; sourceTree = ""; }; 8E83E1B43DBE472B896D7240 /* MainViewController+RemoteControls.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "MainViewController+RemoteControls.m"; path = "com.rd11.remote-controls/MainViewController+RemoteControls.m"; sourceTree = ""; }; - 8F23067EAAAE45D890E44B4D /* CDVReachability.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVReachability.m; path = "cordova-plugin-network-information/CDVReachability.m"; sourceTree = ""; }; 912B578A9F52489B89C625E0 /* CDVDevice.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVDevice.m; path = "cordova-plugin-device/CDVDevice.m"; sourceTree = ""; }; 96813CCE77A64CC499AFB989 /* StoreKit.framework */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = wrapper.framework; name = StoreKit.framework; path = System/Library/Frameworks/StoreKit.framework; sourceTree = SDKROOT; }; 9AF3A54C672247169A7323B1 /* IonicCameraRoll.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = IonicCameraRoll.m; path = com.drifty.cordova.cameraroll/IonicCameraRoll.m; sourceTree = ""; }; @@ -235,7 +230,6 @@ A3F135841C0CFAB20010885D /* libc++.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = "libc++.tbd"; path = "usr/lib/libc++.tbd"; sourceTree = SDKROOT; }; A3F135861C0CFACD0010885D /* AVFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = AVFoundation.framework; path = System/Library/Frameworks/AVFoundation.framework; sourceTree = SDKROOT; }; A3F3C5271BA0AE9A00B1DE6D /* MobileVLCKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = MobileVLCKit.framework; path = ../../plugins/org.nypr.cordova.vlcplugin/VLCKit/build/MobileVLCKit.framework; sourceTree = ""; }; - A81122697F424DF99226F99B /* CDVConnection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVConnection.h; path = "cordova-plugin-network-information/CDVConnection.h"; sourceTree = ""; }; A9007F559BFF42E7B665B0E4 /* CDVWebViewUIDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVWebViewUIDelegate.h; path = com.telerik.plugins.wkwebview/CDVWebViewUIDelegate.h; sourceTree = ""; }; AA72F02DCC5643F3890A200C /* AppVersion.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = AppVersion.m; path = "cordova-plugin-app-version/AppVersion.m"; sourceTree = ""; }; AA77B17EB92A4D56B9C35BF9 /* SelectDeviceDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SelectDeviceDelegate.h; path = "fw-cordova-chromecast/SelectDeviceDelegate.h"; sourceTree = ""; }; @@ -245,17 +239,14 @@ B971AD058EEB4524A7D2862D /* WebKit.framework */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; }; BFEAEC02855344AFBCB134FE /* MyMainViewController.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = MyMainViewController.h; path = com.telerik.plugins.wkwebview/MyMainViewController.h; sourceTree = ""; }; C2C374D3F2B74479A84498C2 /* MediaPlayer.framework */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = wrapper.framework; name = MediaPlayer.framework; path = System/Library/Frameworks/MediaPlayer.framework; sourceTree = SDKROOT; }; - C40BB7DB6F0A4E25978AA560 /* CDVConnection.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVConnection.m; path = "cordova-plugin-network-information/CDVConnection.m"; sourceTree = ""; }; C5FCEE75AC0A4BBD8328D39D /* CommandDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CommandDelegate.h; path = "fw-cordova-chromecast/CommandDelegate.h"; sourceTree = ""; }; D4A0D8751607E02300AEF8BB /* Default-568h@2x~iphone.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "Default-568h@2x~iphone.png"; sourceTree = ""; }; D9AE1924B8724E35B840A1D3 /* CommandDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CommandDelegate.m; path = "fw-cordova-chromecast/CommandDelegate.m"; sourceTree = ""; }; DAA7987E313B4B2382677478 /* ReroutingUIWebView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = ReroutingUIWebView.h; path = com.telerik.plugins.wkwebview/ReroutingUIWebView.h; sourceTree = ""; }; DC869047775B49C2BEE16432 /* NSString+URLEncoding.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = "NSString+URLEncoding.m"; path = "cordova-plugin-x-socialsharing/NSString+URLEncoding.m"; sourceTree = ""; }; - DD05F96FCAFD492CB8EBA878 /* Launcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = Launcher.h; path = com.hutchind.cordova.plugins.launcher/Launcher.h; sourceTree = ""; }; DE7FAC890C224173948E60EA /* SocialSharing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SocialSharing.h; path = "cordova-plugin-x-socialsharing/SocialSharing.h"; sourceTree = ""; }; E79410C29F1C406BAB77B6E8 /* AppDelegate+WKWebViewPolyfill.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "AppDelegate+WKWebViewPolyfill.h"; path = "com.telerik.plugins.wkwebview/AppDelegate+WKWebViewPolyfill.h"; sourceTree = ""; }; E7C4837BBC2A4789B82A1ADC /* AudioToolbox.framework */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = wrapper.framework; name = AudioToolbox.framework; path = System/Library/Frameworks/AudioToolbox.framework; sourceTree = SDKROOT; }; - E8B0D7710AD54D1A93E25CC9 /* Launcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = Launcher.m; path = com.hutchind.cordova.plugins.launcher/Launcher.m; sourceTree = ""; }; E9358E49698E4BAB980D5205 /* ActionSheet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ActionSheet.m; path = "cordova-plugin-actionsheet/ActionSheet.m"; sourceTree = ""; }; EB46367E21A0418586508762 /* RemoteControls.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = RemoteControls.h; path = "com.rd11.remote-controls/RemoteControls.h"; sourceTree = ""; }; EB87FDF21871DA7A0020F90C /* merges */ = {isa = PBXFileReference; lastKnownFileType = folder; name = merges; path = ../../merges; sourceTree = ""; }; @@ -265,7 +256,6 @@ EE7AA692E43540C68C8150C9 /* ReroutingUIWebView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = ReroutingUIWebView.m; path = com.telerik.plugins.wkwebview/ReroutingUIWebView.m; sourceTree = ""; }; EEE8787A3C12489297CEBD93 /* InAppPurchase.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = InAppPurchase.m; path = cc.fovea.cordova.purchase/InAppPurchase.m; sourceTree = ""; }; EF19C3A2FC59467A94B31A79 /* FileUtility.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = FileUtility.h; path = cc.fovea.cordova.purchase/FileUtility.h; sourceTree = ""; }; - F08D7A9ADF3B41668D53A788 /* CDVReachability.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = CDVReachability.h; path = "cordova-plugin-network-information/CDVReachability.h"; sourceTree = ""; }; F101CFA1AC26437DB0574DF0 /* MainViewController+RemoteControls.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = "MainViewController+RemoteControls.h"; path = "com.rd11.remote-controls/MainViewController+RemoteControls.h"; sourceTree = ""; }; F56589A630DC417D9D78FCD1 /* CFNetwork.framework */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = System/Library/Frameworks/CFNetwork.framework; sourceTree = SDKROOT; }; F63AE9C39D334BFFA6C509B6 /* CDVWebViewOperationsDelegate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = CDVWebViewOperationsDelegate.m; path = com.telerik.plugins.wkwebview/CDVWebViewOperationsDelegate.m; sourceTree = ""; }; @@ -433,8 +423,6 @@ children = ( A3C30B071CAEEF4300DB4916 /* DeviceTextChannel.h */, A3C30B081CAEEF4300DB4916 /* DeviceTextChannel.m */, - E8B0D7710AD54D1A93E25CC9 /* Launcher.m */, - DD05F96FCAFD492CB8EBA878 /* Launcher.h */, 38FC119E4CC9416AA4EA2946 /* BackgroundAudio.m */, 6AAFD15D090B49A9A0331AB7 /* BackgroundAudio.h */, 9AF3A54C672247169A7323B1 /* IonicCameraRoll.m */, @@ -468,10 +456,6 @@ 5681F00574DF4467811AD489 /* DeviceScannerDelegate.h */, AA77B17EB92A4D56B9C35BF9 /* SelectDeviceDelegate.h */, 9D5CABDF3ABF43F3946686CB /* MediaChannelDelegate.h */, - C40BB7DB6F0A4E25978AA560 /* CDVConnection.m */, - 8F23067EAAAE45D890E44B4D /* CDVReachability.m */, - A81122697F424DF99226F99B /* CDVConnection.h */, - F08D7A9ADF3B41668D53A788 /* CDVReachability.h */, 5016B0BD5FED4DF4B26546DD /* RemoteControls.m */, 8E83E1B43DBE472B896D7240 /* MainViewController+RemoteControls.m */, EB46367E21A0418586508762 /* RemoteControls.h */, @@ -702,7 +686,6 @@ 1D60589B0D05DD56006BFB54 /* main.m in Sources */, 1D3623260D0F684500981E51 /* AppDelegate.m in Sources */, 302D95F114D2391D003F00A1 /* MainViewController.m in Sources */, - 8CB79D171E4848D6A69CAFFA /* Launcher.m in Sources */, 2A1BEEAC35414DDE90D2914F /* BackgroundAudio.m in Sources */, 549F66737C8F4BDBABD4002E /* IonicCameraRoll.m in Sources */, F8002EF797EA4200A619F27E /* BackgroundDownload.m in Sources */, @@ -721,8 +704,6 @@ 0C1D2EB896FC40B8BF2C0CDC /* DeviceScannerDelegate.m in Sources */, 20DCCDABC35A463C94516888 /* SelectDeviceDelegate.m in Sources */, 30856C5D8E8F4BB9A0420D20 /* MediaChannelDelegate.m in Sources */, - 0693067B697E40ED8F4B9125 /* CDVConnection.m in Sources */, - A531A8461C0B46BBB09FB2DA /* CDVReachability.m in Sources */, E0C10C6B3E8A47CBA2EBD253 /* RemoteControls.m in Sources */, 93953DFD1C00480AADAD091A /* MainViewController+RemoteControls.m in Sources */, AE4CC7A1D77540A283EA2059 /* InAppPurchase.m in Sources */, diff --git a/platforms/ios/Emby/Plugins/com.hutchind.cordova.plugins.launcher/Launcher.h b/platforms/ios/Emby/Plugins/com.hutchind.cordova.plugins.launcher/Launcher.h deleted file mode 100644 index 3028368..0000000 --- a/platforms/ios/Emby/Plugins/com.hutchind.cordova.plugins.launcher/Launcher.h +++ /dev/null @@ -1,8 +0,0 @@ -#import - -@interface Launcher : CDVPlugin - -- (void)canLaunch:(CDVInvokedUrlCommand*)command; -- (void)launch:(CDVInvokedUrlCommand*)command; - -@end diff --git a/platforms/ios/Emby/Plugins/com.hutchind.cordova.plugins.launcher/Launcher.m b/platforms/ios/Emby/Plugins/com.hutchind.cordova.plugins.launcher/Launcher.m deleted file mode 100644 index 2b1f151..0000000 --- a/platforms/ios/Emby/Plugins/com.hutchind.cordova.plugins.launcher/Launcher.m +++ /dev/null @@ -1,46 +0,0 @@ -#import "Launcher.h" -#import - -@implementation Launcher - -- (void)canLaunch:(CDVInvokedUrlCommand*)command { - NSDictionary* options = [command.arguments objectAtIndex:0]; - CDVPluginResult * pluginResult = nil; - - if ([options objectForKey:@"uri"]) { - NSString *uri = [options objectForKey:@"uri"]; - if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:uri]]) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self writeJavascript:[pluginResult toSuccessCallbackString:command.callbackId]]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No app installed that can handle that uri."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Missing option: 'uri' required."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } -} - -- (void)launch:(CDVInvokedUrlCommand*)command { - NSDictionary* options = [command.arguments objectAtIndex:0]; - CDVPluginResult * pluginResult = nil; - - if ([options objectForKey:@"uri"]) { - NSString *uri = [options objectForKey:@"uri"]; - if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:uri]]) { - NSURL *launchURL = [NSURL URLWithString:uri]; - [[UIApplication sharedApplication] openURL: launchURL]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self writeJavascript:[pluginResult toSuccessCallbackString:command.callbackId]]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No app installed that can handle that uri."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Missing option: 'uri' required."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } -} - -@end \ No newline at end of file diff --git a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVConnection.h b/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVConnection.h deleted file mode 100644 index 8add027..0000000 --- a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVConnection.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - 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. - */ - -#import -#import -#import "CDVReachability.h" - -@interface CDVConnection : CDVPlugin { - NSString* type; - NSString* _callbackId; - - CDVReachability* internetReach; -} - -@property (copy) NSString* connectionType; -@property (strong) CDVReachability* internetReach; - -@end diff --git a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVConnection.m b/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVConnection.m deleted file mode 100644 index 223dd7c..0000000 --- a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVConnection.m +++ /dev/null @@ -1,127 +0,0 @@ -/* - 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. - */ - -#import "CDVConnection.h" -#import "CDVReachability.h" - -@interface CDVConnection (PrivateMethods) -- (void)updateOnlineStatus; -- (void)sendPluginResult; -@end - -@implementation CDVConnection - -@synthesize connectionType, internetReach; - -- (void)getConnectionInfo:(CDVInvokedUrlCommand*)command -{ - _callbackId = command.callbackId; - [self sendPluginResult]; -} - -- (void)sendPluginResult -{ - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:self.connectionType]; - - [result setKeepCallbackAsBool:YES]; - [self.commandDelegate sendPluginResult:result callbackId:_callbackId]; -} - -- (NSString*)w3cConnectionTypeFor:(CDVReachability*)reachability -{ - NetworkStatus networkStatus = [reachability currentReachabilityStatus]; - - switch (networkStatus) { - case NotReachable: - return @"none"; - - case ReachableViaWWAN: - { - BOOL isConnectionRequired = [reachability connectionRequired]; - if (isConnectionRequired) { - return @"none"; - } else { - return @"cellular"; - } - } - case ReachableViaWiFi: - return @"wifi"; - - default: - return @"unknown"; - } -} - -- (BOOL)isCellularConnection:(NSString*)theConnectionType -{ - return [theConnectionType isEqualToString:@"2g"] || - [theConnectionType isEqualToString:@"3g"] || - [theConnectionType isEqualToString:@"4g"] || - [theConnectionType isEqualToString:@"cellular"]; -} - -- (void)updateReachability:(CDVReachability*)reachability -{ - if (reachability) { - // check whether the connection type has changed - NSString* newConnectionType = [self w3cConnectionTypeFor:reachability]; - if ([newConnectionType isEqualToString:self.connectionType]) { // the same as before, remove dupes - return; - } else { - self.connectionType = [self w3cConnectionTypeFor:reachability]; - } - } - [self sendPluginResult]; -} - -- (void)updateConnectionType:(NSNotification*)note -{ - CDVReachability* curReach = [note object]; - - if ((curReach != nil) && [curReach isKindOfClass:[CDVReachability class]]) { - [self updateReachability:curReach]; - } -} - -- (void)onPause -{ - [self.internetReach stopNotifier]; -} - -- (void)onResume -{ - [self.internetReach startNotifier]; - [self updateReachability:self.internetReach]; -} - -- (void)pluginInitialize -{ - self.connectionType = @"none"; - self.internetReach = [CDVReachability reachabilityForInternetConnection]; - self.connectionType = [self w3cConnectionTypeFor:self.internetReach]; - [self.internetReach startNotifier]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:) - name:kReachabilityChangedNotification object:nil]; - if (UIApplicationDidEnterBackgroundNotification && UIApplicationWillEnterForegroundNotification) { - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; - } -} - -@end diff --git a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVReachability.h b/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVReachability.h deleted file mode 100644 index 01a95c3..0000000 --- a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVReachability.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - - File: Reachability.h - Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. - Version: 2.2 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. - ("Apple") in consideration of your agreement to the following terms, and your - use, installation, modification or redistribution of this Apple software - constitutes acceptance of these terms. If you do not agree with these terms, - please do not use, install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and subject - to these terms, Apple grants you a personal, non-exclusive license, under - Apple's copyrights in this original Apple software (the "Apple Software"), to - use, reproduce, modify and redistribute the Apple Software, with or without - modifications, in source and/or binary forms; provided that if you redistribute - the Apple Software in its entirety and without modifications, you must retain - this notice and the following text and disclaimers in all such redistributions - of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may be used - to endorse or promote products derived from the Apple Software without specific - prior written permission from Apple. Except as expressly stated in this notice, - no other rights or licenses, express or implied, are granted by Apple herein, - including but not limited to any patent rights that may be infringed by your - derivative works or by other works in which the Apple Software may be - incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED - WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN - COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR - DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF - CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF - APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2010 Apple Inc. All Rights Reserved. - -*/ - -#import -#import -#import - -typedef enum { - NotReachable = 0, - ReachableViaWWAN, // this value has been swapped with ReachableViaWiFi for Cordova backwards compat. reasons - ReachableViaWiFi // this value has been swapped with ReachableViaWWAN for Cordova backwards compat. reasons -} NetworkStatus; -#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification" - -@interface CDVReachability : NSObject -{ - BOOL localWiFiRef; - SCNetworkReachabilityRef reachabilityRef; -} - -// reachabilityWithHostName- Use to check the reachability of a particular host name. -+ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; - -// reachabilityWithAddress- Use to check the reachability of a particular IP address. -+ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; - -// reachabilityForInternetConnection- checks whether the default route is available. -// Should be used by applications that do not connect to a particular host -+ (CDVReachability*)reachabilityForInternetConnection; - -// reachabilityForLocalWiFi- checks whether a local wifi connection is available. -+ (CDVReachability*)reachabilityForLocalWiFi; - -// Start listening for reachability notifications on the current run loop -- (BOOL)startNotifier; -- (void)stopNotifier; - -- (NetworkStatus)currentReachabilityStatus; -// WWAN may be available, but not active until a connection has been established. -// WiFi may require a connection for VPN on Demand. -- (BOOL)connectionRequired; -@end diff --git a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVReachability.m b/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVReachability.m deleted file mode 100644 index c60261a..0000000 --- a/platforms/ios/Emby/Plugins/cordova-plugin-network-information/CDVReachability.m +++ /dev/null @@ -1,260 +0,0 @@ -/* - - File: Reachability.m - Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. - Version: 2.2 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. - ("Apple") in consideration of your agreement to the following terms, and your - use, installation, modification or redistribution of this Apple software - constitutes acceptance of these terms. If you do not agree with these terms, - please do not use, install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and subject - to these terms, Apple grants you a personal, non-exclusive license, under - Apple's copyrights in this original Apple software (the "Apple Software"), to - use, reproduce, modify and redistribute the Apple Software, with or without - modifications, in source and/or binary forms; provided that if you redistribute - the Apple Software in its entirety and without modifications, you must retain - this notice and the following text and disclaimers in all such redistributions - of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may be used - to endorse or promote products derived from the Apple Software without specific - prior written permission from Apple. Except as expressly stated in this notice, - no other rights or licenses, express or implied, are granted by Apple herein, - including but not limited to any patent rights that may be infringed by your - derivative works or by other works in which the Apple Software may be - incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED - WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN - COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR - DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF - CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF - APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2010 Apple Inc. All Rights Reserved. - -*/ - -#import -#import -#import -#import -#import -#import - -#import - -#import "CDVReachability.h" - -#define kShouldPrintReachabilityFlags 0 - -static void CDVPrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment) -{ -#if kShouldPrintReachabilityFlags - NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", - (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', - (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', - - (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', - (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', - (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', - (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-', - comment - ); -#endif -} - -@implementation CDVReachability - -static void CDVReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) -{ -#pragma unused (target, flags) - // NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); - // NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); - - // Converted the asserts above to conditionals, with safe return from the function - if (info == NULL) { - NSLog(@"info was NULL in ReachabilityCallback"); - return; - } - - if (![(__bridge NSObject*)info isKindOfClass :[CDVReachability class]]) { - NSLog(@"info was wrong class in ReachabilityCallback"); - return; - } - - // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively - // in case someon uses the Reachability object in a different thread. - @autoreleasepool { - CDVReachability* noteObject = (__bridge CDVReachability*)info; - // Post a notification to notify the client that the network reachability changed. - [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:noteObject]; - } -} - -- (BOOL)startNotifier -{ - BOOL retVal = NO; - SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL}; - - if (SCNetworkReachabilitySetCallback(reachabilityRef, CDVReachabilityCallback, &context)) { - if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { - retVal = YES; - } - } - return retVal; -} - -- (void)stopNotifier -{ - if (reachabilityRef != NULL) { - SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - } -} - -- (void)dealloc -{ - [self stopNotifier]; - if (reachabilityRef != NULL) { - CFRelease(reachabilityRef); - } -} - -+ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; -{ - CDVReachability* retVal = NULL; - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); - if (reachability != NULL) { - retVal = [[self alloc] init]; - if (retVal != NULL) { - retVal->reachabilityRef = reachability; - retVal->localWiFiRef = NO; - } - } - return retVal; -} - -+ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; -{ - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); - CDVReachability* retVal = NULL; - if (reachability != NULL) { - retVal = [[self alloc] init]; - if (retVal != NULL) { - retVal->reachabilityRef = reachability; - retVal->localWiFiRef = NO; - } - } - return retVal; -} - -+ (CDVReachability*)reachabilityForInternetConnection; -{ - struct sockaddr_in zeroAddress; - bzero(&zeroAddress, sizeof(zeroAddress)); - zeroAddress.sin_len = sizeof(zeroAddress); - zeroAddress.sin_family = AF_INET; - return [self reachabilityWithAddress:&zeroAddress]; -} - -+ (CDVReachability*)reachabilityForLocalWiFi; -{ - struct sockaddr_in localWifiAddress; - bzero(&localWifiAddress, sizeof(localWifiAddress)); - localWifiAddress.sin_len = sizeof(localWifiAddress); - localWifiAddress.sin_family = AF_INET; - // IN_LINKLOCALNETNUM is defined in as 169.254.0.0 - localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); - CDVReachability* retVal = [self reachabilityWithAddress:&localWifiAddress]; - if (retVal != NULL) { - retVal->localWiFiRef = YES; - } - return retVal; -} - -#pragma mark Network Flag Handling - -- (NetworkStatus)localWiFiStatusForFlags:(SCNetworkReachabilityFlags)flags -{ - CDVPrintReachabilityFlags(flags, "localWiFiStatusForFlags"); - - BOOL retVal = NotReachable; - if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)) { - retVal = ReachableViaWiFi; - } - return retVal; -} - -- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags -{ - CDVPrintReachabilityFlags(flags, "networkStatusForFlags"); - if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { - // if target host is not reachable - return NotReachable; - } - - NetworkStatus retVal = NotReachable; - - if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) { - // if target host is reachable and no connection is required - // then we'll assume (for now) that your on Wi-Fi - retVal = ReachableViaWiFi; - } - - if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) || - ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))) { - // ... and the connection is on-demand (or on-traffic) if the - // calling application is using the CFSocketStream or higher APIs - - if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) { - // ... and no [user] intervention is needed - retVal = ReachableViaWiFi; - } - } - - if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) { - // ... but WWAN connections are OK if the calling application - // is using the CFNetwork (CFSocketStream?) APIs. - retVal = ReachableViaWWAN; - } - return retVal; -} - -- (BOOL)connectionRequired; -{ - NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { - return flags & kSCNetworkReachabilityFlagsConnectionRequired; - } - return NO; -} - -- (NetworkStatus)currentReachabilityStatus -{ - NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); - NetworkStatus retVal = NotReachable; - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { - if (localWiFiRef) { - retVal = [self localWiFiStatusForFlags:flags]; - } else { - retVal = [self networkStatusForFlags:flags]; - } - } - return retVal; -} - -@end diff --git a/platforms/ios/ios.json b/platforms/ios/ios.json index 744a6ca..248232f 100644 --- a/platforms/ios/ios.json +++ b/platforms/ios/ios.json @@ -18,10 +18,6 @@ } ], "/*": [ - { - "xml": "", - "count": 1 - }, { "xml": "", "count": 1 @@ -54,10 +50,6 @@ "xml": "", "count": 1 }, - { - "xml": "", - "count": 1 - }, { "xml": "", "count": 1 @@ -116,9 +108,6 @@ } }, "installed_plugins": { - "com.hutchind.cordova.plugins.launcher": { - "PACKAGE_NAME": "com.emby.mobile" - }, "nl.x-services.plugins.backgroundaudio": { "PACKAGE_NAME": "com.emby.mobile" }, @@ -149,18 +138,12 @@ "fw-cordova-chromecast": { "PACKAGE_NAME": "com.emby.mobile" }, - "cordova-plugin-network-information": { - "PACKAGE_NAME": "com.emby.mobile" - }, "com.rd11.remote-controls": { "PACKAGE_NAME": "com.emby.mobile" }, "cc.fovea.cordova.purchase": { "PACKAGE_NAME": "com.emby.mobile" }, - "cordova-plugin-crosswalk-webview": { - "PACKAGE_NAME": "com.emby.mobile" - }, "cordova-plugin-app-version": { "PACKAGE_NAME": "com.emby.mobile" }, @@ -188,14 +171,6 @@ }, "dependent_plugins": {}, "modules": [ - { - "file": "plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js", - "id": "com.hutchind.cordova.plugins.launcher.Launcher", - "pluginId": "com.hutchind.cordova.plugins.launcher", - "clobbers": [ - "plugins.launcher" - ] - }, { "file": "plugins/com.drifty.cordova.cameraroll/www/CameraRoll.js", "id": "com.drifty.cordova.cameraroll.CameraRoll", @@ -280,23 +255,6 @@ "cordova.plugins.FWChromecast" ] }, - { - "file": "plugins/cordova-plugin-network-information/www/network.js", - "id": "cordova-plugin-network-information.network", - "pluginId": "cordova-plugin-network-information", - "clobbers": [ - "navigator.connection", - "navigator.network.connection" - ] - }, - { - "file": "plugins/cordova-plugin-network-information/www/Connection.js", - "id": "cordova-plugin-network-information.Connection", - "pluginId": "cordova-plugin-network-information", - "clobbers": [ - "Connection" - ] - }, { "file": "plugins/com.rd11.remote-controls/www/RemoteControls.js", "id": "com.rd11.remote-controls.RemoteControls", @@ -552,7 +510,6 @@ } ], "plugin_metadata": { - "com.hutchind.cordova.plugins.launcher": "0.2.2", "nl.x-services.plugins.backgroundaudio": "1.0.1", "cordova-plugin-webserver": "1.0.3", "com.drifty.cordova.cameraroll": "0.2.1", @@ -563,10 +520,8 @@ "cordova-plugin-chrome-apps-sockets-udp": "1.2.2", "cordova-plugin-statusbar": "2.0.0", "fw-cordova-chromecast": "0.0.1", - "cordova-plugin-network-information": "1.1.0", "com.rd11.remote-controls": "1.0.1", "cc.fovea.cordova.purchase": "6.0.0", - "cordova-plugin-crosswalk-webview": "2.0.0", "cordova-plugin-app-version": "0.1.9", "cordova-plugin-x-socialsharing": "5.1.3", "cordova-plugin-actionsheet": "2.3.1", diff --git a/platforms/ios/platform_www/cordova_plugins.js b/platforms/ios/platform_www/cordova_plugins.js index f002755..36bb9e6 100644 --- a/platforms/ios/platform_www/cordova_plugins.js +++ b/platforms/ios/platform_www/cordova_plugins.js @@ -1,13 +1,5 @@ cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ - { - "file": "plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js", - "id": "com.hutchind.cordova.plugins.launcher.Launcher", - "pluginId": "com.hutchind.cordova.plugins.launcher", - "clobbers": [ - "plugins.launcher" - ] - }, { "file": "plugins/com.drifty.cordova.cameraroll/www/CameraRoll.js", "id": "com.drifty.cordova.cameraroll.CameraRoll", @@ -92,23 +84,6 @@ module.exports = [ "cordova.plugins.FWChromecast" ] }, - { - "file": "plugins/cordova-plugin-network-information/www/network.js", - "id": "cordova-plugin-network-information.network", - "pluginId": "cordova-plugin-network-information", - "clobbers": [ - "navigator.connection", - "navigator.network.connection" - ] - }, - { - "file": "plugins/cordova-plugin-network-information/www/Connection.js", - "id": "cordova-plugin-network-information.Connection", - "pluginId": "cordova-plugin-network-information", - "clobbers": [ - "Connection" - ] - }, { "file": "plugins/com.rd11.remote-controls/www/RemoteControls.js", "id": "com.rd11.remote-controls.RemoteControls", @@ -366,7 +341,6 @@ module.exports = [ module.exports.metadata = // TOP OF METADATA { - "com.hutchind.cordova.plugins.launcher": "0.2.2", "nl.x-services.plugins.backgroundaudio": "1.0.1", "cordova-plugin-webserver": "1.0.3", "com.drifty.cordova.cameraroll": "0.2.1", @@ -377,10 +351,8 @@ module.exports.metadata = "cordova-plugin-chrome-apps-sockets-udp": "1.2.2", "cordova-plugin-statusbar": "2.0.0", "fw-cordova-chromecast": "0.0.1", - "cordova-plugin-network-information": "1.1.0", "com.rd11.remote-controls": "1.0.1", "cc.fovea.cordova.purchase": "6.0.0", - "cordova-plugin-crosswalk-webview": "2.0.0", "cordova-plugin-app-version": "0.1.9", "cordova-plugin-x-socialsharing": "5.1.3", "cordova-plugin-actionsheet": "2.3.1", diff --git a/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/EventEmitter.js b/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/EventEmitter.js deleted file mode 100644 index ed5fa4a..0000000 --- a/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/EventEmitter.js +++ /dev/null @@ -1,449 +0,0 @@ -cordova.define("acidhax.cordova.chromecast.EventEmitter", function(require, exports, module) { /*! - * EventEmitter v4.2.11 - git.io/ee - * Unlicense - http://unlicense.org/ - * Oliver Caldwell - http://oli.me.uk/ - * @preserve - */ - - 'use strict'; - - /** - * Class for managing events. - * Can be extended to provide event functionality in other classes. - * - * @class EventEmitter Manages event registering and emitting. - */ - function EventEmitter() {} - - // Shortcuts to improve speed and size - var proto = EventEmitter.prototype; - - /** - * Finds the index of the listener for the event in its storage array. - * - * @param {Function[]} listeners Array of listeners to search through. - * @param {Function} listener Method to look for. - * @return {Number} Index of the specified listener, -1 if not found - * @api private - */ - function indexOfListener(listeners, listener) { - var i = listeners.length; - while (i--) { - if (listeners[i].listener === listener) { - return i; - } - } - - return -1; - } - - /** - * Alias a method while keeping the context correct, to allow for overwriting of target method. - * - * @param {String} name The name of the target method. - * @return {Function} The aliased method - * @api private - */ - function alias(name) { - return function aliasClosure() { - return this[name].apply(this, arguments); - }; - } - - /** - * Returns the listener array for the specified event. - * Will initialise the event object and listener arrays if required. - * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. - * Each property in the object response is an array of listener functions. - * - * @param {String|RegExp} evt Name of the event to return the listeners from. - * @return {Function[]|Object} All listener functions for the event. - */ - proto.getListeners = function getListeners(evt) { - var events = this._getEvents(); - var response; - var key; - - // Return a concatenated array of all matching events if - // the selector is a regular expression. - if (evt instanceof RegExp) { - response = {}; - for (key in events) { - if (events.hasOwnProperty(key) && evt.test(key)) { - response[key] = events[key]; - } - } - } - else { - response = events[evt] || (events[evt] = []); - } - - return response; - }; - - /** - * Takes a list of listener objects and flattens it into a list of listener functions. - * - * @param {Object[]} listeners Raw listener objects. - * @return {Function[]} Just the listener functions. - */ - proto.flattenListeners = function flattenListeners(listeners) { - var flatListeners = []; - var i; - - for (i = 0; i < listeners.length; i += 1) { - flatListeners.push(listeners[i].listener); - } - - return flatListeners; - }; - - /** - * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. - * - * @param {String|RegExp} evt Name of the event to return the listeners from. - * @return {Object} All listener functions for an event in an object. - */ - proto.getListenersAsObject = function getListenersAsObject(evt) { - var listeners = this.getListeners(evt); - var response; - - if (listeners instanceof Array) { - response = {}; - response[evt] = listeners; - } - - return response || listeners; - }; - - /** - * Adds a listener function to the specified event. - * The listener will not be added if it is a duplicate. - * If the listener returns true then it will be removed after it is called. - * If you pass a regular expression as the event name then the listener will be added to all events that match it. - * - * @param {String|RegExp} evt Name of the event to attach the listener to. - * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.addListener = function addListener(evt, listener) { - var listeners = this.getListenersAsObject(evt); - var listenerIsWrapped = typeof listener === 'object'; - var key; - - for (key in listeners) { - if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) { - listeners[key].push(listenerIsWrapped ? listener : { - listener: listener, - once: false - }); - } - } - - return this; - }; - - /** - * Alias of addListener - */ - proto.on = alias('addListener'); - - /** - * Semi-alias of addListener. It will add a listener that will be - * automatically removed after its first execution. - * - * @param {String|RegExp} evt Name of the event to attach the listener to. - * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.addOnceListener = function addOnceListener(evt, listener) { - return this.addListener(evt, { - listener: listener, - once: true - }); - }; - - /** - * Alias of addOnceListener. - */ - proto.once = alias('addOnceListener'); - - /** - * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. - * You need to tell it what event names should be matched by a regex. - * - * @param {String} evt Name of the event to create. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.defineEvent = function defineEvent(evt) { - this.getListeners(evt); - return this; - }; - - /** - * Uses defineEvent to define multiple events. - * - * @param {String[]} evts An array of event names to define. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.defineEvents = function defineEvents(evts) { - for (var i = 0; i < evts.length; i += 1) { - this.defineEvent(evts[i]); - } - return this; - }; - - /** - * Removes a listener function from the specified event. - * When passed a regular expression as the event name, it will remove the listener from all events that match it. - * - * @param {String|RegExp} evt Name of the event to remove the listener from. - * @param {Function} listener Method to remove from the event. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.removeListener = function removeListener(evt, listener) { - var listeners = this.getListenersAsObject(evt); - var index; - var key; - - for (key in listeners) { - if (listeners.hasOwnProperty(key)) { - index = indexOfListener(listeners[key], listener); - - if (index !== -1) { - listeners[key].splice(index, 1); - } - } - } - - return this; - }; - - /** - * Alias of removeListener - */ - proto.off = alias('removeListener'); - - /** - * Adds listeners in bulk using the manipulateListeners method. - * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. - * You can also pass it a regular expression to add the array of listeners to all events that match it. - * Yeah, this function does quite a bit. That's probably a bad thing. - * - * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. - * @param {Function[]} [listeners] An optional array of listener functions to add. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.addListeners = function addListeners(evt, listeners) { - // Pass through to manipulateListeners - return this.manipulateListeners(false, evt, listeners); - }; - - /** - * Removes listeners in bulk using the manipulateListeners method. - * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. - * You can also pass it an event name and an array of listeners to be removed. - * You can also pass it a regular expression to remove the listeners from all events that match it. - * - * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. - * @param {Function[]} [listeners] An optional array of listener functions to remove. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.removeListeners = function removeListeners(evt, listeners) { - // Pass through to manipulateListeners - return this.manipulateListeners(true, evt, listeners); - }; - - /** - * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. - * The first argument will determine if the listeners are removed (true) or added (false). - * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. - * You can also pass it an event name and an array of listeners to be added/removed. - * You can also pass it a regular expression to manipulate the listeners of all events that match it. - * - * @param {Boolean} remove True if you want to remove listeners, false if you want to add. - * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. - * @param {Function[]} [listeners] An optional array of listener functions to add/remove. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) { - var i; - var value; - var single = remove ? this.removeListener : this.addListener; - var multiple = remove ? this.removeListeners : this.addListeners; - - // If evt is an object then pass each of its properties to this method - if (typeof evt === 'object' && !(evt instanceof RegExp)) { - for (i in evt) { - if (evt.hasOwnProperty(i) && (value = evt[i])) { - // Pass the single listener straight through to the singular method - if (typeof value === 'function') { - single.call(this, i, value); - } - else { - // Otherwise pass back to the multiple function - multiple.call(this, i, value); - } - } - } - } - else { - // So evt must be a string - // And listeners must be an array of listeners - // Loop over it and pass each one to the multiple method - i = listeners.length; - while (i--) { - single.call(this, evt, listeners[i]); - } - } - - return this; - }; - - /** - * Removes all listeners from a specified event. - * If you do not specify an event then all listeners will be removed. - * That means every event will be emptied. - * You can also pass a regex to remove all events that match it. - * - * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.removeEvent = function removeEvent(evt) { - var type = typeof evt; - var events = this._getEvents(); - var key; - - // Remove different things depending on the state of evt - if (type === 'string') { - // Remove all listeners for the specified event - delete events[evt]; - } - else if (evt instanceof RegExp) { - // Remove all events matching the regex. - for (key in events) { - if (events.hasOwnProperty(key) && evt.test(key)) { - delete events[key]; - } - } - } - else { - // Remove all listeners in all events - delete this._events; - } - - return this; - }; - - /** - * Alias of removeEvent. - * - * Added to mirror the node API. - */ - proto.removeAllListeners = alias('removeEvent'); - - /** - * Emits an event of your choice. - * When emitted, every listener attached to that event will be executed. - * If you pass the optional argument array then those arguments will be passed to every listener upon execution. - * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. - * So they will not arrive within the array on the other side, they will be separate. - * You can also pass a regular expression to emit to all events that match it. - * - * @param {String|RegExp} evt Name of the event to emit and execute listeners for. - * @param {Array} [args] Optional array of arguments to be passed to each listener. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.emitEvent = function emitEvent(evt, args) { - var listeners = this.getListenersAsObject(evt); - var listener; - var i; - var key; - var response; - - for (key in listeners) { - if (listeners.hasOwnProperty(key)) { - i = listeners[key].length; - - while (i--) { - // If the listener returns true then it shall be removed from the event - // The function is executed either with a basic call or an apply if there is an args array - listener = listeners[key][i]; - - if (listener.once === true) { - this.removeListener(evt, listener.listener); - } - - response = listener.listener.apply(this, args || []); - - if (response === this._getOnceReturnValue()) { - this.removeListener(evt, listener.listener); - } - } - } - } - - return this; - }; - - /** - * Alias of emitEvent - */ - proto.trigger = alias('emitEvent'); - - /** - * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. - * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. - * - * @param {String|RegExp} evt Name of the event to emit and execute listeners for. - * @param {...*} Optional additional arguments to be passed to each listener. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.emit = function emit(evt) { - var args = Array.prototype.slice.call(arguments, 1); - return this.emitEvent(evt, args); - }; - - /** - * Sets the current value to check against when executing listeners. If a - * listeners return value matches the one set here then it will be removed - * after execution. This value defaults to true. - * - * @param {*} value The new value to check for when executing listeners. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.setOnceReturnValue = function setOnceReturnValue(value) { - this._onceReturnValue = value; - return this; - }; - - /** - * Fetches the current value to check against when executing listeners. If - * the listeners return value matches this one then it should be removed - * automatically. It will return true by default. - * - * @return {*|Boolean} The current value to check for or the default, true. - * @api private - */ - proto._getOnceReturnValue = function _getOnceReturnValue() { - if (this.hasOwnProperty('_onceReturnValue')) { - return this._onceReturnValue; - } - else { - return true; - } - }; - - /** - * Fetches the events object and creates one if required. - * - * @return {Object} The events storage object. - * @api private - */ - proto._getEvents = function _getEvents() { - return this._events || (this._events = {}); - }; - - module.exports = EventEmitter; - -}); diff --git a/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/chrome.cast.js b/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/chrome.cast.js deleted file mode 100644 index b955b90..0000000 --- a/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/chrome.cast.js +++ /dev/null @@ -1,1200 +0,0 @@ -cordova.define("acidhax.cordova.chromecast.ChromecastApi", function(require, exports, module) { var EventEmitter = require('acidhax.cordova.chromecast.EventEmitter'); - -var chrome = {}; -chrome.cast = { - - /** - * The API version. - * @type {Array} - */ - VERSION: [1, 1], - - /** - * Describes availability of a Cast receiver. - * AVAILABLE: At least one receiver is available that is compatible with the session request. - * UNAVAILABLE: No receivers are available. - * @type {Object} - */ - ReceiverAvailability: { AVAILABLE: "available", UNAVAILABLE: "unavailable" }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.ReceiverType - * CAST: - * DIAL: - * CUSTOM: - * @type {Object} - */ - ReceiverType: { CAST: "cast", DIAL: "dial", CUSTOM: "custom" }, - - - /** - * Describes a sender application platform. - * CHROME: - * IOS: - * ANDROID: - * @type {Object} - */ - SenderPlatform: { CHROME: "chrome", IOS: "ios", ANDROID: "android" }, - - /** - * Auto-join policy determines when the SDK will automatically connect a sender application to an existing session after API initialization. - * ORIGIN_SCOPED: Automatically connects when the session was started with the same appId and the same page origin (regardless of tab). - * PAGE_SCOPED: No automatic connection. - * TAB_AND_ORIGIN_SCOPED: Automatically connects when the session was started with the same appId, in the same tab and page origin. - * @type {Object} - */ - AutoJoinPolicy: { TAB_AND_ORIGIN_SCOPED: "tab_and_origin_scoped", ORIGIN_SCOPED: "origin_scoped", PAGE_SCOPED: "page_scoped" }, - - /** - * Capabilities that are supported by the receiver device. - * AUDIO_IN: The receiver supports audio input (microphone). - * AUDIO_OUT: The receiver supports audio output. - * VIDEO_IN: The receiver supports video input (camera). - * VIDEO_OUT: The receiver supports video output. - * @type {Object} - */ - Capability: { VIDEO_OUT: "video_out", AUDIO_OUT: "audio_out", VIDEO_IN: "video_in", AUDIO_IN: "audio_in" }, - - /** - * Default action policy determines when the SDK will automatically create a session after initializing the API. This also controls the default action for the tab in the extension popup. - * CAST_THIS_TAB: No automatic launch is done after initializing the API, even if the tab is being cast. - * CREATE_SESSION: If the tab containing the app is being casted when the API initializes, the SDK stops tab casting and automatically launches the app. - * @type {Object} - */ - DefaultActionPolicy: { CREATE_SESSION: "create_session", CAST_THIS_TAB: "cast_this_tab" }, - - /** - * Errors that may be returned by the SDK. - * API_NOT_INITIALIZED: The API is not initialized. - * CANCEL: The operation was canceled by the user. - * CHANNEL_ERROR: A channel to the receiver is not available. - * EXTENSION_MISSING: The Cast extension is not available. - * EXTENSION_NOT_COMPATIBLE: The API script is not compatible with the installed Cast extension. - * INVALID_PARAMETER: The parameters to the operation were not valid. - * LOAD_MEDIA_FAILED: Load media failed. - * RECEIVER_UNAVAILABLE: No receiver was compatible with the session request. - * SESSION_ERROR: A session could not be created, or a session was invalid. - * TIMEOUT: The operation timed out. - * @type {Object} - */ - ErrorCode: { - API_NOT_INITIALIZED: "api_not_initialized", - CANCEL: "cancel", - CHANNEL_ERROR: "channel_error", - EXTENSION_MISSING: "extension_missing", - EXTENSION_NOT_COMPATIBLE: "extension_not_compatible", - INVALID_PARAMETER: "invalid_parameter", - LOAD_MEDIA_FAILED: "load_media_failed", - RECEIVER_UNAVAILABLE: "receiver_unavailable", - SESSION_ERROR: "session_error", - TIMEOUT: "timeout", - UNKNOWN: "unknown", - NOT_IMPLEMENTED: "not_implemented" - }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.timeout - * @type {Object} - */ - timeout: { - requestSession: 10000, - sendCustomMessage: 3000, - setReceiverVolume: 3000, - stopSession: 3000 - }, - - /** - * Flag for clients to check whether the API is loaded. - * @type {Boolean} - */ - isAvailable: false, - - - // CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES - - /** - * [ApiConfig description] - * @param {chrome.cast.SessionRequest} sessionRequest Describes the session to launch or the session to connect. - * @param {function} sessionListener Listener invoked when a session is created or connected by the SDK. - * @param {function} receiverListener Function invoked when the availability of a Cast receiver that supports the application in sessionRequest is known or changes. - * @param {chrome.cast.AutoJoinPolicy} autoJoinPolicy Determines whether the SDK will automatically connect to a running session after initialization. - * @param {chrome.cast.DefaultActionPolicy} defaultActionPolicy Requests whether the application should be launched on API initialization when the tab is already being cast. - */ - ApiConfig: function (sessionRequest, sessionListener, receiverListener, autoJoinPolicy, defaultActionPolicy) { - this.sessionRequest = sessionRequest; - this.sessionListener = sessionListener; - this.receiverListener = receiverListener; - this.autoJoinPolicy = autoJoinPolicy || chrome.cast.AutoJoinPolicy.TAB_AND_ORIGIN_SCOPED; - this.defaultActionPolicy = defaultActionPolicy || chrome.cast.DefaultActionPolicy.CREATE_SESSION; - }, - - /** - * Describes the receiver running an application. Normally, these objects should not be created by the client. - * @param {string} label An identifier for the receiver that is unique to the browser profile and the origin of the API client. - * @param {string} friendlyName The user given name for the receiver. - * @param {chrome.cast.Capability[]} capabilities The capabilities of the receiver, for example audio and video. - * @param {chrome.cast.Volume} volume The current volume of the receiver. - */ - Receiver: function (label, friendlyName, capabilities, volume) { - this.label = label; - this.friendlyName = friendlyName; - this.capabilities = capabilities || []; - this.volume = volume || null; - this.receiverType = chrome.cast.ReceiverType.CAST; - this.isActiveInput = null; - }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.DialRequest - * @param {[type]} appName [description] - * @param {[type]} launchParameter [description] - */ - DialRequest: function (appName, launchParameter) { - this.appName = appName; - this.launchParameter = launchParameter; - }, - - /** - * A request to start or connect to a session. - * @param {string} appId The receiver application id. - * @param {chrome.cast.Capability[]} capabilities Capabilities required of the receiver device. - * @property {chrome.cast.DialRequest} dialRequest If given, the SDK will also discover DIAL devices that support the DIAL application given in the dialRequest. - */ - SessionRequest: function (appId, capabilities) { - this.appId = appId; - this.capabilities = capabilities || [chrome.cast.Capability.VIDEO_OUT, chrome.cast.Capability.AUDIO_OUT]; - this.dialRequest = null; - }, - - /** - * Describes an error returned by the API. Normally, these objects should not be created by the client. - * @param {chrome.cast.ErrorCode} code The error code. - * @param {string} description Human readable description of the error. - * @param {Object} details Details specific to the error. - */ - Error: function (code, description, details) { - this.code = code; - this.description = description || null; - this.details = details || null; - }, - - /** - * An image that describes a receiver application or media item. This could be an application icon, cover art, or a thumbnail. - * @param {string} url The URL to the image. - * @property {number} height The height of the image - * @property {number} width The width of the image - */ - Image: function (url) { - this.url = url; - this.width = this.height = null; - }, - - /** - * Describes a sender application. Normally, these objects should not be created by the client. - * @param {chrome.cast.SenderPlatform} platform The supported platform. - * @property {string} packageId The identifier or URL for the application in the respective platform's app store. - * @property {string} url URL or intent to launch the application. - */ - SenderApplication: function (platform) { - this.platform = platform; - this.packageId = this.url = null; - }, - - /** - * The volume of a device or media stream. - * @param {number} level The current volume level as a value between 0.0 and 1.0. - * @param {boolean} muted Whether the receiver is muted, independent of the volume level. - */ - Volume: function (level, muted) { - this.level = level || null; - this.muted = null; - if (muted === true || muted === false) { - this.muted = muted; - } - }, - - - // media package - media: { - /** - * The default receiver app. - */ - DEFAULT_MEDIA_RECEIVER_APP_ID: 'CC1AD845', - - /** - * Possible states of the media player. - * BUFFERING: Player is in PLAY mode but not actively playing content. currentTime will not change. - * IDLE: No media is loaded into the player. - * PAUSED: The media is not playing. - * PLAYING: The media is playing. - * @type {Object} - */ - PlayerState: { IDLE: "IDLE", PLAYING: "PLAYING", PAUSED: "PAUSED", BUFFERING: "BUFFERING" }, - - /** - * States of the media player after resuming. - * PLAYBACK_PAUSE: Force media to pause. - * PLAYBACK_START: Force media to start. - * @type {Object} - */ - ResumeState: { PLAYBACK_START: "PLAYBACK_START", PLAYBACK_PAUSE: "PLAYBACK_PAUSE" }, - - /** - * Possible media commands supported by the receiver application. - * @type {Object} - */ - MediaCommand: { PAUSE: "pause", SEEK: "seek", STREAM_VOLUME: "stream_volume", STREAM_MUTE: "stream_mute" }, - - /** - * Possible types of media metadata. - * GENERIC: Generic template suitable for most media types. Used by chrome.cast.media.GenericMediaMetadata. - * MOVIE: A full length movie. Used by chrome.cast.media.MovieMediaMetadata. - * MUSIC_TRACK: A music track. Used by chrome.cast.media.MusicTrackMediaMetadata. - * PHOTO: Photo. Used by chrome.cast.media.PhotoMediaMetadata. - * TV_SHOW: An episode of a TV series. Used by chrome.cast.media.TvShowMediaMetadata. - * @type {Object} - */ - MetadataType: { GENERIC: 0, TV_SHOW: 1, MOVIE: 2, MUSIC_TRACK: 3, PHOTO: 4 }, - - /** - * Possible media stream types. - * BUFFERED: Stored media streamed from an existing data store. - * LIVE: Live media generated on the fly. - * OTHER: None of the above. - * @type {Object} - */ - StreamType: { BUFFERED: 'buffered', LIVE: 'live', OTHER: 'other' }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.timeout - * @type {Object} - */ - timeout: { - load: 0, - ob: 0, - pause: 0, - play: 0, - seek: 0, - setVolume: 0, - stop: 0 - }, - - - // CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES - - /** - * A request to load new media into the player. - * @param {chrome.cast.media.MediaInfo} media Media description. - * @property {boolean} autoplay Whether the media will automatically play. - * @property {number} currentTime Seconds from the beginning of the media to start playback. - * @property {Object} customData Custom data for the receiver application. - */ - LoadRequest: function (media) { - this.type = 'LOAD'; - this.sessionId = this.requestId = this.customData = this.currentTime = null; - this.media = media; - this.autoplay = !0; - }, - - /** - * A request to play the currently paused media. - * @property {Object} customData Custom data for the receiver application. - */ - PlayRequest: function () { - this.customData = null; - }, - - /** - * A request to seek the current media. - * @property {number} currentTime The new current time for the media, in seconds after the start of the media. - * @property {chrome.cast.media.ResumeState} resumeState The desired media player state after the seek is complete. - * @property {Object} customData Custom data for the receiver application. - */ - SeekRequest: function () { - this.customData = this.resumeState = this.currentTime = null; - }, - - /** - * A request to set the stream volume of the playing media. - * @param {chrome.cast.Volume} volume The new volume of the stream. - * @property {Object} customData Custom data for the receiver application. - */ - VolumeRequest: function (volume) { - this.volume = volume; - this.customData = null; - }, - - /** - * A request to stop the media player. - * @property {Object} customData Custom data for the receiver application. - */ - StopRequest: function () { - this.customData = null; - }, - - /** - * A request to pause the currently playing media. - * @property {Object} customData Custom data for the receiver application. - */ - PauseRequest: function () { - this.customData = null; - }, - - /** - * A generic media description. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} releaseDate ISO 8601 date and/or time when the content was released, e.g. - * @property {number} releaseYear Integer year when the content was released. - * @property {string} subtitle Content subtitle. - * @property {string} title Content title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - GenericMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.GENERIC; - this.releaseDate = this.releaseYear = this.images = this.subtitle = this.title = null; - }, - - /** - * A movie media description. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} releaseDate ISO 8601 date and/or time when the content was released, e.g. - * @property {number} releaseYear Integer year when the content was released. - * @property {string} studio Movie studio - * @property {string} subtitle Content subtitle. - * @property {string} title Content title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - MovieMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.MOVIE; - this.releaseDate = this.releaseYear = this.images = this.subtitle = this.studio = this.title = null; - }, - - /** - * A music track media description. - * @property {string} albumArtist Album artist name. - * @property {string} albumName Album name. - * @property {string} artist Track artist name. - * @property {string} artistName Track artist name. - * @property {string} composer Track composer name. - * @property {number} discNumber Disc number. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} releaseDate ISO 8601 date when the track was released, e.g. - * @property {number} releaseYear Integer year when the album was released. - * @property {string} songName Track name. - * @property {string} title Track title. - * @property {number} trackNumber Track number in album. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - MusicTrackMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.MUSIC_TRACK; - this.releaseDate = this.releaseYear = this.images = this.discNumber = this.trackNumber = this.artistName = this.songName = this.composer = this.artist = this.albumArtist = this.title = this.albumName = null; - }, - - /** - * A photo media description. - * @property {string} artist Name of the photographer. - * @property {string} creationDateTime ISO 8601 date and time the photo was taken, e.g. - * @property {number} height Photo height, in pixels. - * @property {chrome.cast.Image[]} images Images associated with the content. - * @property {number} latitude Latitude. - * @property {string} location Location where the photo was taken. - * @property {number} longitude Longitude. - * @property {string} title Photo title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - * @property {number} width Photo width, in pixels. - */ - PhotoMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.PHOTO; - this.creationDateTime = this.height = this.width = this.longitude = this.latitude = this.images = this.location = this.artist = this.title = null; - }, - - /** - * [TvShowMediaMetadata description] - * @property {number} episode TV episode number. - * @property {number} episodeNumber TV episode number. - * @property {string} episodeTitle TV episode title. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} originalAirdate ISO 8601 date when the episode originally aired, e.g. - * @property {number} releaseYear Integer year when the content was released. - * @property {number} season TV episode season. - * @property {number} seasonNumber TV episode season. - * @property {string} seriesTitle TV series title. - * @property {string} title TV episode title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - TvShowMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.TV_SHOW; - this.originalAirdate = this.releaseYear = this.images = this.episode = this.episodeNumber = this.season = this.seasonNumber = this.episodeTitle = this.title = this.seriesTitle = null; - }, - - /** - * Describes a media item. - * @param {string} contentId Identifies the content. - * @param {string} contentType MIME content type of the media. - * @property {Object} customData Custom data set by the receiver application. - * @property {number} duration Duration of the content, in seconds. - * @property {any type} metadata Describes the media content. - * @property {chrome.cast.media.StreamType} streamType The type of media stream. - */ - MediaInfo: function (contentId, contentType) { - this.contentId = contentId; - this.streamType = chrome.cast.media.StreamType.BUFFERED; - this.contentType = contentType; - this.customData = this.duration = this.metadata = null; - } - } -}; - -var _sessionRequest = null; -var _autoJoinPolicy = null; -var _defaultActionPolicy = null; -var _receiverListener = null; -var _sessionListener = null; - -var _sessions = {}; -var _currentMedia = null; -var _routeListEl = document.createElement('ul'); -_routeListEl.classList.add('route-list'); -var _routeList = {}; -var _routeRefreshInterval = null; - -var _receiverAvailable = false; - -/** - * Initializes the API. Note that either successCallback and errorCallback will be invoked once the API has finished initialization. - * The sessionListener and receiverListener may be invoked at any time afterwards, and possibly more than once. - * @param {chrome.cast.ApiConfig} apiConfig The object with parameters to initialize the API. Must not be null. - * @param {function} successCallback - * @param {function} errorCallback - */ -chrome.cast.initialize = function (apiConfig, successCallback, errorCallback) { - if (!chrome.cast.isAvailable) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - _sessionListener = apiConfig.sessionListener; - _autoJoinPolicy = apiConfig.autoJoinPolicy; - _defaultActionPolicy = apiConfig.defaultActionPolicy; - _receiverListener = apiConfig.receiverListener; - _sessionRequest = apiConfig.sessionRequest; - - execute('initialize', _sessionRequest.appId, _autoJoinPolicy, _defaultActionPolicy, function(err) { - if (!err) { - successCallback(); - - clearInterval(_routeRefreshInterval); - _routeRefreshInterval = setInterval(function() { - execute('emitAllRoutes'); - }, 15000); - - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Requests that a receiver application session be created or joined. - * By default, the SessionRequest passed to the API at initialization time is used; - * this may be overridden by passing a different session request in opt_sessionRequest. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, INVALID_PARAMETER, API_NOT_INITIALIZED, CANCEL, CHANNEL_ERROR, SESSION_ERROR, RECEIVER_UNAVAILABLE, and EXTENSION_MISSING. Note that the timeout timer starts after users select a receiver. Selecting a receiver requires user's action, which has no timeout. - * @param {chrome.cast.SessionRequest} opt_sessionRequest - */ -chrome.cast.requestSession = function (successCallback, errorCallback, opt_sessionRequest) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - if (_receiverAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.RECEIVER_UNAVAILABLE, 'No receiver was compatible with the session request.', {})); - return; - } - - execute('requestSession', function(err, obj) { - if (!err) { - var sessionId = obj.sessionId; - var appId = obj.appId; - var displayName = obj.displayName; - var appImages = obj.appImages || []; - var receiver = new chrome.cast.Receiver(obj.receiver.label, obj.receiver.friendlyName, obj.receiver.capabilities || [], obj.volume || null); - - var session = _sessions[sessionId] = new chrome.cast.Session(sessionId, appId, displayName, appImages, receiver); - - if (obj.media && obj.media.sessionId) - { - _currentMedia = new chrome.cast.media.Media(sessionId, obj.media.mediaSessionId); - _currentMedia.currentTime = obj.media.currentTime; - _currentMedia.playerState = obj.media.playerState; - _currentMedia.media = obj.media.media; - session.media[0] = _currentMedia; - } - - successCallback(session); - _sessionListener(session); /*Fix - Already has a sessionListener*/ - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Sets custom receiver list - * @param {chrome.cast.Receiver[]} receivers The new list. Must not be null. - * @param {function} successCallback - * @param {function} errorCallback - */ -chrome.cast.setCustomReceivers = function (receivers, successCallback, errorCallback) { - // TODO: Implement -}; - - - - -/** SESSION SESSION SESSION SESSION SESSION SESSION SESSION SESSION **/ - - - - -/** - * Describes the state of a currently running Cast application. Normally, these objects should not be created by the client. - * @param {string} sessionId Uniquely identifies this instance of the receiver application. - * @param {string} appId The identifer of the Cast application. - * @param {string} displayName The human-readable name of the Cast application, for example, "YouTube". - * @param {chrome.cast.Image[]} appImages Array of images available describing the application. - * @param {chrome.cast.Receiver} receiver The receiver that is running the application. - * - * @property {Object} customData Custom data set by the receiver application. - * @property {chrome.cast.media.Media} media The media that belong to this Cast session, including those loaded by other senders. - * @property {Object[]} namespaces A list of the namespaces supported by the receiver application. - * @property {chrome.cast.SenderApplication} senderApps The sender applications supported by the receiver application. - * @property {string} statusText Descriptive text for the current application content, for example “My Wedding Slideshow”. - */ -chrome.cast.Session = function(sessionId, appId, displayName, appImages, receiver) { - EventEmitter.call(this); - this.sessionId = sessionId; - this.appId = appId; - this.displayName = displayName; - this.appImages = appImages || []; - this.receiver = receiver; - this.media = []; -}; -chrome.cast.Session.prototype = Object.create(EventEmitter.prototype); - -/** - * Sets the receiver volume. - * @param {number} newLevel The new volume level between 0.0 and 1.0. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.setReceiverVolumeLevel = function (newLevel, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('setReceiverVolumeLevel', newLevel, function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - - -/** - * Sets the receiver volume. - * @param {boolean} muted The new muted status. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.setReceiverMuted = function (muted, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('setReceiverMuted', muted, function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Stops the running receiver application associated with the session. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.stop = function (successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('sessionStop', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Leaves the current session. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.leave = function (successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('sessionLeave', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Sends a message to the receiver application on the given namespace. - * The successCallback is invoked when the message has been submitted to the messaging channel. - * Delivery to the receiver application is best effort and not guaranteed. - * @param {string} namespace - * @param {Object or string} message Must not be null - * @param {[type]} successCallback Invoked when the message has been sent. Must not be null. - * @param {[type]} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING - */ -chrome.cast.Session.prototype.sendMessage = function (namespace, message, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - if (typeof message === 'object') { - message = JSON.stringify(message); - } - execute('sendMessage', namespace, message, function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Request to load media. Must not be null. - * @param {chrome.cast.media.LoadRequest} loadRequest Request to load media. Must not be null. - * @param {function} successCallback Invoked with the loaded Media on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.loadMedia = function (loadRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - var self = this; - - var mediaInfo = loadRequest.media; - execute('loadMedia', mediaInfo.contentId, mediaInfo.contentType, mediaInfo.duration || 0.0, mediaInfo.streamType, loadRequest.autoplay || false, loadRequest.currentTime || 0, mediaInfo.metadata, function(err, obj) { - if (!err) { - _currentMedia = new chrome.cast.media.Media(self.sessionId, obj.mediaSessionId); - _currentMedia.media = mediaInfo; - _currentMedia.media.duration = obj.media.duration; - _currentMedia.currentTime = obj.currentTime /* ??? */ - - // TODO: Fill in the rest of the media properties - - successCallback(_currentMedia); - - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Adds a listener that is invoked when the status of the Session has changed. - * Changes to the following properties will trigger the listener: statusText, namespaces, customData, and the volume of the receiver. - * The callback will be invoked with 'true' (isAlive) parameter. - * When this session is ended, the callback will be invoked with 'false' (isAlive); - * @param {function} listener The listener to add. - */ -chrome.cast.Session.prototype.addUpdateListener = function (listener) { - this.on('_sessionUpdated', listener); -}; - -/** - * Removes a previously added listener for this Session. - * @param {function} listener The listener to remove. - */ -chrome.cast.Session.prototype.removeUpdateListener = function (listener) { - this.removeListener('_sessionUpdated', listener); -}; - -/** - * Adds a listener that is invoked when a message is received from the receiver application. - * The listener is invoked with the the namespace as the first argument and the message as the second argument. - * @param {string} namespace The namespace to listen on. - * @param {function} listener The listener to add. - */ -chrome.cast.Session.prototype.addMessageListener = function (namespace, listener) { - execute('addMessageListener', namespace); - this.on('message:' + namespace, listener); -}; - -/** - * Removes a previously added listener for messages. - * @param {string} namespace The namespace that is listened to. - * @param {function} listener The listener to remove. - */ -chrome.cast.Session.prototype.removeMessageListener = function (namespace, listener) { - this.removeListener('message:' + namespace, listener); -}; - -/** - * Adds a listener that is invoked when a media session is created by another sender. - * @param {function} listener The listener to add. - */ -chrome.cast.Session.prototype.addMediaListener = function (listener) { - this.on('_mediaListener', listener); -}; - -/** - * Removes a listener that was previously added with addMediaListener. - * @param {function} listener The listener to remove. - */ -chrome.cast.Session.prototype.removeMediaListener = function (listener) { - this.removeListener('_mediaListener', listener); -}; - - -chrome.cast.Session.prototype._update = function(isAlive, obj) { - - this.appId = obj.appId; - this.appImages = obj.appImages; - this.displayName = obj.displayName; - if (obj.receiver) { - if (!this.receiver) { - this.receiver = new chrome.cast.Receiver(null, null, null, null); - } - this.receiver.friendlyName = obj.receiver.friendlyName; - this.receiver.label = obj.receiver.label; - - if (obj.receiver.volume) { - this.receiver.volume = new chrome.cast.Volume(obj.receiver.volume.level, obj.receiver.volume.muted); - } - } - - this.emit('_sessionUpdated', isAlive); -}; - - - - - -/* MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA */ -/** - * Represents a media item that has been loaded into the receiver application. - * @param {string} sessionId Identifies the session that is hosting the media. - * @param {number} mediaSessionId Identifies the media item. - * - * @property {Object} customData Custom data set by the receiver application. - * @property {number} currentTime The current playback position in seconds since the start of the media. - * @property {chrome.cast.media.MediaInfo} media Media description. - * @property {number} playbackRate The playback rate. - * @property {chrome.cast.media.PlayerState} playerState The player state. - * @property {chrome.cast.media.MediaCommand[]} supportedMediaCommands The media commands supported by the media player. - * @property {chrome.cast.Volume} volume The media stream volume. - * @property {string} idleReason Reason for idling - */ -chrome.cast.media.Media = function(sessionId, mediaSessionId) { - EventEmitter.call(this); - this.sessionId = sessionId; - this.mediaSessionId = mediaSessionId; - this.currentTime = 0; - this.playbackRate = 1; - this.playerState = chrome.cast.media.PlayerState.BUFFERING; - this.supportedMediaCommands = [ - chrome.cast.media.MediaCommand.PAUSE, - chrome.cast.media.MediaCommand.SEEK, - chrome.cast.media.MediaCommand.STREAM_VOLUME, - chrome.cast.media.MediaCommand.STREAM_MUTE - ]; - this.volume = new chrome.cast.Volume(1, false); - this._lastUpdatedTime = Date.now(); - this.media = {}; -}; -chrome.cast.media.Media.prototype = Object.create(EventEmitter.prototype); - -/** - * Plays the media item. - * @param {chrome.cast.media.PlayRequest} playRequest The optional media play request. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.play = function (playRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaPlay', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Pauses the media item. - * @param {chrome.cast.media.PauseRequest} pauseRequest The optional media pause request. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.pause = function (pauseRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaPause', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Seeks the media item. - * @param {chrome.cast.media.SeekRequest} seekRequest The media seek request. Must not be null. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.seek = function (seekRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaSeek', seekRequest.currentTime, seekRequest.resumeState || "", function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }) -}; - -/** - * Stops the media player. - * @param {chrome.cast.media.StopRequest} stopRequest The media stop request. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.stop = function (stopRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaStop', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }) -}; - -/** - * Sets the media stream volume. At least one of volumeRequest.level or volumeRequest.muted must be set. Changing the mute state does not affect the volume level, and vice versa. - * @param {chrome.cast.media.VolumeRequest} volumeRequest The set volume request. Must not be null. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.setVolume = function (volumeRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - var args = []; - - if (volumeRequest.volume.level !== null) { - args.push('setMediaVolume'); - args.push(volumeRequest.volume.level); - } else if (volumeRequest.volume.muted !== null) { - args.push('setMediaMuted'); - args.push(volumeRequest.volume.muted); - } - - if (args.length < 2) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.INVALID_PARAMETER), 'Invalid request.', {}); - } else { - args.push(function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); - - execute.apply(null, args); - } -}; - -/** - * Determines whether the media player supports the given media command. - * @param {chrome.cast.media.MediaCommand} command The command to query. Must not be null. - * @returns {boolean} True if the player supports the command. - */ -chrome.cast.media.Media.prototype.supportsCommand = function (command) { - return this.supportsCommands.indexOf(command) > -1; -}; - -/** - * Estimates the current playback position. - * @returns {number} number An estimate of the current playback position in seconds since the start of the media. - */ -chrome.cast.media.Media.prototype.getEstimatedTime = function () { - if (this.playerState === chrome.cast.media.PlayerState.PLAYING) { - var elapsed = (Date.now() - this._lastUpdatedTime) / 1000; - var estimatedTime = this.currentTime + elapsed; - - return estimatedTime; - } else { - return this.currentTime; - } -}; - -/** - * Adds a listener that is invoked when the status of the media has changed. - * Changes to the following properties will trigger the listener: currentTime, volume, metadata, playbackRate, playerState, customData. - * @param {function} listener The listener to add. The parameter indicates whether the Media object is still alive. - */ -chrome.cast.media.Media.prototype.addUpdateListener = function (listener) { - this.on('_mediaUpdated', listener); -}; - -/** - * Removes a previously added listener for this Media. - * @param {function} listener The listener to remove. - */ -chrome.cast.media.Media.prototype.removeUpdateListener = function (listener) { - this.removeListener('_mediaUpdated', listener); -}; - -chrome.cast.media.Media.prototype._update = function(isAlive, obj) { - this.currentTime = obj.currentTime || this.currentTime; - this.idleReason = obj.idleReason || this.idleReason; - this.sessionId = obj.sessionId || this.sessionId; - this.mediaSessionId = obj.mediaSessionId || this.mediaSessionId; - this.playbackRate = obj.playbackRate || this.playbackRate; - this.playerState = obj.playerState || this.playerState; - - if (obj.media && obj.media.duration) { - this.media.duration = obj.media.duration || this.media.duration; - this.media.streamType = obj.media.streamType || this.media.streamType; - } - - this.volume.level = obj.volume.level; - this.volume.muted = obj.volume.muted; - - this._lastUpdatedTime = Date.now(); - - this.emit('_mediaUpdated', isAlive); -}; - - -function createRouteElement(route) { - var el = document.createElement('li'); - el.classList.add('route'); - el.addEventListener('touchstart', onRouteClick); - el.textContent = route.name; - el.setAttribute('data-routeid', route.id); - return el; -} - -function onRouteClick() { - var id = this.getAttribute('data-routeid'); - - if (id) { - try { - chrome.cast._emitConnecting(); - } catch(e) { - console.error('Error in connectingListener', e); - } - - execute('selectRoute', id, function(err, obj) { - var sessionId = obj.sessionId; - var appId = obj.appId; - var displayName = obj.displayName; - var appImages = obj.appImages || []; - var receiver = new chrome.cast.Receiver(obj.receiver.label, obj.receiver.friendlyName, obj.receiver.capabilities || [], obj.volume || null); - - var session = _sessions[sessionId] = new chrome.cast.Session(sessionId, appId, displayName, appImages, receiver); - - _sessionListener && _sessionListener(session); - }); - } -} - -chrome.cast.getRouteListElement = function() { - return _routeListEl; -}; - - -var _connectingListeners = []; -chrome.cast.addConnectingListener = function(cb) { - _connectingListeners.push(cb); -}; - -chrome.cast.removeConnectingListener = function(cb) { - if (_connectingListeners.indexOf(cb) > -1) { - _connectingListeners.splice(_connectingListeners.indexOf(cb), 1); - } -}; - -chrome.cast._emitConnecting = function() { - for (var n = 0; n < _connectingListeners.length; n++) { - _connectingListeners[n](); - } -}; - -chrome.cast._ = { - receiverUnavailable: function() { - _receiverListener(chrome.cast.ReceiverAvailability.UNAVAILABLE); - _receiverAvailable = false; - }, - receiverAvailable: function() { - _receiverListener(chrome.cast.ReceiverAvailability.AVAILABLE); - _receiverAvailable = true; - }, - routeAdded: function(route) { - if (!_routeList[route.id]) { - route.el = createRouteElement(route); - _routeList[route.id] = route; - - _routeListEl.appendChild(route.el); - } - }, - routeRemoved: function(route) { - if (_routeList[route.id]) { - _routeList[route.id].el.remove(); - delete _routeList[route.id]; - } - }, - sessionUpdated: function(isAlive, session) { - if (session && session.sessionId && _sessions[session.sessionId]) { - _sessions[session.sessionId]._update(isAlive, session); - } - }, - mediaUpdated: function(isAlive, media) { - if (media && media.mediaSessionId !== undefined && _currentMedia) { - _currentMedia._update(isAlive, media); - } - }, - mediaLoaded: function(isAlive, media) { - if (_sessions[media.sessionId]) { - - if (!_currentMedia) - { - _currentMedia = new chrome.cast.media.Media(media.sessionId, media.mediaSessionId); - } - _currentMedia._update(isAlive, media); - _sessions[media.sessionId].emit('_mediaListener', _currentMedia); - } else { - console.log('mediaLoaded --- but there is no session tied to it', media); - } - }, - sessionJoined: function(obj) { - var sessionId = obj.sessionId; - var appId = obj.appId; - var displayName = obj.displayName; - var appImages = obj.appImages || []; - var receiver = new chrome.cast.Receiver(obj.receiver.label, obj.receiver.friendlyName, obj.receiver.capabilities || [], obj.volume || null); - - var session = _sessions[sessionId] = new chrome.cast.Session(sessionId, appId, displayName, appImages, receiver); - - _sessionListener && _sessionListener(session); - }, - onMessage: function(sessionId, namespace, message) { - if (_sessions[sessionId]) { - _sessions[sessionId].emit('message:' + namespace, namespace, message); - } - } -}; - - -module.exports = chrome.cast; - -function execute (action) { - var args = [].slice.call(arguments); - args.shift(); - var callback; - if (args[args.length-1] instanceof Function) { - callback = args.pop(); - } - cordova.exec(function (result) { callback && callback(null, result); }, function(err) { callback && callback(err); }, "Chromecast", action, args); -} - -function handleError(err, callback) { - var errorCode = chrome.cast.ErrorCode.UNKNOWN; - var errorDescription = err; - var errorData = {}; - - err = err || ""; - if (err.toUpperCase() === 'TIMEOUT') { - errorCode = chrome.cast.ErrorCode.TIMEOUT; - errorDescription = 'The operation timed out.'; - } else if (err.toUpperCase() === 'INVALID_PARAMETER') { - errorCode = chrome.cast.ErrorCode.INVALID_PARAMETER; - errorDescription = 'The parameters to the operation were not valid.'; - } else if (err.toUpperCase() === 'RECEIVER_UNAVAILABLE') { - errorCode = chrome.cast.ErrorCode.RECEIVER_UNAVAILABLE; - errorDescription = 'No receiver was compatible with the session request.'; - } else if (err.toUpperCase() === 'CANCEL') { - errorCode = chrome.cast.ErrorCode.CANCEL; - errorDescription = 'The operation was canceled by the user.'; - } else if (err.toUpperCase() === 'CHANNEL_ERROR') { - errorCode = chrome.cast.ErrorCode.CHANNEL_ERROR; - errorDescription = 'A channel to the receiver is not available.'; - } else if (err.toUpperCase() === 'SESSION_ERROR') { - errorCode = chrome.cast.ErrorCode.SESSION_ERROR; - errorDescription = 'A session could not be created, or a session was invalid.'; - } - - var error = new Error(errorCode, errorDescription, errorData); - if (callback) { - callback(error); - } -} - - -execute('setup', function(err) { - if (!err) { - chrome.cast.isAvailable = true; - } else { - throw new Error('Unable to setup chrome.cast API' + err); - } -}); -}); diff --git a/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/tests/tests.js b/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/tests/tests.js deleted file mode 100644 index 473eabf..0000000 --- a/platforms/ios/platform_www/plugins/acidhax.cordova.chromecast/tests/tests.js +++ /dev/null @@ -1,286 +0,0 @@ -cordova.define("acidhax.cordova.chromecast.tests", function(require, exports, module) { exports.init = function() { - eval(require('org.apache.cordova.test-framework.test').injectJasmineInterface(this, 'this')); - jasmine.DEFAULT_TIMEOUT_INTERVAL = 25000; - - // var cc = require('acidhax.cordova.chromecast.Chromecast'); - - var applicationID = 'CC1AD845'; - var videoUrl = 'http://s3.nwgat.net/flvplayers3/bbb.mp4'; - - - describe('chrome.cast', function() { - - var _session = null; - var _receiverAvailability = null; - var _sessionUpdatedFired = false; - var _mediaUpdatedFired = false; - // var _currentMedia = null; - - it('should contain definitions', function(done) { - setTimeout(function() { - expect(chrome.cast.VERSION).toBeDefined(); - expect(chrome.cast.ReceiverAvailability).toBeDefined(); - expect(chrome.cast.ReceiverType).toBeDefined(); - expect(chrome.cast.SenderPlatform).toBeDefined(); - expect(chrome.cast.AutoJoinPolicy).toBeDefined(); - expect(chrome.cast.Capability).toBeDefined(); - expect(chrome.cast.DefaultActionPolicy).toBeDefined(); - expect(chrome.cast.ErrorCode).toBeDefined(); - expect(chrome.cast.timeout).toBeDefined(); - expect(chrome.cast.isAvailable).toBeDefined(); - expect(chrome.cast.ApiConfig).toBeDefined(); - expect(chrome.cast.Receiver).toBeDefined(); - expect(chrome.cast.DialRequest).toBeDefined(); - expect(chrome.cast.SessionRequest).toBeDefined(); - expect(chrome.cast.Error).toBeDefined(); - expect(chrome.cast.Image).toBeDefined(); - expect(chrome.cast.SenderApplication).toBeDefined(); - expect(chrome.cast.Volume).toBeDefined(); - expect(chrome.cast.media).toBeDefined(); - expect(chrome.cast.initialize).toBeDefined(); - expect(chrome.cast.requestSession).toBeDefined(); - expect(chrome.cast.setCustomReceivers).toBeDefined(); - expect(chrome.cast.Session).toBeDefined(); - expect(chrome.cast.media.PlayerState).toBeDefined(); - expect(chrome.cast.media.ResumeState).toBeDefined(); - expect(chrome.cast.media.MediaCommand).toBeDefined(); - expect(chrome.cast.media.MetadataType).toBeDefined(); - expect(chrome.cast.media.StreamType).toBeDefined(); - expect(chrome.cast.media.timeout).toBeDefined(); - expect(chrome.cast.media.LoadRequest).toBeDefined(); - expect(chrome.cast.media.PlayRequest).toBeDefined(); - expect(chrome.cast.media.SeekRequest).toBeDefined(); - expect(chrome.cast.media.VolumeRequest).toBeDefined(); - expect(chrome.cast.media.StopRequest).toBeDefined(); - expect(chrome.cast.media.PauseRequest).toBeDefined(); - expect(chrome.cast.media.GenericMediaMetadata).toBeDefined(); - expect(chrome.cast.media.MovieMediaMetadata).toBeDefined(); - expect(chrome.cast.media.MusicTrackMediaMetadata).toBeDefined(); - expect(chrome.cast.media.PhotoMediaMetadata).toBeDefined(); - expect(chrome.cast.media.TvShowMediaMetadata).toBeDefined(); - expect(chrome.cast.media.MediaInfo).toBeDefined(); - expect(chrome.cast.media.Media).toBeDefined(); - expect(chrome.cast.Session.prototype.setReceiverVolumeLevel).toBeDefined(); - expect(chrome.cast.Session.prototype.setReceiverMuted).toBeDefined(); - expect(chrome.cast.Session.prototype.stop).toBeDefined(); - expect(chrome.cast.Session.prototype.sendMessage).toBeDefined(); - expect(chrome.cast.Session.prototype.addUpdateListener).toBeDefined(); - expect(chrome.cast.Session.prototype.removeUpdateListener).toBeDefined(); - expect(chrome.cast.Session.prototype.addMessageListener).toBeDefined(); - expect(chrome.cast.Session.prototype.removeMessageListener).toBeDefined(); - expect(chrome.cast.Session.prototype.addMediaListener).toBeDefined(); - expect(chrome.cast.Session.prototype.removeMediaListener).toBeDefined(); - expect(chrome.cast.Session.prototype.loadMedia).toBeDefined(); - expect(chrome.cast.media.Media.prototype.play).toBeDefined(); - expect(chrome.cast.media.Media.prototype.pause).toBeDefined(); - expect(chrome.cast.media.Media.prototype.seek).toBeDefined(); - expect(chrome.cast.media.Media.prototype.stop).toBeDefined(); - expect(chrome.cast.media.Media.prototype.setVolume).toBeDefined(); - expect(chrome.cast.media.Media.prototype.supportsCommand).toBeDefined(); - expect(chrome.cast.media.Media.prototype.getEstimatedTime).toBeDefined(); - expect(chrome.cast.media.Media.prototype.addUpdateListener).toBeDefined(); - expect(chrome.cast.media.Media.prototype.removeUpdateListener).toBeDefined(); - done(); - }, 1000); - }); - - it('api should be available', function(done) { - setTimeout(function() { - console.log('api should be available'); - expect(chrome.cast.isAvailable).toEqual(true); - done(); - }, 4000) - }); - - it('initialize should succeed', function(done) { - console.log('initialize should succeed'); - var sessionRequest = new chrome.cast.SessionRequest(applicationID); - var apiConfig = new chrome.cast.ApiConfig(sessionRequest, function(session) { - console.log('sessionCallback'); - _session = session; - }, function(available) { - console.log('receiverCallback') - _receiverAvailability = available; - }); - - chrome.cast.initialize(apiConfig, function() { - console.log('initialize done'); - done(); - }, function(err) { - console.log('initialize error', err); - expect(err).toBe(null); - done(); - }); - }); - - it('receiver available', function(done) { - setTimeout(function() { - console.log('receiver available', _receiverAvailability); - expect(_receiverAvailability).toEqual(chrome.cast.ReceiverAvailability.AVAILABLE); - done(); - }, 2000); - }); - - - it('requestSession should succeed', function(done) { - chrome.cast.requestSession(function(session) { - console.log('request session success'); - _session = session; - expect(session).toBeDefined(); - expect(session.appId).toBeDefined(); - expect(session.displayName).toBeDefined(); - expect(session.receiver).toBeDefined(); - expect(session.receiver.friendlyName).toBeDefined(); - expect(session.addUpdateListener).toBeDefined(); - expect(session.removeUpdateListener).toBeDefined(); - - var updateListener = function(isAlive) { - _sessionUpdatedFired = true; - session.removeUpdateListener(updateListener); - }; - - session.addUpdateListener(updateListener); - done(); - }, function(err) { - console.log('request session error'); - expect(err).toBe(null); - done(); - }) - }); - - it('loadRequest should work', function(done) { - var mediaInfo = new chrome.cast.media.MediaInfo(videoUrl, 'video/mp4'); - var request = new chrome.cast.media.LoadRequest(mediaInfo); - expect(_session).not.toBeNull() - _session.loadMedia(request, function(media) { - console.log('loadRequest success', media); - _currentMedia = media; - // expect(_currentMedia instanceof chrome.cast.media.Media).toBe(true); - - expect(_currentMedia.sessionId).toEqual(_session.sessionId); - expect(_currentMedia.addUpdateListener).toBeDefined(); - expect(_currentMedia.removeUpdateListener).toBeDefined(); - - var updateListener = function() { - _mediaUpdatedFired = true; - _currentMedia.removeUpdateListener(updateListener); - }; - - _currentMedia.addUpdateListener(updateListener); - - done(); - }, function(err) { - console.log('loadRequest error', err); - expect(err).toBeNull(); - done(); - }); - - }); - - it('pause media should succeed', function(done) { - setTimeout(function() { - _currentMedia.pause(null, function() { - console.log('pause success'); - done(); - }, function(err) { - console.log('pause error', err); - expect(err).toBeNull(); - done(); - }); - }, 5000); - }); - - it('play media should succeed', function(done) { - setTimeout(function() { - _currentMedia.play(null, function() { - console.log('play success'); - done(); - }, function(err) { - console.log('play error', err); - expect(err).toBeNull(); - done(); - }); - }, 1000); - }); - - it('seek media should succeed', function(done) { - setTimeout(function() { - var request = new chrome.cast.media.SeekRequest(); - request.currentTime = 10; - - _currentMedia.seek(request, function() { - done(); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - }, 1000); - }); - - it('session updateListener', function(done) { - expect(_sessionUpdatedFired).toEqual(true); - done(); - }); - - it('media updateListener', function(done) { - expect(_mediaUpdatedFired).toEqual(true); - done(); - }); - - it('volume and muting', function(done) { - var volume = new chrome.cast.Volume(); - volume.level = 0.5; - - var request = new chrome.cast.media.VolumeRequest(); - request.volume = volume; - - _currentMedia.setVolume(request, function() { - - var request = new chrome.cast.media.VolumeRequest(new chrome.cast.Volume(null, true)); - _currentMedia.setVolume(request, function() { - - - var request = new chrome.cast.media.VolumeRequest(new chrome.cast.Volume(null, false)); - _currentMedia.setVolume(request, function() { - done(); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - - }, function(err) { - expect(err).toBeNull(); - done(); - }); - - }, function(err) { - expect(err).toBeNull(); - done(); - }); - - }); - - - it('stopping the video', function(done) { - _currentMedia.stop(null, function() { - setTimeout(done, 1000); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - }); - - it('unloading the session', function(done) { - _session.stop(function() { - done(); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - }); - - }); -}; - - -}); diff --git a/platforms/ios/platform_www/plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js b/platforms/ios/platform_www/plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js deleted file mode 100644 index ea58b6a..0000000 --- a/platforms/ios/platform_www/plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js +++ /dev/null @@ -1,29 +0,0 @@ -cordova.define("com.hutchind.cordova.plugins.launcher.Launcher", function(require, exports, module) { "use strict"; -function Launcher() {} - -Launcher.prototype.canLaunch = function (options, successCallback, errorCallback) { - options = options || {}; - options.successCallback = options.successCallback || successCallback; - options.errorCallback = options.errorCallback || errorCallback; - cordova.exec(options.successCallback || null, options.errorCallback || null, "Launcher", "canLaunch", [options]); -}; - -Launcher.prototype.launch = function(options, successCallback, errorCallback) { - options = options || {}; - options.successCallback = options.successCallback || successCallback; - options.errorCallback = options.errorCallback || errorCallback; - cordova.exec(options.successCallback || null, options.errorCallback || null, "Launcher", "launch", [options]); -}; - -Launcher.install = function () { - if (!window.plugins) { - window.plugins = {}; - } - - window.plugins.launcher = new Launcher(); - return window.plugins.launcher; -}; - -cordova.addConstructor(Launcher.install); - -}); diff --git a/platforms/ios/platform_www/plugins/cordova-plugin-network-information/www/Connection.js b/platforms/ios/platform_www/plugins/cordova-plugin-network-information/www/Connection.js deleted file mode 100644 index 1450e95..0000000 --- a/platforms/ios/platform_www/plugins/cordova-plugin-network-information/www/Connection.js +++ /dev/null @@ -1,36 +0,0 @@ -cordova.define("cordova-plugin-network-information.Connection", 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. - * -*/ - -/** - * Network status - */ -module.exports = { - UNKNOWN: "unknown", - ETHERNET: "ethernet", - WIFI: "wifi", - CELL_2G: "2g", - CELL_3G: "3g", - CELL_4G: "4g", - CELL:"cellular", - NONE: "none" -}; - -}); diff --git a/platforms/ios/platform_www/plugins/cordova-plugin-network-information/www/network.js b/platforms/ios/platform_www/plugins/cordova-plugin-network-information/www/network.js deleted file mode 100644 index bfac2e3..0000000 --- a/platforms/ios/platform_www/plugins/cordova-plugin-network-information/www/network.js +++ /dev/null @@ -1,93 +0,0 @@ -cordova.define("cordova-plugin-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 navigator object with our own -// object in bootstrap.js. -// Browser platform do not need to define this property, because -// it is already supported by modern browsers -if (cordova.platformId !== 'browser' && 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; - -}); diff --git a/plugins/acidhax.cordova.chromecast/EventEmitter.js b/plugins/acidhax.cordova.chromecast/EventEmitter.js deleted file mode 100644 index 426cb8a..0000000 --- a/plugins/acidhax.cordova.chromecast/EventEmitter.js +++ /dev/null @@ -1,447 +0,0 @@ -/*! - * EventEmitter v4.2.11 - git.io/ee - * Unlicense - http://unlicense.org/ - * Oliver Caldwell - http://oli.me.uk/ - * @preserve - */ - - 'use strict'; - - /** - * Class for managing events. - * Can be extended to provide event functionality in other classes. - * - * @class EventEmitter Manages event registering and emitting. - */ - function EventEmitter() {} - - // Shortcuts to improve speed and size - var proto = EventEmitter.prototype; - - /** - * Finds the index of the listener for the event in its storage array. - * - * @param {Function[]} listeners Array of listeners to search through. - * @param {Function} listener Method to look for. - * @return {Number} Index of the specified listener, -1 if not found - * @api private - */ - function indexOfListener(listeners, listener) { - var i = listeners.length; - while (i--) { - if (listeners[i].listener === listener) { - return i; - } - } - - return -1; - } - - /** - * Alias a method while keeping the context correct, to allow for overwriting of target method. - * - * @param {String} name The name of the target method. - * @return {Function} The aliased method - * @api private - */ - function alias(name) { - return function aliasClosure() { - return this[name].apply(this, arguments); - }; - } - - /** - * Returns the listener array for the specified event. - * Will initialise the event object and listener arrays if required. - * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. - * Each property in the object response is an array of listener functions. - * - * @param {String|RegExp} evt Name of the event to return the listeners from. - * @return {Function[]|Object} All listener functions for the event. - */ - proto.getListeners = function getListeners(evt) { - var events = this._getEvents(); - var response; - var key; - - // Return a concatenated array of all matching events if - // the selector is a regular expression. - if (evt instanceof RegExp) { - response = {}; - for (key in events) { - if (events.hasOwnProperty(key) && evt.test(key)) { - response[key] = events[key]; - } - } - } - else { - response = events[evt] || (events[evt] = []); - } - - return response; - }; - - /** - * Takes a list of listener objects and flattens it into a list of listener functions. - * - * @param {Object[]} listeners Raw listener objects. - * @return {Function[]} Just the listener functions. - */ - proto.flattenListeners = function flattenListeners(listeners) { - var flatListeners = []; - var i; - - for (i = 0; i < listeners.length; i += 1) { - flatListeners.push(listeners[i].listener); - } - - return flatListeners; - }; - - /** - * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. - * - * @param {String|RegExp} evt Name of the event to return the listeners from. - * @return {Object} All listener functions for an event in an object. - */ - proto.getListenersAsObject = function getListenersAsObject(evt) { - var listeners = this.getListeners(evt); - var response; - - if (listeners instanceof Array) { - response = {}; - response[evt] = listeners; - } - - return response || listeners; - }; - - /** - * Adds a listener function to the specified event. - * The listener will not be added if it is a duplicate. - * If the listener returns true then it will be removed after it is called. - * If you pass a regular expression as the event name then the listener will be added to all events that match it. - * - * @param {String|RegExp} evt Name of the event to attach the listener to. - * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.addListener = function addListener(evt, listener) { - var listeners = this.getListenersAsObject(evt); - var listenerIsWrapped = typeof listener === 'object'; - var key; - - for (key in listeners) { - if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) { - listeners[key].push(listenerIsWrapped ? listener : { - listener: listener, - once: false - }); - } - } - - return this; - }; - - /** - * Alias of addListener - */ - proto.on = alias('addListener'); - - /** - * Semi-alias of addListener. It will add a listener that will be - * automatically removed after its first execution. - * - * @param {String|RegExp} evt Name of the event to attach the listener to. - * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.addOnceListener = function addOnceListener(evt, listener) { - return this.addListener(evt, { - listener: listener, - once: true - }); - }; - - /** - * Alias of addOnceListener. - */ - proto.once = alias('addOnceListener'); - - /** - * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. - * You need to tell it what event names should be matched by a regex. - * - * @param {String} evt Name of the event to create. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.defineEvent = function defineEvent(evt) { - this.getListeners(evt); - return this; - }; - - /** - * Uses defineEvent to define multiple events. - * - * @param {String[]} evts An array of event names to define. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.defineEvents = function defineEvents(evts) { - for (var i = 0; i < evts.length; i += 1) { - this.defineEvent(evts[i]); - } - return this; - }; - - /** - * Removes a listener function from the specified event. - * When passed a regular expression as the event name, it will remove the listener from all events that match it. - * - * @param {String|RegExp} evt Name of the event to remove the listener from. - * @param {Function} listener Method to remove from the event. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.removeListener = function removeListener(evt, listener) { - var listeners = this.getListenersAsObject(evt); - var index; - var key; - - for (key in listeners) { - if (listeners.hasOwnProperty(key)) { - index = indexOfListener(listeners[key], listener); - - if (index !== -1) { - listeners[key].splice(index, 1); - } - } - } - - return this; - }; - - /** - * Alias of removeListener - */ - proto.off = alias('removeListener'); - - /** - * Adds listeners in bulk using the manipulateListeners method. - * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. - * You can also pass it a regular expression to add the array of listeners to all events that match it. - * Yeah, this function does quite a bit. That's probably a bad thing. - * - * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. - * @param {Function[]} [listeners] An optional array of listener functions to add. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.addListeners = function addListeners(evt, listeners) { - // Pass through to manipulateListeners - return this.manipulateListeners(false, evt, listeners); - }; - - /** - * Removes listeners in bulk using the manipulateListeners method. - * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. - * You can also pass it an event name and an array of listeners to be removed. - * You can also pass it a regular expression to remove the listeners from all events that match it. - * - * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. - * @param {Function[]} [listeners] An optional array of listener functions to remove. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.removeListeners = function removeListeners(evt, listeners) { - // Pass through to manipulateListeners - return this.manipulateListeners(true, evt, listeners); - }; - - /** - * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. - * The first argument will determine if the listeners are removed (true) or added (false). - * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. - * You can also pass it an event name and an array of listeners to be added/removed. - * You can also pass it a regular expression to manipulate the listeners of all events that match it. - * - * @param {Boolean} remove True if you want to remove listeners, false if you want to add. - * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. - * @param {Function[]} [listeners] An optional array of listener functions to add/remove. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) { - var i; - var value; - var single = remove ? this.removeListener : this.addListener; - var multiple = remove ? this.removeListeners : this.addListeners; - - // If evt is an object then pass each of its properties to this method - if (typeof evt === 'object' && !(evt instanceof RegExp)) { - for (i in evt) { - if (evt.hasOwnProperty(i) && (value = evt[i])) { - // Pass the single listener straight through to the singular method - if (typeof value === 'function') { - single.call(this, i, value); - } - else { - // Otherwise pass back to the multiple function - multiple.call(this, i, value); - } - } - } - } - else { - // So evt must be a string - // And listeners must be an array of listeners - // Loop over it and pass each one to the multiple method - i = listeners.length; - while (i--) { - single.call(this, evt, listeners[i]); - } - } - - return this; - }; - - /** - * Removes all listeners from a specified event. - * If you do not specify an event then all listeners will be removed. - * That means every event will be emptied. - * You can also pass a regex to remove all events that match it. - * - * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.removeEvent = function removeEvent(evt) { - var type = typeof evt; - var events = this._getEvents(); - var key; - - // Remove different things depending on the state of evt - if (type === 'string') { - // Remove all listeners for the specified event - delete events[evt]; - } - else if (evt instanceof RegExp) { - // Remove all events matching the regex. - for (key in events) { - if (events.hasOwnProperty(key) && evt.test(key)) { - delete events[key]; - } - } - } - else { - // Remove all listeners in all events - delete this._events; - } - - return this; - }; - - /** - * Alias of removeEvent. - * - * Added to mirror the node API. - */ - proto.removeAllListeners = alias('removeEvent'); - - /** - * Emits an event of your choice. - * When emitted, every listener attached to that event will be executed. - * If you pass the optional argument array then those arguments will be passed to every listener upon execution. - * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. - * So they will not arrive within the array on the other side, they will be separate. - * You can also pass a regular expression to emit to all events that match it. - * - * @param {String|RegExp} evt Name of the event to emit and execute listeners for. - * @param {Array} [args] Optional array of arguments to be passed to each listener. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.emitEvent = function emitEvent(evt, args) { - var listeners = this.getListenersAsObject(evt); - var listener; - var i; - var key; - var response; - - for (key in listeners) { - if (listeners.hasOwnProperty(key)) { - i = listeners[key].length; - - while (i--) { - // If the listener returns true then it shall be removed from the event - // The function is executed either with a basic call or an apply if there is an args array - listener = listeners[key][i]; - - if (listener.once === true) { - this.removeListener(evt, listener.listener); - } - - response = listener.listener.apply(this, args || []); - - if (response === this._getOnceReturnValue()) { - this.removeListener(evt, listener.listener); - } - } - } - } - - return this; - }; - - /** - * Alias of emitEvent - */ - proto.trigger = alias('emitEvent'); - - /** - * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. - * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. - * - * @param {String|RegExp} evt Name of the event to emit and execute listeners for. - * @param {...*} Optional additional arguments to be passed to each listener. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.emit = function emit(evt) { - var args = Array.prototype.slice.call(arguments, 1); - return this.emitEvent(evt, args); - }; - - /** - * Sets the current value to check against when executing listeners. If a - * listeners return value matches the one set here then it will be removed - * after execution. This value defaults to true. - * - * @param {*} value The new value to check for when executing listeners. - * @return {Object} Current instance of EventEmitter for chaining. - */ - proto.setOnceReturnValue = function setOnceReturnValue(value) { - this._onceReturnValue = value; - return this; - }; - - /** - * Fetches the current value to check against when executing listeners. If - * the listeners return value matches this one then it should be removed - * automatically. It will return true by default. - * - * @return {*|Boolean} The current value to check for or the default, true. - * @api private - */ - proto._getOnceReturnValue = function _getOnceReturnValue() { - if (this.hasOwnProperty('_onceReturnValue')) { - return this._onceReturnValue; - } - else { - return true; - } - }; - - /** - * Fetches the events object and creates one if required. - * - * @return {Object} The events storage object. - * @api private - */ - proto._getEvents = function _getEvents() { - return this._events || (this._events = {}); - }; - - module.exports = EventEmitter; diff --git a/plugins/acidhax.cordova.chromecast/README.md b/plugins/acidhax.cordova.chromecast/README.md deleted file mode 100644 index b2b6b76..0000000 --- a/plugins/acidhax.cordova.chromecast/README.md +++ /dev/null @@ -1,32 +0,0 @@ -cordova-chromecast -================== - -Chromecast in Cordova - -##Installation -For now, add the plugin from this repository, we'll publish soon with more progress. - -``` -cordova plugin add https://github.com/GetVideostream/cordova-chromecast.git -``` - -If you have NodeJS installed, the dependencies should be automatically copied. - -- `http://nodejs.org/` - -If not you will need to import the following projects as Library Projects in order for this plugin to work: - -- `adt-bundle\sdk\extras\google\google_play_services\libproject\google-play-services_lib` -- `adt-bundle\sdk\extras\android\support\v7\appcompat` -- `adt-bundle\sdk\extras\android\support\v7\mediarouter` - -##Usage - -This project attempts to implement the official Google Cast SDK for Chrome... in Cordova. We've made a lot of progress in making this possible, check out the offical docs for examples: https://developers.google.com/cast/docs/chrome_sender - -When you call `chrome.cast.requestSession()` an ugly popup will be displayed to select a Chromecast. If you're not cool with this - you can call: `chrome.cast.getRouteListElement()` which will return a `
    ` tag that contains the Chromecasts in a list. All you have to do is style that bad boy and you're off to the races! - - -##Status - -The project is now pretty much feature complete - the only things that probably break will be missing parameters. We haven't done any checking for optional paramaters. When using it, make sure your constructors and function calls have every parameter specified in the API. diff --git a/plugins/acidhax.cordova.chromecast/chrome.cast.js b/plugins/acidhax.cordova.chromecast/chrome.cast.js deleted file mode 100644 index 4d4da2d..0000000 --- a/plugins/acidhax.cordova.chromecast/chrome.cast.js +++ /dev/null @@ -1,1235 +0,0 @@ -var EventEmitter = require('acidhax.cordova.chromecast.EventEmitter'); - -var chrome = {}; -chrome.cast = { - - /** - * The API version. - * @type {Array} - */ - VERSION: [1, 1], - - /** - * Describes availability of a Cast receiver. - * AVAILABLE: At least one receiver is available that is compatible with the session request. - * UNAVAILABLE: No receivers are available. - * @type {Object} - */ - ReceiverAvailability: { AVAILABLE: "available", UNAVAILABLE: "unavailable" }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.ReceiverType - * CAST: - * DIAL: - * CUSTOM: - * @type {Object} - */ - ReceiverType: { CAST: "cast", DIAL: "dial", CUSTOM: "custom" }, - - - /** - * Describes a sender application platform. - * CHROME: - * IOS: - * ANDROID: - * @type {Object} - */ - SenderPlatform: { CHROME: "chrome", IOS: "ios", ANDROID: "android" }, - - /** - * Auto-join policy determines when the SDK will automatically connect a sender application to an existing session after API initialization. - * ORIGIN_SCOPED: Automatically connects when the session was started with the same appId and the same page origin (regardless of tab). - * PAGE_SCOPED: No automatic connection. - * TAB_AND_ORIGIN_SCOPED: Automatically connects when the session was started with the same appId, in the same tab and page origin. - * @type {Object} - */ - AutoJoinPolicy: { TAB_AND_ORIGIN_SCOPED: "tab_and_origin_scoped", ORIGIN_SCOPED: "origin_scoped", PAGE_SCOPED: "page_scoped" }, - - /** - * Capabilities that are supported by the receiver device. - * AUDIO_IN: The receiver supports audio input (microphone). - * AUDIO_OUT: The receiver supports audio output. - * VIDEO_IN: The receiver supports video input (camera). - * VIDEO_OUT: The receiver supports video output. - * @type {Object} - */ - Capability: { VIDEO_OUT: "video_out", AUDIO_OUT: "audio_out", VIDEO_IN: "video_in", AUDIO_IN: "audio_in" }, - - /** - * Default action policy determines when the SDK will automatically create a session after initializing the API. This also controls the default action for the tab in the extension popup. - * CAST_THIS_TAB: No automatic launch is done after initializing the API, even if the tab is being cast. - * CREATE_SESSION: If the tab containing the app is being casted when the API initializes, the SDK stops tab casting and automatically launches the app. - * @type {Object} - */ - DefaultActionPolicy: { CREATE_SESSION: "create_session", CAST_THIS_TAB: "cast_this_tab" }, - - /** - * Errors that may be returned by the SDK. - * API_NOT_INITIALIZED: The API is not initialized. - * CANCEL: The operation was canceled by the user. - * CHANNEL_ERROR: A channel to the receiver is not available. - * EXTENSION_MISSING: The Cast extension is not available. - * EXTENSION_NOT_COMPATIBLE: The API script is not compatible with the installed Cast extension. - * INVALID_PARAMETER: The parameters to the operation were not valid. - * LOAD_MEDIA_FAILED: Load media failed. - * RECEIVER_UNAVAILABLE: No receiver was compatible with the session request. - * SESSION_ERROR: A session could not be created, or a session was invalid. - * TIMEOUT: The operation timed out. - * @type {Object} - */ - ErrorCode: { - API_NOT_INITIALIZED: "api_not_initialized", - CANCEL: "cancel", - CHANNEL_ERROR: "channel_error", - EXTENSION_MISSING: "extension_missing", - EXTENSION_NOT_COMPATIBLE: "extension_not_compatible", - INVALID_PARAMETER: "invalid_parameter", - LOAD_MEDIA_FAILED: "load_media_failed", - RECEIVER_UNAVAILABLE: "receiver_unavailable", - SESSION_ERROR: "session_error", - TIMEOUT: "timeout", - UNKNOWN: "unknown", - NOT_IMPLEMENTED: "not_implemented" - }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.timeout - * @type {Object} - */ - timeout: { - requestSession: 10000, - sendCustomMessage: 3000, - setReceiverVolume: 3000, - stopSession: 3000 - }, - - /** - * Flag for clients to check whether the API is loaded. - * @type {Boolean} - */ - isAvailable: false, - - - // CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES - - /** - * [ApiConfig description] - * @param {chrome.cast.SessionRequest} sessionRequest Describes the session to launch or the session to connect. - * @param {function} sessionListener Listener invoked when a session is created or connected by the SDK. - * @param {function} receiverListener Function invoked when the availability of a Cast receiver that supports the application in sessionRequest is known or changes. - * @param {chrome.cast.AutoJoinPolicy} autoJoinPolicy Determines whether the SDK will automatically connect to a running session after initialization. - * @param {chrome.cast.DefaultActionPolicy} defaultActionPolicy Requests whether the application should be launched on API initialization when the tab is already being cast. - */ - ApiConfig: function (sessionRequest, sessionListener, receiverListener, autoJoinPolicy, defaultActionPolicy) { - this.sessionRequest = sessionRequest; - this.sessionListener = sessionListener; - this.receiverListener = receiverListener; - this.autoJoinPolicy = autoJoinPolicy || chrome.cast.AutoJoinPolicy.TAB_AND_ORIGIN_SCOPED; - this.defaultActionPolicy = defaultActionPolicy || chrome.cast.DefaultActionPolicy.CREATE_SESSION; - }, - - /** - * Describes the receiver running an application. Normally, these objects should not be created by the client. - * @param {string} label An identifier for the receiver that is unique to the browser profile and the origin of the API client. - * @param {string} friendlyName The user given name for the receiver. - * @param {chrome.cast.Capability[]} capabilities The capabilities of the receiver, for example audio and video. - * @param {chrome.cast.Volume} volume The current volume of the receiver. - */ - Receiver: function (label, friendlyName, capabilities, volume) { - this.label = label; - this.friendlyName = friendlyName; - this.capabilities = capabilities || []; - this.volume = volume || null; - this.receiverType = chrome.cast.ReceiverType.CAST; - this.isActiveInput = null; - }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.DialRequest - * @param {[type]} appName [description] - * @param {[type]} launchParameter [description] - */ - DialRequest: function (appName, launchParameter) { - this.appName = appName; - this.launchParameter = launchParameter; - }, - - /** - * A request to start or connect to a session. - * @param {string} appId The receiver application id. - * @param {chrome.cast.Capability[]} capabilities Capabilities required of the receiver device. - * @property {chrome.cast.DialRequest} dialRequest If given, the SDK will also discover DIAL devices that support the DIAL application given in the dialRequest. - */ - SessionRequest: function (appId, capabilities) { - this.appId = appId; - this.capabilities = capabilities || [chrome.cast.Capability.VIDEO_OUT, chrome.cast.Capability.AUDIO_OUT]; - this.dialRequest = null; - }, - - /** - * Describes an error returned by the API. Normally, these objects should not be created by the client. - * @param {chrome.cast.ErrorCode} code The error code. - * @param {string} description Human readable description of the error. - * @param {Object} details Details specific to the error. - */ - Error: function (code, description, details) { - this.code = code; - this.description = description || null; - this.details = details || null; - }, - - /** - * An image that describes a receiver application or media item. This could be an application icon, cover art, or a thumbnail. - * @param {string} url The URL to the image. - * @property {number} height The height of the image - * @property {number} width The width of the image - */ - Image: function (url) { - this.url = url; - this.width = this.height = null; - }, - - /** - * Describes a sender application. Normally, these objects should not be created by the client. - * @param {chrome.cast.SenderPlatform} platform The supported platform. - * @property {string} packageId The identifier or URL for the application in the respective platform's app store. - * @property {string} url URL or intent to launch the application. - */ - SenderApplication: function (platform) { - this.platform = platform; - this.packageId = this.url = null; - }, - - /** - * The volume of a device or media stream. - * @param {number} level The current volume level as a value between 0.0 and 1.0. - * @param {boolean} muted Whether the receiver is muted, independent of the volume level. - */ - Volume: function (level, muted) { - this.level = level || null; - this.muted = null; - if (muted === true || muted === false) { - this.muted = muted; - } - }, - - - // media package - media: { - /** - * The default receiver app. - */ - DEFAULT_MEDIA_RECEIVER_APP_ID: 'CC1AD845', - - /** - * Possible states of the media player. - * BUFFERING: Player is in PLAY mode but not actively playing content. currentTime will not change. - * IDLE: No media is loaded into the player. - * PAUSED: The media is not playing. - * PLAYING: The media is playing. - * @type {Object} - */ - PlayerState: { IDLE: "IDLE", PLAYING: "PLAYING", PAUSED: "PAUSED", BUFFERING: "BUFFERING" }, - - /** - * States of the media player after resuming. - * PLAYBACK_PAUSE: Force media to pause. - * PLAYBACK_START: Force media to start. - * @type {Object} - */ - ResumeState: { PLAYBACK_START: "PLAYBACK_START", PLAYBACK_PAUSE: "PLAYBACK_PAUSE" }, - - /** - * Possible media commands supported by the receiver application. - * @type {Object} - */ - MediaCommand: { PAUSE: "pause", SEEK: "seek", STREAM_VOLUME: "stream_volume", STREAM_MUTE: "stream_mute" }, - - /** - * Possible types of media metadata. - * GENERIC: Generic template suitable for most media types. Used by chrome.cast.media.GenericMediaMetadata. - * MOVIE: A full length movie. Used by chrome.cast.media.MovieMediaMetadata. - * MUSIC_TRACK: A music track. Used by chrome.cast.media.MusicTrackMediaMetadata. - * PHOTO: Photo. Used by chrome.cast.media.PhotoMediaMetadata. - * TV_SHOW: An episode of a TV series. Used by chrome.cast.media.TvShowMediaMetadata. - * @type {Object} - */ - MetadataType: { GENERIC: 0, TV_SHOW: 1, MOVIE: 2, MUSIC_TRACK: 3, PHOTO: 4 }, - - /** - * Possible media stream types. - * BUFFERED: Stored media streamed from an existing data store. - * LIVE: Live media generated on the fly. - * OTHER: None of the above. - * @type {Object} - */ - StreamType: { BUFFERED: 'buffered', LIVE: 'live', OTHER: 'other' }, - - /** - * TODO: Update when the official API docs are finished - * https://developers.google.com/cast/docs/reference/chrome/chrome.cast.media.timeout - * @type {Object} - */ - timeout: { - load: 0, - ob: 0, - pause: 0, - play: 0, - seek: 0, - setVolume: 0, - stop: 0 - }, - - - // CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES CLASSES - - /** - * A request to load new media into the player. - * @param {chrome.cast.media.MediaInfo} media Media description. - * @property {boolean} autoplay Whether the media will automatically play. - * @property {number} currentTime Seconds from the beginning of the media to start playback. - * @property {Object} customData Custom data for the receiver application. - */ - LoadRequest: function (media) { - this.type = 'LOAD'; - this.sessionId = this.requestId = this.customData = this.currentTime = null; - this.media = media; - this.autoplay = !0; - }, - - /** - * A request to play the currently paused media. - * @property {Object} customData Custom data for the receiver application. - */ - PlayRequest: function () { - this.customData = null; - }, - - /** - * A request to seek the current media. - * @property {number} currentTime The new current time for the media, in seconds after the start of the media. - * @property {chrome.cast.media.ResumeState} resumeState The desired media player state after the seek is complete. - * @property {Object} customData Custom data for the receiver application. - */ - SeekRequest: function () { - this.customData = this.resumeState = this.currentTime = null; - }, - - /** - * A request to set the stream volume of the playing media. - * @param {chrome.cast.Volume} volume The new volume of the stream. - * @property {Object} customData Custom data for the receiver application. - */ - VolumeRequest: function (volume) { - this.volume = volume; - this.customData = null; - }, - - /** - * A request to stop the media player. - * @property {Object} customData Custom data for the receiver application. - */ - StopRequest: function () { - this.customData = null; - }, - - /** - * A request to pause the currently playing media. - * @property {Object} customData Custom data for the receiver application. - */ - PauseRequest: function () { - this.customData = null; - }, - - /** - * A generic media description. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} releaseDate ISO 8601 date and/or time when the content was released, e.g. - * @property {number} releaseYear Integer year when the content was released. - * @property {string} subtitle Content subtitle. - * @property {string} title Content title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - GenericMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.GENERIC; - this.releaseDate = this.releaseYear = this.images = this.subtitle = this.title = null; - }, - - /** - * A movie media description. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} releaseDate ISO 8601 date and/or time when the content was released, e.g. - * @property {number} releaseYear Integer year when the content was released. - * @property {string} studio Movie studio - * @property {string} subtitle Content subtitle. - * @property {string} title Content title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - MovieMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.MOVIE; - this.releaseDate = this.releaseYear = this.images = this.subtitle = this.studio = this.title = null; - }, - - /** - * A music track media description. - * @property {string} albumArtist Album artist name. - * @property {string} albumName Album name. - * @property {string} artist Track artist name. - * @property {string} artistName Track artist name. - * @property {string} composer Track composer name. - * @property {number} discNumber Disc number. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} releaseDate ISO 8601 date when the track was released, e.g. - * @property {number} releaseYear Integer year when the album was released. - * @property {string} songName Track name. - * @property {string} title Track title. - * @property {number} trackNumber Track number in album. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - MusicTrackMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.MUSIC_TRACK; - this.releaseDate = this.releaseYear = this.images = this.discNumber = this.trackNumber = this.artistName = this.songName = this.composer = this.artist = this.albumArtist = this.title = this.albumName = null; - }, - - /** - * A photo media description. - * @property {string} artist Name of the photographer. - * @property {string} creationDateTime ISO 8601 date and time the photo was taken, e.g. - * @property {number} height Photo height, in pixels. - * @property {chrome.cast.Image[]} images Images associated with the content. - * @property {number} latitude Latitude. - * @property {string} location Location where the photo was taken. - * @property {number} longitude Longitude. - * @property {string} title Photo title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - * @property {number} width Photo width, in pixels. - */ - PhotoMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.PHOTO; - this.creationDateTime = this.height = this.width = this.longitude = this.latitude = this.images = this.location = this.artist = this.title = null; - }, - - /** - * [TvShowMediaMetadata description] - * @property {number} episode TV episode number. - * @property {number} episodeNumber TV episode number. - * @property {string} episodeTitle TV episode title. - * @property {chrome.cast.Image[]} images Content images. - * @property {string} originalAirdate ISO 8601 date when the episode originally aired, e.g. - * @property {number} releaseYear Integer year when the content was released. - * @property {number} season TV episode season. - * @property {number} seasonNumber TV episode season. - * @property {string} seriesTitle TV series title. - * @property {string} title TV episode title. - * @property {chrome.cast.media.MetadataType} type The type of metadata. - */ - TvShowMediaMetadata: function () { - this.metadataType = this.type = chrome.cast.media.MetadataType.TV_SHOW; - this.originalAirdate = this.releaseYear = this.images = this.episode = this.episodeNumber = this.season = this.seasonNumber = this.episodeTitle = this.title = this.seriesTitle = null; - }, - - /** - * Describes a media item. - * @param {string} contentId Identifies the content. - * @param {string} contentType MIME content type of the media. - * @property {Object} customData Custom data set by the receiver application. - * @property {number} duration Duration of the content, in seconds. - * @property {any type} metadata Describes the media content. - * @property {chrome.cast.media.StreamType} streamType The type of media stream. - */ - MediaInfo: function (contentId, contentType) { - this.contentId = contentId; - this.streamType = chrome.cast.media.StreamType.BUFFERED; - this.contentType = contentType; - this.customData = this.duration = this.metadata = null; - } - } -}; - -var _sessionRequest = null; -var _autoJoinPolicy = null; -var _defaultActionPolicy = null; -var _receiverListener = null; -var _sessionListener = null; - -var _sessions = {}; -var _currentMedia = null; -var _routeListEl = document.createElement('ul'); -_routeListEl.classList.add('route-list'); -var _routeList = {}; -var _routeRefreshInterval = null; - -var _receiverAvailable = false; - -/** - * Initializes the API. Note that either successCallback and errorCallback will be invoked once the API has finished initialization. - * The sessionListener and receiverListener may be invoked at any time afterwards, and possibly more than once. - * @param {chrome.cast.ApiConfig} apiConfig The object with parameters to initialize the API. Must not be null. - * @param {function} successCallback - * @param {function} errorCallback - */ -chrome.cast.initialize = function (apiConfig, successCallback, errorCallback) { - if (!chrome.cast.isAvailable) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - _sessionListener = apiConfig.sessionListener; - _autoJoinPolicy = apiConfig.autoJoinPolicy; - _defaultActionPolicy = apiConfig.defaultActionPolicy; - _receiverListener = apiConfig.receiverListener; - _sessionRequest = apiConfig.sessionRequest; - - execute('initialize', _sessionRequest.appId, _autoJoinPolicy, _defaultActionPolicy, function(err) { - if (!err) { - successCallback(); - - clearInterval(_routeRefreshInterval); - _routeRefreshInterval = setInterval(function() { - execute('emitAllRoutes'); - }, 15000); - - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Requests that a receiver application session be created or joined. - * By default, the SessionRequest passed to the API at initialization time is used; - * this may be overridden by passing a different session request in opt_sessionRequest. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, INVALID_PARAMETER, API_NOT_INITIALIZED, CANCEL, CHANNEL_ERROR, SESSION_ERROR, RECEIVER_UNAVAILABLE, and EXTENSION_MISSING. Note that the timeout timer starts after users select a receiver. Selecting a receiver requires user's action, which has no timeout. - * @param {chrome.cast.SessionRequest} opt_sessionRequest - */ -chrome.cast.requestSession = function (successCallback, errorCallback, opt_sessionRequest) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - if (_receiverAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.RECEIVER_UNAVAILABLE, 'No receiver was compatible with the session request.', {})); - return; - } - - execute('requestSession', function(err, obj) { - if (!err) { - var sessionId = obj.sessionId; - var appId = obj.appId; - var displayName = obj.displayName; - var appImages = obj.appImages || []; - var receiver = new chrome.cast.Receiver(obj.receiver.label, obj.receiver.friendlyName, obj.receiver.capabilities || [], obj.volume || null); - - var session = _sessions[sessionId] = new chrome.cast.Session(sessionId, appId, displayName, appImages, receiver); - - if (obj.media && obj.media.sessionId) - { - _currentMedia = new chrome.cast.media.Media(sessionId, obj.media.mediaSessionId); - _currentMedia.currentTime = obj.media.currentTime; - _currentMedia.playerState = obj.media.playerState; - _currentMedia.media = obj.media.media; - session.media[0] = _currentMedia; - } - - successCallback(session); - _sessionListener(session); /*Fix - Already has a sessionListener*/ - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Sets custom receiver list - * @param {chrome.cast.Receiver[]} receivers The new list. Must not be null. - * @param {function} successCallback - * @param {function} errorCallback - */ -chrome.cast.setCustomReceivers = function (receivers, successCallback, errorCallback) { - // TODO: Implement -}; - - - - -/** SESSION SESSION SESSION SESSION SESSION SESSION SESSION SESSION **/ - - - - -/** - * Describes the state of a currently running Cast application. Normally, these objects should not be created by the client. - * @param {string} sessionId Uniquely identifies this instance of the receiver application. - * @param {string} appId The identifer of the Cast application. - * @param {string} displayName The human-readable name of the Cast application, for example, "YouTube". - * @param {chrome.cast.Image[]} appImages Array of images available describing the application. - * @param {chrome.cast.Receiver} receiver The receiver that is running the application. - * - * @property {Object} customData Custom data set by the receiver application. - * @property {chrome.cast.media.Media} media The media that belong to this Cast session, including those loaded by other senders. - * @property {Object[]} namespaces A list of the namespaces supported by the receiver application. - * @property {chrome.cast.SenderApplication} senderApps The sender applications supported by the receiver application. - * @property {string} statusText Descriptive text for the current application content, for example “My Wedding Slideshow”. - */ -chrome.cast.Session = function(sessionId, appId, displayName, appImages, receiver) { - EventEmitter.call(this); - this.sessionId = sessionId; - this.appId = appId; - this.displayName = displayName; - this.appImages = appImages || []; - this.receiver = receiver; - this.media = []; -}; -chrome.cast.Session.prototype = Object.create(EventEmitter.prototype); - -/** - * Sets the receiver volume. - * @param {number} newLevel The new volume level between 0.0 and 1.0. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.setReceiverVolumeLevel = function (newLevel, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('setReceiverVolumeLevel', newLevel, function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - - -/** - * Sets the receiver volume. - * @param {boolean} muted The new muted status. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.setReceiverMuted = function (muted, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('setReceiverMuted', muted, function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Stops the running receiver application associated with the session. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.stop = function (successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('sessionStop', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Leaves the current session. - * @param {function} successCallback - * @param {function} errorCallback The possible errors are TIMEOUT, API_NOT_INITIALIZED, CHANNEL_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.leave = function (successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('sessionLeave', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Sends a message to the receiver application on the given namespace. - * The successCallback is invoked when the message has been submitted to the messaging channel. - * Delivery to the receiver application is best effort and not guaranteed. - * @param {string} namespace - * @param {Object or string} message Must not be null - * @param {[type]} successCallback Invoked when the message has been sent. Must not be null. - * @param {[type]} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING - */ -chrome.cast.Session.prototype.sendMessage = function (namespace, message, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - if (typeof message === 'object') { - message = JSON.stringify(message); - } - execute('sendMessage', namespace, message, function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Request to load media. Must not be null. - * @param {chrome.cast.media.LoadRequest} loadRequest Request to load media. Must not be null. - * @param {function} successCallback Invoked with the loaded Media on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.Session.prototype.loadMedia = function (loadRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - var self = this; - - var mediaInfo = loadRequest.media; - execute('loadMedia', mediaInfo.contentId, mediaInfo.contentType, mediaInfo.duration || 0.0, mediaInfo.streamType, loadRequest.autoplay || false, loadRequest.currentTime || 0, mediaInfo.metadata, function(err, obj) { - if (!err) { - _currentMedia = new chrome.cast.media.Media(self.sessionId, obj.mediaSessionId); - _currentMedia.media = mediaInfo; - _currentMedia.media.duration = obj.media.duration; - _currentMedia.currentTime = obj.currentTime /* ??? */ - - // TODO: Fill in the rest of the media properties - - successCallback(_currentMedia); - - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Adds a listener that is invoked when the status of the Session has changed. - * Changes to the following properties will trigger the listener: statusText, namespaces, customData, and the volume of the receiver. - * The callback will be invoked with 'true' (isAlive) parameter. - * When this session is ended, the callback will be invoked with 'false' (isAlive); - * @param {function} listener The listener to add. - */ -chrome.cast.Session.prototype.addUpdateListener = function (listener) { - this.on('_sessionUpdated', listener); -}; - -/** - * Removes a previously added listener for this Session. - * @param {function} listener The listener to remove. - */ -chrome.cast.Session.prototype.removeUpdateListener = function (listener) { - this.removeListener('_sessionUpdated', listener); -}; - -/** - * Adds a listener that is invoked when a message is received from the receiver application. - * The listener is invoked with the the namespace as the first argument and the message as the second argument. - * @param {string} namespace The namespace to listen on. - * @param {function} listener The listener to add. - */ -chrome.cast.Session.prototype.addMessageListener = function (namespace, listener) { - execute('addMessageListener', namespace); - this.on('message:' + namespace, listener); -}; - -/** - * Removes a previously added listener for messages. - * @param {string} namespace The namespace that is listened to. - * @param {function} listener The listener to remove. - */ -chrome.cast.Session.prototype.removeMessageListener = function (namespace, listener) { - this.removeListener('message:' + namespace, listener); -}; - -/** - * Adds a listener that is invoked when a media session is created by another sender. - * @param {function} listener The listener to add. - */ -chrome.cast.Session.prototype.addMediaListener = function (listener) { - this.on('_mediaListener', listener); -}; - -/** - * Removes a listener that was previously added with addMediaListener. - * @param {function} listener The listener to remove. - */ -chrome.cast.Session.prototype.removeMediaListener = function (listener) { - this.removeListener('_mediaListener', listener); -}; - - -chrome.cast.Session.prototype._update = function(isAlive, obj) { - - this.appId = obj.appId; - this.appImages = obj.appImages; - this.displayName = obj.displayName; - if (obj.receiver) { - if (!this.receiver) { - this.receiver = new chrome.cast.Receiver(null, null, null, null); - } - this.receiver.friendlyName = obj.receiver.friendlyName; - this.receiver.label = obj.receiver.label; - - if (obj.receiver.volume) { - this.receiver.volume = new chrome.cast.Volume(obj.receiver.volume.level, obj.receiver.volume.muted); - } - } - - this.emit('_sessionUpdated', isAlive); -}; - - - - - -/* MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA MEDIA */ -/** - * Represents a media item that has been loaded into the receiver application. - * @param {string} sessionId Identifies the session that is hosting the media. - * @param {number} mediaSessionId Identifies the media item. - * - * @property {Object} customData Custom data set by the receiver application. - * @property {number} currentTime The current playback position in seconds since the start of the media. - * @property {chrome.cast.media.MediaInfo} media Media description. - * @property {number} playbackRate The playback rate. - * @property {chrome.cast.media.PlayerState} playerState The player state. - * @property {chrome.cast.media.MediaCommand[]} supportedMediaCommands The media commands supported by the media player. - * @property {chrome.cast.Volume} volume The media stream volume. - * @property {string} idleReason Reason for idling - */ -chrome.cast.media.Media = function(sessionId, mediaSessionId) { - EventEmitter.call(this); - this.sessionId = sessionId; - this.mediaSessionId = mediaSessionId; - this.currentTime = 0; - this.playbackRate = 1; - this.playerState = chrome.cast.media.PlayerState.BUFFERING; - this.supportedMediaCommands = [ - chrome.cast.media.MediaCommand.PAUSE, - chrome.cast.media.MediaCommand.SEEK, - chrome.cast.media.MediaCommand.STREAM_VOLUME, - chrome.cast.media.MediaCommand.STREAM_MUTE - ]; - this.volume = new chrome.cast.Volume(1, false); - this._lastUpdatedTime = Date.now(); - this.media = {}; -}; -chrome.cast.media.Media.prototype = Object.create(EventEmitter.prototype); - -/** - * Plays the media item. - * @param {chrome.cast.media.PlayRequest} playRequest The optional media play request. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.play = function (playRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaPlay', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Pauses the media item. - * @param {chrome.cast.media.PauseRequest} pauseRequest The optional media pause request. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.pause = function (pauseRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaPause', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); -}; - -/** - * Seeks the media item. - * @param {chrome.cast.media.SeekRequest} seekRequest The media seek request. Must not be null. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.seek = function (seekRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaSeek', seekRequest.currentTime, seekRequest.resumeState || "", function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }) -}; - -/** - * Stops the media player. - * @param {chrome.cast.media.StopRequest} stopRequest The media stop request. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.stop = function (stopRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - - execute('mediaStop', function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }) -}; - -/** - * Sets the media stream volume. At least one of volumeRequest.level or volumeRequest.muted must be set. Changing the mute state does not affect the volume level, and vice versa. - * @param {chrome.cast.media.VolumeRequest} volumeRequest The set volume request. Must not be null. - * @param {function} successCallback Invoked on success. - * @param {function} errorCallback Invoked on error. The possible errors are TIMEOUT, API_NOT_INITIALIZED, INVALID_PARAMETER, CHANNEL_ERROR, SESSION_ERROR, and EXTENSION_MISSING. - */ -chrome.cast.media.Media.prototype.setVolume = function (volumeRequest, successCallback, errorCallback) { - if (chrome.cast.isAvailable === false) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.API_NOT_INITIALIZED), 'The API is not initialized.', {}); - return; - } - var args = []; - - if (volumeRequest.volume.level !== null) { - args.push('setMediaVolume'); - args.push(volumeRequest.volume.level); - } else if (volumeRequest.volume.muted !== null) { - args.push('setMediaMuted'); - args.push(volumeRequest.volume.muted); - } - - if (args.length < 2) { - errorCallback(new chrome.cast.Error(chrome.cast.ErrorCode.INVALID_PARAMETER), 'Invalid request.', {}); - } else { - args.push(function(err) { - if (!err) { - successCallback && successCallback(); - } else { - handleError(err, errorCallback); - } - }); - - execute.apply(null, args); - } -}; - -/** - * Determines whether the media player supports the given media command. - * @param {chrome.cast.media.MediaCommand} command The command to query. Must not be null. - * @returns {boolean} True if the player supports the command. - */ -chrome.cast.media.Media.prototype.supportsCommand = function (command) { - return this.supportsCommands.indexOf(command) > -1; -}; - -/** - * Estimates the current playback position. - * @returns {number} number An estimate of the current playback position in seconds since the start of the media. - */ -chrome.cast.media.Media.prototype.getEstimatedTime = function () { - if (this.playerState === chrome.cast.media.PlayerState.PLAYING) { - var elapsed = (Date.now() - this._lastUpdatedTime) / 1000; - var estimatedTime = this.currentTime + elapsed; - - return estimatedTime; - } else { - return this.currentTime; - } -}; - -/** - * Adds a listener that is invoked when the status of the media has changed. - * Changes to the following properties will trigger the listener: currentTime, volume, metadata, playbackRate, playerState, customData. - * @param {function} listener The listener to add. The parameter indicates whether the Media object is still alive. - */ -chrome.cast.media.Media.prototype.addUpdateListener = function (listener) { - this.on('_mediaUpdated', listener); -}; - -/** - * Removes a previously added listener for this Media. - * @param {function} listener The listener to remove. - */ -chrome.cast.media.Media.prototype.removeUpdateListener = function (listener) { - this.removeListener('_mediaUpdated', listener); -}; - -chrome.cast.media.Media.prototype._update = function(isAlive, obj) { - this.currentTime = obj.currentTime || this.currentTime; - this.idleReason = obj.idleReason || this.idleReason; - this.sessionId = obj.sessionId || this.sessionId; - this.mediaSessionId = obj.mediaSessionId || this.mediaSessionId; - this.playbackRate = obj.playbackRate || this.playbackRate; - this.playerState = obj.playerState || this.playerState; - - if (obj.media && obj.media.duration) { - this.media.duration = obj.media.duration || this.media.duration; - this.media.streamType = obj.media.streamType || this.media.streamType; - } - - this.volume.level = obj.volume.level; - this.volume.muted = obj.volume.muted; - - this._lastUpdatedTime = Date.now(); - - this.emit('_mediaUpdated', isAlive); -}; - - -function createRouteElement(route) { - var el = document.createElement('li'); - el.classList.add('route'); - el.addEventListener('touchstart', onRouteClick); - el.textContent = route.name; - el.setAttribute('data-routeid', route.id); - return el; -} - -function onRouteClick() { - var id = this.getAttribute('data-routeid'); - - if (id) { - chrome.cast.connectToId(id); - } -} - -chrome.cast.connectToId = function(id) { - return new Promise(function (resolve, reject) { - try { - chrome.cast._emitConnecting(); - } catch (e) { - console.error('Error in connectingListener', e); - } - - execute('selectRoute', id, function (err, obj) { - var sessionId = obj.sessionId; - var appId = obj.appId; - var displayName = obj.displayName; - var appImages = obj.appImages || []; - var receiver = new chrome.cast.Receiver(obj.receiver.label, obj.receiver.friendlyName, obj.receiver.capabilities || [], obj.volume || null); - - var session = _sessions[sessionId] = new chrome.cast.Session(sessionId, appId, displayName, appImages, receiver); - - _sessionListener && _sessionListener(session); - resolve(); - }); - }); -}; - -chrome.cast.getRouteListElement = function() { - return _routeListEl; -}; - -chrome.cast.getRouteList = function () { - var routes = []; - for (var id in _routeList) { - routes.push(_routeList[id]); - } - return routes; -}; - - -var _connectingListeners = []; -chrome.cast.addConnectingListener = function(cb) { - _connectingListeners.push(cb); -}; - -chrome.cast.removeConnectingListener = function(cb) { - if (_connectingListeners.indexOf(cb) > -1) { - _connectingListeners.splice(_connectingListeners.indexOf(cb), 1); - } -}; - -chrome.cast._emitConnecting = function() { - for (var n = 0; n < _connectingListeners.length; n++) { - _connectingListeners[n](); - } -}; - -chrome.cast._ = { - receiverUnavailable: function() { - _receiverListener(chrome.cast.ReceiverAvailability.UNAVAILABLE); - _receiverAvailable = false; - }, - receiverAvailable: function() { - _receiverListener(chrome.cast.ReceiverAvailability.AVAILABLE); - _receiverAvailable = true; - }, - routeAdded: function(route) { - if (!_routeList[route.id]) { - route.el = createRouteElement(route); - _routeList[route.id] = route; - - _routeListEl.appendChild(route.el); - } - }, - routeRemoved: function(route) { - if (_routeList[route.id]) { - _routeList[route.id].el.remove(); - delete _routeList[route.id]; - } - }, - sessionUpdated: function(isAlive, session) { - if (session && session.sessionId && _sessions[session.sessionId]) { - _sessions[session.sessionId]._update(isAlive, session); - } - }, - mediaUpdated: function(isAlive, media) { - - if (media && media.mediaSessionId !== undefined) - { - if (_currentMedia) { - _currentMedia._update(isAlive, media); - } else { - _currentMedia = new chrome.cast.media.Media(media.sessionId, media.mediaSessionId); - _currentMedia.currentTime = media.currentTime; - _currentMedia.playerState = media.playerState; - _currentMedia.media = media.media; - - _sessions[media.sessionId].media[0] = _currentMedia; - _sessionListener && _sessionListener(_sessions[media.sessionId]); - } - } - }, - mediaLoaded: function(isAlive, media) { - if (_sessions[media.sessionId]) { - - if (!_currentMedia) - { - _currentMedia = new chrome.cast.media.Media(media.sessionId, media.mediaSessionId); - } - _currentMedia._update(isAlive, media); - _sessions[media.sessionId].emit('_mediaListener', _currentMedia); - } else { - console.log('mediaLoaded --- but there is no session tied to it', media); - } - }, - sessionJoined: function(obj) { - var sessionId = obj.sessionId; - var appId = obj.appId; - var displayName = obj.displayName; - var appImages = obj.appImages || []; - var receiver = new chrome.cast.Receiver(obj.receiver.label, obj.receiver.friendlyName, obj.receiver.capabilities || [], obj.volume || null); - - var session = _sessions[sessionId] = new chrome.cast.Session(sessionId, appId, displayName, appImages, receiver); - - if (obj.media && obj.media.sessionId) - { - _currentMedia = new chrome.cast.media.Media(sessionId, obj.media.mediaSessionId); - _currentMedia.currentTime = obj.media.currentTime; - _currentMedia.playerState = obj.media.playerState; - _currentMedia.media = obj.media.media; - session.media[0] = _currentMedia; - } - - _sessionListener && _sessionListener(session); - }, - onMessage: function(sessionId, namespace, message) { - if (_sessions[sessionId]) { - _sessions[sessionId].emit('message:' + namespace, namespace, message); - } - } -}; - - -module.exports = chrome.cast; - -function execute (action) { - var args = [].slice.call(arguments); - args.shift(); - var callback; - if (args[args.length-1] instanceof Function) { - callback = args.pop(); - } - cordova.exec(function (result) { callback && callback(null, result); }, function(err) { callback && callback(err); }, "Chromecast", action, args); -} - -function handleError(err, callback) { - var errorCode = chrome.cast.ErrorCode.UNKNOWN; - var errorDescription = err; - var errorData = {}; - - err = err || ""; - if (err.toUpperCase() === 'TIMEOUT') { - errorCode = chrome.cast.ErrorCode.TIMEOUT; - errorDescription = 'The operation timed out.'; - } else if (err.toUpperCase() === 'INVALID_PARAMETER') { - errorCode = chrome.cast.ErrorCode.INVALID_PARAMETER; - errorDescription = 'The parameters to the operation were not valid.'; - } else if (err.toUpperCase() === 'RECEIVER_UNAVAILABLE') { - errorCode = chrome.cast.ErrorCode.RECEIVER_UNAVAILABLE; - errorDescription = 'No receiver was compatible with the session request.'; - } else if (err.toUpperCase() === 'CANCEL') { - errorCode = chrome.cast.ErrorCode.CANCEL; - errorDescription = 'The operation was canceled by the user.'; - } else if (err.toUpperCase() === 'CHANNEL_ERROR') { - errorCode = chrome.cast.ErrorCode.CHANNEL_ERROR; - errorDescription = 'A channel to the receiver is not available.'; - } else if (err.toUpperCase() === 'SESSION_ERROR') { - errorCode = chrome.cast.ErrorCode.SESSION_ERROR; - errorDescription = 'A session could not be created, or a session was invalid.'; - } - - var error = new Error(errorCode, errorDescription, errorData); - if (callback) { - callback(error); - } -} - - -execute('setup', function(err) { - if (!err) { - chrome.cast.isAvailable = true; - } else { - throw new Error('Unable to setup chrome.cast API' + err); - } -}); \ No newline at end of file diff --git a/plugins/acidhax.cordova.chromecast/init-playservices-dependencies.js b/plugins/acidhax.cordova.chromecast/init-playservices-dependencies.js deleted file mode 100644 index b4d2eae..0000000 --- a/plugins/acidhax.cordova.chromecast/init-playservices-dependencies.js +++ /dev/null @@ -1,161 +0,0 @@ -#!/usr/bin/env node - -// Adds Google PlayServices dependencies to the current Cordova project -// This is done by turning (a copy of) Android SDK libraries AppCompat, MediaRouter and PlayServices into -// project libraries and linking them to the current project. -// Requires the Android SDK to be installed locally including ANDROID_HOME environment variable to be set. - -var fs = require('fs'); -var path = require('path'); -var exec = require('child_process').exec; - -var androidHome = process.env.ANDROID_HOME; -if( !androidHome ) { - //throw new Error("Environment variable ANDROID_HOME is not set to Android SDK directory"); -} -else { - console.log("Found Android SDK at "+androidHome); -} - - -/** - * Copies an entire directory into another - */ -var copyRecursiveSync = function(src, dest) { - var exists = fs.existsSync(src); - var stats = exists && fs.statSync(src); - var isDirectory = exists && stats.isDirectory(); - if (exists && isDirectory) { - fs.mkdirSync(dest); - fs.readdirSync(src).forEach(function(childItemName) { - copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName)); - }); - } else { - fs.createReadStream( src ).pipe( fs.createWriteStream( dest ) ); - } -}; - -/** - * Executes an (external) command - */ -var execCommand = function(command, callback) { - - console.log("Executing "+command+" ..."); - var p = exec(command, function(error, stdout, stderr) { - - if(!!stdout ) { - console.log("Exec: "+stdout); - } - if(!!stderr ) { - console.error("Exec: "+stderr); - } - if(!!error ) { - throw new Error("Exec: "+error); - } - }); - p.on("close", function(code) { - if( code !== 0 ) { - throw new Error("Error executing "+command+": "+code); - } - console.info("Executed "+command); - if( !!callback ) { - callback(); - } - }); -}; - -/** - * Turns a project into an android "library project" - * @param path The location of the project - */ -var prepareLibraryProject = function(path, callback) { - - execCommand(androidHome+"/tools/android update lib-project -p "+path+" -t \"android-21\"", function() { - execCommand("ant clean -f "+path+"/build.xml", function() { - execCommand("ant release -f "+path+"/build.xml", function() { - - console.info("Turned "+path+" into a library project"); - if(!!callback ) { - callback(); - } - }); - }); - }); -}; - -/** - * Adds a library reference to a "library project" - * @param libraryPath path The location of the project - * @param referencePaths The relative locations of the references - */ -var addLibraryReference = function(libraryPath, referencePaths, callback) { - - var projectProperties = libraryPath+"/project.properties"; - console.info("Adding references "+referencePaths+" to "+projectProperties); - - fs.readFile(projectProperties, 'utf8', function (err,data) { - if (err) { - throw new Error("Error reading "+projectProperties); - } - - // find the next available reference index - var referenceIndex = 1; - while( data.indexOf('android.library.reference.'+referenceIndex) > -1 ) { - referenceIndex++; - } - - // compute the entries to be appended - var appends = ""; - for( var i=0; i - - - - - - Cordova ChromeCast - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/acidhax.cordova.chromecast/src/android/Chromecast.java b/plugins/acidhax.cordova.chromecast/src/android/Chromecast.java deleted file mode 100644 index eb5ce10..0000000 --- a/plugins/acidhax.cordova.chromecast/src/android/Chromecast.java +++ /dev/null @@ -1,785 +0,0 @@ -package acidhax.cordova.chromecast; - -import android.annotation.TargetApi; -import android.os.Build; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.HashMap; -import java.util.List; -import java.util.ArrayList; - -import com.google.android.gms.cast.CastMediaControlIntent; - -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.content.SharedPreferences; -import android.support.v7.media.MediaRouter; -import android.support.v7.media.MediaRouteSelector; -import android.support.v7.media.MediaRouter.RouteInfo; -import android.util.Log; -import android.widget.ArrayAdapter; - -public class Chromecast extends CordovaPlugin implements ChromecastOnMediaUpdatedListener, ChromecastOnSessionUpdatedListener { - - private static final String SETTINGS_NAME= "CordovaChromecastSettings"; - - private MediaRouter mMediaRouter; - private MediaRouteSelector mMediaRouteSelector; - private volatile ChromecastMediaRouterCallback mMediaRouterCallback = new ChromecastMediaRouterCallback(); - private String appId; - - private boolean autoConnect = false; - private String lastSessionId = null; - private String lastAppId = null; - - private SharedPreferences settings; - - - private volatile ChromecastSession currentSession; - - private void log(String s) { - sendJavascript("console.log('" + s + "');"); - } - - - public void initialize(final CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - - // Restore preferences - this.settings = this.cordova.getActivity().getSharedPreferences(SETTINGS_NAME, 0); - this.lastSessionId = settings.getString("lastSessionId", ""); - this.lastAppId = settings.getString("lastAppId", ""); - } - - public void onDestroy() { - super.onDestroy(); - - if (this.currentSession != null) { -// this.currentSession.kill(new ChromecastSessionCallback() { -// void onSuccess(Object object) { } -// void onError(String reason) {} -// }); - } - } - - @Override - public boolean execute(String action, JSONArray args, CallbackContext cbContext) throws JSONException { - try { - Method[] list = this.getClass().getMethods(); - Method methodToExecute = null; - for (Method method : list) { - if (method.getName().equals(action)) { - Type[] types = method.getGenericParameterTypes(); - if (args.length() + 1 == types.length) { // +1 is the cbContext - boolean isValid = true; - for (int i = 0; i < args.length(); i++) { - Class arg = args.get(i).getClass(); - if (types[i] == arg) { - isValid = true; - } else { - isValid = false; - break; - } - } - if (isValid) { - methodToExecute = method; - break; - } - } - } - } - if (methodToExecute != null) { - Type[] types = methodToExecute.getGenericParameterTypes(); - Object[] variableArgs = new Object[types.length]; - for (int i = 0; i < args.length(); i++) { - variableArgs[i] = args.get(i); - } - variableArgs[variableArgs.length-1] = cbContext; - Class r = methodToExecute.getReturnType(); - if (r == boolean.class) { - return (Boolean) methodToExecute.invoke(this, variableArgs); - } else { - methodToExecute.invoke(this, variableArgs); - return true; - } - } else { - return false; - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - return false; - } catch (IllegalArgumentException e) { - e.printStackTrace(); - return false; - } catch (InvocationTargetException e) { - e.printStackTrace(); - return false; - } - } - - private void setLastSessionId(String sessionId) { - this.lastSessionId = sessionId; - this.settings.edit().putString("lastSessionId", sessionId).apply(); - } - - - /** - * Do everything you need to for "setup" - calling back sets the isAvailable and lets every function on the - * javascript side actually do stuff. - * @param callbackContext - */ - public boolean setup (CallbackContext callbackContext) { - callbackContext.success(); - - return true; - } - - /** - * Initialize all of the MediaRouter stuff with the AppId - * For now, ignore the autoJoinPolicy and defaultActionPolicy; those will come later - * @param appId The appId we're going to use for ALL session requests - * @param autoJoinPolicy tab_and_origin_scoped | origin_scoped | page_scoped - * @param defaultActionPolicy create_session | cast_this_tab - * @param callbackContext - */ - public boolean initialize (final String appId, String autoJoinPolicy, String defaultActionPolicy, final CallbackContext callbackContext) { - final Activity activity = cordova.getActivity(); - final Chromecast that = this; - this.appId = appId; - - log("initialize " + autoJoinPolicy + " " + appId + " " + this.lastAppId); - if (autoJoinPolicy.equals("origin_scoped") && appId.equals(this.lastAppId)) { - log("lastAppId " + lastAppId); - autoConnect = true; - } else if (autoJoinPolicy.equals("origin_scoped")) { - log("setting lastAppId " + lastAppId); - this.settings.edit().putString("lastAppId", appId).apply(); - } - - activity.runOnUiThread(new Runnable() { - public void run() { - mMediaRouter = MediaRouter.getInstance(activity.getApplicationContext()); - mMediaRouteSelector = new MediaRouteSelector.Builder() - .addControlCategory(CastMediaControlIntent.categoryForCast(appId)) - .build(); - mMediaRouterCallback.registerCallbacks(that); - mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_PERFORM_ACTIVE_SCAN); - callbackContext.success(); - - Chromecast.this.checkReceiverAvailable(); - Chromecast.this.emitAllRoutes(null); - } - }); - - return true; - } - - /** - * Request the session for the previously sent appId - * THIS IS WHAT LAUNCHES THE CHROMECAST PICKER - * NOTE: Make a request session that is automatic - it'll do most of this code - refactor will be required - * @param callbackContext - */ - public boolean requestSession (final CallbackContext callbackContext) { - if (this.currentSession != null) { - callbackContext.success(this.currentSession.createSessionObject()); - return true; - } - - this.setLastSessionId(""); - - final Activity activity = cordova.getActivity(); - activity.runOnUiThread(new Runnable() { - public void run() { - mMediaRouter = MediaRouter.getInstance(activity.getApplicationContext()); - final List routeList = mMediaRouter.getRoutes(); - - AlertDialog.Builder builder = new AlertDialog.Builder(activity); - builder.setTitle("Choose a Chromecast"); - //CharSequence[] seq = new CharSequence[routeList.size() -1]; - ArrayList seq_tmp1 = new ArrayList(); - - final ArrayList seq_tmp_cnt_final = new ArrayList(); - - for (int n = 1; n < routeList.size(); n++) { - RouteInfo route = routeList.get(n); - if (!route.getName().equals("Phone") && route.getId().indexOf("Cast") > -1) { - seq_tmp1.add(route.getName()); - seq_tmp_cnt_final.add(n); - //seq[n-1] = route.getName(); - } - } - - CharSequence[] seq; - seq = seq_tmp1.toArray(new CharSequence[seq_tmp1.size()]); - - builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - dialog.dismiss(); - callbackContext.error("cancel"); - } - }); - - builder.setItems(seq, new DialogInterface.OnClickListener() { - @Override - public void onClick(DialogInterface dialog, int which) { - which = seq_tmp_cnt_final.get(which); - RouteInfo selectedRoute = routeList.get(which); - //RouteInfo selectedRoute = routeList.get(which + 1); - Chromecast.this.createSession(selectedRoute, callbackContext); - } - }); - - builder.show(); - - } - }); - - return true; - } - - - /** - * Selects a route by its id - * @param routeId - * @param callbackContext - * @return - */ - public boolean selectRoute (final String routeId, final CallbackContext callbackContext) { - if (this.currentSession != null) { - callbackContext.success(this.currentSession.createSessionObject()); - return true; - } - - this.setLastSessionId(""); - - final Activity activity = cordova.getActivity(); - activity.runOnUiThread(new Runnable() { - public void run() { - mMediaRouter = MediaRouter.getInstance(activity.getApplicationContext()); - final List routeList = mMediaRouter.getRoutes(); - - for (RouteInfo route : routeList) { - if (route.getId().equals(routeId)) { - Chromecast.this.createSession(route, callbackContext); - return; - } - } - - callbackContext.error("No route found"); - - } - }); - - return true; - } - - /** - * Helper for the creating of a session! The user-selected RouteInfo needs to be passed to a new ChromecastSession - * @param routeInfo - * @param callbackContext - */ - private void createSession(RouteInfo routeInfo, final CallbackContext callbackContext) { - this.currentSession = new ChromecastSession(routeInfo, this.cordova, this, this); - - // Launch the app. - this.currentSession.launch(this.appId, new ChromecastSessionCallback() { - - @Override - void onSuccess(Object object) { - ChromecastSession session = (ChromecastSession) object; - if (object == null) { - onError("unknown"); - } else if (session == Chromecast.this.currentSession){ - Chromecast.this.setLastSessionId(Chromecast.this.currentSession.getSessionId()); - - if (callbackContext != null) { - callbackContext.success(session.createSessionObject()); - } else { - sendJavascript("chrome.cast._.sessionJoined(" + Chromecast.this.currentSession.createSessionObject().toString() + ");"); - } - } - } - - @Override - void onError(String reason) { - if (reason != null) { - Chromecast.this.log("createSession onError " + reason); - if (callbackContext != null) { - callbackContext.error(reason); - } - } else { - if (callbackContext != null) { - callbackContext.error("unknown"); - } - } - } - - }); - } - - private void joinSession(RouteInfo routeInfo) { - ChromecastSession sessionJoinAttempt = new ChromecastSession(routeInfo, this.cordova, this, this); - sessionJoinAttempt.join(this.appId, this.lastSessionId, new ChromecastSessionCallback() { - - @Override - void onSuccess(Object object) { - if (Chromecast.this.currentSession == null) { - try { - Chromecast.this.currentSession = (ChromecastSession) object; - Chromecast.this.setLastSessionId(Chromecast.this.currentSession.getSessionId()); - sendJavascript("chrome.cast._.sessionJoined(" + Chromecast.this.currentSession.createSessionObject().toString() + ");"); - } catch (Exception e) { - log("wut.... " + e.getMessage() + e.getStackTrace()); - } - } - } - - @Override - void onError(String reason) { - log("sessionJoinAttempt error " +reason); - } - - }); - } - - /** - * Set the volume level on the receiver - this is a Chromecast volume, not a Media volume - * @param newLevel - */ - public boolean setReceiverVolumeLevel (Double newLevel, CallbackContext callbackContext) { - if (this.currentSession != null) { - this.currentSession.setVolume(newLevel, genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - return true; - } - - public boolean setReceiverVolumeLevel (Integer newLevel, CallbackContext callbackContext) { - return this.setReceiverVolumeLevel(newLevel.doubleValue(), callbackContext); - } - - /** - * Sets the muted boolean on the receiver - this is a Chromecast mute, not a Media mute - * @param muted - * @param callbackContext - */ - public boolean setReceiverMuted (Boolean muted, CallbackContext callbackContext) { - if (this.currentSession != null) { - this.currentSession.setMute(muted, genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - return true; - } - - /** - * Stop the session! Disconnect! All of that jazz! - * @param callbackContext [description] - */ - public boolean stopSession(CallbackContext callbackContext) { - callbackContext.error("not_implemented"); - return true; - } - - /** - * Send a custom message to the receiver - we don't need this just yet... it was just simple to implement on the js side - * @param namespace - * @param message - * @param callbackContext - */ - public boolean sendMessage (String namespace, String message, final CallbackContext callbackContext) { - if (this.currentSession != null) { - this.currentSession.sendMessage(namespace, message, new ChromecastSessionCallback() { - - @Override - void onSuccess(Object object) { - callbackContext.success(); - } - - @Override - void onError(String reason) { - callbackContext.error(reason); - } - }); - } - return true; - } - - - /** - * Adds a listener to a specific namespace - * @param namespace - * @param callbackContext - * @return - */ - public boolean addMessageListener(String namespace, CallbackContext callbackContext) { - if (this.currentSession != null) { - this.currentSession.addMessageListener(namespace); - callbackContext.success(); - } - return true; - } - - /** - * Loads some media on the Chromecast using the media APIs - * @param contentId The URL of the media item - * @param contentType MIME type of the content - * @param duration Duration of the content - * @param streamType buffered | live | other - * @param loadRequest.autoPlay Whether or not to automatically start playing the media - * @param loadRequest.currentTime Where to begin playing from - * @param callbackContext - */ - public boolean loadMedia (String contentId, String contentType, Integer duration, String streamType, Boolean autoPlay, Double currentTime, JSONObject metadata, final CallbackContext callbackContext) { - - if (this.currentSession != null) { - return this.currentSession.loadMedia(contentId, contentType, duration, streamType, autoPlay, currentTime, metadata, - new ChromecastSessionCallback() { - - @Override - void onSuccess(Object object) { - if (object == null) { - onError("unknown"); - } else { - callbackContext.success((JSONObject) object); - } - } - - @Override - void onError(String reason) { - callbackContext.error(reason); - } - - }); - } else { - callbackContext.error("session_error"); - return false; - } - } - public boolean loadMedia (String contentId, String contentType, Integer duration, String streamType, Boolean autoPlay, Integer currentTime, JSONObject metadata, final CallbackContext callbackContext) { - return this.loadMedia (contentId, contentType, duration, streamType, autoPlay, new Double(currentTime.doubleValue()), metadata, callbackContext); - } - - /** - * Play on the current media in the current session - * @param callbackContext - * @return - */ - public boolean mediaPlay(CallbackContext callbackContext) { - if (currentSession != null) { - currentSession.mediaPlay(genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - return true; - } - - /** - * Pause on the current media in the current session - * @param callbackContext - * @return - */ - public boolean mediaPause(CallbackContext callbackContext) { - if (currentSession != null) { - currentSession.mediaPause(genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - return true; - } - - - /** - * Seeks the current media in the current session - * @param seekTime - * @param resumeState - * @param callbackContext - * @return - */ - public boolean mediaSeek(Integer seekTime, String resumeState, CallbackContext callbackContext) { - if (currentSession != null) { - currentSession.mediaSeek(seekTime.longValue() * 1000, resumeState, genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - return true; - } - - - /** - * Set the volume on the media - * @param level - * @param callbackContext - * @return - */ - public boolean setMediaVolume(Double level, CallbackContext callbackContext) { - if (currentSession != null) { - currentSession.mediaSetVolume(level, genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - - return true; - } - - /** - * Set the muted on the media - * @param muted - * @param callbackContext - * @return - */ - public boolean setMediaMuted(Boolean muted, CallbackContext callbackContext) { - if (currentSession != null) { - currentSession.mediaSetMuted(muted, genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - - return true; - } - - /** - * Stops the current media! - * @param callbackContext - * @return - */ - public boolean mediaStop(CallbackContext callbackContext) { - if (currentSession != null) { - currentSession.mediaStop(genericCallback(callbackContext)); - } else { - callbackContext.error("session_error"); - } - - return true; - } - - /** - * Stops the session - * @param callbackContext - * @return - */ - public boolean sessionStop (CallbackContext callbackContext) { - if (this.currentSession != null) { - this.currentSession.kill(genericCallback(callbackContext)); - this.currentSession = null; - this.setLastSessionId(""); - } else { - callbackContext.success(); - } - - return true; - } - - /** - * Stops the session - * @param callbackContext - * @return - */ - public boolean sessionLeave (CallbackContext callbackContext) { - if (this.currentSession != null) { - this.currentSession.leave(genericCallback(callbackContext)); - this.currentSession = null; - this.setLastSessionId(""); - } else { - callbackContext.success(); - } - - return true; - } - - public boolean emitAllRoutes(CallbackContext callbackContext) { - final Activity activity = cordova.getActivity(); - - activity.runOnUiThread(new Runnable() { - public void run() { - mMediaRouter = MediaRouter.getInstance(activity.getApplicationContext()); - List routeList = mMediaRouter.getRoutes(); - - for (RouteInfo route : routeList) { - if (!route.getName().equals("Phone") && route.getId().indexOf("Cast") > -1) { - sendJavascript("chrome.cast._.routeAdded(" + routeToJSON(route) + ")"); - } - } - } - }); - - if (callbackContext != null) { - callbackContext.success(); - } - - return true; - } - - /** - * Checks to see how many receivers are available - emits the receiver status down to Javascript - */ - private void checkReceiverAvailable() { - final Activity activity = cordova.getActivity(); - - activity.runOnUiThread(new Runnable() { - public void run() { - mMediaRouter = MediaRouter.getInstance(activity.getApplicationContext()); - List routeList = mMediaRouter.getRoutes(); - boolean available = false; - - for (RouteInfo route: routeList) { - if (!route.getName().equals("Phone") && route.getId().indexOf("Cast") > -1) { - available = true; - break; - } - } - if (available || (Chromecast.this.currentSession != null && Chromecast.this.currentSession.isConnected())) { - sendJavascript("chrome.cast._.receiverAvailable()"); - } else { - sendJavascript("chrome.cast._.receiverUnavailable()"); - } - } - }); - } - - /** - * Creates a ChromecastSessionCallback that's generic for a CallbackContext - * @param callbackContext - * @return - */ - private ChromecastSessionCallback genericCallback (final CallbackContext callbackContext) { - return new ChromecastSessionCallback() { - - @Override - public void onSuccess(Object object) { - callbackContext.success(); - } - - @Override - public void onError(String reason) { - callbackContext.error(reason); - } - - }; - }; - - /** - * Called when a route is discovered - * @param router - * @param route - */ - protected void onRouteAdded(MediaRouter router, final RouteInfo route) { - if (this.autoConnect && this.currentSession == null && !route.getName().equals("Phone")) { - log("Attempting to join route " + route.getName()); - this.joinSession(route); - } else { - log("For some reason, not attempting to join route " + route.getName() + ", " + this.currentSession + ", " + this.autoConnect); - } - if (!route.getName().equals("Phone") && route.getId().indexOf("Cast") > -1) { - sendJavascript("chrome.cast._.routeAdded(" + routeToJSON(route) + ")"); - } - this.checkReceiverAvailable(); - } - - /** - * Called when a discovered route is lost - * @param router - * @param route - */ - protected void onRouteRemoved(MediaRouter router, RouteInfo route) { - this.checkReceiverAvailable(); - if (!route.getName().equals("Phone") && route.getId().indexOf("Cast") > -1) { - sendJavascript("chrome.cast._.routeRemoved(" + routeToJSON(route) + ")"); - } - } - - /** - * Called when a route is selected through the MediaRouter - * @param router - * @param route - */ - protected void onRouteSelected(MediaRouter router, RouteInfo route) { - this.createSession(route, null); - } - - /** - * Called when a route is unselected through the MediaRouter - * @param router - * @param route - */ - protected void onRouteUnselected(MediaRouter router, RouteInfo route) {} - - /** - * Simple helper to convert a route to JSON for passing down to the javascript side - * @param route - * @return - */ - private JSONObject routeToJSON(RouteInfo route) { - JSONObject obj = new JSONObject(); - - try { - obj.put("name", route.getName()); - obj.put("id", route.getId()); - } catch (JSONException e) { - e.printStackTrace(); - } - - return obj; - } - - @Override - public void onMediaUpdated(boolean isAlive, JSONObject media) { - if (isAlive) { - sendJavascript("chrome.cast._.mediaUpdated(true, " + media.toString() +");"); - } else { - sendJavascript("chrome.cast._.mediaUpdated(false, " + media.toString() +");"); - } - } - - @Override - public void onSessionUpdated(boolean isAlive, JSONObject session) { - if (isAlive) { - sendJavascript("chrome.cast._.sessionUpdated(true, " + session.toString() + ");"); - } else { - log("SESSION DESTROYYYY"); - sendJavascript("chrome.cast._.sessionUpdated(false, " + session.toString() + ");"); - this.currentSession = null; - } - } - - @Override - public void onMediaLoaded(JSONObject media) { - sendJavascript("chrome.cast._.mediaLoaded(true, " + media.toString() +");"); - } - - @Override - public void onMessage(ChromecastSession session, String namespace, String message) { - sendJavascript("chrome.cast._.onMessage('" + session.getSessionId() +"', '" + namespace + "', '" + message + "')"); - } - - //Change all @deprecated this.webView.sendJavascript(String) to this local function sendJavascript(String) - @TargetApi(Build.VERSION_CODES.KITKAT) - private void sendJavascript(final String javascript) { - - webView.post(new Runnable() { - @Override - public void run() { - // See: https://github.com/GoogleChrome/chromium-webview-samples/blob/master/jsinterface-example/app/src/main/java/jsinterfacesample/android/chrome/google/com/jsinterface_example/MainFragment.java - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { - webView.evaluateJavascript(javascript, null); - } else { - webView.loadUrl("javascript:" + javascript); - } - } - }); - } - -} diff --git a/plugins/acidhax.cordova.chromecast/src/android/ChromecastException.java b/plugins/acidhax.cordova.chromecast/src/android/ChromecastException.java deleted file mode 100644 index 77fa03e..0000000 --- a/plugins/acidhax.cordova.chromecast/src/android/ChromecastException.java +++ /dev/null @@ -1,5 +0,0 @@ -package acidhax.cordova.chromecast; - -public class ChromecastException extends Exception { - -} diff --git a/plugins/acidhax.cordova.chromecast/src/android/ChromecastMediaController.java b/plugins/acidhax.cordova.chromecast/src/android/ChromecastMediaController.java deleted file mode 100644 index 8d8ceab..0000000 --- a/plugins/acidhax.cordova.chromecast/src/android/ChromecastMediaController.java +++ /dev/null @@ -1,138 +0,0 @@ -package acidhax.cordova.chromecast; - -import com.google.android.gms.cast.MediaInfo; -import com.google.android.gms.cast.MediaMetadata; -import com.google.android.gms.cast.RemoteMediaPlayer; -import com.google.android.gms.cast.RemoteMediaPlayer.MediaChannelResult; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.common.api.PendingResult; -import com.google.android.gms.common.api.ResultCallback; -import com.google.android.gms.common.images.WebImage; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.net.Uri; -import android.util.Log; - -public class ChromecastMediaController { - private RemoteMediaPlayer remote = null; - public ChromecastMediaController(RemoteMediaPlayer mRemoteMediaPlayer) { - this.remote = mRemoteMediaPlayer; - } - - public MediaInfo createLoadUrlRequest(String contentId, String contentType, long duration, String streamType, JSONObject metadata) { - - // Try creating a GENERIC MediaMetadata obj - MediaMetadata mediaMetadata = new MediaMetadata(); - try { - - int metadataType = metadata.has("metadataType") ? metadata.getInt("metadataType") : MediaMetadata.MEDIA_TYPE_MOVIE; - - // GENERIC - if (metadataType == MediaMetadata.MEDIA_TYPE_GENERIC) { - mediaMetadata = new MediaMetadata(); // Creates GENERIC MediaMetaData - mediaMetadata.putString(MediaMetadata.KEY_TITLE, (metadata.has("title")) ? metadata.getString("title") : "[Title not set]" ); // TODO: What should it default to? - mediaMetadata.putString(MediaMetadata.KEY_SUBTITLE, (metadata.has("title")) ? metadata.getString("subtitle") : "[Subtitle not set]" ); // TODO: What should it default to? - mediaMetadata = addImages(metadata, mediaMetadata); - } - - } catch(Exception e) { - e.printStackTrace(); - // Fallback - mediaMetadata = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE); - } - - int _streamType = MediaInfo.STREAM_TYPE_BUFFERED; - if (streamType.equals("buffered")) { - - } else if (streamType.equals("live")) { - _streamType = MediaInfo.STREAM_TYPE_LIVE; - } else if (streamType.equals("other")) { - _streamType = MediaInfo.STREAM_TYPE_NONE; - } - - MediaInfo mediaInfo = new MediaInfo.Builder(contentId) - .setContentType(contentType) - .setStreamType(_streamType) - .setStreamDuration(duration) - .setMetadata(mediaMetadata) - .build(); - - return mediaInfo; - } - - public void play(GoogleApiClient apiClient, ChromecastSessionCallback callback) { - PendingResult res = this.remote.play(apiClient); - res.setResultCallback(this.createMediaCallback(callback)); - } - - public void pause(GoogleApiClient apiClient, ChromecastSessionCallback callback) { - PendingResult res = this.remote.pause(apiClient); - res.setResultCallback(this.createMediaCallback(callback)); - } - - public void stop(GoogleApiClient apiClient, ChromecastSessionCallback callback) { - PendingResult res = this.remote.stop(apiClient); - res.setResultCallback(this.createMediaCallback(callback)); - } - - public void seek(long seekPosition, String resumeState, GoogleApiClient apiClient, final ChromecastSessionCallback callback) { - PendingResult res = null; - if (resumeState != null && !resumeState.equals("")) { - if (resumeState.equals("PLAYBACK_PAUSE")) { - res = this.remote.seek(apiClient, seekPosition, RemoteMediaPlayer.RESUME_STATE_PAUSE); - } else if (resumeState.equals("PLAYBACK_START")) { - res = this.remote.seek(apiClient, seekPosition, RemoteMediaPlayer.RESUME_STATE_PLAY); - } else { - res = this.remote.seek(apiClient, seekPosition, RemoteMediaPlayer.RESUME_STATE_UNCHANGED); - } - } - - if (res == null) { - res = this.remote.seek(apiClient, seekPosition); - } - - res.setResultCallback(this.createMediaCallback(callback)); - } - - public void setVolume(double volume, GoogleApiClient apiClient, final ChromecastSessionCallback callback) { - PendingResult res = this.remote.setStreamVolume(apiClient, volume); - res.setResultCallback(this.createMediaCallback(callback)); - } - - public void setMuted(boolean muted, GoogleApiClient apiClient, final ChromecastSessionCallback callback) { - PendingResult res = this.remote.setStreamMute(apiClient, muted); - res.setResultCallback(this.createMediaCallback(callback)); - } - - private ResultCallback createMediaCallback(final ChromecastSessionCallback callback) { - return new ResultCallback() { - @Override - public void onResult(MediaChannelResult result) { - if (result.getStatus().isSuccess()) { - callback.onSuccess(); - } else { - callback.onError("channel_error"); - } - } - }; - } - - private MediaMetadata addImages(JSONObject metadata, MediaMetadata mediaMetadata) throws JSONException { - if (metadata.has("images")) { - JSONArray imageUrls = metadata.getJSONArray("images"); - for (int i=0; i routes = new ArrayList(); - - private Chromecast callback = null; - - public void registerCallbacks(Chromecast instance) { - this.callback = instance; - } - - public synchronized RouteInfo getRoute(String id) { - for (RouteInfo i : this.routes) { - if (i.getId().equals(id)) { - return i; - } - } - return null; - } - - public synchronized RouteInfo getRoute(int index) { - return routes.get(index); - } - - public synchronized Collection getRoutes() { - return routes; - } - - @Override - public synchronized void onRouteAdded(MediaRouter router, RouteInfo route) { - routes.add(route); - if (this.callback != null) { - this.callback.onRouteAdded(router, route); - } - } - - @Override - public void onRouteRemoved(MediaRouter router, RouteInfo route) { - routes.remove(route); - if (this.callback != null) { - this.callback.onRouteRemoved(router, route); - } - } - - @Override - public void onRouteSelected(MediaRouter router, RouteInfo info) { - if (this.callback != null) { - this.callback.onRouteSelected(router, info); - } - } - - @Override - public void onRouteUnselected(MediaRouter router, RouteInfo info) { - if (this.callback != null) { - this.callback.onRouteUnselected(router, info); - } - } -} diff --git a/plugins/acidhax.cordova.chromecast/src/android/ChromecastOnMediaUpdatedListener.java b/plugins/acidhax.cordova.chromecast/src/android/ChromecastOnMediaUpdatedListener.java deleted file mode 100644 index 034c796..0000000 --- a/plugins/acidhax.cordova.chromecast/src/android/ChromecastOnMediaUpdatedListener.java +++ /dev/null @@ -1,8 +0,0 @@ -package acidhax.cordova.chromecast; - -import org.json.JSONObject; - -public interface ChromecastOnMediaUpdatedListener { - void onMediaLoaded(JSONObject media); - void onMediaUpdated(boolean isAlive, JSONObject media); -} \ No newline at end of file diff --git a/plugins/acidhax.cordova.chromecast/src/android/ChromecastOnSessionUpdatedListener.java b/plugins/acidhax.cordova.chromecast/src/android/ChromecastOnSessionUpdatedListener.java deleted file mode 100644 index 4172e49..0000000 --- a/plugins/acidhax.cordova.chromecast/src/android/ChromecastOnSessionUpdatedListener.java +++ /dev/null @@ -1,8 +0,0 @@ -package acidhax.cordova.chromecast; - -import org.json.JSONObject; - -public interface ChromecastOnSessionUpdatedListener { - void onSessionUpdated(boolean isAlive, JSONObject properties); - void onMessage(ChromecastSession session, String namespace, String message); -} \ No newline at end of file diff --git a/plugins/acidhax.cordova.chromecast/src/android/ChromecastSession.java b/plugins/acidhax.cordova.chromecast/src/android/ChromecastSession.java deleted file mode 100644 index dbcfd47..0000000 --- a/plugins/acidhax.cordova.chromecast/src/android/ChromecastSession.java +++ /dev/null @@ -1,665 +0,0 @@ -package acidhax.cordova.chromecast; - -import java.io.IOException; -import java.util.HashSet; -import java.util.List; - -import org.apache.cordova.CordovaInterface; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import com.google.android.gms.cast.ApplicationMetadata; -import com.google.android.gms.cast.Cast; -import com.google.android.gms.cast.Cast.ApplicationConnectionResult; -import com.google.android.gms.cast.CastDevice; -import com.google.android.gms.cast.MediaInfo; -import com.google.android.gms.cast.MediaStatus; -import com.google.android.gms.cast.RemoteMediaPlayer; -import com.google.android.gms.cast.RemoteMediaPlayer.MediaChannelResult; -import com.google.android.gms.cast.RemoteMediaPlayer.OnMetadataUpdatedListener; -import com.google.android.gms.cast.RemoteMediaPlayer.OnStatusUpdatedListener; -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.common.api.ResultCallback; -import com.google.android.gms.common.api.Status; -import com.google.android.gms.common.images.WebImage; - -import android.os.Bundle; -import android.support.v7.media.MediaRouter.RouteInfo; - -/* - * All of the Chromecast session specific functions should start here. - */ -public class ChromecastSession - extends Cast.Listener - implements - GoogleApiClient.ConnectionCallbacks, - GoogleApiClient.OnConnectionFailedListener, - OnMetadataUpdatedListener, - OnStatusUpdatedListener, - Cast.MessageReceivedCallback { - - private RouteInfo routeInfo = null; - private volatile GoogleApiClient mApiClient = null; - private volatile RemoteMediaPlayer mRemoteMediaPlayer; - private CordovaInterface cordova = null; - private CastDevice device = null; - private ChromecastMediaController chromecastMediaController; - private ChromecastOnMediaUpdatedListener onMediaUpdatedListener; - private ChromecastOnSessionUpdatedListener onSessionUpdatedListener; - - private volatile String appId; - private volatile String displayName; - private volatile List appImages; - private volatile String sessionId = null; - private volatile String lastSessionId = null; - private boolean isConnected = false; - - private ChromecastSessionCallback launchCallback; - private ChromecastSessionCallback joinSessionCallback; - - private boolean joinInsteadOfConnecting = false; - private HashSet messageNamespaces = new HashSet(); - - public ChromecastSession(RouteInfo routeInfo, CordovaInterface cordovaInterface, - ChromecastOnMediaUpdatedListener onMediaUpdatedListener, ChromecastOnSessionUpdatedListener onSessionUpdatedListener) { - this.cordova = cordovaInterface; - this.onMediaUpdatedListener = onMediaUpdatedListener; - this.onSessionUpdatedListener = onSessionUpdatedListener; - this.routeInfo = routeInfo; - this.device = CastDevice.getFromBundle(this.routeInfo.getExtras()); - - this.mRemoteMediaPlayer = new RemoteMediaPlayer(); - this.mRemoteMediaPlayer.setOnMetadataUpdatedListener(this); - this.mRemoteMediaPlayer.setOnStatusUpdatedListener(this); - - this.chromecastMediaController = new ChromecastMediaController(mRemoteMediaPlayer); - } - - - /** - * Sets the wheels in motion - connects to the Chromecast and launches the given app - * @param appId - */ - public void launch(String appId, ChromecastSessionCallback launchCallback) { - this.appId = appId; - this.launchCallback = launchCallback; - this.connectToDevice(); - } - - public boolean isConnected() { return this.isConnected; } - - /** - * Adds a message listener if one does not already exist - * @param namespace - */ - public void addMessageListener(String namespace) { - if (messageNamespaces.contains(namespace) == false) { - try { - Cast.CastApi.setMessageReceivedCallbacks(mApiClient, namespace, this); - messageNamespaces.add(namespace); - } catch(Exception e) { - - } - } - } - - /** - * Sends a message to a specified namespace - * @param namespace - * @param message - * @param callback - */ - public void sendMessage(String namespace, String message, final ChromecastSessionCallback callback) { - try { - Cast.CastApi.sendMessage(mApiClient, namespace, message).setResultCallback(new ResultCallback() { - @Override - public void onResult(Status result) { - if (!result.isSuccess()) { - callback.onSuccess(); - } else { - callback.onError(result.toString()); - } - } - }); - } catch(Exception e) { - callback.onError(e.getMessage()); - } - } - - /** - * Join a currently running app with an appId and a session - * @param appId - * @param sessionId - * @param joinSessionCallback - */ - public void join (String appId, String sessionId, ChromecastSessionCallback joinSessionCallback) { - this.appId = appId; - this.joinSessionCallback = joinSessionCallback; - this.joinInsteadOfConnecting = true; - this.lastSessionId = sessionId; - this.connectToDevice(); - } - - /** - * Kills a session and it's underlying media player - * @param callback - */ - public void kill (final ChromecastSessionCallback callback) { -// this.mRemoteMediaPlayer.stop(mApiClient).setResultCallback(new ResultCallback() { -// @Override -// public void onResult(MediaChannelResult result) { -// try { -// Cast.CastApi.stopApplication(mApiClient); -// mApiClient.disconnect(); -// } catch(Exception e) { -// -// } -// -// callback.onSuccess(); -// } -// }); - try { - Cast.CastApi.stopApplication(mApiClient); - mApiClient.disconnect(); - } catch(Exception e) { - - } - - callback.onSuccess(); -// Cast.CastApi.stopApplication(mApiClient); - } - - /** - * Leaves the session. - * @param callback - */ - public void leave (final ChromecastSessionCallback callback) { - try { - Cast.CastApi.leaveApplication(mApiClient); - } catch(Exception e) { - - } - - callback.onSuccess(); - } - - /** - * Loads media over the media API - * @param contentId - The URL of the content - * @param contentType - The MIME type of the content - * @param duration - The length of the video (if known) - * @param streamType - * @param autoPlay - Whether or not to start the video playing or not - * @param currentTime - Where in the video to begin playing from - * @param callback - * @return - */ - public boolean loadMedia(String contentId, String contentType, long duration, String streamType, boolean autoPlay, double currentTime, JSONObject metadata, final ChromecastSessionCallback callback) { - try { - MediaInfo mediaInfo = chromecastMediaController.createLoadUrlRequest(contentId, contentType, duration, streamType, metadata); - - mRemoteMediaPlayer.load(mApiClient, mediaInfo, autoPlay, (long)(currentTime * 1000)) - .setResultCallback(new ResultCallback() { - @Override - public void onResult(MediaChannelResult result) { - if (result.getStatus().isSuccess()) { - System.out.println("Media loaded successfully"); - - ChromecastSession.this.onMediaUpdatedListener.onMediaLoaded(ChromecastSession.this.createMediaObject()); - callback.onSuccess(ChromecastSession.this.createMediaObject()); - - } else { - callback.onError("session_error"); - } - } - }); - } catch (IllegalStateException e) { - e.printStackTrace(); - System.out.println("Problem occurred with media during loading"); - callback.onError("session_error"); - return false; - } catch (Exception e) { - e.printStackTrace(); - callback.onError("session_error"); - System.out.println("Problem opening media during loading"); - return false; - } - return true; - } - - /** - * Media API - Calls play on the current media - * @param callback - */ - public void mediaPlay(ChromecastSessionCallback callback) { - chromecastMediaController.play(mApiClient, callback); - } - - /** - * Media API - Calls pause on the current media - * @param callback - */ - public void mediaPause(ChromecastSessionCallback callback) { - chromecastMediaController.pause(mApiClient, callback); - } - - /** - * Media API - Seeks the current playing media - * @param seekPosition - Seconds to seek to - * @param resumeState - Resume state once seeking is complete: PLAYBACK_PAUSE or PLAYBACK_START - * @param callback - */ - public void mediaSeek(long seekPosition, String resumeState, ChromecastSessionCallback callback) { - chromecastMediaController.seek(seekPosition, resumeState, mApiClient, callback); - } - - /** - * Media API - Sets the volume on the current playing media object NOT ON THE CHROMECAST DIRECTLY - * @param level - * @param callback - */ - public void mediaSetVolume(double level, ChromecastSessionCallback callback) { - chromecastMediaController.setVolume(level, mApiClient, callback); - } - - /** - * Media API - Sets the muted state on the current playing media NOT THE CHROMECAST DIRECTLY - * @param muted - * @param callback - */ - public void mediaSetMuted(boolean muted, ChromecastSessionCallback callback) { - chromecastMediaController.setMuted(muted, mApiClient, callback); - } - - /** - * Media API - Stops and unloads the current playing media - * @param callback - */ - public void mediaStop(ChromecastSessionCallback callback) { - chromecastMediaController.stop(mApiClient, callback); - } - - - /** - * Sets the receiver volume level - * @param volume - * @param callback - */ - public void setVolume(double volume, ChromecastSessionCallback callback) { - try { - Cast.CastApi.setVolume(mApiClient, volume); - callback.onSuccess(); - } catch (Exception e) { - e.printStackTrace(); - callback.onError(e.getMessage()); - } - } - - /** - * Mutes the receiver - * @param muted - * @param callback - */ - public void setMute(boolean muted, ChromecastSessionCallback callback) { - try{ - Cast.CastApi.setMute(mApiClient, muted); - callback.onSuccess(); - } catch (Exception e) { - e.printStackTrace(); - callback.onError(e.getMessage()); - } - } - - - /** - * Connects to the device with all callbacks and things - */ - private void connectToDevice() { - try { - Cast.CastOptions.Builder apiOptionsBuilder = Cast.CastOptions.builder(this.device, this); - - this.mApiClient = new GoogleApiClient.Builder(this.cordova.getActivity().getApplicationContext()) - .addApi(Cast.API, apiOptionsBuilder.build()) - .addConnectionCallbacks(this) - .addOnConnectionFailedListener(this) - .build(); - - this.mApiClient.connect(); - } catch(Exception e) { - e.printStackTrace(); - } - } - - /** - * Launches the application and gets a new session - */ - private void launchApplication() { - Cast.CastApi.launchApplication(mApiClient, this.appId, false) - .setResultCallback(launchApplicationResultCallback); - } - - /** - * Attemps to join an already running session - */ - private void joinApplication() { - Cast.CastApi.joinApplication(this.mApiClient, this.appId, this.lastSessionId) - .setResultCallback(joinApplicationResultCallback); - } - - /** - * Connects to the remote media player on the receiver - * @throws IllegalStateException - * @throws IOException - */ - private void connectRemoteMediaPlayer() throws IllegalStateException, IOException { - Cast.CastApi.setMessageReceivedCallbacks(mApiClient, mRemoteMediaPlayer.getNamespace(), mRemoteMediaPlayer); - mRemoteMediaPlayer.requestStatus(mApiClient) - .setResultCallback(connectRemoteMediaPlayerCallback); - } - - - /** - * launchApplication callback - */ - private ResultCallback launchApplicationResultCallback = new ResultCallback() { - @Override - public void onResult(ApplicationConnectionResult result) { - - ApplicationMetadata metadata = result.getApplicationMetadata(); - ChromecastSession.this.sessionId = result.getSessionId(); - ChromecastSession.this.displayName = metadata.getName(); - ChromecastSession.this.appImages = metadata.getImages(); - - Status status = result.getStatus(); - - if (status.isSuccess()) { - try { - ChromecastSession.this.launchCallback.onSuccess(ChromecastSession.this); - connectRemoteMediaPlayer(); - ChromecastSession.this.isConnected = true; - } catch (IllegalStateException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - ChromecastSession.this.isConnected = false; - } - } - }; - - /** - * joinApplication callback - */ - private ResultCallback joinApplicationResultCallback = new ResultCallback() { - @Override - public void onResult(ApplicationConnectionResult result) { - - Status status = result.getStatus(); - - if (status.isSuccess()) { - try { - ApplicationMetadata metadata = result.getApplicationMetadata(); - ChromecastSession.this.sessionId = result.getSessionId(); - ChromecastSession.this.displayName = metadata.getName(); - ChromecastSession.this.appImages = metadata.getImages(); - - ChromecastSession.this.joinSessionCallback.onSuccess(ChromecastSession.this); - connectRemoteMediaPlayer(); - ChromecastSession.this.isConnected = true; - } catch (IllegalStateException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } else { - ChromecastSession.this.joinSessionCallback.onError(status.toString()); - ChromecastSession.this.isConnected = false; - } - } - }; - - /** - * connectRemoteMediaPlayer callback - */ - private ResultCallback connectRemoteMediaPlayerCallback = new ResultCallback() { - @Override - public void onResult(MediaChannelResult result) { - if (result.getStatus().isSuccess()) { - ChromecastSession.this.onMediaUpdatedListener.onMediaUpdated(true, ChromecastSession.this.createMediaObject()); - /*ChromecastSession.this.onMediaUpdatedListener.onMediaLoaded(ChromecastSession.this.createMediaObject());*/ - } else { - System.out.println("Failed to request status."); - } - } - }; - - /** - * Creates a JSON representation of this session - * @return - */ - public JSONObject createSessionObject() { - JSONObject out = new JSONObject(); - try { - out.put("appId", this.appId); - out.put("media", createMediaObject()); - - if (this.appImages != null) { - JSONArray appImages = new JSONArray(); - for(WebImage o : this.appImages) { - appImages.put(o.toString()); - } - } - - out.put("appImages", appImages); - out.put("sessionId", this.sessionId); - out.put("displayName", this.displayName); - - JSONObject receiver = new JSONObject(); - receiver.put("friendlyName", this.device.getFriendlyName()); - receiver.put("label", this.device.getDeviceId()); - - JSONObject volume = new JSONObject(); - try { - volume.put("level", Cast.CastApi.getVolume(mApiClient)); - volume.put("muted", Cast.CastApi.isMute(mApiClient)); - } catch(Exception e) { - - } - - receiver.put("volume", volume); - - out.put("receiver", receiver); - - } catch(JSONException e) { - e.printStackTrace(); - } - - return out; - } - - /** - * Creates a JSON representation of the current playing media - * @return - */ - private JSONObject createMediaObject() { - JSONObject out = new JSONObject(); - JSONObject objInfo = new JSONObject(); - - MediaStatus mediaStatus = mRemoteMediaPlayer.getMediaStatus(); - if (mediaStatus == null) { - return out; - } - - MediaInfo mediaInfo = mediaStatus.getMediaInfo(); - try { - out.put("media", objInfo); - out.put("mediaSessionId", 1); - out.put("sessionId", this.sessionId); - out.put("currentTime", mediaStatus.getStreamPosition() / 1000.0); - out.put("playbackRate", mediaStatus.getPlaybackRate()); - out.put("customData", mediaStatus.getCustomData()); - - switch(mediaStatus.getPlayerState()) { - case MediaStatus.PLAYER_STATE_BUFFERING: - out.put("playerState", "BUFFERING"); break; - case MediaStatus.PLAYER_STATE_IDLE: - out.put("playerState", "IDLE"); break; - case MediaStatus.PLAYER_STATE_PAUSED: - out.put("playerState", "PAUSED"); break; - case MediaStatus.PLAYER_STATE_PLAYING: - out.put("playerState", "PLAYING"); break; - case MediaStatus.PLAYER_STATE_UNKNOWN: - out.put("playerState", "UNKNOWN"); break; - } - - switch(mediaStatus.getIdleReason()) { - case MediaStatus.IDLE_REASON_CANCELED: - out.put("idleReason", "canceled"); break; - case MediaStatus.IDLE_REASON_ERROR: - out.put("idleReason", "error"); break; - case MediaStatus.IDLE_REASON_FINISHED: - out.put("idleReason", "finished"); break; - case MediaStatus.IDLE_REASON_INTERRUPTED: - out.put("idleReason", "iterrupted"); break; - case MediaStatus.IDLE_REASON_NONE: - out.put("idleReason", "none"); break; - } - - JSONObject volume = new JSONObject(); - volume.put("level", mediaStatus.getStreamVolume()); - volume.put("muted", mediaStatus.isMute()); - - out.put("volume", volume); - - try { - objInfo.put("duration", mediaInfo.getStreamDuration() / 1000.0); - switch(mediaInfo.getStreamType()) { - case MediaInfo.STREAM_TYPE_BUFFERED: - objInfo.put("streamType", "buffered"); break; - case MediaInfo.STREAM_TYPE_LIVE: - objInfo.put("streamType", "live"); break; - case MediaInfo.STREAM_TYPE_NONE: - objInfo.put("streamType", "other"); break; - } - } catch (Exception e) { - - } - - } catch(JSONException e) { - - } - - return out; - } - - - - /* GoogleApiClient.ConnectionCallbacks implementation - * Called when we successfully connect to the API - * (non-Javadoc) - * @see com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks#onConnected(android.os.Bundle) - */ - @Override - public void onConnected(Bundle connectionHint) { - if (this.joinInsteadOfConnecting) { - this.joinApplication(); - } else { - this.launchApplication(); - } - } - - - /* GoogleApiClient.ConnectionCallbacks implementation - * (non-Javadoc) - * @see com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks#onConnectionSuspended(android.os.Bundle) - */ - @Override - public void onConnectionSuspended(int cause) { - if (this.onSessionUpdatedListener != null) { - this.isConnected = false; - this.onSessionUpdatedListener.onSessionUpdated(false, this.createSessionObject()); - } - } - - /* - * GoogleApiClient.OnConnectionFailedListener implementation - * When Google API fails to connect. - * (non-Javadoc) - * @see com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener#onConnectionFailed(com.google.android.gms.common.ConnectionResult) - */ - @Override - public void onConnectionFailed(ConnectionResult result) { - if (this.launchCallback != null) { - this.isConnected = false; - this.launchCallback.onError("channel_error"); - } - } - - /** - * Cast.Listener implementation - * When Chromecast application status changed - */ - @Override - public void onApplicationStatusChanged() { - if (this.onSessionUpdatedListener != null) { - ChromecastSession.this.isConnected = true; - this.onSessionUpdatedListener.onSessionUpdated(true, createSessionObject()); - } - } - - /** - * Cast.Listener implementation - * When the volume is changed on the Chromecast - */ - @Override - public void onVolumeChanged() { - if (this.onSessionUpdatedListener != null) { - this.onSessionUpdatedListener.onSessionUpdated(true, createSessionObject()); - } - } - - /** - * Cast.Listener implementation - * When the application is disconnected - */ - @Override - public void onApplicationDisconnected(int errorCode) { - if (this.onSessionUpdatedListener != null) { - this.isConnected = false; - this.onSessionUpdatedListener.onSessionUpdated(false, this.createSessionObject()); - } - } - - - @Override - public void onMetadataUpdated() { - if (this.onMediaUpdatedListener != null) { - this.onMediaUpdatedListener.onMediaUpdated(true, this.createMediaObject()); - } - } - - - @Override - public void onStatusUpdated() { - if (this.onMediaUpdatedListener != null) { - this.onMediaUpdatedListener.onMediaUpdated(true, this.createMediaObject()); - } - } - - - /// GETTERS - public String getSessionId() { - return this.sessionId; - } - - - @Override - public void onMessageReceived(CastDevice castDevice, String namespace, String message) { - if (this.onSessionUpdatedListener != null) { - this.onSessionUpdatedListener.onMessage(this, namespace, message); - } - } -} diff --git a/plugins/acidhax.cordova.chromecast/src/android/ChromecastSessionCallback.java b/plugins/acidhax.cordova.chromecast/src/android/ChromecastSessionCallback.java deleted file mode 100644 index 0cc0421..0000000 --- a/plugins/acidhax.cordova.chromecast/src/android/ChromecastSessionCallback.java +++ /dev/null @@ -1,9 +0,0 @@ -package acidhax.cordova.chromecast; - -public abstract class ChromecastSessionCallback { - public void onSuccess() { - onSuccess(null); - } - abstract void onSuccess(Object object); - abstract void onError(String reason); -} \ No newline at end of file diff --git a/plugins/acidhax.cordova.chromecast/tests/README.md b/plugins/acidhax.cordova.chromecast/tests/README.md deleted file mode 100644 index 7c0474c..0000000 --- a/plugins/acidhax.cordova.chromecast/tests/README.md +++ /dev/null @@ -1 +0,0 @@ -See cordova-labs cdvtest branch if interested in autotests diff --git a/plugins/acidhax.cordova.chromecast/tests/tests.js b/plugins/acidhax.cordova.chromecast/tests/tests.js deleted file mode 100644 index fbf1def..0000000 --- a/plugins/acidhax.cordova.chromecast/tests/tests.js +++ /dev/null @@ -1,284 +0,0 @@ -exports.init = function() { - eval(require('org.apache.cordova.test-framework.test').injectJasmineInterface(this, 'this')); - jasmine.DEFAULT_TIMEOUT_INTERVAL = 25000; - - // var cc = require('acidhax.cordova.chromecast.Chromecast'); - - var applicationID = 'CC1AD845'; - var videoUrl = 'http://s3.nwgat.net/flvplayers3/bbb.mp4'; - - - describe('chrome.cast', function() { - - var _session = null; - var _receiverAvailability = null; - var _sessionUpdatedFired = false; - var _mediaUpdatedFired = false; - // var _currentMedia = null; - - it('should contain definitions', function(done) { - setTimeout(function() { - expect(chrome.cast.VERSION).toBeDefined(); - expect(chrome.cast.ReceiverAvailability).toBeDefined(); - expect(chrome.cast.ReceiverType).toBeDefined(); - expect(chrome.cast.SenderPlatform).toBeDefined(); - expect(chrome.cast.AutoJoinPolicy).toBeDefined(); - expect(chrome.cast.Capability).toBeDefined(); - expect(chrome.cast.DefaultActionPolicy).toBeDefined(); - expect(chrome.cast.ErrorCode).toBeDefined(); - expect(chrome.cast.timeout).toBeDefined(); - expect(chrome.cast.isAvailable).toBeDefined(); - expect(chrome.cast.ApiConfig).toBeDefined(); - expect(chrome.cast.Receiver).toBeDefined(); - expect(chrome.cast.DialRequest).toBeDefined(); - expect(chrome.cast.SessionRequest).toBeDefined(); - expect(chrome.cast.Error).toBeDefined(); - expect(chrome.cast.Image).toBeDefined(); - expect(chrome.cast.SenderApplication).toBeDefined(); - expect(chrome.cast.Volume).toBeDefined(); - expect(chrome.cast.media).toBeDefined(); - expect(chrome.cast.initialize).toBeDefined(); - expect(chrome.cast.requestSession).toBeDefined(); - expect(chrome.cast.setCustomReceivers).toBeDefined(); - expect(chrome.cast.Session).toBeDefined(); - expect(chrome.cast.media.PlayerState).toBeDefined(); - expect(chrome.cast.media.ResumeState).toBeDefined(); - expect(chrome.cast.media.MediaCommand).toBeDefined(); - expect(chrome.cast.media.MetadataType).toBeDefined(); - expect(chrome.cast.media.StreamType).toBeDefined(); - expect(chrome.cast.media.timeout).toBeDefined(); - expect(chrome.cast.media.LoadRequest).toBeDefined(); - expect(chrome.cast.media.PlayRequest).toBeDefined(); - expect(chrome.cast.media.SeekRequest).toBeDefined(); - expect(chrome.cast.media.VolumeRequest).toBeDefined(); - expect(chrome.cast.media.StopRequest).toBeDefined(); - expect(chrome.cast.media.PauseRequest).toBeDefined(); - expect(chrome.cast.media.GenericMediaMetadata).toBeDefined(); - expect(chrome.cast.media.MovieMediaMetadata).toBeDefined(); - expect(chrome.cast.media.MusicTrackMediaMetadata).toBeDefined(); - expect(chrome.cast.media.PhotoMediaMetadata).toBeDefined(); - expect(chrome.cast.media.TvShowMediaMetadata).toBeDefined(); - expect(chrome.cast.media.MediaInfo).toBeDefined(); - expect(chrome.cast.media.Media).toBeDefined(); - expect(chrome.cast.Session.prototype.setReceiverVolumeLevel).toBeDefined(); - expect(chrome.cast.Session.prototype.setReceiverMuted).toBeDefined(); - expect(chrome.cast.Session.prototype.stop).toBeDefined(); - expect(chrome.cast.Session.prototype.sendMessage).toBeDefined(); - expect(chrome.cast.Session.prototype.addUpdateListener).toBeDefined(); - expect(chrome.cast.Session.prototype.removeUpdateListener).toBeDefined(); - expect(chrome.cast.Session.prototype.addMessageListener).toBeDefined(); - expect(chrome.cast.Session.prototype.removeMessageListener).toBeDefined(); - expect(chrome.cast.Session.prototype.addMediaListener).toBeDefined(); - expect(chrome.cast.Session.prototype.removeMediaListener).toBeDefined(); - expect(chrome.cast.Session.prototype.loadMedia).toBeDefined(); - expect(chrome.cast.media.Media.prototype.play).toBeDefined(); - expect(chrome.cast.media.Media.prototype.pause).toBeDefined(); - expect(chrome.cast.media.Media.prototype.seek).toBeDefined(); - expect(chrome.cast.media.Media.prototype.stop).toBeDefined(); - expect(chrome.cast.media.Media.prototype.setVolume).toBeDefined(); - expect(chrome.cast.media.Media.prototype.supportsCommand).toBeDefined(); - expect(chrome.cast.media.Media.prototype.getEstimatedTime).toBeDefined(); - expect(chrome.cast.media.Media.prototype.addUpdateListener).toBeDefined(); - expect(chrome.cast.media.Media.prototype.removeUpdateListener).toBeDefined(); - done(); - }, 1000); - }); - - it('api should be available', function(done) { - setTimeout(function() { - console.log('api should be available'); - expect(chrome.cast.isAvailable).toEqual(true); - done(); - }, 4000) - }); - - it('initialize should succeed', function(done) { - console.log('initialize should succeed'); - var sessionRequest = new chrome.cast.SessionRequest(applicationID); - var apiConfig = new chrome.cast.ApiConfig(sessionRequest, function(session) { - console.log('sessionCallback'); - _session = session; - }, function(available) { - console.log('receiverCallback') - _receiverAvailability = available; - }); - - chrome.cast.initialize(apiConfig, function() { - console.log('initialize done'); - done(); - }, function(err) { - console.log('initialize error', err); - expect(err).toBe(null); - done(); - }); - }); - - it('receiver available', function(done) { - setTimeout(function() { - console.log('receiver available', _receiverAvailability); - expect(_receiverAvailability).toEqual(chrome.cast.ReceiverAvailability.AVAILABLE); - done(); - }, 2000); - }); - - - it('requestSession should succeed', function(done) { - chrome.cast.requestSession(function(session) { - console.log('request session success'); - _session = session; - expect(session).toBeDefined(); - expect(session.appId).toBeDefined(); - expect(session.displayName).toBeDefined(); - expect(session.receiver).toBeDefined(); - expect(session.receiver.friendlyName).toBeDefined(); - expect(session.addUpdateListener).toBeDefined(); - expect(session.removeUpdateListener).toBeDefined(); - - var updateListener = function(isAlive) { - _sessionUpdatedFired = true; - session.removeUpdateListener(updateListener); - }; - - session.addUpdateListener(updateListener); - done(); - }, function(err) { - console.log('request session error'); - expect(err).toBe(null); - done(); - }) - }); - - it('loadRequest should work', function(done) { - var mediaInfo = new chrome.cast.media.MediaInfo(videoUrl, 'video/mp4'); - var request = new chrome.cast.media.LoadRequest(mediaInfo); - expect(_session).not.toBeNull() - _session.loadMedia(request, function(media) { - console.log('loadRequest success', media); - _currentMedia = media; - // expect(_currentMedia instanceof chrome.cast.media.Media).toBe(true); - - expect(_currentMedia.sessionId).toEqual(_session.sessionId); - expect(_currentMedia.addUpdateListener).toBeDefined(); - expect(_currentMedia.removeUpdateListener).toBeDefined(); - - var updateListener = function() { - _mediaUpdatedFired = true; - _currentMedia.removeUpdateListener(updateListener); - }; - - _currentMedia.addUpdateListener(updateListener); - - done(); - }, function(err) { - console.log('loadRequest error', err); - expect(err).toBeNull(); - done(); - }); - - }); - - it('pause media should succeed', function(done) { - setTimeout(function() { - _currentMedia.pause(null, function() { - console.log('pause success'); - done(); - }, function(err) { - console.log('pause error', err); - expect(err).toBeNull(); - done(); - }); - }, 5000); - }); - - it('play media should succeed', function(done) { - setTimeout(function() { - _currentMedia.play(null, function() { - console.log('play success'); - done(); - }, function(err) { - console.log('play error', err); - expect(err).toBeNull(); - done(); - }); - }, 1000); - }); - - it('seek media should succeed', function(done) { - setTimeout(function() { - var request = new chrome.cast.media.SeekRequest(); - request.currentTime = 10; - - _currentMedia.seek(request, function() { - done(); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - }, 1000); - }); - - it('session updateListener', function(done) { - expect(_sessionUpdatedFired).toEqual(true); - done(); - }); - - it('media updateListener', function(done) { - expect(_mediaUpdatedFired).toEqual(true); - done(); - }); - - it('volume and muting', function(done) { - var volume = new chrome.cast.Volume(); - volume.level = 0.5; - - var request = new chrome.cast.media.VolumeRequest(); - request.volume = volume; - - _currentMedia.setVolume(request, function() { - - var request = new chrome.cast.media.VolumeRequest(new chrome.cast.Volume(null, true)); - _currentMedia.setVolume(request, function() { - - - var request = new chrome.cast.media.VolumeRequest(new chrome.cast.Volume(null, false)); - _currentMedia.setVolume(request, function() { - done(); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - - }, function(err) { - expect(err).toBeNull(); - done(); - }); - - }, function(err) { - expect(err).toBeNull(); - done(); - }); - - }); - - - it('stopping the video', function(done) { - _currentMedia.stop(null, function() { - setTimeout(done, 1000); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - }); - - it('unloading the session', function(done) { - _session.stop(function() { - done(); - }, function(err) { - expect(err).toBeNull(); - done(); - }); - }); - - }); -}; - diff --git a/plugins/android.support.v4/AUTHORS b/plugins/android.support.v4/AUTHORS deleted file mode 100644 index 6ca313d..0000000 --- a/plugins/android.support.v4/AUTHORS +++ /dev/null @@ -1,9 +0,0 @@ -# This is the official list of authors for copyright purposes. -# This file is distinct from the CONTRIBUTORS files. -# See the latter for an explanation. - -# Names should be added to this file as: -# Name or Organization -# The email address is not required for organizations. - -Google Inc. diff --git a/plugins/android.support.v4/CONTRIBUTING.md b/plugins/android.support.v4/CONTRIBUTING.md deleted file mode 100644 index fd9f315..0000000 --- a/plugins/android.support.v4/CONTRIBUTING.md +++ /dev/null @@ -1,13 +0,0 @@ -# Contributing to this Repository - -Thank you for your interest in contributing! - -Unfortunately there are some legal hurdles. Sorry about that. - -This repository is a Google open source project, and so we require contributors to sign Google's open source Contributor License Agreement. -It's easy to do, just click here to sign as an [individual](https://developers.google.com/open-source/cla/individual) or [corporation](https://developers.google.com/open-source/cla/corporate). -Individuals can sign electronically in seconds (see the bottom of the page); corporations will need to email a PDF, or mail. - -We cannot accept PRs or patches larger than fixing typos and the like without a signed CLA. - -If your Github account doesn't show the name your used to sign, please mention your name in your PR. diff --git a/plugins/android.support.v4/CONTRIBUTORS b/plugins/android.support.v4/CONTRIBUTORS deleted file mode 100644 index 3cebd45..0000000 --- a/plugins/android.support.v4/CONTRIBUTORS +++ /dev/null @@ -1,13 +0,0 @@ -# People who have agreed to one of the CLAs and can contribute patches. -# The AUTHORS file lists the copyright holders; this file -# lists people. For example, Google employees are listed here -# but not in AUTHORS, because Google holds the copyright. -# -# https://developers.google.com/open-source/cla/individual -# https://developers.google.com/open-source/cla/corporate -# -# Names should be added to this file as: -# Name - -Andrew Grieve -Max Woghiren diff --git a/plugins/android.support.v4/LICENSE b/plugins/android.support.v4/LICENSE deleted file mode 100644 index 1140764..0000000 --- a/plugins/android.support.v4/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2014 The Chromium Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/plugins/android.support.v4/README.md b/plugins/android.support.v4/README.md deleted file mode 100644 index ea421da..0000000 --- a/plugins/android.support.v4/README.md +++ /dev/null @@ -1,3 +0,0 @@ -This is a Cordova plugin that adds the Android Support v4 client library. -It is meant to be depended on by other plugins. - diff --git a/plugins/android.support.v4/android-support-v4.jar b/plugins/android.support.v4/android-support-v4.jar deleted file mode 100644 index ac4181f..0000000 Binary files a/plugins/android.support.v4/android-support-v4.jar and /dev/null differ diff --git a/plugins/android.support.v4/package.json b/plugins/android.support.v4/package.json deleted file mode 100644 index d37e152..0000000 --- a/plugins/android.support.v4/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "version": "21.0.1", - "name": "android.support.v4", - "cordova_name": "Android Support v4", - "platforms": [ - "android" - ], - "engines": [ - { - "name": "cordova", - "version": ">=3.0.0" - } - ] -} \ No newline at end of file diff --git a/plugins/android.support.v4/plugin.xml b/plugins/android.support.v4/plugin.xml deleted file mode 100644 index e887ff5..0000000 --- a/plugins/android.support.v4/plugin.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - Android Support v4 - - - - - diff --git a/plugins/com.hutchind.cordova.plugins.launcher/LICENSE b/plugins/com.hutchind.cordova.plugins.launcher/LICENSE deleted file mode 100644 index 366db7b..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Nicholas Hutchind - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/plugins/com.hutchind.cordova.plugins.launcher/README.md b/plugins/com.hutchind.cordova.plugins.launcher/README.md deleted file mode 100644 index 3a64823..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/README.md +++ /dev/null @@ -1,286 +0,0 @@ -App-Launcher-Cordova-Plugin -=========================== - -Simple Cordova plugin to see if other apps are installed and launch them. - -## 0. Index -1. [Description](#1-description) -2. [Installation](#2-installation) -3. [Usage](#3-usage) -4. [Changelog](#4-changelog) -5. [Credits](#5-credits) -6. [License](#6-license) - -## 1. Description - -This plugin allows you to check if an app is installed that can handle a specific uri and launch an app via uri on iOS and Android. Additionally, you may open an Android app using its package id. -* (iOS, Android) Check if any apps are installed that can launch via a specified uri. -* (iOS, Android) Launch an app via a specified uri. -* (Android) Check if an app is installed via its package id. -* (Android) Launch an app via its package id. -* (Android) Launch an app with extras included. -* (Android) Return results from a launched app once it is finished. - -## 2. Installation - -### Automatically (CLI / Plugman) - -``` -$ cordova plugin add https://github.com/nchutchind/App-Launcher-Cordova-Plugin.git -``` -and then (this step will modify your project): -``` -$ cordova prepare -``` - -1\. Add the following xml to your `config.xml`: -```xml - - - - -``` -```xml - - - - -``` - -2\. Add `www/Launcher.js` to your project and reference it in `index.html`: -```html - -``` - -3\. Copy the files in `src/` for iOS and/or Android into your project. - -iOS: Copy `Launcher.h` and `Launcher.m` to `platforms/ios//Plugins` - -Android: Copy `Launcher.java` to `platforms/android/src/com/hutchind/cordova/plugins` (you will probably need to create this path) - -### PhoneGap Build - -Add the following xml to your `config.xml` to always use the latest version of this plugin: -```xml - -``` -or to use a specific version: -```xml - -``` - -## 3. Usage -```javascript - // Default handlers - var successCallback = function(data) { - alert("Success!"); - // if calling canLaunch() with getAppList:true, data will contain an array named "appList" with the package names of applications that can handle the uri specified. - }; - var errorCallback = function(errMsg) { - alert("Error! " + errMsg); - } -``` - -Check to see if Facebook can be launched via uri (**iOS** and **Android**) -```javascript - window.plugins.launcher.canLaunch({uri:'fb://'}, successCallback, errorCallback); -``` - -Check to see if Facebook is installed (**Android**) -```javascript - window.plugins.launcher.canLaunch({packageName:'com.facebook.katana'}, successCallback, errorCallback); -``` - -Launch Facebook to the logged in user's profile (**iOS** and **Android**) -```javascript - window.plugins.launcher.launch({uri:'fb://profile'}, successCallback, errorCallback); -``` - -Launch Facebook via package id (**Android**) -```javascript - window.plugins.launcher.launch({packageName:'com.facebook.katana'}, successCallback, errorCallback); -``` - -Check to see if an app is installed that can play NASA TV (**Android**) -```javascript - window.plugins.launcher.canLaunch({ - uri:'http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8', - dataType:'application/x-mpegURL' - }, successCallback, errorCallback); -``` - -Get a list of installed app packages that can play NASA TV (**Android**) -```javascript - window.plugins.launcher.canLaunch({ - uri:'http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8', - dataType:'application/x-mpegURL', - getAppList: true - }, successCallback, errorCallback); -``` - -Launch NASA TV video stream in MxPlayer Free (**Android**) -```javascript - window.plugins.launcher.launch({ - packageName:'com.mxtech.videoplayer.ad', - uri:'http://www.nasa.gov/multimedia/nasatv/NTV-Public-IPS.m3u8', - dataType:'application/x-mpegURL' - }, successCallback, errorCallback); -``` - -Launch MxPlayer Free with Extras for specific videos from the sdcard, specific titles, and starting at 3 seconds in (**Android**) -```javascript - var sdcard = "file:///sdcard/"; - var file1 = sdcard + "video1.mp4", file2 = sdcard + "video2.mp4"; - - window.plugins.launcher.launch({ - packageName:'com.mxtech.videoplayer.ad', - uri:file1, - dataType:'video/*' - extras: [ - {"name":"video_list", "value":[file1,file2], "dataType":"ParcelableArray", "paType":"Uri"}, - {"name":"video_list.name", "value":["Awesome Video","Sweet Title"], "dataType":"StringArray"}, - {"name":"position", "value":3000, "dataType":"int"} - ] - }, successCallback, errorCallback); -``` -Launch MxPlayer Free with Extras for a specific video with title and return results (**Android**) -```javascript - var filename = "file:///sdcard/video.mp4"; - - window.plugins.launcher.launch({ - packageName:'com.mxtech.videoplayer.ad', - uri:filename, - dataType:'video/*', - extras: [ - {"name":"video_list", "value":[filename], "dataType":"ParcelableArray", "paType":"Uri"}, - {"name":"video_list.name", "value":["Whatever Title You Want"], "dataType":"StringArray"}, - {"name":"return_result", "value":true, "dataType":"Boolean"} - ], - successCallback: function(json) { - if (json.isActivityDone) { - if (json.extras && json.extras.end_by) { - if (json.data) { - alert("MxPlayer stopped while on video: " + json.data); - } - if (json.extras.end_by == "user") { - // MxPlayer stopped because the User quit - alert("User watched " + json.extras.position + " of " + json.extras.duration + " before quitting."); - } else { - alert("MxPlayer finished playing video without user quitting."); - } - } else { - alert("Playback finished, but we have no results from MxPlayer."); - } - } else { - console.log("MxPlayer launched"); - } - }, - errorCallback: function(err) { - alert("There was an error launching MxPlayer.") - } - }); -``` -# Extras Data Types - -Most datatypes that can be put into an Android Bundle are able to be passed in. You must provide the datatype to convert to. -Only Uri Parcelables are supported currently. -```javascript - extras: [ - {"name":"myByte", "value":1, "dataType":"Byte"}, - {"name":"myByteArray", "value":[1,0,2,3], "dataType":"ByteArray"}, - {"name":"myShort", "value":5, "dataType":"Short"}, - {"name":"myShortArray", "value":[1,2,3,4], "dataType":"ShortArray"}, - {"name":"myInt", "value":2000, "dataType":"Int"}, - {"name":"myIntArray", "value":[12,34,56], "dataType":"IntArray"}, - {"name":"myIntArrayList", "value":[123,456,789], "dataType":"IntArrayList"}, - {"name":"myLong", "value":123456789101112, "dataType":"Long"}, - {"name":"myLongArray", "value":[123456789101112,121110987654321], "dataType":"LongArray"}, - {"name":"myFloat", "value":12.34, "dataType":"Float"}, - {"name":"myFloatArray", "value":[12.34,56.78], "dataType":"FloatArray"}, - {"name":"myDouble", "value":12.3456789, "dataType":"Double"}, - {"name":"myDoubleArray", "value":[12.3456789, 98.7654321], "dataType":"DoubleArray"}, - {"name":"myBoolean", "value":false, "dataType":"Boolean"}, - {"name":"myBooleanArray", "value":[true,false,true], "dataType":"BooleanArray"}, - {"name":"myString", "value":"this is a test", "dataType":"String"}, - {"name":"myStringArray", "value":["this","is", "a", "test"], "dataType":"StringArray"}, - {"name":"myStringArrayList", "value":["this","is","a","test"], "dataType":"StringArrayList"}, - {"name":"myChar", "value":"T", "dataType":"Char"}, - {"name":"myCharArray", "value":"this is a test", "dataType":"CharArray"}, - {"name":"myCharSequence", "value":"this is a test", "dataType":"CharSequence"}, - {"name":"myCharSequenceArray", "value":["this","is a", "test"], "dataType":"CharSequenceArray"}, - {"name":"myCharSequenceArrayList", "value":["this","is a", "test"], "dataType":"CharSequenceArrayList"}, - {"name":"myParcelable", "value":"http://foo", "dataType":"Parcelable", "paType":"Uri"}, - {"name":"myParcelableArray", "value":["http://foo","http://bar"], "dataType":"ParcelableArray", "paType":"Uri"}, - {"name":"myParcelableArrayList", "value":["http://foo","http://bar"], "dataType":"ParcelableArrayList", "paType":"Uri"}, - {"name":"mySparseParcelableArray", "value":{"10":"http://foo", "-25":"http://bar"}, "dataType":"SparseParcelableArray", "paType":"Uri"}, - ] -``` - -#### Launcher.canLaunch Success Callback -No data is passed. - -#### Launcher.canLaunch Error Callback -Passes a string containing an error message. - -#### Launcher.launch Success Callback Data -Passes a JSON object with varying parts. - -Activity launched -```javascript - { - isLaunched: true - } -``` - -Activity finished -```javascript - { - isActivityDone: true - } -``` - -Activity launched and data returned -```javascript - { - isActivityDone: true, - data: , - extras - } -``` - -#### Launcher.launch Error Callback Data -Passes an error message as a string. - -## 4. Changelog -0.2.0: Android: Added ability to launch activity with extras and receive data back from launched app when it is finished. - -0.1.2: Added ability to check if any apps are installed that can handle a certain datatype on Android. - -0.1.1: Added ability to launch a package with a data uri and datatype on Android. - -0.1.0: initial version supporting Android and iOS - -## 5. Credits -Special thanks to [@michael1t](https://github.com/michael1t) for sponsoring the development of the Extras portion of this plugin. - -## 6. License - -[The MIT License (MIT)](http://www.opensource.org/licenses/mit-license.html) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/plugins/com.hutchind.cordova.plugins.launcher/plugin.xml b/plugins/com.hutchind.cordova.plugins.launcher/plugin.xml deleted file mode 100644 index e88732b..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/plugin.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - Launcher - - - This plugin allows you to see if other apps are installed and launch them. On Android, you can send extras to the launched Activity and receive result data (if available), as well as retrieve a list of applications that can open a specified uri. - - - MIT - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/plugins/com.hutchind.cordova.plugins.launcher/src/android/Launcher.java b/plugins/com.hutchind.cordova.plugins.launcher/src/android/Launcher.java deleted file mode 100644 index ba7c279..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/src/android/Launcher.java +++ /dev/null @@ -1,488 +0,0 @@ -package com.hutchind.cordova.plugins.launcher; - -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.PluginResult; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.app.Activity; -import android.content.ActivityNotFoundException; -import android.content.Intent; -import android.net.Uri; -import android.util.Log; -import android.content.pm.ActivityInfo; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.content.pm.PackageManager.NameNotFoundException; -import android.content.pm.ResolveInfo; -import android.os.Bundle; -import android.os.Parcelable; -import android.os.Build; - -import java.lang.reflect.Array; -import java.util.List; -import java.util.Arrays; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.Set; -import java.util.HashSet; - -public class Launcher extends CordovaPlugin { - public static final String TAG = "Launcher Plugin"; - public static final String ACTION_CAN_LAUNCH = "canLaunch"; - public static final String ACTION_LAUNCH = "launch"; - public static final int LAUNCH_REQUEST = 0; - - private CallbackContext callback; - - private abstract class LauncherRunnable implements Runnable { - public CallbackContext callbackContext; - LauncherRunnable(CallbackContext cb) { - this.callbackContext = cb; - } - } - - @Override - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { - callback = callbackContext; - if (ACTION_CAN_LAUNCH.equals(action)) { - return canLaunch(args); - } else if (ACTION_LAUNCH.equals(action)) { - return launch(args); - } - return false; - } - - private boolean canLaunch(JSONArray args) throws JSONException { - final JSONObject options = args.getJSONObject(0); - final CordovaInterface mycordova = cordova; - final CordovaPlugin plugin = this; - - if (options.has("packageName")) { - final String appPackageName = options.getString("packageName"); - cordova.getThreadPool().execute(new LauncherRunnable(this.callback) { - public void run() { - final Intent intent = new Intent(Intent.ACTION_VIEW); - String packageName = appPackageName; - String passedActivityName = null; - if (packageName.contains("/")) { - String[] items = appPackageName.split("/"); - packageName = items[0]; - passedActivityName = items[1]; - } - final ActivityInfo appInfo = getAppInfo(intent, packageName); - - if (appInfo != null) { - Log.d(TAG, "App Info found for " + packageName); - callbackContext.success(); - } else { - final PackageManager pm = plugin.webView.getContext().getPackageManager(); - final Intent launchIntent = pm.getLaunchIntentForPackage(packageName); - if (launchIntent != null) { - Log.d(TAG, "Launch Intent for " + packageName + " found."); - callbackContext.success(); - } else { - Log.d(TAG, "Could not find launch intent for package: " + packageName); - callbackContext.error("Application is not installed."); - } - } - - } - }); - } else if (options.has("uri")) { - final String uri = options.getString("uri"); - final String dataType = options.has("dataType") ? options.getString("dataType") : null; - - cordova.getThreadPool().execute(new LauncherRunnable(this.callback) { - public void run() { - final PackageManager pm = plugin.webView.getContext().getPackageManager(); - final Intent intent = new Intent(Intent.ACTION_VIEW); - if (dataType != null) { - intent.setDataAndType(Uri.parse(uri), dataType); - } else { - intent.setData(Uri.parse(uri)); - } - - List resInfos = pm.queryIntentActivities(intent, 0); - if (resInfos.size() > 0) { - Log.d(TAG, "Found Activities that handle uri: " + uri); - - boolean shouldGetAppList = false; - try { - shouldGetAppList = options.has("getAppList") && options.getBoolean("getAppList") == true; - } catch (JSONException e) {} - - if (shouldGetAppList) { - JSONObject obj = new JSONObject(); - JSONArray appList = new JSONArray(); - - for(ResolveInfo resolveInfo : resInfos) { - try { - appList.put(resolveInfo.activityInfo.packageName); - } catch (Exception e) { - //Do Nothing - } - } - - try { - obj.put("appList", wrap(appList)); - } catch(Exception e) { - - } - callbackContext.success(obj); - } else { - callbackContext.success(); - } - } else { - Log.d(TAG, "No Activities found that handle uri: " + uri); - callbackContext.error("No application found."); - } - } - }); - } - - return true; - } - - private ActivityInfo getAppInfo(final Intent intent, final String appPackageName) { - final PackageManager pm = webView.getContext().getPackageManager(); - try { - Log.d(TAG, pm.getApplicationInfo(appPackageName, 0) + ""); - }catch (NameNotFoundException e) { - Log.i(TAG, "No info found for package: " + appPackageName); - } - return null; - } - - private boolean launch(JSONArray args) throws JSONException { - final JSONObject options = args.getJSONObject(0); - Bundle extras = null; - if (options.has("extras")) { - extras = createExtras(options.getJSONArray("extras")); - } else { - extras = new Bundle(); - } - if (options.has("uri") && (options.has("packageName") || options.has("dataType"))) { - String dataType = null; - String packageName = null; - if (options.has("packageName")) { - packageName = options.getString("packageName"); - } - if (options.has("dataType")) { - dataType = options.getString("dataType"); - } - launchAppWithData(packageName, options.getString("uri"), dataType, extras); - return true; - } else if (options.has("packageName")) { - launchApp(options.getString("packageName"), extras); - return true; - } else if (options.has("uri")) { - launchIntent(options.getString("uri"), extras); - return true; - } - return false; - } - - private Bundle createExtras(JSONArray extrasObj) throws JSONException { - Bundle extras = new Bundle(); - for (int i = 0, size = extrasObj.length(); i < size; i++) { - JSONObject extra = extrasObj.getJSONObject(i); - if (extra.has("name") && extra.has("value") && extra.has("dataType")) { - String extraName = extra.getString("name"); - String dataType = extra.getString("dataType"); - try { - if (dataType.equalsIgnoreCase("Byte")) { - try { - extras.putByte(extraName, ((byte) extra.getInt("value"))); - } catch (Exception e) { - Log.e(TAG, "Error converting to byte for extra: " + extraName); - e.printStackTrace(); - throw e; - } - } else if (dataType.equalsIgnoreCase("ByteArray")) { - try { - extras.putByteArray(extraName, ParseTypes.toByteArray(extra.getJSONArray("value"))); - } catch (Exception e) { - Log.e(TAG, "Error converting to byte for extra: " + extraName); - e.printStackTrace(); - throw e; - } - } else if (dataType.equalsIgnoreCase("Short")) { - try { - extras.putShort(extraName, ((short) extra.getInt("value"))); - } catch (Exception e) { - Log.e(TAG, "Error converting to short for extra: " + extraName); - e.printStackTrace(); - throw e; - } - } else if (dataType.equalsIgnoreCase("ShortArray")) { - extras.putShortArray(extraName, ParseTypes.toShortArray(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("Int")) { - extras.putInt(extraName, extra.getInt("value")); - } else if (dataType.equalsIgnoreCase("IntArray")) { - extras.putIntArray(extraName, ParseTypes.toIntArray(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("IntArrayList")) { - extras.putIntegerArrayList(extraName, ParseTypes.toIntegerArrayList(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("Long")) { - extras.putLong(extraName, extra.getLong("value")); - } else if (dataType.equalsIgnoreCase("LongArray")) { - extras.putLongArray(extraName, ParseTypes.toLongArray(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("Float")) { - try { - extras.putFloat(extraName, Float.parseFloat(extra.getString("value"))); - } catch (Exception e) { - Log.e(TAG, "Error parsing float for extra: " + extraName); - e.printStackTrace(); - throw e; - } - } else if (dataType.equalsIgnoreCase("FloatArray")) { - try { - extras.putFloatArray(extraName, ParseTypes.toFloatArray(extra.getJSONArray("value"))); - } catch (Exception e) { - Log.e(TAG, "Error parsing float for extra: " + extraName); - e.printStackTrace(); - throw e; - } - } else if (dataType.equalsIgnoreCase("Double")) { - extras.putDouble(extraName, extra.getDouble("value")); - } else if (dataType.equalsIgnoreCase("DoubleArray")) { - extras.putDoubleArray(extraName, ParseTypes.toDoubleArray(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("Boolean")) { - extras.putBoolean(extraName, extra.getBoolean("value")); - } else if (dataType.equalsIgnoreCase("BooleanArray")) { - extras.putBooleanArray(extraName, ParseTypes.toBooleanArray(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("String")) { - extras.putString(extraName, extra.getString("value")); - } else if (dataType.equalsIgnoreCase("StringArray")) { - extras.putStringArray(extraName, ParseTypes.toStringArray(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("StringArrayList")) { - extras.putStringArrayList(extraName, ParseTypes.toStringArrayList(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("Char")) { - extras.putChar(extraName, ParseTypes.toChar(extra.getString("value"))); - } else if (dataType.equalsIgnoreCase("CharArray")) { - extras.putCharArray(extraName, ParseTypes.toCharArray(extra.getString("value"))); - } else if (dataType.equalsIgnoreCase("CharSequence")) { - extras.putCharSequence(extraName, extra.getString("value")); - } else if (dataType.equalsIgnoreCase("CharSequenceArray")) { - extras.putCharSequenceArray(extraName, ParseTypes.toCharSequenceArray(extra.getJSONArray("value"))); - } else if (dataType.equalsIgnoreCase("CharSequenceArrayList")) { - extras.putCharSequenceArrayList(extraName, ParseTypes.toCharSequenceArrayList(extra.getJSONArray("value"))); - /* - } else if (dataType.equalsIgnoreCase("Size") && Build.VERSION.SDK_INT >= 21) { - extras.putSize(extraName, extra.getJSONObject("value")); - } else if (dataType.equalsIgnoreCase("SizeF") && Build.VERSION.SDK_INT >= 21) { - extras.putSizeF(extraName, extra.getJSONObject("value")); - */ - } else if (dataType.toLowerCase().contains("parcelable")) { - if (!extra.has("paType")) { - Log.e(TAG, "Property 'paType' must be provided if dataType is " + dataType + "."); - throw new Exception("Missing property paType."); - } else { - String paType = extra.getString("paType").toUpperCase(); - if (ParseTypes.SUPPORTED_PA_TYPES.contains(paType)) { - if (dataType.equalsIgnoreCase("Parcelable")) { - extras.putParcelable(extraName, ParseTypes.toParcelable(extra.getString("value"), paType)); - } else if (dataType.equalsIgnoreCase("ParcelableArray")) { - extras.putParcelableArray(extraName, ParseTypes.toParcelableArray(extra.getJSONArray("value"), paType)); - } else if (dataType.equalsIgnoreCase("ParcelableArrayList")) { - extras.putParcelableArrayList(extraName, ParseTypes.toParcelableArrayList(extra.getJSONArray("value"), paType)); - } else if (dataType.equalsIgnoreCase("SparseParcelableArray")) { - extras.putSparseParcelableArray(extraName, ParseTypes.toSparseParcelableArray(extra.getJSONObject("value"), paType)); - } - } else { - Log.e(TAG, "ParcelableArray type '" + paType + "' is not currently supported."); - throw new Exception("Provided parcelable array type not supported."); - } - } - } - } catch (Exception e) { - Log.e(TAG, "Error processing extra. Skipping: " + extraName); - } - } else { - Log.e(TAG, "Extras must have a name, value, and datatype."); - } - } - - Log.d(TAG, "EXTRAS"); - Log.d(TAG, "" + extras); - - return extras; - } - - private void launchAppWithData(final String packageName, final String uri, final String dataType, final Bundle extras) throws JSONException { - final CordovaInterface mycordova = cordova; - final CordovaPlugin plugin = this; - final CallbackContext callbackContext = this.callback; - cordova.getThreadPool().execute(new LauncherRunnable(this.callback) { - public void run() { - Intent intent = new Intent(Intent.ACTION_VIEW); - if (dataType != null) { - intent.setDataAndType(Uri.parse(uri), dataType); - } else { - intent.setData(Uri.parse(uri)); - } - - if (packageName != null && !packageName.equals("")) { - intent.setPackage(packageName); - } - - intent.putExtras(extras); - - try { - mycordova.startActivityForResult(plugin, intent, LAUNCH_REQUEST); - ((Launcher) plugin).callbackLaunched(); - } catch(ActivityNotFoundException e) { - Log.e(TAG, "Error: No applications installed that can handle uri " + uri); - e.printStackTrace(); - callbackContext.error("Application not found for uri."); - } - - } - }); - } - - private void launchApp(final String packageName, final Bundle extras) { - final CordovaInterface mycordova = cordova; - final CordovaPlugin plugin = this; - Log.i(TAG, "Trying to launch app: " + packageName); - cordova.getThreadPool().execute(new LauncherRunnable(this.callback) { - public void run() { - final PackageManager pm = plugin.webView.getContext().getPackageManager(); - final Intent launchIntent = pm.getLaunchIntentForPackage(packageName); - boolean appNotFound = launchIntent == null; - - if (!appNotFound) { - try { - launchIntent.putExtras(extras); - mycordova.startActivityForResult(plugin, launchIntent, LAUNCH_REQUEST); - ((Launcher) plugin).callbackLaunched(); - } catch (ActivityNotFoundException e) { - Log.e(TAG, "Error: Activity for package" + packageName + " was not found."); - e.printStackTrace(); - callbackContext.error("Activity not found for package name."); - } - } else { - callbackContext.error("Activity not found for package name."); - } - } - }); - } - - private void launchIntent(final String uri, final Bundle extras) { - final CordovaInterface mycordova = cordova; - final CordovaPlugin plugin = this; - cordova.getThreadPool().execute(new LauncherRunnable(this.callback) { - public void run() { - Intent intent = new Intent(Intent.ACTION_VIEW); - intent.setData(Uri.parse(uri)); - try { - intent.putExtras(extras); - mycordova.startActivityForResult(plugin, intent, LAUNCH_REQUEST); - ((Launcher) plugin).callbackLaunched(); - } catch (ActivityNotFoundException e) { - Log.e(TAG, "Error: Activity for " + uri + " was not found."); - e.printStackTrace(); - callbackContext.error("Activity not found for uri."); - } - } - }); - } - - @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) { - super.onActivityResult(requestCode, resultCode, intent); - if (requestCode == LAUNCH_REQUEST) { - if (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_CANCELED) { - JSONObject json = new JSONObject(); - try { - json.put("isActivityDone", true); - } catch(JSONException ignored) {} - if (intent != null) { - Bundle extras = intent.getExtras(); - if (extras != null) { - JSONObject jsonExtras = new JSONObject(); - Set keys = extras.keySet(); - for (String key : keys) { - try { - jsonExtras.put(key, wrap(extras.get(key))); - } catch(JSONException ignored) {} - } - try { - json.put("extras", jsonExtras); - } catch(JSONException ignored) {} - } - - try { - json.put("data", intent.getDataString()); - } catch(JSONException ignored) {} - } - callback.success(json); - } else { - callback.error("Activity failed (" + resultCode + ")."); - } - } - } - - public void callbackLaunched() { - try { - JSONObject json = new JSONObject(); - json.put("isLaunched", true); - PluginResult result = new PluginResult(PluginResult.Status.OK, json); - result.setKeepCallback(true); - callback.sendPluginResult(result); - } catch (JSONException e) { - PluginResult result = new PluginResult(PluginResult.Status.OK, "{'isLaunched':true}"); - result.setKeepCallback(true); - callback.sendPluginResult(result); - } - } - - private Object wrap(Object o) { - if (o == null) { - return JSONObject.NULL; - } - if (o instanceof JSONArray || o instanceof JSONObject) { - return o; - } - if (o.equals(JSONObject.NULL)) { - return o; - } - try { - if (o instanceof Collection) { - return new JSONArray((Collection) o); - } else if (o.getClass().isArray()) { - JSONArray jsa = new JSONArray(); - int length = Array.getLength(o); - for (int i = 0; i < length; i += 1) { - jsa.put(wrap(Array.get(o, i))); - } - return jsa; - } - if (o instanceof Map) { - return new JSONObject((Map) o); - } - if (o instanceof Boolean || - o instanceof Byte || - o instanceof Character || - o instanceof Double || - o instanceof Float || - o instanceof Integer || - o instanceof Long || - o instanceof Short || - o instanceof String) { - return o; - } - if (o.getClass().getPackage().getName().startsWith("java.")) { - return o.toString(); - } - } catch (Exception ignored) { - } - return null; - } -} \ No newline at end of file diff --git a/plugins/com.hutchind.cordova.plugins.launcher/src/android/ParseTypes.java b/plugins/com.hutchind.cordova.plugins.launcher/src/android/ParseTypes.java deleted file mode 100644 index dbe0dbc..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/src/android/ParseTypes.java +++ /dev/null @@ -1,178 +0,0 @@ -package com.hutchind.cordova.plugins.launcher; - -import android.net.Uri; -import android.os.Parcelable; -import android.util.SparseArray; -//import android.annotation.TargetApi; - -import org.json.JSONObject; -import org.json.JSONArray; -import org.json.JSONException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Collections; -import java.util.Iterator; - -public class ParseTypes { - public static final List SUPPORTED_PA_TYPES = Collections.unmodifiableList(Arrays.asList("URI")); - - public static byte[] toByteArray(JSONArray arr) throws JSONException { - int jsize = arr.length(); - byte[] exVal = new byte[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = (byte) arr.getInt(j); - } - return exVal; - } - public static short[] toShortArray(JSONArray arr) throws JSONException { - int jsize = arr.length(); - short[] exVal = new short[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = (short) arr.getInt(j); - } - return exVal; - } - public static int[] toIntArray(JSONArray arr) throws JSONException { - int jsize = arr.length(); - int[] exVal = new int[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = arr.getInt(j); - } - return exVal; - } - public static ArrayList toIntegerArrayList(JSONArray arr) throws JSONException { - int[] ints = ParseTypes.toIntArray(arr); - ArrayList exVal = new ArrayList(); - for (int i = 0; i < ints.length; i++) { - exVal.add(ints[i]); - } - return exVal; - } - public static long[] toLongArray(JSONArray arr) throws JSONException { - int jsize = arr.length(); - long[] exVal = new long[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = arr.getLong(j); - } - return exVal; - } - public static float[] toFloatArray(JSONArray arr) throws JSONException, NumberFormatException { - int jsize = arr.length(); - float[] exVal = new float[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = Float.parseFloat(arr.getString(j)); - } - return exVal; - } - public static double[] toDoubleArray(JSONArray arr) throws JSONException { - int jsize = arr.length(); - double[] exVal = new double[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = arr.getDouble(j); - } - return exVal; - } - public static boolean[] toBooleanArray(JSONArray arr) throws JSONException { - int jsize = arr.length(); - boolean[] exVal = new boolean[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = arr.getBoolean(j); - } - return exVal; - } - public static String[] toStringArray(JSONArray arr) throws JSONException { - int jsize = arr.length(); - String[] exVal = new String[jsize]; - for(int j=0; j < jsize; j++) { - exVal[j] = arr.getString(j); - } - return exVal; - } - public static ArrayList toStringArrayList(JSONArray arr) throws JSONException { - String[] strs = ParseTypes.toStringArray(arr); - ArrayList exVal = new ArrayList(); - for (int i = 0; i < strs.length; i++) { - exVal.add(strs[i]); - } - return exVal; - } - public static char toChar(String str) { - if (str == null) { - return (char) 0; - } else { - return str.charAt(0); - } - } - public static char[] toCharArray(String str) { - if (str == null) { - return new char[0]; - } else { - return str.toCharArray(); - } - } - public static CharSequence[] toCharSequenceArray(JSONArray arr) throws JSONException { - return ParseTypes.toStringArray(arr); - } - public static ArrayList toCharSequenceArrayList(JSONArray arr) throws JSONException { - CharSequence[] strs = ParseTypes.toCharSequenceArray(arr); - ArrayList exVal = new ArrayList(); - for (int i = 0; i < strs.length; i++) { - exVal.add(strs[i]); - } - return exVal; - } - /*@TargetApi(21) - public static android.util.Size toSize(JSONObject o) throws JSONException { - int width = 0, height = 0; - try { - width = o.getInt("width"); - height = o.getInt("height"); - } catch (JSONException e) { - width = o.getInt("w"); - height = o.getInt("h"); - } - return new android.util.Size(width, height); - } - @TargetApi(21) - public static android.util.SizeF toSizeF(JSONObject o) throws JSONException { - float width = 0, height = 0; - try { - width = Float.parseFloat(o.getString("width")); - height = Float.parseFloat(o.getString("height")); - } catch (JSONException e) { - width = Float.parseFloat(o.getString("w")); - height = Float.parseFloat(o.getString("h")); - } - return new android.util.SizeF(width, height); - }*/ - public static SparseArray toSparseParcelableArray(JSONObject o, String pType) throws Exception, NullPointerException, JSONException { - SparseArray sa = new SparseArray(); - for(Iterator iter = o.keys(); iter.hasNext();) { - String jsonKey = iter.next(); - Integer saKey = Integer.parseInt(jsonKey); - sa.put(saKey, ParseTypes.toParcelable(o.getString(jsonKey), pType)); - } - return sa; - } - public static Parcelable toParcelable(String str, String pType) throws Exception, NullPointerException { - if (pType.equalsIgnoreCase("URI")) { - return Uri.parse(str); - } - throw new Exception("Parcelable type " + pType + " is not supported."); - } - public static Parcelable[] toParcelableArray(JSONArray arr, String pType) throws Exception, NullPointerException, JSONException { - ArrayList items = (ArrayList)ParseTypes.toParcelableArrayList(arr, pType); - return items.toArray(new Parcelable[items.size()]); - } - public static ArrayList toParcelableArrayList(JSONArray arr, String pType) throws Exception, NullPointerException, JSONException { - int jsize = arr.length(); - ArrayList items = new ArrayList(); - for(int j=0; j < jsize; j++) { - items.add(ParseTypes.toParcelable(arr.getString(j), pType)); - } - - return items; - } -} diff --git a/plugins/com.hutchind.cordova.plugins.launcher/src/ios/Launcher.h b/plugins/com.hutchind.cordova.plugins.launcher/src/ios/Launcher.h deleted file mode 100644 index 8fb6783..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/src/ios/Launcher.h +++ /dev/null @@ -1,8 +0,0 @@ -#import - -@interface Launcher : CDVPlugin - -- (void)canLaunch:(CDVInvokedUrlCommand*)command; -- (void)launch:(CDVInvokedUrlCommand*)command; - -@end \ No newline at end of file diff --git a/plugins/com.hutchind.cordova.plugins.launcher/src/ios/Launcher.m b/plugins/com.hutchind.cordova.plugins.launcher/src/ios/Launcher.m deleted file mode 100644 index 2b1f151..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/src/ios/Launcher.m +++ /dev/null @@ -1,46 +0,0 @@ -#import "Launcher.h" -#import - -@implementation Launcher - -- (void)canLaunch:(CDVInvokedUrlCommand*)command { - NSDictionary* options = [command.arguments objectAtIndex:0]; - CDVPluginResult * pluginResult = nil; - - if ([options objectForKey:@"uri"]) { - NSString *uri = [options objectForKey:@"uri"]; - if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:uri]]) { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self writeJavascript:[pluginResult toSuccessCallbackString:command.callbackId]]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No app installed that can handle that uri."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Missing option: 'uri' required."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } -} - -- (void)launch:(CDVInvokedUrlCommand*)command { - NSDictionary* options = [command.arguments objectAtIndex:0]; - CDVPluginResult * pluginResult = nil; - - if ([options objectForKey:@"uri"]) { - NSString *uri = [options objectForKey:@"uri"]; - if ([[UIApplication sharedApplication] canOpenURL: [NSURL URLWithString:uri]]) { - NSURL *launchURL = [NSURL URLWithString:uri]; - [[UIApplication sharedApplication] openURL: launchURL]; - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; - [self writeJavascript:[pluginResult toSuccessCallbackString:command.callbackId]]; - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"No app installed that can handle that uri."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } - } else { - pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Missing option: 'uri' required."]; - [self writeJavascript:[pluginResult toErrorCallbackString:command.callbackId]]; - } -} - -@end \ No newline at end of file diff --git a/plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js b/plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js deleted file mode 100644 index bfcbf0f..0000000 --- a/plugins/com.hutchind.cordova.plugins.launcher/www/Launcher.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -function Launcher() {} - -Launcher.prototype.canLaunch = function (options, successCallback, errorCallback) { - options = options || {}; - options.successCallback = options.successCallback || successCallback; - options.errorCallback = options.errorCallback || errorCallback; - cordova.exec(options.successCallback || null, options.errorCallback || null, "Launcher", "canLaunch", [options]); -}; - -Launcher.prototype.launch = function(options, successCallback, errorCallback) { - options = options || {}; - options.successCallback = options.successCallback || successCallback; - options.errorCallback = options.errorCallback || errorCallback; - cordova.exec(options.successCallback || null, options.errorCallback || null, "Launcher", "launch", [options]); -}; - -Launcher.install = function () { - if (!window.plugins) { - window.plugins = {}; - } - - window.plugins.launcher = new Launcher(); - return window.plugins.launcher; -}; - -cordova.addConstructor(Launcher.install); diff --git a/plugins/cordova-plugin-crosswalk-webview/LICENSE b/plugins/cordova-plugin-crosswalk-webview/LICENSE deleted file mode 100644 index 578fa3b..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/LICENSE +++ /dev/null @@ -1,235 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. - -/************************************************/ -This product bundles CordovaXWalkCoreExtensionBridge.java as well -as the XWalk.pak and the Crosswalk JSApi which is available under a -"3-clause BSD" license. For details, see below: - - Copyright (c) 2013 Intel Corporation. All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are - met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above - copyright notice, this list of conditions and the following disclaimer - in the documentation and/or other materials provided with the - distribution. - * Neither the name of Intel Corporation nor the names of its - contributors may be used to endorse or promote products derived from - this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS - "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT - OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT - LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/plugins/cordova-plugin-crosswalk-webview/NOTICE b/plugins/cordova-plugin-crosswalk-webview/NOTICE deleted file mode 100644 index 81636de..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/NOTICE +++ /dev/null @@ -1,8 +0,0 @@ -Apache Cordova -Copyright 2014 The Apache Software Foundation - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org) - -This software includes software developed at Intel Corporation. -Copyright 2014 Intel Corporation diff --git a/plugins/cordova-plugin-crosswalk-webview/PlatformScriptsWorkflow.md b/plugins/cordova-plugin-crosswalk-webview/PlatformScriptsWorkflow.md deleted file mode 100644 index aa31dcd..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/PlatformScriptsWorkflow.md +++ /dev/null @@ -1,30 +0,0 @@ -### Directions for Non-CLI Android-Only cordova project - -* Pull down the Cordova Android -``` -$ git clone https://github.com/apache/cordova-android.git -``` -* Generate a project, e.g creating HelloWorld -``` -$ /path/to/cordova-android/bin/create hello com.example.hello HelloWorld -``` -* Navigate to the project folder -``` -$ cd hello -``` -* Install Crosswalk engine plugin by plugman (version >= 0.22.17) -``` -$ plugman install --platform android --plugin https://github.com/MobileChromeApps/cordova-crosswalk-engine.git --project . -``` -* Build -``` -$ ./cordova/build -``` -The build script will automatically fetch the Crosswalk WebView libraries from Crosswalk project download site (https://download.01.org/crosswalk/releases/crosswalk/android/) and build for both X86 and ARM architectures. - -For example, building HelloWorld generates: - -``` -/path/to/hello/build/outputs/apk/hello-x86-debug.apk -/path/to/hello/build/outputs/apk/hello-armv7-debug.apk -``` diff --git a/plugins/cordova-plugin-crosswalk-webview/README.md b/plugins/cordova-plugin-crosswalk-webview/README.md deleted file mode 100644 index 56e43b9..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/README.md +++ /dev/null @@ -1,153 +0,0 @@ -# cordova-plugin-crosswalk-webview - -Makes your Cordova application use the [Crosswalk WebView](https://crosswalk-project.org/) -instead of the System WebView. Requires cordova-android 4.0 or greater. - -### Benefits - -* WebView doesn't change depending on Android version -* Capabilities: such as WebRTC, WebAudio, Web Components -* Performance improvements (compared to older system webviews) - - -### Drawbacks - -* Increased memory footprint - * An overhead of ~30MB (as reported by the RSS column of ps) -* Increased APK size (about 17MB) -* Increased size on disk when installed (about 50MB) -* Crosswalk WebView stores data (IndexedDB, LocalStorage, etc) separately from System WebView - * You'll need to manually migrate local data when switching between the two (note: this is fixed in Crosswalk 15) - -### Install - -The following directions are for cordova-cli (most people). Alternatively you can use the [Android platform scripts workflow](PlatformScriptsWorkflow.md). - -* Open an existing cordova project, with cordova-android 4.0.0+, and using the latest CLI. Crosswalk variables can be configured as an option when installing the plugin -* Add this plugin - -``` -$ cordova plugin add cordova-plugin-crosswalk-webview -``` - -* Build -``` -$ cordova build android -``` -The build script will automatically fetch the Crosswalk WebView libraries from Crosswalk project download site (https://download.01.org/crosswalk/releases/crosswalk/android/maven2/) and build for both X86 and ARM architectures. - -For example, building android with Crosswalk generates: - -``` -/path/to/hello/platforms/android/build/outputs/apk/hello-x86-debug.apk -/path/to/hello/platforms/android/build/outputs/apk/hello-armv7-debug.apk -``` - -Note that you might have to run `cordova clean` before building, if you previously built the app without cordova-plugin-crosswalk-webview. Also, manually uninstall the app from the device/emulator before attempting to install the crosswalk-enabled version. - -Also note that it is also possible to publish a multi-APK application on the Play Store that uses Crosswalk for Pre-L devices, and the (updatable) system webview for L+: - -To build Crosswalk-enabled apks, add this plugin and run: - - $ cordova build --release - -To build System-webview apk, remove this plugin and run: - - $ cordova build --release -- --minSdkVersion=21 - -### Configure - -You can try out a different Crosswalk version by specifying certain variables while installing the plugin, or by changing the value of `xwalkVersion` in your `config.xml` after installing the plugin. Some examples: - - - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_VERSION="org.xwalk:xwalk_core_library:14+" - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_VERSION="xwalk_core_library:14+" - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_VERSION="14+" - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_VERSION="14" - - - - - -You can also use a Crosswalk beta version. Some examples: - - - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_VERSION="org.xwalk:xwalk_core_library_beta:14+" - - -You can set [command-line flags](http://peter.sh/experiments/chromium-command-line-switches/) as well: - - - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_COMMANDLINE="--disable-pull-to-refresh-effect" - - -You can use the Crosswalk [shared mode](https://crosswalk-project.org/documentation/shared_mode.html) which allows multiple Crosswalk applications to share one Crosswalk runtime downloaded from the Play Store. - - - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_MODE="shared" - - -You can also use a Crosswalk beta version on shared mode, e.g.: - - - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_VERSION="org.xwalk:xwalk_shared_library_beta:14+" - -You can use the Crosswalk [lite mode](https://crosswalk-project.org/documentation/crosswalk_lite.html) which is the Crosswalk runtime designed to be as small as possible by removing less common libraries and features and compressing the APK. - - - cordova plugin add cordova-plugin-crosswalk-webview --variable XWALK_MODE="lite" - - -You can set background color with the preference of BackgroundColor. - - - - -You can also set user agent with the preference of xwalkUserAgent. - - - -### Release Notes - -#### 1.8.0 (June 30, 2016) -* Uses the latest Crosswalk 19 stable version by default - -#### 1.7.0 (May 4, 2016) -* Uses the latest Crosswalk 18 stable version by default -* Support to use [Crosswalk Lite](https://crosswalk-project.org/documentation/crosswalk_lite.html), It's possible to specify lite value with the variable of XWALK_MODE at install plugin time. -* [Cordova screenshot plugin](https://github.com/gitawego/cordova-screenshot.git) can capture the visible content of web page with Crosswalk library. -* Doesn't work with Crosswalk 17 and earlier - -#### 1.6.0 (March 11, 2016) -* Uses the latest Crosswalk 17 stable version by default -* Support to [package apps for 64-bit devices](https://crosswalk-project.org/documentation/android/android_64bit.html), it's possible to specify 64-bit targets using the `--xwalk64bit` option in the build command: - - cordova build android --xwalk64bit - -#### 1.5.0 (January 18, 2016) -* Uses the latest Crosswalk 16 stable version by default -* The message of xwalk's ready can be listened - -#### 1.4.0 (November 5, 2015) -* Uses the latest Crosswalk 15 stable version by default -* Support User Agent and Background Color configuration preferences -* Compatible with the newest Cordova version 5.3.4 - -#### 1.3.0 (August 28, 2015) -* Crosswalk variables can be configured as an option via CLI -* Support for [Crosswalk's shared mode](https://crosswalk-project.org/documentation/shared_mode.html) via the XWALK_MODE install variable or xwalkMode preference -* Uses the latest Crosswalk 14 stable version by default -* The ANIMATABLE_XWALK_VIEW preference is false by default -* Doesn't work with Crosswalk 14.43.343.17 and earlier - -#### 1.2.0 (April 22, 2015) -* Made Crosswalk command-line configurable via `` -* Disabled pull-down-to-refresh by default - -#### 1.1.0 (April 21, 2015) -* Based on Crosswalk v13 -* Made Crosswalk version configurable via `` - -#### 1.0.0 (Mar 25, 2015) -* Initial release -* Based on Crosswalk v11 diff --git a/plugins/cordova-plugin-crosswalk-webview/hooks/after_build/000-build_64_bit.js b/plugins/cordova-plugin-crosswalk-webview/hooks/after_build/000-build_64_bit.js deleted file mode 100644 index 4083ecc..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/hooks/after_build/000-build_64_bit.js +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env node - -module.exports = function(context) { - - /** @external */ - var deferral = context.requireCordovaModule('q').defer(), - UpdateConfig = require('./../update_config.js'), - updateConfig = new UpdateConfig(context); - - /** Main method */ - var main = function() { - // Remove the xwalk variables - updateConfig.afterBuild64bit(); - - deferral.resolve(); - }; - - main(); - - return deferral.promise; - -}; diff --git a/plugins/cordova-plugin-crosswalk-webview/hooks/after_plugin_install/000-shared_mode_special.js b/plugins/cordova-plugin-crosswalk-webview/hooks/after_plugin_install/000-shared_mode_special.js deleted file mode 100644 index d0a33ca..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/hooks/after_plugin_install/000-shared_mode_special.js +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env node - -module.exports = function(context) { - - /** @external */ - var deferral = context.requireCordovaModule('q').defer(), - UpdateConfig = require('./../update_config.js'), - updateConfig = new UpdateConfig(context); - - /** Main method */ - var main = function() { - // Add xwalk preference to config.xml - updateConfig.addPreferences(); - - deferral.resolve(); - }; - - main(); - - return deferral.promise; - -}; diff --git a/plugins/cordova-plugin-crosswalk-webview/hooks/before_build/000-build_64_bit.js b/plugins/cordova-plugin-crosswalk-webview/hooks/before_build/000-build_64_bit.js deleted file mode 100644 index 7c6fef7..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/hooks/before_build/000-build_64_bit.js +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env node - -module.exports = function(context) { - - /** @external */ - var deferral = context.requireCordovaModule('q').defer(), - UpdateConfig = require('./../update_config.js'), - updateConfig = new UpdateConfig(context); - - /** Main method */ - var main = function() { - // Remove the xwalk variables - updateConfig.beforeBuild64bit(); - - deferral.resolve(); - }; - - main(); - - return deferral.promise; - -}; diff --git a/plugins/cordova-plugin-crosswalk-webview/hooks/before_plugin_uninstall/000-shared_mode_special.js b/plugins/cordova-plugin-crosswalk-webview/hooks/before_plugin_uninstall/000-shared_mode_special.js deleted file mode 100644 index 19909b8..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/hooks/before_plugin_uninstall/000-shared_mode_special.js +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env node - -module.exports = function(context) { - - /** @external */ - var deferral = context.requireCordovaModule('q').defer(), - UpdateConfig = require('./../update_config.js'), - updateConfig = new UpdateConfig(context); - - /** Main method */ - var main = function() { - // Remove the xwalk variables - updateConfig.removePreferences(); - - deferral.resolve(); - }; - - main(); - - return deferral.promise; - -}; diff --git a/plugins/cordova-plugin-crosswalk-webview/hooks/update_config.js b/plugins/cordova-plugin-crosswalk-webview/hooks/update_config.js deleted file mode 100644 index 2b1f787..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/hooks/update_config.js +++ /dev/null @@ -1,201 +0,0 @@ -#!/usr/bin/env node - -module.exports = function(context) { - - var ConfigParser, XmlHelpers; - try { - // cordova-lib >= 5.3.4 doesn't contain ConfigParser and xml-helpers anymore - ConfigParser = context.requireCordovaModule("cordova-common").ConfigParser; - XmlHelpers = context.requireCordovaModule("cordova-common").xmlHelpers; - } catch (e) { - ConfigParser = context.requireCordovaModule("cordova-lib/src/configparser/ConfigParser"); - XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers"); - } - - /** @external */ - var fs = context.requireCordovaModule('fs'), - path = context.requireCordovaModule('path'), - et = context.requireCordovaModule('elementtree'); - - /** @defaults */ - var xwalkVariables = {}, - argumentsString = context.cmdLine, - pluginConfigurationFile = path.join(context.opts.plugin.dir, 'plugin.xml'), - androidPlatformDir = path.join(context.opts.projectRoot, - 'platforms', 'android'), - projectConfigurationFile = path.join(context.opts.projectRoot, - 'config.xml'), - platformConfigurationFile = path.join(androidPlatformDir, - 'res', 'xml', 'config.xml'), - projectManifestFile = path.join(androidPlatformDir, - 'AndroidManifest.xml'), - xwalk64bit = "xwalk64bit", - xwalkLiteVersion = "", - specificVersion = false; - - /** Init */ - var CordovaConfig = new ConfigParser(platformConfigurationFile); - - var addPermission = function() { - var projectManifestXmlRoot = XmlHelpers.parseElementtreeSync(projectManifestFile); - var child = et.XML(''); - XmlHelpers.graftXML(projectManifestXmlRoot, [child], '/manifest'); - fs.writeFileSync(projectManifestFile, projectManifestXmlRoot.write({indent: 4}), 'utf-8'); - } - - var removePermission = function() { - var projectManifestXmlRoot = XmlHelpers.parseElementtreeSync(projectManifestFile); - var child = et.XML(''); - XmlHelpers.pruneXML(projectManifestXmlRoot, [child], '/manifest'); - fs.writeFileSync(projectManifestFile, projectManifestXmlRoot.write({indent: 4}), 'utf-8'); - } - - var defaultPreferences = function() { - var pluginPreferences = {}; - - var pluginXmlRoot = XmlHelpers.parseElementtreeSync(pluginConfigurationFile), - tagName = "preference", - containerName = "config-file", - targetPlatform = 'android', - targetPlatformTag = pluginXmlRoot.find('./platform[@name="' + targetPlatform + '"]'); - - var tagsInRoot = pluginXmlRoot.findall(tagName) || [], - tagsInPlatform = targetPlatformTag ? targetPlatformTag.findall(tagName) : [], - tagsInContainer = targetPlatformTag ? targetPlatformTag.findall(containerName) : [], - tagsList = tagsInRoot.concat(tagsInContainer); - - // Parses tags within -blocks - tagsList.map(function(prefTag) { - prefTag.getchildren().forEach(function(element) { - if ((element.tag == 'preference') && (element.attrib['name']) && element.attrib['default']) { - // Don't add xwalkLiteVersion in the app/config.xml - if (element.attrib['name'] == "xwalkLiteVersion") { - xwalkLiteVersion = element.attrib['default']; - } else { - pluginPreferences[element.attrib['name']] = element.attrib['default']; - } - } - }); - }); - - return pluginPreferences; - } - - /** The style of name align with config.xml */ - var setConfigPreference = function(name, value) { - var trimName = name.replace('_', ''); - for (var localName in xwalkVariables) { - if (localName.toUpperCase() == trimName.toUpperCase()) { - xwalkVariables[localName] = value; - if (localName == 'xwalkVersion') { - specificVersion = true; - } - } - } - } - - /** Pase the cli command to get the specific preference*/ - var parseCliPreference = function() { - var commandlineVariablesList = argumentsString.split('--variable'); - if (commandlineVariablesList) { - commandlineVariablesList.forEach(function(element) { - element = element.trim(); - if(element && element.indexOf('XWALK') == 0) { - var preference = element.split('='); - if (preference && preference.length == 2) { - setConfigPreference(preference[0], preference[1]); - } - } - }); - } - } - - /** Add preference */ - this.addPreferences = function() { - // Pick the xwalk variables with the cli preferences - // parseCliPreference(); - - // Add the permission of writing external storage when using shared mode - if (CordovaConfig.getGlobalPreference('xwalkMode') == 'shared') { - addPermission(); - } - - // Configure the final value in the config.xml - // var configXmlRoot = XmlHelpers.parseElementtreeSync(projectConfigurationFile); - // var preferenceUpdated = false; - // for (var name in xwalkVariables) { - // var child = configXmlRoot.find('./preference[@name="' + name + '"]'); - // if(!child) { - // preferenceUpdated = true; - // child = et.XML(''); - // XmlHelpers.graftXML(configXmlRoot, [child], '/*'); - // } - // } - // if(preferenceUpdated) { - // fs.writeFileSync(projectConfigurationFile, configXmlRoot.write({indent: 4}), 'utf-8'); - // } - } - - /** Remove preference*/ - this.removePreferences = function() { - if (CordovaConfig.getGlobalPreference('xwalkMode') == 'shared') { - // Add the permission of write_external_storage in shared mode - removePermission(); - } - - // var configXmlRoot = XmlHelpers.parseElementtreeSync(projectConfigurationFile); - // for (var name in xwalkVariables) { - // var child = configXmlRoot.find('./preference[@name="' + name + '"]'); - // if (child) { - // XmlHelpers.pruneXML(configXmlRoot, [child], '/*'); - // } - // } - // fs.writeFileSync(projectConfigurationFile, configXmlRoot.write({indent: 4}), 'utf-8'); - } - - var build64bit = function() { - var build64bit = false; - var commandlineVariablesList = argumentsString.split('--'); - - if (commandlineVariablesList) { - commandlineVariablesList.forEach(function(element) { - element = element.trim(); - if(element && element.indexOf(xwalk64bit) == 0) { - build64bit = true; - } - }); - } - return build64bit; - } - - this.beforeBuild64bit = function() { - if(build64bit()) { - var configXmlRoot = XmlHelpers.parseElementtreeSync(projectConfigurationFile); - var child = configXmlRoot.find('./preference[@name="' + xwalk64bit + '"]'); - if(!child) { - child = et.XML(''); - XmlHelpers.graftXML(configXmlRoot, [child], '/*'); - fs.writeFileSync(projectConfigurationFile, configXmlRoot.write({indent: 4}), 'utf-8'); - } - } - } - - this.afterBuild64bit = function() { - if(build64bit()) { - var configXmlRoot = XmlHelpers.parseElementtreeSync(projectConfigurationFile); - var child = configXmlRoot.find('./preference[@name="' + xwalk64bit + '"]'); - if (child) { - XmlHelpers.pruneXML(configXmlRoot, [child], '/*'); - fs.writeFileSync(projectConfigurationFile, configXmlRoot.write({indent: 4}), 'utf-8'); - } - } - - console.log("Crosswalk info:"); - console.log(" After much discussion and analysis of the market,"); - console.log(" we have decided to discontinue support for Android 4.0 (ICS) in Crosswalk starting with version 20,"); - console.log(" so the minSdkVersion of Cordova project is configured to 16 by default. \n"); - } - - xwalkVariables = defaultPreferences(); - -}; diff --git a/plugins/cordova-plugin-crosswalk-webview/package.json b/plugins/cordova-plugin-crosswalk-webview/package.json deleted file mode 100644 index 231d942..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "cordova-plugin-crosswalk-webview", - "version": "2.0.0", - "description": "Changes the default WebView to CrossWalk", - "cordova": { - "id": "cordova-plugin-crosswalk-webview", - "platforms": [ - "android" - ] - }, - "repository": { - "type": "git", - "url": "https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview.git" - }, - "keywords": [ - "cordova", - "chromium", - "crosswalk", - "webview", - "engine", - "ecosystem:cordova", - "cordova-android" - ], - "engines": [ - { - "name": "cordova-android", - "version": ">=4" - }, - { - "name": "cordova-plugman", - "version": ">=4.2.0" - } - ], - "author": "", - "license": "Apache 2.0", - "bugs": { - "url": "https://crosswalk-project.org/jira" - }, - "homepage": "https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview" -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaClientCertRequest.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaClientCertRequest.java deleted file mode 100644 index ea1b95f..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaClientCertRequest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - 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. -*/ -package org.crosswalk.engine; - -import org.apache.cordova.ICordovaClientCertRequest; -import org.xwalk.core.ClientCertRequest; - -import java.security.cert.X509Certificate; -import java.security.Principal; -import java.security.PrivateKey; -import java.util.Arrays; - -public class XWalkCordovaClientCertRequest implements ICordovaClientCertRequest { - - private final ClientCertRequest request; - - public XWalkCordovaClientCertRequest(ClientCertRequest request) { - this.request = request; - } - - /** - * Cancel this request - */ - public void cancel() { - request.cancel(); - } - - /* - * Returns the host name of the server requesting the certificate. - */ - public String getHost() { - return request.getHost(); - } - - /* - * Returns the acceptable types of asymmetric keys (can be null). - */ - public String[] getKeyTypes() { - return request.getKeyTypes(); - } - - /* - * Returns the port number of the server requesting the certificate. - */ - public int getPort() { - return request.getPort(); - } - - /* - * Returns the acceptable certificate issuers for the certificate matching the private - * key (can be null). - */ - public Principal[] getPrincipals() { - return request.getPrincipals(); - } - - /* - * Ignore the request for now. Do not remember user's choice. - */ - public void ignore() { - request.ignore(); - } - - /* - * Proceed with the specified private key and client certificate chain. Remember the user's - * positive choice and use it for future requests. - * - * @param privateKey The privateKey - * @param chain The certificate chain - */ - public void proceed(PrivateKey privateKey, X509Certificate[] chain) { - request.proceed(privateKey, Arrays.asList(chain)); - } -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaCookieManager.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaCookieManager.java deleted file mode 100644 index ddf1127..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaCookieManager.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - 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. -*/ -package org.crosswalk.engine; - -import org.apache.cordova.ICordovaCookieManager; -import org.xwalk.core.XWalkCookieManager; - -class XWalkCordovaCookieManager implements ICordovaCookieManager { - - protected XWalkCookieManager cookieManager = null; - - public XWalkCordovaCookieManager() { - cookieManager = new XWalkCookieManager(); - } - - public void setCookiesEnabled(boolean accept) { - cookieManager.setAcceptCookie(accept); - } - - public void setCookie(final String url, final String value) { - cookieManager.setCookie(url, value); - } - - public String getCookie(final String url) { - return cookieManager.getCookie(url); - } - - public void clearCookies() { - cookieManager.removeAllCookie(); - } - - public void flush() { - cookieManager.flushCookieStore(); - } -}; - - diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaHttpAuthHandler.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaHttpAuthHandler.java deleted file mode 100644 index c1e9dd4..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaHttpAuthHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - 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. -*/ -package org.crosswalk.engine; - -import org.apache.cordova.ICordovaHttpAuthHandler; -import org.xwalk.core.XWalkHttpAuthHandler; - -/** - * Specifies interface for HTTP auth handler object which is used to handle auth requests and - * specifying user credentials. - */ -public class XWalkCordovaHttpAuthHandler implements ICordovaHttpAuthHandler { - - private final XWalkHttpAuthHandler handler; - - public XWalkCordovaHttpAuthHandler(XWalkHttpAuthHandler handler) { - this.handler = handler; - } - - /** - * Instructs the XWalkView to cancel the authentication request. - */ - public void cancel() { - handler.cancel(); - } - - /** - * Instructs the XWalkView to proceed with the authentication with the given credentials. - * - * @param username - * @param password - */ - public void proceed(String username, String password) { - handler.proceed(username, password); - } -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaResourceClient.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaResourceClient.java deleted file mode 100644 index e37d780..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaResourceClient.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - 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. -*/ -package org.crosswalk.engine; - -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.net.Uri; -import android.net.http.SslError; -import android.webkit.ValueCallback; -import android.webkit.WebResourceResponse; - -import org.apache.cordova.CordovaResourceApi; -import org.apache.cordova.CordovaResourceApi.OpenForReadResult; -import org.apache.cordova.LOG; -import org.apache.cordova.PluginManager; -import org.xwalk.core.ClientCertRequest; -import org.xwalk.core.XWalkHttpAuthHandler; -import org.xwalk.core.XWalkResourceClient; -import org.xwalk.core.XWalkView; - -import java.io.FileNotFoundException; -import java.io.IOException; - -public class XWalkCordovaResourceClient extends XWalkResourceClient { - - private static final String TAG = "XWalkCordovaResourceClient"; - protected XWalkWebViewEngine parentEngine; - - public XWalkCordovaResourceClient(XWalkWebViewEngine parentEngine) { - super(parentEngine.webView); - this.parentEngine = parentEngine; - } - - /** - * Report an error to the host application. These errors are unrecoverable (i.e. the main resource is unavailable). - * The errorCode parameter corresponds to one of the ERROR_* constants. - * - * @param view The WebView that is initiating the callback. - * @param errorCode The error code corresponding to an ERROR_* value. - * @param description A String describing the error. - * @param failingUrl The url that failed to load. - */ - @Override - public void onReceivedLoadError(XWalkView view, int errorCode, String description, - String failingUrl) { - LOG.d(TAG, "CordovaWebViewClient.onReceivedError: Error code=%s Description=%s URL=%s", errorCode, description, failingUrl); - - parentEngine.client.onReceivedError(errorCode, description, failingUrl); - } - - @Override - public WebResourceResponse shouldInterceptLoadRequest(XWalkView view, String url) { - try { - // Check the against the white-list. - if (!parentEngine.pluginManager.shouldAllowRequest(url)) { - LOG.w(TAG, "URL blocked by whitelist: " + url); - // Results in a 404. - return new WebResourceResponse("text/plain", "UTF-8", null); - } - - CordovaResourceApi resourceApi = parentEngine.resourceApi; - Uri origUri = Uri.parse(url); - // Allow plugins to intercept WebView requests. - Uri remappedUri = resourceApi.remapUri(origUri); - - if (!origUri.equals(remappedUri)) { - OpenForReadResult result = resourceApi.openForRead(remappedUri, true); - return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream); - } - // If we don't need to special-case the request, let the browser load it. - return null; - } catch (IOException e) { - if (!(e instanceof FileNotFoundException)) { - LOG.e(TAG, "Error occurred while loading a file (returning a 404).", e); - } - // Results in a 404. - return new WebResourceResponse("text/plain", "UTF-8", null); - } - } - - @Override - public boolean shouldOverrideUrlLoading(XWalkView view, String url) { - return parentEngine.client.onNavigationAttempt(url); - } - - - /** - * Notify the host application that an SSL error occurred while loading a - * resource. The host application must call either callback.onReceiveValue(true) - * or callback.onReceiveValue(false). Note that the decision may be - * retained for use in response to future SSL errors. The default behavior - * is to pop up a dialog. - */ - @Override - public void onReceivedSslError(XWalkView view, ValueCallback callback, SslError error) { - final String packageName = parentEngine.cordova.getActivity().getPackageName(); - final PackageManager pm = parentEngine.cordova.getActivity().getPackageManager(); - - ApplicationInfo appInfo; - try { - appInfo = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA); - if ((appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { - // debug = true - callback.onReceiveValue(true); - } else { - // debug = false - callback.onReceiveValue(false); - } - } catch (PackageManager.NameNotFoundException e) { - // When it doubt, lock it out! - callback.onReceiveValue(false); - } - } - - @Override - public void onReceivedHttpAuthRequest(XWalkView view, XWalkHttpAuthHandler handler, - String host, String realm) { - // Check if there is some plugin which can resolve this auth challenge - PluginManager pluginManager = parentEngine.pluginManager; - if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest( - parentEngine.parentWebView, - new XWalkCordovaHttpAuthHandler(handler), host, realm)) { - parentEngine.client.clearLoadTimeoutTimer(); - return; - } - - // By default handle 401 like we'd normally do! - super.onReceivedHttpAuthRequest(view, handler, host, realm); - } - - @Override - public void onReceivedClientCertRequest(XWalkView view, ClientCertRequest request) { - // Check if there is some plugin which can resolve this certificate request - PluginManager pluginManager = parentEngine.pluginManager; - if (pluginManager != null && pluginManager.onReceivedClientCertRequest( - parentEngine.parentWebView, new XWalkCordovaClientCertRequest(request))) { - parentEngine.client.clearLoadTimeoutTimer(); - return; - } - - super.onReceivedClientCertRequest(view, request); - } -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaUiClient.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaUiClient.java deleted file mode 100644 index cdc41a2..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaUiClient.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - 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. -*/ -package org.crosswalk.engine; - -import android.app.Activity; -import android.content.ActivityNotFoundException; -import android.content.Intent; -import android.net.Uri; -import android.util.Log; -import android.webkit.ValueCallback; - -import org.apache.cordova.CordovaDialogsHelper; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.LOG; -import org.xwalk.core.XWalkJavascriptResult; -import org.xwalk.core.XWalkUIClient; -import org.xwalk.core.XWalkView; - -public class XWalkCordovaUiClient extends XWalkUIClient { - private static final String TAG = "XWalkCordovaUiClient"; - protected final CordovaDialogsHelper dialogsHelper; - protected final XWalkWebViewEngine parentEngine; - - private static final int FILECHOOSER_RESULTCODE = 5173; - - public XWalkCordovaUiClient(XWalkWebViewEngine parentEngine) { - super(parentEngine.webView); - this.parentEngine = parentEngine; - dialogsHelper = new CordovaDialogsHelper(parentEngine.webView.getContext()); - } - - @Override - public boolean onJavascriptModalDialog(XWalkView view, JavascriptMessageType type, String url, - String message, String defaultValue, XWalkJavascriptResult result) { - switch (type) { - case JAVASCRIPT_ALERT: - return onJsAlert(view, url, message, result); - case JAVASCRIPT_CONFIRM: - return onJsConfirm(view, url, message, result); - case JAVASCRIPT_PROMPT: - return onJsPrompt(view, url, message, defaultValue, result); - case JAVASCRIPT_BEFOREUNLOAD: - // Reuse onJsConfirm to show the dialog. - return onJsConfirm(view, url, message, result); - default: - break; - } - assert (false); - return false; - } - - /** - * Tell the client to display a javascript alert dialog. - */ - public boolean onJsAlert(XWalkView view, String url, String message, - final XWalkJavascriptResult result) { - dialogsHelper.showAlert(message, new CordovaDialogsHelper.Result() { - @Override - public void gotResult(boolean success, String value) { - if (success) { - result.confirm(); - } else { - result.cancel(); - } - } - }); - return true; - } - - /** - * Tell the client to display a confirm dialog to the user. - */ - public boolean onJsConfirm(XWalkView view, String url, String message, - final XWalkJavascriptResult result) { - dialogsHelper.showConfirm(message, new CordovaDialogsHelper.Result() { - @Override - public void gotResult(boolean success, String value) { - if (success) { - result.confirm(); - } else { - result.cancel(); - } - } - }); - return true; - } - - /** - * Tell the client to display a prompt dialog to the user. - * If the client returns true, WebView will assume that the client will - * handle the prompt dialog and call the appropriate JsPromptResult method. - *

    - * Since we are hacking prompts for our own purposes, we should not be using them for - * this purpose, perhaps we should hack console.log to do this instead! - */ - public boolean onJsPrompt(XWalkView view, String origin, String message, String defaultValue, - final XWalkJavascriptResult result) { - // Unlike the @JavascriptInterface bridge, this method is always called on the UI thread. - String handledRet = parentEngine.bridge.promptOnJsPrompt(origin, message, defaultValue); - if (handledRet != null) { - result.confirmWithResult(handledRet); - } else { - dialogsHelper.showPrompt(message, defaultValue, new CordovaDialogsHelper.Result() { - @Override - public void gotResult(boolean success, String value) { - if (success) { - result.confirmWithResult(value); - } else { - result.cancel(); - } - } - }); - - } - return true; - } - - /** - * Notify the host application that a page has started loading. - * This method is called once for each main frame load so a page with iframes or framesets will call onPageLoadStarted - * one time for the main frame. This also means that onPageLoadStarted will not be called when the contents of an - * embedded frame changes, i.e. clicking a link whose target is an iframe. - * - * @param view The webView initiating the callback. - * @param url The url of the page. - */ - @Override - public void onPageLoadStarted(XWalkView view, String url) { - LOG.d(TAG, "onPageLoadStarted(" + url + ")"); - if (view.getUrl() != null) { - // Flush stale messages. - parentEngine.client.onPageStarted(url); - parentEngine.bridge.reset(); - } - } - - /** - * Notify the host application that a page has stopped loading. - * This method is called only for main frame. When onPageLoadStopped() is called, the rendering picture may not be updated yet. - * - * @param view The webView initiating the callback. - * @param url The url of the page. - * @param status The load status of the webView, can be FINISHED, CANCELLED or FAILED. - */ - @Override - public void onPageLoadStopped(XWalkView view, String url, LoadStatus status) { - LOG.d(TAG, "onPageLoadStopped(" + url + ")"); - if (status == LoadStatus.FINISHED) { - parentEngine.client.onPageFinishedLoading(url); - } else if (status == LoadStatus.FAILED) { - // TODO: Should this call parentEngine.client.onReceivedError()? - // Right now we call this from ResourceClient, but maybe that is just for sub-resources? - } - } - - // File Chooser - @Override - public void openFileChooser(XWalkView view, final ValueCallback uploadFile, String acceptType, String capture) { - uploadFile.onReceiveValue(null); - - parentEngine.cordova.setActivityResultCallback(new CordovaPlugin() { - @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) { - parentEngine.webView.onActivityResult(requestCode, resultCode, intent); - } - }); - } -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaView.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaView.java deleted file mode 100644 index bc0353c..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkCordovaView.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.crosswalk.engine; - -import org.apache.cordova.CordovaPreferences; -import org.xwalk.core.XWalkPreferences; -import org.xwalk.core.XWalkResourceClient; -import org.xwalk.core.XWalkUIClient; -import org.xwalk.core.XWalkView; - -import android.content.Context; -import android.content.Intent; -import android.content.pm.ApplicationInfo; -import android.content.pm.PackageManager; -import android.os.Bundle; -import android.util.AttributeSet; -import android.util.Log; -import android.view.KeyEvent; - -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.CordovaWebViewEngine; - -public class XWalkCordovaView extends XWalkView implements CordovaWebViewEngine.EngineView { - - public static final String TAG = "XWalkCordovaView"; - - protected XWalkCordovaResourceClient resourceClient; - protected XWalkCordovaUiClient uiClient; - protected XWalkWebViewEngine parentEngine; - - private static boolean hasSetStaticPref; - // This needs to run before the super's constructor. - private static Context setGlobalPrefs(Context context, CordovaPreferences preferences) { - if (!hasSetStaticPref) { - hasSetStaticPref = true; - ApplicationInfo ai = null; - try { - ai = context.getPackageManager().getApplicationInfo(context.getApplicationContext().getPackageName(), PackageManager.GET_META_DATA); - } catch (PackageManager.NameNotFoundException e) { - throw new RuntimeException(e); - } - boolean prefAnimatable = preferences == null ? false : preferences.getBoolean("CrosswalkAnimatable", false); - boolean manifestAnimatable = ai.metaData == null ? false : ai.metaData.getBoolean("CrosswalkAnimatable"); - // Selects between a TextureView (obeys framework transforms applied to view) or a SurfaceView (better performance). - XWalkPreferences.setValue(XWalkPreferences.ANIMATABLE_XWALK_VIEW, prefAnimatable || manifestAnimatable); - if ((ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { - XWalkPreferences.setValue(XWalkPreferences.REMOTE_DEBUGGING, true); - } - XWalkPreferences.setValue(XWalkPreferences.JAVASCRIPT_CAN_OPEN_WINDOW, true); - XWalkPreferences.setValue(XWalkPreferences.ALLOW_UNIVERSAL_ACCESS_FROM_FILE, true); - } - return context; - } - - public XWalkCordovaView(Context context, CordovaPreferences preferences) { - super(setGlobalPrefs(context, preferences), (AttributeSet)null); - } - - public XWalkCordovaView(Context context, AttributeSet attrs) { - super(setGlobalPrefs(context, null), attrs); - } - - void init(XWalkWebViewEngine parentEngine) { - this.parentEngine = parentEngine; - if (resourceClient == null) { - setResourceClient(new XWalkCordovaResourceClient(parentEngine)); - } - if (uiClient == null) { - setUIClient(new XWalkCordovaUiClient(parentEngine)); - } - } - - @Override - public void setResourceClient(XWalkResourceClient client) { - // XWalk calls this method from its constructor. - if (client instanceof XWalkCordovaResourceClient) { - this.resourceClient = (XWalkCordovaResourceClient)client; - } - super.setResourceClient(client); - } - - @Override - public void setUIClient(XWalkUIClient client) { - // XWalk calls this method from its constructor. - if (client instanceof XWalkCordovaUiClient) { - this.uiClient = (XWalkCordovaUiClient)client; - } - super.setUIClient(client); - } - - // Call CordovaInterface to start activity for result to make sure - // onActivityResult() callback will be triggered from CordovaActivity correctly. - // Todo(leonhsl) How to handle |options|? - @Override - public void startActivityForResult(Intent intent, int requestCode, Bundle options) { - parentEngine.cordova.startActivityForResult(new CordovaPlugin() { - @Override - public void onActivityResult(int requestCode, int resultCode, Intent intent) { - // Route to XWalkView. - Log.i(TAG, "Route onActivityResult() to XWalkView"); - XWalkCordovaView.this.onActivityResult(requestCode, resultCode, intent); - } - }, intent, requestCode); - } - - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - Boolean ret = parentEngine.client.onDispatchKeyEvent(event); - if (ret != null) { - return ret.booleanValue(); - } - return super.dispatchKeyEvent(event); - } - - @Override - public void pauseTimers() { - // This is called by XWalkViewInternal.onActivityStateChange(). - // We don't want them paused by default though. - } - - public void pauseTimersForReal() { - super.pauseTimers(); - } - - @Override - public CordovaWebView getCordovaWebView() { - return parentEngine == null ? null : parentEngine.getCordovaWebView(); - } - - @Override - public void setBackgroundColor(int color) { - if (parentEngine != null && parentEngine.isXWalkReady()) { - super.setBackgroundColor(color); - } - } -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkExposedJsApi.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkExposedJsApi.java deleted file mode 100644 index 2571521..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkExposedJsApi.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - 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. -*/ -package org.crosswalk.engine; - -import android.os.Looper; - -import org.apache.cordova.CordovaBridge; -import org.apache.cordova.ExposedJsApi; -import org.json.JSONException; -import org.xwalk.core.JavascriptInterface; - -class XWalkExposedJsApi implements ExposedJsApi { - private final CordovaBridge bridge; - - XWalkExposedJsApi(CordovaBridge bridge) { - this.bridge = bridge; - } - - @JavascriptInterface - public String exec(int bridgeSecret, String service, String action, String callbackId, String arguments) throws JSONException, IllegalAccessException { - if (Looper.myLooper() == null) { - Looper.prepare(); - } - return bridge.jsExec(bridgeSecret, service, action, callbackId, arguments); - } - - @JavascriptInterface - public void setNativeToJsBridgeMode(int bridgeSecret, int value) throws IllegalAccessException { - bridge.jsSetNativeToJsBridgeMode(bridgeSecret, value); - } - - @JavascriptInterface - public String retrieveJsMessages(int bridgeSecret, boolean fromOnlineEvent) throws IllegalAccessException { - return bridge.jsRetrieveJsMessages(bridgeSecret, fromOnlineEvent); - } -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkWebViewEngine.java b/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkWebViewEngine.java deleted file mode 100644 index 43061d2..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/src/org/crosswalk/engine/XWalkWebViewEngine.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - 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. -*/ - -package org.crosswalk.engine; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.content.res.AssetManager; -import android.graphics.Bitmap; -import android.graphics.Color; -import android.util.Log; -import android.view.View; - -import java.io.File; -import java.io.IOException; - -import junit.framework.Assert; - -import org.apache.cordova.CordovaBridge; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.CordovaPreferences; -import org.apache.cordova.CordovaResourceApi; -import org.apache.cordova.CordovaWebView; -import org.apache.cordova.CordovaWebViewEngine; -import org.apache.cordova.ICordovaCookieManager; -import org.apache.cordova.NativeToJsMessageQueue; -import org.apache.cordova.PluginEntry; -import org.apache.cordova.PluginManager; -import org.xwalk.core.XWalkActivityDelegate; -import org.xwalk.core.XWalkNavigationHistory; -import org.xwalk.core.XWalkView; -import org.xwalk.core.XWalkGetBitmapCallback; - -/** - * Glue class between CordovaWebView (main Cordova logic) and XWalkCordovaView (the actual View). - */ -public class XWalkWebViewEngine implements CordovaWebViewEngine { - - public static final String TAG = "XWalkWebViewEngine"; - public static final String XWALK_USER_AGENT = "xwalkUserAgent"; - public static final String XWALK_Z_ORDER_ON_TOP = "xwalkZOrderOnTop"; - - private static final String XWALK_EXTENSIONS_FOLDER = "xwalk-extensions"; - - protected final XWalkCordovaView webView; - protected XWalkCordovaCookieManager cookieManager; - protected CordovaBridge bridge; - protected CordovaWebViewEngine.Client client; - protected CordovaWebView parentWebView; - protected CordovaInterface cordova; - protected PluginManager pluginManager; - protected CordovaResourceApi resourceApi; - protected NativeToJsMessageQueue nativeToJsMessageQueue; - protected XWalkActivityDelegate activityDelegate; - protected String startUrl; - protected CordovaPreferences preferences; - - /** Used when created via reflection. */ - public XWalkWebViewEngine(Context context, CordovaPreferences preferences) { - this.preferences = preferences; - Runnable cancelCommand = new Runnable() { - @Override - public void run() { - cordova.getActivity().finish(); - } - }; - Runnable completeCommand = new Runnable() { - @Override - public void run() { - cookieManager = new XWalkCordovaCookieManager(); - - initWebViewSettings(); - exposeJsInterface(webView, bridge); - loadExtensions(); - - CordovaPlugin notifPlugin = new CordovaPlugin() { - @Override - public void onNewIntent(Intent intent) { - Log.i(TAG, "notifPlugin route onNewIntent() to XWalkView: " + intent.toString()); - XWalkWebViewEngine.this.webView.onNewIntent(intent); - } - - @Override - public Object onMessage(String id, Object data) { - if (id.equals("captureXWalkBitmap")) { - // Capture bitmap on UI thread. - XWalkWebViewEngine.this.cordova.getActivity().runOnUiThread(new Runnable() { - public void run() { - XWalkWebViewEngine.this.webView.captureBitmapAsync( - new XWalkGetBitmapCallback() { - @Override - public void onFinishGetBitmap(Bitmap bitmap, - int response) { - pluginManager.postMessage( - "onGotXWalkBitmap", bitmap); - } - }); - } - }); - } - return null; - } - }; - pluginManager.addService(new PluginEntry("XWalkNotif", notifPlugin)); - - // Send the massage of xwalk's ready to plugin. - if (pluginManager != null) { - pluginManager.postMessage("onXWalkReady", this); - } - - if (startUrl != null) { - webView.load(startUrl, null); - } - } - }; - activityDelegate = new XWalkActivityDelegate((Activity) context, cancelCommand, completeCommand); - - webView = new XWalkCordovaView(context, preferences); - } - - // Use two-phase init so that the control will work with XML layouts. - - @Override - public void init(CordovaWebView parentWebView, CordovaInterface cordova, CordovaWebViewEngine.Client client, - CordovaResourceApi resourceApi, PluginManager pluginManager, - NativeToJsMessageQueue nativeToJsMessageQueue) { - if (this.cordova != null) { - throw new IllegalStateException(); - } - this.parentWebView = parentWebView; - this.cordova = cordova; - this.client = client; - this.resourceApi = resourceApi; - this.pluginManager = pluginManager; - this.nativeToJsMessageQueue = nativeToJsMessageQueue; - - CordovaPlugin activityDelegatePlugin = new CordovaPlugin() { - @Override - public void onResume(boolean multitasking) { - activityDelegate.onResume(); - } - }; - pluginManager.addService(new PluginEntry("XWalkActivityDelegate", activityDelegatePlugin)); - - webView.init(this); - - nativeToJsMessageQueue.addBridgeMode(new NativeToJsMessageQueue.OnlineEventsBridgeMode( - new NativeToJsMessageQueue.OnlineEventsBridgeMode.OnlineEventsBridgeModeDelegate() { - @Override - public void setNetworkAvailable(boolean value) { - webView.setNetworkAvailable(value); - } - @Override - public void runOnUiThread(Runnable r) { - XWalkWebViewEngine.this.cordova.getActivity().runOnUiThread(r); - } - })); - bridge = new CordovaBridge(pluginManager, nativeToJsMessageQueue); - } - - @Override - public CordovaWebView getCordovaWebView() { - return parentWebView; - } - - @Override - public View getView() { - return webView; - } - - private void initWebViewSettings() { - webView.setVerticalScrollBarEnabled(false); - - boolean zOrderOnTop = preferences == null ? false : preferences.getBoolean(XWALK_Z_ORDER_ON_TOP, false); - webView.setZOrderOnTop(zOrderOnTop); - - // Set xwalk webview settings by Cordova preferences. - String xwalkUserAgent = preferences == null ? "" : preferences.getString(XWALK_USER_AGENT, ""); - if (!xwalkUserAgent.isEmpty()) { - webView.setUserAgentString(xwalkUserAgent); - } - - String appendUserAgent = preferences.getString("AppendUserAgent", ""); - if (!appendUserAgent.isEmpty()) { - webView.setUserAgentString(webView.getUserAgentString() + " " + appendUserAgent); - } - - if (preferences.contains("BackgroundColor")) { - int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK); - webView.setBackgroundColor(backgroundColor); - } - } - - private static void exposeJsInterface(XWalkView webView, CordovaBridge bridge) { - XWalkExposedJsApi exposedJsApi = new XWalkExposedJsApi(bridge); - webView.addJavascriptInterface(exposedJsApi, "_cordovaNative"); - } - - private void loadExtensions() { - AssetManager assetManager = cordova.getActivity().getAssets(); - String[] extList; - try { - Log.i(TAG, "Iterate assets/xwalk-extensions folder"); - extList = assetManager.list(XWALK_EXTENSIONS_FOLDER); - } catch (IOException e) { - Log.w(TAG, "Failed to iterate assets/xwalk-extensions folder"); - return; - } - - for (String path : extList) { - // Load the extension. - Log.i(TAG, "Start to load extension: " + path); - webView.getExtensionManager().loadExtension(XWALK_EXTENSIONS_FOLDER + File.separator + path); - } - } - - @Override - public boolean canGoBack() { - if (!activityDelegate.isXWalkReady()) return false; - return this.webView.getNavigationHistory().canGoBack(); - } - - @Override - public boolean goBack() { - if (this.webView.getNavigationHistory().canGoBack()) { - this.webView.getNavigationHistory().navigate(XWalkNavigationHistory.Direction.BACKWARD, 1); - return true; - } - return false; - } - - @Override - public void setPaused(boolean value) { - if (!activityDelegate.isXWalkReady()) return; - if (value) { - // TODO: I think this has been fixed upstream and we don't need to override pauseTimers() anymore. - webView.pauseTimersForReal(); - } else { - webView.resumeTimers(); - } - } - - @Override - public void destroy() { - if (!activityDelegate.isXWalkReady()) return; - webView.onDestroy(); - } - - @Override - public void clearHistory() { - if (!activityDelegate.isXWalkReady()) return; - this.webView.getNavigationHistory().clear(); - } - - @Override - public void stopLoading() { - if (!activityDelegate.isXWalkReady()) return; - this.webView.stopLoading(); - } - - @Override - public void clearCache() { - if (!activityDelegate.isXWalkReady()) return; - webView.clearCache(true); - } - - @Override - public String getUrl() { - if (!activityDelegate.isXWalkReady()) return null; - return this.webView.getUrl(); - } - - @Override - public ICordovaCookieManager getCookieManager() { - return cookieManager; - } - - @Override - public void loadUrl(String url, boolean clearNavigationStack) { - if (!activityDelegate.isXWalkReady()) { - startUrl = url; - return; - } - webView.load(url, null); - } - - public boolean isXWalkReady() { - return activityDelegate.isXWalkReady(); - } -} diff --git a/plugins/cordova-plugin-crosswalk-webview/platforms/android/xwalk.gradle b/plugins/cordova-plugin-crosswalk-webview/platforms/android/xwalk.gradle deleted file mode 100644 index ec545e6..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/platforms/android/xwalk.gradle +++ /dev/null @@ -1,167 +0,0 @@ -/* - 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. -*/ - -def EMBEDDED_MODE = "embedded" -def SHARED_MODE = "shared" -def LITE_MODE = "lite" -def DEFAULT_GROUP_ID = "org.xwalk:" -def SHARED_ARTIFACT_ID = "xwalk_shared_library:" -def EMBEDD_ARTIFACT_ID = "xwalk_core_library:" -def CANARY_ARTIFACT_ID = "xwalk_core_library_canary:" -def BIT_64 = ":64bit@aar" - -def getConfigPreference(name) { - name = name.toLowerCase() - def xml = file("res/xml/config.xml").getText() - // Disable namespace awareness since Cordova doesn't use them properly - def root = new XmlParser(false, false).parseText(xml) - - def ret, defaultValue - root.preference.each { it -> - def attrName = it.attribute("name") - if (attrName && attrName.toLowerCase() == name) { - if (it.attribute('default') != null) { - defaultValue = it.attribute('default'); - } else { - ret = it.attribute("value") - } - } - } - return ret ? ret : defaultValue -} - -if (!project.hasProperty('xwalk64bit')) { - ext.xwalk64bit = getConfigPreference("xwalk64bit"); - println xwalk64bit -} -if (cdvBuildMultipleApks == null) { - ext.xwalkMultipleApk = getConfigPreference("xwalkMultipleApk").toBoolean(); -} else { - ext.xwalkMultipleApk = cdvBuildMultipleApks.toBoolean(); -} - -if (cdvMinSdkVersion == null) { - def minSdk = getConfigPreference("android-minSdkVersion"); - ext.cdvMinSdkVersion = minSdk && minSdk.toInteger() > 14 ? minSdk : 14; -} - -if (!project.hasProperty('xwalkMode')) { - ext.xwalkMode = getConfigPreference("xwalkMode"); -} - - -if (ext.xwalkMode == SHARED_MODE) { - // Build one apk at shared mode because the value of - // ext.cdvBuildMultipleApks is false by default. - xwalk64bit = null; -} else if (xwalk64bit == null) { - // Build embedded 32 bit crosswalk will generate two apks by default. - ext.cdvBuildMultipleApks = xwalkMultipleApk; -} - -// Set defaults before project's build-extras.gradle -if (!project.hasProperty('xwalkVersion')) { - ext.xwalkVersion = getConfigPreference("xwalkVersion") -} - -// Set defaults before project's build-extras.gradle -if (!project.hasProperty('xwalkLiteVersion')) { - ext.xwalkLiteVersion = getConfigPreference("xwalkLiteVersion") -} - -if (!project.hasProperty('xwalkCommandLine')) { - ext.xwalkCommandLine = getConfigPreference("xwalkCommandLine") -} -// Apply values after project's build-extras.gradle -cdvPluginPostBuildExtras.add({ - def xwalkMavenRepo = 'https://download.01.org/crosswalk/releases/crosswalk/android/maven2'; - if (xwalkMode == LITE_MODE) { - xwalkMavenRepo = 'https://download.01.org/crosswalk/releases/crosswalk-lite/android/maven2'; - } - repositories { - maven { - url xwalkMavenRepo - } - } - - android { - if (xwalk64bit != null) { - productFlavors { - x86_64 { - versionCode defaultConfig.versionCode + 6 - ndk { - abiFilters "x86_64", "" - } - } - arm64 { - versionCode defaultConfig.versionCode + 9 - ndk { - abiFilters "arm64-v8a", "" - } - } - } - } - } - - def xwalkSpec = xwalkVersion - if (ext.xwalkMode == LITE_MODE) { - xwalkSpec = xwalkLiteVersion; - } - - if ((xwalkSpec =~ /:/).count == 1) { - xwalkSpec = DEFAULT_GROUP_ID + xwalkSpec - } else if ((xwalkSpec =~ /:/).count == 0) { - if (xwalkSpec ==~ /\d+/) { - xwalkSpec = "${xwalkSpec}+" - } - - def artifactid = EMBEDD_ARTIFACT_ID; - if (ext.xwalkMode == SHARED_MODE) { - artifactid = SHARED_ARTIFACT_ID; - } else if (ext.xwalkMode == LITE_MODE) { - artifactid = CANARY_ARTIFACT_ID; - } - xwalkSpec = DEFAULT_GROUP_ID + artifactid + xwalkSpec - } - if (xwalk64bit != null) { - xwalkSpec = xwalkSpec + BIT_64 - } - println xwalkSpec - - dependencies { - compile xwalkSpec - } - - if (file('assets/xwalk-command-line').exists()) { - println('Not writing assets/xwalk-command-line since file already exists.') - return - } - android.applicationVariants.all { variant -> - def variantName = variant.name.capitalize() - def mergeTask = tasks["merge${variantName}Assets"] - def processTask = tasks["process${variantName}Resources"] - def outFile = new File (mergeTask.outputDir, "xwalk-command-line") - def newTask = project.task("createXwalkCommandLineFile${variantName}") << { - mergeTask.outputDir.mkdirs() - outFile.write("xwalk ${xwalkCommandLine}\n") - } - newTask.dependsOn(mergeTask) - processTask.dependsOn(newTask) - } -}) diff --git a/plugins/cordova-plugin-crosswalk-webview/plugin.xml b/plugins/cordova-plugin-crosswalk-webview/plugin.xml deleted file mode 100644 index 6f667de..0000000 --- a/plugins/cordova-plugin-crosswalk-webview/plugin.xml +++ /dev/null @@ -1,64 +0,0 @@ - - - - - Crosswalk WebView Engine - Changes the default WebView to CrossWalk - Apache 2.0 - cordova,chromium,crosswalk,webview - https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview - https://crosswalk-project.org/jira - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - After much discussion and analysis of the market, we have decided to discontinue support for Android 4.0 (ICS) in Crosswalk starting with version 20. - - So the minSdkVersion of Cordova project is configured to 16 by default. - - diff --git a/plugins/cordova-plugin-network-information/CONTRIBUTING.md b/plugins/cordova-plugin-network-information/CONTRIBUTING.md deleted file mode 100644 index 4c8e6a5..0000000 --- a/plugins/cordova-plugin-network-information/CONTRIBUTING.md +++ /dev/null @@ -1,37 +0,0 @@ - - -# Contributing to Apache Cordova - -Anyone can contribute to Cordova. And we need your contributions. - -There are multiple ways to contribute: report bugs, improve the docs, and -contribute code. - -For instructions on this, start with the -[contribution overview](http://cordova.apache.org/contribute/). - -The details are explained there, but the important items are: - - Sign and submit an Apache ICLA (Contributor License Agreement). - - Have a Jira issue open that corresponds to your contribution. - - Run the tests so your patch doesn't break existing functionality. - -We look forward to your contributions! diff --git a/plugins/cordova-plugin-network-information/LICENSE b/plugins/cordova-plugin-network-information/LICENSE deleted file mode 100644 index 7a4a3ea..0000000 --- a/plugins/cordova-plugin-network-information/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/NOTICE b/plugins/cordova-plugin-network-information/NOTICE deleted file mode 100644 index fb19cbd..0000000 --- a/plugins/cordova-plugin-network-information/NOTICE +++ /dev/null @@ -1,8 +0,0 @@ -Apache Cordova -Copyright 2012 The Apache Software Foundation - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). - -This product includes software developed by Apple Inc. License can be found in the header of the affected files. (src/ios/CDVReachability.h, src/ios/CDVReachability.m) - diff --git a/plugins/cordova-plugin-network-information/README.md b/plugins/cordova-plugin-network-information/README.md deleted file mode 100644 index a0c8041..0000000 --- a/plugins/cordova-plugin-network-information/README.md +++ /dev/null @@ -1,209 +0,0 @@ - - -# cordova-plugin-network-information - - -This plugin provides an implementation of an old version of the -[Network Information API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). -It provides information about the device's cellular and -wifi connection, and whether the device has an internet connection. - -:warning: Report issues on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Network%20Information%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC) - -## Installation - - cordova plugin add cordova-plugin-network-information - -## Supported Platforms - -- Amazon Fire OS -- Android -- BlackBerry 10 -- Browser -- iOS -- Windows Phone 7 and 8 -- Tizen -- Windows -- Firefox OS - -# Connection - -> The `connection` object, exposed via `navigator.connection`, provides information about the device's cellular and wifi connection. - -## Properties - -- connection.type - -## Constants - -- Connection.UNKNOWN -- Connection.ETHERNET -- Connection.WIFI -- Connection.CELL_2G -- Connection.CELL_3G -- Connection.CELL_4G -- Connection.CELL -- Connection.NONE - -## connection.type - -This property offers a fast way to determine the device's network -connection state, and type of connection. - -### Quick Example - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API Change - -Until Cordova 2.3.0, the `Connection` object was accessed via -`navigator.network.connection`, after which it was changed to -`navigator.connection` to match the W3C specification. It's still -available at its original location, but is deprecated and will -eventually be removed. - -### iOS Quirks - -- iOS can't detect the type of cellular network connection. - - `navigator.connection.type` is set to `Connection.CELL` for all cellular data. - -### Windows Phone Quirks - -- When running in the emulator, always detects `navigator.connection.type` as `Connection.UNKNOWN`. - -- Windows Phone can't detect the type of cellular network connection. - - `navigator.connection.type` is set to `Connection.CELL` for all cellular data. - -### Windows Quirks - -- When running in the Phone 8.1 emulator, always detects `navigator.connection.type` as `Connection.ETHERNET`. - -### Tizen Quirks - -- Tizen can only detect a WiFi or cellular connection. - - `navigator.connection.type` is set to `Connection.CELL_2G` for all cellular data. - -### Firefox OS Quirks - -- Firefox OS can't detect the type of cellular network connection. - - `navigator.connection.type` is set to `Connection.CELL` for all cellular data. - -### Browser Quirks - -- Browser can't detect the type of network connection. -`navigator.connection.type` is always set to `Connection.UNKNOWN` when online. - -# Network-related Events - -## offline - -The event fires when an application goes offline, and the device is -not connected to the Internet. - - document.addEventListener("offline", yourCallbackFunction, false); - -### Details - -The `offline` event fires when a previously connected device loses a -network connection so that an application can no longer access the -Internet. It relies on the same information as the Connection API, -and fires when the value of `connection.type` becomes `NONE`. - -Applications typically should use `document.addEventListener` to -attach an event listener once the `deviceready` event fires. - -### Quick Example - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS Quirks - -During initial startup, the first offline event (if applicable) takes at least a second to fire. - -### Windows Phone 7 Quirks - -When running in the Emulator, the `connection.status` is always unknown, so this event does _not_ fire. - -### Windows Phone 8 Quirks - -The Emulator reports the connection type as `Cellular`, which does not change, so the event does _not_ fire. - -## online - -This event fires when an application goes online, and the device -becomes connected to the Internet. - - document.addEventListener("online", yourCallbackFunction, false); - -### Details - -The `online` event fires when a previously unconnected device receives -a network connection to allow an application access to the Internet. -It relies on the same information as the Connection API, -and fires when the `connection.type` changes from `NONE` to any other -value. - -Applications typically should use `document.addEventListener` to -attach an event listener once the `deviceready` event fires. - -### Quick Example - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS Quirks - -During initial startup, the first `online` event (if applicable) takes -at least a second to fire, prior to which `connection.type` is -`UNKNOWN`. - -### Windows Phone 7 Quirks - -When running in the Emulator, the `connection.status` is always unknown, so this event does _not_ fire. - -### Windows Phone 8 Quirks - -The Emulator reports the connection type as `Cellular`, which does not change, so events does _not_ fire. diff --git a/plugins/cordova-plugin-network-information/RELEASENOTES.md b/plugins/cordova-plugin-network-information/RELEASENOTES.md deleted file mode 100644 index 95ca114..0000000 --- a/plugins/cordova-plugin-network-information/RELEASENOTES.md +++ /dev/null @@ -1,124 +0,0 @@ - -# Release Notes - -### 1.1.0 (Nov 18, 2015) -* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest -* Fixing contribute link. -* These notifications are objects so their address always evaluates to true. -* Update `NetworkManager.java` -* [CB-9542](https://issues.apache.org/jira/browse/CB-9542) `Browser Proxy` not defined correctly -* Solved `toLowerCase` issue with `Locale.US` - -### 1.0.1 (Jun 17, 2015) -* Adding .ratignore file. -* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-network-information documentation translation: cordova-plugin-network-information -* fix npm md issue - -### 1.0.0 (Apr 15, 2015) -* [CB-8746](https://issues.apache.org/jira/browse/CB-8746) gave plugin major version bump -* [CB-8683](https://issues.apache.org/jira/browse/CB-8683) changed plugin-id to pacakge-name -* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) properly updated translated docs to use new id -* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) updated translated docs to use new id -* [CB-8185](https://issues.apache.org/jira/browse/CB-8185) Fixes typo in `cordova.platformId` -* Use TRAVIS_BUILD_DIR, install paramedic by npm -* [CB-8185](https://issues.apache.org/jira/browse/CB-8185) Use `navigator.onLine` as connection information source on browser platform -* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme -* [CB-8659](https://issues.apache.org/jira/browse/CB-8659): ios: 4.0.x Compatibility: Remove use of initWebView method -* [CB-8573](https://issues.apache.org/jira/browse/CB-8573) Integrate TravisCI -* [CB-8438](https://issues.apache.org/jira/browse/CB-8438) cordova-plugin-network-information documentation translation: cordova-plugin-network-information -* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file - -### 0.2.15 (Feb 04, 2015) -* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Network status change support on Windows -* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Fixes the way we detect online status on Windows -* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Add Windows platform quirks -* [CB-8384](https://issues.apache.org/jira/browse/CB-8384) Add Windows section to Network Information plugin - -### 0.2.14 (Dec 02, 2014) -* [CB-7976](https://issues.apache.org/jira/browse/CB-7976) **Android**: Use webView's context rather than Activity's context for intent receiver -* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-network-information documentation translation: cordova-plugin-network-information - -### 0.2.13 (Oct 03, 2014) -* [CB-7595](https://issues.apache.org/jira/browse/CB-7595): Android L changes the type from Mobile to Cellular, I'm pretty sure this isn't documented - -### 0.2.12 (Sep 17, 2014) -* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-network-information documentation translation -* Fix network information type exception on fxos 2 -* Added support for the browser -* [CB-6724](https://issues.apache.org/jira/browse/CB-6724) added documentation for manual tests -* remove reference to test assets, they are optional -* Renamed test dir and added nested plugin.xml -* [CB-6964](https://issues.apache.org/jira/browse/CB-6964) ported manual tests -* Port network tests to plugin-test-framework -* Fix naviagtor typo - -### 0.2.11 (Aug 06, 2014) -* **FFOS** update NetworkProxy.js -* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs -* [CB-7019](https://issues.apache.org/jira/browse/CB-7019) Updated version and RELEASENOTES.md for release 0.2.10 -* Fixed docs for online/offline event being backwards - -### 0.2.10 (Jun 24, 2014) -* [CB-6907](https://issues.apache.org/jira/browse/CB-6907): [android] Don't crash on startup if no networks available - -### 0.2.9 (Jun 05, 2014) -* updated notice file to include missing license -* Cached extra info to better detect changes. -* [CB-6809](https://issues.apache.org/jira/browse/CB-6809) Add license to CONTRIBUTING.md -* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md -* [CB-6350](https://issues.apache.org/jira/browse/CB-6350) - Fix networkStatusForFlags return value type to work with 64-bit iOS (closes #8) -* Initial version of firefox os network information plugin -* there was an error in the object definition - -### 0.2.8 (Apr 17, 2014) -* [CB-6342](https://issues.apache.org/jira/browse/CB-6342): [iOS] iOS reports a cellular connection even when in Airplane mode -* [CB-6422](https://issues.apache.org/jira/browse/CB-6422): [windows8] use cordova/exec/proxy -* [CB-6460](https://issues.apache.org/jira/browse/CB-6460): Update license headers -* [CB-6465](https://issues.apache.org/jira/browse/CB-6465): Add license headers to Tizen code -* Add NOTICE file - -### 0.2.7 (Feb 05, 2014) -* Initial implementation of Tizen plugin. - -### 0.2.6 (Jan 02, 2014) -* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for netinfo plugin - -### 0.2.5 (Dec 4, 2013) -* [ubuntu] specify policy_group -* add ubuntu platform -* Added amazon-fireos platform. Change to use amazon-fireos as the platform if user agent string contains 'cordova-amazon-fireos' - -### 0.2.4 (Oct 28, 2013) -* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): add repo + issue tag to plugin.xml for network information plugin -* [CB-4915](https://issues.apache.org/jira/browse/CB-4915) Incremented plugin version on dev branch. - -### 0.2.3 (Sept 25, 2013) -* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) bumping&resetting version -* [windows8] commandProxy was moved -* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.network-information to org.apache.cordova.network-information -* removed duplicate comment line from plugin.xml -* added Network APIs for FirefoxOS -* Rename CHANGELOG.md -> RELEASENOTES.md -* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch. - -### 0.2.1 (Sept 5, 2013) -* [CB-4432](https://issues.apache.org/jira/browse/CB-4432) copyright notice change diff --git a/plugins/cordova-plugin-network-information/doc/de/README.md b/plugins/cordova-plugin-network-information/doc/de/README.md deleted file mode 100644 index f6292b2..0000000 --- a/plugins/cordova-plugin-network-information/doc/de/README.md +++ /dev/null @@ -1,190 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -Dieses Plugin stellt eine Implementierung einer alten Version der [Netzwerk-Informationen-API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Es werden Informationen über das Gerät Mobilfunk und Wifi-Anschluss, und ob das Gerät über eine Internetverbindung verfügt. - -## Installation - - cordova plugin add cordova-plugin-network-information - - -## Unterstützte Plattformen - - * Amazon Fire OS - * Android - * BlackBerry 10 - * Browser - * iOS - * Windows Phone 7 und 8 - * Tizen - * Windows - * Firefox OS - -# Connection - -> Das `connection` Objekt, verfügbar gemachten über `navigator.connection`, enthält Informationen über die Mobilfunk- und Wi-Fi-Verbindung des Gerätes. - -## Eigenschaften - - * connection.type - -## Konstanten - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## connection.type - -Diese Eigenschaft bietet eine schnelle Möglichkeit, um den Netzwerkverbindungsstatus und die Art der Verbindung zu bestimmen. - -### Kurzes Beispiel - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API Änderung - -Bis Cordova 2.3.0 wurde auf das `Connection` Objekt über `navigator.network.connection` zugegriffen, danach wurde der Zugriff auf `navigator.connection` geändert, um der W3C-Spezifikation zu entsprechen. Es steht immer noch an seiner ursprünglichen Stelle, aber ist veraltet und wird schliesslich entfernt. - -### iOS Macken - - * iOS kann Mobilfunknetz Verbindungstyp nicht erkennen. - * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. - -### Windows Phone Macken - - * Wenn im Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als`Connection.UNKNOWN`. - - * Windows Phone kann Mobilfunknetz Verbindungstyp nicht erkennen. - - * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. - -### Windows-Eigenheiten - - * Wenn im Telefon 8.1 Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als `Connection.ETHERNET`. - -### Tizen Macken - - * Tizen kann nur ein WiFi oder Mobilfunkverbindung erkennen. - * `Navigator.Connection.Type` ist für alle Handy-Daten auf `Connection.CELL_2G` festgelegt. - -### Firefox OS Macken - - * Firefox-OS kann Mobilfunknetz Verbindungstyp nicht erkennen. - * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. - -### Browser-Eigenheiten - - * Browser kann die Art der Netzwerkverbindung nicht erkennen. `navigator.connection.type` ist immer auf `Connection.UNKNOWN` beim online gesetzt. - -# Netzwerk-Veranstaltungen - -## offline - -Das Ereignis wird ausgelöst, wenn eine Anwendung offline geht, und das Gerät nicht mit dem Internet verbunden ist. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Details - -Das `offline` -Ereignis wird ausgelöst, wenn ein bereits angeschlossenes Gerät eine Netzwerkverbindung verliert, so dass eine Anwendung nicht mehr auf das Internet zugreifen kann. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn der Wert des `connection.type` wird`NONE`. - -Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. - -### Kurzes Beispiel - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS Macken - -Beim ersten Start dauert das erste offline-Event (falls zutreffend) mindestens eine Sekunde zu schießen. - -### Windows Phone 7 Macken - -Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. - -### Windows Phone 8 Macken - -Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass das Ereignis *nicht* Feuer. - -## online - -Dieses Ereignis wird ausgelöst, wenn eine Anwendung online geht, und das Gerät wird mit dem Internet verbunden. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Details - -Das `online` -Ereignis wird ausgelöst, wenn ein zuvor unverbundenen Gerät eine Netzwerkverbindung zu einem Anwendung Zugriff auf das Internet empfängt. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn die `connection.type` ändert sich von `NONE` auf einen anderen Wert. - -Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. - -### Kurzes Beispiel - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS Macken - -Beim ersten Start die erste `online` Ereignis (falls zutreffend) dauert mindestens eine Sekunde vor dem Feuer `connection.type` ist`UNKNOWN`. - -### Windows Phone 7 Macken - -Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. - -### Windows Phone 8 Macken - -Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass Ereignisse *nicht* Feuer. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/de/index.md b/plugins/cordova-plugin-network-information/doc/de/index.md deleted file mode 100644 index 537328a..0000000 --- a/plugins/cordova-plugin-network-information/doc/de/index.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# cordova-plugin-network-information - -Dieses Plugin stellt eine Implementierung einer alten Version der [Netzwerk-Informationen-API][1]. Es werden Informationen über das Gerät Mobilfunk und Wifi-Anschluss, und ob das Gerät über eine Internetverbindung verfügt. - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## Installation - - cordova plugin add cordova-plugin-network-information - - -## Unterstützte Plattformen - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Browser -* iOS -* Windows Phone 7 und 8 -* Tizen -* Windows -* Firefox OS - -# Connection - -> Das `connection` Objekt, verfügbar gemachten über `navigator.connection`, enthält Informationen über die Mobilfunk- und Wi-Fi-Verbindung des Gerätes. - -## Eigenschaften - -* connection.type - -## Konstanten - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## connection.type - -Diese Eigenschaft bietet eine schnelle Möglichkeit, um den Netzwerkverbindungsstatus und die Art der Verbindung zu bestimmen. - -### Kurzes Beispiel - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API Änderung - -Bis Cordova 2.3.0 wurde auf das `Connection` Objekt über `navigator.network.connection` zugegriffen, danach wurde der Zugriff auf `navigator.connection` geändert, um der W3C-Spezifikation zu entsprechen. Es steht immer noch an seiner ursprünglichen Stelle, aber ist veraltet und wird schliesslich entfernt. - -### iOS Macken - -* iOS kann Mobilfunknetz Verbindungstyp nicht erkennen. - * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. - -### Windows Phone Macken - -* Wenn im Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als`Connection.UNKNOWN`. - -* Windows Phone kann Mobilfunknetz Verbindungstyp nicht erkennen. - - * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. - -### Windows-Eigenheiten - -* Wenn im Telefon 8.1 Emulator ausgeführt wird, erkennt immer `navigator.connection.type` als `Connection.ETHERNET`. - -### Tizen Macken - -* Tizen kann nur ein WiFi oder Mobilfunkverbindung erkennen. - * `Navigator.Connection.Type` ist für alle Handy-Daten auf `Connection.CELL_2G` festgelegt. - -### Firefox OS Macken - -* Firefox-OS kann Mobilfunknetz Verbindungstyp nicht erkennen. - * `navigator.connection.type`auf festgelegt ist `Connection.CELL` für alle Handy-Daten. - -# Netzwerk-Veranstaltungen - -## offline - -Das Ereignis wird ausgelöst, wenn eine Anwendung offline geht, und das Gerät nicht mit dem Internet verbunden ist. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Details - -Das `offline` -Ereignis wird ausgelöst, wenn ein bereits angeschlossenes Gerät eine Netzwerkverbindung verliert, so dass eine Anwendung nicht mehr auf das Internet zugreifen kann. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn der Wert des `connection.type` wird`NONE`. - -Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. - -### Kurzes Beispiel - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS Macken - -Beim ersten Start dauert das erste offline-Event (falls zutreffend) mindestens eine Sekunde zu schießen. - -### Windows Phone 7 Macken - -Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. - -### Windows Phone 8 Macken - -Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass das Ereignis *nicht* Feuer. - -## online - -Dieses Ereignis wird ausgelöst, wenn eine Anwendung online geht, und das Gerät wird mit dem Internet verbunden. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Details - -Das `online` -Ereignis wird ausgelöst, wenn ein zuvor unverbundenen Gerät eine Netzwerkverbindung zu einem Anwendung Zugriff auf das Internet empfängt. Es stützt sich auf die gleichen Informationen wie die Verbindung-API und wird ausgelöst, wenn die `connection.type` ändert sich von `NONE` auf einen anderen Wert. - -Anwendungen sollten in der Regel verwenden `document.addEventListener` einmal einen Ereignis-Listener hinzufügen das `deviceready` -Ereignis ausgelöst. - -### Kurzes Beispiel - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS Macken - -Beim ersten Start die erste `online` Ereignis (falls zutreffend) dauert mindestens eine Sekunde vor dem Feuer `connection.type` ist`UNKNOWN`. - -### Windows Phone 7 Macken - -Bei der Ausführung im Emulator, der `connection.status` ist immer unbekannt, so dass dieses Ereignis *nicht* Feuer. - -### Windows Phone 8 Macken - -Der Emulator meldet den Verbindungstyp als `Cellular` , die wird nicht geändert, so dass Ereignisse *nicht* Feuer. diff --git a/plugins/cordova-plugin-network-information/doc/es/README.md b/plugins/cordova-plugin-network-information/doc/es/README.md deleted file mode 100644 index 4e30593..0000000 --- a/plugins/cordova-plugin-network-information/doc/es/README.md +++ /dev/null @@ -1,190 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -Este plugin proporciona una implementación de una versión antigua de la [Red de información API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Proporciona información acerca del dispositivo móvil y conexión wifi, y si el dispositivo tiene una conexión a internet. - -## Instalación - - cordova plugin add cordova-plugin-network-information - - -## Plataformas soportadas - - * Amazon fire OS - * Android - * BlackBerry 10 - * Explorador - * iOS - * Windows Phone 7 y 8 - * Tizen - * Windows - * Firefox OS - -# Connection - -> El objeto de `connection`, expuesto a través de `navigator.connection`, proporciona información sobre conexión celular y wifi del dispositivo. - -## Propiedades - - * connection.type - -## Constantes - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## connection.type - -Esta propiedad ofrece una forma rápida de determinar el estado de conexión de red del dispositivo y el tipo de conexión. - -### Ejemplo rápido - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Cambio de API - -Hasta Cordova 2.3.0, el objeto de `conexión` era acceder a través de `navigator.network.connection`, tras lo cual fue cambiada a `navigator.connection` para que coincida con la especificación del W3C. Sigue estando disponible en su ubicación original, pero es obsoleto y eventualmente desaparecerá. - -### iOS rarezas - - * iOS no puede detectar el tipo de conexión de red celular. - * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. - -### Windows Phone rarezas - - * Cuando se ejecuta en el emulador, siempre detecta `navigator.connection.type` como `Connection.UNKNOWN`. - - * Windows Phone no puede detectar el tipo de conexión de red celular. - - * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. - -### Windows rarezas - - * Cuando se ejecuta en el emulador de teléfono 8.1, siempre detecta `navigator.connection.type` como`Connection.ETHERNET`. - -### Rarezas Tizen - - * Tizen sólo puede detectar un Wi-Fi o conexión celular. - * `navigator.connection.type`se establece en `Connection.CELL_2G` para todos los datos celulares. - -### Firefox OS rarezas - - * Firefox OS no puede detectar el tipo de conexión de red celular. - * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. - -### Navegador rarezas - - * Navegador no puede detectar el tipo de conexión de red. `Navigator.Connection.Type` se encuentra siempre a `Connection.UNKNOWN` cuando en línea. - -# Eventos relacionados con la red - -## offline - -El evento se desencadena cuando una aplicación está desconectada, y el dispositivo no está conectado a Internet. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Detalles - -El evento `offline` se desencadena cuando un dispositivo conectado previamente pierde una conexión de red para que una aplicación no puede acceder a Internet. Se basa en la misma información que la API de conexión y cuando se dispara el valor del `connection.type` se convierte`NONE`. - -Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. - -### Ejemplo rápido - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS rarezas - -Durante el arranque inicial, el primer evento offline (si es aplicable) tarda al menos un segundo en fuego. - -### Windows Phone 7 rarezas - -Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. - -### Windows Phone 8 rarezas - -El emulador informa el tipo de conexión como `celular`, que no cambia, así que el evento *no se* fuego. - -## online - -Este evento se desencadena cuando una aplicación va en línea, y el dispositivo se conecta a Internet. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Detalles - -El evento `online` se desencadena cuando un dispositivo previamente inconexos recibe una conexión de red para permitir un acceso a las aplicaciones para Internet. Se basa en la misma información que la API de conexión y se desencadena cuando el `connection.type` cambia de `ninguno` a cualquier otro valor. - -Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. - -### Ejemplo rápido - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS rarezas - -Durante el arranque inicial, el primer evento `en línea` (si procede) al menos toma un segundo para disparar, antes de que `connection.type` es `desconocido`. - -### Windows Phone 7 rarezas - -Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. - -### Windows Phone 8 rarezas - -El emulador, informa el tipo de conexión como `Cellular` , que no cambia, así que se lo eventos *no* fuego. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/es/index.md b/plugins/cordova-plugin-network-information/doc/es/index.md deleted file mode 100644 index 65158ef..0000000 --- a/plugins/cordova-plugin-network-information/doc/es/index.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# cordova-plugin-network-information - -Este plugin proporciona una implementación de una versión antigua de la [Red de información API][1]. Proporciona información acerca del dispositivo móvil y conexión wifi, y si el dispositivo tiene una conexión a internet. - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## Instalación - - cordova plugin add cordova-plugin-network-information - - -## Plataformas soportadas - -* Amazon fire OS -* Android -* BlackBerry 10 -* Explorador -* iOS -* Windows Phone 7 y 8 -* Tizen -* Windows -* Firefox OS - -# Conexión - -> El objeto de `connection`, expuesto a través de `navigator.connection`, proporciona información sobre conexión celular y wifi del dispositivo. - -## Propiedades - -* connection.type - -## Constantes - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_4G -* Connection.CELL_3G -* Connection.CELL -* Connection.NONE - -## connection.type - -Esta propiedad ofrece una forma rápida de determinar el estado de conexión de red del dispositivo y el tipo de conexión. - -### Ejemplo rápido - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Cambio de API - -Hasta Cordova 2.3.0, el objeto de `conexión` era acceder a través de `navigator.network.connection`, tras lo cual fue cambiada a `navigator.connection` para que coincida con la especificación del W3C. Sigue estando disponible en su ubicación original, pero es obsoleto y eventualmente desaparecerá. - -### iOS rarezas - -* iOS no puede detectar el tipo de conexión de red celular. - * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. - -### Windows Phone rarezas - -* Cuando se ejecuta en el emulador, siempre detecta `navigator.connection.type` como `Connection.UNKNOWN`. - -* Windows Phone no puede detectar el tipo de conexión de red celular. - - * `navigator.connection.type` está establecido en `Connection.CELL` para todos los datos de celulares. - -### Windows rarezas - -* Cuando se ejecuta en el emulador de teléfono 8.1, siempre detecta `navigator.connection.type` como`Connection.ETHERNET`. - -### Rarezas Tizen - -* Tizen sólo puede detectar un Wi-Fi o conexión celular. - * `navigator.connection.type`se establece en `Connection.CELL_2G` para todos los datos celulares. - -### Firefox OS rarezas - -* Firefox OS no puede detectar el tipo de conexión de red celular. - * `navigator.connection.type`se establece en `Connection.CELL` para todos los datos celulares. - -# Eventos relacionados con la red - -## offline - -El evento se desencadena cuando una aplicación está desconectada, y el dispositivo no está conectado a Internet. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Detalles - -El evento `offline` se desencadena cuando un dispositivo conectado previamente pierde una conexión de red para que una aplicación no puede acceder a Internet. Se basa en la misma información que la API de conexión y cuando se dispara el valor del `connection.type` se convierte`NONE`. - -Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. - -### Ejemplo rápido - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS rarezas - -Durante el arranque inicial, el primer evento offline (si es aplicable) tarda al menos un segundo en fuego. - -### Windows Phone 7 rarezas - -Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. - -### Windows Phone 8 rarezas - -El emulador informa el tipo de conexión como `celular`, que no cambia, así que el evento *no se* fuego. - -## online - -Este evento se desencadena cuando una aplicación va en línea, y el dispositivo se conecta a Internet. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Detalles - -El evento `online` se desencadena cuando un dispositivo previamente inconexos recibe una conexión de red para permitir un acceso a las aplicaciones para Internet. Se basa en la misma información que la API de conexión y se desencadena cuando el `connection.type` cambia de `ninguno` a cualquier otro valor. - -Las aplicaciones normalmente deben utilizar `document.addEventListener` para conectar un detector de eventos una vez que se desencadene el evento `deviceready`. - -### Ejemplo rápido - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS rarezas - -Durante el arranque inicial, el primer evento `en línea` (si procede) al menos toma un segundo para disparar, antes de que `connection.type` es `desconocido`. - -### Windows Phone 7 rarezas - -Cuando se ejecuta en el emulador, la `connection.status` siempre es desconocido, así que este evento no se ** fuego. - -### Windows Phone 8 rarezas - -El emulador, informa el tipo de conexión como `Cellular` , que no cambia, así que se lo eventos *no* fuego. diff --git a/plugins/cordova-plugin-network-information/doc/fr/README.md b/plugins/cordova-plugin-network-information/doc/fr/README.md deleted file mode 100644 index 8f2b82c..0000000 --- a/plugins/cordova-plugin-network-information/doc/fr/README.md +++ /dev/null @@ -1,188 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -Ce plugin fournit une implémentation d'une ancienne version de l' [API Information Network](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Il fournit des informations sur l'appareil cellulaire et connexion wifi, et si l'appareil dispose d'une connexion internet. - -## Installation - - cordova plugin add cordova-plugin-network-information - - -## Plates-formes supportées - - * Amazon Fire OS - * Android - * BlackBerry 10 - * Navigateur - * iOS - * Windows Phone 7 et 8 - * Paciarelli - * Windows - * Firefox OS - -# Connexion - -> L'objet `connection`, disponible via `navigator.connection`, fournit des informations sur la connection cellulaire/wifi de l'appareil. - -## Propriétés - - * connection.type - -## Constantes - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## connection.type - -Cette propriété offre un moyen rapide pour déterminer l'état et le type de la connexion réseau de l'appareil. - -### Exemple court - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Changement d'API - -Jusqu'à Cordova 2.3.0, l'objet `Connection` était accessible via `navigator.network.connection` ; ceci a été changé pour `navigator.connection` afin de concorder avec la spécification du W3C. L'accès est toujours possible à l'emplacement d'origine, mais est considéré comme obsolète et sera bientôt supprimé. - -### Notes au sujet d'iOS - - * iOS ne peut pas détecter le type de connexion au réseau cellulaire. - * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. - -### Windows Phone Quirks - - * Lors de l'exécution dans l'émulateur, détecte toujours `navigator.connection.type` comme`Connection.UNKNOWN`. - - * Windows Phone ne peut pas détecter le type de connexion au réseau cellulaire. - - * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. - -### Bizarreries de Windows - - * Lors de l'exécution dans l'émulateur de téléphone 8.1, `Connection.ETHERNET` détecte toujours `navigator.connection.type`. - -### Bizarreries de paciarelli - - * Paciarelli ne peut détecter une connexion cellulaire ou le WiFi. - * `navigator.connection.type` a la valeur `Connection.CELL_2G` pour toutes les données cellulaires. - -### Firefox OS Quirks - - * Firefox OS ne peut pas détecter le type de connexion au réseau cellulaire. - * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. - -### Bizarreries navigateur - - * Navigateur ne peut pas détecter le type de connexion réseau. `navigator.connection.type` est toujours définie sur `Connection.UNKNOWN` en ligne. - -# Événements liés au réseau - -## offline - -L'évènement se déclenche lorsqu'une application se déconnecte, quand l'appareil n'est pas connecté à Internet. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Détails - -L'évènement `offline` se déclenche lorsqu'un appareil précédemment connecté perd sa connexion au réseau, empêchant ainsi l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche lorsque la valeur de `connection.type` devient`NONE`. - -Les applications devraient en général utiliser `document.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché. - -### Exemple court - - document.addEventListener (« hors ligne », onOffline, false) ; - - function onOffline() {/ / gestion de l'événement en mode hors connexion} - - -### Notes au sujet d'iOS - -Lors du démarrage initial, le déclenchement du premier évènement offline (si applicable) prend au moins une seconde. - -### Windows Phone 7 Quirks - -Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. - -### Notes au sujet de Windows Phone 8 - -L'émulateur signale le type de connexion comme `Cellular`, type qui ne change jamais, ainsi l'évènement n'est *pas* déclenché. - -## online - -L'évènement se déclenche lorsqu'une application se connecte, quand l'appareil est connecté à Internet. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Détails - -L'évènement `online` se déclenche lorsqu'un appareil précédemment non-connecté se connecte au réseau, permettant ainsi à l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche quand le `connection.type` passe de `NONE` à une autre valeur. - -Les applications devraient en général utiliser `document.addEventListener` pour attacher un écouteur d'évènements, une fois l'évènement `deviceready` déclenché. - -### Exemple court - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### Notes au sujet d'iOS - -Lors du démarrage initial, le déclenchement du premier évènement `online` (si applicable) prend au moins une seconde avant quoi `connection.type` vaut `UNKNOWN`. - -### Windows Phone 7 Quirks - -Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. - -### Notes au sujet de Windows Phone 8 - -L'émulateur signale le type de connexion comme `Cellular` , qui ne change pas, aussi des événements ne fait *pas* de feu. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/fr/index.md b/plugins/cordova-plugin-network-information/doc/fr/index.md deleted file mode 100644 index e49c5d5..0000000 --- a/plugins/cordova-plugin-network-information/doc/fr/index.md +++ /dev/null @@ -1,184 +0,0 @@ - - -# cordova-plugin-network-information - -Ce plugin fournit une implémentation d'une ancienne version de l' [API Information Network][1]. Il fournit des informations sur l'appareil cellulaire et connexion wifi, et si l'appareil dispose d'une connexion internet. - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## Installation - - cordova plugin add cordova-plugin-network-information - - -## Plates-formes prises en charge - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Navigateur -* iOS -* Windows Phone 7 et 8 -* Paciarelli -* Windows -* Firefox OS - -# Connexion - -> L'objet `connection`, disponible via `navigator.connection`, fournit des informations sur la connection cellulaire/wifi de l'appareil. - -## Propriétés - -* connection.type - -## Constantes - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## connection.type - -Cette propriété offre un moyen rapide pour déterminer l'état et le type de la connexion réseau de l'appareil. - -### Petit exemple - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Changement d'API - -Jusqu'à Cordova 2.3.0, l'objet `Connection` était accessible via `navigator.network.connection` ; ceci a été changé pour `navigator.connection` afin de concorder avec la spécification du W3C. L'accès est toujours possible à l'emplacement d'origine, mais est considéré comme obsolète et sera bientôt supprimé. - -### iOS Quirks - -* iOS ne peut pas détecter le type de connexion au réseau cellulaire. - * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. - -### Windows Phone Quirks - -* Lors de l'exécution dans l'émulateur, détecte toujours `navigator.connection.type` comme`Connection.UNKNOWN`. - -* Windows Phone ne peut pas détecter le type de connexion au réseau cellulaire. - - * `navigator.connection.type`a la valeur `Connection.CELL` pour toutes les données cellulaires. - -### Bizarreries de Windows - -* Lors de l'exécution dans l'émulateur de téléphone 8.1, `Connection.ETHERNET` détecte toujours `navigator.connection.type`. - -### Bizarreries de paciarelli - -* Paciarelli ne peut détecter une connexion cellulaire ou le WiFi. - * `navigator.connection.type` a la valeur `Connection.CELL_2G` pour toutes les données cellulaires. - -### Firefox OS Quirks - -* Firefox OS ne peut pas détecter le type de connexion au réseau cellulaire. - * `navigator.connection.type` a la valeur `Connection.CELL` pour toutes les données cellulaires. - -# Événements liés au réseau - -## offline - -L'évènement se déclenche lorsqu'une application se déconnecte, quand l'appareil n'est pas connecté à Internet. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Détails - -L'évènement `offline` se déclenche lorsqu'un appareil précédemment connecté perd sa connexion au réseau, empêchant ainsi l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche lorsque la valeur de `connection.type` devient`NONE`. - -Les applications doivent généralement utiliser `document.addEventListener` pour attacher un écouteur d'événements une fois le `deviceready` événement se déclenche. - -### Exemple court - - document.addEventListener (« hors ligne », onOffline, false) ; - - function onOffline() {/ / gestion de l'événement en mode hors connexion} - - -### Notes au sujet d'iOS - -Lors du démarrage initial, le déclenchement du premier évènement offline (si applicable) prend au moins une seconde. - -### Windows Phone 7 Quirks - -Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. - -### Notes au sujet de Windows Phone 8 - -L'émulateur signale le type de connexion comme `Cellular`, type qui ne change jamais, ainsi l'évènement n'est *pas* déclenché. - -## online - -L'évènement se déclenche lorsqu'une application se connecte, quand l'appareil est connecté à Internet. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Détails - -L'évènement `online` se déclenche lorsqu'un appareil précédemment non-connecté se connecte au réseau, permettant ainsi à l'application d'accéder à Internet. Il s'appuie sur les mêmes informations que l'API de connexion et se déclenche quand le `connection.type` passe de `NONE` à une autre valeur. - -Les applications doivent généralement utiliser `document.addEventListener` pour attacher un écouteur d'événements une fois le `deviceready` événement se déclenche. - -### Exemple court - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### Notes au sujet d'iOS - -Lors du démarrage initial, le déclenchement du premier évènement `online` (si applicable) prend au moins une seconde avant quoi `connection.type` vaut `UNKNOWN`. - -### Windows Phone 7 Quirks - -Lors de l'exécution dans l'émulateur, le `connection.status` est toujours inconnu, ainsi cet événement ne fait *pas* de feu. - -### Notes au sujet de Windows Phone 8 - -L'émulateur signale le type de connexion comme `Cellular` , qui ne change pas, aussi des événements ne fait *pas* de feu. diff --git a/plugins/cordova-plugin-network-information/doc/it/README.md b/plugins/cordova-plugin-network-information/doc/it/README.md deleted file mode 100644 index f434359..0000000 --- a/plugins/cordova-plugin-network-information/doc/it/README.md +++ /dev/null @@ -1,190 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di informazioni di rete](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Fornisce informazioni sul dispositivo cellulare e connessione wifi, e se il dispositivo dispone di una connessione internet. - -## Installazione - - cordova plugin add cordova-plugin-network-information - - -## Piattaforme supportate - - * Amazon fuoco OS - * Android - * BlackBerry 10 - * Browser - * iOS - * Windows Phone 7 e 8 - * Tizen - * Windows - * Firefox OS - -# Connessione - -> Il `connection` oggetto, esposto tramite `navigator.connection` , fornisce informazioni sulla connessione wifi e cellulare del dispositivo. - -## Proprietà - - * connection.type - -## Costanti - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## connection.type - -Questa proprietà offre un modo rapido per determinare stato della connessione di rete del dispositivo e il tipo di connessione. - -### Esempio rapido - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Cambiamento di API - -Fino a Cordova 2.3.0, il `Connection` oggetto era accessibile tramite `navigator.network.connection` , dopo che è stato cambiato in `navigator.connection` per abbinare la specifica W3C. È ancora disponibile nella sua posizione originale, ma è obsoleto e verrà rimosso alla fine. - -### iOS stranezze - - * iOS non è possibile rilevare il tipo di connessione di rete cellulare. - * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. - -### Stranezze di Windows Phone - - * Quando è in esecuzione nell'emulatore, rileva sempre `navigator.connection.type` come`Connection.UNKNOWN`. - - * Windows Phone non riesce a rilevare il tipo di connessione di rete cellulare. - - * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. - -### Stranezze di Windows - - * Quando è in esecuzione nell'emulatore Phone 8.1, sempre rileva `navigator.connection.type` come `Connection.ETHERNET`. - -### Tizen stranezze - - * Tizen può rilevare solo un WiFi o una connessione cellulare. - * `navigator.connection.type` è impostata su `Connection.CELL_2G` per tutti i dati cellulare. - -### Firefox OS stranezze - - * Sistema operativo Firefox non riesce a rilevare il tipo di connessione di rete cellulare. - * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. - -### Stranezze browser - - * Browser non è in grado di rilevare il tipo di connessione di rete. `navigator.connection.type` è sempre impostata su `Connection.UNKNOWN` quando si è online. - -# Eventi relativi alla rete - -## offline - -L'evento viene generato quando un'applicazione passa alla modalità offline, e il dispositivo non è connesso a Internet. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Dettagli - -Il `offline` evento viene generato quando un dispositivo precedentemente connesso perde una connessione di rete in modo che un'applicazione non è più possibile accedere a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene generato quando il valore di `connection.type` diventa`NONE`. - -Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. - -### Esempio rapido - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS stranezze - -Durante l'avvio iniziale, il primo evento offline (se applicabile) richiede almeno un secondo al fuoco. - -### Windows Phone 7 capricci - -Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. - -### Windows Phone 8 stranezze - -L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, così fa l'evento *non* fuoco. - -## online - -Questo evento viene generato quando un'applicazione va online, e il dispositivo diventa collegato a Internet. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Dettagli - -Il `online` evento viene generato quando un dispositivo precedentemente scollegato riceve una connessione di rete per consentire un'accesso di applicazione a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene attivato quando il `connection.type` cambia da `NONE` a qualsiasi altro valore. - -Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. - -### Esempio rapido - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS stranezze - -Durante l'avvio iniziale, il primo `online` evento (se applicabile) richiede almeno un secondo al fuoco, prima che `connection.type` è`UNKNOWN`. - -### Windows Phone 7 capricci - -Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. - -### Windows Phone 8 stranezze - -L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, quindi, non gli eventi *non* a fuoco. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/it/index.md b/plugins/cordova-plugin-network-information/doc/it/index.md deleted file mode 100644 index e191719..0000000 --- a/plugins/cordova-plugin-network-information/doc/it/index.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# cordova-plugin-network-information - -Questo plugin fornisce un'implementazione di una vecchia versione dell' [API di informazioni di rete][1]. Fornisce informazioni sul dispositivo cellulare e connessione wifi, e se il dispositivo dispone di una connessione internet. - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## Installazione - - cordova plugin add cordova-plugin-network-information - - -## Piattaforme supportate - -* Amazon fuoco OS -* Android -* BlackBerry 10 -* Browser -* iOS -* Windows Phone 7 e 8 -* Tizen -* Windows -* Firefox OS - -# Connessione - -> Il `connection` oggetto, esposto tramite `navigator.connection` , fornisce informazioni sulla connessione wifi e cellulare del dispositivo. - -## Proprietà - -* connection.type - -## Costanti - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## connection.type - -Questa proprietà offre un modo rapido per determinare stato della connessione di rete del dispositivo e il tipo di connessione. - -### Esempio rapido - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Cambiamento di API - -Fino a Cordova 2.3.0, il `Connection` oggetto era accessibile tramite `navigator.network.connection` , dopo che è stato cambiato in `navigator.connection` per abbinare la specifica W3C. È ancora disponibile nella sua posizione originale, ma è obsoleto e verrà rimosso alla fine. - -### iOS stranezze - -* iOS non è possibile rilevare il tipo di connessione di rete cellulare. - * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. - -### Stranezze di Windows Phone - -* Quando è in esecuzione nell'emulatore, rileva sempre `navigator.connection.type` come`Connection.UNKNOWN`. - -* Windows Phone non riesce a rilevare il tipo di connessione di rete cellulare. - - * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. - -### Stranezze di Windows - -* Quando è in esecuzione nell'emulatore Phone 8.1, sempre rileva `navigator.connection.type` come `Connection.ETHERNET`. - -### Tizen stranezze - -* Tizen può rilevare solo un WiFi o una connessione cellulare. - * `navigator.connection.type` è impostata su `Connection.CELL_2G` per tutti i dati cellulare. - -### Firefox OS stranezze - -* Sistema operativo Firefox non riesce a rilevare il tipo di connessione di rete cellulare. - * `navigator.connection.type`è impostata su `Connection.CELL` per tutti i dati cellulare. - -# Eventi relativi alla rete - -## offline - -L'evento viene generato quando un'applicazione passa alla modalità offline, e il dispositivo non è connesso a Internet. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Dettagli - -Il `offline` evento viene generato quando un dispositivo precedentemente connesso perde una connessione di rete in modo che un'applicazione non è più possibile accedere a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene generato quando il valore di `connection.type` diventa`NONE`. - -Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. - -### Esempio rapido - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS stranezze - -Durante l'avvio iniziale, il primo evento offline (se applicabile) richiede almeno un secondo al fuoco. - -### Windows Phone 7 capricci - -Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. - -### Windows Phone 8 stranezze - -L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, così fa l'evento *non* fuoco. - -## online - -Questo evento viene generato quando un'applicazione va online, e il dispositivo diventa collegato a Internet. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Dettagli - -Il `online` evento viene generato quando un dispositivo precedentemente scollegato riceve una connessione di rete per consentire un'accesso di applicazione a Internet. Esso si basa sulle stesse informazioni come l'API di connessione e viene attivato quando il `connection.type` cambia da `NONE` a qualsiasi altro valore. - -Applicazioni in genere è necessario utilizzare `document.addEventListener` per fissare un listener di eventi una volta il `deviceready` evento incendi. - -### Esempio rapido - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS stranezze - -Durante l'avvio iniziale, il primo `online` evento (se applicabile) richiede almeno un secondo al fuoco, prima che `connection.type` è`UNKNOWN`. - -### Windows Phone 7 capricci - -Quando è in esecuzione nell'emulatore, il `connection.status` è sempre sconosciuto, così fa di questo evento *non* fuoco. - -### Windows Phone 8 stranezze - -L'emulatore riporta il tipo di connessione come `Cellular` , che non cambia, quindi, non gli eventi *non* a fuoco. diff --git a/plugins/cordova-plugin-network-information/doc/ja/README.md b/plugins/cordova-plugin-network-information/doc/ja/README.md deleted file mode 100644 index 797b741..0000000 --- a/plugins/cordova-plugin-network-information/doc/ja/README.md +++ /dev/null @@ -1,190 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -このプラグインは、古いバージョンの[ネットワーク情報 API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)の実装を提供します。 デバイスの携帯電話や wifi 接続に関する情報を提供し、かどうか、デバイスがインターネットに接続します。 - -## インストール - - cordova plugin add cordova-plugin-network-information - - -## サポートされているプラットフォーム - - * アマゾン火 OS - * アンドロイド - * ブラックベリー 10 - * ブラウザー - * iOS - * Windows Phone 7 と 8 - * Tizen - * Windows - * Firefox の OS - -# Connection - -> `connection`オブジェクトによって公開されて `navigator.connection` 、デバイスの携帯電話や wifi 接続に関する情報を提供します。 - -## プロパティ - - * connection.type - -## 定数 - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## connection.type - -このプロパティはデバイスのネットワーク接続状態を確認する速い方法を提供し、接続の種類。 - -### 簡単な例 - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API の変更 - -コルドバ 2.3.0、まで、 `Connection` 経由でアクセスされたオブジェクトが `navigator.network.connection` 、それに変更されましたが後 `navigator.connection` W3C の仕様に一致します。 それはまだ元の場所は廃止され、最終的に削除されます。 - -### iOS の癖 - - * iOS は、携帯電話のネットワーク接続の種類を検出できません。 - * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 - -### Windows Phone の癖 - - * エミュレーターで実行しているときを常に検出 `navigator.connection.type` として`Connection.UNKNOWN`. - - * Windows Phone 携帯電話ネットワーク接続の種類を検出できません。 - - * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 - -### Windows の癖 - - * 電話 8.1 エミュレーターで実行する場合は、常に `Connection.ETHERNET` として `navigator.connection.type` を検出します. - -### Tizen の癖 - - * Tizen には、WiFi または携帯電話の接続だけを検出できます。 - * `navigator.connection.type` は、すべての携帯電話のデータを `Connection.CELL_2G` に設定されます。 - -### Firefox OS 癖 - - * Firefox の OS は、携帯電話のネットワーク接続の種類を検出できません。 - * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 - -### ブラウザーの癖 - - * ブラウザーは、ネットワーク接続の種類を検出できません。 `navigator.connection.type`は、 `Connection.UNKNOWN`オンライン時に常に設定されます。 - -# ネットワーク関連のイベント - -## offline - -アプリケーションがオフラインになり、デバイスがインターネットに接続されていないときに発生します。 - - document.addEventListener("offline", yourCallbackFunction, false); - - -### 詳細 - -`offline`アプリケーションはもはや、インターネットにアクセスできるように、以前接続されたデバイスは、ネットワーク接続が失われたときに発生します。 接続 API と同じ情報に依存しており、火災時の値 `connection.type` になります。`NONE`. - -通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 - -### 簡単な例 - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS の癖 - -初回起動時 (当てはまる場合) の最初のオフライン イベントは火に 1 秒以上かかります。 - -### Windows Phone 7 の癖 - -エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 - -### Windows Phone 8 癖 - -エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 - -## online - -アプリケーションは、オンラインになるし、デバイスがインターネットに接続するときに発生します。 - - document.addEventListener("online", yourCallbackFunction, false); - - -### 詳細 - -`online`以前接続されていないデバイスが、インターネットへのアプリケーション アクセスを許可するネットワーク接続を受信するときに発生します。 接続 API と同じ情報に依存しており、場合に適用されます、 `connection.type` から変更 `NONE` 以外の値にします。 - -通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 - -### 簡単な例 - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS の癖 - -初回起動時には、最初の `online` (当てはまる場合) イベントが少なくとも火を前に第 2 `connection.type` は`UNKNOWN`. - -### Windows Phone 7 の癖 - -エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 - -### Windows Phone 8 癖 - -エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/ja/index.md b/plugins/cordova-plugin-network-information/doc/ja/index.md deleted file mode 100644 index 71b6f82..0000000 --- a/plugins/cordova-plugin-network-information/doc/ja/index.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# cordova-plugin-network-information - -このプラグインは、古いバージョンの[ネットワーク情報 API][1]の実装を提供します。 デバイスの携帯電話や wifi 接続に関する情報を提供し、かどうか、デバイスがインターネットに接続します。 - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## インストール - - cordova plugin add cordova-plugin-network-information - - -## サポートされているプラットフォーム - -* アマゾン火 OS -* アンドロイド -* ブラックベリー 10 -* ブラウザー -* iOS -* Windows Phone 7 と 8 -* Tizen -* Windows -* Firefox の OS - -# Connection - -> `connection`オブジェクトによって公開されて `navigator.connection` 、デバイスの携帯電話や wifi 接続に関する情報を提供します。 - -## プロパティ - -* connection.type - -## 定数 - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## connection.type - -このプロパティはデバイスのネットワーク接続状態を確認する速い方法を提供し、接続の種類。 - -### 簡単な例 - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API の変更 - -コルドバ 2.3.0、まで、 `Connection` 経由でアクセスされたオブジェクトが `navigator.network.connection` 、それに変更されましたが後 `navigator.connection` W3C の仕様に一致します。 それはまだ元の場所は廃止され、最終的に削除されます。 - -### iOS の癖 - -* iOS は、携帯電話のネットワーク接続の種類を検出できません。 - * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 - -### Windows Phone の癖 - -* エミュレーターで実行しているときを常に検出 `navigator.connection.type` として`Connection.UNKNOWN`. - -* Windows Phone 携帯電話ネットワーク接続の種類を検出できません。 - - * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 - -### Windows の癖 - -* 電話 8.1 エミュレーターで実行する場合は、常に `Connection.ETHERNET` として `navigator.connection.type` を検出します. - -### Tizen の癖 - -* Tizen には、WiFi または携帯電話の接続だけを検出できます。 - * `navigator.connection.type` は、すべての携帯電話のデータを `Connection.CELL_2G` に設定されます。 - -### Firefox OS 癖 - -* Firefox の OS は、携帯電話のネットワーク接続の種類を検出できません。 - * `navigator.connection.type`設定する `Connection.CELL` すべての携帯電話データの。 - -# ネットワーク関連のイベント - -## offline - -アプリケーションがオフラインになり、デバイスがインターネットに接続されていないときに発生します。 - - document.addEventListener("offline", yourCallbackFunction, false); - - -### 詳細 - -`offline`アプリケーションはもはや、インターネットにアクセスできるように、以前接続されたデバイスは、ネットワーク接続が失われたときに発生します。 接続 API と同じ情報に依存しており、火災時の値 `connection.type` になります。`NONE`. - -通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 - -### 簡単な例 - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS の癖 - -初回起動時 (当てはまる場合) の最初のオフライン イベントは火に 1 秒以上かかります。 - -### Windows Phone 7 の癖 - -エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 - -### Windows Phone 8 癖 - -エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 - -## online - -アプリケーションは、オンラインになるし、デバイスがインターネットに接続するときに発生します。 - - document.addEventListener("online", yourCallbackFunction, false); - - -### 詳細 - -`online`以前接続されていないデバイスが、インターネットへのアプリケーション アクセスを許可するネットワーク接続を受信するときに発生します。 接続 API と同じ情報に依存しており、場合に適用されます、 `connection.type` から変更 `NONE` 以外の値にします。 - -通常アプリケーションに使用する必要があります `document.addEventListener` 一度のイベント リスナーをアタッチし、 `deviceready` イベントが発生します。 - -### 簡単な例 - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS の癖 - -初回起動時には、最初の `online` (当てはまる場合) イベントが少なくとも火を前に第 2 `connection.type` は`UNKNOWN`. - -### Windows Phone 7 の癖 - -エミュレーターで実行しているとき、 `connection.status` は常に知られている、このイベントは*ない*火。 - -### Windows Phone 8 癖 - -エミュレーターと接続の種類のレポート `Cellular` は変化しません、イベントは*ない*火。 diff --git a/plugins/cordova-plugin-network-information/doc/ko/README.md b/plugins/cordova-plugin-network-information/doc/ko/README.md deleted file mode 100644 index a667539..0000000 --- a/plugins/cordova-plugin-network-information/doc/ko/README.md +++ /dev/null @@ -1,190 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -이 플러그인 [네트워크 정보 API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)의 이전 버전에 대 한 구현을 제공합니다. 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다 장치는 인터넷 연결에 있는지 여부. - -## 설치 - - cordova plugin add cordova-plugin-network-information - - -## 지원 되는 플랫폼 - - * 아마존 화재 운영 체제 - * 안 드 로이드 - * 블랙베리 10 - * 브라우저 - * iOS - * Windows Phone 7과 8 - * Tizen - * 윈도우 - * Firefox 운영 체제 - -# 연결 - -> `connection`개체를 통해 노출 `navigator.connection` , 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다. - -## 속성 - - * connection.type - -## 상수 - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## connection.type - -이 디바이스의 네트워크 연결 상태를 확인 하는 빠른 방법을 제공 합니다 및 연결의 종류. - -### 빠른 예제 - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API 변경 - -코르 도우 바 2.3.0까지 `Connection` 개체를 통해 액세스 했습니다 `navigator.network.connection` , 후에 변경 된 `navigator.connection` W3C 사양에 맞게. 그것은 그것의 원래 위치에 계속 사용할 수 하지만 사용 되지 않습니다 및 결국 제거 될 것 이다. - -### iOS 단점 - - * iOS는 셀룰러 네트워크 연결의 종류를 감지할 수 없습니다. - * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. - -### Windows Phone 단점 - - * 에뮬레이터에서 실행할 때 항상 검색 `navigator.connection.type` 으로`Connection.UNKNOWN`. - - * Windows Phone 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. - - * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. - -### 윈도우 특수 - - * 전화 8.1 에뮬레이터에서 실행 하는 경우 항상 `Connection.ETHERNET`로 `navigator.connection.type`를 감지합니다. - -### Tizen 특수 - - * Tizen은 와이파이 또는 휴대 전화 연결에만 검색할 수 있습니다. - * `navigator.connection.type`는 모든 셀룰러 데이터에 대 한 `Connection.CELL_2G`로 설정 됩니다. - -### 파이어 폭스 OS 단점 - - * 파이어 폭스 OS 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. - * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. - -### 브라우저 만지면 - - * 브라우저는 네트워크 연결의 종류를 검색할 수 없습니다. `navigator.connection.type` `Connection.UNKNOWN` 때 온라인으로 항상 설정 됩니다. - -# 네트워크 관련 이벤트 - -## offline - -이벤트가 발생 하면 응용 프로그램 오프 라인, 이동 및 장치가 인터넷에 연결 되어 있지. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### 세부 정보 - -`offline`이벤트가 발생 하면 응용 프로그램이 더 이상 인터넷에 액세스할 수 있도록 이전 연결 된 장치가 네트워크 연결 손실. 그것은 연결 API와 동일한 정보에 의존 하 고 경우의 값 `connection.type` 된다`NONE`. - -일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. - -### 빠른 예제 - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS 단점 - -처음 시작 하는 동안 첫 번째 오프 라인 이벤트 (있는 경우)를 적어도 초를 걸립니다. - -### Windows Phone 7 단점 - -에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. - -### Windows Phone 8 단점 - -에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. - -## online - -응용 프로그램은 온라인 및 장치가 인터넷에 연결 된다 때이 이벤트가 발생 합니다. - - document.addEventListener("online", yourCallbackFunction, false); - - -### 세부 정보 - -`online`이전 연결 되지 않은 장치는 인터넷에 대 한 응용 프로그램 액세스를 허용 하도록 네트워크 연결을 받을 때 이벤트가 발생 합니다. 그것은 연결 API와 동일한 정보에 의존 하 고 경우에 `connection.type` 에서 변경 `NONE` 다른 값으로. - -일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. - -### 빠른 예제 - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS 단점 - -처음 시작 하는 동안 첫 번째 `online` 이벤트 (있는 경우) 이전에 불 초 걸립니다 이상 `connection.type` 입니다`UNKNOWN`. - -### Windows Phone 7 단점 - -에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. - -### Windows Phone 8 단점 - -에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/ko/index.md b/plugins/cordova-plugin-network-information/doc/ko/index.md deleted file mode 100644 index cb4c727..0000000 --- a/plugins/cordova-plugin-network-information/doc/ko/index.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# cordova-plugin-network-information - -이 플러그인 [네트워크 정보 API][1]의 이전 버전에 대 한 구현을 제공합니다. 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다 장치는 인터넷 연결에 있는지 여부. - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## 설치 - - cordova plugin add cordova-plugin-network-information - - -## 지원 되는 플랫폼 - -* 아마존 화재 운영 체제 -* 안 드 로이드 -* 블랙베리 10 -* 브라우저 -* iOS -* Windows Phone 7과 8 -* Tizen -* 윈도우 -* Firefox 운영 체제 - -# 연결 - -> `connection`개체를 통해 노출 `navigator.connection` , 소자의 셀룰러와 와이파이 연결에 대 한 정보를 제공 합니다. - -## 속성 - -* connection.type - -## 상수 - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## connection.type - -이 디바이스의 네트워크 연결 상태를 확인 하는 빠른 방법을 제공 합니다 및 연결의 종류. - -### 빠른 예제 - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API 변경 - -코르 도우 바 2.3.0까지 `Connection` 개체를 통해 액세스 했습니다 `navigator.network.connection` , 후에 변경 된 `navigator.connection` W3C 사양에 맞게. 그것은 그것의 원래 위치에 계속 사용할 수 하지만 사용 되지 않습니다 및 결국 제거 될 것 이다. - -### iOS 단점 - -* iOS는 셀룰러 네트워크 연결의 종류를 감지할 수 없습니다. - * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. - -### Windows Phone 단점 - -* 에뮬레이터에서 실행할 때 항상 검색 `navigator.connection.type` 으로`Connection.UNKNOWN`. - -* Windows Phone 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. - - * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. - -### 윈도우 특수 - -* 전화 8.1 에뮬레이터에서 실행 하는 경우 항상 `Connection.ETHERNET`로 `navigator.connection.type`를 감지합니다. - -### Tizen 특수 - -* Tizen은 와이파이 또는 휴대 전화 연결에만 검색할 수 있습니다. - * `navigator.connection.type`는 모든 셀룰러 데이터에 대 한 `Connection.CELL_2G`로 설정 됩니다. - -### 파이어 폭스 OS 단점 - -* 파이어 폭스 OS 셀룰러 네트워크 연결 유형을 검색할 수 없습니다. - * `navigator.connection.type`로 설정 된 `Connection.CELL` 모든 셀룰러 데이터에 대 한. - -# 네트워크 관련 이벤트 - -## offline - -이벤트가 발생 하면 응용 프로그램 오프 라인, 이동 및 장치가 인터넷에 연결 되어 있지. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### 세부 정보 - -`offline`이벤트가 발생 하면 응용 프로그램이 더 이상 인터넷에 액세스할 수 있도록 이전 연결 된 장치가 네트워크 연결 손실. 그것은 연결 API와 동일한 정보에 의존 하 고 경우의 값 `connection.type` 된다`NONE`. - -일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. - -### 빠른 예제 - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS 단점 - -처음 시작 하는 동안 첫 번째 오프 라인 이벤트 (있는 경우)를 적어도 초를 걸립니다. - -### Windows Phone 7 단점 - -에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. - -### Windows Phone 8 단점 - -에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. - -## online - -응용 프로그램은 온라인 및 장치가 인터넷에 연결 된다 때이 이벤트가 발생 합니다. - - document.addEventListener("online", yourCallbackFunction, false); - - -### 세부 정보 - -`online`이전 연결 되지 않은 장치는 인터넷에 대 한 응용 프로그램 액세스를 허용 하도록 네트워크 연결을 받을 때 이벤트가 발생 합니다. 그것은 연결 API와 동일한 정보에 의존 하 고 경우에 `connection.type` 에서 변경 `NONE` 다른 값으로. - -일반적으로 응용 프로그램을 사용 해야 합니다 `document.addEventListener` 한번 이벤트 리스너를 연결 하는 `deviceready` 이벤트가 발생 합니다. - -### 빠른 예제 - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS 단점 - -처음 시작 하는 동안 첫 번째 `online` 이벤트 (있는 경우) 이전에 불 초 걸립니다 이상 `connection.type` 입니다`UNKNOWN`. - -### Windows Phone 7 단점 - -에뮬레이터에서 실행 하는 경우는 `connection.status` 항상 불명 하다, 그래서이 이벤트는 *없는* 불. - -### Windows Phone 8 단점 - -에뮬레이터도 연결 형식을 보고 `Cellular` 는 변경 되지 않습니다, 그래서 이벤트 않습니다 *하지* 불. diff --git a/plugins/cordova-plugin-network-information/doc/pl/README.md b/plugins/cordova-plugin-network-information/doc/pl/README.md deleted file mode 100644 index 4b66cbb..0000000 --- a/plugins/cordova-plugin-network-information/doc/pl/README.md +++ /dev/null @@ -1,190 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -Wtyczka stanowi implementację starą wersję [API informacji w sieci](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/). Udostępnia informacje na temat urządzenia komórkowe i wifi połączenie, i czy urządzenie ma połączenie z Internetem. - -## Instalacja - - cordova plugin add cordova-plugin-network-information - - -## Obsługiwane platformy - - * Amazon Fire OS - * Android - * BlackBerry 10 - * Przeglądarka - * iOS - * Windows Phone 7 i 8 - * Tizen - * Windows - * Firefox OS - -# Połączenie - -> `connection`Obiektu, wystawiony przez `navigator.connection` , zawiera informacje o połączeniu urządzenia komórkowe i wifi. - -## Właściwości - - * Connection.Type - -## Stałe - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## Connection.Type - -Oferuje szybki sposób ustalić stan połączenia sieciowego urządzenia i typ połączenia. - -### Szybki przykład - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Zmiana interfejsu API - -Do Cordova 2.3.0 `Connection` obiekt uzyskano za pośrednictwem `navigator.network.connection` , po którym został zmieniony na `navigator.connection` odpowiadać specyfikacji W3C. To jest nadal dostępne w jego oryginalnej lokalizacji, ale jest niezalecane i zostaną ostatecznie usunięte. - -### Dziwactwa iOS - - * iOS nie może wykryć typ połączenia w sieci komórkowej. - * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. - -### Windows Phone dziwactwa - - * Po uruchomieniu w emulatorze, zawsze wykrywa `navigator.connection.type` jako`Connection.UNKNOWN`. - - * Windows Phone nie może wykryć typ połączenia w sieci komórkowej. - - * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. - -### Windows dziwactwa - - * Po uruchomieniu w emulatorze telefonu 8.1, zawsze wykrywa `navigator.connection.type` jako `Connection.ETHERNET`. - -### Dziwactwa Tizen - - * Tizen można tylko dostrzegać Wi-Fi lub połączenia komórkowe. - * `Navigator.Connection.Type` jest zestaw do `Connection.CELL_2G` dla wszystkich komórek danych. - -### Firefox OS dziwactwa - - * Firefox OS nie można wykryć typ połączenia w sieci komórkowej. - * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. - -### Quirks przeglądarki - - * Przeglądarka nie może wykryć typ połączenia sieciowego. `Navigator.Connection.Type` jest zawsze zestaw do `Connection.UNKNOWN` podczas online. - -# Zdarzenia związane z sieci - -## offline - -Zdarzenie odpala gdy aplikacja przejdzie do trybu offline, a urządzenie nie jest podłączone do Internetu. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Szczegóły - -`offline`Zdarzenie fires po wcześniej podłączone urządzenie traci połączenia z siecią, dzięki czemu aplikacja może już dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam wartość `connection.type` staje się`NONE`. - -Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. - -### Szybki przykład - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### Dziwactwa iOS - -Podczas uruchamiania systemu pierwsza impreza offline (jeśli dotyczy) trwa co najmniej drugi ognia. - -### Dziwactwa Windows Phone 7 - -Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. - -### Windows Phone 8 dziwactwa - -Emulator raporty typ połączenia, jako `Cellular` , co nie zmienia, więc zdarzenie *nie* ogień. - -## online - -Wydarzenie to odpala gdy aplikacja przechodzi w tryb online i urządzenie staje się połączenie z Internetem. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Szczegóły - -`online`Zdarzenie odpala gdy wcześniej niezwiązane urządzenie odbiera połączenie sieciowe, aby umożliwić aplikacji dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam `connection.type` zmienia się z `NONE` na inną wartość. - -Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. - -### Szybki przykład - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### Dziwactwa iOS - -Podczas uruchamiania systemu pierwszy `online` zdarzenia (w stosownych przypadkach) zajmuje co najmniej drugie ognia, przed którym `connection.type` jest`UNKNOWN`. - -### Dziwactwa Windows Phone 7 - -Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. - -### Windows Phone 8 dziwactwa - -Emulator sprawozdania jako typ połączenia `Cellular` , które nie zmienia, więc wydarzenia czy *nie* ogień. \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/pl/index.md b/plugins/cordova-plugin-network-information/doc/pl/index.md deleted file mode 100644 index a42b973..0000000 --- a/plugins/cordova-plugin-network-information/doc/pl/index.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# cordova-plugin-network-information - -Wtyczka stanowi implementację starą wersję [API informacji w sieci][1]. Udostępnia informacje na temat urządzenia komórkowe i wifi połączenie, i czy urządzenie ma połączenie z Internetem. - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## Instalacja - - cordova plugin add cordova-plugin-network-information - - -## Obsługiwane platformy - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Przeglądarka -* iOS -* Windows Phone 7 i 8 -* Tizen -* Windows -* Firefox OS - -# Połączenie - -> `connection`Obiektu, wystawiony przez `navigator.connection` , zawiera informacje o połączeniu urządzenia komórkowe i wifi. - -## Właściwości - -* Connection.Type - -## Stałe - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## Connection.Type - -Oferuje szybki sposób ustalić stan połączenia sieciowego urządzenia i typ połączenia. - -### Szybki przykład - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Zmiana interfejsu API - -Do Cordova 2.3.0 `Connection` obiekt uzyskano za pośrednictwem `navigator.network.connection` , po którym został zmieniony na `navigator.connection` odpowiadać specyfikacji W3C. To jest nadal dostępne w jego oryginalnej lokalizacji, ale jest niezalecane i zostaną ostatecznie usunięte. - -### Dziwactwa iOS - -* iOS nie może wykryć typ połączenia w sieci komórkowej. - * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. - -### Windows Phone dziwactwa - -* Po uruchomieniu w emulatorze, zawsze wykrywa `navigator.connection.type` jako`Connection.UNKNOWN`. - -* Windows Phone nie może wykryć typ połączenia w sieci komórkowej. - - * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. - -### Windows dziwactwa - -* Po uruchomieniu w emulatorze telefonu 8.1, zawsze wykrywa `navigator.connection.type` jako `Connection.ETHERNET`. - -### Dziwactwa Tizen - -* Tizen można tylko dostrzegać Wi-Fi lub połączenia komórkowe. - * `Navigator.Connection.Type` jest zestaw do `Connection.CELL_2G` dla wszystkich komórek danych. - -### Firefox OS dziwactwa - -* Firefox OS nie można wykryć typ połączenia w sieci komórkowej. - * `navigator.connection.type`jest zestaw `Connection.CELL` dla wszystkich komórek danych. - -# Zdarzenia związane z sieci - -## offline - -Zdarzenie odpala gdy aplikacja przejdzie do trybu offline, a urządzenie nie jest podłączone do Internetu. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Szczegóły - -`offline`Zdarzenie fires po wcześniej podłączone urządzenie traci połączenia z siecią, dzięki czemu aplikacja może już dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam wartość `connection.type` staje się`NONE`. - -Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. - -### Szybki przykład - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### Dziwactwa iOS - -Podczas uruchamiania systemu pierwsza impreza offline (jeśli dotyczy) trwa co najmniej drugi ognia. - -### Dziwactwa Windows Phone 7 - -Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. - -### Windows Phone 8 dziwactwa - -Emulator raporty typ połączenia, jako `Cellular` , co nie zmienia, więc zdarzenie *nie* ogień. - -## online - -Wydarzenie to odpala gdy aplikacja przechodzi w tryb online i urządzenie staje się połączenie z Internetem. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Szczegóły - -`online`Zdarzenie odpala gdy wcześniej niezwiązane urządzenie odbiera połączenie sieciowe, aby umożliwić aplikacji dostęp do Internetu. Opiera się na te same informacje połączenia API i gdy odpalam `connection.type` zmienia się z `NONE` na inną wartość. - -Aplikacje zwykle należy użyć `document.addEventListener` Aby dołączyć słuchacza raz `deviceready` pożary zdarzenia. - -### Szybki przykład - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### Dziwactwa iOS - -Podczas uruchamiania systemu pierwszy `online` zdarzenia (w stosownych przypadkach) zajmuje co najmniej drugie ognia, przed którym `connection.type` jest`UNKNOWN`. - -### Dziwactwa Windows Phone 7 - -Po uruchomieniu w emulatorze, `connection.status` zawsze jest nieznana, więc to wydarzenie *nie* ogień. - -### Windows Phone 8 dziwactwa - -Emulator sprawozdania jako typ połączenia `Cellular` , które nie zmienia, więc wydarzenia czy *nie* ogień. diff --git a/plugins/cordova-plugin-network-information/doc/ru/index.md b/plugins/cordova-plugin-network-information/doc/ru/index.md deleted file mode 100644 index 481c1b1..0000000 --- a/plugins/cordova-plugin-network-information/doc/ru/index.md +++ /dev/null @@ -1,182 +0,0 @@ - - -# cordova-plugin-network-information - -Этот плагин обеспечивает реализацию старой версии [API Сетевой информации][1]. Он предоставляет информацию о сотовых и Wi-Fi подключениях устройства, и информацию имеет ли устройство подключение к Интернету. - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## Установка - - cordova plugin add cordova-plugin-network-information - - -## Поддерживаемые платформы - -* Amazon Fire OS -* Android -* BlackBerry 10 -* Браузер -* iOS -* Windows Phone 7 и 8 -* Tizen -* Windows 8 -* Firefox OS - -# Connection - -> Объект `connection`, доступный через `navigator.connection`, предоставляет информацию о сотовых и wifi подключениях устройства. - -## Свойства - -* connection.type - -## Константы - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## connection.type - -Это свойство предоставляет быстрый способ для определения состояния подключения устройства к сети и тип этого подключения. - -### Краткий пример - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### Изменения в API - -До Cordova 2.3.0 объект `Connection` был доступен через `navigator.network.connection`, после чего это свойство было изменено на `navigator.connection` в соответствии со спецификацией консорциума W3C. Он все еще доступен в его исходном расположении, но это расположение является устаревшим и в конечном итоге будет удалено. - -### Особенности iOS - -* iOS не может определить тип подключения к сотовой сети. - * `navigator.connection.type` имеет значение `Connection.CELL` для всех сотовых данных. - -### Особенности Windows Phone - -* Когда работает в эмуляторе, тип подключения всегда определяется `navigator.connection.type` как `Connection.UNKNOWN`. - -* Windows Phone не может определить тип подключения к сотовой сети. - - * `navigator.connection.type` имеет значение `Connection.CELL` для всех сотовых данных. - -### Особенности Tizen - -* Tizen может обнаружить только соединения Wi-Fi или наличие сотовой связи. - * `navigator.connection.type` имеет значение `Connection.CELL_2G` для всех сотовых данных. - -### Особенности Firefox OS - -* Firefox OS не может определить тип подключения к сотовой сети. - * `navigator.connection.type` имеет значение `Connection.CELL` для всех сотовых данных. - -# События, связанные с сетью - -## offline - -Событие возникает, когда приложение переходит в автономный режим, и устройство не подключено к сети Интернет. - - document.addEventListener("offline", yourCallbackFunction, false); - - -### Подробности - -Событие `offline` возникает, когда ранее подключенное устройство теряет подключение к сети, так что приложение больше не может получить доступ к Интернет. Он опирается на ту же информацию, что и Connection API и срабатывает, когда значение `connection.type` становится равным `NONE`. - -Приложения обычно должно использовать `window.addEventListener` чтобы добавить обработчик события после того как произойдет событие `deviceready`. - -### Краткий пример - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### Особенности iOS - -Во время первоначального запуска первому событию offline (если применимо) требуется по крайней мере секунду на срабатывание. - -### Особенности Windows Phone 7 - -Когда работает в эмуляторе, `connection.status` всегда неизвестен, так что это событие *не* срабатывает. - -### Особенности Windows Phone 8 - -Эмулятор сообщает тип подключения как `Cellular` , которое не меняется, поэтому событие не *не* срабатывает. - -## online - -Это событие возникает, когда приложение выходит в онлайн, и устройство подключается к Интернету. - - document.addEventListener("online", yourCallbackFunction, false); - - -### Подробности - -Событие `online` возникает, когда ранее не подключенное к сети устройство получает сетевое подключение, разрешающее приложению доступ к Интернету. Оно опирается на ту же информацию, Connection API и вызывается когда `connection.type` меняется с `NONE` в любое другое значение. - -Приложения обычно должны использовать `window.addEventListener` чтобы добавить обработчик события после того как произойдет событие `deviceready`. - -### Краткий пример - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### Особенности iOS - -Во время первоначального запуска первое событие `online` (если применимо) занимает по меньшей мере секунду на срабатывание, до этого момента `connection.type` является равным `UNKNOWN`. - -### Особенности Windows Phone 7 - -Когда работает в эмуляторе, `connection.status` всегда неизвестен, так что это событие *не* срабатывает. - -### Особенности Windows Phone 8 - -Эмулятор сообщает тип подключения как `Cellular` , которое не меняется, поэтому событие не *не* срабатывает. diff --git a/plugins/cordova-plugin-network-information/doc/zh/README.md b/plugins/cordova-plugin-network-information/doc/zh/README.md deleted file mode 100644 index 09e11e7..0000000 --- a/plugins/cordova-plugin-network-information/doc/zh/README.md +++ /dev/null @@ -1,190 +0,0 @@ - - -# cordova-plugin-network-information - -[![Build Status](https://travis-ci.org/apache/cordova-plugin-network-information.svg)](https://travis-ci.org/apache/cordova-plugin-network-information) - -這個外掛程式提供的舊版本的[網路資訊 API](http://www.w3.org/TR/2011/WD-netinfo-api-20110607/)實現的。 它提供了有關該設備的行動電話和無線網路連接的資訊和設備是否已連接到 internet。 - -## 安裝 - - cordova plugin add cordova-plugin-network-information - - -## 支援的平臺 - - * 亞馬遜火 OS - * Android 系統 - * 黑莓 10 - * 瀏覽器 - * iOS - * Windows Phone 7 和 8 - * Tizen - * Windows - * 火狐瀏覽器作業系統 - -# 連接 - -> `connection`物件,通過公開 `navigator.connection` ,提供了有關該設備的行動電話和無線網路連接的資訊。 - -## 屬性 - - * connection.type - -## 常量 - - * Connection.UNKNOWN - * Connection.ETHERNET - * Connection.WIFI - * Connection.CELL_2G - * Connection.CELL_3G - * Connection.CELL_4G - * Connection.CELL - * Connection.NONE - -## connection.type - -此屬性提供快速的方法來確定設備的網路連接狀態,和連線類型。 - -### 快速的示例 - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API 更改 - -科爾多瓦 2.3.0,直到 `Connection` 物件的訪問通過 `navigator.network.connection` 後才改為其中, `navigator.connection` 以匹配的 W3C 規範。 它在其原始位置,是仍然可用,但已廢棄,最終將被刪除。 - -### iOS 的怪癖 - - * iOS 無法檢測到蜂窩網路連接的類型。 - * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 - -### Windows Phone 怪癖 - - * 當運行在模擬器中,總能檢測到 `navigator.connection.type` 作為`Connection.UNKNOWN`. - - * Windows Phone 不能檢測的蜂窩網路連接的類型。 - - * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 - -### Windows 的怪癖 - - * 當電話 8.1 在模擬器中運行,總能檢測到 `navigator.connection.type` 作為 `Connection.ETHERNET`. - -### Tizen 怪癖 - - * 泰只能檢測一個 WiFi 或細胞連接。 - * `navigator.connection.type` 是所有蜂窩資料設置為 `Connection.CELL_2G`。 - -### 火狐瀏覽器作業系統的怪癖 - - * 火狐瀏覽器作業系統無法檢測到蜂窩網路連接的類型。 - * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 - -### 瀏覽器的怪癖 - - * 瀏覽器無法檢測到網路連接的類型。 `navigator.connection.type`總是被設置為`Connection.UNKNOWN`時線上。 - -# 與網路相關的事件 - -## offline - -當一個應用程式離線時,與該設備未連接到互聯網時,將觸發該事件。 - - document.addEventListener("offline", yourCallbackFunction, false); - - -### 詳細資訊 - -`offline`以前連接的設備失去網路連接,這樣,應用程式不再可以訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊和火災時的值 `connection.type` 變得`NONE`. - -應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 - -### 快速的示例 - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS 的怪癖 - -在初始啟動期間,第一次離線事件 (如果適用) 需至少一秒的火。 - -### Windows Phone 7 的怪癖 - -當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 - -### Windows Phone 8 怪癖 - -模擬程式報告連線類型為 `Cellular` ,而不會更改,所以該事件不會*不*火。 - -## online - -當應用程式進入線上狀態,和該設備將成為連接到互聯網時觸發此事件。 - - document.addEventListener("online", yourCallbackFunction, false); - - -### 詳細資訊 - -`online`當先前連接的行動裝置接收到一個網路連接以允許應用程式訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊,則會激發 `connection.type` 從更改 `NONE` 為任何其他值。 - -應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 - -### 快速的示例 - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS 的怪癖 - -在初始啟動期間第一次 `online` 事件 (如果適用),至少需一秒的火災之前的, `connection.type` 是`UNKNOWN`. - -### Windows Phone 7 的怪癖 - -當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 - -### Windows Phone 8 怪癖 - -模擬程式報告連線類型為 `Cellular` ,而不會更改,所以事件不**火。 \ No newline at end of file diff --git a/plugins/cordova-plugin-network-information/doc/zh/index.md b/plugins/cordova-plugin-network-information/doc/zh/index.md deleted file mode 100644 index 2041467..0000000 --- a/plugins/cordova-plugin-network-information/doc/zh/index.md +++ /dev/null @@ -1,186 +0,0 @@ - - -# cordova-plugin-network-information - -這個外掛程式提供的舊版本的[網路資訊 API][1]實現的。 它提供了有關該設備的行動電話和無線網路連接的資訊和設備是否已連接到 internet。 - - [1]: http://www.w3.org/TR/2011/WD-netinfo-api-20110607/ - -## 安裝 - - cordova plugin add cordova-plugin-network-information - - -## 支援的平臺 - -* 亞馬遜火 OS -* Android 系統 -* 黑莓 10 -* 瀏覽器 -* iOS -* Windows Phone 7 和 8 -* 泰 -* Windows -* 火狐瀏覽器的作業系統 - -# 連接 - -> `connection`物件,通過公開 `navigator.connection` ,提供了有關該設備的行動電話和無線網路連接的資訊。 - -## 屬性 - -* connection.type - -## 常量 - -* Connection.UNKNOWN -* Connection.ETHERNET -* Connection.WIFI -* Connection.CELL_2G -* Connection.CELL_3G -* Connection.CELL_4G -* Connection.CELL -* Connection.NONE - -## connection.type - -此屬性提供快速的方法來確定設備的網路連接狀態,和連線類型。 - -### 快速的示例 - - function checkConnection() { - var networkState = navigator.connection.type; - - var states = {}; - states[Connection.UNKNOWN] = 'Unknown connection'; - states[Connection.ETHERNET] = 'Ethernet connection'; - states[Connection.WIFI] = 'WiFi connection'; - states[Connection.CELL_2G] = 'Cell 2G connection'; - states[Connection.CELL_3G] = 'Cell 3G connection'; - states[Connection.CELL_4G] = 'Cell 4G connection'; - states[Connection.CELL] = 'Cell generic connection'; - states[Connection.NONE] = 'No network connection'; - - alert('Connection type: ' + states[networkState]); - } - - checkConnection(); - - -### API 更改 - -科爾多瓦 2.3.0,直到 `Connection` 物件的訪問通過 `navigator.network.connection` 後才改為其中, `navigator.connection` 以匹配的 W3C 規範。 它在其原始位置,是仍然可用,但已廢棄,最終將被刪除。 - -### iOS 的怪癖 - -* iOS 無法檢測到蜂窩網路連接的類型。 - * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 - -### Windows Phone 怪癖 - -* 當運行在模擬器中,總能檢測到 `navigator.connection.type` 作為`Connection.UNKNOWN`. - -* Windows Phone 不能檢測的蜂窩網路連接的類型。 - - * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 - -### Windows 的怪癖 - -* 當電話 8.1 在模擬器中運行,總能檢測到 `navigator.connection.type` 作為 `Connection.ETHERNET`. - -### Tizen 怪癖 - -* 泰只能檢測一個 WiFi 或細胞連接。 - * `navigator.connection.type` 是所有蜂窩資料設置為 `Connection.CELL_2G`。 - -### 火狐瀏覽器作業系統的怪癖 - -* 火狐瀏覽器作業系統無法檢測到蜂窩網路連接的類型。 - * `navigator.connection.type`設置為 `Connection.CELL` 為所有蜂窩資料。 - -# 與網路相關的事件 - -## offline - -當一個應用程式離線時,與該設備未連接到互聯網時,將觸發該事件。 - - document.addEventListener("offline", yourCallbackFunction, false); - - -### 詳細資訊 - -`offline`以前連接的設備失去網路連接,這樣,應用程式不再可以訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊和火災時的值 `connection.type` 變得`NONE`. - -應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 - -### 快速的示例 - - document.addEventListener("offline", onOffline, false); - - function onOffline() { - // Handle the offline event - } - - -### iOS 的怪癖 - -在初始啟動期間,第一次離線事件 (如果適用) 需至少一秒的火。 - -### Windows Phone 7 的怪癖 - -當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 - -### Windows Phone 8 怪癖 - -模擬程式報告連線類型為 `Cellular` ,而不會更改,所以該事件不會*不*火。 - -## online - -當應用程式進入線上狀態,和該設備將成為連接到互聯網時觸發此事件。 - - document.addEventListener("online", yourCallbackFunction, false); - - -### 詳細資訊 - -`online`當先前連接的行動裝置接收到一個網路連接以允許應用程式訪問互聯網時激發的事件。 它依賴于連接 API,相同的資訊,則會激發 `connection.type` 從更改 `NONE` 為任何其他值。 - -應用程式通常應使用 `document.addEventListener` 將一個事件攔截器附加一次 `deviceready` 事件火災。 - -### 快速的示例 - - document.addEventListener("online", onOnline, false); - - function onOnline() { - // Handle the online event - } - - -### iOS 的怪癖 - -在初始啟動期間第一次 `online` 事件 (如果適用),至少需一秒的火災之前的, `connection.type` 是`UNKNOWN`. - -### Windows Phone 7 的怪癖 - -當運行在模擬器中, `connection.status` 始終是未知的因此此事件不會*不*火。 - -### Windows Phone 8 怪癖 - -模擬程式報告連線類型為 `Cellular` ,而不會更改,所以事件不**火。 diff --git a/plugins/cordova-plugin-network-information/package.json b/plugins/cordova-plugin-network-information/package.json deleted file mode 100644 index 8a0a886..0000000 --- a/plugins/cordova-plugin-network-information/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "cordova-plugin-network-information", - "version": "1.1.0", - "description": "Cordova Network Information Plugin", - "cordova": { - "id": "cordova-plugin-network-information", - "platforms": [ - "firefoxos", - "android", - "amazon-fireos", - "ubuntu", - "ios", - "blackberry10", - "wp7", - "wp8", - "windows8", - "windows", - "tizen", - "browser" - ] - }, - "repository": { - "type": "git", - "url": "https://github.com/apache/cordova-plugin-network-information" - }, - "keywords": [ - "cordova", - "network", - "information", - "ecosystem:cordova", - "cordova-firefoxos", - "cordova-android", - "cordova-amazon-fireos", - "cordova-ubuntu", - "cordova-ios", - "cordova-blackberry10", - "cordova-wp7", - "cordova-wp8", - "cordova-windows8", - "cordova-windows", - "cordova-tizen", - "cordova-browser" - ], - "author": "Apache Software Foundation", - "license": "Apache 2.0" -} diff --git a/plugins/cordova-plugin-network-information/plugin.xml b/plugins/cordova-plugin-network-information/plugin.xml deleted file mode 100644 index a017abd..0000000 --- a/plugins/cordova-plugin-network-information/plugin.xml +++ /dev/null @@ -1,173 +0,0 @@ - - - - - - Network Information - Cordova Network Information Plugin - Apache 2.0 - cordova,network,information - https://git-wip-us.apache.org/repos/asf/cordova-plugin-network-information.git - https://issues.apache.org/jira/browse/CB/component/12320640 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/plugins/cordova-plugin-network-information/src/android/NetworkManager.java b/plugins/cordova-plugin-network-information/src/android/NetworkManager.java deleted file mode 100644 index 0323f69..0000000 --- a/plugins/cordova-plugin-network-information/src/android/NetworkManager.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - 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. -*/ -package org.apache.cordova.networkinformation; - -import org.apache.cordova.CallbackContext; -import org.apache.cordova.CordovaInterface; -import org.apache.cordova.CordovaPlugin; -import org.apache.cordova.PluginResult; -import org.apache.cordova.CordovaWebView; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.net.ConnectivityManager; -import android.net.NetworkInfo; -import android.util.Log; - -import java.util.Locale; - -public class NetworkManager extends CordovaPlugin { - - public static int NOT_REACHABLE = 0; - public static int REACHABLE_VIA_CARRIER_DATA_NETWORK = 1; - public static int REACHABLE_VIA_WIFI_NETWORK = 2; - - public static final String WIFI = "wifi"; - public static final String WIMAX = "wimax"; - // mobile - public static final String MOBILE = "mobile"; - - // Android L calls this Cellular, because I have no idea! - public static final String CELLULAR = "cellular"; - // 2G network types - public static final String GSM = "gsm"; - public static final String GPRS = "gprs"; - public static final String EDGE = "edge"; - // 3G network types - public static final String CDMA = "cdma"; - public static final String UMTS = "umts"; - public static final String HSPA = "hspa"; - public static final String HSUPA = "hsupa"; - public static final String HSDPA = "hsdpa"; - public static final String ONEXRTT = "1xrtt"; - public static final String EHRPD = "ehrpd"; - // 4G network types - public static final String LTE = "lte"; - public static final String UMB = "umb"; - public static final String HSPA_PLUS = "hspa+"; - // return type - public static final String TYPE_UNKNOWN = "unknown"; - public static final String TYPE_ETHERNET = "ethernet"; - public static final String TYPE_WIFI = "wifi"; - public static final String TYPE_2G = "2g"; - public static final String TYPE_3G = "3g"; - public static final String TYPE_4G = "4g"; - public static final String TYPE_NONE = "none"; - - private static final String LOG_TAG = "NetworkManager"; - - private CallbackContext connectionCallbackContext; - - ConnectivityManager sockMan; - BroadcastReceiver receiver; - private JSONObject lastInfo = null; - - /** - * Sets the context of the Command. This can then be used to do things like - * get file paths associated with the Activity. - * - * @param cordova The context of the main Activity. - * @param webView The CordovaWebView Cordova is running in. - */ - public void initialize(CordovaInterface cordova, CordovaWebView webView) { - super.initialize(cordova, webView); - this.sockMan = (ConnectivityManager) cordova.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); - this.connectionCallbackContext = null; - - // We need to listen to connectivity events to update navigator.connection - IntentFilter intentFilter = new IntentFilter(); - intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); - if (this.receiver == null) { - this.receiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - // (The null check is for the ARM Emulator, please use Intel Emulator for better results) - if(NetworkManager.this.webView != null) - updateConnectionInfo(sockMan.getActiveNetworkInfo()); - } - }; - webView.getContext().registerReceiver(this.receiver, intentFilter); - } - - } - - /** - * Executes the request and returns PluginResult. - * - * @param action The action to execute. - * @param args JSONArry of arguments for the plugin. - * @param callbackContext The callback id used when calling back into JavaScript. - * @return True if the action was valid, false otherwise. - */ - public boolean execute(String action, JSONArray args, CallbackContext callbackContext) { - if (action.equals("getConnectionInfo")) { - this.connectionCallbackContext = callbackContext; - NetworkInfo info = sockMan.getActiveNetworkInfo(); - String connectionType = ""; - try { - connectionType = this.getConnectionInfo(info).get("type").toString(); - } catch (JSONException e) { } - - PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, connectionType); - pluginResult.setKeepCallback(true); - callbackContext.sendPluginResult(pluginResult); - return true; - } - return false; - } - - /** - * Stop network receiver. - */ - public void onDestroy() { - if (this.receiver != null) { - try { - webView.getContext().unregisterReceiver(this.receiver); - } catch (Exception e) { - Log.e(LOG_TAG, "Error unregistering network receiver: " + e.getMessage(), e); - } finally { - receiver = null; - } - } - } - - //-------------------------------------------------------------------------- - // LOCAL METHODS - //-------------------------------------------------------------------------- - - /** - * Updates the JavaScript side whenever the connection changes - * - * @param info the current active network info - * @return - */ - private void updateConnectionInfo(NetworkInfo info) { - // send update to javascript "navigator.network.connection" - // Jellybean sends its own info - JSONObject thisInfo = this.getConnectionInfo(info); - if(!thisInfo.equals(lastInfo)) - { - String connectionType = ""; - try { - connectionType = thisInfo.get("type").toString(); - } catch (JSONException e) { } - - sendUpdate(connectionType); - lastInfo = thisInfo; - } - } - - /** - * Get the latest network connection information - * - * @param info the current active network info - * @return a JSONObject that represents the network info - */ - private JSONObject getConnectionInfo(NetworkInfo info) { - String type = TYPE_NONE; - String extraInfo = ""; - if (info != null) { - // If we are not connected to any network set type to none - if (!info.isConnected()) { - type = TYPE_NONE; - } - else { - type = getType(info); - } - extraInfo = info.getExtraInfo(); - } - - Log.d("CordovaNetworkManager", "Connection Type: " + type); - Log.d("CordovaNetworkManager", "Connection Extra Info: " + extraInfo); - - JSONObject connectionInfo = new JSONObject(); - - try { - connectionInfo.put("type", type); - connectionInfo.put("extraInfo", extraInfo); - } catch (JSONException e) { } - - return connectionInfo; - } - - /** - * Create a new plugin result and send it back to JavaScript - * - * @param connection the network info to set as navigator.connection - */ - private void sendUpdate(String type) { - if (connectionCallbackContext != null) { - PluginResult result = new PluginResult(PluginResult.Status.OK, type); - result.setKeepCallback(true); - connectionCallbackContext.sendPluginResult(result); - } - webView.postMessage("networkconnection", type); - } - - /** - * Determine the type of connection - * - * @param info the network info so we can determine connection type. - * @return the type of mobile network we are on - */ - private String getType(NetworkInfo info) { - if (info != null) { - String type = info.getTypeName().toLowerCase(Locale.US); - - Log.d("CordovaNetworkManager", "toLower : " + type.toLowerCase()); - Log.d("CordovaNetworkManager", "wifi : " + WIFI); - if (type.equals(WIFI)) { - return TYPE_WIFI; - } - else if (type.toLowerCase().equals(TYPE_ETHERNET)) { - return TYPE_ETHERNET; - } - else if (type.equals(MOBILE) || type.equals(CELLULAR)) { - type = info.getSubtypeName(); - if (type.equals(GSM) || - type.equals(GPRS) || - type.equals(EDGE)) { - return TYPE_2G; - } - else if (type.startsWith(CDMA) || - type.equals(UMTS) || - type.equals(ONEXRTT) || - type.equals(EHRPD) || - type.equals(HSUPA) || - type.equals(HSDPA) || - type.equals(HSPA)) { - return TYPE_3G; - } - else if (type.equals(LTE) || - type.equals(UMB) || - type.equals(HSPA_PLUS)) { - return TYPE_4G; - } - } - } - else { - return TYPE_NONE; - } - return TYPE_UNKNOWN; - } -} diff --git a/plugins/cordova-plugin-network-information/src/blackberry10/index.js b/plugins/cordova-plugin-network-information/src/blackberry10/index.js deleted file mode 100644 index d47d840..0000000 --- a/plugins/cordova-plugin-network-information/src/blackberry10/index.js +++ /dev/null @@ -1,64 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - -//map from BB10 to cordova connection types: -//https://github.com/apache/cordova-js/blob/master/lib/common/plugin/Connection.js -function mapConnectionType(con) { - switch (con.type) { - case 'wired': - return 'ethernet'; - case 'wifi': - return 'wifi'; - case 'none': - return 'none'; - case 'cellular': - switch (con.technology) { - case 'edge': - case 'gsm': - return '2g'; - case 'evdo': - return '3g'; - case 'umts': - return '3g'; - case 'lte': - return '4g'; - } - return "cellular"; - } - return 'unknown'; -} - -function currentConnectionType() { - try { - //possible for webplatform to throw pps exception - return mapConnectionType(window.qnx.webplatform.device.activeConnection || { type : 'none' }); - } - catch (e) { - return 'unknown'; - } -} - -module.exports = { - getConnectionInfo: function (success, fail, args, env) { - var result = new PluginResult(args, env); - result.ok(currentConnectionType()); - } -}; diff --git a/plugins/cordova-plugin-network-information/src/browser/network.js b/plugins/cordova-plugin-network-information/src/browser/network.js deleted file mode 100644 index 5769dd9..0000000 --- a/plugins/cordova-plugin-network-information/src/browser/network.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - -/*global module, require*/ - -var cordova = require('cordova'), - proxy = require("cordova/exec/proxy"), - Connection = require('./Connection'); - -var type = navigator.onLine ? Connection.UNKNOWN : Connection.NONE; - -// Subscribe to 'native' online/offline events -function onStatusChange(evt) { - type = navigator.onLine ? Connection.UNKNOWN : Connection.NONE; - // force async - setTimeout(function(){ - cordova.fireDocumentEvent(evt.type); - },0); -} - -window.addEventListener('online', onStatusChange); -window.addEventListener('offline', onStatusChange); - -proxy.add("NetworkStatus", { - getConnectionInfo:function(cbSuccess) { - // force async - setTimeout(function(){ - cbSuccess(type); - },0); - } -}); - - diff --git a/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js b/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js deleted file mode 100644 index 40d6163..0000000 --- a/plugins/cordova-plugin-network-information/src/firefoxos/NetworkProxy.js +++ /dev/null @@ -1,97 +0,0 @@ -/* - * - * 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. - * - */ - -/* - Network API overview: http://www.w3.org/TR/netinfo-api/ - and http://w3c.github.io/netinfo/ -*/ - -var cordova = require('cordova'), - Connection = require('./Connection'), - modulemapper = require('cordova/modulemapper'); - -var origConnection = modulemapper.getOriginalSymbol(window, 'navigator.connection'); - -module.exports = { - - getConnectionInfo: function(successCallback, errorCallback) { - var connection = origConnection || navigator.mozConnection, - connectionType = Connection.UNKNOWN; - - if (!connection) { - setTimeout(function() { - successCallback(connectionType); - }, 0); - return; - } - - var bandwidth = connection.bandwidth, - metered = connection.metered, - type = connection.type; - - if (type != undefined) { - // For more information see: - // https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API - - switch(type) { - case "cellular": - connectionType = Connection.CELL; - break; - case "ethernet": - connectionType = Connection.ETHERNET; - break; - case "wifi": - connectionType = Connection.WIFI; - break; - case "none": - connectionType = Connection.NONE; - break; - } - } else if (bandwidth != undefined && metered != undefined) { - /* - bandwidth of type double, readonly - The user agent must set the value of the bandwidth attribute to: - 0 if the user is currently offline; - Infinity if the bandwidth is unknown; - an estimation of the current bandwidth in MB/s (Megabytes per seconds) - available for communication with the browsing context active document's - domain. - - For more information see: - https://developer.mozilla.org/en-US/docs/Web/API/Connection - */ - - if (bandwidth === 0) { - connectionType = Connection.NONE; - } else if (metered && isFinite(bandwidth)) { - connectionType = Connection.CELL; - } else if (!metered && isFinite(bandwidth)) { - connectionType = Connection.WIFI; - } - } - - setTimeout(function() { - successCallback(connectionType); - }, 0); - } -}; - -require("cordova/exec/proxy").add("NetworkStatus", module.exports); diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h b/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h deleted file mode 100644 index 8add027..0000000 --- a/plugins/cordova-plugin-network-information/src/ios/CDVConnection.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - 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. - */ - -#import -#import -#import "CDVReachability.h" - -@interface CDVConnection : CDVPlugin { - NSString* type; - NSString* _callbackId; - - CDVReachability* internetReach; -} - -@property (copy) NSString* connectionType; -@property (strong) CDVReachability* internetReach; - -@end diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m b/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m deleted file mode 100644 index 223dd7c..0000000 --- a/plugins/cordova-plugin-network-information/src/ios/CDVConnection.m +++ /dev/null @@ -1,127 +0,0 @@ -/* - 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. - */ - -#import "CDVConnection.h" -#import "CDVReachability.h" - -@interface CDVConnection (PrivateMethods) -- (void)updateOnlineStatus; -- (void)sendPluginResult; -@end - -@implementation CDVConnection - -@synthesize connectionType, internetReach; - -- (void)getConnectionInfo:(CDVInvokedUrlCommand*)command -{ - _callbackId = command.callbackId; - [self sendPluginResult]; -} - -- (void)sendPluginResult -{ - CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:self.connectionType]; - - [result setKeepCallbackAsBool:YES]; - [self.commandDelegate sendPluginResult:result callbackId:_callbackId]; -} - -- (NSString*)w3cConnectionTypeFor:(CDVReachability*)reachability -{ - NetworkStatus networkStatus = [reachability currentReachabilityStatus]; - - switch (networkStatus) { - case NotReachable: - return @"none"; - - case ReachableViaWWAN: - { - BOOL isConnectionRequired = [reachability connectionRequired]; - if (isConnectionRequired) { - return @"none"; - } else { - return @"cellular"; - } - } - case ReachableViaWiFi: - return @"wifi"; - - default: - return @"unknown"; - } -} - -- (BOOL)isCellularConnection:(NSString*)theConnectionType -{ - return [theConnectionType isEqualToString:@"2g"] || - [theConnectionType isEqualToString:@"3g"] || - [theConnectionType isEqualToString:@"4g"] || - [theConnectionType isEqualToString:@"cellular"]; -} - -- (void)updateReachability:(CDVReachability*)reachability -{ - if (reachability) { - // check whether the connection type has changed - NSString* newConnectionType = [self w3cConnectionTypeFor:reachability]; - if ([newConnectionType isEqualToString:self.connectionType]) { // the same as before, remove dupes - return; - } else { - self.connectionType = [self w3cConnectionTypeFor:reachability]; - } - } - [self sendPluginResult]; -} - -- (void)updateConnectionType:(NSNotification*)note -{ - CDVReachability* curReach = [note object]; - - if ((curReach != nil) && [curReach isKindOfClass:[CDVReachability class]]) { - [self updateReachability:curReach]; - } -} - -- (void)onPause -{ - [self.internetReach stopNotifier]; -} - -- (void)onResume -{ - [self.internetReach startNotifier]; - [self updateReachability:self.internetReach]; -} - -- (void)pluginInitialize -{ - self.connectionType = @"none"; - self.internetReach = [CDVReachability reachabilityForInternetConnection]; - self.connectionType = [self w3cConnectionTypeFor:self.internetReach]; - [self.internetReach startNotifier]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateConnectionType:) - name:kReachabilityChangedNotification object:nil]; - if (UIApplicationDidEnterBackgroundNotification && UIApplicationWillEnterForegroundNotification) { - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil]; - } -} - -@end diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h b/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h deleted file mode 100644 index 01a95c3..0000000 --- a/plugins/cordova-plugin-network-information/src/ios/CDVReachability.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - - File: Reachability.h - Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. - Version: 2.2 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. - ("Apple") in consideration of your agreement to the following terms, and your - use, installation, modification or redistribution of this Apple software - constitutes acceptance of these terms. If you do not agree with these terms, - please do not use, install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and subject - to these terms, Apple grants you a personal, non-exclusive license, under - Apple's copyrights in this original Apple software (the "Apple Software"), to - use, reproduce, modify and redistribute the Apple Software, with or without - modifications, in source and/or binary forms; provided that if you redistribute - the Apple Software in its entirety and without modifications, you must retain - this notice and the following text and disclaimers in all such redistributions - of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may be used - to endorse or promote products derived from the Apple Software without specific - prior written permission from Apple. Except as expressly stated in this notice, - no other rights or licenses, express or implied, are granted by Apple herein, - including but not limited to any patent rights that may be infringed by your - derivative works or by other works in which the Apple Software may be - incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED - WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN - COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR - DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF - CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF - APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2010 Apple Inc. All Rights Reserved. - -*/ - -#import -#import -#import - -typedef enum { - NotReachable = 0, - ReachableViaWWAN, // this value has been swapped with ReachableViaWiFi for Cordova backwards compat. reasons - ReachableViaWiFi // this value has been swapped with ReachableViaWWAN for Cordova backwards compat. reasons -} NetworkStatus; -#define kReachabilityChangedNotification @"kNetworkReachabilityChangedNotification" - -@interface CDVReachability : NSObject -{ - BOOL localWiFiRef; - SCNetworkReachabilityRef reachabilityRef; -} - -// reachabilityWithHostName- Use to check the reachability of a particular host name. -+ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; - -// reachabilityWithAddress- Use to check the reachability of a particular IP address. -+ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; - -// reachabilityForInternetConnection- checks whether the default route is available. -// Should be used by applications that do not connect to a particular host -+ (CDVReachability*)reachabilityForInternetConnection; - -// reachabilityForLocalWiFi- checks whether a local wifi connection is available. -+ (CDVReachability*)reachabilityForLocalWiFi; - -// Start listening for reachability notifications on the current run loop -- (BOOL)startNotifier; -- (void)stopNotifier; - -- (NetworkStatus)currentReachabilityStatus; -// WWAN may be available, but not active until a connection has been established. -// WiFi may require a connection for VPN on Demand. -- (BOOL)connectionRequired; -@end diff --git a/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m b/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m deleted file mode 100644 index c60261a..0000000 --- a/plugins/cordova-plugin-network-information/src/ios/CDVReachability.m +++ /dev/null @@ -1,260 +0,0 @@ -/* - - File: Reachability.m - Abstract: Basic demonstration of how to use the SystemConfiguration Reachability APIs. - Version: 2.2 - - Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. - ("Apple") in consideration of your agreement to the following terms, and your - use, installation, modification or redistribution of this Apple software - constitutes acceptance of these terms. If you do not agree with these terms, - please do not use, install, modify or redistribute this Apple software. - - In consideration of your agreement to abide by the following terms, and subject - to these terms, Apple grants you a personal, non-exclusive license, under - Apple's copyrights in this original Apple software (the "Apple Software"), to - use, reproduce, modify and redistribute the Apple Software, with or without - modifications, in source and/or binary forms; provided that if you redistribute - the Apple Software in its entirety and without modifications, you must retain - this notice and the following text and disclaimers in all such redistributions - of the Apple Software. - Neither the name, trademarks, service marks or logos of Apple Inc. may be used - to endorse or promote products derived from the Apple Software without specific - prior written permission from Apple. Except as expressly stated in this notice, - no other rights or licenses, express or implied, are granted by Apple herein, - including but not limited to any patent rights that may be infringed by your - derivative works or by other works in which the Apple Software may be - incorporated. - - The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO - WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED - WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR - PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN - COMBINATION WITH YOUR PRODUCTS. - - IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE - GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR - DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF - CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF - APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2010 Apple Inc. All Rights Reserved. - -*/ - -#import -#import -#import -#import -#import -#import - -#import - -#import "CDVReachability.h" - -#define kShouldPrintReachabilityFlags 0 - -static void CDVPrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment) -{ -#if kShouldPrintReachabilityFlags - NSLog(@"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n", - (flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-', - (flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-', - - (flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-', - (flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-', - (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-', - (flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-', - (flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-', - comment - ); -#endif -} - -@implementation CDVReachability - -static void CDVReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info) -{ -#pragma unused (target, flags) - // NSCAssert(info != NULL, @"info was NULL in ReachabilityCallback"); - // NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], @"info was wrong class in ReachabilityCallback"); - - // Converted the asserts above to conditionals, with safe return from the function - if (info == NULL) { - NSLog(@"info was NULL in ReachabilityCallback"); - return; - } - - if (![(__bridge NSObject*)info isKindOfClass :[CDVReachability class]]) { - NSLog(@"info was wrong class in ReachabilityCallback"); - return; - } - - // We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively - // in case someon uses the Reachability object in a different thread. - @autoreleasepool { - CDVReachability* noteObject = (__bridge CDVReachability*)info; - // Post a notification to notify the client that the network reachability changed. - [[NSNotificationCenter defaultCenter] postNotificationName:kReachabilityChangedNotification object:noteObject]; - } -} - -- (BOOL)startNotifier -{ - BOOL retVal = NO; - SCNetworkReachabilityContext context = {0, (__bridge void*)(self), NULL, NULL, NULL}; - - if (SCNetworkReachabilitySetCallback(reachabilityRef, CDVReachabilityCallback, &context)) { - if (SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode)) { - retVal = YES; - } - } - return retVal; -} - -- (void)stopNotifier -{ - if (reachabilityRef != NULL) { - SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); - } -} - -- (void)dealloc -{ - [self stopNotifier]; - if (reachabilityRef != NULL) { - CFRelease(reachabilityRef); - } -} - -+ (CDVReachability*)reachabilityWithHostName:(NSString*)hostName; -{ - CDVReachability* retVal = NULL; - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]); - if (reachability != NULL) { - retVal = [[self alloc] init]; - if (retVal != NULL) { - retVal->reachabilityRef = reachability; - retVal->localWiFiRef = NO; - } - } - return retVal; -} - -+ (CDVReachability*)reachabilityWithAddress:(const struct sockaddr_in*)hostAddress; -{ - SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress); - CDVReachability* retVal = NULL; - if (reachability != NULL) { - retVal = [[self alloc] init]; - if (retVal != NULL) { - retVal->reachabilityRef = reachability; - retVal->localWiFiRef = NO; - } - } - return retVal; -} - -+ (CDVReachability*)reachabilityForInternetConnection; -{ - struct sockaddr_in zeroAddress; - bzero(&zeroAddress, sizeof(zeroAddress)); - zeroAddress.sin_len = sizeof(zeroAddress); - zeroAddress.sin_family = AF_INET; - return [self reachabilityWithAddress:&zeroAddress]; -} - -+ (CDVReachability*)reachabilityForLocalWiFi; -{ - struct sockaddr_in localWifiAddress; - bzero(&localWifiAddress, sizeof(localWifiAddress)); - localWifiAddress.sin_len = sizeof(localWifiAddress); - localWifiAddress.sin_family = AF_INET; - // IN_LINKLOCALNETNUM is defined in as 169.254.0.0 - localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM); - CDVReachability* retVal = [self reachabilityWithAddress:&localWifiAddress]; - if (retVal != NULL) { - retVal->localWiFiRef = YES; - } - return retVal; -} - -#pragma mark Network Flag Handling - -- (NetworkStatus)localWiFiStatusForFlags:(SCNetworkReachabilityFlags)flags -{ - CDVPrintReachabilityFlags(flags, "localWiFiStatusForFlags"); - - BOOL retVal = NotReachable; - if ((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect)) { - retVal = ReachableViaWiFi; - } - return retVal; -} - -- (NetworkStatus)networkStatusForFlags:(SCNetworkReachabilityFlags)flags -{ - CDVPrintReachabilityFlags(flags, "networkStatusForFlags"); - if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { - // if target host is not reachable - return NotReachable; - } - - NetworkStatus retVal = NotReachable; - - if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0) { - // if target host is reachable and no connection is required - // then we'll assume (for now) that your on Wi-Fi - retVal = ReachableViaWiFi; - } - - if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0) || - ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))) { - // ... and the connection is on-demand (or on-traffic) if the - // calling application is using the CFSocketStream or higher APIs - - if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0) { - // ... and no [user] intervention is needed - retVal = ReachableViaWiFi; - } - } - - if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) { - // ... but WWAN connections are OK if the calling application - // is using the CFNetwork (CFSocketStream?) APIs. - retVal = ReachableViaWWAN; - } - return retVal; -} - -- (BOOL)connectionRequired; -{ - NSAssert(reachabilityRef != NULL, @"connectionRequired called with NULL reachabilityRef"); - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { - return flags & kSCNetworkReachabilityFlagsConnectionRequired; - } - return NO; -} - -- (NetworkStatus)currentReachabilityStatus -{ - NSAssert(reachabilityRef != NULL, @"currentNetworkStatus called with NULL reachabilityRef"); - NetworkStatus retVal = NotReachable; - SCNetworkReachabilityFlags flags; - if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) { - if (localWiFiRef) { - retVal = [self localWiFiStatusForFlags:flags]; - } else { - retVal = [self networkStatusForFlags:flags]; - } - } - return retVal; -} - -@end diff --git a/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js b/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js deleted file mode 100644 index cd9506e..0000000 --- a/plugins/cordova-plugin-network-information/src/tizen/NetworkProxy.js +++ /dev/null @@ -1,92 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - -var cordova = require('cordova'); -var Connection = require('./Connection'); - -module.exports = { - getConnectionInfo: function(successCallback, errorCallback) { - var cncType = Connection.NONE; - var infoCount = 0; - var deviceCapabilities = null; - var timerId = 0; - var timeout = 300; - - - function connectionCB() { - if (timerId !== null) { - clearTimeout(timerId); - timerId = null; - } - - infoCount++; - - if (infoCount > 1) { - if (successCallback) { - successCallback(cncType); - } - } - } - - function errorCB(error) { - console.log("Error: " + error.code + "," + error.name + "," + error.message); - - if (errorCallback) { - errorCallback(); - } - } - - function wifiSuccessCB(wifi) { - if ((wifi.status === "ON") && (wifi.ipAddress.length !== 0)) { - cncType = Connection.WIFI; - } - connectionCB(); - } - - function cellularSuccessCB(cell) { - if ((cncType === Connection.NONE) && (cell.status === "ON") && (cell.ipAddress.length !== 0)) { - cncType = Connection.CELL_2G; - } - connectionCB(); - } - - - deviceCapabilities = tizen.systeminfo.getCapabilities(); - - - timerId = setTimeout(function() { - timerId = null; - infoCount = 1; - connectionCB(); - }, timeout); - - - if (deviceCapabilities.wifi) { - tizen.systeminfo.getPropertyValue("WIFI_NETWORK", wifiSuccessCB, errorCB); - } - - if (deviceCapabilities.telephony) { - tizen.systeminfo.getPropertyValue("CELLULAR_NETWORK", cellularSuccessCB, errorCB); - } - } -}; - -require("cordova/tizen/commandProxy").add("NetworkStatus", module.exports); diff --git a/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp b/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp deleted file mode 100644 index 8fdb494..0000000 --- a/plugins/cordova-plugin-network-information/src/ubuntu/network_information.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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. - */ - -#include "network_information.h" - -void NetworkInformation::getConnectionInfo(int scId, int ecId) { - Q_UNUSED(ecId); - - QString result; - QNetworkInfo::NetworkMode networkMode = m_systemNetworkInfo.currentNetworkMode(); - QNetworkInfo::NetworkStatus networkStatus = m_systemNetworkInfo.networkStatus(networkMode, 0); - QNetworkInfo::CellDataTechnology cellDataTechnology = m_systemNetworkInfo.currentCellDataTechnology(0); - - if (networkStatus == QNetworkInfo::NoNetworkAvailable) - result = "Connection.NONE"; - - switch (networkMode) { - case QNetworkInfo::WimaxMode: - case QNetworkInfo::WlanMode: - result = "Connection.WIFI"; - break; - case QNetworkInfo::EthernetMode: - result = "Connection.ETHERNET"; - break; - case QNetworkInfo::LteMode: - result = "Connection.CELL_4G"; - break; - case QNetworkInfo::GsmMode: - case QNetworkInfo::CdmaMode: - case QNetworkInfo::TdscdmaMode: - case QNetworkInfo::WcdmaMode: - switch (cellDataTechnology) { - case QNetworkInfo::UmtsDataTechnology: - case QNetworkInfo::HspaDataTechnology: - result = "Connection.CELL_3G"; - break; - case QNetworkInfo::EdgeDataTechnology: - case QNetworkInfo::GprsDataTechnology: - result = "Connection.CELL_2G"; - break; - case QNetworkInfo::UnknownDataTechnology: - result = "Connection.UNKNOWN"; - break; - } - case QNetworkInfo::BluetoothMode: - case QNetworkInfo::UnknownMode: - result = "Connection.UNKNOWN"; - break; - } - - this->callback(scId, result); -} diff --git a/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h b/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h deleted file mode 100644 index aca20e7..0000000 --- a/plugins/cordova-plugin-network-information/src/ubuntu/network_information.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ - -#ifndef NETWORK_INFORMATION_H -#define NETWORK_INFORMATION_H - -#include - -#include -#include - -class NetworkInformation: public CPlugin { - Q_OBJECT -public: - explicit NetworkInformation(Cordova *cordova): CPlugin(cordova) {} - - virtual const QString fullName() override { - return NetworkInformation::fullID(); - } - - virtual const QString shortName() override { - return "Connection"; - } - - static const QString fullID() { - return "NetworkStatus"; - } - -public slots: - void getConnectionInfo(int scId, int ecId); - -private: - QNetworkInfo m_systemNetworkInfo; -}; - -#endif diff --git a/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js b/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js deleted file mode 100644 index 27ad2f0..0000000 --- a/plugins/cordova-plugin-network-information/src/windows/NetworkInfoProxy.js +++ /dev/null @@ -1,88 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - -/*global Windows:true */ - -var cordova = require('cordova'); -var Connection = require('./Connection'); - -var winNetConn = Windows.Networking.Connectivity; -var networkInfo = winNetConn.NetworkInformation; -var networkCostInfo = winNetConn.NetworkCostType; -var networkConnectivityInfo = winNetConn.NetworkConnectivityLevel; -var networkAuthenticationInfo = winNetConn.NetworkAuthenticationType; -var networkEncryptionInfo = winNetConn.NetworkEncryptionType; - -function getCurrrentConnectionType() { - - var profile = networkInfo.getInternetConnectionProfile(); - - if (!profile) { - return Connection.NONE; - } - - var conLevel = profile.getNetworkConnectivityLevel(); - var interfaceType = profile.networkAdapter.ianaInterfaceType; - - // since we use this to detect whether we are online or offline we do check agains InternetAccess - // localAccess (airplane mode as an example) or constrainedInternetAccess mean there is no access to the internet available - // https://msdn.microsoft.com/library/windows/apps/windows.networking.connectivity.networkconnectivitylevel.aspx - if (conLevel != Windows.Networking.Connectivity.NetworkConnectivityLevel.internetAccess) { - return Connection.NONE; - } - - var connectionType; - - switch (interfaceType) { - case 71: - connectionType = Connection.WIFI; - break; - case 6: - connectionType = Connection.ETHERNET; - break; - case 243: // (3GPP WWAN) // Fallthrough is intentional - case 244: // (3GPP2 WWAN) - connectionType = Connection.CELL_3G; - break; - default: - connectionType = Connection.UNKNOWN; - break; - } - - return connectionType; -} - -module.exports = { - - getConnectionInfo:function(win,fail,args) - { - var reportConnectionInfoOnce = function () { - win(getCurrrentConnectionType(), { keepCallback: true }); - } - - // report current connection type - setTimeout(reportConnectionInfoOnce, 0); - // start traking future changes - networkInfo.addEventListener("networkstatuschanged", reportConnectionInfoOnce); - } -}; - -require("cordova/exec/proxy").add("NetworkStatus",module.exports); diff --git a/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs b/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs deleted file mode 100644 index 12eb061..0000000 --- a/plugins/cordova-plugin-network-information/src/wp/NetworkStatus.cs +++ /dev/null @@ -1,129 +0,0 @@ -/* - 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. -*/ - -using System; -using System.Diagnostics; -using System.Net; -using System.Net.NetworkInformation; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Documents; -using System.Windows.Ink; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Animation; -using System.Windows.Shapes; -using Microsoft.Phone.Net.NetworkInformation; - -namespace WPCordovaClassLib.Cordova.Commands -{ - - // http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation(v=VS.92).aspx - // http://msdn.microsoft.com/en-us/library/microsoft.phone.net.networkinformation.devicenetworkinformation(v=VS.92).aspx - - public class NetworkStatus : BaseCommand - { - const string UNKNOWN = "unknown"; - const string ETHERNET = "ethernet"; - const string WIFI = "wifi"; - const string CELL_2G = "2g"; - const string CELL_3G = "3g"; - const string CELL_4G = "4g"; - const string NONE = "none"; - const string CELL = "cellular"; - - private bool HasCallback = false; - - public NetworkStatus() - { - DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler(ChangeDetected); - } - - public override void OnResume(object sender, Microsoft.Phone.Shell.ActivatedEventArgs e) - { - this.getConnectionInfo(""); - } - - public void getConnectionInfo(string empty) - { - HasCallback = true; - updateConnectionType(checkConnectionType()); - } - - private string checkConnectionType() - { - if (DeviceNetworkInformation.IsNetworkAvailable) - { - if (DeviceNetworkInformation.IsWiFiEnabled) - { - return WIFI; - } - else - { - return DeviceNetworkInformation.IsCellularDataEnabled ? CELL : UNKNOWN; - } - } - return NONE; - } - - private string checkConnectionType(NetworkInterfaceSubType type) - { - switch (type) - { - case NetworkInterfaceSubType.Cellular_1XRTT: //cell - case NetworkInterfaceSubType.Cellular_GPRS: //cell - return CELL; - case NetworkInterfaceSubType.Cellular_EDGE: //2 - return CELL_2G; - case NetworkInterfaceSubType.Cellular_3G: - case NetworkInterfaceSubType.Cellular_EVDO: //3 - case NetworkInterfaceSubType.Cellular_EVDV: //3 - case NetworkInterfaceSubType.Cellular_HSPA: //3 - return CELL_3G; - case NetworkInterfaceSubType.WiFi: - return WIFI; - case NetworkInterfaceSubType.Unknown: - case NetworkInterfaceSubType.Desktop_PassThru: - default: - return UNKNOWN; - } - } - - void ChangeDetected(object sender, NetworkNotificationEventArgs e) - { - switch (e.NotificationType) - { - case NetworkNotificationType.InterfaceConnected: - updateConnectionType(checkConnectionType(e.NetworkInterface.InterfaceSubtype)); - break; - case NetworkNotificationType.InterfaceDisconnected: - updateConnectionType(NONE); - break; - default: - break; - } - } - - private void updateConnectionType(string type) - { - // This should also implicitly fire offline/online events as that is handled on the JS side - if (this.HasCallback) - { - PluginResult result = new PluginResult(PluginResult.Status.OK, type); - result.KeepCallback = true; - DispatchCommandResult(result); - } - } - } -} diff --git a/plugins/cordova-plugin-network-information/tests/plugin.xml b/plugins/cordova-plugin-network-information/tests/plugin.xml deleted file mode 100644 index c99ca40..0000000 --- a/plugins/cordova-plugin-network-information/tests/plugin.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - Cordova Network Information Plugin Tests - Apache 2.0 - - - - diff --git a/plugins/cordova-plugin-network-information/tests/tests.js b/plugins/cordova-plugin-network-information/tests/tests.js deleted file mode 100644 index 23be97a..0000000 --- a/plugins/cordova-plugin-network-information/tests/tests.js +++ /dev/null @@ -1,101 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * -*/ - -exports.defineAutoTests = function () { - describe('Network (navigator.connection)', function () { - it("network.spec.1 should exist", function () { - expect(navigator.network && navigator.network.connection).toBeDefined(); - expect(navigator.connection).toBeDefined(); - }); - - it("network.spec.2 should be set to a valid value", function () { - var validValues = { - 'unknown': 1, - 'ethernet': 1, - 'wifi': 1, - '2g': 1, - 'cellular': 1, - '3g': 1, - '4g': 1, - 'none': 1 - }; - expect(validValues[navigator.connection.type]).toBe(1); - }); - - it("network.spec.3 should have the same value in deprecated and non-deprecated apis", function () { - expect(navigator.network.connection.type).toBe(navigator.connection.type); - }); - - it("network.spec.4 should define constants for connection status", function () { - expect(Connection.UNKNOWN).toBe("unknown"); - expect(Connection.ETHERNET).toBe("ethernet"); - expect(Connection.WIFI).toBe("wifi"); - expect(Connection.CELL_2G).toBe("2g"); - expect(Connection.CELL_3G).toBe("3g"); - expect(Connection.CELL_4G).toBe("4g"); - expect(Connection.NONE).toBe("none"); - expect(Connection.CELL).toBe("cellular"); - }); - }); -}; - -/******************************************************************************/ -/******************************************************************************/ -/******************************************************************************/ - -exports.defineManualTests = function (contentEl, createActionButton) { - function eventOutput(s) { - var el = document.getElementById("results"); - el.innerHTML = el.innerHTML + s + "
    "; - } - - function printNetwork() { - eventOutput("navigator.connection.type=" + navigator.connection.type); - eventOutput("navigator.network.connection.type=" + navigator.network.connection.type); - } - - function onEvent(e) { - eventOutput('Event of type: ' + e.type); - printNetwork(); - } - - /******************************************************************************/ - - var html = '

    ' + - 'Results:
    ' + - '' + - '
    ' + - 'Expected result: Status box will update with type of connection using two different methods. Both values must match.' + - ' The result will be unknown, ethernet, wifi, 2g, 3g, 4g, none, or cellular. Make sure it matches what the device is connected to.' + - '

    '; - - document.addEventListener("online", onEvent, false); - document.addEventListener("offline", onEvent, false); - contentEl.innerHTML = html; - - createActionButton('Show Network Connection', function () { - printNetwork(); - }, 'connection'); - - createActionButton('Clear Log', function () { - document.getElementById('results').innerHTML = ''; - }, 'actions'); -}; diff --git a/plugins/cordova-plugin-network-information/www/Connection.js b/plugins/cordova-plugin-network-information/www/Connection.js deleted file mode 100644 index f20a485..0000000 --- a/plugins/cordova-plugin-network-information/www/Connection.js +++ /dev/null @@ -1,34 +0,0 @@ -/* - * - * 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. - * -*/ - -/** - * Network status - */ -module.exports = { - UNKNOWN: "unknown", - ETHERNET: "ethernet", - WIFI: "wifi", - CELL_2G: "2g", - CELL_3G: "3g", - CELL_4G: "4g", - CELL:"cellular", - NONE: "none" -}; diff --git a/plugins/cordova-plugin-network-information/www/network.js b/plugins/cordova-plugin-network-information/www/network.js deleted file mode 100644 index ac792d8..0000000 --- a/plugins/cordova-plugin-network-information/www/network.js +++ /dev/null @@ -1,91 +0,0 @@ -/* - * 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 navigator object with our own -// object in bootstrap.js. -// Browser platform do not need to define this property, because -// it is already supported by modern browsers -if (cordova.platformId !== 'browser' && 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; diff --git a/plugins/fetch.json b/plugins/fetch.json index 9c0a1ad..ac99ded 100644 --- a/plugins/fetch.json +++ b/plugins/fetch.json @@ -23,23 +23,6 @@ "is_top_level": false, "variables": {} }, - "android.support.v4": { - "source": { - "type": "registry", - "id": "android.support.v4" - }, - "is_top_level": false, - "variables": {} - }, - "com.hutchind.cordova.plugins.launcher": { - "source": { - "type": "git", - "url": "https://github.com/nchutchind/App-Launcher-Cordova-Plugin.git", - "subdir": "." - }, - "is_top_level": true, - "variables": {} - }, "nl.x-services.plugins.backgroundaudio": { "source": { "type": "git", @@ -109,23 +92,6 @@ "is_top_level": true, "variables": {} }, - "cordova-plugin-network-information": { - "source": { - "type": "registry", - "id": "cordova-plugin-network-information" - }, - "is_top_level": true, - "variables": {} - }, - "acidhax.cordova.chromecast": { - "source": { - "type": "git", - "url": "https://github.com/MediaBrowser/cordova-chromecast", - "subdir": "." - }, - "is_top_level": true, - "variables": {} - }, "cordova-android-support-v4": { "source": { "type": "registry", @@ -178,15 +144,6 @@ "BILLING_KEY": "1" } }, - "cordova-plugin-crosswalk-webview": { - "source": { - "type": "git", - "url": "https://github.com/crosswalk-project/cordova-plugin-crosswalk-webview", - "subdir": "." - }, - "is_top_level": true, - "variables": {} - }, "cordova-plugin-app-version": { "source": { "type": "registry", diff --git a/plugins/ios.json b/plugins/ios.json index 641a025..a3ac943 100644 --- a/plugins/ios.json +++ b/plugins/ios.json @@ -296,9 +296,6 @@ } }, "installed_plugins": { - "com.hutchind.cordova.plugins.launcher": { - "PACKAGE_NAME": "com.emby.mobile" - }, "nl.x-services.plugins.backgroundaudio": { "PACKAGE_NAME": "com.emby.mobile" }, @@ -320,9 +317,6 @@ "cordova-plugin-statusbar": { "PACKAGE_NAME": "com.emby.mobile" }, - "cordova-plugin-network-information": { - "PACKAGE_NAME": "com.emby.mobile" - }, "fw-cordova-chromecast": { "PACKAGE_NAME": "com.emby.mobile" }, @@ -332,9 +326,6 @@ "cc.fovea.cordova.purchase": { "PACKAGE_NAME": "com.emby.mobile" }, - "cordova-plugin-crosswalk-webview": { - "PACKAGE_NAME": "com.emby.mobile" - }, "cordova-plugin-app-version": { "PACKAGE_NAME": "com.emby.mobile" },