Initial Commit ...

This commit is contained in:
2026-04-17 17:04:44 +03:30
commit a986295e19
842 changed files with 97431 additions and 0 deletions
+16
View File
@@ -0,0 +1,16 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# For the full list of supported browsers by the Angular framework, please see:
# https://angular.io/guide/browser-support
# You can see what browsers were selected by your queries by running:
# npx browserslist
last 1 Chrome version
last 1 Firefox version
last 2 Edge major versions
last 2 Safari major versions
last 2 iOS major versions
Firefox ESR
+16
View File
@@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false
+54
View File
@@ -0,0 +1,54 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db
#
src/app/views/temp
#
# Electron ...
platforms/electron/dist
platforms/electron/www
platforms/electron/node_modules
#
package-lock.json
+18
View File
@@ -0,0 +1,18 @@
{
"extends": [
"development"
],
"hints": {
"meta-viewport": "off",
"apple-touch-icons": "off",
"compat-api/html": "off",
"no-inline-styles": "off",
"axe/name-role-value": [
"default",
{
"link-name": "off"
}
],
"disown-opener": "off"
}
}
+12
View File
@@ -0,0 +1,12 @@
# xClient
this is an [**XFramework**](https://x-framework.ir) based App.
a client of xSaherElm Project.
## Maintainer
Hadi Khazaee asl
[https://www.saherelm.ir](https://www.saherelm.ir)
[hadi_khazaee_asl@yahoo.com](mailto:hadi_khazaee_asl@yahoo.com)
+181
View File
@@ -0,0 +1,181 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"cli": {
"packageManager": "npm",
"analytics": false,
"defaultCollection": "@ionic/angular-toolkit"
},
"newProjectRoot": "projects",
"projects": {
"xClient": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"inlineTemplate": true,
"inlineStyle": true,
"style": "scss",
"skipTests": true
},
"@schematics/angular:class": {
"skipTests": true
},
"@schematics/angular:directive": {
"skipTests": true
},
"@schematics/angular:guard": {
"skipTests": true
},
"@schematics/angular:interceptor": {
"skipTests": true
},
"@schematics/angular:pipe": {
"skipTests": true
},
"@schematics/angular:resolver": {
"skipTests": true
},
"@schematics/angular:service": {
"skipTests": true
},
"@schematics/angular:application": {
"strict": true
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"outputPath": "dist/xClient",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "src/assets",
"output": "assets"
},
{
"glob": "**/*.svg",
"input": "node_modules/x-framework-components/assets/icon/svg",
"output": "./svg"
},
{
"glob": "**/*.svg",
"input": "node_modules/ionicons/dist/ionicons/svg",
"output": "./svg"
},
"src/favicon.ico",
"src/manifest.webmanifest"
],
"styles": [
"src/theme/theme.scss"
],
"scripts": [],
"allowedCommonJsDependencies": [
"lodash"
],
"customWebpackConfig": {
"path": "./polyfill-webpack.config.js",
"replaceDuplicatePlugins": true
}
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "15mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "1mb"
}
],
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "development"
},
"serve": {
"builder": "@angular-builders/custom-webpack:dev-server",
"options": {
"browserTarget": "app:build",
"sslKey": "./ssl/xClient.key",
"sslCert": "./ssl/xClient.crt"
},
"configurations": {
"production": {
"browserTarget": "xClient:build:production"
},
"development": {
"browserTarget": "xClient:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "xClient:build"
}
},
"ionic-cordova-build": {
"builder": "@ionic/angular-toolkit:cordova-build",
"options": {
"browserTarget": "app:build"
},
"configurations": {
"production": {
"browserTarget": "app:build:production"
}
}
},
"ionic-cordova-serve": {
"builder": "@ionic/angular-toolkit:cordova-serve",
"options": {
"cordovaBuildTarget": "app:ionic-cordova-build",
"devServerTarget": "app:serve"
},
"configurations": {
"production": {
"cordovaBuildTarget": "app:ionic-cordova-build:production",
"devServerTarget": "app:serve:production"
}
}
}
}
}
},
"defaultProject": "xClient",
"schematics": {
"@ionic/angular-toolkit:component": {
"styleext": "scss"
},
"@ionic/angular-toolkit:page": {
"styleext": "scss"
}
}
}
+148
View File
@@ -0,0 +1,148 @@
<?xml version='1.0' encoding='utf-8'?>
<widget id="ir.saherelmhub.xSaherElm" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>xSaherElm</name>
<description>an xFramework based Application</description>
<author email="hadi_khazaee_asl@yahoo.com" href="https://www.saherelm.ir">Hadi Khazaee Asl</author>
<content src="index.html" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<preference name="ScrollEnabled" value="false" />
<preference name="BackupWebStorage" value="none" />
<preference name="SplashMaintainAspectRatio" value="true" />
<preference name="FadeSplashScreenDuration" value="300" />
<preference name="SplashShowOnlyFirstTime" value="false" />
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="3000" />
<platform name="android">
<edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android">
<application android:networkSecurityConfig="@xml/network_security_config" />
</edit-config>
<resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" />
<allow-intent href="market:*" />
<icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" />
<icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" />
<icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" />
<icon density="xhdpi" src="resources/android/icon/drawable-xhdpi-icon.png" />
<icon density="xxhdpi" src="resources/android/icon/drawable-xxhdpi-icon.png" />
<icon density="xxxhdpi" src="resources/android/icon/drawable-xxxhdpi-icon.png" />
<splash density="land-ldpi" src="resources/android/splash/drawable-land-ldpi-screen.png" />
<splash density="land-mdpi" src="resources/android/splash/drawable-land-mdpi-screen.png" />
<splash density="land-hdpi" src="resources/android/splash/drawable-land-hdpi-screen.png" />
<splash density="land-xhdpi" src="resources/android/splash/drawable-land-xhdpi-screen.png" />
<splash density="land-xxhdpi" src="resources/android/splash/drawable-land-xxhdpi-screen.png" />
<splash density="land-xxxhdpi" src="resources/android/splash/drawable-land-xxxhdpi-screen.png" />
<splash density="port-ldpi" src="resources/android/splash/drawable-port-ldpi-screen.png" />
<splash density="port-mdpi" src="resources/android/splash/drawable-port-mdpi-screen.png" />
<splash density="port-hdpi" src="resources/android/splash/drawable-port-hdpi-screen.png" />
<splash density="port-xhdpi" src="resources/android/splash/drawable-port-xhdpi-screen.png" />
<splash density="port-xxhdpi" src="resources/android/splash/drawable-port-xxhdpi-screen.png" />
<splash density="port-xxxhdpi" src="resources/android/splash/drawable-port-xxxhdpi-screen.png" />
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
<icon height="57" src="resources/ios/icon/icon.png" width="57" />
<icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
<icon height="29" src="resources/ios/icon/icon-small.png" width="29" />
<icon height="58" src="resources/ios/icon/icon-small@2x.png" width="58" />
<icon height="87" src="resources/ios/icon/icon-small@3x.png" width="87" />
<icon height="20" src="resources/ios/icon/icon-20.png" width="20" />
<icon height="40" src="resources/ios/icon/icon-20@2x.png" width="40" />
<icon height="60" src="resources/ios/icon/icon-20@3x.png" width="60" />
<icon height="48" src="resources/ios/icon/icon-24@2x.png" width="48" />
<icon height="55" src="resources/ios/icon/icon-27.5@2x.png" width="55" />
<icon height="29" src="resources/ios/icon/icon-29.png" width="29" />
<icon height="58" src="resources/ios/icon/icon-29@2x.png" width="58" />
<icon height="87" src="resources/ios/icon/icon-29@3x.png" width="87" />
<icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
<icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
<icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
<icon height="88" src="resources/ios/icon/icon-44@2x.png" width="88" />
<icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
<icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
<icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
<icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
<icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
<icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
<icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
<icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
<icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
<icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
<icon height="172" src="resources/ios/icon/icon-86@2x.png" width="172" />
<icon height="196" src="resources/ios/icon/icon-98@2x.png" width="196" />
<icon height="1024" src="resources/ios/icon/icon-1024.png" width="1024" />
<splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
<splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
<splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
<splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
<splash height="1125" src="resources/ios/splash/Default-Landscape-2436h.png" width="2436" />
<splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
<splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
<splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
<splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
<splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
<splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
<splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
<splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
<splash height="2436" src="resources/ios/splash/Default-2436h.png" width="1125" />
<splash height="2732" src="resources/ios/splash/Default@2x~universal~anyany.png" width="2732" />
<icon height="57" src="resources/ios/icon/icon.png" width="57" />
<icon height="114" src="resources/ios/icon/icon@2x.png" width="114" />
<icon height="20" src="resources/ios/icon/icon-20.png" width="20" />
<icon height="40" src="resources/ios/icon/icon-20@2x.png" width="40" />
<icon height="60" src="resources/ios/icon/icon-20@3x.png" width="60" />
<icon height="29" src="resources/ios/icon/icon-29.png" width="29" />
<icon height="58" src="resources/ios/icon/icon-29@2x.png" width="58" />
<icon height="87" src="resources/ios/icon/icon-29@3x.png" width="87" />
<icon height="48" src="resources/ios/icon/icon-24@2x.png" width="48" />
<icon height="55" src="resources/ios/icon/icon-27.5@2x.png" width="55" />
<icon height="88" src="resources/ios/icon/icon-44@2x.png" width="88" />
<icon height="172" src="resources/ios/icon/icon-86@2x.png" width="172" />
<icon height="196" src="resources/ios/icon/icon-98@2x.png" width="196" />
<icon height="216" src="resources/ios/icon/icon-108@2x.png" width="216" />
<icon height="40" src="resources/ios/icon/icon-40.png" width="40" />
<icon height="80" src="resources/ios/icon/icon-40@2x.png" width="80" />
<icon height="120" src="resources/ios/icon/icon-40@3x.png" width="120" />
<icon height="50" src="resources/ios/icon/icon-50.png" width="50" />
<icon height="100" src="resources/ios/icon/icon-50@2x.png" width="100" />
<icon height="60" src="resources/ios/icon/icon-60.png" width="60" />
<icon height="120" src="resources/ios/icon/icon-60@2x.png" width="120" />
<icon height="180" src="resources/ios/icon/icon-60@3x.png" width="180" />
<icon height="72" src="resources/ios/icon/icon-72.png" width="72" />
<icon height="144" src="resources/ios/icon/icon-72@2x.png" width="144" />
<icon height="76" src="resources/ios/icon/icon-76.png" width="76" />
<icon height="152" src="resources/ios/icon/icon-76@2x.png" width="152" />
<icon height="167" src="resources/ios/icon/icon-83.5@2x.png" width="167" />
<icon height="1024" src="resources/ios/icon/icon-1024.png" width="1024" />
<splash height="1136" src="resources/ios/splash/Default-568h@2x~iphone.png" width="640" />
<splash height="1334" src="resources/ios/splash/Default-667h.png" width="750" />
<splash height="2688" src="resources/ios/splash/Default-2688h~iphone.png" width="1242" />
<splash height="1242" src="resources/ios/splash/Default-Landscape-2688h~iphone.png" width="2688" />
<splash height="1792" src="resources/ios/splash/Default-1792h~iphone.png" width="828" />
<splash height="828" src="resources/ios/splash/Default-Landscape-1792h~iphone.png" width="1792" />
<splash height="2436" src="resources/ios/splash/Default-2436h.png" width="1125" />
<splash height="1125" src="resources/ios/splash/Default-Landscape-2436h.png" width="2436" />
<splash height="2208" src="resources/ios/splash/Default-736h.png" width="1242" />
<splash height="1242" src="resources/ios/splash/Default-Landscape-736h.png" width="2208" />
<splash height="1536" src="resources/ios/splash/Default-Landscape@2x~ipad.png" width="2048" />
<splash height="2048" src="resources/ios/splash/Default-Landscape@~ipadpro.png" width="2732" />
<splash height="768" src="resources/ios/splash/Default-Landscape~ipad.png" width="1024" />
<splash height="2048" src="resources/ios/splash/Default-Portrait@2x~ipad.png" width="1536" />
<splash height="2732" src="resources/ios/splash/Default-Portrait@~ipadpro.png" width="2048" />
<splash height="1024" src="resources/ios/splash/Default-Portrait~ipad.png" width="768" />
<splash height="960" src="resources/ios/splash/Default@2x~iphone.png" width="640" />
<splash height="480" src="resources/ios/splash/Default~iphone.png" width="320" />
<splash height="2732" src="resources/ios/splash/Default@2x~universal~anyany.png" width="2732" />
</platform>
<plugin name="cordova-plugin-whitelist" spec="1.3.3" />
<plugin name="cordova-plugin-statusbar" spec="2.4.2" />
<plugin name="cordova-plugin-device" spec="2.0.2" />
<plugin name="cordova-plugin-splashscreen" spec="5.0.2" />
<plugin name="cordova-plugin-ionic-webview" spec="^4.0.0" />
<plugin name="cordova-plugin-ionic-keyboard" spec="^2.0.5" />
</widget>
+7
View File
@@ -0,0 +1,7 @@
{
"name": "xSaherElm",
"integrations": {
"cordova": {}
},
"type": "angular"
}
+30
View File
@@ -0,0 +1,30 @@
{
"$schema": "./node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
]
}
}
]
}
+159
View File
@@ -0,0 +1,159 @@
{
"name": "xClient",
"version": "0.0.0",
"scripts": {
"|aaa1|=========|aaa1|": "",
"|aaa2| Regular |aaa2|": "",
"|aaa3|=========|aaa3|": "",
"ng": "ng",
"start": "npm run serveXFrameworkProject",
"watch": "ng build --watch --configuration development",
"|aaa1|==========|aaa1|": "",
"|aaa2| /Regular |aaa2|": "",
"|aaa3|==========|aaa3|": "",
"|aaa1|=====|aaa1|": "",
"|aaa2| Run |aaa2|": "",
"|aaa3|=====|aaa3|": "",
"onlyServe": "ng serve -o",
"onlyServeSSL": "ng serve --ssl -o",
"runAndroid": "ionic cordova run android",
"emulateIos": "ionic cordova emulate ios",
"emulateAndroid": "ionic cordova emulate android",
"runElectron": "cd platforms/electron && npm run --force runElectron",
"startElectron": "cd platforms/electron && npm run --force startElectron",
"runProdElectron": "cd platforms/electron && npm run --force runProdElectron",
"serveXFrameworkProject": "npm run --force prepareDependenciesFromRegistry && ng serve -o",
"serveInLabXFrameworkProject": "npm run --force prepareDependenciesFromRegistry && ionic serve -l",
"serveSSLXFrameworkProject": "npm run --force prepareDependenciesFromRegistry && ng serve -o --ssl",
"runXElectron": "npm run prepareDependenciesFromRegistry && cd platforms/electron && npm run --force runElectron",
"serveSSLWithKeysXFrameworkProjectWithoutOpen": "npm run --force prepareDependenciesFromRegistry && ng serve --ssl",
"serveProdXFrameworkProject": "npm run --force prepareDependenciesFromRegistry && ng serve -o --configuration production",
"serveSSLProdXFrameworkProject": "npm run --force prepareDependenciesFromRegistry && ng serve -o --ssl --configuration production",
"|aaa0|======|aaa1|": "",
"|aaa2| /Run |aaa2|": "",
"|aaa3|======|aaa1|": "",
"|aaa4|=======|aaa1|": "",
"|aaa2| Build |aaa2|": "",
"|aaa3|=======|aaa1|": "",
"build": "ng build --aot --base-href ./",
"buildProd": "ng build --configuration production --aot --base-href ./",
"buildElectronWin32": "cd platforms/electron && npm run --force buildElectronWin32",
"buildElectronWin64": "cd platforms/electron && npm run --force buildElectronWin64",
"buildElectronMac64": "cd platforms/electron && npm run --force buildElectronMac64",
"buildElectronLinux64": "cd platforms/electron && npm run --force buildElectronLinux64",
"|aaa0|========|aaa1|": "",
"|aaa2| /Build |aaa2|": "",
"|aaa3|========|aaa1|": "",
"|aaa0|=========|aaa1|": "",
"|aaa2| Prepare |aaa2|": "",
"|aaa3|=========|aaa1|": "",
"resourcesIos": "ionic cordova resources ios",
"requirementsIos": "ionic cordova requirements ios",
"resourcesAndroid": "ionic cordova resources android",
"requirementsAndroid": "ionic cordova requirements android",
"prepareElectron": "cd platforms/electron && npm run prepareElectron",
"prepareDependencies": "npm i --force -D ../Documents/pack/x-framework-core-0.0.1.tgz ../Documents/pack/x-framework-services-0.0.1.tgz ../Documents/pack/x-framework-components-0.0.1.tgz ../Documents/pack/x-framework-identity-sdk-0.0.1.tgz ../Documents/pack/x-framework-push-service-0.0.1.tgz ../Documents/pack/x-saherelm-api-sdk-0.0.1.tgz",
"prepareDependenciesByLink": "npm link x-framework-core x-framework-services x-framework-components x-framework-identity-sdk x-framework-push-service x-saherelm-api-sdk",
"prepareXDependenciesFromRegistry": "npm i --force -D --registry https://npm.saherelmhub.ir x-framework-core x-framework-services x-framework-components x-framework-identity-sdk x-framework-push-service",
"prepareDependenciesFromRegistry": "npm i --force -D --registry https://npm.saherelmhub.ir x-framework-core x-framework-services x-framework-components x-framework-identity-sdk x-framework-push-service x-saherelm-api-sdk",
"addAPISDKRegisteryDependency": "npm i --force -D --registry https://npm.saherelmhub.ir x-saherelm-api-sdk",
"addAPISDKLocalDependency": "npm i --force -D ../Documents/pack/x-saherelm-api-sdk-0.0.1.tgz",
"|aaa0|==========|aaa1|": "",
"|aaa2| /Prepare |aaa2|": "",
"|aaa3|==========|aaa1|": ""
},
"private": true,
"dependencies": {
"@angular/animations": "~12.0.4",
"@angular/common": "~12.0.4",
"@angular/compiler": "~12.0.4",
"@angular/core": "~12.0.4",
"@angular/forms": "~12.0.4",
"@angular/platform-browser": "~12.0.4",
"@angular/platform-browser-dynamic": "~12.0.4",
"@angular/router": "~12.0.4",
"@angular/service-worker": "~12.0.4",
"rxjs": "~6.6.0",
"tslib": "^2.1.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-builders/custom-webpack": "^12.1.1",
"@angular-devkit/build-angular": "~12.0.5",
"@angular/cdk": "^12.1.2",
"@angular/cli": "~12.0.4",
"@angular/compiler-cli": "~12.0.4",
"@angular/flex-layout": "^12.0.0-beta.34",
"@angular/material": "^12.1.2",
"@angular/material-moment-adapter": "^12.1.2",
"@compodoc/compodoc": "^1.1.14",
"@ionic/angular": "^5.6.12",
"@ionic/angular-toolkit": "^4.0.0",
"@ionic/lab": "3.2.10",
"@microsoft/signalr": "^6.0.5",
"@microsoft/signalr-protocol-msgpack": "^7.0.2",
"@types/crypto-js": "^4.0.2",
"@types/dom-to-image": "^2.6.3",
"@types/howler": "^2.2.3",
"@types/jasmine": "~3.6.0",
"@types/node": "^12.11.1",
"@types/uuid": "^8.3.1",
"ace-builds": "^1.11.2",
"angular-gridster2": "^12.1.0",
"bignumber.js": "^9.0.2",
"cordova-android": "^9.1.0",
"cordova-ios": "^6.2.0",
"cordova-plugin-device": "^2.0.2",
"cordova-plugin-ionic-keyboard": "^2.2.0",
"cordova-plugin-ionic-webview": "^4.2.1",
"cordova-plugin-splashscreen": "^5.0.2",
"cordova-plugin-statusbar": "^2.4.2",
"cordova-plugin-whitelist": "^1.3.3",
"cordova-res": "^0.15.3",
"crypto-js": "^4.0.0",
"dom-to-image": "^2.6.0",
"echarts": "^5.4.2",
"electron": "^21.0.1",
"howler": "^2.2.3",
"ionicons": "^5.5.2",
"jalali-moment": "^3.3.10",
"jasmine-core": "~3.7.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"libphonenumber-js": "^1.9.22",
"md5-typescript": "^1.0.5",
"moment": "^2.29.1",
"native-run": "^1.4.0",
"ng-packagr": "^12.0.0",
"ngx-device-detector": "^2.1.1",
"ngx-markdown": "^12.0.1",
"node-polyfill-webpack-plugin": "^1.1.4",
"ol": "^6.6.1",
"shx": "^0.3.3",
"typescript": "~4.2.3",
"uuid": "^8.3.2",
"x-framework-components": "0.0.1",
"x-framework-core": "0.0.1",
"x-framework-identity-sdk": "0.0.1",
"x-framework-push-service": "0.0.1",
"x-framework-services": "0.0.1",
"x-saherelm-api-sdk": "file:../Documents/pack/x-saherelm-api-sdk-0.0.1.tgz"
},
"cordova": {
"plugins": {
"cordova-plugin-whitelist": {},
"cordova-plugin-statusbar": {},
"cordova-plugin-device": {},
"cordova-plugin-splashscreen": {},
"cordova-plugin-ionic-webview": {},
"cordova-plugin-ionic-keyboard": {}
},
"platforms": [
"android",
"ios"
]
}
}
+11
View File
@@ -0,0 +1,11 @@
# xMabsut Client Application
an application which provides Mabsut features on Platforms.
## Maintainer
Hadi Khazaee Asl
[https://www.saherelm.ir](https://www.saherelm.ir)
[hadi_khazaee_asl@yahoo.com](mailto:hadi_khazaee_asl@yahoo.com)
+460
View File
@@ -0,0 +1,460 @@
//
//#region Required Modules ...
const url = require("url");
const path = require("path");
const { Subject } = require("rxjs");
const uuid = require("./modules/tools/x-uuid.tools");
const XLogger = require("./modules/tools/x-logger.tools");
const windowManager = require('./modules/tools/x-window.tools');
const { XElectronChannel, XElectronMessage } = require('./modules/services/x-electron.service');
const { app, shell, Tray, ipcMain, BrowserWindow, Menu } = require("electron");
//#endregion
//
//#region Prepare Required Config Data ...
//
// Set Environment ...
process.env.NODE_ENV = 'production';
//
const isDevelopment = process.env.NODE_ENV !== "production" ? true : false; // app.isPackaged;
const isMac = process.platform === "darwin" ? true : false;
//
// Show Logs ...
const showLogs = false;
//
// Show Debug Window ...
const showDebug = false;
//
// Force Window to show fullscreen ...
const isFullscreen = false;
//
// Show Window on Startup ...
const showWindowOnStartup = true;
//
const iconPath = path.join(__dirname, "www/assets/icon/favicon.png");
const trayIconPath = path.join(__dirname, "www/assets/icon/icon-16x16.png");
//#endregion
//
//#region Handle Logging ...
if (showLogs) {
XLogger.enableLogging();
} else {
XLogger.disableLogging();
}
//
console.log('XLogger State: ', XLogger.isLoggingEnable());
//#endregion
//
//#region Global Objects ...
//
let tray;
let mainUrl;
let mainWindow;
let mainWindowID;
//
const appId = uuid.generateUuid('XFrameworkElectronApp');
//#endregion
//
//#region Subscribers ...
//
const otherChannelsSubject = new Subject();
const defaultChannelSubject = new Subject();
const handShakeChannelSubject = new Subject();
//
// Register Handshake Handler ...
handShakeChannelSubject
.asObservable()
.subscribe(message => {
//
XLogger.logWarn(
XLogger.XLogMessage(
XLogger.XLogTag.Warn,
`Handshake Channel`,
[message]
)
);
});
//
// Register Default Handler ...
defaultChannelSubject
.asObservable()
.subscribe(message => {
//
XLogger.logWarn(
XLogger.XLogMessage(
XLogger.XLogTag.Warn,
`Default Channel`,
[message]
)
);
});
//
// Register Other Handler ...
otherChannelsSubject
.asObservable()
.subscribe(async message => {
//
XLogger.logWarn(
XLogger.XLogMessage(
XLogger.XLogTag.Warn,
`Other Channel`,
[message]
)
);
//
// File Service ...
if (message && message.channel === XElectronChannel.FileService) {
await handleFileServiceAction(message);
}
//
// Projects Service ...
if (message && message.channel === XElectronChannel.ProjectsService) {
await handleProjectsServiceAction(message);
}
});
//#endregion
//
//#region Creator Fuctions ...
/**
* Creat SysTray Object for using in app ...
*/
function createTray() {
//
// Create Tray Instance ...
tray = new Tray(trayIconPath);
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Tray Created ...'));
//
// Attach Event Listener to Tray Click ...
tray.on("click", () => {
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Tray Clicked ...'));
//
toggleMainWindow();
});
//
// Attach Event Listener to Tray RightClick ...
tray.on("right-click", () => {
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Tray Right Clicked ...'));
//
const contextMenu = Menu.buildFromTemplate([
{
label: "quit",
click: () => {
//
app.isClosing = true;
app.quit();
},
},
]);
//
tray.popUpContextMenu(contextMenu);
});
}
/**
* Create Main Window Instance ...
*/
function createWindow() {
//
// Create Main Window ...
mainWindow = new BrowserWindow({
icon: iconPath,
show: showWindowOnStartup,
width: isDevelopment ? 1200 : 800,
height: isDevelopment ? 800 : 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
});
//
// Handle FullScreen state if Window shown on startup ...
if (isFullscreen && showWindowOnStartup) {
mainWindow.maximize();
mainWindow.setFullScreen(true);
}
//
// Generate Main Windows UUID ...
mainWindowID = uuid.generateUuid("XFrameworkElectronWindow");
mainWindow.name = mainWindowID;
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Window ${mainWindowID} Created ...`));
//
// Fix new Window Open action ...
mainWindow.webContents.on("new-window", function (e, url) {
e.preventDefault();
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'New Window Requested ...'));
//
shell.openExternal(url);
});
//
// Handle load Main Url on Navigate for handling Navigation on Angular Apps ...
mainWindow.webContents.on("will-navigate", function (e, url) {
e.preventDefault();
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Window Will Navigate Called ...'));
//
mainWindow.loadURL(mainUrl);
});
//
// Prepare Main Url ...
mainUrl = url.format({
pathname: path.join(__dirname, "/www/index.html"),
protocol: "file",
slashes: true,
});
//
// Load Content on Main Window ...
mainWindow.loadURL(mainUrl);
//
// Remove Browser Window Default menu ...
mainWindow.removeMenu();
//
// Open Dev Tools on Development environment ...
if (showDebug) {
//
mainWindow.webContents.openDevTools();
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, 'Window Dev Tools Opened ...'));
}
//
// Handle Window Closed ...
mainWindow.on("closed", () => {
//
mainWindow = null;
windowManager.remove(mainWindowID);
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Window ${mainWindowID} Closed ...`));
});
//
// Handle Window Close ...
mainWindow.on("close", (e) => {
//
if (!app.isClosing) {
//
e.preventDefault();
//
mainWindow.hide();
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Window ${mainWindowID} Hided ...`));
}
//
return true;
});
//
// Send Handshake Message to Angular App for Notifing id of main window ...
mainWindow.webContents.on("did-finish-load", () => {
//
// Instancing new Message for Sending ...
const handshakeMsg = new XElectronMessage(
appId,
mainWindowID,
undefined,
undefined,
XElectronChannel.Handshake,
new Date().getTime()
);
//
// Sending Handshake Message to MainWindow ...
sendMessage(handshakeMsg);
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `sending Handshake to Window ${mainWindowID} ...`));
});
//
//#region IPC Handlers ...
//
// Register Event Handler for HandShake ...
ipcMain.on(XElectronChannel.Handshake, (event, message) => {
//
if (!message || !message.sender) {
return;
}
//
const windowID = message.sender;
windowManager.set(windowID, mainWindow);
//
handShakeChannelSubject.next(message);
});
//
// Register Event Handler for Message ...
ipcMain.on(XElectronChannel.Default, (event, message) => {
defaultChannelSubject.next(message);
});
//
const channels = Object.assign({}, XElectronChannel);
delete channels.Default;
delete channels.Handshake;
//
Object.keys(channels).forEach(channel => {
//
// Register Event Handler for Message on other Channel ...
ipcMain.on(channels[channel], (event, message) => {
otherChannelsSubject.next(message);
});
});
//#endregion
}
/**
* Toggle Show/Hide Main Window ...
*/
function toggleMainWindow() {
//
if (!mainWindow) {
return;
}
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `Toggle Window ...`));
//
if (mainWindow.isVisible()) {
mainWindow.hide();
} else {
//
if (isFullscreen) {
mainWindow.maximize();
mainWindow.setFullScreen(true);
}
mainWindow.show();
}
}
//#endregion
//
//#region Event Emitters ...
/**
* attach event to call when it's ready, to app object ...
*/
app.whenReady().then(() => {
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `App Ready ...`));
//
createTray();
createWindow();
});
/**
* attach event to call when all application Windows closed, to app object ...
*/
app.on("window-all-closed", () => {
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `All Windows Closed ...`));
//
if (!isMac) {
app.quit();
}
});
/**
* attach event to call when application activated, to app object ...
*/
app.on("activate", () => {
//
XLogger.logDebug(XLogger.XLogMessage(XLogger.XLogTag.Debug, `App Activated ...`));
//
if (!mainWindow) {
createWindow();
}
});
//#endregion
//
//#region Window Comminucations ...
/**
* send a message to specified window ...
*
* @param {XElectronMessageDto} message the message which required to send ...
*/
function sendMessage(message) {
//
if (!message) {
return;
}
//
if (!message.sender) {
message.sender = appId;
}
//
if (!message.reciever) {
message.reciever = mainWindowID;
}
//
let destWindow = undefined;
if (windowManager.count() === 0) {
destWindow = mainWindow;
} else {
destWindow = windowManager.get(message.reciever);
}
//
if (!destWindow) {
//
const errorMessage = 'Dest Window not found ...';
XLogger.logError(XLogger.XLogMessage(XLogger.XLogTag.Error, errorMessage))
throw errorMessage;
}
//
// Sending Message to Window ...
destWindow.webContents.send(
message.channel,
JSON.stringify(message)
);
}
//#endregion
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,622 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XDecoratorDescriptor = require('./x-decorator.descriptor');
//#endregion
/**
* check an object instance is ClassDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result =
object.hasOwnProperty('raw') &&
Array.isArray(object.extends) &&
object.hasOwnProperty('name') &&
Array.isArray(object.implements) &&
object.hasOwnProperty('extends') &&
object.hasOwnProperty('isPublic') &&
object.hasOwnProperty('decorator') &&
object.hasOwnProperty('implements') &&
object.hasOwnProperty('isExported') &&
object.hasOwnProperty('isExtended') &&
object.hasOwnProperty('isAbstract') &&
object.hasOwnProperty('hasDecorator') &&
object.hasOwnProperty('isImplemented');
//
return result;
}
/**
* retrieve base or filled ClassDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of ClassDescriptor object ...
*/
function createDescriptor(value) {
//
const result = {
raw: '',
name: '',
extends: [],
implements: [],
isPublic: true,
isExported: false,
isExtended: false,
isAbstract: false,
hasDecorator: false,
isImplemented: false,
decorator: {
...XDecoratorDescriptor.createDescriptor()
},
};
//
//#region Apply Props ...
if (value) {
//
//#region name ...
if (XValueTools.isValidArg(value.name)) {
result.name = value.name;
}
//#endregion
//
//#region extends ...
if (XValueTools.hasChildArray(value.extends)) {
result.extends = [...value.extends];
}
//#endregion
//
//#region implements ...
if (XValueTools.hasChildArray(value.implements)) {
result.implements = [...value.implements];
}
//#endregion
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region isPublic ...
if (!!value.isPublic) {
result.isPublic = true;
} else if (value.isPublic === false) {
result.isPublic = false;
}
//#endregion
//
//#region isExported ...
if (!!value.isExported) {
result.isExported = true;
}
//#endregion
//
//#region isExtended ...
if (!!value.isExtended) {
result.isExtended = true;
}
//#endregion
//
//#region isAbstract ...
if (!!value.isAbstract) {
result.isAbstract = true;
}
//#endregion
//
//#region hasDecorator ...
if (!!value.hasDecorator) {
result.hasDecorator = true;
}
//#endregion
//
//#region decorator ...
if (!!result.hasDecorator && value.decorator) {
result.decorator = {
...XDecoratorDescriptor.createDescriptor(value.decorator)
};
} else {
result.decorator = undefined;
}
//#endregion
//
//#region isImplemented ...
if (!!value.isImplemented) {
result.isImplemented = true;
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of ClassDescriptor ...
* @returns creator string ...
*/
function toExpression(
descriptor = createDescriptor(),
forceClearContent = false,
) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
let classContent = '';
let classContentIndexers = XValueTools.findClosedContent('{', '}', descriptor.raw);
if (XValueTools.hasChildArray(classContentIndexers)) {
//
classContent = XValueTools
.clearObjectSurround(classContentIndexers[0].content);
//
if (!!forceClearContent) {
classContent = XBaseDescriptor.clearContent(classContent);
}
}
//
// Handle Class Decorator ...
if (
!!descriptor.hasDecorator &&
XValueTools.isValidArgs(descriptor.decorator.type) &&
XBaseDescriptor.isValidDecoratorType(descriptor.decorator.type)
) {
//
result += XDecoratorDescriptor
.toExpression(descriptor.decorator) +
'\n';
}
//
// Handle Class ...
result +=
//
// Export ...
(
descriptor.isExported ?
XBaseDescriptor.ExpressionKeys.Export +
' ' :
''
) +
//
// Public or Private ...
(
!descriptor.isPublic ?
XBaseDescriptor.ExpressionKeys.Private +
' ' :
''
) +
//
// Abstract ...
(
descriptor.isAbstract ?
XBaseDescriptor.ExpressionKeys.Abstract +
' ' :
''
) +
//
// Class Definition ...
XBaseDescriptor.ExpressionKeys.Class +
' ' +
descriptor.name +
' ' +
//
// Extends ...
(
descriptor.isExtended ?
XBaseDescriptor.ExpressionKeys.Extends +
' ' +
descriptor.extends.join(', ')
+ ' ' :
''
) +
//
// Implements ...
(
descriptor.isImplemented ?
XBaseDescriptor.ExpressionKeys.Implements +
' ' +
descriptor.implements.join(', ') +
' ' :
''
) +
//
// Open Class ...
'{\n' +
//
// Class Content ...
(
XValueTools.isValidArg(classContent) ?
classContent :
''
) +
//
// Close Class ...
'\n}';
//
return result;
}
/**
* extract all exists ClassDescriptors ...
*
* @param {string} file a file path ...
* @returns a collection of ClassDescriptors ...
*/
async function extractDescriptors(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorsFromContent(fileContent);
//
return result;
}
/**
* extract all exists ClassDescriptors ...
*
* @param {string} content a file content ...
* @returns a collection of ClassDescriptors ...
*/
function extractDescriptorsFromContent(content = '') {
//
// Prepare result ...
let result = [
createDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!XValueTools.isValidArg(content) ||
!content.includes(XBaseDescriptor.ExpressionKeys.Class)
) {
return result;
}
//
// Extract all Key Indexes ...
const keyIndexes = XBaseDescriptor.
extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Class, content);
//
// Validate Keys Exists on Content ...
if (!XValueTools.hasChildArray(keyIndexes)) {
return result;
}
//
// Loop through indexes ...
for (let index of keyIndexes) {
//
// create an empty instance of descriptor ...
let descriptor = {
...createDescriptor()
}
//
let startIndex = index;
let endIndex = content.indexOf('{', startIndex);
let rawIndexContents = XValueTools.findClosedContent('{', '}', content, endIndex);
if (!XValueTools.hasChildArray(rawIndexContents)) {
continue;
}
//
let identifier = content.substring(
index + XBaseDescriptor.ExpressionKeys.Class.length,
endIndex
).trim();
//
//#region HasExtends, Extends, HasImplements, Implements ...
//
const hasExtends = identifier.includes(XBaseDescriptor.ExpressionKeys.Extends);
const hasImplements = identifier.includes(XBaseDescriptor.ExpressionKeys.Implements);
//
descriptor.isExtended = hasExtends;
descriptor.isImplemented = hasImplements;
//
let extendsStartIndex = -1;
let implementsStartIndex = -1;
//
// Extends ...
if (!!hasExtends) {
//
extendsStartIndex = identifier
.indexOf(XBaseDescriptor.ExpressionKeys.Extends) +
XBaseDescriptor.ExpressionKeys.Extends.length;
//
let extendsIdentifier = identifier
.substring(extendsStartIndex)
.trim();
if (extendsIdentifier
.includes(XBaseDescriptor.ExpressionKeys.Implements)) {
//
let extendsEndIndex = extendsIdentifier
.indexOf(XBaseDescriptor.ExpressionKeys.Implements);
extendsIdentifier = extendsIdentifier
.substring(0, extendsEndIndex)
.trim();
}
//
// Continue if it's not Valid ...
if (!XValueTools.isValidArg(extendsIdentifier)) {
continue;
}
//
// Check if extends is Array or not ...
if (extendsIdentifier.includes(',')) {
descriptor.extends.push(
...extendsIdentifier
.split(',')
.map(e => e.trim())
.filter(e => XValueTools.isValidArg(e))
)
} else {
descriptor.extends.push(extendsIdentifier);
}
}
//
// Implements ...
if (!!hasImplements) {
//
implementsStartIndex = identifier
.indexOf(XBaseDescriptor.ExpressionKeys.Implements) +
XBaseDescriptor.ExpressionKeys.Implements.length;
//
let implementsIdentifier = identifier
.substring(implementsStartIndex)
.trim();
if (implementsIdentifier
.includes(XBaseDescriptor.ExpressionKeys.Extends)) {
//
let implementsEndIndex = implementsIdentifier
.indexOf(XBaseDescriptor.ExpressionKeys.Extends);
implementsIdentifier = implementsIdentifier
.substring(0, implementsEndIndex)
.trim();
}
//
// Continue if it's not Valid ...
if (!XValueTools.isValidArg(implementsIdentifier)) {
continue;
}
//
// Check if extends is Array or not ...
if (implementsIdentifier.includes(',')) {
descriptor.implements.push(
...implementsIdentifier
.split(',')
.map(i => i.trim())
.filter(i => XValueTools.isValidArg(i))
)
} else {
descriptor.implements.push(implementsIdentifier);
}
}
//#endregion
//
//#region Class Name ...
let nameEndIndex = Math.min(
...[
extendsStartIndex,
implementsStartIndex,
identifier.length
]
.filter(i => i >= 0)
);
identifier = identifier
.substring(0, nameEndIndex)
.replace(XBaseDescriptor.ExpressionKeys.Extends, '')
.replace(XBaseDescriptor.ExpressionKeys.Implements, '')
.trim();
//
// Continue if class name is not valid ...
if (!XValueTools.isValidArg(identifier)) {
continue;
}
//
// Set Descriptor name ...
descriptor.name = identifier;
//#endregion
//
//#region Exported, Public, Abstract ...
//
const lengthForComeBack =
XBaseDescriptor.ExpressionKeys.Export.length +
XBaseDescriptor.ExpressionKeys.Public.length +
XBaseDescriptor.ExpressionKeys.Private.length +
XBaseDescriptor.ExpressionKeys.Abstract.length;
//
startIndex = index - lengthForComeBack;
endIndex = index;
identifier = content
.substring(startIndex, endIndex)
.trim();
//
// Exported ...
descriptor.isExported = identifier.includes(XBaseDescriptor.ExpressionKeys.Export);
//
// Public ...
descriptor.isPublic = identifier.includes(XBaseDescriptor.ExpressionKeys.Public) ||
!identifier.includes(XBaseDescriptor.ExpressionKeys.Private);
//
// Abstract ...
descriptor.isAbstract = identifier.includes(XBaseDescriptor.ExpressionKeys.Abstract);
//#endregion
//
//#region Raw ...
let classStartIndex = Math.max(
...[
content.indexOf(XBaseDescriptor.ExpressionKeys.Export, startIndex),
content.indexOf(XBaseDescriptor.ExpressionKeys.Public, startIndex),
content.indexOf(XBaseDescriptor.ExpressionKeys.Private, startIndex),
content.indexOf(XBaseDescriptor.ExpressionKeys.Abstract, startIndex),
]
.filter(i => i >= 0 && i <= rawIndexContents[0].start)
);
let classEndIndex = rawIndexContents[0].end + 1;
descriptor.raw = content.substring(classStartIndex, classEndIndex);
//#endregion
//
//#region Decorator ...
//
const forExtractDecoratorContentEndIndex = content.indexOf(descriptor.raw);
let forExtractDecoratorContent = content.substring(0, forExtractDecoratorContentEndIndex);
//
let decoratorIndexes = XValueTools
.findAllIndexes('@(.*)\\({', forExtractDecoratorContent)
.map(index => {
return {
startIndex: index,
decoratorContentIndexer: XValueTools
.findClosedContent('({', '})', forExtractDecoratorContent, index)[0]
}
});
let decoratorIndex = decoratorIndexes
.find(i => i.decoratorContentIndexer.end + 1 === classStartIndex - 1);
if (
!decoratorIndex &&
decoratorIndexes.length === 1 &&
XValueTools.hasChildArray(decoratorIndexes)
) {
//
decoratorIndex = {
//
...decoratorIndexes[0],
//
decoratorContentIndexer: {
//
...decoratorIndexes[0]
.decoratorContentIndexer,
//
end: classStartIndex - 1,
//
content: content.substring(
decoratorIndexes[0]
.decoratorContentIndexer
.start,
classStartIndex - 1
),
}
};
}
//
if (decoratorIndex) {
//
identifier = forExtractDecoratorContent
.substring(
decoratorIndex.startIndex,
decoratorIndex.decoratorContentIndexer.end + 1
);
//
const decorator = XDecoratorDescriptor.extractDescriptorFromContent(identifier);
if (!decorator) {
continue;
}
//
descriptor.hasDecorator = true;
descriptor.decorator = {
...decorator
};
}
//#endregion
//
result.push(descriptor);
}
//
return result;
}
//
// Module Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptors,
extractDescriptorsFromContent,
}
@@ -0,0 +1,354 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XContentDescriptor = require('./x-content.descriptor');
//#endregion
/**
* check an object instance is ConstDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result =
object.hasOwnProperty('raw') &&
object.hasOwnProperty('name') &&
object.hasOwnProperty('content') &&
object.hasOwnProperty('isExported');
//
return result;
}
/**
* retrieve base or filled ConstDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of ConstDescriptor object ...
*/
function createDescriptor(value) {
//
let result = {
raw: '',
name: '',
type: '',
content: {
...XContentDescriptor.createDescriptor()
},
isExported: false,
};
//
//#region Apply Value ...
if (value) {
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region name ...
if (XValueTools.isValidArg(value.name)) {
result.name = value.name;
}
//#endregion
//
//#region type ...
if (XValueTools.isValidArg(value.type)) {
result.type = value.type;
}
//#endregion
//
//#region content ...
if (
value.content &&
XContentDescriptor.isDescriptor(value.content)
) {
result.content = { ...value.content };
}
//#endregion
//
//#region isExported ...
if (!!value.isExported) {
result.isExported = value.isExported;
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of ConstDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
result += (
!!descriptor.isExported ?
XBaseDescriptor.ExpressionKeys.Export + ' ' :
''
) +
XBaseDescriptor.ExpressionKeys.Const +
' ' +
descriptor.name +
(
XValueTools.isValidArg(descriptor.type) ?
': ' +
descriptor.type :
''
) +
' = ';
//
let contentExpression = XContentDescriptor.toExpression(descriptor.content, ':');
if (XValueTools.isValidArg(contentExpression)) {
result += contentExpression;
}
//
result += ';';
//
return result;
}
/**
* extract all exists ConstDescriptors ...
*
* @param {string} file a file path ...
* @returns a collection of ConstDescriptors ...
*/
async function extractDescriptors(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorsFromContent(fileContent);
//
return result;
}
/**
* extract all exists ConstDescriptors ...
*
* @param {string} content a file content ...
* @returns a collection of ConstDescriptors ...
*/
function extractDescriptorsFromContent(content = '') {
//
// Prepare result ...
let result = [
createDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!XValueTools.isValidArg(content) ||
!content.includes(XBaseDescriptor.ExpressionKeys.Const)
) {
return result;
}
//
// Extract all Key Indexes ...
const keyIndexes = XBaseDescriptor.
extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Const, content);
//
// Validate Keys Exists on Content ...
if (!XValueTools.hasChildArray(keyIndexes)) {
return result;
}
//
// Loop through indexes ...
for (let index of keyIndexes) {
//
let startIndex = index - 1;
let endIndex = index + XBaseDescriptor.ExpressionKeys.Const.length + 1;
//
// create an empty instance of descriptor ...
let descriptor = {
...createDescriptor()
}
//
//#region Name and Type extractor ...
const nameEndIndex = content.indexOf('=', index);
identifier = content
.substring(index + XBaseDescriptor.ExpressionKeys.Const.length, nameEndIndex)
.trim();
if (XValueTools.isValidArg(identifier)) {
//
// Check to Extract Type ...
if (identifier.includes(':')) {
//
startIndex = 0;
endIndex = identifier.indexOf(':', startIndex);
//
descriptor.name = identifier
.substring(startIndex, endIndex)
.trim();
//
// Type extraction ...
startIndex = endIndex + 1;
descriptor.type = identifier
.substring(startIndex)
.trim();
} else {
descriptor.name = identifier;
}
}
//#endregion
//
//#region Extract isExported ...
const isExported = XBaseDescriptor.checkIsExported(index, content);
descriptor.isExported = isExported;
if (isExported) {
startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1;
} else {
startIndex = index;
}
//#endregion
//
//#region Extract raw content ...
identifier = content.substring(startIndex);
startIndex = 0;
endIndex = XValueTools.findNearestIndex(
[
';',
'{',
'[',
'\n'
],
identifier,
0 // nameEndIndex - startIndex
);
const nearestChar = identifier.charAt(endIndex);
if (nearestChar === '{') {
//
const closedItemsIndexes = XValueTools.findClosedContent('{', '}', identifier, endIndex);
if (!XValueTools.hasChildArray(closedItemsIndexes)) {
continue;
}
//
endIndex = closedItemsIndexes[0].end;
} else if (nearestChar === '[') {
//
const closedItemsIndexes = XValueTools.findClosedContent('[', ']', identifier, endIndex);
if (!XValueTools.hasChildArray(closedItemsIndexes)) {
continue;
}
//
endIndex = closedItemsIndexes[0].end;
}
//
identifier = identifier
.substring(startIndex, endIndex + 1)
.trim();
if (XValueTools.isValidArg(identifier)) {
descriptor.raw = identifier;
}
//#endregion
//
//#region Parse Content ...
startIndex = identifier.indexOf('=', 0);
let contentContainer = identifier
.substring(startIndex + 1)
.trim()
//
// Clear Content ...
contentContainer = XBaseDescriptor
.clearContent(contentContainer);
//
const contentType = XBaseDescriptor.getContentType(contentContainer);
const parsedContents = XBaseDescriptor.parseContent(contentContainer) || [];
const contentDescriptor = XContentDescriptor.createDescriptor();
//
contentDescriptor.type = contentType;
contentDescriptor.childs = [
...parsedContents
];
//
descriptor.content = {
...contentDescriptor
};
//#endregion
//
result.push(descriptor);
}
//
return result;
}
//
// Module Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptors,
extractDescriptorsFromContent,
}
@@ -0,0 +1,154 @@
//
//#region Imports ...
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XKeyValueDescriptor = require('./x-key-value.descriptor');
//#endregion
/**
* check an object is valid ContentDescriptor object ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
let result = false;
result = object &&
object.hasOwnProperty('type') &&
object.hasOwnProperty('childs') &&
Array.isArray(object.childs) &&
(
object.childs.length > 0 ?
object.childs.every(ch => XKeyValueDescriptor.isDescriptor(ch)) :
true
);
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of ContentDescriptor ...
* @param {string} assignSymbol property assign symbol ...
* @returns creator string ...
*/
function toExpression(
descriptor = createDescriptor(),
assignSymbol = ':',
separator = ','
) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
// Normalize Property Assign Symbol ...
assignSymbol = !XValueTools.isValidArg(assignSymbol) ?
':' :
assignSymbol;
//
const isArrayType = descriptor.type === XBaseDescriptor.ContentTypes.Array;
const isObjectType = descriptor.type === XBaseDescriptor.ContentTypes.Object;
//
result += (
isObjectType ? '{\n' :
isArrayType ? '[\n' :
''
);
//
for (let i = 0; i < descriptor.childs.length; i++) {
//
const keyVal = descriptor.childs[i];
const keyValExpression = XKeyValueDescriptor.toExpression(keyVal, assignSymbol);
//
if (separator === ';') {
//
result += keyValExpression + (
i === descriptor.childs.length - 1 ?
separator :
`${separator}\n`
);
} else {
//
result += keyValExpression + (
i === descriptor.childs.length - 1 ?
'' :
`${separator}\n`
);
}
}
//
result += (
isObjectType ? '\n}' :
isArrayType ? '\n]' :
''
);
//
return result;
}
/**
* retrieve base or filled ContentDescriptor object instance ...
*
* @param {any} value value provider object instance ...
* @returns an instance of ContentDescriptor ...
*/
function createDescriptor(value) {
//
let result = {
type: XBaseDescriptor.ContentTypes.Unknown,
childs: [
XKeyValueDescriptor.createDescriptor()
]
};
result.childs.pop();
//
//#region Apply Value ...
if (value) {
//
//#region type ...
if (XBaseDescriptor.isValidContentType(value.type)) {
result.type = value.type;
}
//#endregion
//
//#region childs ...
if (
XValueTools.hasChildArray(value.childs) &&
value.childs.every(ch => XKeyValueDescriptor.isDescriptor(ch))
) {
result.childs = [
...value.childs
];
}
//#endregion
}
//#endregion
//
return result;
}
//
// Module Exports ...
module.exports = {
isDescriptor,
toExpression,
createDescriptor,
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,307 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XContentDescriptor = require('./x-content.descriptor');
//#endregion
/**
* check an object instance is EnumDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result =
object.hasOwnProperty('raw') &&
object.hasOwnProperty('name') &&
object.hasOwnProperty('content') &&
object.hasOwnProperty('isExported');
//
return result;
}
/**
* retrieve base or filled EnumDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of EnumDescriptor object ...
*/
function createDescriptor(value) {
//
let result = {
raw: '',
name: '',
content: {
...XContentDescriptor.createDescriptor()
},
isExported: false,
}
//
//#region Apply Value ...
if (value) {
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region name ...
if (XValueTools.isValidArg(value.name)) {
result.name = value.name;
}
//#endregion
//
//#region content ...
if (
value.content &&
XContentDescriptor.isDescriptor(value.content)
) {
result.content = {
...value.content
};
}
//#endregion
//
//#region isExported ...
if (!!value.isExported) {
result.isExported = value.isExported;
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of EnumDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
result += (
!!descriptor.isExported ?
XBaseDescriptor.ExpressionKeys.Export + ' ' :
''
) +
XBaseDescriptor.ExpressionKeys.Enum +
' ' +
descriptor.name +
' ' +
'{';
//
let contentExpression = XContentDescriptor.toExpression(descriptor.content, ' =');
if (XValueTools.isValidArg(contentExpression)) {
//
if (XValueTools.isSurroundedArray(contentExpression)) {
contentExpression = XValueTools.clearArraySurround(contentExpression);
} else if (XValueTools.isSurroundedObject(contentExpression)) {
contentExpression = XValueTools.clearObjectSurround(contentExpression);
}
//
if (XValueTools.isValidArg(contentExpression)) {
result += contentExpression;
}
}
//
result += '}';
//
return result;
}
/**
* extract all exists EnumDescriptors ...
*
* @param {string} file a file path ...
* @returns a collection of EnumDescriptor ...
*/
async function extractDescriptors(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorsFromContent(fileContent);
//
return result;
}
/**
* extract all exists EnumDescriptors ...
*
* @param {string} content a file content ...
* @returns a collection of EnumDescriptor ...
*/
function extractDescriptorsFromContent(content = '') {
//
// Prepare Result ...
let result = [
createDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!XValueTools.isValidArg(content) ||
!content.includes(XBaseDescriptor.ExpressionKeys.Enum)
) {
return result;
}
//
// Extract all key Indexes ...
const keyIndexes = XBaseDescriptor.
extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Enum, content);
//
// Validate them ...
if (!XValueTools.hasChildArray(keyIndexes)) {
return result;
}
//
// Loop through indexes ...
for (const index of keyIndexes) {
//
let startIndex = index - 1;
let endIndex = index + XBaseDescriptor.ExpressionKeys.Enum.length + 1;
//
// create an empty instance of descriptor ...
let descriptor = {
...createDescriptor()
}
//
//#region Name extractor ...
const nameEndIndex = content.indexOf('{', index);
identifier = content
.substring(index + XBaseDescriptor.ExpressionKeys.Enum.length, nameEndIndex)
.trim();
if (XValueTools.isValidArg(identifier)) {
descriptor.name = identifier;
}
//#endregion
//
//#region Extract isExported ...
const isExported = XBaseDescriptor.checkIsExported(index, content);
descriptor.isExported = isExported;
if (isExported) {
startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1;
}
//#endregion
//
//#region Extract raw content ...
identifier = content.substring(startIndex);
let closedContenstIndexes = XValueTools.findClosedContent('{', '}', identifier);
if (!XValueTools.hasChildArray(closedContenstIndexes)) {
continue;
}
//
startIndex = 0;
endIndex = closedContenstIndexes[0].end;
if (endIndex < 0) {
continue;
}
//
const raw = identifier.substring(startIndex, endIndex + 1);
if (!XValueTools.isValidArg(raw)) {
continue;
}
//
descriptor.raw = raw;
//#endregion
//
//#region Parse Enum Content ...
startIndex = closedContenstIndexes[0].start;
endIndex = closedContenstIndexes[0].end + 1;
let contentContainer = identifier.substring(startIndex, endIndex);
contentContainer = XBaseDescriptor.clearContent(contentContainer);
//
const contentType = XBaseDescriptor.getContentType(contentContainer);
const parsedContents = XBaseDescriptor.parseContent(contentContainer);
const contentDescriptor = XContentDescriptor.createDescriptor();
//
contentDescriptor.type = contentType;
contentDescriptor.childs = [
...parsedContents
];
//
descriptor.content = {
...contentDescriptor
};
//#endregion
//
result.push(descriptor);
}
//
return result;
}
//
// Moduile Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptors,
extractDescriptorsFromContent,
}
@@ -0,0 +1,480 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
//#endregion
/**
* check an object instance is ExportDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result = Array.isArray(object.objects) &&
object.hasOwnProperty('raw') &&
object.hasOwnProperty('type') &&
object.hasOwnProperty('module') &&
object.hasOwnProperty('objects');
//
return result;
}
/**
* retrieve base or filled ExportDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of ExportDescriptor object ...
*/
function createDescriptor(value) {
//
let result = {
raw: '',
type: '',
module: '',
objects: ['']
}
result.objects.pop();
//
//#region Apply Value ...
if (value) {
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region type ...
if (
XValueTools.isValidArg(value.type) ||
XBaseDescriptor.isValidContentType(value.type)
) {
result.type = value.type;
}
//#endregion
//
//#region module ..
if (XValueTools.isValidArg(value.module)) {
result.module = value.module;
}
//#endregion
//
//#region objects ...
if (XValueTools.hasChildArray(value.objects)) {
result.objects = [
...value.objects
];
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of ExportDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
result += XBaseDescriptor.ExpressionKeys.Export +
' ';
//
//#region objects ...
//
if (descriptor.type === XBaseDescriptor.ContentTypes.Object) {
//
let objectsIdentifier = descriptor.objects.join(', ');
objectsIdentifier = `{ ${objectsIdentifier} }`;
//
result += objectsIdentifier;
} else {
result += descriptor.objects[0];
}
//
result += ' ';
//#endregion
//
//#region module ...
result += XBaseDescriptor.ExpressionKeys.From +
' ' +
XValueTools.surroundBy('\'', descriptor.module);
//#endregion
//
result += ';'
//
return result;
}
/**
* extract all exists ExportDescriptor ...
*
* @param {string} file a file path ...
* @returns a collection of ExportDescriptor ...
*/
async function extractDescriptors(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorsFromContent(fileContent);
//
return result;
}
/**
* extract all exists ExportDescriptor ...
*
* @param {string} content a file content ...
* @returns a collection of ExportDescriptor ...
*/
function extractDescriptorsFromContent(content = '') {
//
// Prepare Result ...
let result = [
createDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!XValueTools.isValidArg(content) ||
!content.includes(XBaseDescriptor.ExpressionKeys.Export)
) {
return result;
}
//
// Extract all key Indexes ...
const keyIndexes = XBaseDescriptor.
extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Export, content)
.filter(i => {
//
// Exports ...
let startIndex = i;
let key = XBaseDescriptor.ExpressionKeys.Exports;
let endIndex = startIndex + key.length;
let subStr = content.substring(startIndex, endIndex);
if (subStr === key) {
return false;
}
//
// Const ...
startIndex = i + XBaseDescriptor.ExpressionKeys.Export.length + 1;
key = XBaseDescriptor.ExpressionKeys.Const;
endIndex = startIndex + key.length;
subStr = content.substring(startIndex, endIndex);
if (subStr === key) {
return false;
}
//
// Enum ...
key = XBaseDescriptor.ExpressionKeys.Enum;
endIndex = startIndex + key.length;
subStr = content.substring(startIndex, endIndex);
if (subStr === key) {
return false;
}
//
// Type ...
key = XBaseDescriptor.ExpressionKeys.Type;
endIndex = startIndex + key.length;
subStr = content.substring(startIndex, endIndex);
if (subStr === key) {
return false;
}
//
// Class ...
key = XBaseDescriptor.ExpressionKeys.Class;
endIndex = startIndex + key.length;
subStr = content.substring(startIndex, endIndex);
if (subStr === key) {
return false;
}
//
// Interface ...
key = XBaseDescriptor.ExpressionKeys.Interface;
endIndex = startIndex + key.length;
subStr = content.substring(startIndex, endIndex);
if (subStr === key) {
return false;
}
//
return true;
});
//
// Validate them ...
if (!XValueTools.hasChildArray(keyIndexes)) {
return result;
}
//
// Loop through indexes ...
for (const index of keyIndexes) {
//
// create an empty instance of descriptor ...
let descriptor = {
...createDescriptor()
}
//
let startIndex = index;
let endIndex = XValueTools.findNearestIndex(
[
';',
'\n'
],
content,
startIndex
);
const nearestChar = content.charAt(endIndex);
if (nearestChar === ';') {
endIndex++;
}
//
let identifier = content
.substring(startIndex, endIndex)
.trim();
//
// Check Identifier must includes FROM ...
if (!identifier.includes(XBaseDescriptor.ExpressionKeys.From)) {
continue;
}
//
//#region raw ...
const raw = identifier;
descriptor.raw = raw;
//#endregion
//
const fromIndex = identifier.indexOf(XBaseDescriptor.ExpressionKeys.From);
//
//#region extracts Objects ...
startIndex = XBaseDescriptor.ExpressionKeys.Import.length;
endIndex = fromIndex;
identifier = identifier
.substring(startIndex, endIndex)
.trim();
//
// Clear Unused Content ...
identifier = XBaseDescriptor.clearContent(identifier);
//
// Clear Also \n ...
identifier = XValueTools.clearContent('\n', identifier);
//
if (XValueTools.isSurroundedObject(identifier)) {
//
// Clear Object Surround ...
identifier = XValueTools.clearObjectSurround(identifier);
//
// Extract Imported Objects ...
let importedObjects = identifier
.split(',')
.map(o => o.trim())
.filter(o => XValueTools.isValidArg(o));
//
descriptor.type = XBaseDescriptor.ContentTypes.Object;
descriptor.objects = [
...importedObjects
];
} else {
//
descriptor.type = XBaseDescriptor.ContentTypes.String;
descriptor.objects.push(identifier)
}
//#endregion
//
//#region Module ...
startIndex = fromIndex + XBaseDescriptor.ExpressionKeys.From.length;
identifier = raw
.substring(startIndex)
.trim();
identifier = XValueTools.findClosedStrings(identifier)[0].content;
if (XValueTools.isSurroundedString(identifier)) {
//
const surroundSymbol = identifier.charAt(0);
identifier = XValueTools.clearSurround(surroundSymbol, identifier);
}
//
descriptor.module = identifier;
//#endregion
//
result.push(descriptor);
}
//
return result;
}
//
//#region Custom Actions ...
function update(
descriptors,
addOrUpdates
) {
//
// Prepare Result ...
let result = [createDescriptor()];
result.pop();
//
//#region Validate Args ...
//
// Validate Descriptors ...
if (XValueTools.hasChildArray(descriptors)) {
//
// Validate All Objects is Descriptor ...
const isAllIsImport = descriptors.every(d => isDescriptor(d));
if (!isAllIsImport) {
return result;
}
//
result = [
...descriptors
];
}
//
// Validate addOrUpdates ...
if (XValueTools.hasChildArray(addOrUpdates)) {
//
// Validate All Objects is Descriptor ...
const isAllIsImport = addOrUpdates.every(d => isDescriptor(d));
if (!isAllIsImport) {
return result;
}
} else {
return result;
}
//#endregion
//
for (const desc of addOrUpdates) {
//
// Find same Module if exists ...
//
let descriptor = createDescriptor(desc);
//
let existsModuleIndex = result.findIndex(d => descriptor.module === d.module);
if (existsModuleIndex >= 0) {
//
descriptor = result[existsModuleIndex];
let mustAddObjects = desc.objects.filter(o => o.includes('*') ||
!descriptor.objects.includes(o));
if (XValueTools.hasChildArray(mustAddObjects)) {
descriptor.objects = [
...descriptor.objects,
...mustAddObjects
];
}
//
result[existsModuleIndex] = {
...descriptor
};
} else {
//
let mustAddObjects = descriptor.objects.filter(o => o.includes('*') ||
result
.map(d => d.objects)
.every(objects => !objects.includes(o))
);
//
descriptor.objects = [
...mustAddObjects
];
//
result.push(descriptor);
}
}
//
return result;
}
//#endregion
//
// Moduile Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptors,
extractDescriptorsFromContent,
//
update,
}
@@ -0,0 +1,353 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XEnumDescriptor = require('./x-enum.descriptor');
const XTypeDescriptor = require('./x-type.descriptor');
const XClassDescriptor = require('./x-class.descriptor');
const XConstDescriptor = require('./x-const.descriptor');
const XImportDescriptor = require('./x-import.descriptor');
const XExportDescriptor = require('./x-export.descriptor');
const XInterfaceDescriptor = require('./x-interface.descriptor');
//#endregion
/**
* check an object instance is XFileDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result =
Array.isArray(object.types) &&
object.hasOwnProperty('types') &&
//
Array.isArray(object.enums) &&
object.hasOwnProperty('enums') &&
//
Array.isArray(object.consts) &&
object.hasOwnProperty('consts') &&
//
Array.isArray(object.classes) &&
object.hasOwnProperty('classes') &&
//
Array.isArray(object.imports) &&
object.hasOwnProperty('imports') &&
//
Array.isArray(object.exports) &&
object.hasOwnProperty('exports') &&
//
Array.isArray(object.interfaces) &&
object.hasOwnProperty('interfaces');
//
return result;
}
/**
* retrieve base or filled XFileDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of XFileDescriptor object ...
*/
function createDescriptor(value) {
//
let result = {
types: [XTypeDescriptor.createDescriptor()],
enums: [XEnumDescriptor.createDescriptor()],
consts: [XConstDescriptor.createDescriptor()],
classes: [XClassDescriptor.createDescriptor()],
imports: [XImportDescriptor.createDescriptor()],
exports: [XExportDescriptor.createDescriptor()],
interfaces: [XInterfaceDescriptor.createDescriptor()],
};
//
result.types.pop();
result.enums.pop();
result.consts.pop();
result.classes.pop();
result.imports.pop();
result.exports.pop();
result.interfaces.pop();
//
//#region Apply Value ...
if (value) {
//
//#region types ...
if (XValueTools.hasChildArray(value.types)) {
result.types = [
...value.types
];
}
//#endregion
//
//#region enums ...
if (XValueTools.hasChildArray(value.enums)) {
result.enums = [
...value.enums
];
}
//#endregion
//
//#region consts ...
if (XValueTools.hasChildArray(value.consts)) {
result.consts = [
...value.consts
];
}
//#endregion
//
//#region classes ...
if (XValueTools.hasChildArray(value.classes)) {
result.classes = [
...value.classes
];
}
//#endregion
//
//#region imports ...
if (XValueTools.hasChildArray(value.imports)) {
result.imports = [
...value.imports
];
}
//#endregion
//
//#region exports ...
if (XValueTools.hasChildArray(value.exports)) {
result.exports = [
...value.exports
];
}
//#endregion
//
//#region interfaces ...
if (XValueTools.hasChildArray(value.interfaces)) {
result.interfaces = [
...value.interfaces
];
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of XFileDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
//#region Imports ...
if (XValueTools.hasChildArray(descriptor.imports)) {
//
const expression = descriptor.imports
.map(d => XImportDescriptor
.toExpression(d)
).join('\n');
//
result += expression + '\n\n';
}
//#endregion
//
//#region Enums ...
if (XValueTools.hasChildArray(descriptor.enums)) {
//
const expression = descriptor.enums
.map(d => XEnumDescriptor
.toExpression(d)
).join('\n');
//
result += expression + '\n\n';
}
//#endregion
//
//#region Types ...
if (XValueTools.hasChildArray(descriptor.types)) {
//
const expression = descriptor.types
.map(d => XTypeDescriptor
.toExpression(d)
).join('\n');
//
result += expression + '\n\n';
}
//#endregion
//
//#region Interfaces ...
if (XValueTools.hasChildArray(descriptor.interfaces)) {
//
const expression = descriptor.interfaces
.map(d => XInterfaceDescriptor
.toExpression(d)
).join('\n');
//
result += expression + '\n\n';
}
//#endregion
//
//#region Consts ...
if (XValueTools.hasChildArray(descriptor.consts)) {
//
const expression = descriptor.consts
.map(d => XConstDescriptor
.toExpression(d)
).join('\n');
//
result += expression + '\n\n';
}
//#endregion
//
//#region Classes ...
if (XValueTools.hasChildArray(descriptor.classes)) {
//
const expression = descriptor.classes
.map(d => XClassDescriptor
.toExpression(d)
).join('\n');
//
result += expression + '\n\n';
}
//#endregion
//
//#region Exports ...
if (XValueTools.hasChildArray(descriptor.exports)) {
//
const expression = descriptor.exports
.map(d => XExportDescriptor
.toExpression(d)
).join('\n');
//
result += expression + '\n\n';
}
//#endregion
//
if (XValueTools.endsWidth('\n', result)) {
result = result.substring(0, result.length - 1);
}
//
return result;
}
/**
* extract all exists XFileDescriptors ...
*
* @param {string} file a file path ...
* @returns a collection of XFileDescriptors ...
*/
async function extractDescriptor(file = '') {
//
let result = createDescriptor();
//
if (!XFileTools.isFileExists(file)) {
return undefined;
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return undefined;
}
//
result = extractDescriptorFromContent(fileContent);
return result;
}
/**
* extract all exists XFileDescriptors ...
*
* @param {string} content a file content ...
* @returns a collection of XFileDescriptors ...
*/
function extractDescriptorFromContent(content = '') {
//
// Prepare result ...
let result = createDescriptor();
//
// Validate Args ...
if (!XValueTools.isValidArg(content)) {
return undefined;
}
//
const types = XTypeDescriptor.extractDescriptorsFromContent(content);
const enums = XEnumDescriptor.extractDescriptorsFromContent(content);
const consts = XConstDescriptor.extractDescriptorsFromContent(content);
const classes = XClassDescriptor.extractDescriptorsFromContent(content);
const exports = XExportDescriptor.extractDescriptorsFromContent(content);
const imports = XImportDescriptor.extractDescriptorsFromContent(content);
const interfaces = XInterfaceDescriptor.extractDescriptorsFromContent(content);
//
result = {
types,
enums,
consts,
imports,
exports,
classes,
interfaces,
};
//
return result;
}
//
// Module Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptor,
extractDescriptorFromContent,
}
@@ -0,0 +1,423 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
//#endregion
/**
* check an object instance is ImportDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result = Array.isArray(object.objects) &&
object.hasOwnProperty('raw') &&
object.hasOwnProperty('type') &&
object.hasOwnProperty('module') &&
object.hasOwnProperty('objects');
//
return result;
}
/**
* retrieve base or filled ImportDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of ImportDescriptor object ...
*/
function createDescriptor(value) {
//
let result = {
raw: '',
type: '',
module: '',
objects: ['']
}
result.objects.pop();
//
//#region Apply Value ...
if (value) {
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region type ...
if (
XValueTools.isValidArg(value.type) ||
XBaseDescriptor.isValidContentType(value.type)
) {
result.type = value.type;
}
//#endregion
//
//#region module ..
if (XValueTools.isValidArg(value.module)) {
result.module = value.module;
}
//#endregion
//
//#region objects ...
if (XValueTools.hasChildArray(value.objects)) {
result.objects = [
...value.objects
];
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of ImportDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
result += XBaseDescriptor.ExpressionKeys.Import +
' ';
//
//#region objects ...
//
if (descriptor.type === XBaseDescriptor.ContentTypes.Object) {
//
let objectsIdentifier = descriptor.objects.join(', ');
objectsIdentifier = `{ ${objectsIdentifier} }`;
//
result += objectsIdentifier;
} else {
result += descriptor.objects[0];
}
//
result += ' ';
//#endregion
//
//#region module ...
result += XBaseDescriptor.ExpressionKeys.From +
' ' +
XValueTools.surroundBy('\'', descriptor.module);
//#endregion
//
result += ';'
//
return result;
}
/**
* extract all exists ImportDescriptor ...
*
* @param {string} file a file path ...
* @returns a collection of ImportDescriptor ...
*/
async function extractDescriptors(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorsFromContent(fileContent);
//
return result;
}
/**
* extract all exists ImportDescriptor ...
*
* @param {string} content a file content ...
* @returns a collection of ImportDescriptor ...
*/
function extractDescriptorsFromContent(content = '') {
//
// Prepare Result ...
let result = [
createDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!XValueTools.isValidArg(content) ||
!content.includes(XBaseDescriptor.ExpressionKeys.Import)
) {
return result;
}
//
// Extract all key Indexes ...
const keyIndexes = XBaseDescriptor.
extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Import, content);
//
// Validate them ...
if (!XValueTools.hasChildArray(keyIndexes)) {
return result;
}
//
// Loop through indexes ...
for (const index of keyIndexes) {
//
// create an empty instance of descriptor ...
let descriptor = {
...createDescriptor()
}
//
let startIndex = index;
let endIndex = XValueTools.findNearestIndex(
[
';',
'\n'
],
content,
startIndex
);
const nearestChar = content.charAt(endIndex);
if (nearestChar === ';') {
endIndex++;
}
//
let identifier = content
.substring(startIndex, endIndex)
.trim();
//
// Check Identifier must includes FROM ...
if (!identifier.includes(XBaseDescriptor.ExpressionKeys.From)) {
continue;
}
//
//#region raw ...
const raw = identifier;
descriptor.raw = raw;
//#endregion
//
const fromIndex = identifier.indexOf(XBaseDescriptor.ExpressionKeys.From);
//
//#region extracts Objects ...
startIndex = XBaseDescriptor.ExpressionKeys.Import.length;
endIndex = fromIndex;
identifier = identifier
.substring(startIndex, endIndex)
.trim();
//
// Clear Unused Content ...
identifier = XBaseDescriptor.clearContent(identifier);
//
// Clear Also \n ...
identifier = XValueTools.clearContent('\n', identifier);
//
if (XValueTools.isSurroundedObject(identifier)) {
//
// Type ...
descriptor.type = XBaseDescriptor.ContentTypes.Object;
//
// Clear Object Surround ...
identifier = XValueTools.clearObjectSurround(identifier);
//
// Extract Imported Objects ...
let importedObjects = identifier
.split(',')
.map(o => o.trim())
.filter(o => XValueTools.isValidArg(o));
//
descriptor.objects = [
...importedObjects
];
} else {
//
descriptor.type = XBaseDescriptor.ContentTypes.String;
descriptor.objects.push(identifier)
}
//#endregion
//
//#region Module ...
startIndex = fromIndex + XBaseDescriptor.ExpressionKeys.From.length;
identifier = raw
.substring(startIndex)
.trim();
identifier = XValueTools.findClosedStrings(identifier)[0].content;
if (XValueTools.isSurroundedString(identifier)) {
//
const surroundSymbol = identifier.charAt(0);
identifier = XValueTools.clearSurround(surroundSymbol, identifier);
}
//
descriptor.module = identifier;
//#endregion
//
result.push(descriptor);
}
//
return result;
}
//
//#region Custom Actions ...
function update(
descriptors,
addOrUpdates
) {
//
// Prepare Result ...
let result = [createDescriptor()];
result.pop();
//
//#region Validate Args ...
//
// Validate Descriptors ...
if (XValueTools.hasChildArray(descriptors)) {
//
// Validate All Objects is Descriptor ...
const isAllIsImport = descriptors.every(d => isDescriptor(d));
if (!isAllIsImport) {
return result;
}
//
result = [
...descriptors
];
}
//
// Validate addOrUpdates ...
if (XValueTools.hasChildArray(addOrUpdates)) {
//
// Validate All Objects is Descriptor ...
const isAllIsImport = addOrUpdates.every(d => isDescriptor(d));
if (!isAllIsImport) {
return result;
}
} else {
return result;
}
//#endregion
//
for (const desc of addOrUpdates) {
//
// Find same Module if exists ...
//
let descriptor = createDescriptor(desc);
//
let existsModuleIndex = result.findIndex(d => descriptor.module === d.module);
if (existsModuleIndex >= 0) {
//
descriptor = result[existsModuleIndex];
let mustAddObjects = desc.objects.filter(o => o.includes('*') ||
!descriptor.objects.includes(o));
if (XValueTools.hasChildArray(mustAddObjects)) {
descriptor.objects = [
...descriptor.objects,
...mustAddObjects
];
}
//
result[existsModuleIndex] = {
...descriptor
};
} else {
//
let mustAddObjects = descriptor.objects
.filter(o => o.includes('*') ||
result
.map(d => d.objects)
.every(objects => !objects.includes(o))
);
//
descriptor.objects = [
...mustAddObjects
];
//
result.push(descriptor);
}
}
//
return result;
}
//#endregion
//
// Moduile Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptors,
extractDescriptorsFromContent,
//
update,
}
@@ -0,0 +1,380 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XContentDescriptor = require('./x-content.descriptor');
//#endregion
/**
* check an object instance is InterfaceDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result =
object.hasOwnProperty('raw') &&
object.hasOwnProperty('name') &&
Array.isArray(object.extends) &&
object.hasOwnProperty('extends') &&
object.hasOwnProperty('isExtended') &&
object.hasOwnProperty('isExported');
//
return result;
}
/**
* retrieve base or filled InterfaceDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of InterfaceDescriptor object ...
*/
function createDescriptor(value) {
//
let result = {
raw: '',
name: '',
extends: [''],
isExtended: false,
isExported: false,
properties: {
...XContentDescriptor.createDescriptor()
},
};
result.extends.pop();
//
//#region Apply Value ...
if (value) {
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region name ...
if (XValueTools.isValidArg(value.name)) {
result.name = value.name;
}
//#endregion
//
//#region isExported ...
if (!!value.isExported) {
result.isExported = value.isExported;
}
//#endregion
//
//#region isExtended ...
if (!!value.isExtended) {
result.isExtended = value.isExtended;
}
//#endregion
//
//#region extends ...
if (XValueTools.hasChildArray(value.extends)) {
result.extends = [
...value.extends
];
}
//#endregion
//
//#region properties ...
if (
value.properties &&
XContentDescriptor.isDescriptor(value.properties)
) {
result.properties = {
...value.properties
};
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of InterfaceDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
result += (
!!descriptor.isExported ?
XBaseDescriptor.ExpressionKeys.Export + ' ' :
''
) +
XBaseDescriptor.ExpressionKeys.Interface +
' ' +
descriptor.name +
' ' +
(
!!descriptor.isExtended &&
XValueTools.hasChildArray(descriptor.extends) ?
XBaseDescriptor.ExpressionKeys.Extends +
' ' +
descriptor.extends.join(', ') +
' ' :
''
);
//
let contentExpression = XContentDescriptor.toExpression(descriptor.properties, ':', ';');
if (XValueTools.isValidArg(contentExpression)) {
result += contentExpression;
}
//
return result;
}
/**
* extract all exists InterfaceDescriptors ...
*
* @param {string} file a file path ...
* @returns a collection of InterfaceDescriptors ...
*/
async function extractDescriptors(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorsFromContent(fileContent);
//
return result;
}
/**
* extract all exists InterfaceDescriptors ...
*
* @param {string} content a file content ...
* @returns a collection of InterfaceDescriptors ...
*/
function extractDescriptorsFromContent(content = '') {
//
// Prepare result ...
let result = [
createDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!XValueTools.isValidArg(content) ||
!content.includes(XBaseDescriptor.ExpressionKeys.Interface)
) {
return result;
}
//
// Extract all Key Indexes ...
const keyIndexes = XBaseDescriptor.
extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Interface, content);
//
// Validate Keys Exists on Content ...
if (!XValueTools.hasChildArray(keyIndexes)) {
return result;
}
//
// Loop through indexes ...
for (let index of keyIndexes) {
//
let startIndex = index - 1;
let endIndex = index + XBaseDescriptor.ExpressionKeys.Interface.length + 1;
//
// create an empty instance of descriptor ...
let descriptor = {
...createDescriptor()
}
//
//#region Extract isExported ...
const isExported = XBaseDescriptor.checkIsExported(index, content);
descriptor.isExported = isExported;
if (isExported) {
startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1;
} else {
startIndex = index;
}
//#endregion
//
// Closed Item ...
let closedContents = XValueTools.findClosedContent('{', '}', content, index);
if (!XValueTools.hasChildArray(closedContents)) {
continue;
}
//
let interfaceContentIndexer = closedContents[0];
endIndex = interfaceContentIndexer.start - 1;
//
identifier = content
.substring(startIndex, endIndex)
.trim();
//
//#region extract Name, Extends ...
let name = '';
let nameCandidate = identifier
.replace(XBaseDescriptor.ExpressionKeys.Export, '')
.replace(XBaseDescriptor.ExpressionKeys.Interface, '')
.trim();
let extendsIdentifiers = nameCandidate;
if (nameCandidate.includes(XBaseDescriptor.ExpressionKeys.Extends)) {
//
// Name ...
let nameEndIndex = nameCandidate.indexOf(XBaseDescriptor.ExpressionKeys.Extends);
nameCandidate = nameCandidate
.substring(0, nameEndIndex)
.trim();
//
//isExtended ...
descriptor.isExtended = true;
extendsIdentifiers = extendsIdentifiers
.substring(nameEndIndex + XBaseDescriptor.ExpressionKeys.Extends.length)
.trim();
//
if (
!XValueTools.isValidArg(nameCandidate) ||
!XValueTools.isValidArg(extendsIdentifiers)
) {
continue;
}
//
// Extends ...
descriptor.extends = [
...extendsIdentifiers
.split(',')
.map(e => e.trim())
.filter(e => XValueTools.isValidArg(e))
];
//
name = nameCandidate;
} else {
name = nameCandidate;
}
//
if (!XValueTools.isValidArg(name)) {
continue;
}
//
descriptor.name = name;
//#endregion
//
//#region extract Content ...
let contentContainer = interfaceContentIndexer.content;
//
// Clear Content ...
contentContainer = XBaseDescriptor
.clearContent(contentContainer);
//
const contentType = XBaseDescriptor.getContentType(contentContainer);
const parsedContents = XBaseDescriptor.parseContent(
contentContainer,
true
);
const contentDescriptor = XContentDescriptor.createDescriptor();
//
contentDescriptor.type = contentType;
contentDescriptor.childs = [
...parsedContents
];
//
descriptor.properties = {
...contentDescriptor
}
//#endregion
//
//#region Extract raw content ...
//
endIndex = interfaceContentIndexer.end + 1;
identifier = content
.substring(startIndex, endIndex)
.trim();
if (!XValueTools.isValidArg(identifier)) {
continue;
}
//
descriptor.raw = identifier;
//#endregion
//
result.push(descriptor);
}
//
return result;
}
//
// Module Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptors,
extractDescriptorsFromContent,
}
@@ -0,0 +1,118 @@
//
//#region Imports ...
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
//#endregion
/**
* check an object is valid key/value object ...
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
let result = false;
result = object &&
object.hasOwnProperty('key') &&
object.hasOwnProperty('type') &&
object.hasOwnProperty('value');
//
return result;
}
/**
* retrieve base or filled KeyValueProvider object instance ...
*
* @param {any} value value provider object instance ...
* @returns an instance of KeyValueDescriptor ...
*/
function createDescriptor(value) {
//
const result = {
key: '',
value: undefined,
type: XBaseDescriptor.ContentTypes.Unknown,
};
//
//#region Apply Value ...
if (value) {
//
//#region key ...
if (XValueTools.isValidArg(value.key)) {
result.key = value.key;
}
//#endregion
//
//#region type ...
if (
XValueTools.isValidArg(value.type) &&
XBaseDescriptor.isValidContentType(value.type)
) {
result.type = value.type;
}
//#endregion
//
//#region value ...
if (value.value) {
result.value = value.value;
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of KeyValueDescriptor ...
* @param {string} assignSymbol property assign symbol ...
* @returns creator string ...
*/
function toExpression(
descriptor = createDescriptor(),
assignSymbol = ''
) {
//
let result = '';
//
// Validate Args ...
if (!isDescriptor(descriptor)) {
return result;
}
//
// Normalize Assign Symbol ...
assignSymbol = !XValueTools.isValidArg(assignSymbol) ?
'' :
assignSymbol;
//
// Handle Key ...
if (descriptor.key !== XBaseDescriptor.ExpressionKeys.IGNORED_KEY) {
result += descriptor.key + assignSymbol + ' ';
}
//
// Handle Value ...
const valueExpression = XBaseDescriptor.toExpression(descriptor);
result += valueExpression;
//
return result;
}
//
// Module Exports ...
module.exports = {
isDescriptor,
toExpression,
createDescriptor,
}
@@ -0,0 +1,527 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
const XConstDescriptor = require('./x-const.descriptor');
const XContentDescriptor = require('./x-content.descriptor');
//#endregion
//
//#region Constants ...
/**
* all possible usage of localeResources ...
*/
const LocalizationResourceIdentifiers = {
ResourceIDs: 'ResourceIDs.',
XResourceIDs: 'XResourceIDs.',
XAppResourceIDs: 'AppResourceIDs.',
ThisResourceIDs: 'this.ResourceIDs.',
ThisAppResourceIDs: 'this.AppResourceIDs.',
};
//#endregion
//
//#region ResourceIDsDescriptor ...
/**
* check an object instance is ResourceIDsDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isResourceIDsDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result =
object.hasOwnProperty('resourceIds') &&
object.hasOwnProperty('appResourceIds') &&
Array.isArray(object.resourceIds) &&
Array.isArray(object.appResourceIds);
//
return result;
}
/**
* retrieve base or filled ResourceIDsDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of ResourceIDsDescriptor object ...
*/
function createResourceIDsDescriptor(value) {
//
let result = {
resourceIds: [''],
appResourceIds: ['']
}
result.resourceIds.pop();
result.appResourceIds.pop();
//
//#region Apply Value ...
if (value) {
//
//#region ResourceIDs ...
if (XValueTools.hasChildArray(value.resourceIds)) {
result.resourceIds = [
...value.resourceIds
];
}
//#endregion
//
//#region appResourceIds ...
if (XValueTools.hasChildArray(value.appResourceIds)) {
result.appResourceIds = [
...value.appResourceIds
];
}
//#endregion
}
//#endregion
//
return result;
}
/**
* extract exists used ResourceIds form files ...
*
* @param {string|string[]} files a file(s) path ...
* @returns an instance of ResourceIDsDescriptor ...
*/
async function extractResourceIDsDescriptor(files) {
//
// Prepare Result ...
let result = createResourceIDsDescriptor();
//
// Normalize Files ...
const normalFiles = XValueTools.toNormalArray(files);
//
// Validate Args ...
if (
!XValueTools.hasChildArray(normalFiles) ||
!normalFiles.every(file => XFileTools.isFileExists(file))
) {
return result;
}
//
const readFileContentTasks = normalFiles.map(file => XFileTools.readFile(file));
const fileContents = await Promise.all(readFileContentTasks);
if (!XValueTools.hasChildArray(fileContents)) {
return result;
}
//
result = extractResourceIDsDescriptorFromContent(fileContents);
//
return result;
}
/**
* extract exists ResourceIDsDescriptor from file contents ...
*
* @param {string|string[]} contents a file(s) content(s) ...
* @returns an instance of ResourceIDsDescriptor ...
*/
function extractResourceIDsDescriptorFromContent(contents) {
//
// Prepare Result ...
let result = createResourceIDsDescriptor();
//
// Validate Args ...
if (!contents) {
return result;
}
//
// Normalize Contents ...
const normalContents = XValueTools
.toNormalArray(contents)
.map(c => c.trim())
.filter(c => XValueTools.isValidArg(c));
if (!XValueTools.hasChildArray(normalContents)) {
return result;
}
//
// Loop through all normal contents and extract result ...
for (const content of normalContents) {
//
// Find all indexes in File for eachType ...
const indexes = XValueTools.findAllIndexes(
Object.values(LocalizationResourceIdentifiers),
content
);
if (!XValueTools.hasChildArray(indexes)) {
continue;
}
//
// Try to Parse Content by indexes ...
for (const idx of indexes) {
//
let identifierToken = content.substring(idx, idx + LocalizationResourceIdentifiers.ThisAppResourceIDs.length);
if (identifierToken.includes(LocalizationResourceIdentifiers.ThisAppResourceIDs)) {
identifierToken = identifierToken.includes(LocalizationResourceIdentifiers.ThisAppResourceIDs);
} else if (identifierToken.includes(LocalizationResourceIdentifiers.ThisResourceIDs)) {
identifierToken = LocalizationResourceIdentifiers.ThisResourceIDs;
} else if (identifierToken.includes(LocalizationResourceIdentifiers.XAppResourceIDs)) {
identifierToken = LocalizationResourceIdentifiers.XAppResourceIDs;
} else if (identifierToken.includes(LocalizationResourceIdentifiers.XResourceIDs)) {
identifierToken = LocalizationResourceIdentifiers.XResourceIDs;
} else if (identifierToken.includes(LocalizationResourceIdentifiers.ResourceIDs)) {
identifierToken = LocalizationResourceIdentifiers.ResourceIDs;
} else {
identifierToken = undefined;
}
//
if (!XValueTools.isValidArg(identifierToken)) {
continue;
}
//
let endIndex = XValueTools.findNearestIndex(
[
';',
'\"',
',',
' ',
')',
'\n'
],
content,
idx,
true
);
//
const identifier = content
.substring(idx, endIndex)
.replace(identifierToken, '');
if (XValueTools.isValidArg(identifier)) {
//
switch (identifierToken) {
//
// ResourceIDs ...
case LocalizationResourceIdentifiers.ResourceIDs:
case LocalizationResourceIdentifiers.XResourceIDs:
case LocalizationResourceIdentifiers.ThisResourceIDs:
if (!result.resourceIds.includes(identifier)) {
result.resourceIds.push(identifier);
}
break;
//
// AppResourceIDs ...
case LocalizationResourceIdentifiers.XAppResourceIDs:
case LocalizationResourceIdentifiers.ThisAppResourceIDs:
if (!result.appResourceIds.includes(identifier)) {
result.appResourceIds.push(identifier);
}
break;
}
}
}
}
//
return result;
}
//#endregion
//
//#region LocaleResourceItemDescriptor ...
function isLocaleResourceItemDescriptor(value) {
//
let result = false;
//
result = value &&
value.hasOwnProperty('id') &&
value.hasOwnProperty('value');
//
return result;
}
function createLocaleResourceItemDescriptor(value) {
//
let result = {
id: '',
value: ''
};
//
//#region Apply Value ...
if (value) {
//
//#region id ...
if (XValueTools.isValidArg(value.id)) {
result.id = value.id;
}
//#endregion
//
//#region value ...
if (XValueTools.isValidArg(value.value)) {
result.value = value.value;
}
//#endregion
}
//#endregion
//
return result;
}
//#endregion
//
//#region LocalizationDescriptor ...
function isLocalizationDescriptor(value) {
//
let result = false;
//
result = value &&
value.hasOwnProperty('name') &&
value.hasOwnProperty('locale') &&
value.hasOwnProperty('language') &&
value.hasOwnProperty('direction') &&
value.hasOwnProperty('resources') &&
Array.isArray(value.resources) &&
(XValueTools.hasChildArray(value.resources) ?
value.resources.every(r => isLocaleResourceItemDescriptor(r)) : true);
//
return result;
}
function createLocalizationDescriptor(value) {
//
let result = {
name: '',
locale: '',
language: '',
direction: '',
resources: [
createLocaleResourceItemDescriptor()
]
};
result.resources.pop();
//
//#region Apply Value ...
if (value) {
//
//#region name ...
if (XValueTools.isValidArg(value.name)) {
result.name = value.name;
}
//#endregion
//
//#region locale ...
if (XValueTools.isValidArg(value.locale)) {
result.locale = value.locale;
}
//#endregion
//
//#region language ...
if (XValueTools.isValidArg(value.language)) {
result.language = value.language;
}
//#endregion
//
//#region direction ...
if (XValueTools.isValidArg(value.direction)) {
result.direction = value.direction;
}
//#endregion
//
//#region resources ...
if (
XValueTools.hasChildArray(value.resources) &&
value.resources.every(r => isLocaleResourceItemDescriptor(r))
) {
result.resources = [
...value.resources
];
}
//#endregion
}
//#endregion
//
return result;
}
function extractLocalizationDescriptors(
constDescriptor = XConstDescriptor.createDescriptor()
) {
//
let result = [
createLocalizationDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!constDescriptor ||
!XConstDescriptor.isDescriptor(constDescriptor) ||
!XValueTools.hasChildArray(constDescriptor.content.childs)
) {
return result;
}
//
// extract childs of content ...
for (const child of constDescriptor.content.childs) {
//
const localizationDescriptor = createLocalizationDescriptor();
for (const value of child.value) {
//
if (value.key !== 'resources') {
localizationDescriptor[value.key] = XValueTools.toStringExpression(value.value);
} else {
localizationDescriptor[value.key] = value.value.map(v => {
//
const id = XValueTools
.toStringExpression(
v.value.find(
vv => vv.key === 'id')?.value
);
//
const value = XValueTools
.toStringExpression(
v.value.find(
vv => vv.key === 'value')?.value
);
//
const result = createLocaleResourceItemDescriptor({
id,
value,
});
//
return result;
});
}
}
//
result.push(localizationDescriptor);
}
//
return result;
}
//#endregion
//
//#region ResourceIDUsedCase ...
/**
* create an empty/filled LocaleResourceIDUsedCaseDescriptor object instance ...
*
* @param {any} value value provider for filling ...
* @returns an instance of Specific Descriptor ...
*/
function createLocaleResourceIDUsedCaseDescriptor(value) {
//
// Prepare Result ...
let result = {
resourceID: '',
usedCases: [
''
],
};
result.usedCases.pop();
//
//#region Apply Value ...
if (value) {
//
//#region resourceID ...
if (XValueTools.isValidArg(value.resourceID)) {
result.resourceID = value.resourceID;
}
//#endregion
//
//#region usedCases ...
if (XValueTools.hasChildArray(value.usedCases)) {
result.usedCases = [
...value.usedCases
];
}
//#endregion
}
//#endregion
//
return result;
}
/**
* check an object is LocaleResourceIDUsedCaseDescriptor instance or not ...
*
* @param {any} value proposed object to check ...
* @returns
*/
function isLocaleResourceIDUsedCaseDescriptor(value) {
//
let result = false;
//
result = value &&
value.hasOwnProperty('resourceID') &&
value.hasOwnProperty('usedCases') &&
Array.isArray(value.usedCases);
//
return result;
}
//#endregion
//
// Moduile Exports ...
module.exports = {
//
LocalizationResourceIdentifiers,
//
isResourceIDsDescriptor,
createResourceIDsDescriptor,
extractResourceIDsDescriptor,
extractResourceIDsDescriptorFromContent,
//
isLocaleResourceItemDescriptor,
createLocaleResourceItemDescriptor,
//
isLocalizationDescriptor,
createLocalizationDescriptor,
extractLocalizationDescriptors,
//
isLocaleResourceIDUsedCaseDescriptor,
createLocaleResourceIDUsedCaseDescriptor,
}
@@ -0,0 +1,279 @@
//
//#region Imports ...
const XFileTools = require('../tools/x-file.tools');
const XValueTools = require('../tools/x-value.tools');
const XBaseDescriptor = require('./x-base.descriptor');
//#endregion
/**
* check an object instance is typeDescriptor or not ...
*
* @param {any} object proposed object to check ...
* @returns
*/
function isDescriptor(object) {
//
if (!object) {
return false;
}
//
let result = false;
result =
object.hasOwnProperty('raw') &&
object.hasOwnProperty('name') &&
object.hasOwnProperty('content') &&
object.hasOwnProperty('isExported');
//
return result;
}
/**
* retrieve base or filled TypeDescriptor object instance ...
*
* @param {any} value a value provider object ...
* @returns an instance of TypeDescriptor object ...
*/
function createDescriptor(value) {
//
let result = {
raw: '',
name: '',
content: '',
isExported: false,
};
//
//#region Apply Value ...
if (value) {
//
//#region raw ...
if (XValueTools.isValidArg(value.raw)) {
result.raw = value.raw;
}
//#endregion
//
//#region name ...
if (XValueTools.isValidArg(value.name)) {
result.name = value.name;
}
//#endregion
//
//#region content ...
if (XValueTools.isValidArg(value.content)) {
result.content = value.content;
}
//#endregion
//
//#region isExported ...
if (!!value.isExported) {
result.isExported = true;
}
//#endregion
}
//#endregion
//
return result;
}
/**
* converts an instance of Descriptor to Expression ...
*
* @param descriptor an instance of TypeDescriptor ...
* @returns creator string ...
*/
function toExpression(descriptor = createDescriptor()) {
//
let result = '';
//
// Validate Arg ...
if (!isDescriptor(descriptor)) {
return result;
}
//
result += (
!!descriptor.isExported ?
XBaseDescriptor.ExpressionKeys.Export + ' ' :
''
) +
XBaseDescriptor.ExpressionKeys.Type +
' ' +
descriptor.name +
' = ' +
descriptor.content
+ ';';
//
return result;
}
/**
* extract all exists TypeDescriptors ...
*
* @param {string} file a file path ...
* @returns a collection of TypeDescriptor ...
*/
async function extractDescriptors(file = '') {
//
if (!XFileTools.isFileExists(file)) {
return [];
}
//
const fileContent = await XFileTools.readFile(file);
if (!XValueTools.isValidArg(fileContent)) {
return [];
}
//
let result = [
createDescriptor()
];
result.pop();
//
result = extractDescriptorsFromContent(fileContent);
//
return result;
}
/**
* extract all exists TypeDescriptors ...
*
* @param {string} content a file content ...
* @returns a collection of TypeDescriptor ...
*/
function extractDescriptorsFromContent(content = '') {
//
// Prepare Result ...
let result = [
createDescriptor()
];
result.pop();
//
// Validate Args ...
if (
!XValueTools.isValidArg(content) ||
!content.includes(XBaseDescriptor.ExpressionKeys.Type)
) {
return result;
}
//
// Extract all key Indexes ...
const keyIndexes = XBaseDescriptor.
extractValidIdentifierIndexes(XBaseDescriptor.ExpressionKeys.Type, content);
//
// Validate them ...
if (!XValueTools.hasChildArray(keyIndexes)) {
return result;
}
//
// Loop through indexes ...
for (const index of keyIndexes) {
//
// Check Type after befre content ...
let startIndex = index - 1;
let endIndex = index + XBaseDescriptor.ExpressionKeys.Type.length + 1;
//
// create an empty instance of descriptor ...
let descriptor = {
...createDescriptor()
}
//
//#region Name extractor ...
const nameEndIndex = content.indexOf('=', index);
identifier = content
.substring(index + XBaseDescriptor.ExpressionKeys.Type.length, nameEndIndex)
.trim();
if (XValueTools.isValidArg(identifier)) {
descriptor.name = identifier;
}
//#endregion
//
//#region Extract isExported ...
const isExported = XBaseDescriptor.checkIsExported(index, content);
descriptor.isExported = isExported;
if (isExported) {
startIndex = index - XBaseDescriptor.ExpressionKeys.Export.length - 1;
}
//#endregion
//
//#region Extract raw content ...
identifier = content.substring(startIndex);
startIndex = 0;
endIndex = XValueTools.findNearestIndex(
[
';',
'{',
'\n'
]
, identifier
);
const nearestChar = identifier.charAt(endIndex);
if (nearestChar === '{') {
//
const closedItemsIndexes = XValueTools.findClosedContentIndexes('{', '}', identifier, endIndex);
if (!XValueTools.hasChildArray(closedItemsIndexes)) {
continue;
}
//
endIndex = closedItemsIndexes[0].end;
}
//
identifier = identifier
.substring(startIndex, endIndex)
.trim();
if (XValueTools.isValidArg(identifier)) {
descriptor.raw = identifier;
}
//#endregion
//
//#region Parse Content ...
startIndex = identifier.indexOf('=', 0);
identifier = identifier
.substring(startIndex + 1)
.trim();
identifier = XBaseDescriptor.clearContent(identifier);
if (XValueTools.isValidArg(identifier)) {
descriptor.content = identifier;
}
//#endregion
//
result.push(descriptor);
}
//
return result;
}
//
// Module Exports ...
module.exports = {
//
isDescriptor,
toExpression,
createDescriptor,
extractDescriptors,
extractDescriptorsFromContent,
}
@@ -0,0 +1,48 @@
'use strict';
//
const XElectronChannel = {
Default: 'xMessage',
Handshake: 'xHandshake',
FileService: 'xFileService',
ProjectsService: 'xProjectsService',
}
//
// Module Exports ...
module.exports = {
//
XElectronChannel: XElectronChannel,
//
XElectronMessage: class XElectronMessage {
//
constructor(
sender = '',
reciever = '',
message = '',
payload = undefined,
channel = undefined,
timestamp = undefined,
) {
//
if (!timestamp) {
timestamp = Date.now();
}
//
if (!channel) {
channel = XElectronChannel.Default;
}
//
this.sender = sender;
this.reciever = reciever;
this.payload = payload;
this.message = message;
this.timestamp = timestamp;
this.channel = channel;
}
}
}
@@ -0,0 +1,617 @@
const fs = require('fs');
const os = require('os');
const Path = require('path');
const XValueTools = require('./x-value.tools');
/**
* required folder names ...
*/
const FolderNames = {
Documents: 'Documents',
}
/**
* current os path separators ...
*/
const PathSeparator = Path.sep;
/**
* current directory ...
*/
const CurrentDir = __dirname;
//
//#region Global ...
/**
* retrieve a path status ...
*
* @param {string} path a path value to check ...
* @returns an stat object ...
*/
function getStatus(path = '') {
//
if (!XValueTools.isValidArg(path)) {
return undefined;
}
//
return fs.statSync(path);
}
/**
* retrieve user's Document path ...
*
* @returns a path ...
*/
function getDocumentsPath() {
return Path.join(os.homedir(), FolderNames.Documents);
}
/**
* retrieve user's Document contents ...
*
* @returns resources contents as string array ...
*/
function getDocumentsContents() {
return getDirectoryContents(getDocumentsPath());
}
//#endregion
//
//#region Path ...
/**
* retrieve the base name of specific address path ...
*
* @param {string} path address of file or folder ...
* @returns string ...
*/
function basename(path = '') {
//
if (!XValueTools.isValidArg(path)) {
return '';
}
//
const result = Path.basename(path);
return result;
}
/**
* join several path segments together ...
*
* @param {...string} path path params ...
* @returns a joined paths ...
*/
function joinPath(...path) {
return Path.join(...path);
}
//#endregion
//
//#region File ...
/**
* determines a path destination is a file or not ...
*
* @param {string} path a path value to check ...
* @returns a boolean value ...
*/
function isFileExists(path = '') {
//
if (!XValueTools.isValidArg(path)) {
return false;
}
//
try {
const stat = getStatus(path);
if (!stat) {
return false;
}
//
return stat.isFile();
} catch {
return false;
}
}
/**
* remove a file ...
*
* @param {string} path a file path ...
* @returns {Promise<boolean>} action done or not ...
*/
function removeFile(path = '') {
return new Promise((resolve) => {
//
if (!isFileExists(path)) {
resolve(false);
}
//
fs.unlink(path, (err) => {
//
if (err) {
resolve(false);
return;
}
//
resolve(true);
});
});
}
/**
* copy a file to destination path ...
*
* @param {string} source source file path ...
* @param {string} dest dest folder path ...
* @returns {Promise<boolean>} action done or not ...
*/
function copyFile(
source = '',
dest = ''
) {
return new Promise((resolve) => {
//
if (
!isFileExists(source) ||
!isDirectoryExists(dest)
) {
resolve(false);
return;
}
//
const destFilePath = Path.join(dest, Path.basename(source));
fs.copyFile(source, destFilePath, (err) => {
//
if (err) {
resolve(false);
return;
}
//
resolve(true);
});
});
}
/**
* reading specified file content ...
*
* @param {string} path a file path ...
* @returns {Promise<string>} file content ...
*/
function readFile(path = '') {
return new Promise((resolve) => {
//
if (!isFileExists(path)) {
resolve('');
return;
}
//
fs.readFile(path, 'utf8', (err, content) => {
//
if (err) {
resolve(undefined);
return;
}
//
resolve(content);
});
});
}
/**
* write content to a file ...
*
* @param {string} path a file path ...
* @param {string} content the content which going to write to the file ...
* @param {bool} overwrite determines file overwrite if exists ...
* @returns {Promise<boolean>} action done or not ...
*/
function writeFile(
path = '',
content = '',
overwrite = true
) {
return new Promise((resolve) => {
//
if (isFileExists(path) && !overwrite) {
//
resolve(false);
return;
}
//
// Normalize Content ...
content = XValueTools.isValidArg(content) ?
content :
'';
//
fs.writeFile(path, content, (err) => {
//
if (err) {
//
resolve(false);
return;
}
//
resolve(true);
});
});
}
/**
* create a file ...
*
* @param {string} path file path ...
* @param {string} fileName file name ...
* @returns {Promise<boolean>} action done or not ...
*/
function createFile(
path = '',
fileName = ''
) {
return new Promise((resolve) => {
//
const filePath = Path.join(path, fileName);
if (
isFileExists(filePath) ||
!XValueTools.isValidArg(path) ||
!XValueTools.isValidArg(fileName)
) {
//
resolve(false);
return;
}
//
fs.writeFile(filePath, '', (err) => {
//
if (err) {
//
resolve(false);
return;
}
//
resolve(true);
});
});
}
/**
* remove a file name extension ...
*
* @param {string} name
* @returns {string} name without extension ...
*/
function removeFileExtension(name = '') {
return name.substring(0, name.lastIndexOf('.')) || name;
}
//#endregion
//
//#region Directory ...
/**
* create a directory ...
*
* @param {string} path destination path including dir name ...
* @param {boolean} recursive create directories recursively ...
* @returns action done or not ...
*/
function createDirectory(
path = '',
recursive = true
) {
//
let result = false;
//
if (
isDirectoryExists(path) ||
!XValueTools.isValidArg(path)
) {
return false;
}
//
try {
//
fs.mkdirSync(path, { recursive: recursive });
result = true;
return result;
} catch {
return false;
}
}
/**
* remove a directory ...
*
* @param {string} path destination path including dir name ...
* @param {boolean} recursive removes directories recursively ...
* @returns {Promise<boolean>} action done or not ...
*/
function removeDirectory(
path = '',
recursive = false
) {
return new Promise((resolve) => {
//
if (!isDirectoryExists(path)) {
resolve(false);
return;
}
//
fs.rm(path, {
recursive
}, (err) => {
//
if (err) {
resolve(false);
return;
}
//
resolve(true);
});
});
}
/**
* determines a path destination is a directory or not ...
*
* @param {string} path a folder path ...
* @returns represent destnation path is Directory or not ...
*/
function isDirectoryExists(path = '') {
//
if (!XValueTools.isValidArg(path)) {
return false;
}
//
try {
//
const isExists = fs.existsSync(path);
if (!isExists) {
return false;
}
//
const stat = getStatus(path);
if (!stat) {
return false;
}
//
const result = stat.isDirectory();
return result;
} catch {
return false;
}
}
/**
* retrieve a directory content ...
*
* @param {string} path a folder path ...
* @returns {Promise<string[]>} a collection of folder files ...
*/
function getDirectoryContents(path = '') {
return new Promise((resolve) => {
//
if (!isDirectoryExists(path)) {
resolve([]);
return;
}
//
fs.readdir(path, (err, content) => {
//
if (err) {
resolve([]);
return;
}
//
resolve(content);
});
});
}
/**
* retrieve a directory files ...
*
* @param {string} path a folder path ...
* @returns {Promise<string[]>} a collection of folder files ...
*/
function getDirectoryFiles(
path = '',
containsHiddenFiles = false
) {
return new Promise((resolve) => {
//
if (!isDirectoryExists(path)) {
resolve([]);
return;
}
//
fs.readdir(path, (err, content) => {
//
if (err) {
resolve([]);
return;
}
//
if (!containsHiddenFiles) {
content = content.filter(c => !c.startsWith('.'))
}
//
const result = [];
content
.forEach(c => {
//
const cPath = Path.join(path, c);
if (isFileExists(cPath)) {
result.push(c);
}
});
//
resolve(result);
});
});
}
/**
* retrieve a directory folders ...
*
* @param {string} path a folder path ...
* @returns {Promise<string[]>} a collection of folder names ...
*/
function getDirectoryFolders(path = '') {
return new Promise((resolve) => {
//
if (!isDirectoryExists(path)) {
resolve([]);
return;
}
//
fs.readdir(path, (err, content) => {
//
if (err) {
resolve([]);
return;
}
//
const result = [];
content.forEach(c => {
//
const cPath = Path.join(path, c);
if (isDirectoryExists(cPath)) {
result.push(c);
}
});
//
resolve(result);
});
});
}
/**
* copy a folder with all of it's content to dest ...
*
* @param {string} source source folder path ...
* @param {string} dest dest folder path ...
* @returns {Promise<boolean>} action done or not ...
*/
async function copyFolder(
source = '',
dest = ''
) {
//
if (
!isDirectoryExists(source) ||
!XValueTools.isValidArg(dest) ||
!XValueTools.isValidArg(source)
) {
return false;
}
//
const folderName = Path.basename(source);
const destPath = Path.join(dest, folderName);
//
// Create Dest Path folder if not exists ...
if (!isDirectoryExists(destPath)) {
//
let result = createDirectory(destPath, true);
if (!result) {
return false;
}
}
//
// Files ...
const files = await getDirectoryFiles(source);
if (files && files.constructor === Array && files.length > 0) {
//
const filesPromises = files.map(file => copyFile(Path.join(source, file), destPath));
const filesResult = (await Promise.all(filesPromises)).every(r => !!r);
if (!filesResult) {
return false;
}
}
//
// Folders ...
const folders = await getDirectoryFolders(source);
if (folders && folders.constructor === Array && folders.length > 0) {
//
const folderPromises = folders.map(folder => copyFolder(Path.join(source, folder), destPath));
const filesResult = (await Promise.all(folderPromises)).every(r => !!r);
if (!filesResult) {
return false;
}
}
//
return true;
}
//#endregion
//
// Module Exports ...
module.exports = {
//
CurrentDir,
FolderNames,
PathSeparator,
//
getStatus,
getDocumentsPath,
getDocumentsContents,
//
basename,
joinPath,
//
copyFile,
readFile,
writeFile,
createFile,
removeFile,
isFileExists,
removeFileExtension,
//
copyFolder,
createDirectory,
removeDirectory,
createDirectory,
removeDirectory,
isDirectoryExists,
isDirectoryExists,
getDirectoryFiles,
getDirectoryFolders,
getDirectoryContents,
}
@@ -0,0 +1,187 @@
const baseLogTag = 'XFrameworkElectronApp';
let enableLogging = true;
/**
* Log Tags ...
*/
const XLogTag = {
Debug: 'debug',
Info: 'info',
Warn: 'warn',
Error: 'error'
};
/**
* retrieve an instance of XLogMessage ...
*
* @param {string} tag tag of logging ...
* @param {string} message content of log message ...
* @param {array of any} args args of content which required to logging ...
* @param {number} timestamp logging time ...
*
* @returns an instance of log message object ...
*/
function XLogMessage(tag, message, args, timestamp) {
//
if (!tag) {
throw 'Tag not provided ...';
}
//
if (!message) {
throw 'Message not provided ...';
}
//
if (!args) {
args = [];
}
//
if (!timestamp) {
timestamp = new Date().getTime();
}
//
return {
tag,
message,
args,
timestamp,
};
}
/**
* log data ...
*
* @param {XLogMessage} message
*/
function log(message) {
//
if (!message || !message.tag || !message.message || !enableLogging) {
return;
}
//
message.timestamp = new Date().getTime();
//
switch (message.tag) {
//
case XLogTag.Debug:
logDebug(message);
break;
//
case XLogTag.Info:
logInfo(message);
break;
//
case XLogTag.Warn:
logWarn(message);
break;
//
case XLogTag.Error:
logError(message);
break;
//
default:
break;
}
}
/**
* Log Debug ...
*
* @param {XLogMessage} message
*/
function logDebug(message) {
//
if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Debug) {
return;
}
//
message.timestamp = new Date().getTime();
//
console.debug(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args);
}
/**
* Log Info ...
*
* @param {XLogMessage} message
*/
function logInfo(message) {
//
if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Info) {
return;
}
//
message.timestamp = new Date().getTime();
//
console.info(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args);
}
/**
* Log Warn ...
*
* @param {XLogMessage} message
*/
function logWarn(message) {
//
if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Warn) {
return;
}
//
message.timestamp = new Date().getTime();
//
console.warn(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args);
}
/**
* Log Error ...
*
* @param {XLogMessage} message
*/
function logError(message) {
//
if (!message || !message.message || !enableLogging || message.tag !== XLogTag.Error) {
return;
}
//
message.timestamp = new Date().getTime();
//
console.error(`${baseLogTag}:${message.tag} => ${message.message}`, ...message.args);
}
//
// Module Eports ...
module.exports = {
//
enableLogging: () => {
enableLogging = true;
},
disableLogging: () => {
enableLogging = false;
},
isLoggingEnable: () => {
return enableLogging;
},
//
XLogTag: XLogTag,
XLogMessage: XLogMessage,
log: log,
logDebug: logDebug,
logInfo: logInfo,
logWarn: logWarn,
logError: logError,
}
@@ -0,0 +1,203 @@
//
//#region Imports ...
const os = require('os');
const process = require('process');
const { exec } = require("child_process");
const XFileTools = require('../tools/x-file.tools');
//#endregion
//
//#region Constants ...
//
const OS = {
Aix: 'aix',
Darwin: 'darwin',
FreeBSD: 'freebsd',
Linux: 'linux',
OpenBSD: 'openbsd',
SnOS: 'sunos',
Windows: 'win32'
}
//
const isWindows = process.platform === OS.Windows;
//#endregion
//
//#region Actions ...
//
//#region Pure shell commands ...
/**
* execute a command using NodeJS on shell ...
*
* @param {string} cmd command to execute ...
* @param {string} cwd working directory ...
*
* @returns Promise<any, errr> instance ...
*/
function execute(cmd, cwd) {
return new Promise((resolve, reject) => {
//
if (!cmd || cmd.toString().length === 0 || (cwd && !XFileTools.isDirectoryExists(cwd))) {
reject('invalid args ...');
return;
}
//
exec(cmd, { cwd }, (err, result, stdError) => {
//
if (err) {
reject(err);
return;
}
//
if (stdError) {
//
// reject(stdError);
// return;
}
//
resolve(result);
});
});
};
/**
* determines a command exists on host or not ...
*
* @param {string} name specific command name ...
*
* @returns boolean Promise ...
*/
function checkCommandExists(name) {
return new Promise(resolve => {
//
if (!name) {
resolve(false);
return;
}
//
const cmd = isWindows ? `${name} >nul 2>&1` : `type ${name} >/dev/null 2>&1`;
execute(cmd).then(result => {
resolve(true);
})
.catch(err => {
resolve(false);
});
});
}
//#endregion
//
//#region required commands state ...
/**
* check al required commands exists or not ...
*
* @returns
*/
async function isRequiredCommandsExists() {
//
let result = false;
//
// const isTarExists = await isTarCommandExists();
// const isCatExists = await isCatCommandExists();
// const isGrepExists = await isGrepCommandExists();
// const isSedExists = await isSedCommandExists();
// const isNpmExists = await isNpmCommandExists();
const isNgExists = await isNgCommandExists();
const isIonicExists = await isIonicCommandExists();
const isCordovaExists = await isCordovaCommandExists();
//
result = isNgExists &&
isIonicExists &&
isCordovaExists;
//
return result;
}
/**
* retrieve required commands state object ...
*
* @returns
*/
async function getRequiredCommandsStates() {
//
const result = {};
//
// const isTarExists = await isTarCommandExists();
// const isCatExists = await isCatCommandExists();
// const isGrepExists = await isGrepCommandExists();
// const isSedExists = await isSedCommandExists();
// const isNpmExists = await isNpmCommandExists();
const isNgExists = await isNgCommandExists();
const isIonicExists = await isIonicCommandExists();
const isCordovaExists = await isCordovaCommandExists();
//
result['ng'] = isNgExists;
result['ionic'] = isIonicExists;
result['cordova'] = isCordovaExists;
//
return result;
}
//#endregion
//
//#region Commonly used Command Checkers ...
/**
* determines ng command exists or not ...
*
* @returns
*/
function isNgCommandExists() {
return checkCommandExists('ng');
}
/**
* determines ionic command exists or not ...
*
* @returns
*/
function isIonicCommandExists() {
return checkCommandExists('ionic');
}
/**
* determines cordova command exists or not ...
*
* @returns
*/
function isCordovaCommandExists() {
return checkCommandExists('cordova');
}
//#endregion
//#endregion
//
// Module Exports ...
module.exports = {
//
execute,
checkCommandExists,
isRequiredCommandsExists,
getRequiredCommandsStates,
//
// isFxCommandExists,
// isTarCommandExists,
// isCatCommandExists,
// isSedCommandExists,
// isNpmCommandExists,
// isGrepCommandExists,
isNgCommandExists,
isIonicCommandExists,
isCordovaCommandExists,
}
@@ -0,0 +1,252 @@
/**
* all supported data types ...
*/
const DataTypes = {
Null: 'null',
Date: 'date',
Array: 'array',
Object: 'object',
String: 'string',
Number: 'number',
Unknown: 'unknown',
Boolean: 'boolean',
Function: 'function',
Undefined: 'undefined',
};
/**
* detect type of a content ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function getType(value) {
//
const type = typeof value;
//
let result = DataTypes.Unknown;
let dateIdentifier = '[object Date]';
let constructor = value && value.constructor ?
value.constructor.toString() :
'';
//
switch (type) {
//
case 'undefined':
result = DataTypes.Undefined;
break;
//
case 'boolean':
result = DataTypes.Boolean;
break;
//
case 'string':
result = DataTypes.String;
break;
//
case 'number':
result = DataTypes.Number;
break;
//
case 'function':
result = DataTypes.Function;
break;
//
case 'object':
//
// Null ...
if (value === null) {
result = DataTypes.Null;
} else
//
// Array ...
if (Array.isArray(value)) {
result = DataTypes.Array;
} else
//
// Data ...
if (
value instanceof Date ||
isFunction(value.getMonth) ||
constructor.includes(dateIdentifier) ||
Object.prototype.toString.call(value) === dateIdentifier
) {
result = DataTypes.Date;
} else
//
// Object ...
{
result = DataTypes.Object;
}
break;
//
default:
result = DataTypes.Unknown;
break;
}
//
return result;
}
/**
* retrieve an object constructor ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function getConstructor(value) {
//
const result = value && value.constructor ?
value.constructor.toString() :
'';
//
return result;
}
/**
* retrieve an object prototype ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function getPrototype(value) {
//
const result = value ?
Object.prototype.toString.call(value) :
'';
//
return result;
}
/**
* check an object is null or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isNull(value) {
return getType(value) === DataTypes.Null;
}
/**
* check an object is undefined or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isUndefined(value) {
return getType(value) === DataTypes.Undefined;
}
/**
* check an object is null or undefined or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isNullOrUndefined(value) {
return isNull(value) || isUndefined(value);
}
/**
* check an object is a date or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isDate(value) {
return getType(value) === DataTypes.Date;
}
/**
* check an object is number or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isNumber(value) {
return getType(value) === DataTypes.Number;
}
/**
* check an object is string or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isString(value) {
return getType(value) === DataTypes.String;
}
/**
* check an object is boolean or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isBoolean(value) {
return getType(value) === DataTypes.Boolean;
}
/**
* check an object is an Array or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isArray(value) {
return getType(value) === DataTypes.Array;
}
/**
* check an object is and Object or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isObject(value) {
return getType(value) === DataTypes.Object;
}
/**
* check an object is a Function or not ...
*
* @param {any} value the content which going to check ...
* @returns
*/
function isFunction(value) {
return getType(value) === DataTypes.Function;
}
//
// Module Exports ...
module.exports = {
//
DataTypes,
//
getType,
getConstructor,
getPrototype,
isNull,
isUndefined,
isNullOrUndefined,
isDate,
isNumber,
isString,
isBoolean,
isArray,
isObject,
isFunction,
}
@@ -0,0 +1,37 @@
//
//#region Imports ...
const uuid = require("uuid");
//#endregion
//
//#region Constants ...
const DEFAULT_NAMESPACE = "SaherElm IT Center";
//#endregion
/**
* generate a uniqu identifier ...
*
* @param {string} prefix the prefix of generated uuid ...
* @param {string} content the additional content which added to generated uuid ...
* @param {string} nameSpace the proposed name space for generating uuid ...
* @returns a unique universal uuid ...
*/
function generateUuid(
prefix,
content,
nameSpace = DEFAULT_NAMESPACE
) {
//
const uId = content ? uuid.v5(content, nameSpace) : uuid.v4();
const result = prefix ? `${prefix}_${uId}` : uId;
//
return result;
}
//
// Module Exports ...
module.exports = {
DEFAULT_NAMESPACE,
generateUuid,
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,125 @@
/**
* main storage object ...
*/
const windows = {};
/**
* retrieve all exists window id's ...
*
* @returns an array of strings which represents window id's ...
*/
function keys() {
return Object.keys(windows);
}
/**
* retrieve all available windows ...
*
* @returns an array of strings which represent BrowserWindow Objects ...
*/
function values() {
return Object.values(windows);
}
/**
* retrieve count of available windows ...
*
* @returns number
*/
function count() {
return Object.keys(windows).length;
}
/**
* check a BrowserWindow id exists or not ...
*
* @param {string} key window id ...
* @returns a boolean value which represent window exists or not ...
*/
function has(key) {
//
if (!key) {
return false;
}
//
return keys()
.includes(key);
}
/**
* retrieve a window by providing it's id ...
*
* @param {string} key window id ...
* @returns an instance of Browserwindow instance ...
*/
function get(key) {
//
if (!has(key)) {
return undefined;
}
//
return windows[key];
}
/**
* set a window by it's id ...
*
* @param {string} key window id ...
* @param {BrowserWindow} value specified window instance ...
* @returns a boolean value ...
*/
function set(key, value) {
//
try {
windows[key] = value;
return true;
} catch {
return false;
}
}
/**
* remove a key/value from windows ...
*
* @param {string} key window id ...
* @returns a boolean value ...
*/
function remove(key) {
//
if (!has(key)) {
return false;
}
//
try {
//
delete windows[key];
return true;
} catch {
return false;
}
}
/**
* clear all registered objects ...
*/
function clear() {
windows = {};
}
module.exports = {
//
windows: windows,
//
has: has,
get: get,
set: set,
keys: keys,
count: count,
clear: clear,
values: values,
remove: remove,
}
+37
View File
@@ -0,0 +1,37 @@
{
"name": "x-mabsut-client",
"version": "1.0.0",
"description": "Mabsut CLient application",
"homepage": "https://mabsut.ir",
"author": {
"name": "Hadi Khazaee Asl",
"email": "hadi_khazaee_asl@yahoo.com",
"url": "https://saherelm.ir"
},
"keywords": [
"x-mabsut",
"x-framework",
"saherelm"
],
"scripts": {
"true": "",
"startElectron": "electron .",
"rmWWW": "shx --silent rm -rf ./www",
"prepareElectron": "npm run rmWWW && shx --silent cp -r ../../dist/xClient ./www",
"runElectron": "npm run rmWWW && cd .. && cd .. && npm run build && cd platforms/electron && npm run prepareElectron && npm run startElectron",
"runProdElectron": "cd .. && cd .. && npm run buildProd && cd platforms/electron && npm run prepareElectron && npm run startElectron",
"buildElectronWin32": "cd .. && cd .. && npm run buildProd && cd platforms/electron && npm run prepareElectron && electron-packager . --platform=win32 --arch=ia32 --icon=www/assets/icon/favicon.ico --overwrite --prune=true --out=dist",
"buildElectronWin64": "cd .. && cd .. && npm run buildProd && cd platforms/electron && npm run prepareElectron && electron-packager . --platform=win32 --arch=x64 --icon=www/assets/icon/favicon.ico --overwrite --prune=true --out=dist",
"buildElectronMac64": "cd .. && cd .. && npm run buildProd && cd platforms/electron && npm run prepareElectron && electron-packager . --platform=darwin --arch=x64 --icon=www/assets/icon/favicon.icns --overwrite --prune=true --out=dist",
"buildElectronLinux64": "cd .. && cd .. && npm run buildProd && cd platforms/electron && npm run prepareElectron && electron-packager . --platform=linux --arch=x64 --icon=www/assets/icon/favicon.png --overwrite --prune=true --out=dist"
},
"devDependencies": {
"electron-packager": "^15.3.0",
"uuid": "^8.3.2",
"shx": "^0.3.3"
},
"dependencies": {
"electron": "^13.1.7"
},
"main": "app.electron.js"
}
+31
View File
@@ -0,0 +1,31 @@
{
"prepare_queue": {
"installed": [],
"uninstalled": []
},
"config_munge": {
"files": {}
},
"installed_plugins": {
"cordova-plugin-device": {
"PACKAGE_NAME": "ir.saherelm.xFramework.xFramework"
},
"cordova-plugin-ionic-keyboard": {
"PACKAGE_NAME": "ir.saherelm.xFramework.xFramework"
},
"cordova-plugin-ionic-webview": {
"ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+",
"PACKAGE_NAME": "ir.saherelm.xFramework.xFramework"
},
"cordova-plugin-splashscreen": {
"PACKAGE_NAME": "ir.saherelm.xFramework.xFramework"
},
"cordova-plugin-statusbar": {
"PACKAGE_NAME": "ir.saherelm.xFramework.xFramework"
},
"cordova-plugin-whitelist": {
"PACKAGE_NAME": "ir.saherelm.xFramework.xFramework"
}
},
"dependent_plugins": {}
}
@@ -0,0 +1,28 @@
# appveyor file
# http://www.appveyor.com/docs/appveyor-yml
max_jobs: 1
shallow_clone: true
init:
- git config --global core.autocrlf true
image:
- Visual Studio 2017
environment:
nodejs_version: "4"
matrix:
- PLATFORM: windows-10-store
JUST_BUILD: --justBuild
install:
- npm cache clean -f
- node --version
- npm install -g cordova-paramedic@https://github.com/apache/cordova-paramedic.git
- npm install -g cordova
build: off
test_script:
- cordova-paramedic --config pr\%PLATFORM% --plugin . %JUST_BUILD%
@@ -0,0 +1,10 @@
root: true
extends: semistandard
rules:
indent:
- error
- 4
camelcase: off
padded-blocks: off
operator-linebreak: off
no-throw-literal: off
@@ -0,0 +1,22 @@
<!--
Please make sure the checklist boxes are all checked before submitting the PR. The checklist
is intended as a quick reference, for complete details please see our Contributor Guidelines:
http://cordova.apache.org/contribute/contribute_guidelines.html
Thanks!
-->
### Platforms affected
### What does this PR do?
### What testing has been done on this change?
### Checklist
- [ ] [Reported an issue](http://cordova.apache.org/contribute/issues.html) in the JIRA database
- [ ] Commit message follows the format: "CB-3232: (android) Fix bug with resolving file paths", where CB-xxxx is the JIRA ID & "android" is the platform affected.
- [ ] Added automated test coverage as appropriate for this change.
+23
View File
@@ -0,0 +1,23 @@
#If ignorance is bliss, then somebody knock the smile off my face
*.csproj.user
*.suo
*.cache
Thumbs.db
*.DS_Store
*.bak
*.cache
*.log
*.swp
*.user
node_modules
+87
View File
@@ -0,0 +1,87 @@
sudo: false
addons:
jwt:
secure: egTo2EERSKVWdBoP+6ewd/JIyyly2XTT1xOVj27v2L148c453uRNPjXwiGRYu7vTw5rkGK+H54n4FG3rUOuEVNX9NDNC5TlkhTfmecXNzjyOIuV7xD0qg5s6Q3IXg8kAp9+JXWbVVR6hoPzmAAnTT4rcoh6cPg4Tf327W2sRGkw=
env:
global:
- SAUCE_USERNAME=snay
- TRAVIS_NODE_VERSION="4.2"
matrix:
include:
- env: PLATFORM=browser-chrome
os: linux
language: node_js
node_js: '4.2'
- env: PLATFORM=browser-firefox
os: linux
language: node_js
node_js: '4.2'
- env: PLATFORM=browser-safari
os: linux
language: node_js
node_js: '4.2'
- env: PLATFORM=browser-edge
os: linux
language: node_js
node_js: '4.2'
- env: PLATFORM=ios-9.3
os: osx
osx_image: xcode7.3
language: node_js
node_js: '4.2'
- env: PLATFORM=ios-10.0
os: osx
osx_image: xcode7.3
language: node_js
node_js: '4.2'
- env: PLATFORM=android-4.4
os: linux
language: android
jdk: oraclejdk8
android:
components:
- tools
- build-tools-26.0.2
- env: PLATFORM=android-5.1
os: linux
language: android
jdk: oraclejdk8
android:
components:
- tools
- build-tools-26.0.2
- env: PLATFORM=android-6.0
os: linux
language: android
jdk: oraclejdk8
android:
components:
- tools
- build-tools-26.0.2
- env: PLATFORM=android-7.0
os: linux
language: android
jdk: oraclejdk8
android:
components:
- tools
- build-tools-26.0.2
before_install:
- rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm
&& git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm
install $TRAVIS_NODE_VERSION
- node --version
- if [[ "$PLATFORM" =~ android ]]; then gradle --version; fi
- if [[ "$PLATFORM" =~ ios ]]; then npm install -g ios-deploy; fi
- if [[ "$PLATFORM" =~ android ]]; then echo y | android update sdk -u --filter android-22,android-23,android-24,android-25,android-26;
fi
- git clone https://github.com/apache/cordova-paramedic /tmp/paramedic && pushd /tmp/paramedic
&& npm install && popd
- npm install -g cordova
install:
- npm install
script:
- npm test
- node /tmp/paramedic/main.js --config pr/$PLATFORM --plugin $(pwd) --shouldUseSauce
--buildName travis-plugin-device-$TRAVIS_JOB_NUMBER
@@ -0,0 +1,37 @@
<!--
#
# 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.
#
-->
# 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!
+202
View File
@@ -0,0 +1,202 @@
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.
+5
View File
@@ -0,0 +1,5 @@
Apache Cordova
Copyright 2012 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).
+267
View File
@@ -0,0 +1,267 @@
---
title: Device
description: Get device information.
---
<!--
# license: 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.
-->
|AppVeyor|Travis CI|
|:-:|:-:|
|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-device?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-device)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)|
# cordova-plugin-device
This plugin defines a global `device` object, which describes the device's hardware and software.
Although the object is in the global scope, it is not available until after the `deviceready` event.
```js
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
```
Report issues with this plugin 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%20Device%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)
## Installation
cordova plugin add cordova-plugin-device
## Properties
- device.cordova
- device.model
- device.platform
- device.uuid
- device.version
- device.manufacturer
- device.isVirtual
- device.serial
## device.cordova
Get the version of Cordova running on the device.
### Supported Platforms
- Android
- Browser
- iOS
- Windows
- OSX
## device.model
The `device.model` returns the name of the device's model or
product. The value is set by the device manufacturer and may be
different across versions of the same product.
### Supported Platforms
- Android
- Browser
- iOS
- Windows
- OSX
### Quick Example
```js
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models
// OSX: returns "x86_64"
//
var model = device.model;
```
### Android Quirks
- Gets the [product name](http://developer.android.com/reference/android/os/Build.html#PRODUCT) instead of the [model name](http://developer.android.com/reference/android/os/Build.html#MODEL), which is often the production code name. For example, the Nexus One returns `Passion`, and Motorola Droid returns `voles`.
## device.platform
Get the device's operating system name.
```js
var string = device.platform;
```
### Supported Platforms
- Android
- Browser
- iOS
- Windows
- OSX
### Quick Example
```js
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - "browser"
// - "iOS"
// - "WinCE"
// - "Tizen"
// - "Mac OS X"
var devicePlatform = device.platform;
```
## device.uuid
Get the device's Universally Unique Identifier ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)).
```js
var string = device.uuid;
```
### Description
The details of how a UUID is generated are determined by the device manufacturer and are specific to the device's platform or model.
### Supported Platforms
- Android
- iOS
- Windows
- OSX
### Quick Example
```js
// Android: Returns a random 64-bit integer (as a string, again!)
// The integer is generated on the device's first boot
//
// BlackBerry: Returns the PIN number of the device
// This is a nine-digit unique integer (as a string, though!)
//
// iPhone: (Paraphrased from the UIDevice Class documentation)
// Returns the [UIDevice identifierForVendor] UUID which is unique and the same for all apps installed by the same vendor. However the UUID can be different if the user deletes all apps from the vendor and then reinstalls it.
// Windows Phone 7 : Returns a hash of device+current user,
// if the user is not defined, a guid is generated and will persist until the app is uninstalled
// Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number
// unique to every GSM and UMTS mobile phone.
var deviceID = device.uuid;
```
### iOS Quirk
The `uuid` on iOS uses the identifierForVendor property. It is unique to the device across the same vendor, but will be different for different vendors and will change if all apps from the vendor are deleted and then reinstalled.
Refer [here](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDevice_Class/#//apple_ref/occ/instp/UIDevice/identifierForVendor) for details.
The UUID will be the same if app is restored from a backup or iCloud as it is saved in preferences. Users using older versions of this plugin will still receive the same previous UUID generated by another means as it will be retrieved from preferences.
### OSX Quirk
The `uuid` on OSX is generated automatically if it does not exist yet and is stored in the `standardUserDefaults` in the `CDVUUID` property.
## device.version
Get the operating system version.
var string = device.version;
### Supported Platforms
- Android 2.1+
- Browser
- iOS
- Windows
- OSX
### Quick Example
```js
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Windows 8: return the current OS version, ex on Windows 8.1 returns 6.3.9600.16384
// Tizen: returns "TIZEN_20120425_2"
// OSX: El Capitan would return "10.11.2"
//
var deviceVersion = device.version;
```
## device.manufacturer
Get the device's manufacturer.
var string = device.manufacturer;
### Supported Platforms
- Android
- iOS
- Windows
### Quick Example
```js
// Android: Motorola XT1032 would return "motorola"
// BlackBerry: returns "BlackBerry"
// iPhone: returns "Apple"
//
var deviceManufacturer = device.manufacturer;
```
## device.isVirtual
whether the device is running on a simulator.
```js
var isSim = device.isVirtual;
```
### Supported Platforms
- Android 2.1+
- Browser
- iOS
- Windows
- OSX
### OSX and Browser Quirk
The `isVirtual` property on OS X and Browser always returns false.
## device.serial
Get the device hardware serial number ([SERIAL](http://developer.android.com/reference/android/os/Build.html#SERIAL)).
```js
var string = device.serial;
```
### Supported Platforms
- Android
- OSX
@@ -0,0 +1,181 @@
<!--
#
# 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.
#
-->
# Release Notes
### 2.0.2 (Apr 12, 2018)
* [CB-13893](https://issues.apache.org/jira/browse/CB-13893) **iOS** delete `libz.tbd` from device plugin
### 2.0.1 (Dec 27, 2017)
* [CB-13702](https://issues.apache.org/jira/browse/CB-13702) Fix to allow 2.0.0 version install
### 2.0.0 (Dec 15, 2017)
* [CB-13670](https://issues.apache.org/jira/browse/CB-13670) Remove deprecated platforms
### 1.1.7 (Nov 06, 2017)
* [CB-13472](https://issues.apache.org/jira/browse/CB-13472) (CI) Fixed Travis **Android** builds again
* [CB-12895](https://issues.apache.org/jira/browse/CB-12895) setup `eslint` and removed `jshint`
* [CB-13113](https://issues.apache.org/jira/browse/CB-13113) (browser) `device.isVirtual` is always false
* [CB-13028](https://issues.apache.org/jira/browse/CB-13028) (CI) **Browser** builds on Travis and AppVeyor
* [CB-13000](https://issues.apache.org/jira/browse/CB-13000) (CI) Speed up **Android** builds
* [CB-12847](https://issues.apache.org/jira/browse/CB-12847) added `bugs` entry to `package.json`.
### 1.1.6 (Apr 27, 2017)
* [CB-12622](https://issues.apache.org/jira/browse/CB-12622) Added **Android 6.0** build badge to `README`
* [CB-12685](https://issues.apache.org/jira/browse/CB-12685) added `package.json` to tests folder
* [CB-12105](https://issues.apache.org/jira/browse/CB-12105) (browser) Properly detect Edge
### 1.1.5 (Feb 28, 2017)
* [CB-12353](https://issues.apache.org/jira/browse/CB-12353) Corrected merges usage in `plugin.xml`
* [CB-12369](https://issues.apache.org/jira/browse/CB-12369) Add plugin typings from `DefinitelyTyped`
* [CB-12363](https://issues.apache.org/jira/browse/CB-12363) Added build badges for **iOS 9.3** and **iOS 10.0**
* [CB-12230](https://issues.apache.org/jira/browse/CB-12230) Removed **Windows 8.1** build badges
### 1.1.4 (Dec 07, 2016)
* [CB-12224](https://issues.apache.org/jira/browse/CB-12224) Updated version and RELEASENOTES.md for release 1.1.4
* [CB-11917](https://issues.apache.org/jira/browse/CB-11917) - Remove pull request template checklist item: "iCLA has been submitted…"
* [CB-11832](https://issues.apache.org/jira/browse/CB-11832) Incremented plugin version.
### 1.1.3 (Sep 08, 2016)
* [CB-11795](https://issues.apache.org/jira/browse/CB-11795) Add 'protective' entry to cordovaDependencies
* Add badges for paramedic builds on Jenkins
* Add pull request template.
* Readme: Add fenced code blocks with langauage hints
* [CB-10996](https://issues.apache.org/jira/browse/CB-10996) Adding front matter to `README.md`
### 1.1.2 (Apr 15, 2016)
* Use passed device, follow create policy forf `CFUUIDCreate`
* [CB-10631](https://issues.apache.org/jira/browse/CB-10631) Fix for `device.uuid` in **iOS 5.1.1**
* Updating the comment to exclude URL
* [CB-10636](https://issues.apache.org/jira/browse/CB-10636) Add `JSHint` for plugins
* Refactored `deviceInfo` on **iOS** for better readability.
### 1.1.1 (Jan 15, 2016)
* [CB-10238](https://issues.apache.org/jira/browse/CB-10238) **OSX** Move `device-plugin` out from `cordovalib` to the plugin repository
* [CB-9923](https://issues.apache.org/jira/browse/CB-9923) Update `device.platform` documentation for **Browser** platform
### 1.1.0 (Nov 18, 2015)
* [CB-10035](https://issues.apache.org/jira/browse/CB-10035) Updated `RELEASENOTES` to be newest to oldest
* Add `isVirtual` for **Windows Phone 8.x**
* Added basic **Android** support for hardware serial number
* [CB-9865](https://issues.apache.org/jira/browse/CB-9865) Better simulator detection for **iOS**
* Fixing contribute link.
* Added **WP8** implementation
* update to use `TARGET_OS_SIMULATOR` as `TARGET_IPHONE_SIMULATOR` is deprecated.
* update code to use 'isVirtual'
* create test to verify existence and type of new property 'isVirtual'
* add `isSimulator` for **iOS** & **Android** device
* Updated documentation to mention backwards compatibility
* Updated **README** to reflect new behaviour and quirks on **iOS**
* Check user defaults first to maintain backwards compatibility
* Changed `UUID` to use `[UIDevice identifierForVendor]`
### 1.0.1 (Jun 17, 2015)
* [CB-9128](https://issues.apache.org/jira/browse/CB-9128) cordova-plugin-device documentation translation: cordova-plugin-device
* Attempts to corrent npm markdown 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
* Use TRAVIS_BUILD_DIR, install paramedic by npm
* [CB-8653](https://issues.apache.org/jira/browse/CB-8653) Updated Readme
* remove defunct windows8 version
* add travis badge
* Add cross-plugin ios paramedic test running for TravisCI
* [CB-8538](https://issues.apache.org/jira/browse/CB-8538) Added package.json file
### 0.3.0 (Feb 04, 2015)
* Added device.manufacturer property for Android, iOS, Blackberry, WP8
* Support for Windows Phone 8 ANID2 ANID is only supported up to Windows Phone 7.5
* [CB-8351](https://issues.apache.org/jira/browse/CB-8351) Use a local copy of uniqueAppInstanceIdentifier rather than CordovaLib's version
* browser: Fixed a bug that caused an "cannot call method of undefined" error if the browser's user agent wasn't recognized
### 0.2.13 (Dec 02, 2014)
* Changing `device.platform` to always report the platform as "browser".
* [CB-5892](https://issues.apache.org/jira/browse/CB-5892) - Remove deprecated `window.Settings`
* [CB-7700](https://issues.apache.org/jira/browse/CB-7700) cordova-plugin-device documentation translation: cordova-plugin-device
* [CB-7571](https://issues.apache.org/jira/browse/CB-7571) Bump version of nested plugin to match parent plugin
### 0.2.12 (Sep 17, 2014)
* [CB-7471](https://issues.apache.org/jira/browse/CB-7471) cordova-plugin-device documentation translation
* [CB-7552](https://issues.apache.org/jira/browse/CB-7552) device.name docs have not been removed
* [fxos] Fix cordova version
* added status box and documentation to manual tests
* [fxos] Fix cordova version
* added status box and documentation to manual tests
* Added plugin support for the browser
* [CB-7262](https://issues.apache.org/jira/browse/CB-7262) Adds support for universal windows apps.
### 0.2.11 (Aug 06, 2014)
* [FFOS] update DeviceProxy.js
* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Updated translations for docs
* Use Windows system calls to get better info
### 0.2.10 (Jun 05, 2014)
* [CB-6127](https://issues.apache.org/jira/browse/CB-6127) Spanish and French Translations added. Github close #12
* Changing 1.5 to 2.0
* added firefoxos version - conversion
* added firefoxos version
* [CB-6800](https://issues.apache.org/jira/browse/CB-6800) Add license
* [CB-6491](https://issues.apache.org/jira/browse/CB-6491) add CONTRIBUTING.md
### 0.2.9 (Apr 17, 2014)
* [CB-5105](https://issues.apache.org/jira/browse/CB-5105): [Android, windows8, WP, BlackBerry10] Removed dead code for device.version
* [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
* Add NOTICE file
### 0.2.8 (Feb 05, 2014)
* Tizen support added
### 0.2.7 (Jan 07, 2014)
* [CB-5737](https://issues.apache.org/jira/browse/CB-5737) Fix exception on close caused by left over telephony code from [CB-5504](https://issues.apache.org/jira/browse/CB-5504)
### 0.2.6 (Jan 02, 2014)
* [CB-5658](https://issues.apache.org/jira/browse/CB-5658) Add doc/index.md for Device plugin
* [CB-5504](https://issues.apache.org/jira/browse/CB-5504) Moving Telephony Logic out of Device
### 0.2.5 (Dec 4, 2013)
* [CB-5316](https://issues.apache.org/jira/browse/CB-5316) Spell Cordova as a brand unless it's a command or script
* [ubuntu] use cordova/exec/proxy
* add ubuntu platform
* Modify Device.platform logic to use amazon-fireos as the platform for Amazon Devices
* 1. Added amazon-fireos platform. 2. Change to use cordova-amazon-fireos as the platform if user agent contains 'cordova-amazon-fireos'
### 0.2.4 (Oct 28, 2013)
* [CB-5128](https://issues.apache.org/jira/browse/CB-5128): added repo + issue tag in plugin.xml for device plugin
* [CB-5085](https://issues.apache.org/jira/browse/CB-5085) device.cordova returning wrong value
* [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 has moved
* [BlackBerry10] removed uneeded permission tags in plugin.xml
* [CB-4889](https://issues.apache.org/jira/browse/CB-4889) renaming org.apache.cordova.core.device to org.apache.cordova.device
* Rename CHANGELOG.md -> RELEASENOTES.md
* updated to use commandProxy for ffos
* add firefoxos support
* [CB-4752](https://issues.apache.org/jira/browse/CB-4752) Incremented plugin version on dev branch.
### 0.2.1 (Sept 5, 2013)
* removed extraneous print statement
* [CB-4432](https://issues.apache.org/jira/browse/CB-4432) copyright notice change
@@ -0,0 +1,203 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
Dieses Plugin definiert eine globale `device` -Objekt, das des Geräts Hard- und Software beschreibt. Das Objekt im globalen Gültigkeitsbereich ist es zwar nicht verfügbar bis nach dem `deviceready` Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Installation
cordova plugin add cordova-plugin-device
## Eigenschaften
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Rufen Sie die Version von Cordova, die auf dem Gerät ausgeführt.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Browser
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
## device.model
Die `device.model` gibt den Namen der Modell- oder des Geräts zurück. Der Wert wird vom Gerätehersteller festgelegt und kann zwischen den Versionen des gleichen Produkts unterschiedlich sein.
### Unterstützte Plattformen
* Android
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Finden Sie unter http://theiphonewiki.com/wiki/index.php?title=Models / / Var-Modell = device.model;
### Android Eigenarten
* Ruft den [Produktname](http://developer.android.com/reference/android/os/Build.html#PRODUCT) anstelle des [Modellnamens](http://developer.android.com/reference/android/os/Build.html#MODEL), das ist oft der Codename für die Produktion. Beispielsweise das Nexus One gibt `Passion` , und Motorola Droid gibt`voles`.
### Tizen Macken
* Gibt z. B. das Gerätemodell von dem Kreditor zugeordnet,`TIZEN`
### Windows Phone 7 und 8 Eigenarten
* Gibt das vom Hersteller angegebenen Gerätemodell zurück. Beispielsweise gibt der Samsung-Fokus`SGH-i917`.
## device.platform
Name des Betriebssystems des Geräts zu erhalten.
var string = device.platform;
### Unterstützte Plattformen
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 Macken
Windows Phone 7 Geräte melden die Plattform als`WinCE`.
### Windows Phone 8 Macken
Windows Phone 8 Geräte melden die Plattform als`Win32NT`.
## device.uuid
Des Geräts Universally Unique Identifier ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier) zu erhalten).
var string = device.uuid;
### Beschreibung
Die Details wie eine UUID generiert wird werden vom Gerätehersteller und beziehen sich auf die Plattform oder das Modell des Geräts.
### Unterstützte Plattformen
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
/ / Android: wird eine zufällige 64-Bit-Ganzzahl (als Zeichenfolge, wieder!) / / die ganze Zahl wird beim ersten Start des Geräts erzeugt / / / / BlackBerry: gibt die PIN-Nummer des Gerätes / / Dies ist eine neunstellige eindeutige Ganzzahl (als String, obwohl!) / / / / iPhone: (paraphrasiert aus der Dokumentation zur UIDevice-Klasse) / / liefert eine Reihe von Hash-Werte, die aus mehreren Hardware erstellt identifiziert.
/ / Es ist gewährleistet, dass für jedes Gerät eindeutig sein und kann nicht gebunden werden / / an den Benutzer weitergeleitet.
/ / Windows Phone 7: gibt einen Hash des Gerät + aktueller Benutzer, / / wenn der Benutzer nicht definiert ist, eine Guid generiert und wird weiter bestehen, bis die app deinstalliert wird / / Tizen: gibt das Gerät IMEI (International Mobile Equipment Identity oder IMEI ist eine Zahl / / einzigartig für jedes GSM- und UMTS-Handy.
var deviceID = device.uuid;
### iOS Quirk
Die `uuid` auf iOS ist nicht eindeutig zu einem Gerät, aber für jede Anwendung, für jede Installation variiert. Es ändert sich, wenn Sie löschen und neu die app installieren, und möglicherweise auch beim iOS zu aktualisieren, oder auch ein Upgrade möglich die app pro Version (scheinbaren in iOS 5.1). Die `uuid` ist kein zuverlässiger Wert.
### Windows Phone 7 und 8 Eigenarten
Die `uuid` für Windows Phone 7 die Berechtigung erfordert `ID_CAP_IDENTITY_DEVICE` . Microsoft wird diese Eigenschaft wahrscheinlich bald abzuschaffen. Wenn die Funktion nicht verfügbar ist, generiert die Anwendung eine persistente Guid, die für die Dauer der Installation der Anwendung auf dem Gerät gewährleistet ist.
## device.version
Version des Betriebssystems zu erhalten.
var string = device.version;
### Unterstützte Plattformen
* Android 2.1 +
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,206 @@
<!---
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.
-->
# cordova-plugin-device
Dieses Plugin definiert eine globale `device` -Objekt, das des Geräts Hard- und Software beschreibt. Das Objekt im globalen Gültigkeitsbereich ist es zwar nicht verfügbar bis nach dem `deviceready` Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Installation
cordova plugin add cordova-plugin-device
## Eigenschaften
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Rufen Sie die Version von Cordova, die auf dem Gerät ausgeführt.
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Browser
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
## device.model
Die `device.model` gibt den Namen der Modell- oder des Geräts zurück. Der Wert wird vom Gerätehersteller festgelegt und kann zwischen den Versionen des gleichen Produkts unterschiedlich sein.
### Unterstützte Plattformen
* Android
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Finden Sie unter http://theiphonewiki.com/wiki/index.php?title=Models / / Var-Modell = device.model;
### Android Eigenarten
* Ruft den [Produktname][1] anstelle des [Modellnamens][2], das ist oft der Codename für die Produktion. Beispielsweise das Nexus One gibt `Passion` , und Motorola Droid gibt`voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
[2]: http://developer.android.com/reference/android/os/Build.html#MODEL
### Tizen Macken
* Gibt z. B. das Gerätemodell von dem Kreditor zugeordnet,`TIZEN`
### Windows Phone 7 und 8 Eigenarten
* Gibt das vom Hersteller angegebenen Gerätemodell zurück. Beispielsweise gibt der Samsung-Fokus`SGH-i917`.
## device.platform
Name des Betriebssystems des Geräts zu erhalten.
var string = device.platform;
### Unterstützte Plattformen
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 Macken
Windows Phone 7 Geräte melden die Plattform als`WinCE`.
### Windows Phone 8 Macken
Windows Phone 8 Geräte melden die Plattform als`Win32NT`.
## device.uuid
Des Geräts Universally Unique Identifier ([UUID][3] zu erhalten).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### Beschreibung
Die Details wie eine UUID generiert wird werden vom Gerätehersteller und beziehen sich auf die Plattform oder das Modell des Geräts.
### Unterstützte Plattformen
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
/ / Android: wird eine zufällige 64-Bit-Ganzzahl (als Zeichenfolge, wieder!) / / die ganze Zahl wird beim ersten Start des Geräts erzeugt / / / / BlackBerry: gibt die PIN-Nummer des Gerätes / / Dies ist eine neunstellige eindeutige Ganzzahl (als String, obwohl!) / / / / iPhone: (paraphrasiert aus der Dokumentation zur UIDevice-Klasse) / / liefert eine Reihe von Hash-Werte, die aus mehreren Hardware erstellt identifiziert.
/ / Es ist gewährleistet, dass für jedes Gerät eindeutig sein und kann nicht gebunden werden / / an den Benutzer weitergeleitet.
/ / Windows Phone 7: gibt einen Hash des Gerät + aktueller Benutzer, / / wenn der Benutzer nicht definiert ist, eine Guid generiert und wird weiter bestehen, bis die app deinstalliert wird / / Tizen: gibt das Gerät IMEI (International Mobile Equipment Identity oder IMEI ist eine Zahl / / einzigartig für jedes GSM- und UMTS-Handy.
var deviceID = device.uuid;
### iOS Quirk
Die `uuid` auf iOS ist nicht eindeutig zu einem Gerät, aber für jede Anwendung, für jede Installation variiert. Es ändert sich, wenn Sie löschen und neu die app installieren, und möglicherweise auch beim iOS zu aktualisieren, oder auch ein Upgrade möglich die app pro Version (scheinbaren in iOS 5.1). Die `uuid` ist kein zuverlässiger Wert.
### Windows Phone 7 und 8 Eigenarten
Die `uuid` für Windows Phone 7 die Berechtigung erfordert `ID_CAP_IDENTITY_DEVICE` . Microsoft wird diese Eigenschaft wahrscheinlich bald abzuschaffen. Wenn die Funktion nicht verfügbar ist, generiert die Anwendung eine persistente Guid, die für die Dauer der Installation der Anwendung auf dem Gerät gewährleistet ist.
## device.version
Version des Betriebssystems zu erhalten.
var string = device.version;
### Unterstützte Plattformen
* Android 2.1 +
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Kurzes Beispiel
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,216 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
Este plugin define un global `device` objeto que describe del dispositivo hardware y software. Aunque el objeto está en el ámbito global, no está disponible hasta después de la `deviceready` evento.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Instalación
cordova plugin add cordova-plugin-device
## Propiedades
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Obtener la versión de Cordova que se ejecuta en el dispositivo.
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Explorador
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
## device.model
El `device.model` devuelve el nombre de modelo del dispositivo o producto. El valor es fijado por el fabricante del dispositivo y puede ser diferente a través de versiones del mismo producto.
### Plataformas soportadas
* Android
* BlackBerry 10
* Explorador
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models
//
var model = device.model;
### Rarezas Android
* Obtiene el [nombre del producto](http://developer.android.com/reference/android/os/Build.html#PRODUCT) en lugar del [nombre de la modelo](http://developer.android.com/reference/android/os/Build.html#MODEL), que es a menudo el nombre de código de producción. Por ejemplo, el Nexus One devuelve `Passion` y Motorola Droid devuelve `voles`.
### Rarezas Tizen
* Devuelve que el modelo de dispositivo asignado por el proveedor, por ejemplo, `TIZEN`
### Windows Phone 7 y 8 rarezas
* Devuelve el modelo de dispositivo especificado por el fabricante. Por ejemplo, el Samsung Focus devuelve `SGH-i917`.
## device.platform
Obtener el nombre del sistema operativo del dispositivo.
var string = device.platform;
### Plataformas soportadas
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 rarezas
Dispositivos Windows Phone 7 informe de la plataforma como `WinCE`.
### Windows Phone 8 rarezas
Dispositivos Windows Phone 8 Informe la plataforma como `Win32NT`.
## device.uuid
Obtener identificador universalmente única del dispositivo ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)).
var string = device.uuid;
### Descripción
Los detalles de cómo se genera un UUID son determinados por el fabricante del dispositivo y son específicos a la plataforma del dispositivo o modelo.
### Plataformas soportadas
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Android: Returns a random 64-bit integer (as a string, again!)
// The integer is generated on the device's first boot
//
// BlackBerry: Returns the PIN number of the device
// This is a nine-digit unique integer (as a string, though!)
//
// iPhone: (Paraphrased from the UIDevice Class documentation)
// Returns a string of hash values created from multiple hardware identifies.
// It is guaranteed to be unique for every device and can't be tied
// to the user account.
// Windows Phone 7 : Returns a hash of device+current user,
// if the user is not defined, a guid is generated and will persist until the app is uninstalled
// Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number
// unique to every GSM and UMTS mobile phone.
var deviceID = device.uuid;
### Rarezas de iOS
El `uuid` en iOS no es exclusiva de un dispositivo, pero varía para cada aplicación, para cada instalación. Cambia si puedes borrar y volver a instalar la aplicación, y posiblemente también cuándo actualizar iOS, o incluso mejorar la aplicación por la versión (evidente en iOS 5.1). El `uuid` no es un valor confiable.
### Windows Phone 7 y 8 rarezas
El `uuid` para Windows Phone 7 requiere el permiso `ID_CAP_IDENTITY_DEVICE`. Microsoft pronto probablemente desaprueban esta propiedad. Si la capacidad no está disponible, la aplicación genera un guid persistente que se mantiene durante la duración de la instalación de la aplicación en el dispositivo.
## device.version
Obtener la versión del sistema operativo.
var string = device.version;
### Plataformas soportadas
* Android 2.1 +
* BlackBerry 10
* Explorador
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,220 @@
<!---
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.
-->
# cordova-plugin-device
Este plugin define un global `device` objeto que describe del dispositivo hardware y software. Aunque el objeto está en el ámbito global, no está disponible hasta después de la `deviceready` evento.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Instalación
cordova plugin add cordova-plugin-device
## Propiedades
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Obtener la versión de Cordova que se ejecuta en el dispositivo.
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Explorador
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
## device.model
El `device.model` devuelve el nombre de modelo del dispositivo o producto. El valor es fijado por el fabricante del dispositivo y puede ser diferente a través de versiones del mismo producto.
### Plataformas soportadas
* Android
* BlackBerry 10
* Explorador
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models
//
var model = device.model;
### Rarezas Android
* Obtiene el [nombre del producto][1] en lugar del [nombre de la modelo][2], que es a menudo el nombre de código de producción. Por ejemplo, el Nexus One devuelve `Passion` y Motorola Droid devuelve `voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
[2]: http://developer.android.com/reference/android/os/Build.html#MODEL
### Rarezas Tizen
* Devuelve que el modelo de dispositivo asignado por el proveedor, por ejemplo, `TIZEN`
### Windows Phone 7 y 8 rarezas
* Devuelve el modelo de dispositivo especificado por el fabricante. Por ejemplo, el Samsung Focus devuelve `SGH-i917`.
## device.platform
Obtener el nombre del sistema operativo del dispositivo.
var string = device.platform;
### Plataformas soportadas
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 rarezas
Dispositivos Windows Phone 7 informe de la plataforma como `WinCE`.
### Windows Phone 8 rarezas
Dispositivos Windows Phone 8 Informe la plataforma como `Win32NT`.
## device.uuid
Obtener identificador universalmente única del dispositivo ([UUID][3]).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### Descripción
Los detalles de cómo se genera un UUID son determinados por el fabricante del dispositivo y son específicos a la plataforma del dispositivo o modelo.
### Plataformas soportadas
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Android: devuelve un entero de 64 bits al azar (como una cadena, otra vez!)
// el entero es generado en el primer arranque del dispositivo
//
// BlackBerry: devuelve el número PIN del dispositivo
// este es un entero único de nueve dígitos (como una cadena, aunque!)
//
// iPhone: (parafraseado de la documentación de la clase UIDevice)
// devuelve una cadena de valores hash creado a partir
// de múltiples hardware identifica.
/ / Está garantizado para ser único para cada dispositivo y no puede ser atado / / a la cuenta de usuario.
// Windows Phone 7: devuelve un hash de dispositivo + usuario actual,
// si el usuario no está definido, un guid generado y persistirá hasta que se desinstala la aplicación
//
// Tizen: devuelve el dispositivo IMEI (identidad de equipo móvil internacional o IMEI es un número
// único para cada teléfono móvil GSM y UMTS.
var deviceID = device.uuid;
### iOS chanfle
El `uuid` en iOS no es exclusiva de un dispositivo, pero varía para cada aplicación, para cada instalación. Cambia si puedes borrar y volver a instalar la aplicación, y posiblemente también cuándo actualizar iOS, o incluso mejorar la aplicación por la versión (evidente en iOS 5.1). El `uuid` no es un valor confiable.
### Windows Phone 7 y 8 rarezas
El `uuid` para Windows Phone 7 requiere el permiso `ID_CAP_IDENTITY_DEVICE`. Microsoft pronto probablemente desaprueban esta propiedad. Si la capacidad no está disponible, la aplicación genera un guid persistente que se mantiene durante la duración de la instalación de la aplicación en el dispositivo.
## device.version
Obtener la versión del sistema operativo.
var string = device.version;
### Plataformas soportadas
* Android 2.1 +
* BlackBerry 10
* Explorador
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Ejemplo rápido
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. el Mango se vuelve 7.10.7720
// Tizen: devuelve "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,215 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
Ce plugin définit un global `device` objet qui décrit le matériel et les logiciels de l'appareil. Bien que l'objet est dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Installation
cordova plugin add cordova-plugin-device
## Propriétés
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Retourne la version de Cordova en cours d'exécution sur l'appareil.
### Plates-formes supportées
* Amazon Fire OS
* Android
* BlackBerry 10
* Navigateur
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
## device.model
L'objet `device.model` retourne le nom du modèle de l'appareil/produit. Cette valeur est définie par le fabricant du périphérique et peut varier entre les différentes versions d'un même produit.
### Plates-formes supportées
* Android
* BlackBerry 10
* Navigateur
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Exemple court
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Voir http://theiphonewiki.com/wiki/index.php?title=Models
//
var model = device.model;
### Quirks Android
* Retourne le [nom du produit](http://developer.android.com/reference/android/os/Build.html#PRODUCT) au lieu du [nom du modèle](http://developer.android.com/reference/android/os/Build.html#MODEL), ce qui équivaut souvent au nom de code de production. Par exemple, `Passion` pour le Nexus One et `voles` pour le Motorola Droid.
### Bizarreries de paciarelli
* Retourne le modèle du dispositif, assigné par le vendeur, par exemple `TIZEN`
### Notes au sujet de Windows Phone 7 et 8
* Retourne le modèle de l'appareil spécifié par le fabricant. Par exemple `SGH-i917` pour le Samsung Focus.
## device.platform
Obtenir le nom de système d'exploitation de l'appareil.
var string = device.platform;
### Plates-formes supportées
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Exemple court
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 Quirks
Appareils Windows Phone 7 rapport de la plate-forme comme`WinCE`.
### Notes au sujet de Windows Phone 8
Appareils Windows Phone 8 rapport de la plate-forme comme`Win32NT`.
## device.uuid
Obtenir Universally Unique Identifier de l'appareil ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)).
var string = device.uuid;
### Description
Les détails de comment un UUID généré sont déterminées par le fabricant du périphérique et sont spécifiques à la plate-forme ou le modèle de l'appareil.
### Plates-formes supportées
* Android
* BlackBerry 10
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Exemple court
// Android : retourne un nombre entier 64-bit aléatoire (sous la forme d'une chaîne de caractères, encore !)
// Ce nombre entier est généré lors du premier démarrage de l'appareil
//
// BlackBerry : retourne le numéro PIN de l'appareil
// Il s'agit d'un nombre entier unique à neuf chiffres (sous la forme d'une chaîne de caractères cependant !)
//
// iPhone : (copié depuis la documentation de la classe UIDevice)
// Retourne une chaîne de caractères générée à partir de plusieurs caractéristiques matérielles.
/ / Il est garanti pour être unique pour chaque appareil et ne peut pas être lié / / pour le compte d'utilisateur.
// Windows Phone 7 : retourne un hashage généré à partir de appareil+utilisateur actuel,
// si aucun utilisateur n'est défini, un guid est généré persistera jusqu'à ce que l'application soit désinstallée
// Tizen : retourne le numéro IMEI (International Mobile Equipment Identity) de l'appareil, ce numéro est
// unique pour chaque téléphone GSM et UMTS.
var deviceID = device.uuid;
### Spécificités iOS
Le `uuid` sur iOS n'est pas propre à un périphérique, mais varie pour chaque application, pour chaque installation. Elle change si vous supprimez, puis réinstallez l'application, et éventuellement aussi quand vous mettre à jour d'iOS, ou même mettre à jour le soft par version (apparent dans iOS 5.1). Le `uuid` n'est pas une valeur fiable.
### Notes au sujet de Windows Phone 7 et 8
Le `uuid` pour Windows Phone 7 requiert l'autorisation `ID_CAP_IDENTITY_DEVICE` . Microsoft va probablement bientôt obsolète de cette propriété. Si la capacité n'est pas disponible, l'application génère un guid persistant qui est maintenu pendant toute la durée de l'installation de l'application sur le périphérique.
## device.version
Téléchargez la version de système d'exploitation.
var string = device.version;
### Plates-formes supportées
* Android 2.1+
* BlackBerry 10
* Navigateur
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Exemple court
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,218 @@
<!---
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.
-->
# cordova-plugin-device
Ce plugin définit un global `device` objet qui décrit le matériel et les logiciels de l'appareil. Bien que l'objet est dans la portée globale, il n'est pas disponible jusqu'après la `deviceready` événement.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Installation
cordova plugin add cordova-plugin-device
## Propriétés
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Retourne la version de Cordova en cours d'exécution sur l'appareil.
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* BlackBerry 10
* Navigateur
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
## device.model
L'objet `device.model` retourne le nom du modèle de l'appareil/produit. Cette valeur est définie par le fabricant du périphérique et peut varier entre les différentes versions d'un même produit.
### Plates-formes prises en charge
* Android
* BlackBerry 10
* Navigateur
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Petit exemple
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Voir http://theiphonewiki.com/wiki/index.php?title=Models
//
var model = device.model;
### Quirks Android
* Retourne le [nom du produit][1] au lieu du [nom du modèle][2], ce qui équivaut souvent au nom de code de production. Par exemple, `Passion` pour le Nexus One et `voles` pour le Motorola Droid.
[1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
[2]: http://developer.android.com/reference/android/os/Build.html#MODEL
### Bizarreries de paciarelli
* Retourne le modèle du dispositif, assigné par le vendeur, par exemple `TIZEN`
### Windows Phone 7 et 8 Quirks
* Retourne le modèle de l'appareil spécifié par le fabricant. Par exemple `SGH-i917` pour le Samsung Focus.
## device.platform
Obtenir le nom de système d'exploitation de l'appareil.
var string = device.platform;
### Plates-formes prises en charge
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Petit exemple
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 Quirks
Appareils Windows Phone 7 rapport de la plate-forme comme`WinCE`.
### Notes au sujet de Windows Phone 8
Appareils Windows Phone 8 rapport de la plate-forme comme`Win32NT`.
## device.uuid
Obtenir Universally Unique Identifier de l'appareil ([UUID][3]).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### Description
Les détails de comment un UUID généré sont déterminées par le fabricant du périphérique et sont spécifiques à la plate-forme ou le modèle de l'appareil.
### Plates-formes prises en charge
* Android
* BlackBerry 10
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Petit exemple
// Android : retourne un nombre entier 64-bit aléatoire (sous la forme d'une chaîne de caractères, encore !)
// Ce nombre entier est généré lors du premier démarrage de l'appareil
//
// BlackBerry : retourne le numéro PIN de l'appareil
// Il s'agit d'un nombre entier unique à neuf chiffres (sous la forme d'une chaîne de caractères cependant !)
//
// iPhone : (copié depuis la documentation de la classe UIDevice)
// Retourne une chaîne de caractères générée à partir de plusieurs caractéristiques matérielles.
/ / Il est garanti pour être unique pour chaque appareil et ne peut pas être lié / / pour le compte d'utilisateur.
// Windows Phone 7 : retourne un hashage généré à partir de appareil+utilisateur actuel,
// si aucun utilisateur n'est défini, un guid est généré persistera jusqu'à ce que l'application soit désinstallée
// Tizen : retourne le numéro IMEI (International Mobile Equipment Identity) de l'appareil, ce numéro est
// unique pour chaque téléphone GSM et UMTS.
var deviceID = device.uuid;
### Spécificités iOS
Le `uuid` sur iOS n'est pas propre à un périphérique, mais varie pour chaque application, pour chaque installation. Elle change si vous supprimez, puis réinstallez l'application, et éventuellement aussi quand vous mettre à jour d'iOS, ou même mettre à jour le soft par version (apparent dans iOS 5.1). Le `uuid` n'est pas une valeur fiable.
### Windows Phone 7 et 8 Quirks
Le `uuid` pour Windows Phone 7 requiert l'autorisation `ID_CAP_IDENTITY_DEVICE` . Microsoft va probablement bientôt obsolète de cette propriété. Si la capacité n'est pas disponible, l'application génère un guid persistant qui est maintenu pendant toute la durée de l'installation de l'application sur le périphérique.
## device.version
Téléchargez la version de système d'exploitation.
var string = device.version;
### Plates-formes prises en charge
* Android 2.1+
* BlackBerry 10
* Navigateur
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Petit exemple
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,203 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
Questo plugin definisce un global `device` oggetto che descrive il dispositivo hardware e software. Sebbene l'oggetto sia in ambito globale, non è disponibile fino a dopo il `deviceready` evento.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Installazione
cordova plugin add cordova-plugin-device
## Proprietà
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Ottenere la versione di Cordova in esecuzione nel dispositivo.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Browser
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
## device.model
Il `device.model` restituisce il nome del modello del dispositivo o del prodotto. Il valore viene impostato dal produttore del dispositivo e può essere differente tra le versioni dello stesso prodotto.
### Piattaforme supportate
* Android
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Vedi http://theiphonewiki.com/wiki/index.php?title=Models / / modello var = device.model;
### Stranezze Android
* Ottiene il [nome del prodotto](http://developer.android.com/reference/android/os/Build.html#PRODUCT) anziché il [nome del modello](http://developer.android.com/reference/android/os/Build.html#MODEL), che è spesso il nome di codice di produzione. Ad esempio, restituisce il Nexus One `Passion` , e Motorola Droid restituisce`voles`.
### Tizen stranezze
* Restituisce il modello di dispositivo assegnato dal fornitore, ad esempio,`TIZEN`
### Windows Phone 7 e 8 stranezze
* Restituisce il modello di dispositivo specificato dal produttore. Ad esempio, restituisce il Samsung Focus`SGH-i917`.
## device.platform
Ottenere il nome del sistema operativo del dispositivo.
var string = device.platform;
### Piattaforme supportate
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 capricci
Windows Phone 7 dispositivi segnalano la piattaforma come`WinCE`.
### Windows Phone 8 stranezze
Dispositivi Windows Phone 8 segnalano la piattaforma come`Win32NT`.
## device.uuid
Ottenere identificatore del dispositivo univoco universale ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)).
var string = device.uuid;
### Descrizione
I dettagli di come viene generato un UUID sono determinati dal produttore del dispositivo e sono specifici per la piattaforma o il modello del dispositivo.
### Piattaforme supportate
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
/ / Android: restituisce un intero casuale di 64 bit (come stringa, ancora una volta!) / / il numero intero è generato al primo avvio del dispositivo / / / / BlackBerry: restituisce il numero PIN del dispositivo / / questo è un valore integer univoco a nove cifre (come stringa, benchè!) / / / / iPhone: (parafrasato dalla documentazione della classe UIDevice) / / restituisce una stringa di valori hash creata dall'hardware più identifica.
/ / È garantito per essere unica per ogni dispositivo e non può essere legato / / per l'account utente.
/ / Windows Phone 7: restituisce un hash dell'utente corrente, + dispositivo / / se l'utente non è definito, un guid generato e persisterà fino a quando l'applicazione viene disinstallata / / Tizen: restituisce il dispositivo IMEI (International Mobile Equipment Identity o IMEI è un numero / / unico per ogni cellulare GSM e UMTS.
var deviceID = device.uuid;
### iOS Quirk
Il `uuid` su iOS non è univoco per un dispositivo, ma varia per ogni applicazione, per ogni installazione. Cambia se si elimina e re-installare l'app, e possibilmente anche quando aggiornare iOS o anche aggiornare l'app per ogni versione (apparente in iOS 5.1). Il `uuid` non è un valore affidabile.
### Windows Phone 7 e 8 stranezze
Il `uuid` per Windows Phone 7 richiede l'autorizzazione `ID_CAP_IDENTITY_DEVICE` . Microsoft probabilmente sarà presto deprecare questa proprietà. Se la funzionalità non è disponibile, l'applicazione genera un guid persistente che viene mantenuto per la durata dell'installazione dell'applicazione sul dispositivo.
## device.version
Ottenere la versione del sistema operativo.
var string = device.version;
### Piattaforme supportate
* Android 2.1 +
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,206 @@
<!---
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.
-->
# cordova-plugin-device
Questo plugin definisce un global `device` oggetto che descrive il dispositivo hardware e software. Sebbene l'oggetto sia in ambito globale, non è disponibile fino a dopo il `deviceready` evento.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Installazione
cordova plugin add cordova-plugin-device
## Proprietà
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Ottenere la versione di Cordova in esecuzione nel dispositivo.
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Browser
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
## device.model
Il `device.model` restituisce il nome del modello del dispositivo o del prodotto. Il valore viene impostato dal produttore del dispositivo e può essere differente tra le versioni dello stesso prodotto.
### Piattaforme supportate
* Android
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Vedi http://theiphonewiki.com/wiki/index.php?title=Models / / modello var = device.model;
### Stranezze Android
* Ottiene il [nome del prodotto][1] anziché il [nome del modello][2], che è spesso il nome di codice di produzione. Ad esempio, restituisce il Nexus One `Passion` , e Motorola Droid restituisce`voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
[2]: http://developer.android.com/reference/android/os/Build.html#MODEL
### Tizen stranezze
* Restituisce il modello di dispositivo assegnato dal fornitore, ad esempio,`TIZEN`
### Windows Phone 7 e 8 stranezze
* Restituisce il modello di dispositivo specificato dal produttore. Ad esempio, restituisce il Samsung Focus`SGH-i917`.
## device.platform
Ottenere il nome del sistema operativo del dispositivo.
var string = device.platform;
### Piattaforme supportate
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 capricci
Windows Phone 7 dispositivi segnalano la piattaforma come`WinCE`.
### Windows Phone 8 stranezze
Dispositivi Windows Phone 8 segnalano la piattaforma come`Win32NT`.
## device.uuid
Ottenere identificatore del dispositivo univoco universale ([UUID][3]).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### Descrizione
I dettagli di come viene generato un UUID sono determinati dal produttore del dispositivo e sono specifici per la piattaforma o il modello del dispositivo.
### Piattaforme supportate
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
/ / Android: restituisce un intero casuale di 64 bit (come stringa, ancora una volta!) / / il numero intero è generato al primo avvio del dispositivo / / / / BlackBerry: restituisce il numero PIN del dispositivo / / questo è un valore integer univoco a nove cifre (come stringa, benchè!) / / / / iPhone: (parafrasato dalla documentazione della classe UIDevice) / / restituisce una stringa di valori hash creata dall'hardware più identifica.
/ / È garantito per essere unica per ogni dispositivo e non può essere legato / / per l'account utente.
/ / Windows Phone 7: restituisce un hash dell'utente corrente, + dispositivo / / se l'utente non è definito, un guid generato e persisterà fino a quando l'applicazione viene disinstallata / / Tizen: restituisce il dispositivo IMEI (International Mobile Equipment Identity o IMEI è un numero / / unico per ogni cellulare GSM e UMTS.
var deviceID = device.uuid;
### iOS Quirk
Il `uuid` su iOS non è univoco per un dispositivo, ma varia per ogni applicazione, per ogni installazione. Cambia se si elimina e re-installare l'app, e possibilmente anche quando aggiornare iOS o anche aggiornare l'app per ogni versione (apparente in iOS 5.1). Il `uuid` non è un valore affidabile.
### Windows Phone 7 e 8 stranezze
Il `uuid` per Windows Phone 7 richiede l'autorizzazione `ID_CAP_IDENTITY_DEVICE` . Microsoft probabilmente sarà presto deprecare questa proprietà. Se la funzionalità non è disponibile, l'applicazione genera un guid persistente che viene mantenuto per la durata dell'installazione dell'applicazione sul dispositivo.
## device.version
Ottenere la versione del sistema operativo.
var string = device.version;
### Piattaforme supportate
* Android 2.1 +
* BlackBerry 10
* Browser
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Esempio rapido
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,203 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
このプラグインをグローバル定義します `device` オブジェクトは、デバイスのハードウェアとソフトウェアについて説明します。 それは後まで利用可能なオブジェクトがグローバル スコープでは、 `deviceready` イベント。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## インストール
cordova plugin add cordova-plugin-device
## プロパティ
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
デバイスで実行されているコルドバのバージョンを取得します。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* ブラウザー
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
## device.model
`device.model`、デバイスのモデルまたは製品の名前を返します。値は、デバイスの製造元によって設定され、同じ製品のバージョン間で異なる可能性があります。
### サポートされているプラットフォーム
* アンドロイド
* ブラックベリー 10
* ブラウザー
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models を参照してください//var モデル = device.model;
### Android の癖
* 生産コード名は[モデル名](http://developer.android.com/reference/android/os/Build.html#MODEL)の代わりに[製品名](http://developer.android.com/reference/android/os/Build.html#PRODUCT)を取得します。 たとえば、ネクサス 1 つを返します `Passion` 、Motorola のドロイドを返します`voles`.
### Tizen の癖
* たとえば、ベンダーによって割り当てられているデバイスのモデルを返します`TIZEN`
### Windows Phone 7 と 8 癖
* 製造元によって指定されたデバイスのモデルを返します。たとえば、三星フォーカスを返します`SGH-i917`.
## device.platform
デバイスのオペレーティング システム名を取得します。
var string = device.platform;
### サポートされているプラットフォーム
* アンドロイド
* ブラックベリー 10
* Browser4
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 の癖
Windows Phone 7 デバイスとプラットフォームを報告します。`WinCE`.
### Windows Phone 8 癖
Windows Phone 8 デバイスとプラットフォームを報告します。`Win32NT`.
## device.uuid
デバイスのユニバーサル ・ ユニーク識別子 ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)を取得します。).
var string = device.uuid;
### 解説
UUID を生成する方法の詳細は、デバイスの製造元によって決定され、デバイスのプラットフォームやモデルに固有です。
### サポートされているプラットフォーム
* アンドロイド
* ブラックベリー 10
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
//アンドロイド: ランダムな 64 ビットの整数 (を文字列として返します、再び !)/デバイスの最初の起動時に生成される整数/////ブラックベリー: デバイスのピン番号を返します//これは 9 桁の一意な整数 (を文字列としても )////iPhone: (UIDevice クラスのドキュメントから言い換え)//識別複数のハードウェアから作成されたハッシュ値の文字列を返します。。
//それはすべてのデバイスに対して一意であることが保証され、接続することはできません//ユーザー アカウント。
//Windows Phone 7: デバイス + 現在のユーザーのハッシュを返します//ユーザーが定義されていない場合 guid が生成され、アプリがアンインストールされるまで保持されます//Tizen: デバイスの IMEI を返します (国際モバイル機器アイデンティティまたは IMEI は番号です//すべての GSM および UMTS の携帯電話に固有です。
var deviceID = device.uuid;
### iOS の気まぐれ
`uuid`IOS で、デバイスに固有ではないインストールごと、アプリケーションごとに異なります。 削除、アプリを再インストールした場合に変更と多分またときアップグレード iOS の, またはもアップグレードするアプリ (iOS の 5.1 で明らかに) バージョンごと。 `uuid`は信頼性の高い値ではありません。
### Windows Phone 7 と 8 癖
`uuid`のために Windows Phone 7 には、権限が必要です `ID_CAP_IDENTITY_DEVICE` 。 Microsoft はすぐにこのプロパティを廃止して可能性があります。 機能が利用できない場合、アプリケーションはデバイスへのアプリケーションのインストールの持続期間のために保持されている永続的な guid を生成します。
## device.version
オペレーティング システムのバージョンを取得します。
var string = device.version;
### サポートされているプラットフォーム
* アンドロイド 2.1 +
* ブラックベリー 10
* ブラウザー
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,206 @@
<!---
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.
-->
# cordova-plugin-device
このプラグインをグローバル定義します `device` オブジェクトは、デバイスのハードウェアとソフトウェアについて説明します。 それは後まで利用可能なオブジェクトがグローバル スコープでは、 `deviceready` イベント。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## インストール
cordova plugin add cordova-plugin-device
## プロパティ
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
デバイスで実行されているコルドバのバージョンを取得します。
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* ブラウザー
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
## device.model
`device.model`、デバイスのモデルまたは製品の名前を返します。値は、デバイスの製造元によって設定され、同じ製品のバージョン間で異なる可能性があります。
### サポートされているプラットフォーム
* アンドロイド
* ブラックベリー 10
* ブラウザー
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models を参照してください//var モデル = device.model;
### Android の癖
* 生産コード名は[モデル名][1]の代わりに[製品名][2]を取得します。 たとえば、ネクサス 1 つを返します `Passion` 、Motorola のドロイドを返します`voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#MODEL
[2]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
### Tizen の癖
* たとえば、ベンダーによって割り当てられているデバイスのモデルを返します`TIZEN`
### Windows Phone 7 と 8 癖
* 製造元によって指定されたデバイスのモデルを返します。たとえば、三星フォーカスを返します`SGH-i917`.
## device.platform
デバイスのオペレーティング システム名を取得します。
var string = device.platform;
### サポートされているプラットフォーム
* アンドロイド
* ブラックベリー 10
* Browser4
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 の癖
Windows Phone 7 デバイスとプラットフォームを報告します。`WinCE`.
### Windows Phone 8 癖
Windows Phone 8 デバイスとプラットフォームを報告します。`Win32NT`.
## device.uuid
デバイスのユニバーサル ・ ユニーク識別子 ([UUID][3]を取得します。).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### 説明
UUID を生成する方法の詳細は、デバイスの製造元によって決定され、デバイスのプラットフォームやモデルに固有です。
### サポートされているプラットフォーム
* アンドロイド
* ブラックベリー 10
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
//アンドロイド: ランダムな 64 ビットの整数 (を文字列として返します、再び !)/デバイスの最初の起動時に生成される整数/////ブラックベリー: デバイスのピン番号を返します//これは 9 桁の一意な整数 (を文字列としても )////iPhone: (UIDevice クラスのドキュメントから言い換え)//識別複数のハードウェアから作成されたハッシュ値の文字列を返します。。
//それはすべてのデバイスに対して一意であることが保証され、接続することはできません//ユーザー アカウント。
//Windows Phone 7: デバイス + 現在のユーザーのハッシュを返します//ユーザーが定義されていない場合 guid が生成され、アプリがアンインストールされるまで保持されます//Tizen: デバイスの IMEI を返します (国際モバイル機器アイデンティティまたは IMEI は番号です//すべての GSM および UMTS の携帯電話に固有です。
var deviceID = device.uuid;
### iOS の気まぐれ
`uuid`IOS で、デバイスに固有ではないインストールごと、アプリケーションごとに異なります。 削除、アプリを再インストールした場合に変更と多分またときアップグレード iOS の, またはもアップグレードするアプリ (iOS の 5.1 で明らかに) バージョンごと。 `uuid`は信頼性の高い値ではありません。
### Windows Phone 7 と 8 癖
`uuid`のために Windows Phone 7 には、権限が必要です `ID_CAP_IDENTITY_DEVICE` 。 Microsoft はすぐにこのプロパティを廃止して可能性があります。 機能が利用できない場合、アプリケーションはデバイスへのアプリケーションのインストールの持続期間のために保持されている永続的な guid を生成します。
## device.version
オペレーティング システムのバージョンを取得します。
var string = device.version;
### サポートされているプラットフォーム
* アンドロイド 2.1 +
* ブラックベリー 10
* ブラウザー
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### 簡単な例
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,203 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
이 플러그인 정의 전역 `device` 개체, 디바이스의 하드웨어 및 소프트웨어에 설명 합니다. 개체는 전역 범위에서 비록 그것은 후까지 사용할 수 있는 `deviceready` 이벤트.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## 설치
cordova plugin add cordova-plugin-device
## 속성
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
코르도바는 장치에서 실행 중인 버전을 얻을.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* 브라우저
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
## device.model
`device.model`소자의 모델 또는 제품의 이름을 반환 합니다. 값 장치 제조업체에서 설정 되 고 동일 제품의 버전 간에 다를 수 있습니다.
### 지원 되는 플랫폼
* 안 드 로이드
* 블랙베리 10
* 브라우저
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models 참조 / / var 모델 = device.model;
### 안 드 로이드 단점
* 어떤은 종종 프로덕션 코드 이름 대신 [제품 모델 이름](http://developer.android.com/reference/android/os/Build.html#MODEL), [제품 이름](http://developer.android.com/reference/android/os/Build.html#PRODUCT) 을 가져옵니다. 예를 들어 넥서스 하나 반환 합니다 `Passion` , 모토로라 Droid를 반환 합니다`voles`.
### Tizen 특수
* 예를 들어, 공급 업체에 의해 할당 된 디바이스 모델을 반환 합니다.`TIZEN`
### Windows Phone 7, 8 특수
* 제조업체에서 지정 하는 장치 모델을 반환 합니다. 예를 들어 삼성 포커스를 반환 합니다.`SGH-i917`.
## device.platform
장치의 운영 체제 이름을 얻을.
var string = device.platform;
### 지원 되는 플랫폼
* 안 드 로이드
* 블랙베리 10
* Browser4
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 단점
Windows Phone 7 장치 보고 플랫폼으로`WinCE`.
### Windows Phone 8 단점
Windows Phone 8 장치 보고 플랫폼으로`Win32NT`.
## device.uuid
소자의 보편적으로 고유 식별자 ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier) 를 얻을합니다).
var string = device.uuid;
### 설명
UUID 생성 방법의 자세한 내용은 장치 제조업체에 의해 결정 됩니다 및 소자의 플랫폼 이나 모델.
### 지원 되는 플랫폼
* 안 드 로이드
* 블랙베리 10
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
/ / 안 드 로이드: (문자열로 다시!) 임의의 64 비트 정수를 반환 합니다 / / 정수 장치의 첫 번째 부팅에서 생성 / / / / 블랙베리: 디바이스의 핀 번호를 반환 합니다 / / 이것은 9 자리 고유 정수 (문자열로 비록!) / / / / 아이폰: (UIDevice 클래스 설명서에서 읊 었) / / 문자열 여러 하드웨어에서 생성 하는 해시 값을 식별 하는 반환 합니다.
/ 그것은 모든 장치에 대 한 고유 해야 보장 되 고 묶일 수 없습니다 / / / 사용자 계정에.
/ / Windows Phone 7: 장치 + 현재 사용자의 해시를 반환 합니다 / / 사용자 정의 되지 않은 경우 guid 생성 되 고 응용 프로그램을 제거할 때까지 유지 됩니다 / / Tizen: 반환 장치 IMEI (국제 모바일 기기 식별 또는 IMEI 숫자입니다 / / 모든 GSM와 UMTS 휴대 전화 고유.
var deviceID = device.uuid;
### iOS 특질
`uuid`ios 장치에 고유 하지 않습니다 하지만 각 설치에 대 한 응용 프로그램 마다 다릅니다. 삭제 하 고 다시 애플 리 케이 션을 설치 하는 경우 변경 가능 하 게 또한 iOS를 업그레이드 하거나 때 버전 (iOS 5.1에에서 명백한) 당 응용 프로그램 업그레이드도 하 고. `uuid`은 신뢰할 수 있는 값이 아닙니다.
### Windows Phone 7, 8 특수
`uuid`Windows Phone 7 필요 허가 `ID_CAP_IDENTITY_DEVICE` . Microsoft는 곧이 속성을 세웁니다 가능성이 것입니다. 기능을 사용할 수 없는 경우 응용 프로그램 장치에 응용 프로그램의 설치 하는 동안 유지 하는 영구 guid를 생성 합니다.
## device.version
운영 체제 버전을 얻을.
var string = device.version;
### 지원 되는 플랫폼
* 안 드 로이드 2.1 +
* 블랙베리 10
* 브라우저
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,206 @@
<!---
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.
-->
# cordova-plugin-device
이 플러그인 정의 전역 `device` 개체, 디바이스의 하드웨어 및 소프트웨어에 설명 합니다. 개체는 전역 범위에서 비록 그것은 후까지 사용할 수 있는 `deviceready` 이벤트.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## 설치
cordova plugin add cordova-plugin-device
## 속성
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
코르도바는 장치에서 실행 중인 버전을 얻을.
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* 브라우저
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
## device.model
`device.model`소자의 모델 또는 제품의 이름을 반환 합니다. 값 장치 제조업체에서 설정 되 고 동일 제품의 버전 간에 다를 수 있습니다.
### 지원 되는 플랫폼
* 안 드 로이드
* 블랙베리 10
* 브라우저
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Http://theiphonewiki.com/wiki/index.php?title=Models 참조 / / var 모델 = device.model;
### 안 드 로이드 단점
* 어떤은 종종 프로덕션 코드 이름 대신 [제품 모델 이름][1], [제품 이름][2] 을 가져옵니다. 예를 들어 넥서스 하나 반환 합니다 `Passion` , 모토로라 Droid를 반환 합니다`voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#MODEL
[2]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
### Tizen 특수
* 예를 들어, 공급 업체에 의해 할당 된 디바이스 모델을 반환 합니다.`TIZEN`
### Windows Phone 7, 8 특수
* 제조업체에서 지정 하는 장치 모델을 반환 합니다. 예를 들어 삼성 포커스를 반환 합니다.`SGH-i917`.
## device.platform
장치의 운영 체제 이름을 얻을.
var string = device.platform;
### 지원 되는 플랫폼
* 안 드 로이드
* 블랙베리 10
* Browser4
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 단점
Windows Phone 7 장치 보고 플랫폼으로`WinCE`.
### Windows Phone 8 단점
Windows Phone 8 장치 보고 플랫폼으로`Win32NT`.
## device.uuid
소자의 보편적으로 고유 식별자 ([UUID][3] 를 얻을합니다).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### 설명
UUID 생성 방법의 자세한 내용은 장치 제조업체에 의해 결정 됩니다 및 소자의 플랫폼 이나 모델.
### 지원 되는 플랫폼
* 안 드 로이드
* 블랙베리 10
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
/ / 안 드 로이드: (문자열로 다시!) 임의의 64 비트 정수를 반환 합니다 / / 정수 장치의 첫 번째 부팅에서 생성 / / / / 블랙베리: 디바이스의 핀 번호를 반환 합니다 / / 이것은 9 자리 고유 정수 (문자열로 비록!) / / / / 아이폰: (UIDevice 클래스 설명서에서 읊 었) / / 문자열 여러 하드웨어에서 생성 하는 해시 값을 식별 하는 반환 합니다.
/ 그것은 모든 장치에 대 한 고유 해야 보장 되 고 묶일 수 없습니다 / / / 사용자 계정에.
/ / Windows Phone 7: 장치 + 현재 사용자의 해시를 반환 합니다 / / 사용자 정의 되지 않은 경우 guid 생성 되 고 응용 프로그램을 제거할 때까지 유지 됩니다 / / Tizen: 반환 장치 IMEI (국제 모바일 기기 식별 또는 IMEI 숫자입니다 / / 모든 GSM와 UMTS 휴대 전화 고유.
var deviceID = device.uuid;
### iOS 특질
`uuid`ios 장치에 고유 하지 않습니다 하지만 각 설치에 대 한 응용 프로그램 마다 다릅니다. 삭제 하 고 다시 애플 리 케이 션을 설치 하는 경우 변경 가능 하 게 또한 iOS를 업그레이드 하거나 때 버전 (iOS 5.1에에서 명백한) 당 응용 프로그램 업그레이드도 하 고. `uuid`은 신뢰할 수 있는 값이 아닙니다.
### Windows Phone 7, 8 특수
`uuid`Windows Phone 7 필요 허가 `ID_CAP_IDENTITY_DEVICE` . Microsoft는 곧이 속성을 세웁니다 가능성이 것입니다. 기능을 사용할 수 없는 경우 응용 프로그램 장치에 응용 프로그램의 설치 하는 동안 유지 하는 영구 guid를 생성 합니다.
## device.version
운영 체제 버전을 얻을.
var string = device.version;
### 지원 되는 플랫폼
* 안 드 로이드 2.1 +
* 블랙베리 10
* 브라우저
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 빠른 예제
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,214 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
Ten plugin określa globalne `device` obiekt, który opisuje urządzenia sprzętowe i programowe. Mimo, że obiekt jest w globalnym zasięgu, nie jest dostępne dopiero po `deviceready` zdarzenie.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Instalacja
cordova plugin add cordova-plugin-device
## Właściwości
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Pobierz wersję Cordova działa na urządzeniu.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Przeglądarka
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
## device.model
`device.model`Zwraca nazwę modelu lub produktu. Wartość jest zestaw przez producenta urządzenia i mogą się różnić między wersjami tego samego produktu.
### Obsługiwane platformy
* Android
* BlackBerry 10
* Przeglądarka
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Zobacz http://theiphonewiki.com/wiki/index.php?title=Models / / modelu var = device.model;
### Dziwactwa Androida
* Pobiera [nazwę produktu](http://developer.android.com/reference/android/os/Build.html#PRODUCT) zamiast [nazwy modelu](http://developer.android.com/reference/android/os/Build.html#MODEL), który często jest nazwą kod produkcji. Na przykład, Nexus One zwraca `Passion` , i zwraca Motorola Droid`voles`.
### Dziwactwa Tizen
* Zwraca modelu urządzenia przypisane przez dostawcę, na przykład,`TIZEN`
### Windows Phone 7 i 8 dziwactwa
* Zwraca modelu urządzenia, określonej przez producenta. Na przykład Samsung ostrości zwraca`SGH-i917`.
## device.platform
Uzyskać nazwę systemu operacyjnego urządzenia.
var string = device.platform;
### Obsługiwane platformy
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Dziwactwa Windows Phone 7
Urządzenia Windows Phone 7 raport platformy jako`WinCE`.
### Windows Phone 8 dziwactwa
Urządzenia Windows Phone 8 raport platformy jako`Win32NT`.
## device.uuid
Się urządzenia uniwersalnie unikatowy identyfikator ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)).
var string = device.uuid;
### Opis
Szczegóły jak UUID jest generowane są określane przez producenta urządzenia i są specyficzne dla platformy lub modelu urządzenia.
### Obsługiwane platformy
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
// Android: Returns a random 64-bit integer (as a string, again!)
// The integer is generated on the device's first boot
//
// BlackBerry: Returns the PIN number of the device
// This is a nine-digit unique integer (as a string, though!)
//
// iPhone: (Paraphrased from the UIDevice Class documentation)
// Returns a string of hash values created from multiple hardware identifies.
// It is guaranteed to be unique for every device and can't be tied
// to the user account.
// Windows Phone 7 : Returns a hash of device+current user,
// if the user is not defined, a guid is generated and will persist until the app is uninstalled
// Tizen: returns the device IMEI (International Mobile Equipment Identity or IMEI is a number
// unique to every GSM and UMTS mobile phone.
var deviceID = device.uuid;
### iOS dziwactwo
`uuid`Na iOS nie jest przypisany do urządzenia, ale różni się dla każdej aplikacji, dla każdej instalacji. Zmienia się jeśli możesz usunąć i ponownie zainstalować aplikację, a ewentualnie także po aktualizacji iOS czy nawet uaktualnienia aplikacji dla wersji (widoczny w iOS 5.1). `uuid`Jest nie wiarygodne wartości.
### Windows Phone 7 i 8 dziwactwa
`uuid`Dla Windows Phone 7 wymaga uprawnień `ID_CAP_IDENTITY_DEVICE` . Microsoft będzie prawdopodobnie potępiać ten wkrótce. Jeśli funkcja nie jest dostępna, aplikacja generuje trwałe identyfikator guid, który jest utrzymywany przez czas trwania instalacji aplikacji na urządzeniu.
## device.version
Pobierz wersję systemu operacyjnego.
var string = device.version;
### Obsługiwane platformy
* Android 2.1 +
* BlackBerry 10
* Przeglądarka
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,206 @@
<!---
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.
-->
# cordova-plugin-device
Ten plugin określa globalne `device` obiekt, który opisuje urządzenia sprzętowe i programowe. Mimo, że obiekt jest w globalnym zasięgu, nie jest dostępne dopiero po `deviceready` zdarzenie.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Instalacja
cordova plugin add cordova-plugin-device
## Właściwości
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Pobierz wersję Cordova działa na urządzeniu.
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Przeglądarka
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
## device.model
`device.model`Zwraca nazwę modelu lub produktu. Wartość jest zestaw przez producenta urządzenia i mogą się różnić między wersjami tego samego produktu.
### Obsługiwane platformy
* Android
* BlackBerry 10
* Przeglądarka
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. Zobacz http://theiphonewiki.com/wiki/index.php?title=Models / / modelu var = device.model;
### Dziwactwa Androida
* Pobiera [nazwę produktu][1] zamiast [nazwy modelu][2], który często jest nazwą kod produkcji. Na przykład, Nexus One zwraca `Passion` , i zwraca Motorola Droid`voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
[2]: http://developer.android.com/reference/android/os/Build.html#MODEL
### Dziwactwa Tizen
* Zwraca modelu urządzenia przypisane przez dostawcę, na przykład,`TIZEN`
### Windows Phone 7 i 8 dziwactwa
* Zwraca modelu urządzenia, określonej przez producenta. Na przykład Samsung ostrości zwraca`SGH-i917`.
## device.platform
Uzyskać nazwę systemu operacyjnego urządzenia.
var string = device.platform;
### Obsługiwane platformy
* Android
* BlackBerry 10
* Browser4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Dziwactwa Windows Phone 7
Urządzenia Windows Phone 7 raport platformy jako`WinCE`.
### Windows Phone 8 dziwactwa
Urządzenia Windows Phone 8 raport platformy jako`Win32NT`.
## device.uuid
Się urządzenia uniwersalnie unikatowy identyfikator ([UUID][3]).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### Opis
Szczegóły jak UUID jest generowane są określane przez producenta urządzenia i są specyficzne dla platformy lub modelu urządzenia.
### Obsługiwane platformy
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
/ / Android: zwraca losowe 64-bitowa liczba całkowita (jako ciąg, znowu!) / / liczba całkowita jest generowany na pierwszego uruchomienia urządzenia / / / / BlackBerry: zwraca numer PIN urządzenia / / to jest unikatową liczbą całkowitą dziewięciu cyfr (jako ciąg, choć!) / / / / iPhone: (zacytowana w dokumentacji klasy UIDevice) / / zwraca ciąg wartości mieszania utworzone z wielu sprzętu identyfikuje.
Zapewniona jest unikatowy dla każdego urządzenia i nie może być związane z / do konta użytkownika.
/ / Windows Phone 7: zwraca wartość mieszania urządzenia + bieżący użytkownik, / / jeśli nie zdefiniowane przez użytkownika, identyfikator guid jest generowany i będzie trwać do czasu odinstalowania aplikacji / / Tizen: zwraca urządzenia IMEI (International Mobile Equipment Identity lub IMEI jest liczbą / / unikatowe dla każdego telefonu komórkowego GSM i UMTS.
var deviceID = device.uuid;
### iOS dziwactwo
`uuid`Na iOS nie jest przypisany do urządzenia, ale różni się dla każdej aplikacji, dla każdej instalacji. Zmienia się jeśli możesz usunąć i ponownie zainstalować aplikację, a ewentualnie także po aktualizacji iOS czy nawet uaktualnienia aplikacji dla wersji (widoczny w iOS 5.1). `uuid`Jest nie wiarygodne wartości.
### Windows Phone 7 i 8 dziwactwa
`uuid`Dla Windows Phone 7 wymaga uprawnień `ID_CAP_IDENTITY_DEVICE` . Microsoft będzie prawdopodobnie potępiać ten wkrótce. Jeśli funkcja nie jest dostępna, aplikacja generuje trwałe identyfikator guid, który jest utrzymywany przez czas trwania instalacji aplikacji na urządzeniu.
## device.version
Pobierz wersję systemu operacyjnego.
var string = device.version;
### Obsługiwane platformy
* Android 2.1 +
* BlackBerry 10
* Przeglądarka
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Szybki przykład
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,219 @@
<!---
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.
-->
# cordova-plugin-device
Этот плагин определяет глобальный объект `device`, который описывает оборудование и программное обеспечение устройства. Несмотря на то что объект в глобальной области видимости, он не доступен до того момента пока не произойдет событие `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## Установка
cordova plugin add cordova-plugin-device
## Параметры
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
Возвращает версию Cordova, работающую на устройстве.
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* BlackBerry 10
* Обозреватель
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
## device.model
Свойство `device.model` возвращает имя устройства модели или продукта. Значение устанавливается производителем устройства и могут отличаться в разных версиях одного и того же продукта.
### Поддерживаемые платформы
* Android
* BlackBerry 10
* Обозреватель
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Краткий пример
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. See http://theiphonewiki.com/wiki/index.php?title=Models
//
var model = device.model;
### Особенности Android
* Возвращает [имя продукта][1] , а не [имя модели][2], которое часто является производственным кодом. Например, Nexus One из них возвращает `Passion` , и Motorola Droid возвращает `voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
[2]: http://developer.android.com/reference/android/os/Build.html#MODEL
### Особенности Tizen
* Возвращает модель устройства, назначенного вендором, например,`TIZEN`
### Особенности Windows Phone 7 и 8
* Возвращает модель устройства, указанной заводом-изготовителем. Например Samsung Focus возвращает `SGH-i917`.
## device.platform
Получите имя операционной системы устройства.
var string = device.platform;
### Поддерживаемые платформы
* Android
* BlackBerry 10
* Браузером4
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Краткий пример
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Особенности Windows Phone 7
Windows Phone 7 устройства сообщают платформу как `WinCE`.
### Особенности Windows Phone 8
Устройства Windows Phone 8 сообщают платформу как `Win32NT`.
## device.uuid
Возвращает универсальный уникального идентификатора ([UUID][3] устройства).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### Описание
Подробная информация о том как UUID генерируется, определяются изготовителем устройства и являются специфическими для платформы или модели устройства.
### Поддерживаемые платформы
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Краткий пример
// Android: Возвращает случайное 64-разрядное целое число (в виде строки, опять!)
// целое число генерируется при первой загрузке устройства
//
// BlackBerry: Возвращает номер PIN устройства
// это 9 значный уникальный целочисленный (как строка, хотя!)
//
// iPhone: (Перефразировано из документации класса UIDevice)
// возвращает строку хэш-значения, созданные из нескольких аппаратных определяет.
// Это значение гарантированно является уникальным для каждого устройства и не может быть привязано
// к учетной записи пользователя.
// Windows Phone 7: Возвращает хэш устройство + текущего пользователя,
// если пользователь не определен, формируется guid который и будет сохраняться до тех пор, пока приложение не удалиться
// Tizen: возвращает IMEI устройства (Международный идентификатор мобильного оборудования или IMEI это число
// уникальное для каждого мобильного телефона GSM и UMTS.
var deviceID = device.uuid;
### Особенности iOS
На iOS `uuid` не является уникальным для устройства, но варьируется для каждого приложения, и для каждой установки. Значение меняется, если удалить и повторно установить приложение, и возможно также когда вы обновите iOS, или даже обновить приложение до следующей версии (очевидно в iOS 5.1). Значение `uuid` не является надежным.
### Особенности Windows Phone 7 и 8
Для Windows Phone 7 `uuid` требует разрешения `ID_CAP_IDENTITY_DEVICE` . Microsoft скорее всего скоро сделает это свойство устаревшим. Если возможность недоступна, приложение создает постоянные guid, который сохраняется на все время установки приложения на устройстве.
## device.version
Возвращает версию операционной системы.
var string = device.version;
### Поддерживаемые платформы
* Android 2.1 +
* BlackBerry 10
* Обозреватель
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Краткий пример
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,203 @@
<!--
# license: 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.
-->
# cordova-plugin-device
[![Build Status](https://travis-ci.org/apache/cordova-plugin-device.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-device)
這個外掛程式定義全球 `device` 物件,描述該設備的硬體和軟體。 雖然物件是在全球範圍內,但不是可用,直到後 `deviceready` 事件。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## 安裝
cordova plugin add cordova-plugin-device
## 屬性
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
獲取科爾多瓦在設備上運行的版本。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 瀏覽器
* 火狐瀏覽器作業系統
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
## device.model
`device.model`返回設備的模型或產品的名稱。值由設備製造商設置和同一產品的不同版本可能不同。
### 支援的平臺
* Android 系統
* 黑莓 10
* 瀏覽器
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. 請參閱 HTTP://theiphonewiki.com/wiki/index.php?title=Models / / var 模型 = device.model
### Android 的怪癖
* 獲取[產品名稱](http://developer.android.com/reference/android/os/Build.html#PRODUCT)而不是[產品型號名稱](http://developer.android.com/reference/android/os/Build.html#MODEL),這往往是生產代碼名稱。 例如,Nexus One 返回 `Passion` ,和摩托羅拉 Droid 返回`voles`.
### Tizen 怪癖
* 例如,返回與供應商指派的設備模型`TIZEN`
### Windows Phone 7 和 8 怪癖
* 返回由製造商指定的設備模型。例如,三星焦點返回`SGH-i917`.
## device.platform
獲取設備的作業系統名稱。
var string = device.platform;
### 支援的平臺
* Android 系統
* 黑莓 10
* Browser4
* 火狐瀏覽器作業系統
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 的怪癖
Windows Phone 7 設備報告作為平臺`WinCE`.
### Windows Phone 8 怪癖
Windows Phone 8 設備報告作為平臺`Win32NT`.
## device.uuid
獲取設備的通用唯一識別碼 ([UUID](http://en.wikipedia.org/wiki/Universally_Unique_Identifier)).
var string = device.uuid;
### 說明
如何生成一個 UUID 的細節由設備製造商和特定于設備的平臺或模型。
### 支援的平臺
* Android 系統
* 黑莓 10
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
/ / Android: 一個隨機的 64 位整數 (作為字串返回,再次!) / / 上設備的第一次啟動生成的整數 / / / / 黑莓手機: 返回設備的 PIN 號碼 / / 這是九個數字的唯一整數 (作為字串,雖然!) / / / / iPhone (從 UIDevice 類文檔解釋) / / 返回一個字串的雜湊值創建的多個硬體標識。
/ / 它保證是唯一的每個設備並不能綁 / / 到使用者帳戶。
/ / Windows Phone 7: 返回的雜湊代碼的設備 + 當前使用者,/ / 如果未定義使用者,則一個 guid 生成的並且將會保留直到卸載該應用程式 / / Tizen: 返回設備 IMEI (國際行動裝置身份或 IMEI 是一個數位 / / 獨有的每一個 UMTS 和 GSM 行動電話。
var deviceID = device.uuid;
### iOS 怪癖
`uuid`在 iOS 不是唯一的一種裝置,但對於每個應用程式,為每個安裝而異。 如果您刪除並重新安裝該應用程式,它更改和可能還當你升級 iOS,或甚至升級每個版本 (iOS 5.1 中存在明顯的) 的應用程式。 `uuid`不是一個可靠的值。
### Windows Phone 7 和 8 怪癖
`uuid`為 Windows Phone 7 須經許可 `ID_CAP_IDENTITY_DEVICE` 。 Microsoft 可能會很快棄用此屬性。 如果沒有可用的能力,應用程式將生成設備上應用程式的安裝過程中保持持續的 guid。
## device.version
獲取作業系統版本。
var string = device.version;
### 支援的平臺
* Android 2.1 +
* 黑莓 10
* 瀏覽器
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,206 @@
<!---
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.
-->
# cordova-plugin-device
這個外掛程式定義全球 `device` 物件,描述該設備的硬體和軟體。 雖然物件是在全球範圍內,但不是可用,直到後 `deviceready` 事件。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(device.cordova);
}
## 安裝
cordova plugin add cordova-plugin-device
## 屬性
* device.cordova
* device.model
* device.platform
* device.uuid
* device.version
## device.cordova
獲取科爾多瓦在設備上運行的版本。
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 瀏覽器
* 火狐瀏覽器的作業系統
* iOS
*
* Windows Phone 7 和 8
* Windows 8
## device.model
`device.model`返回設備的模型或產品的名稱。值由設備製造商設置和同一產品的不同版本可能不同。
### 支援的平臺
* Android 系統
* 黑莓 10
* 瀏覽器
* iOS
*
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
// Android: Nexus One returns "Passion" (Nexus One code name)
// Motorola Droid returns "voles"
// BlackBerry: Torch 9800 returns "9800"
// Browser: Google Chrome returns "Chrome"
// Safari returns "Safari"
// iOS: for the iPad Mini, returns iPad2,5; iPhone 5 is iPhone 5,1. 請參閱 HTTP://theiphonewiki.com/wiki/index.php?title=Models / / var 模型 = device.model
### Android 的怪癖
* 獲取[產品名稱][1]而不是[產品型號名稱][2],這往往是生產代碼名稱。 例如,Nexus One 返回 `Passion` ,和摩托羅拉 Droid 返回`voles`.
[1]: http://developer.android.com/reference/android/os/Build.html#PRODUCT
[2]: http://developer.android.com/reference/android/os/Build.html#MODEL
### Tizen 怪癖
* 例如,返回與供應商指派的設備模型`TIZEN`
### Windows Phone 7 和 8 怪癖
* 返回由製造商指定的設備模型。例如,三星焦點返回`SGH-i917`.
## device.platform
獲取設備的作業系統名稱。
var string = device.platform;
### 支援的平臺
* Android 系統
* 黑莓 10
* Browser4
* 火狐瀏覽器的作業系統
* iOS
*
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
// Depending on the device, a few examples are:
// - "Android"
// - "BlackBerry 10"
// - Browser: returns "MacIntel" on Mac
// returns "Win32" on Windows
// - "iOS"
// - "WinCE"
// - "Tizen"
var devicePlatform = device.platform;
### Windows Phone 7 的怪癖
Windows Phone 7 設備報告作為平臺`WinCE`.
### Windows Phone 8 怪癖
Windows Phone 8 設備報告作為平臺`Win32NT`.
## device.uuid
獲取設備的通用唯一識別碼 ([UUID][3]).
[3]: http://en.wikipedia.org/wiki/Universally_Unique_Identifier
var string = device.uuid;
### 說明
如何生成一個 UUID 的細節由設備製造商和特定于設備的平臺或模型。
### 支援的平臺
* Android 系統
* 黑莓 10
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
/ / Android: 一個隨機的 64 位整數 (作為字串返回,再次!) / / 上設備的第一次啟動生成的整數 / / / / 黑莓手機: 返回設備的 PIN 號碼 / / 這是九個數字的唯一整數 (作為字串,雖然!) / / / / iPhone (從 UIDevice 類文檔解釋) / / 返回一個字串的雜湊值創建的多個硬體標識。
/ / 它保證是唯一的每個設備並不能綁 / / 到使用者帳戶。
/ / Windows Phone 7: 返回的雜湊代碼的設備 + 當前使用者,/ / 如果未定義使用者,則一個 guid 生成的並且將會保留直到卸載該應用程式 / / Tizen: 返回設備 IMEI (國際行動裝置身份或 IMEI 是一個數位 / / 獨有的每一個 UMTS 和 GSM 行動電話。
var deviceID = device.uuid;
### iOS 怪癖
`uuid`在 iOS 不是唯一的一種裝置,但對於每個應用程式,為每個安裝而異。 如果您刪除並重新安裝該應用程式,它更改和可能還當你升級 iOS,或甚至升級每個版本 (iOS 5.1 中存在明顯的) 的應用程式。 `uuid`不是一個可靠的值。
### Windows Phone 7 和 8 怪癖
`uuid`為 Windows Phone 7 須經許可 `ID_CAP_IDENTITY_DEVICE` 。 Microsoft 可能會很快棄用此屬性。 如果沒有可用的能力,應用程式將生成設備上應用程式的安裝過程中保持持續的 guid。
## device.version
獲取作業系統版本。
var string = device.version;
### 支援的平臺
* Android 2.1 +
* 黑莓 10
* 瀏覽器
* iOS
*
* Windows Phone 7 和 8
* Windows 8
### 快速的示例
// Android: Froyo OS would return "2.2"
// Eclair OS would return "2.1", "2.0.1", or "2.0"
// Version can also return update level "2.1-update1"
//
// BlackBerry: Torch 9800 using OS 6.0 would return "6.0.0.600"
//
// Browser: Returns version number for the browser
//
// iPhone: iOS 3.2 returns "3.2"
//
// Windows Phone 7: returns current OS version number, ex. on Mango returns 7.10.7720
// Tizen: returns "TIZEN_20120425_2"
var deviceVersion = device.version;
@@ -0,0 +1,84 @@
{
"_from": "cordova-plugin-device@2.0.2",
"_id": "cordova-plugin-device@2.0.2",
"_inBundle": false,
"_integrity": "sha1-/Ajzci5n7ve2xnv8mag99q3Quro=",
"_location": "/cordova-plugin-device",
"_phantomChildren": {},
"_requested": {
"type": "version",
"registry": true,
"raw": "cordova-plugin-device@2.0.2",
"name": "cordova-plugin-device",
"escapedName": "cordova-plugin-device",
"rawSpec": "2.0.2",
"saveSpec": null,
"fetchSpec": "2.0.2"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-device/-/cordova-plugin-device-2.0.2.tgz",
"_shasum": "fc08f3722e67eef7b6c67bfc99a83df6add0baba",
"_spec": "cordova-plugin-device@2.0.2",
"_where": "/home/saherelm/Documents/My Projects/xFrameworkTest",
"author": {
"name": "Apache Software Foundation"
},
"bugs": {
"url": "https://issues.apache.org/jira/browse/CB"
},
"bundleDependencies": false,
"cordova": {
"id": "cordova-plugin-device",
"platforms": [
"android",
"ios",
"windows",
"browser",
"osx"
]
},
"deprecated": false,
"description": "Cordova Device Plugin",
"devDependencies": {
"eslint": "^3.19.0",
"eslint-config-semistandard": "^11.0.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.3.0",
"eslint-plugin-node": "^5.0.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1"
},
"engines": {
"cordovaDependencies": {
"3.0.0": {
"cordova": ">100"
}
}
},
"homepage": "https://github.com/apache/cordova-plugin-device#readme",
"keywords": [
"cordova",
"device",
"ecosystem:cordova",
"cordova-android",
"cordova-ios",
"cordova-windows",
"cordova-browser",
"cordova-osx"
],
"license": "Apache-2.0",
"name": "cordova-plugin-device",
"repository": {
"type": "git",
"url": "git+https://github.com/apache/cordova-plugin-device.git"
},
"scripts": {
"eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests",
"test": "npm run eslint"
},
"types": "./types/index.d.ts",
"version": "2.0.2"
}
+93
View File
@@ -0,0 +1,93 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:rim="http://www.blackberry.com/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-device"
version="2.0.2">
<name>Device</name>
<description>Cordova Device Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,device</keywords>
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-device.git</repo>
<issue>https://issues.apache.org/jira/browse/CB/component/12320648</issue>
<js-module src="www/device.js" name="device">
<clobbers target="device" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Device" >
<param name="android-package" value="org.apache.cordova.device.Device"/>
</feature>
</config-file>
<source-file src="src/android/Device.java" target-dir="src/org/apache/cordova/device" />
</platform>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="Device">
<param name="ios-package" value="CDVDevice"/>
</feature>
</config-file>
<header-file src="src/ios/CDVDevice.h" />
<source-file src="src/ios/CDVDevice.m" />
</platform>
<!-- windows -->
<platform name="windows">
<js-module src="src/windows/DeviceProxy.js" name="DeviceProxy">
<runs />
</js-module>
</platform>
<!-- browser -->
<platform name="browser">
<config-file target="config.xml" parent="/*">
<feature name="Device">
<param name="browser-package" value="Device" />
</feature>
</config-file>
<js-module src="src/browser/DeviceProxy.js" name="DeviceProxy">
<runs />
</js-module>
</platform>
<!-- osx -->
<platform name="osx">
<config-file target="config.xml" parent="/*">
<feature name="Device">
<param name="ios-package" value="CDVDevice"/>
</feature>
</config-file>
<header-file src="src/osx/CDVDevice.h" />
<source-file src="src/osx/CDVDevice.m" />
</platform>
</plugin>
@@ -0,0 +1,174 @@
/*
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.device;
import java.util.TimeZone;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaInterface;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.provider.Settings;
public class Device extends CordovaPlugin {
public static final String TAG = "Device";
public static String platform; // Device OS
public static String uuid; // Device UUID
private static final String ANDROID_PLATFORM = "Android";
private static final String AMAZON_PLATFORM = "amazon-fireos";
private static final String AMAZON_DEVICE = "Amazon";
/**
* Constructor.
*/
public Device() {
}
/**
* 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);
Device.uuid = getUuid();
}
/**
* 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 if not.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("getDeviceInfo".equals(action)) {
JSONObject r = new JSONObject();
r.put("uuid", Device.uuid);
r.put("version", this.getOSVersion());
r.put("platform", this.getPlatform());
r.put("model", this.getModel());
r.put("manufacturer", this.getManufacturer());
r.put("isVirtual", this.isVirtual());
r.put("serial", this.getSerialNumber());
callbackContext.success(r);
}
else {
return false;
}
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Get the OS name.
*
* @return
*/
public String getPlatform() {
String platform;
if (isAmazonDevice()) {
platform = AMAZON_PLATFORM;
} else {
platform = ANDROID_PLATFORM;
}
return platform;
}
/**
* Get the device's Universally Unique Identifier (UUID).
*
* @return
*/
public String getUuid() {
String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
return uuid;
}
public String getModel() {
String model = android.os.Build.MODEL;
return model;
}
public String getProductName() {
String productname = android.os.Build.PRODUCT;
return productname;
}
public String getManufacturer() {
String manufacturer = android.os.Build.MANUFACTURER;
return manufacturer;
}
public String getSerialNumber() {
String serial = android.os.Build.SERIAL;
return serial;
}
/**
* Get the OS version.
*
* @return
*/
public String getOSVersion() {
String osversion = android.os.Build.VERSION.RELEASE;
return osversion;
}
public String getSDKVersion() {
@SuppressWarnings("deprecation")
String sdkversion = android.os.Build.VERSION.SDK;
return sdkversion;
}
public String getTimeZoneID() {
TimeZone tz = TimeZone.getDefault();
return (tz.getID());
}
/**
* Function to check if the device is manufactured by Amazon
*
* @return
*/
public boolean isAmazonDevice() {
if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) {
return true;
}
return false;
}
public boolean isVirtual() {
return android.os.Build.FINGERPRINT.contains("generic") ||
android.os.Build.PRODUCT.contains("sdk");
}
}
@@ -0,0 +1,84 @@
/*
*
* 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 browser = require('cordova/platform');
function getPlatform () {
return 'browser';
}
function getModel () {
return getBrowserInfo(true);
}
function getVersion () {
return getBrowserInfo(false);
}
function getBrowserInfo (getModel) {
var userAgent = navigator.userAgent;
var returnVal = '';
var offset;
if ((offset = userAgent.indexOf('Edge')) !== -1) {
returnVal = (getModel) ? 'Edge' : userAgent.substring(offset + 5);
} else if ((offset = userAgent.indexOf('Chrome')) !== -1) {
returnVal = (getModel) ? 'Chrome' : userAgent.substring(offset + 7);
} else if ((offset = userAgent.indexOf('Safari')) !== -1) {
if (getModel) {
returnVal = 'Safari';
} else {
returnVal = userAgent.substring(offset + 7);
if ((offset = userAgent.indexOf('Version')) !== -1) {
returnVal = userAgent.substring(offset + 8);
}
}
} else if ((offset = userAgent.indexOf('Firefox')) !== -1) {
returnVal = (getModel) ? 'Firefox' : userAgent.substring(offset + 8);
} else if ((offset = userAgent.indexOf('MSIE')) !== -1) {
returnVal = (getModel) ? 'MSIE' : userAgent.substring(offset + 5);
} else if ((offset = userAgent.indexOf('Trident')) !== -1) {
returnVal = (getModel) ? 'MSIE' : '11';
}
if ((offset = returnVal.indexOf(';')) !== -1 || (offset = returnVal.indexOf(' ')) !== -1) {
returnVal = returnVal.substring(0, offset);
}
return returnVal;
}
module.exports = {
getDeviceInfo: function (success, error) {
setTimeout(function () {
success({
cordova: browser.cordovaVersion,
platform: getPlatform(),
model: getModel(),
version: getVersion(),
uuid: null,
isVirtual: false
});
}, 0);
}
};
require('cordova/exec/proxy').add('Device', module.exports);
@@ -0,0 +1,30 @@
/*
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 <UIKit/UIKit.h>
#import <Cordova/CDVPlugin.h>
@interface CDVDevice : CDVPlugin
{}
+ (NSString*)cordovaVersion;
- (void)getDeviceInfo:(CDVInvokedUrlCommand*)command;
@end
@@ -0,0 +1,112 @@
/*
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.
*/
#include <sys/types.h>
#include <sys/sysctl.h>
#include "TargetConditionals.h"
#import <Cordova/CDV.h>
#import "CDVDevice.h"
@implementation UIDevice (ModelVersion)
- (NSString*)modelVersion
{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char* machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString* platform = [NSString stringWithUTF8String:machine];
free(machine);
return platform;
}
@end
@interface CDVDevice () {}
@end
@implementation CDVDevice
- (NSString*)uniqueAppInstanceIdentifier:(UIDevice*)device
{
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
static NSString* UUID_KEY = @"CDVUUID";
// Check user defaults first to maintain backwards compaitibility with previous versions
// which didn't user identifierForVendor
NSString* app_uuid = [userDefaults stringForKey:UUID_KEY];
if (app_uuid == nil) {
if ([device respondsToSelector:@selector(identifierForVendor)]) {
app_uuid = [[device identifierForVendor] UUIDString];
} else {
CFUUIDRef uuid = CFUUIDCreate(NULL);
app_uuid = (__bridge_transfer NSString *)CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
}
[userDefaults setObject:app_uuid forKey:UUID_KEY];
[userDefaults synchronize];
}
return app_uuid;
}
- (void)getDeviceInfo:(CDVInvokedUrlCommand*)command
{
NSDictionary* deviceProperties = [self deviceProperties];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:deviceProperties];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (NSDictionary*)deviceProperties
{
UIDevice* device = [UIDevice currentDevice];
return @{
@"manufacturer": @"Apple",
@"model": [device modelVersion],
@"platform": @"iOS",
@"version": [device systemVersion],
@"uuid": [self uniqueAppInstanceIdentifier:device],
@"cordova": [[self class] cordovaVersion],
@"isVirtual": @([self isVirtual])
};
}
+ (NSString*)cordovaVersion
{
return CDV_VERSION;
}
- (BOOL)isVirtual
{
#if TARGET_OS_SIMULATOR
return true;
#elif TARGET_IPHONE_SIMULATOR
return true;
#else
return false;
#endif
}
@end
@@ -0,0 +1,28 @@
/*
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 <Cordova/CDVPlugin.h>
@interface CDVDevice : CDVPlugin
+ (NSString*) cordovaVersion;
- (void) getDeviceInfo:(CDVInvokedUrlCommand*)command;
@end
@@ -0,0 +1,113 @@
/*
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.
*/
#include <sys/sysctl.h>
#import "CDVDevice.h"
#define SYSTEM_VERSION_PLIST @"/System/Library/CoreServices/SystemVersion.plist"
@implementation CDVDevice
- (NSString*) modelVersion {
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char* machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString* modelVersion = [NSString stringWithUTF8String:machine];
free(machine);
return modelVersion;
}
- (NSString*) getSerialNr {
NSString* serialNr;
io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));
if (platformExpert) {
CFTypeRef serialNumberAsCFString =
IORegistryEntryCreateCFProperty(platformExpert,
CFSTR(kIOPlatformSerialNumberKey),
kCFAllocatorDefault, 0);
if (serialNumberAsCFString) {
serialNr = (__bridge NSString*) serialNumberAsCFString;
}
IOObjectRelease(platformExpert);
}
return serialNr;
}
- (NSString*) uniqueAppInstanceIdentifier {
NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
static NSString* UUID_KEY = @"CDVUUID";
NSString* app_uuid = [userDefaults stringForKey:UUID_KEY];
if (app_uuid == nil) {
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
CFStringRef uuidString = CFUUIDCreateString(kCFAllocatorDefault, uuidRef);
app_uuid = [NSString stringWithString:(__bridge NSString*) uuidString];
[userDefaults setObject:app_uuid forKey:UUID_KEY];
[userDefaults synchronize];
CFRelease(uuidString);
CFRelease(uuidRef);
}
return app_uuid;
}
- (NSString*) platform {
return [NSDictionary dictionaryWithContentsOfFile:SYSTEM_VERSION_PLIST][@"ProductName"];
}
- (NSString*) systemVersion {
return [NSDictionary dictionaryWithContentsOfFile:SYSTEM_VERSION_PLIST][@"ProductVersion"];
}
- (void) getDeviceInfo:(CDVInvokedUrlCommand*) command {
NSDictionary* deviceProperties = [self deviceProperties];
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:deviceProperties];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
- (NSDictionary*) deviceProperties {
NSMutableDictionary* devProps = [NSMutableDictionary dictionaryWithCapacity:4];
devProps[@"manufacturer"] = @"Apple";
devProps[@"model"] = [self modelVersion];
devProps[@"platform"] = [self platform];
devProps[@"version"] = [self systemVersion];
devProps[@"uuid"] = [self uniqueAppInstanceIdentifier];
devProps[@"cordova"] = [[self class] cordovaVersion];
devProps[@"serial"] = [self getSerialNr];
devProps[@"isVirtual"] = @NO;
NSDictionary* devReturn = [NSDictionary dictionaryWithDictionary:devProps];
return devReturn;
}
+ (NSString*) cordovaVersion {
return CDV_VERSION;
}
@end
@@ -0,0 +1,96 @@
/*
*
* 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, createUUID */
var ROOT_CONTAINER = '{00000000-0000-0000-FFFF-FFFFFFFFFFFF}';
var DEVICE_CLASS_KEY = '{A45C254E-DF1C-4EFD-8020-67D146A850E0},10';
var DEVICE_CLASS_KEY_NO_SEMICOLON = '{A45C254E-DF1C-4EFD-8020-67D146A850E0}10';
var ROOT_CONTAINER_QUERY = 'System.Devices.ContainerId:="' + ROOT_CONTAINER + '"';
var HAL_DEVICE_CLASS = '4d36e966-e325-11ce-bfc1-08002be10318';
var DEVICE_DRIVER_VERSION_KEY = '{A8B865DD-2E3D-4094-AD97-E593A70C75D6},3';
module.exports = {
getDeviceInfo: function (win, fail, args) {
// deviceId aka uuid, stored in Windows.Storage.ApplicationData.current.localSettings.values.deviceId
var deviceId;
// get deviceId, or create and store one
var localSettings = Windows.Storage.ApplicationData.current.localSettings;
if (localSettings.values.deviceId) {
deviceId = localSettings.values.deviceId;
} else {
// App-specific hardware id could be used as uuid, but it changes if the hardware changes...
try {
var ASHWID = Windows.System.Profile.HardwareIdentification.getPackageSpecificToken(null).id;
deviceId = Windows.Storage.Streams.DataReader.fromBuffer(ASHWID).readGuid();
} catch (e) {
// Couldn't get the hardware UUID
deviceId = createUUID();
}
// ...so cache it per-install
localSettings.values.deviceId = deviceId;
}
var userAgent = window.clientInformation.userAgent;
// this will report "windows" in windows8.1 and windows phone 8.1 apps
// and "windows8" in windows 8.0 apps similar to cordova.js
// See https://github.com/apache/cordova-js/blob/master/src/windows/platform.js#L25
var devicePlatform = userAgent.indexOf('MSAppHost/1.0') === -1 ? 'windows' : 'windows8';
var versionString = userAgent.match(/Windows (?:Phone |NT )?([0-9.]+)/)[1];
var deviceInfo = new Windows.Security.ExchangeActiveSyncProvisioning.EasClientDeviceInformation();
// Running in the Windows Simulator is a remote session.
// Running in the Windows Phone Emulator has the systemProductName set to "Virtual"
var isVirtual = Windows.System.RemoteDesktop.InteractiveSession.isRemote || deviceInfo.systemProductName === 'Virtual';
var manufacturer = deviceInfo.systemManufacturer;
var model = deviceInfo.systemProductName;
var Pnp = Windows.Devices.Enumeration.Pnp;
Pnp.PnpObject.findAllAsync(Pnp.PnpObjectType.device,
[DEVICE_DRIVER_VERSION_KEY, DEVICE_CLASS_KEY],
ROOT_CONTAINER_QUERY)
.then(function (rootDevices) {
for (var i = 0; i < rootDevices.length; i++) {
var rootDevice = rootDevices[i];
if (!rootDevice.properties) continue;
if (rootDevice.properties[DEVICE_CLASS_KEY_NO_SEMICOLON] === HAL_DEVICE_CLASS) {
versionString = rootDevice.properties[DEVICE_DRIVER_VERSION_KEY];
break;
}
}
setTimeout(function () {
win({ platform: devicePlatform,
version: versionString,
uuid: deviceId,
isVirtual: isVirtual,
model: model,
manufacturer: manufacturer});
}, 0);
});
}
}; // exports
require('cordova/exec/proxy').add('Device', module.exports);
@@ -0,0 +1,14 @@
{
"name": "cordova-plugin-device-tests",
"version": "1.1.6-dev",
"description": "",
"cordova": {
"id": "cordova-plugin-device-tests",
"platforms": []
},
"keywords": [
"ecosystem:cordova"
],
"author": "",
"license": "Apache 2.0"
}
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
xmlns:rim="http://www.blackberry.com/ns/widgets"
xmlns:android="http://schemas.android.com/apk/res/android"
id="cordova-plugin-device-tests"
version="2.0.2">
<name>Cordova Device Plugin Tests</name>
<license>Apache 2.0</license>
<js-module src="tests.js" name="tests">
</js-module>
</plugin>
+113
View File
@@ -0,0 +1,113 @@
/*
*
* 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.
*
*/
/* eslint-env jasmine */
exports.defineAutoTests = function () {
describe('Device Information (window.device)', function () {
it('should exist', function () {
expect(window.device).toBeDefined();
});
it('should contain a platform specification that is a string', function () {
expect(window.device.platform).toBeDefined();
expect((String(window.device.platform)).length > 0).toBe(true);
});
it('should contain a version specification that is a string', function () {
expect(window.device.version).toBeDefined();
expect((String(window.device.version)).length > 0).toBe(true);
});
it('should contain a UUID specification that is a string or a number', function () {
expect(window.device.uuid).toBeDefined();
if (typeof window.device.uuid === 'string' || typeof window.device.uuid === 'object') {
expect((String(window.device.uuid)).length > 0).toBe(true);
} else {
expect(window.device.uuid > 0).toBe(true);
}
});
it('should contain a cordova specification that is a string', function () {
expect(window.device.cordova).toBeDefined();
expect((String(window.device.cordova)).length > 0).toBe(true);
});
it('should depend on the presence of cordova.version string', function () {
expect(window.cordova.version).toBeDefined();
expect((String(window.cordova.version)).length > 0).toBe(true);
});
it('should contain device.cordova equal to cordova.version', function () {
expect(window.device.cordova).toBe(window.cordova.version);
});
it('should contain a model specification that is a string', function () {
expect(window.device.model).toBeDefined();
expect((String(window.device.model)).length > 0).toBe(true);
});
it('should contain a manufacturer property that is a string', function () {
expect(window.device.manufacturer).toBeDefined();
expect((String(window.device.manufacturer)).length > 0).toBe(true);
});
it('should contain an isVirtual property that is a boolean', function () {
expect(window.device.isVirtual).toBeDefined();
expect(typeof window.device.isVirtual).toBe('boolean');
});
it('should contain a serial number specification that is a string', function () {
expect(window.device.serial).toBeDefined();
expect((String(window.device.serial)).length > 0).toBe(true);
});
});
};
exports.defineManualTests = function (contentEl, createActionButton) {
var logMessage = function (message, color) {
var log = document.getElementById('info');
var logLine = document.createElement('div');
if (color) {
logLine.style.color = color;
}
logLine.innerHTML = message;
log.appendChild(logLine);
};
var clearLog = function () {
var log = document.getElementById('info');
log.innerHTML = '';
};
var device_tests = '<h3>Press Dump Device button to get device information</h3>' +
'<div id="dump_device"></div>' +
'Expected result: Status box will get updated with device info. (i.e. platform, version, uuid, model, etc)';
contentEl.innerHTML = '<div id="info"></div>' + device_tests;
createActionButton('Dump device', function () {
clearLog();
logMessage(JSON.stringify(window.device, null, '\t'));
}, 'dump_device');
};
+36
View File
@@ -0,0 +1,36 @@
// Type definitions for Apache Cordova Device plugin
// Project: https://github.com/apache/cordova-plugin-device
// Definitions by: Microsoft Open Technologies Inc <http://msopentech.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
// Copyright (c) Microsoft Open Technologies Inc
// Licensed under the MIT license
/**
* This plugin defines a global device object, which describes the device's hardware and software.
* Although the object is in the global scope, it is not available until after the deviceready event.
*/
interface Device {
/** Get the version of Cordova running on the device. */
cordova: string;
/** Indicates that Cordova initialize successfully. */
available: boolean;
/**
* The device.model returns the name of the device's model or product. The value is set
* by the device manufacturer and may be different across versions of the same product.
*/
model: string;
/** Get the device's operating system name. */
platform: string;
/** Get the device's Universally Unique Identifier (UUID). */
uuid: string;
/** Get the operating system version. */
version: string;
/** Get the device's manufacturer. */
manufacturer: string;
/** Whether the device is running on a simulator. */
isVirtual: boolean;
/** Get the device hardware serial number. */
serial: string;}
declare var device: Device;
+83
View File
@@ -0,0 +1,83 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var argscheck = require('cordova/argscheck');
var channel = require('cordova/channel');
var utils = require('cordova/utils');
var exec = require('cordova/exec');
var cordova = require('cordova');
channel.createSticky('onCordovaInfoReady');
// Tell cordova channel to wait on the CordovaInfoReady event
channel.waitForInitialization('onCordovaInfoReady');
/**
* This represents the mobile device, and provides properties for inspecting the model, version, UUID of the
* phone, etc.
* @constructor
*/
function Device () {
this.available = false;
this.platform = null;
this.version = null;
this.uuid = null;
this.cordova = null;
this.model = null;
this.manufacturer = null;
this.isVirtual = null;
this.serial = null;
var me = this;
channel.onCordovaReady.subscribe(function () {
me.getInfo(function (info) {
// ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js
// TODO: CB-5105 native implementations should not return info.cordova
var buildLabel = cordova.version;
me.available = true;
me.platform = info.platform;
me.version = info.version;
me.uuid = info.uuid;
me.cordova = buildLabel;
me.model = info.model;
me.isVirtual = info.isVirtual;
me.manufacturer = info.manufacturer || 'unknown';
me.serial = info.serial || 'unknown';
channel.onCordovaInfoReady.fire();
}, function (e) {
me.available = false;
utils.alert('[ERROR] Error initializing Cordova: ' + e);
});
});
}
/**
* Get device info
*
* @param {Function} successCallback The function to call when the heading data is available
* @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
*/
Device.prototype.getInfo = function (successCallback, errorCallback) {
argscheck.checkArgs('fF', 'Device.getInfo', arguments);
exec(successCallback, errorCallback, 'Device', 'getDeviceInfo', []);
};
module.exports = new Device();
@@ -0,0 +1,23 @@
Copyright 2015-present Drifty Co.
http://drifty.com/
MIT License
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.
@@ -0,0 +1,220 @@
# cordova-plugin-ionic-keyboard
This plugin has been designed to work seamlessly with `cordova-plugin-ionic-webview`, so make sure you have it installed first:
- https://github.com/ionic-team/cordova-plugin-ionic-webview
- https://ionicframework.com/docs/wkwebview/
## Installation
```
cordova plugin add cordova-plugin-ionic-keyboard --save
```
## Preferences
### KeyboardResize (for iOS only)
> Boolean (true by default)
#### Possible values
- `true`: Showing/hiding the keyboard will trigger some kind of resizing of the app (see KeyboardResizeMode)
- `false`: Web will not be resized when the keyboard shows up.
```xml
<preference name="KeyboardResize" value="true" />
```
### KeyboardResizeMode (for iOS only)
> String ('native' by default)
#### Possible values
- `native`: The whole native webview will be resized when the keyboard shows/hides, it will affect the `vh` relative unit.
- `body`: Only the html `<body>` element will be resized. Relative units are not affected, because the viewport does not change.
- `ionic`: Only the html `ion-app` element will be resized. Only for ionic apps.
```xml
<preference name="KeyboardResizeMode" value="native" />
```
### KeyboardStyle (for iOS only)
> String ('light' by default)
#### Possible values
- `light`
- `dark`
```xml
<preference name="KeyboardStyle" value="dark" />
```
### HideKeyboardFormAccessoryBar (for iOS only)
> Boolean (true by default)
#### Possible values
- `true`: hides the keyboard accessory bar.
- `false`: shows the keyboard accessory bar.
```xml
<preference name="HideKeyboardFormAccessoryBar" value="false" />
```
### resizeOnFullScreen (for Android only)
There is an Android bug that prevents the keyboard from resizing the WebView when the app is in full screen (i.e. if StatusBar plugin is used to hide the StatusBar). This setting, if set to true, add a workaround that resizes the WebView even when the app is in full screen.
> Boolean (false by default)
#### Possible values
- `false`: doesn't resize the WebView when the app is in full screen.
- `true`: resizes the WebView when the app is in full screen.
```xml
<preference name="resizeOnFullScreen" value="true" />
```
## Methods
### Keyboard.hideFormAccessoryBar (for iOS only)
> Hide the keyboard toolbar.
Set to true to hide the additional toolbar that is on top of the keyboard. This toolbar features the Prev, Next, and Done buttons.
```js
Keyboard.hideFormAccessoryBar(value, successCallback);
```
#### Quick Example
```js
Keyboard.hideFormAccessoryBar(true);
Keyboard.hideFormAccessoryBar(false);
Keyboard.hideFormAccessoryBar(null, (currentValue) => { console.log(currentValue); });
```
### Keyboard.hide
> Hide the keyboard
Call this method to hide the keyboard
```js
Keyboard.hide();
```
### Keyboard.show (for Android only)
> Show the keyboard
Call this method to show the keyboard.
```js
Keyboard.show();
```
### Keyboard.setResizeMode (for iOS only)
> Programmatically set the resize mode
Call the method with parameter to set the resize mode.
```js
// Possible values are the same as for 'KeyboardResizeMode' preference
Keyboard.setResizeMode('native');
Keyboard.setResizeMode('body');
Keyboard.setResizeMode('ionic');
```
### Keyboard.setKeyboardStyle (for iOS only)
> Programmatically set the keyboard style
```js
// Possible values are the same as for 'KeyboardStyle' preference
Keyboard.setKeyboardStyle('light'); // <- default
Keyboard.setKeyboardStyle('dark');
```
### Keyboard.disableScroll (for iOS only)
> Programmatically enable or disable the WebView scroll
```js
Keyboard.disableScroll(true); // <- default
Keyboard.disableScroll(false);
```
## Properties
### Keyboard.isVisible
> Determine if the keyboard is visible.
Read this property to determine if the keyboard is visible.
```js
if (Keyboard.isVisible) {
// do something
}
```
## Events
### keyboardDidHide
> This event is fired when the keyboard is fully closed.
Attach handler to this event to be able to receive notification when keyboard is closed.
```js
window.addEventListener('keyboardDidHide', () => {
// Describe your logic which will be run each time keyboard is closed.
});
```
### keyboardDidShow
> This event is fired when the keyboard is fully open.
Attach handler to this event to be able to receive notification when keyboard is opened.
```js
window.addEventListener('keyboardDidShow', (event) => {
// Describe your logic which will be run each time when keyboard is about to be shown.
console.log(event.keyboardHeight);
});
```
### keyboardWillShow
> This event fires before keyboard will be shown.
Attach handler to this event to be able to receive notification when keyboard is about to be shown on the screen.
```js
window.addEventListener('keyboardWillShow', (event) => {
// Describe your logic which will be run each time when keyboard is about to be shown.
console.log(event.keyboardHeight);
});
```
### keyboardWillHide
> This event fires before keyboard will be closed.
Attach handler to this event to be able to receive notification when keyboard is about to be closed.
```js
window.addEventListener('keyboardWillHide', () => {
// Describe your logic which will be run each time when keyboard is about to be closed.
});
```
@@ -0,0 +1,59 @@
{
"_from": "cordova-plugin-ionic-keyboard@^2.0.5",
"_id": "cordova-plugin-ionic-keyboard@2.2.0",
"_inBundle": false,
"_integrity": "sha512-yDUG+9ieKVRitq5mGlNxjaZh/MgEhFFIgTIPhqSbUaQ8UuZbawy5mhJAVClqY97q8/rcQtL6dCDa7x2sEtCLcA==",
"_location": "/cordova-plugin-ionic-keyboard",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cordova-plugin-ionic-keyboard@^2.0.5",
"name": "cordova-plugin-ionic-keyboard",
"escapedName": "cordova-plugin-ionic-keyboard",
"rawSpec": "^2.0.5",
"saveSpec": null,
"fetchSpec": "^2.0.5"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-ionic-keyboard/-/cordova-plugin-ionic-keyboard-2.2.0.tgz",
"_shasum": "53ba9ccd5e765165446a094cfe042a2ddd87d81d",
"_spec": "cordova-plugin-ionic-keyboard@^2.0.5",
"_where": "/home/saherelm/Documents/My Projects/xFrameworkTest",
"author": {
"name": "Apache Software Foundation"
},
"bugs": {
"url": "https://github.com/ionic-team/cordova-plugin-ionic-keyboard/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Ionic Keyboard Plugin",
"devDependencies": {
"np": "^5.0.3",
"sync-cordova-xml": "^0.4.0"
},
"homepage": "https://github.com/ionic-team/cordova-plugin-ionic-keyboard#readme",
"keywords": [
"cordova",
"keyboard",
"ecosystem:cordova",
"cordova-ios",
"cordova-android"
],
"license": "Apache 2.0",
"name": "cordova-plugin-ionic-keyboard",
"repository": {
"type": "git",
"url": "git+https://github.com/ionic-team/cordova-plugin-ionic-keyboard.git"
},
"scripts": {
"deploy": "np --yolo",
"sync_plugin_xml": "sync-cordova-xml package.json plugin.xml --output=plugin.xml",
"version": "npm run sync_plugin_xml && git add plugin.xml"
},
"version": "2.2.0"
}
@@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:rim="http://www.blackberry.com/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-ionic-keyboard" version="2.2.0">
<name>cordova-plugin-ionic-keyboard</name>
<description>Ionic Keyboard Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,keyboard,ecosystem:cordova,cordova-ios,cordova-android</keywords>
<repo>https://github.com/ionic-team/cordova-plugin-ionic-keyboard.git</repo>
<issue>https://github.com/ionic-team/cordova-plugin-ionic-keyboard/issues</issue>
<author>Apache Software Foundation</author>
<engines>
<engine name="cordova" version=">=3.2.0"/>
</engines>
<!-- ios -->
<platform name="ios">
<js-module src="www/ios/keyboard.js" name="keyboard">
<clobbers target="window.Keyboard"/>
</js-module>
<config-file target="config.xml" parent="/*">
<feature name="CDVIonicKeyboard">
<param name="ios-package" value="CDVIonicKeyboard" onload="true"/>
</feature>
</config-file>
<header-file src="src/ios/CDVIonicKeyboard.h"/>
<source-file src="src/ios/CDVIonicKeyboard.m"/>
</platform>
<!-- android -->
<platform name="android">
<js-module src="www/android/keyboard.js" name="keyboard">
<clobbers target="window.Keyboard"/>
</js-module>
<config-file target="config.xml" parent="/*">
<feature name="CDVIonicKeyboard">
<param name="android-package" value="io.ionic.keyboard.CDVIonicKeyboard" onload="true"/>
</feature>
</config-file>
<source-file src="src/android/CDVIonicKeyboard.java" target-dir="src/io/ionic/keyboard"/>
</platform>
</plugin>
@@ -0,0 +1,165 @@
package io.ionic.keyboard;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.inputmethod.InputMethodManager;
// import additionally required classes for calculating screen height
import android.view.Display;
import android.graphics.Point;
import android.os.Build;
import android.widget.FrameLayout;
public class CDVIonicKeyboard extends CordovaPlugin {
private OnGlobalLayoutListener list;
private View rootView;
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
}
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if ("hide".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
//http://stackoverflow.com/a/7696791/1091751
InputMethodManager inputManager = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
View v = cordova.getActivity().getCurrentFocus();
if (v == null) {
callbackContext.error("No current focus");
} else {
inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
callbackContext.success(); // Thread-safe.
}
}
});
return true;
}
if ("show".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
callbackContext.success(); // Thread-safe.
}
});
return true;
}
if ("init".equals(action)) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
//calculate density-independent pixels (dp)
//http://developer.android.com/guide/practices/screens_support.html
DisplayMetrics dm = new DisplayMetrics();
cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
final float density = dm.density;
//http://stackoverflow.com/a/4737265/1091751 detect if keyboard is showing
FrameLayout content = (FrameLayout) cordova.getActivity().findViewById(android.R.id.content);
rootView = content.getRootView();
list = new OnGlobalLayoutListener() {
int previousHeightDiff = 0;
@Override
public void onGlobalLayout() {
boolean resize = preferences.getBoolean("resizeOnFullScreen", false);
if (resize) {
possiblyResizeChildOfContent();
}
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
rootView.getWindowVisibleDisplayFrame(r);
PluginResult result;
// cache properties for later use
int rootViewHeight = rootView.getRootView().getHeight();
int resultBottom = r.bottom;
// calculate screen height differently for android versions >= 21: Lollipop 5.x, Marshmallow 6.x
//http://stackoverflow.com/a/29257533/3642890 beware of nexus 5
int screenHeight;
if (Build.VERSION.SDK_INT >= 21) {
Display display = cordova.getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenHeight = size.y;
} else {
screenHeight = rootViewHeight;
}
int heightDiff = screenHeight - resultBottom;
int pixelHeightDiff = (int)(heightDiff / density);
if (pixelHeightDiff > 100 && pixelHeightDiff != previousHeightDiff) { // if more than 100 pixels, its probably a keyboard...
String msg = "S" + Integer.toString(pixelHeightDiff);
result = new PluginResult(PluginResult.Status.OK, msg);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
else if ( pixelHeightDiff != previousHeightDiff && ( previousHeightDiff - pixelHeightDiff ) > 100 ){
String msg = "H";
result = new PluginResult(PluginResult.Status.OK, msg);
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
previousHeightDiff = pixelHeightDiff;
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard/4)) {
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
} else {
frameLayoutParams.height = usableHeightSansKeyboard;
}
mChildOfContent.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);
}
};
mChildOfContent = content.getChildAt(0);
rootView.getViewTreeObserver().addOnGlobalLayoutListener(list);
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
PluginResult dataResult = new PluginResult(PluginResult.Status.OK);
dataResult.setKeepCallback(true);
callbackContext.sendPluginResult(dataResult);
}
});
return true;
}
return false; // Returning false results in a "MethodNotFound" error.
}
@Override
public void onDestroy() {
rootView.getViewTreeObserver().removeOnGlobalLayoutListener(list);
}
}
@@ -0,0 +1,24 @@
/*
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 <Cordova/CDVPlugin.h>
@interface CDVIonicKeyboard : CDVPlugin
@end
@@ -0,0 +1,411 @@
/*
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 "CDVIonicKeyboard.h"
#import <Cordova/CDVAvailability.h>
#import <Cordova/NSDictionary+CordovaPreferences.h>
#import <objc/runtime.h>
typedef enum : NSUInteger {
ResizeNone,
ResizeNative,
ResizeBody,
ResizeIonic,
} ResizePolicy;
#ifndef __CORDOVA_3_2_0
#warning "The keyboard plugin is only supported in Cordova 3.2 or greater, it may not work properly in an older version. If you do use this plugin in an older version, make sure the HideKeyboardFormAccessoryBar and KeyboardShrinksView preference values are false."
#endif
@interface CDVIonicKeyboard () <UIScrollViewDelegate>
@property (readwrite, assign, nonatomic) BOOL disableScroll;
@property (readwrite, assign, nonatomic) BOOL hideFormAccessoryBar;
@property (readwrite, assign, nonatomic) BOOL keyboardIsVisible;
@property (nonatomic, readwrite) ResizePolicy keyboardResizes;
@property (readwrite, assign, nonatomic) NSString* keyboardStyle;
@property (nonatomic, readwrite) BOOL isWK;
@property (nonatomic, readwrite) int paddingBottom;
@end
@implementation CDVIonicKeyboard
NSTimer *hideTimer;
- (id)settingForKey:(NSString *)key
{
return [self.commandDelegate.settings objectForKey:[key lowercaseString]];
}
#pragma mark Initialize
NSString* UIClassString;
NSString* WKClassString;
NSString* UITraitsClassString;
- (void)pluginInitialize
{
UIClassString = [@[@"UI", @"Web", @"Browser", @"View"] componentsJoinedByString:@""];
WKClassString = [@[@"WK", @"Content", @"View"] componentsJoinedByString:@""];
UITraitsClassString = [@[@"UI", @"Text", @"Input", @"Traits"] componentsJoinedByString:@""];
NSDictionary *settings = self.commandDelegate.settings;
self.disableScroll = ![settings cordovaBoolSettingForKey:@"ScrollEnabled" defaultValue:NO];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarDidChangeFrame:) name: UIApplicationDidChangeStatusBarFrameNotification object:nil];
self.keyboardResizes = ResizeNative;
BOOL doesResize = [settings cordovaBoolSettingForKey:@"KeyboardResize" defaultValue:YES];
if (!doesResize) {
self.keyboardResizes = ResizeNone;
NSLog(@"CDVIonicKeyboard: no resize");
} else {
NSString *resizeMode = [settings cordovaSettingForKey:@"KeyboardResizeMode"];
if (resizeMode) {
if ([resizeMode isEqualToString:@"ionic"]) {
self.keyboardResizes = ResizeIonic;
} else if ([resizeMode isEqualToString:@"body"]) {
self.keyboardResizes = ResizeBody;
}
}
NSLog(@"CDVIonicKeyboard: resize mode %lu", (unsigned long)self.keyboardResizes);
}
self.hideFormAccessoryBar = [settings cordovaBoolSettingForKey:@"HideKeyboardFormAccessoryBar" defaultValue:YES];
NSString *keyboardStyle = [settings cordovaSettingForKey:@"KeyboardStyle"];
if (keyboardStyle) {
[self setKeyboardStyle:keyboardStyle];
}
if ([settings cordovaBoolSettingForKey:@"KeyboardAppearanceDark" defaultValue:NO]) {
[self setKeyboardStyle:@"dark"];
}
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(onKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
[nc addObserver:self selector:@selector(onKeyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
[nc addObserver:self selector:@selector(onKeyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[nc addObserver:self selector:@selector(onKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
// Prevent WKWebView to resize window
BOOL isWK = self.isWK = [self.webView isKindOfClass:NSClassFromString(@"WKWebView")];
if (!isWK) {
NSLog(@"CDVIonicKeyboard: WARNING!!: Keyboard plugin works better with WK");
}
if (isWK) {
[nc removeObserver:self.webView name:UIKeyboardWillHideNotification object:nil];
[nc removeObserver:self.webView name:UIKeyboardWillShowNotification object:nil];
[nc removeObserver:self.webView name:UIKeyboardWillChangeFrameNotification object:nil];
[nc removeObserver:self.webView name:UIKeyboardDidChangeFrameNotification object:nil];
}
}
-(void)statusBarDidChangeFrame:(NSNotification*)notification
{
[self _updateFrame];
}
#pragma mark Keyboard events
- (void)resetScrollView
{
UIScrollView *scrollView = [self.webView scrollView];
[scrollView setContentInset:UIEdgeInsetsZero];
}
- (void)onKeyboardWillHide:(NSNotification *)sender
{
if (self.isWK) {
[self setKeyboardHeight:0 delay:0.01];
[self resetScrollView];
}
hideTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(fireOnHiding) userInfo:nil repeats:NO];
}
- (void)fireOnHiding {
[self.commandDelegate evalJs:@"Keyboard.fireOnHiding();"];
}
- (void)onKeyboardWillShow:(NSNotification *)note
{
if (hideTimer != nil) {
[hideTimer invalidate];
}
CGRect rect = [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
double height = rect.size.height;
if (self.isWK) {
double duration = [[note.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
[self setKeyboardHeight:height delay:duration+0.2];
[self resetScrollView];
}
[self setKeyboardStyle:self.keyboardStyle];
NSString *js = [NSString stringWithFormat:@"Keyboard.fireOnShowing(%d);", (int)height];
[self.commandDelegate evalJs:js];
}
- (void)onKeyboardDidShow:(NSNotification *)note
{
CGRect rect = [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
double height = rect.size.height;
if (self.isWK) {
[self resetScrollView];
}
NSString *js = [NSString stringWithFormat:@"Keyboard.fireOnShow(%d);", (int)height];
[self.commandDelegate evalJs:js];
}
- (void)onKeyboardDidHide:(NSNotification *)sender
{
[self.commandDelegate evalJs:@"Keyboard.fireOnHide();"];
[self resetScrollView];
}
- (void)setKeyboardHeight:(int)height delay:(NSTimeInterval)delay
{
if (self.keyboardResizes != ResizeNone) {
[self setPaddingBottom: height delay:delay];
}
}
- (void)setPaddingBottom:(int)paddingBottom delay:(NSTimeInterval)delay
{
if (self.paddingBottom == paddingBottom) {
return;
}
self.paddingBottom = paddingBottom;
__weak CDVIonicKeyboard* weakSelf = self;
SEL action = @selector(_updateFrame);
[NSObject cancelPreviousPerformRequestsWithTarget:weakSelf selector:action object:nil];
if (delay == 0) {
[self _updateFrame];
} else {
[weakSelf performSelector:action withObject:nil afterDelay:delay];
}
}
- (void)_updateFrame
{
CGSize statusBarSize = [[UIApplication sharedApplication] statusBarFrame].size;
int statusBarHeight = MIN(statusBarSize.width, statusBarSize.height);
int _paddingBottom = (int)self.paddingBottom;
if (statusBarHeight == 40) {
_paddingBottom = _paddingBottom + 20;
}
NSLog(@"CDVIonicKeyboard: updating frame");
// NOTE: to handle split screen correctly, the application's window bounds must be used as opposed to the screen's bounds.
CGRect f = [[[[UIApplication sharedApplication] delegate] window] bounds];
CGRect wf = self.webView.frame;
switch (self.keyboardResizes) {
case ResizeBody:
{
NSString *js = [NSString stringWithFormat:@"Keyboard.fireOnResize(%d, %d, document.body);",
_paddingBottom, (int)f.size.height];
[self.commandDelegate evalJs:js];
break;
}
case ResizeIonic:
{
NSString *js = [NSString stringWithFormat:@"Keyboard.fireOnResize(%d, %d, document.querySelector('ion-app'));",
_paddingBottom, (int)f.size.height];
[self.commandDelegate evalJs:js];
break;
}
case ResizeNative:
{
[self.webView setFrame:CGRectMake(wf.origin.x, wf.origin.y, f.size.width - wf.origin.x, f.size.height - wf.origin.y - self.paddingBottom)];
break;
}
default:
break;
}
[self resetScrollView];
}
#pragma mark Keyboard Style
- (void)setKeyboardStyle:(NSString*)style
{
IMP newImp = [style isEqualToString:@"dark"] ? imp_implementationWithBlock(^(id _s) {
return UIKeyboardAppearanceDark;
}) : imp_implementationWithBlock(^(id _s) {
return UIKeyboardAppearanceLight;
});
if (self.isWK) {
for (NSString* classString in @[WKClassString, UITraitsClassString]) {
Class c = NSClassFromString(classString);
Method m = class_getInstanceMethod(c, @selector(keyboardAppearance));
if (m != NULL) {
method_setImplementation(m, newImp);
} else {
class_addMethod(c, @selector(keyboardAppearance), newImp, "l@:");
}
}
}
else {
for (NSString* classString in @[UIClassString, UITraitsClassString]) {
Class c = NSClassFromString(classString);
Method m = class_getInstanceMethod(c, @selector(keyboardAppearance));
if (m != NULL) {
method_setImplementation(m, newImp);
} else {
class_addMethod(c, @selector(keyboardAppearance), newImp, "l@:");
}
}
}
_keyboardStyle = style;
}
#pragma mark HideFormAccessoryBar
static IMP UIOriginalImp;
static IMP WKOriginalImp;
- (void)setHideFormAccessoryBar:(BOOL)hideFormAccessoryBar
{
if (hideFormAccessoryBar == _hideFormAccessoryBar) {
return;
}
Method UIMethod = class_getInstanceMethod(NSClassFromString(UIClassString), @selector(inputAccessoryView));
Method WKMethod = class_getInstanceMethod(NSClassFromString(WKClassString), @selector(inputAccessoryView));
if (hideFormAccessoryBar) {
UIOriginalImp = method_getImplementation(UIMethod);
WKOriginalImp = method_getImplementation(WKMethod);
IMP newImp = imp_implementationWithBlock(^(id _s) {
return nil;
});
method_setImplementation(UIMethod, newImp);
method_setImplementation(WKMethod, newImp);
} else {
method_setImplementation(UIMethod, UIOriginalImp);
method_setImplementation(WKMethod, WKOriginalImp);
}
_hideFormAccessoryBar = hideFormAccessoryBar;
}
#pragma mark scroll
- (void)setDisableScroll:(BOOL)disableScroll {
if (disableScroll == _disableScroll) {
return;
}
if (disableScroll) {
self.webView.scrollView.scrollEnabled = NO;
self.webView.scrollView.delegate = self;
}
else {
self.webView.scrollView.scrollEnabled = YES;
self.webView.scrollView.delegate = nil;
}
_disableScroll = disableScroll;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
[scrollView setContentOffset: CGPointZero];
}
#pragma mark Plugin interface
- (void)hideFormAccessoryBar:(CDVInvokedUrlCommand *)command
{
if (command.arguments.count > 0) {
id value = [command.arguments objectAtIndex:0];
if (!([value isKindOfClass:[NSNumber class]])) {
value = [NSNumber numberWithBool:NO];
}
self.hideFormAccessoryBar = [value boolValue];
}
[self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:self.hideFormAccessoryBar]
callbackId:command.callbackId];
}
- (void)hide:(CDVInvokedUrlCommand *)command
{
[self.webView endEditing:YES];
}
- (void)setResizeMode:(CDVInvokedUrlCommand *)command
{
NSString * mode = [command.arguments objectAtIndex:0];
if ([mode isEqualToString:@"ionic"]) {
self.keyboardResizes = ResizeIonic;
} else if ([mode isEqualToString:@"body"]) {
self.keyboardResizes = ResizeBody;
} else if ([mode isEqualToString:@"native"]) {
self.keyboardResizes = ResizeNative;
} else {
self.keyboardResizes = ResizeNone;
}
}
- (void)keyboardStyle:(CDVInvokedUrlCommand*)command
{
id value = [command.arguments objectAtIndex:0];
if ([value isKindOfClass:[NSString class]]) {
value = [(NSString*)value lowercaseString];
} else {
value = @"light";
}
self.keyboardStyle = value;
}
- (void)disableScroll:(CDVInvokedUrlCommand*)command {
if (!command.arguments || ![command.arguments count]){
return;
}
id value = [command.arguments objectAtIndex:0];
if (value != [NSNull null]) {
self.disableScroll = [value boolValue];
}
}
#pragma mark dealloc
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
@@ -0,0 +1,84 @@
var argscheck = require('cordova/argscheck'),
utils = require('cordova/utils'),
exec = require('cordova/exec'),
channel = require('cordova/channel');
var Keyboard = function () {};
Keyboard.fireOnShow = function (height) {
Keyboard.isVisible = true;
cordova.fireWindowEvent('keyboardDidShow', {
'keyboardHeight': height
});
// To support the keyboardAttach directive listening events
// inside Ionic's main bundle
cordova.fireWindowEvent('native.keyboardshow', {
'keyboardHeight': height
});
};
Keyboard.fireOnHide = function () {
Keyboard.isVisible = false;
cordova.fireWindowEvent('keyboardDidHide');
// To support the keyboardAttach directive listening events
// inside Ionic's main bundle
cordova.fireWindowEvent('native.keyboardhide');
};
Keyboard.fireOnHiding = function () {
cordova.fireWindowEvent('keyboardWillHide');
};
Keyboard.fireOnShowing = function (height) {
cordova.fireWindowEvent('keyboardWillShow', {
'keyboardHeight': height
});
};
Keyboard.hideFormAccessoryBar = Keyboard.hideKeyboardAccessoryBar = function (hide) {
console.warn("Keyboard.hideKeyboardAccessoryBar() not supported in Android");
};
Keyboard.hide = function () {
exec(null, null, "CDVIonicKeyboard", "hide", []);
};
Keyboard.show = function () {
exec(null, null, "CDVIonicKeyboard", "show", []);
};
Keyboard.disableScroll = function (disable) {
console.warn("Keyboard.disableScroll() not supported in Android");
};
Keyboard.setResizeMode = function (mode) {
console.warn("Keyboard.setResizeMode() not supported in Android");
}
Keyboard.setKeyboardStyle = function(style) {
console.warn("Keyboard.setKeyboardStyle() not supported in Android");
};
channel.onCordovaReady.subscribe(function () {
exec(success, null, 'CDVIonicKeyboard', 'init', []);
function success(msg) {
var action = msg.charAt(0);
if (action === 'S') {
var keyboardHeight = parseInt(msg.substr(1));
Keyboard.fireOnShowing(keyboardHeight);
Keyboard.fireOnShow(keyboardHeight);
} else if (action === 'H') {
Keyboard.fireOnHiding();
Keyboard.fireOnHide();
}
}
});
Keyboard.isVisible = false;
module.exports = Keyboard;
@@ -0,0 +1,103 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var argscheck = require('cordova/argscheck'),
utils = require('cordova/utils'),
exec = require('cordova/exec');
var Keyboard = function () {};
Keyboard.fireOnShow = function (height) {
Keyboard.isVisible = true;
cordova.fireWindowEvent('keyboardDidShow', {
'keyboardHeight': height
});
// To support the keyboardAttach directive listening events
// inside Ionic's main bundle
cordova.fireWindowEvent('native.keyboardshow', {
'keyboardHeight': height
});
};
Keyboard.fireOnHide = function () {
Keyboard.isVisible = false;
cordova.fireWindowEvent('keyboardDidHide');
// To support the keyboardAttach directive listening events
// inside Ionic's main bundle
cordova.fireWindowEvent('native.keyboardhide');
};
Keyboard.fireOnHiding = function () {
cordova.fireWindowEvent('keyboardWillHide');
};
Keyboard.fireOnShowing = function (height) {
cordova.fireWindowEvent('keyboardWillShow', {
'keyboardHeight': height
});
};
Keyboard.fireOnResize = function (height, screenHeight, ele) {
if (!ele) {
return;
}
if (height === 0) {
ele.style.height = null;
} else {
ele.style.height = (screenHeight - height) + 'px';
}
};
Keyboard.hideFormAccessoryBar = function (hide, success) {
if (hide !== null && hide !== undefined) {
exec(success, null, "CDVIonicKeyboard", "hideFormAccessoryBar", [hide]);
} else {
exec(success, null, "CDVIonicKeyboard", "hideFormAccessoryBar", []);
}
};
Keyboard.hide = function () {
exec(null, null, "CDVIonicKeyboard", "hide", []);
};
Keyboard.show = function () {
console.warn('Showing keyboard not supported in iOS due to platform limitations.');
console.warn('Instead, use input.focus(), and ensure that you have the following setting in your config.xml: \n');
console.warn(' <preference name="KeyboardDisplayRequiresUserAction" value="false"/>\n');
};
Keyboard.disableScroll = function (disable) {
exec(null, null, "CDVIonicKeyboard", "disableScroll", [disable]);
};
Keyboard.setResizeMode = function (mode) {
exec(null, null, "CDVIonicKeyboard", "setResizeMode", [mode]);
}
Keyboard.setKeyboardStyle = function(style) {
exec(null, null, "CDVIonicKeyboard", "keyboardStyle", [style]);
};
Keyboard.isVisible = false;
module.exports = Keyboard;
@@ -0,0 +1,57 @@
version: 2
aliases:
- &restore-cache
keys:
- dependency-cache-{{ checksum "package.json" }}-1
- &save-cache
key: dependency-cache-{{ checksum "package.json" }}-1
paths:
- node_modules
defaults: &defaults
docker:
- image: circleci/node:10
working_directory: /tmp/workspace
jobs:
build:
<<: *defaults
steps:
- checkout
- restore_cache: *restore-cache
- run: npm install
- save_cache: *save-cache
- persist_to_workspace:
root: /tmp/workspace
paths:
- "*"
deploy:
<<: *defaults
environment:
GIT_AUTHOR_NAME: Ionitron
GIT_AUTHOR_EMAIL: hi@ionicframework.com
GIT_COMMITTER_NAME: Ionitron
GIT_COMMITTER_EMAIL: hi@ionicframework.com
steps:
- add_ssh_keys:
fingerprints:
- "ae:6d:3a:f1:cf:39:e1:94:6e:22:2a:9f:54:f9:b0:1b" # ionitron user key
- checkout
- attach_workspace:
at: /tmp/workspace
- run: npx semantic-release
workflows:
version: 2
build:
jobs:
- build
- deploy:
requires: [build]
filters:
branches:
only: stable
@@ -0,0 +1,248 @@
## [4.2.1](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v4.2.0...v4.2.1) (2020-04-28)
### Bug Fixes
* **ios:** release userAgentLock for IAB compat ([#558](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/558)) ([4c027f3](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/4c027f3e1dadf790b1d699936b90b670b401db9e)), closes [#551](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/551)
# [4.2.0](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v4.1.3...v4.2.0) (2020-04-14)
### Bug Fixes
* **ionassethandler.m:** fix startPath is getting null ([#463](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/463)) ([0bf16f1](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/0bf16f1b73b853f40781c5de83964457cc4493d5))
* **ios:** avoid app scrolling to top on keyboard hide ([#533](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/533)) ([7974eb4](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/7974eb4160f5e83cf4b3e98905beba1f874464a6))
* **ios:** Replace deprecated APIs ([#539](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/539)) ([27b9021](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/27b9021d5d76b3e6dc6bfc83ab46b98cd301e694))
### Features
* **android:** proxy service worker requests through local server ([#452](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/452)) ([c672175](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/c672175b7527d64b077f7715b2ff145325524add))
* **ios:** implement custom userAgent handling ([#537](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/537)) ([8587114](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/85871147ba8e5b23b693e518bf5ea800cccce8cc))
## [4.1.3](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v4.1.2...v4.1.3) (2019-10-30)
### Bug Fixes
* **android:** return proper mimeType for .mjs files ([#455](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/455)) ([173a313](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/173a313))
* **ios:** mitigate media memory usage ([#459](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/459)) ([cbd526d](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/cbd526d))
* **ios:** remove itms-services private scheme ([#464](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/464)) ([d7d2600](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/d7d2600))
## [4.1.2](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v4.1.1...v4.1.2) (2019-09-25)
### Bug Fixes
* **android:** allow schemes that start by https ([#437](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/437)) ([fab9d1f](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/fab9d1f))
* **Android:** return proper mimeType for wasm files ([0eb8a37](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/0eb8a37))
* **ios:** make programmatically focus work on iOS 13 ([#438](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/438)) ([7a514b0](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/7a514b0)), closes [#435](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/435)
## [4.1.1](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v4.1.0...v4.1.1) (2019-06-26)
### Bug Fixes
* **ios:** show error message when app fails to load ([#382](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/382)) ([cb1f026](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/cb1f026))
# [4.1.0](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v4.0.1...v4.1.0) (2019-06-10)
### Features
* **ios:** Add WKSuspendInBackground preference ([#356](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/356)) ([3613602](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/3613602))
## [4.0.1](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v4.0.0...v4.0.1) (2019-03-26)
### Bug Fixes
* **ios:** Fix autofocus on iOS 12.2 ([#334](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/334)) ([cb4c491](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/cb4c491)), closes [#330](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/330)
* account port on resolving uri path ([#321](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/321)) ([fdfe8aa](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/fdfe8aa))
# [4.0.0](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v3.1.2...v4.0.0) (2019-02-18)
### Features
* **ios:** Make iOS app Scheme configurable with a preference ([#307](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/307)) ([d52d37e](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/d52d37e)), closes [#282](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/282)
* **ios:** Remove WKSuspendInBackground preference ([#309](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/309)) ([73b6659](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/73b6659)), closes [#286](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/286)
### BREAKING CHANGES
* **ios:** Remove the WKSuspendInBackground preference, so app relying on that prefere will
not behave as expected
## [3.1.2](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v3.1.1...v3.1.2) (2019-02-04)
### Bug Fixes
* **Android:** Handle Range Requests for proper media file handling ([#298](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/298)) ([6f18248](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/6f18248)), closes [#248](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/248) [#205](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/205) [#141](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/141)
## [3.1.1](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v3.1.0...v3.1.1) (2019-01-18)
### Bug Fixes
* **ios:** Remove unused code ([#281](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/281)) ([fc7ea27](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/fc7ea27))
# [3.1.0](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v3.0.0...v3.1.0) (2019-01-17)
### Bug Fixes
* **ios:** Fix video playback of files with uppercase extension ([#264](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/264)) ([2c4b225](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/2c4b225)), closes [#260](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/260)
* Set engines to require Cordova CLI 7.1.0 or newer ([#276](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/276)) ([40f42e1](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/40f42e1)), closes [#263](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/263)
* Use a single scheme for all files ([#270](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/270)) ([3d1bcdd](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/3d1bcdd)), closes [#258](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/258)
### Features
* **Android:** Make app Scheme configurable with a preference ([#274](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/274)) ([18d9f2c](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/18d9f2c)), closes [#269](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/269) [#255](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/255)
# [3.0.0](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.3.1...v3.0.0) (2019-01-03)
### Bug Fixes
* **iOS:** Remove unused code ([#247](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/247)) ([bceb17a](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/bceb17a))
### Features
* Allows configuration of Mixed Content Mode ([#240](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/240)) ([486d412](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/486d412)), closes [#231](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/231)
* **Android:** Implement ionic-file and ionic-content urls ([#242](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/242)) ([8ef0c30](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/8ef0c30)), closes [#204](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/204) [#183](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/183)
* **iOS:** Remove GCDWebServer ([#244](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/244)) ([0dee0cf](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/0dee0cf))
* **WebViewLocalServer.java:** return 404 error code when a local file is not found ([#217](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/217)) ([f7a551e](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/f7a551e)), closes [#216](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/216)
### BREAKING CHANGES
* **iOS:** Sets deployment-target to 11, so will only work on iOS 11+
* Address changes
* changes the default from 1 (never) to 0 (always)
* **WebViewLocalServer.java:** Until now, the Android part of the plugin was returning a 200 http code even though
the requested file didn't exist. This behavior was inconsistent with the historical behavior of the
iOS webView. This change makes them both work in the same manner but introduces a breaking change
for the current Android users that are expecting a 200 http code no matter what and are testing the
not found error just by checking if the body is null.
## [2.3.1](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.3.0...v2.3.1) (2018-12-06)
### Bug Fixes
* Handle convertFileSrc when using ionic:// scheme ([#236](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/236)) ([89ce899](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/89ce899))
# [2.3.0](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.2.5...v2.3.0) (2018-12-05)
### Features
* **ios:** Add URLSchemeHandler for iOS 11+ ([#221](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/221)) ([4a973f4](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/4a973f4))
## [2.2.5](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.2.4...v2.2.5) (2018-11-20)
### Bug Fixes
* Add option for Dark keyboard appearance ([#44](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/44)) ([6c0fe56](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/6c0fe56))
## [2.2.4](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.2.3...v2.2.4) (2018-11-20)
### Bug Fixes
* fix keyboard displacement bug in iOS 12 WKWebView ([#201](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/201)) ([a670568](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/a670568))
## [2.2.3](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.2.2...v2.2.3) (2018-11-09)
### Bug Fixes
* Remove main and fix description ([d52db66](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/d52db66))
## [2.2.2](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.2.1...v2.2.2) (2018-11-09)
### Bug Fixes
* Add more server checks before loading urls or reloading ([#211](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/211)) ([60eff2f](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/60eff2f))
## [2.2.1](https://github.com/ionic-team/cordova-plugin-ionic-webview/compare/v2.2.0...v2.2.1) (2018-11-07)
### Bug Fixes
* Show error page if server is not running ([#207](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/207)) ([6a2e07e](https://github.com/ionic-team/cordova-plugin-ionic-webview/commit/6a2e07e))
<a name="2.2.0"></a>
### 2.2.0 (2018-10-04)
* Fix issue where two apps running on the same port could conflict with each other ([#169](https://github.com/ionic-team/cordova-plugin-ionic-webview/issues/165) & [#186](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/186))
* Add kitkat support (API 19) ([#144](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/144)) [@leo6104](https://github.com/leo6104)
* Fix issue where local server was being used if launch URL is external ([#169](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/169))
<a name="2.1.4"></a>
### 2.1.4 (2018-09-13)
* Allow Ionic Deploy `DisableDeploy` preference to disable loading of deploy updates ([#172](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/172))
<a name="2.1.3"></a>
### 2.1.3 (2018-09-06)
* Make server path relative ([#164](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/164))
<a name="2.1.2"></a>
### 2.1.2 (2018-09-05)
* Return 404 response when file doesn't exist ([#162](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/162))
* Load local assets if the app is a freshly installed binary ([#155](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/155))
* Reset stored server path on new binary ([#161](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/161))
<a name="2.1.1"></a>
### 2.1.1 (2018-09-04)
* Allow range requests for local files ([#154](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/154))
<a name="2.1.0"></a>
### 2.1.0 (2018-08-23)
* Add support for `cordova-android` 6 ([#150](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/150))
<a name="2.0.3"></a>
### 2.0.3 (2018-08-14)
* Fix nil reference by setting up the server URL before routes are set up. ([#135](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/135)) [@matejkramny](https://github.com/matejkramny)
* Resolve issue when app is launched in background. ([#124](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/124)) [@ghenry22](https://github.com/ghenry22)
<a name="2.0.2"></a>
### 2.0.2 (2018-07-30)
* Immediately load new server base path upon setting it. ([#132](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/132))
<a name="2.0.1"></a>
### 2.0.1 (2018-07-25)
* Avoid "not modified" response on iOS by always overriding last modified date. ([#127](https://github.com/ionic-team/cordova-plugin-ionic-webview/pull/127))
<a name="2.0.0"></a>
### 2.0.0 (2018-07-23)
* **BREAKING**: HTTP server now runs for iOS **and** Android, instead of just iOS. The server is configured the same for both platforms.
* **BREAKING**: HTTP server now loads the app from a base href of `/`. The app URL behaves like `http://localhost:8080/index.html` instead of `http://localhost:8080/Users/.../index.html`.
* **BREAKING**: HTTP server is configured to run in HTML5 routing mode (push state) by default.
* **BREAKING**: File access through the Web View must be served by the HTTP server to avoid security errors in the Web View. Loading files via `file://` is not allowed by the Web View. The HTTP server will serve files via the `_file_` prefix, e.g. `http://localhost:8080/_file_/Users/.../file.png`.
* `window.Ionic.normalizeURL()` has been deprecated. Use `window.Ionic.WebView.convertFileSrc()`.
* iOS update HTTP server to latest upstream version (GCDwebserve 3.4.2)
* iOS update HTTP server to restart sockets with error state when resuming from background
* iOS enable HTTP server to continue running in background if the webview is running.
* iOS enable Webview to continue running in background. Requires background mode capability enabled in xcode + valid use case as per app store requirements. If your app is not performing valid background tasks it will still be suspended by the OS as usual. As long as valid background tasks are running the webview will continue to function as expected.
* iOS add config.xml options:
* WKSuspendInBackground - defaults to true, if set to false then the webview and HTTP server will continue to run when the app is in the background or screen is locked
* WKPort - defaults to 8080, define the port that the HTTP server will listen on
* WKBind - defaults to localhost, if set to 127.0.0.1 then this IP will be used instead of the localhost hostname for the HTTP server
See [Github releases](https://github.com/ionic-team/cordova-plugin-ionic-webview/releases) for earlier changes.
@@ -0,0 +1,32 @@
# Contributing
:mega: **Support/Questions?**: Please see our [Support Page](https://ionicframework.com/support) for general support questions. The issues on GitHub should be reserved for bug reports and feature requests.
### Bug Reports
Please create an issue describing the bug in detail.
### Feature Requests
Please create an issue!
## Developing
Please familiarize yourself with [Cordova plugin development](https://cordova.apache.org/docs/en/latest/guide/hybrid/plugins/).
You can use `cordova plugin add` with a local directory to copy and compile plugin changes into a test project.
### Workflow
This repo uses [semantic-release](https://github.com/semantic-release/semantic-release), so it's important to follow a strict workflow to ensure properly automated releases.
* Work off of `master` branch (create new branch or fork)
* Make changes
* Use `npm run cz` (or `git cz` if [commitizen](https://github.com/commitizen/cz-cli) is installed globally) to make commits
* Create a pull request
* Pull requests will be approved and squashed into the `master` branch
* Try to make pull requests with a single objective (don't have multiple features in one PR, don't mix fixes and features in one PR, etc.)
### Publishing
Releases are automated in CI using [semantic-release](https://github.com/semantic-release/semantic-release) when the `stable` branch is pushed to Github. Rebase `master` with `stable`. Commits in `master` should be appropriately formatted from the PR workflow (see [Workflow](#workflow)).
@@ -0,0 +1,202 @@
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.
@@ -0,0 +1,181 @@
<!--
# license: 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.
-->
<!-- TODO: remove beta in README.md and CONTRIBUTING.md -->
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![Dependabot Status](https://api.dependabot.com/badges/status?host=github&identifier=104773211)](https://dependabot.com)
[![npm](https://img.shields.io/npm/v/cordova-plugin-ionic-webview.svg)](https://www.npmjs.com/package/cordova-plugin-ionic-webview)
# Ionic Web View for Cordova
A Web View plugin for Cordova, focused on providing the highest performance experience for Ionic apps (but can be used with any Cordova app).
This plugin uses WKWebView on iOS and the latest evergreen webview on Android. Additionally, this plugin makes it easy to use HTML5 style routing that web developers expect for building single-page apps.
Note: This repo and its documentation are for `cordova-plugin-ionic-webview` @ `4.x`, which uses the new features that may not work with all apps. See [Requirements](#plugin-requirements) and [Migrating to 4.x](#migrating-to-4x).
2.x documentation can be found [here](https://github.com/ionic-team/cordova-plugin-ionic-webview/blob/2.x/README.md).
:book: **Documentation**: [https://beta.ionicframework.com/docs/building/webview][ionic-webview-docs]
:mega: **Support/Questions?** Please see our [Support Page][ionic-support] for general support questions. The issues on GitHub should be reserved for bug reports and feature requests.
:sparkling_heart: **Want to contribute?** Please see [CONTRIBUTING.md](https://github.com/ionic-team/cordova-plugin-ionic-webview/blob/master/CONTRIBUTING.md).
## Configuration
This plugin has several configuration options that can be set in `config.xml`.
### Android and iOS Preferences
Preferences available for both iOS and Android
#### Hostname
`<preference name="Hostname" value="app" />`
Default value is `localhost`.
Example `ionic://app` on iOS, `http://app` on Android.
If you change it, you'll need to add a new `allow-navigation` entry in the `config.xml` for the configured url (i.e `<allow-navigation href="http://app/*"/>` if `Hostname` is set to `app`).
This is only needed for the Android url when using `http://`, `https://` or a custom scheme. All `ionic://` urls are whitelisted by the plugin.
### Android Preferences
Preferences only available Android platform
#### Scheme
```xml
<preference name="Scheme" value="https" />
```
Default value is `http`
Configures the Scheme the app uses to load the content.
#### ResolveServiceWorkerRequests
```xml
<preference name="ResolveServiceWorkerRequests" value="true" />
```
Default value is `false`
Enable to resolve requests made by Service Workers through the local server.
#### MixedContentMode
```xml
<preference name="MixedContentMode" value="2" />
```
Configures the WebView's behavior when an origin attempts to load a resource from a different origin.
Default value is `0` (`MIXED_CONTENT_ALWAYS_ALLOW`), which allows loading resources from other origins.
Other possible values are `1` (`MIXED_CONTENT_NEVER_ALLOW`) and `2` (`MIXED_CONTENT_COMPATIBILITY_MODE`)
[Android documentation](https://developer.android.com/reference/android/webkit/WebSettings.html#setMixedContentMode(int))
### iOS Preferences
Preferences only available for iOS platform
#### iosScheme
```xml
<preference name="iosScheme" value="httpsionic" />
```
Default value is `ionic`
Configures the Scheme the app uses to load the content.
Values like `http`, `https` or `file` are not valid and will use default value instead.
If you change it, you'll need to add a new `allow-navigation` entry in the `config.xml` for the configured scheme (i.e `<allow-navigation href="httpsionic://*"/>` if `iosScheme` is set to `httpsionic`).
#### WKSuspendInBackground
```xml
<preference name="WKSuspendInBackground" value="false" />
```
Default value is `true` (suspend).
Set to false to stop WKWebView suspending in background too eagerly.
#### KeyboardAppearanceDark
```xml
<preference name="KeyboardAppearanceDark" value="false" />
```
Whether to use a dark styled keyboard on iOS
#### ScrollEnabled
```xml
<preference name="ScrollEnabled" value="true" />
```
Ionic apps work better if the WKWebView is not scrollable, so the scroll is disabled by default, but can be enabled with this preference. This only affects the main ScrollView of the WKWebView, so only affects the body, not other scrollable components.
## Plugin Requirements
* **Cordova CLI**: 7.1.0+
* **iOS**: iOS 11+ and `cordova-ios` 4+
* **Android**: Android 4.4+ and `cordova-android` 6.4+
## Migrating to 4.x
1. Remove and re-add the Web View plugin:
```
cordova plugin rm cordova-plugin-ionic-webview
cordova plugin add cordova-plugin-ionic-webview@latest
```
1. Apps are now served from HTTP on Android by default.
* The default origin for requests from the Android WebView is `http://localhost`. If `Hostname` and `Scheme` preferences are set, then origin will be `schemeValue://HostnameValue`.
1. Apps are now served from `ionic://` scheme on iOS by default.
* The default origin for requests from the iOS WebView is `ionic://localhost`. If `Hostname` and `iosScheme` preferences are set, then origin will be `iosSchemeValue://HostnameValue`.
1. The WebView is not able to display images, videos or other files from file or content protocols or if it doesn't have protocol at all. For those cases use `window.Ionic.WebView.convertFileSrc()` to get the proper url.
1. Replace any usages of `window.Ionic.normalizeURL()` with `window.Ionic.WebView.convertFileSrc()`.
* For Ionic Angular projects, there is an [Ionic Native wrapper](https://beta.ionicframework.com/docs/native/ionic-webview):
```
npm install @ionic-native/ionic-webview@beta
```
[ionic-homepage]: https://ionicframework.com
[ionic-docs]: https://ionicframework.com/docs
[ionic-webview-docs]: https://beta.ionicframework.com/docs/building/webview
[ionic-support]: https://ionicframework.com/support
@@ -0,0 +1,107 @@
{
"_from": "cordova-plugin-ionic-webview@^4.0.0",
"_id": "cordova-plugin-ionic-webview@4.2.1",
"_inBundle": false,
"_integrity": "sha512-7KrmqLaOGq1RP8N2z1ezN1kqkWFzTwwMvQ3/qAkd+exxFZuOe3DIN4eaU1gdNphsxdirI8Ajnr9q4So5vQbWqw==",
"_location": "/cordova-plugin-ionic-webview",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cordova-plugin-ionic-webview@^4.0.0",
"name": "cordova-plugin-ionic-webview",
"escapedName": "cordova-plugin-ionic-webview",
"rawSpec": "^4.0.0",
"saveSpec": null,
"fetchSpec": "^4.0.0"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-ionic-webview/-/cordova-plugin-ionic-webview-4.2.1.tgz",
"_shasum": "42a67bef248472659d421494feb8245ef27becfa",
"_spec": "cordova-plugin-ionic-webview@^4.0.0",
"_where": "/home/saherelm/Documents/My Projects/xFrameworkTest",
"author": {
"name": "Ionic Team"
},
"bugs": {
"url": "https://github.com/ionic-team/cordova-plugin-ionic-webview/issues"
},
"bundleDependencies": false,
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
},
"deprecated": false,
"description": "Ionic Web View Engine Plugin",
"devDependencies": {
"@semantic-release/changelog": "^3.0.0",
"@semantic-release/exec": "^3.3.0",
"@semantic-release/git": "^7.0.4",
"@semantic-release/github": "^5.0.6",
"@semantic-release/npm": "^5.0.4",
"commitizen": "^4.0.3",
"cz-conventional-changelog": "^3.0.2",
"semantic-release": "^15.9.17",
"sync-cordova-xml": "^0.4.0"
},
"engines": {
"cordovaDependencies": {
"2.0.0": {
"cordova-android": ">=6.4.0",
"cordova-ios": ">=4.0.0-dev"
},
"3.1.0": {
"cordova": ">=7.1.0",
"cordova-android": ">=6.4.0",
"cordova-ios": ">=4.0.0-dev"
}
}
},
"homepage": "https://github.com/ionic-team/cordova-plugin-ionic-webview#readme",
"keywords": [
"cordova",
"wkwebview"
],
"license": "Apache-2.0",
"name": "cordova-plugin-ionic-webview",
"release": {
"branch": "stable",
"verifyConditions": [
"@semantic-release/changelog",
"@semantic-release/npm",
"@semantic-release/git",
"@semantic-release/github"
],
"prepare": [
"@semantic-release/changelog",
"@semantic-release/npm",
"@semantic-release/exec",
"@semantic-release/git"
],
"publish": [
"@semantic-release/github",
"@semantic-release/npm"
],
"success": [
"@semantic-release/github"
],
"failure": [
"@semantic-release/github"
],
"prepareCmd": "npm run version"
},
"repository": {
"type": "git",
"url": "git+https://github.com/ionic-team/cordova-plugin-ionic-webview.git"
},
"scripts": {
"cz": "git-cz",
"sync_plugin_xml": "sync-cordova-xml package.json plugin.xml --output=plugin.xml",
"version": "npm run sync_plugin_xml && git add plugin.xml"
},
"version": "4.2.1"
}
@@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
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.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:rim="http://www.blackberry.com/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" id="cordova-plugin-ionic-webview" version="4.2.1">
<name>cordova-plugin-ionic-webview</name>
<description>Ionic Web View Engine Plugin</description>
<license>Apache-2.0</license>
<keywords>cordova,wkwebview</keywords>
<repo>https://github.com/ionic-team/cordova-plugin-ionic-webview</repo>
<engines>
<engine name="cordova" version=">=7.1.0"/>
<engine name="cordova-ios" version=">=4.0.0-dev"/>
<engine name="apple-ios" version=">=11.0"/>
<engine name="cordova-android" version=">=6.4.0"/>
</engines>
<js-module src="src/www/util.js" name="IonicWebView">
<clobbers target="Ionic.WebView"/>
</js-module>
<platform name="android">
<config-file target="config.xml" parent="/*">
<allow-navigation href="http://localhost/*"/>
<allow-navigation href="https://localhost/*"/>
<allow-navigation href="ionic://*"/>
<preference name="webView" value="com.ionicframework.cordova.webview.IonicWebViewEngine"/>
<feature name="IonicWebView">
<param name="android-package" value="com.ionicframework.cordova.webview.IonicWebView"/>
</feature>
</config-file>
<source-file src="src/android/com/ionicframework/cordova/webview/IonicWebViewEngine.java" target-dir="src/com/ionicframework/cordova/webview"/>
<source-file src="src/android/com/ionicframework/cordova/webview/IonicWebView.java" target-dir="src/com/ionicframework/cordova/webview"/>
<source-file src="src/android/com/ionicframework/cordova/webview/AndroidProtocolHandler.java" target-dir="src/com/ionicframework/cordova/webview"/>
<source-file src="src/android/com/ionicframework/cordova/webview/UriMatcher.java" target-dir="src/com/ionicframework/cordova/webview"/>
<source-file src="src/android/com/ionicframework/cordova/webview/WebViewLocalServer.java" target-dir="src/com/ionicframework/cordova/webview"/>
<preference name="ANDROID_SUPPORT_ANNOTATIONS_VERSION" default="27.+"/>
<framework src="com.android.support:support-annotations:$ANDROID_SUPPORT_ANNOTATIONS_VERSION"/>
</platform>
<!-- ios -->
<platform name="ios">
<js-module src="src/www/ios/ios-wkwebview-exec.js" name="ios-wkwebview-exec">
<clobbers target="cordova.exec"/>
</js-module>
<config-file target="config.xml" parent="/*">
<allow-navigation href="ionic://*"/>
<preference name="deployment-target" value="11.0"/>
<feature name="IonicWebView">
<param name="ios-package" value="CDVWKWebViewEngine"/>
</feature>
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine"/>
</config-file>
<framework src="WebKit.framework" weak="true"/>
<header-file src="src/ios/CDVWKWebViewEngine.h"/>
<source-file src="src/ios/CDVWKWebViewEngine.m"/>
<header-file src="src/ios/CDVWKWebViewUIDelegate.h"/>
<source-file src="src/ios/CDVWKWebViewUIDelegate.m"/>
<header-file src="src/ios/CDVWKProcessPoolFactory.h"/>
<source-file src="src/ios/CDVWKProcessPoolFactory.m"/>
<header-file src="src/ios/IONAssetHandler.h"/>
<source-file src="src/ios/IONAssetHandler.m"/>
<asset src="src/ios/wk-plugin.js" target="wk-plugin.js"/>
</platform>
<issue>https://github.com/ionic-team/cordova-plugin-ionic-webview/issues</issue>
<author>Ionic Team</author>
</plugin>
@@ -0,0 +1,107 @@
package com.ionicframework.cordova.webview;
// Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import android.content.Context;
import android.content.res.AssetManager;
import android.net.Uri;
import android.util.Log;
import android.util.TypedValue;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class AndroidProtocolHandler {
private static final String TAG = "AndroidProtocolHandler";
private Context context;
public AndroidProtocolHandler(Context context) {
this.context = context;
}
public InputStream openAsset(String path) throws IOException {
return context.getAssets().open(path, AssetManager.ACCESS_STREAMING);
}
public InputStream openResource(Uri uri) {
assert uri.getPath() != null;
// The path must be of the form ".../asset_type/asset_name.ext".
List<String> pathSegments = uri.getPathSegments();
String assetType = pathSegments.get(pathSegments.size() - 2);
String assetName = pathSegments.get(pathSegments.size() - 1);
// Drop the file extension.
assetName = assetName.split("\\.")[0];
try {
// Use the application context for resolving the resource package name so that we do
// not use the browser's own resources. Note that if 'context' here belongs to the
// test suite, it does not have a separate application context. In that case we use
// the original context object directly.
if (context.getApplicationContext() != null) {
context = context.getApplicationContext();
}
int fieldId = getFieldId(context, assetType, assetName);
int valueType = getValueType(context, fieldId);
if (valueType == TypedValue.TYPE_STRING) {
return context.getResources().openRawResource(fieldId);
} else {
Log.e(TAG, "Asset not of type string: " + uri);
return null;
}
} catch (ClassNotFoundException e) {
Log.e(TAG, "Unable to open resource URL: " + uri, e);
return null;
} catch (NoSuchFieldException e) {
Log.e(TAG, "Unable to open resource URL: " + uri, e);
return null;
} catch (IllegalAccessException e) {
Log.e(TAG, "Unable to open resource URL: " + uri, e);
return null;
}
}
public InputStream openFile(String filePath) throws IOException {
String realPath = filePath.replace(WebViewLocalServer.fileStart, "");
File localFile = new File(realPath);
return new FileInputStream(localFile);
}
public InputStream openContentUrl(Uri uri) throws IOException {
Integer port = uri.getPort();
String realPath;
if (port == -1) {
realPath = uri.toString().replace(uri.getScheme() + "://" + uri.getHost() + WebViewLocalServer.contentStart, "content:/");
} else {
realPath = uri.toString().replace(uri.getScheme() + "://" + uri.getHost() + ":" + port + WebViewLocalServer.contentStart, "content:/");
}
InputStream stream = null;
try {
stream = context.getContentResolver().openInputStream(Uri.parse(realPath));
} catch (SecurityException e) {
Log.e(TAG, "Unable to open content URL: " + uri, e);
}
return stream;
}
private static int getFieldId(Context context, String assetType, String assetName)
throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
Class<?> d = context.getClassLoader()
.loadClass(context.getPackageName() + ".R$" + assetType);
java.lang.reflect.Field field = d.getField(assetName);
int id = field.getInt(null);
return id;
}
private static int getValueType(Context context, int fieldId) {
TypedValue value = new TypedValue();
context.getResources().getValue(fieldId, value, true);
return value.type;
}
}
@@ -0,0 +1,41 @@
package com.ionicframework.cordova.webview;
import android.app.Activity;
import android.content.SharedPreferences;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
public class IonicWebView extends CordovaPlugin {
public static final String WEBVIEW_PREFS_NAME = "WebViewSettings";
public static final String CDV_SERVER_PATH = "serverBasePath";
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals("setServerBasePath")) {
final String path = args.getString(0);
cordova.getActivity().runOnUiThread(new Runnable() {
public void run() {
((IonicWebViewEngine)webView.getEngine()).setServerBasePath(path);
}
});
return true;
} else if (action.equals("getServerBasePath")) {
callbackContext.success(((IonicWebViewEngine)webView.getEngine()).getServerBasePath());
return true;
} else if (action.equals("persistServerBasePath")) {
String path = ((IonicWebViewEngine)webView.getEngine()).getServerBasePath();
SharedPreferences prefs = cordova.getActivity().getApplicationContext().getSharedPreferences(WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(CDV_SERVER_PATH, path);
editor.apply();
return true;
}
return false;
}
}
@@ -0,0 +1,181 @@
package com.ionicframework.cordova.webview;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.webkit.ServiceWorkerController;
import android.webkit.ServiceWorkerClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import org.apache.cordova.ConfigXmlParser;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPreferences;
import org.apache.cordova.CordovaResourceApi;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewEngine;
import org.apache.cordova.NativeToJsMessageQueue;
import org.apache.cordova.PluginManager;
import org.apache.cordova.engine.SystemWebViewClient;
import org.apache.cordova.engine.SystemWebViewEngine;
import org.apache.cordova.engine.SystemWebView;
public class IonicWebViewEngine extends SystemWebViewEngine {
public static final String TAG = "IonicWebViewEngine";
private WebViewLocalServer localServer;
private String CDV_LOCAL_SERVER;
private String scheme;
private static final String LAST_BINARY_VERSION_CODE = "lastBinaryVersionCode";
private static final String LAST_BINARY_VERSION_NAME = "lastBinaryVersionName";
/**
* Used when created via reflection.
*/
public IonicWebViewEngine(Context context, CordovaPreferences preferences) {
super(new SystemWebView(context), preferences);
Log.d(TAG, "Ionic Web View Engine Starting Right Up 1...");
}
public IonicWebViewEngine(SystemWebView webView) {
super(webView, null);
Log.d(TAG, "Ionic Web View Engine Starting Right Up 2...");
}
public IonicWebViewEngine(SystemWebView webView, CordovaPreferences preferences) {
super(webView, preferences);
Log.d(TAG, "Ionic Web View Engine Starting Right Up 3...");
}
@Override
public void init(CordovaWebView parentWebView, CordovaInterface cordova, final CordovaWebViewEngine.Client client,
CordovaResourceApi resourceApi, PluginManager pluginManager,
NativeToJsMessageQueue nativeToJsMessageQueue) {
ConfigXmlParser parser = new ConfigXmlParser();
parser.parse(cordova.getActivity());
String hostname = preferences.getString("Hostname", "localhost");
scheme = preferences.getString("Scheme", "http");
CDV_LOCAL_SERVER = scheme + "://" + hostname;
localServer = new WebViewLocalServer(cordova.getActivity(), hostname, true, parser, scheme);
localServer.hostAssets("www");
webView.setWebViewClient(new ServerClient(this, parser));
super.init(parentWebView, cordova, client, resourceApi, pluginManager, nativeToJsMessageQueue);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final WebSettings settings = webView.getSettings();
int mode = preferences.getInteger("MixedContentMode", 0);
settings.setMixedContentMode(mode);
}
SharedPreferences prefs = cordova.getActivity().getApplicationContext().getSharedPreferences(IonicWebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
String path = prefs.getString(IonicWebView.CDV_SERVER_PATH, null);
if (!isDeployDisabled() && !isNewBinary() && path != null && !path.isEmpty()) {
setServerBasePath(path);
}
boolean setAsServiceWorkerClient = preferences.getBoolean("ResolveServiceWorkerRequests", false);
ServiceWorkerController controller = null;
if (setAsServiceWorkerClient && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
controller = ServiceWorkerController.getInstance();
controller.setServiceWorkerClient(new ServiceWorkerClient(){
@Override
public WebResourceResponse shouldInterceptRequest(WebResourceRequest request) {
return localServer.shouldInterceptRequest(request.getUrl(), request);
}
});
}
}
private boolean isNewBinary() {
String versionCode = "";
String versionName = "";
SharedPreferences prefs = cordova.getActivity().getApplicationContext().getSharedPreferences(IonicWebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
String lastVersionCode = prefs.getString(LAST_BINARY_VERSION_CODE, null);
String lastVersionName = prefs.getString(LAST_BINARY_VERSION_NAME, null);
try {
PackageInfo pInfo = this.cordova.getActivity().getPackageManager().getPackageInfo(this.cordova.getActivity().getPackageName(), 0);
versionCode = Integer.toString(pInfo.versionCode);
versionName = pInfo.versionName;
} catch(Exception ex) {
Log.e(TAG, "Unable to get package info", ex);
}
if (!versionCode.equals(lastVersionCode) || !versionName.equals(lastVersionName)) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(LAST_BINARY_VERSION_CODE, versionCode);
editor.putString(LAST_BINARY_VERSION_NAME, versionName);
editor.putString(IonicWebView.CDV_SERVER_PATH, "");
editor.apply();
return true;
}
return false;
}
private boolean isDeployDisabled() {
return preferences.getBoolean("DisableDeploy", false);
}
private class ServerClient extends SystemWebViewClient {
private ConfigXmlParser parser;
public ServerClient(SystemWebViewEngine parentEngine, ConfigXmlParser parser) {
super(parentEngine);
this.parser = parser;
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
return localServer.shouldInterceptRequest(request.getUrl(), request);
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
return localServer.shouldInterceptRequest(Uri.parse(url), null);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
String launchUrl = parser.getLaunchUrl();
if (!launchUrl.contains(WebViewLocalServer.httpsScheme) && !launchUrl.contains(WebViewLocalServer.httpScheme) && url.equals(launchUrl)) {
view.stopLoading();
// When using a custom scheme the app won't load if server start url doesn't end in /
String startUrl = CDV_LOCAL_SERVER;
if (!scheme.equalsIgnoreCase(WebViewLocalServer.httpsScheme) && !scheme.equalsIgnoreCase(WebViewLocalServer.httpScheme)) {
startUrl += "/";
}
view.loadUrl(startUrl);
}
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() { " +
"window.WEBVIEW_SERVER_URL = '" + CDV_LOCAL_SERVER + "';" +
"})()");
}
}
public void setServerBasePath(String path) {
localServer.hostFiles(path);
webView.loadUrl(CDV_LOCAL_SERVER);
}
public String getServerBasePath() {
return this.localServer.getBasePath();
}
}
@@ -0,0 +1,183 @@
package com.ionicframework.cordova.webview;
/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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.
*/
//package com.google.webviewlocalserver.third_party.android;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class UriMatcher {
/**
* Creates the root node of the URI tree.
*
* @param code the code to match for the root URI
*/
public UriMatcher(Object code) {
mCode = code;
mWhich = -1;
mChildren = new ArrayList<UriMatcher>();
mText = null;
}
private UriMatcher() {
mCode = null;
mWhich = -1;
mChildren = new ArrayList<UriMatcher>();
mText = null;
}
/**
* Add a URI to match, and the code to return when this URI is
* matched. URI nodes may be exact match string, the token "*"
* that matches any text, or the token "#" that matches only
* numbers.
* <p>
* Starting from API level {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
* this method will accept a leading slash in the path.
*
* @param authority the authority to match
* @param path the path to match. * may be used as a wild card for
* any text, and # may be used as a wild card for numbers.
* @param code the code that is returned when a URI is matched
* against the given components. Must be positive.
*/
public void addURI(String scheme, String authority, String path, Object code) {
if (code == null) {
throw new IllegalArgumentException("Code can't be null");
}
String[] tokens = null;
if (path != null) {
String newPath = path;
// Strip leading slash if present.
if (path.length() > 0 && path.charAt(0) == '/') {
newPath = path.substring(1);
}
tokens = PATH_SPLIT_PATTERN.split(newPath);
}
int numTokens = tokens != null ? tokens.length : 0;
UriMatcher node = this;
for (int i = -2; i < numTokens; i++) {
String token;
if (i == -2)
token = scheme;
else if (i == -1)
token = authority;
else
token = tokens[i];
ArrayList<UriMatcher> children = node.mChildren;
int numChildren = children.size();
UriMatcher child;
int j;
for (j = 0; j < numChildren; j++) {
child = children.get(j);
if (token.equals(child.mText)) {
node = child;
break;
}
}
if (j == numChildren) {
// Child not found, create it
child = new UriMatcher();
if (token.equals("**")) {
child.mWhich = REST;
} else if (token.equals("*")) {
child.mWhich = TEXT;
} else {
child.mWhich = EXACT;
}
child.mText = token;
node.mChildren.add(child);
node = child;
}
}
node.mCode = code;
}
static final Pattern PATH_SPLIT_PATTERN = Pattern.compile("/");
/**
* Try to match against the path in a url.
*
* @param uri The url whose path we will match against.
* @return The code for the matched node (added using addURI),
* or null if there is no matched node.
*/
public Object match(Uri uri) {
final List<String> pathSegments = uri.getPathSegments();
final int li = pathSegments.size();
UriMatcher node = this;
if (li == 0 && uri.getAuthority() == null) {
return this.mCode;
}
for (int i = -2; i < li; i++) {
String u;
if (i == -2)
u = uri.getScheme();
else if (i == -1)
u = uri.getAuthority();
else
u = pathSegments.get(i);
ArrayList<UriMatcher> list = node.mChildren;
if (list == null) {
break;
}
node = null;
int lj = list.size();
for (int j = 0; j < lj; j++) {
UriMatcher n = list.get(j);
which_switch:
switch (n.mWhich) {
case EXACT:
if (n.mText.equals(u)) {
node = n;
}
break;
case TEXT:
node = n;
break;
case REST:
return n.mCode;
}
if (node != null) {
break;
}
}
if (node == null) {
return null;
}
}
return node.mCode;
}
private static final int EXACT = 0;
private static final int TEXT = 1;
private static final int REST = 2;
private Object mCode;
private int mWhich;
private String mText;
private ArrayList<UriMatcher> mChildren;
}
@@ -0,0 +1,645 @@
/*
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.ionicframework.cordova.webview;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import org.apache.cordova.ConfigXmlParser;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* Helper class meant to be used with the android.webkit.WebView class to enable hosting assets,
* resources and other data on 'virtual' http(s):// URL.
* Hosting assets and resources on http(s):// URLs is desirable as it is compatible with the
* Same-Origin policy.
* <p>
* This class is intended to be used from within the
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView, String)} and
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView,
* android.webkit.WebResourceRequest)}
* methods.
*/
public class WebViewLocalServer {
private static String TAG = "WebViewAssetServer";
private String basePath;
public final static String httpScheme = "http";
public final static String httpsScheme = "https";
public final static String fileStart = "/_app_file_";
public final static String contentStart = "/_app_content_";
private final UriMatcher uriMatcher;
private final AndroidProtocolHandler protocolHandler;
private final String authority;
private final String customScheme;
// Whether we're serving local files or proxying (for example, when doing livereload on a
// non-local endpoint (will be false in that case)
private boolean isAsset;
// Whether to route all requests to paths without extensions back to `index.html`
private final boolean html5mode;
private ConfigXmlParser parser;
public String getAuthority() { return authority; }
/**
* A handler that produces responses for paths on the virtual asset server.
* <p>
* Methods of this handler will be invoked on a background thread and care must be taken to
* correctly synchronize access to any shared state.
* <p>
* On Android KitKat and above these methods may be called on more than one thread. This thread
* may be different than the thread on which the shouldInterceptRequest method was invoke.
* This means that on Android KitKat and above it is possible to block in this method without
* blocking other resources from loading. The number of threads used to parallelize loading
* is an internal implementation detail of the WebView and may change between updates which
* means that the amount of time spend blocking in this method should be kept to an absolute
* minimum.
*/
public abstract static class PathHandler {
protected String mimeType;
private String encoding;
private String charset;
private int statusCode;
private String reasonPhrase;
private Map<String, String> responseHeaders;
public PathHandler() {
this(null, null, 200, "OK", null);
}
public PathHandler(String encoding, String charset, int statusCode,
String reasonPhrase, Map<String, String> responseHeaders) {
this.encoding = encoding;
this.charset = charset;
this.statusCode = statusCode;
this.reasonPhrase = reasonPhrase;
Map<String, String> tempResponseHeaders;
if (responseHeaders == null) {
tempResponseHeaders = new HashMap<String, String>();
} else {
tempResponseHeaders = responseHeaders;
}
tempResponseHeaders.put("Cache-Control", "no-cache");
this.responseHeaders = tempResponseHeaders;
}
abstract public InputStream handle(Uri url);
public String getEncoding() {
return encoding;
}
public String getCharset() {
return charset;
}
public int getStatusCode() {
return statusCode;
}
public String getReasonPhrase() {
return reasonPhrase;
}
public Map<String, String> getResponseHeaders() {
return responseHeaders;
}
}
/**
* Information about the URLs used to host the assets in the WebView.
*/
public static class AssetHostingDetails {
private Uri httpPrefix;
private Uri httpsPrefix;
/*package*/ AssetHostingDetails(Uri httpPrefix, Uri httpsPrefix) {
this.httpPrefix = httpPrefix;
this.httpsPrefix = httpsPrefix;
}
/**
* Gets the http: scheme prefix at which assets are hosted.
*
* @return the http: scheme prefix at which assets are hosted. Can return null.
*/
public Uri getHttpPrefix() {
return httpPrefix;
}
/**
* Gets the https: scheme prefix at which assets are hosted.
*
* @return the https: scheme prefix at which assets are hosted. Can return null.
*/
public Uri getHttpsPrefix() {
return httpsPrefix;
}
}
WebViewLocalServer(Context context, String authority, boolean html5mode, ConfigXmlParser parser, String customScheme) {
uriMatcher = new UriMatcher(null);
this.html5mode = html5mode;
this.parser = parser;
this.protocolHandler = new AndroidProtocolHandler(context.getApplicationContext());
this.authority = authority;
this.customScheme = customScheme;
}
private static Uri parseAndVerifyUrl(String url) {
if (url == null) {
return null;
}
Uri uri = Uri.parse(url);
if (uri == null) {
Log.e(TAG, "Malformed URL: " + url);
return null;
}
String path = uri.getPath();
if (path == null || path.length() == 0) {
Log.e(TAG, "URL does not have a path: " + url);
return null;
}
return uri;
}
private static WebResourceResponse createWebResourceResponse(String mimeType, String encoding, int statusCode, String reasonPhrase, Map<String, String> responseHeaders, InputStream data) {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int finalStatusCode = statusCode;
try {
if (data.available() == 0) {
finalStatusCode = 404;
}
} catch (IOException e) {
finalStatusCode = 500;
}
return new WebResourceResponse(mimeType, encoding, finalStatusCode, reasonPhrase, responseHeaders, data);
} else {
return new WebResourceResponse(mimeType, encoding, data);
}
}
/**
* Attempt to retrieve the WebResourceResponse associated with the given <code>request</code>.
* This method should be invoked from within
* {@link android.webkit.WebViewClient#shouldInterceptRequest(android.webkit.WebView,
* android.webkit.WebResourceRequest)}.
*
* @param uri the request Uri to process.
* @return a response if the request URL had a matching handler, null if no handler was found.
*/
public WebResourceResponse shouldInterceptRequest(Uri uri, WebResourceRequest request) {
PathHandler handler;
synchronized (uriMatcher) {
handler = (PathHandler) uriMatcher.match(uri);
}
if (handler == null) {
return null;
}
if (isLocalFile(uri) || uri.getAuthority().equals(this.authority)) {
Log.d("SERVER", "Handling local request: " + uri.toString());
return handleLocalRequest(uri, handler, request);
} else {
return handleProxyRequest(uri, handler);
}
}
private boolean isLocalFile(Uri uri) {
String path = uri.getPath();
if (path.startsWith(contentStart) || path.startsWith(fileStart)) {
return true;
}
return false;
}
private WebResourceResponse handleLocalRequest(Uri uri, PathHandler handler, WebResourceRequest request) {
String path = uri.getPath();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && request != null && request.getRequestHeaders().get("Range") != null) {
InputStream responseStream = new LollipopLazyInputStream(handler, uri);
String mimeType = getMimeType(path, responseStream);
Map<String, String> tempResponseHeaders = handler.getResponseHeaders();
int statusCode = 206;
try {
int totalRange = responseStream.available();
String rangeString = request.getRequestHeaders().get("Range");
String[] parts = rangeString.split("=");
String[] streamParts = parts[1].split("-");
String fromRange = streamParts[0];
int range = totalRange-1;
if (streamParts.length > 1) {
range = Integer.parseInt(streamParts[1]);
}
tempResponseHeaders.put("Accept-Ranges", "bytes");
tempResponseHeaders.put("Content-Range", "bytes " + fromRange + "-" + range + "/" + totalRange);
} catch (IOException e) {
statusCode = 404;
}
return createWebResourceResponse(mimeType, handler.getEncoding(),
statusCode, handler.getReasonPhrase(), tempResponseHeaders, responseStream);
}
if (isLocalFile(uri)) {
InputStream responseStream = new LollipopLazyInputStream(handler, uri);
String mimeType = getMimeType(path, responseStream);
return createWebResourceResponse(mimeType, handler.getEncoding(),
handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), responseStream);
}
if (path.equals("") || path.equals("/") || (!uri.getLastPathSegment().contains(".") && html5mode)) {
InputStream stream;
String launchURL = parser.getLaunchUrl();
String launchFile = launchURL.substring(launchURL.lastIndexOf("/") + 1, launchURL.length());
try {
String startPath = this.basePath + "/" + launchFile;
if (isAsset) {
stream = protocolHandler.openAsset(startPath);
} else {
stream = protocolHandler.openFile(startPath);
}
} catch (IOException e) {
Log.e(TAG, "Unable to open " + launchFile, e);
return null;
}
return createWebResourceResponse("text/html", handler.getEncoding(),
handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), stream);
}
int periodIndex = path.lastIndexOf(".");
if (periodIndex >= 0) {
InputStream responseStream = new LollipopLazyInputStream(handler, uri);
String mimeType = getMimeType(path, responseStream);
return createWebResourceResponse(mimeType, handler.getEncoding(),
handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), responseStream);
}
return null;
}
/**
* Instead of reading files from the filesystem/assets, proxy through to the URL
* and let an external server handle it.
* @param uri
* @param handler
* @return
*/
private WebResourceResponse handleProxyRequest(Uri uri, PathHandler handler) {
try {
String path = uri.getPath();
URL url = new URL(uri.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(30 * 1000);
conn.setConnectTimeout(30 * 1000);
InputStream stream = conn.getInputStream();
if (path.equals("/") || (!uri.getLastPathSegment().contains(".") && html5mode)) {
return createWebResourceResponse("text/html", handler.getEncoding(),
handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), stream);
}
int periodIndex = path.lastIndexOf(".");
if (periodIndex >= 0) {
String ext = path.substring(path.lastIndexOf("."), path.length());
// TODO: Conjure up a bit more subtlety than this
if (ext.equals(".html")) {
}
String mimeType = getMimeType(path, stream);
return createWebResourceResponse(mimeType, handler.getEncoding(),
handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), stream);
}
return createWebResourceResponse("", handler.getEncoding(),
handler.getStatusCode(), handler.getReasonPhrase(), handler.getResponseHeaders(), stream);
} catch (SocketTimeoutException ex) {
// bridge.handleAppUrlLoadError(ex);
} catch (Exception ex) {
// bridge.handleAppUrlLoadError(ex);
}
return null;
}
private String getMimeType(String path, InputStream stream) {
String mimeType = null;
try {
mimeType = URLConnection.guessContentTypeFromName(path); // Does not recognize *.js
if (mimeType != null && path.endsWith(".js") && mimeType.equals("image/x-icon")) {
Log.d(IonicWebViewEngine.TAG, "We shouldn't be here");
}
if (mimeType == null) {
if (path.endsWith(".js") || path.endsWith(".mjs")) {
// Make sure JS files get the proper mimetype to support ES modules
mimeType = "application/javascript";
} else if (path.endsWith(".wasm")) {
mimeType = "application/wasm";
} else {
mimeType = URLConnection.guessContentTypeFromStream(stream);
}
}
} catch (Exception ex) {
Log.e(TAG, "Unable to get mime type" + path, ex);
}
return mimeType;
}
/**
* Registers a handler for the given <code>uri</code>. The <code>handler</code> will be invoked
* every time the <code>shouldInterceptRequest</code> method of the instance is called with
* a matching <code>uri</code>.
*
* @param uri the uri to use the handler for. The scheme and authority (domain) will be matched
* exactly. The path may contain a '*' element which will match a single element of
* a path (so a handler registered for /a/* will be invoked for /a/b and /a/c.html
* but not for /a/b/b) or the '**' element which will match any number of path
* elements.
* @param handler the handler to use for the uri.
*/
void register(Uri uri, PathHandler handler) {
synchronized (uriMatcher) {
uriMatcher.addURI(uri.getScheme(), uri.getAuthority(), uri.getPath(), handler);
}
}
/**
* Hosts the application's assets on an http(s):// URL. Assets from the local path
* <code>assetPath/...</code> will be available under
* <code>http(s)://{uuid}.androidplatform.net/assets/...</code>.
*
* @param assetPath the local path in the application's asset folder which will be made
* available by the server (for example "/www").
*/
public void hostAssets(String assetPath) {
hostAssets(authority, assetPath);
}
/**
* Hosts the application's assets on an http(s):// URL. Assets from the local path
* <code>assetPath/...</code> will be available under
* <code>http(s)://{domain}/{virtualAssetPath}/...</code>.
*
* @param domain custom domain on which the assets should be hosted (for example "example.com").
* @param assetPath the local path in the application's asset folder which will be made
* available by the server (for example "/www").
* @return prefixes under which the assets are hosted.
*/
public void hostAssets(final String domain,
final String assetPath) {
this.isAsset = true;
this.basePath = assetPath;
createHostingDetails();
}
private void createHostingDetails() {
final String assetPath = this.basePath;
if (assetPath.indexOf('*') != -1) {
throw new IllegalArgumentException("assetPath cannot contain the '*' character.");
}
PathHandler handler = new PathHandler() {
@Override
public InputStream handle(Uri url) {
InputStream stream = null;
String path = url.getPath();
try {
if (path.startsWith(contentStart)) {
stream = protocolHandler.openContentUrl(url);
} else if (path.startsWith(fileStart) || !isAsset) {
if (!path.startsWith(fileStart)) {
path = basePath + url.getPath();
}
stream = protocolHandler.openFile(path);
} else {
stream = protocolHandler.openAsset(assetPath + path);
}
} catch (IOException e) {
Log.e(TAG, "Unable to open asset URL: " + url);
return null;
}
return stream;
}
};
registerUriForScheme(httpScheme, handler, authority);
registerUriForScheme(httpsScheme, handler, authority);
if (!customScheme.equals(httpScheme) && !customScheme.equals(httpsScheme)) {
registerUriForScheme(customScheme, handler, authority);
}
}
private void registerUriForScheme(String scheme, PathHandler handler, String authority) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(scheme);
uriBuilder.authority(authority);
uriBuilder.path("");
Uri uriPrefix = uriBuilder.build();
register(Uri.withAppendedPath(uriPrefix, "/"), handler);
register(Uri.withAppendedPath(uriPrefix, "**"), handler);
}
/**
* Hosts the application's resources on an http(s):// URL. Resources
* <code>http(s)://{uuid}.androidplatform.net/res/{resource_type}/{resource_name}</code>.
*
* @return prefixes under which the resources are hosted.
*/
public AssetHostingDetails hostResources() {
return hostResources(authority, "/res", true, true);
}
/**
* Hosts the application's resources on an http(s):// URL. Resources
* <code>http(s)://{uuid}.androidplatform.net/{virtualResourcesPath}/{resource_type}/{resource_name}</code>.
*
* @param virtualResourcesPath the path on the local server under which the resources
* should be hosted.
* @param enableHttp whether to enable hosting using the http scheme.
* @param enableHttps whether to enable hosting using the https scheme.
* @return prefixes under which the resources are hosted.
*/
public AssetHostingDetails hostResources(final String virtualResourcesPath, boolean enableHttp,
boolean enableHttps) {
return hostResources(authority, virtualResourcesPath, enableHttp, enableHttps);
}
/**
* Hosts the application's resources on an http(s):// URL. Resources
* <code>http(s)://{domain}/{virtualResourcesPath}/{resource_type}/{resource_name}</code>.
*
* @param domain custom domain on which the assets should be hosted (for example "example.com").
* If untrusted content is to be loaded into the WebView it is advised to make
* this random.
* @param virtualResourcesPath the path on the local server under which the resources
* should be hosted.
* @param enableHttp whether to enable hosting using the http scheme.
* @param enableHttps whether to enable hosting using the https scheme.
* @return prefixes under which the resources are hosted.
*/
public AssetHostingDetails hostResources(final String domain,
final String virtualResourcesPath, boolean enableHttp,
boolean enableHttps) {
if (virtualResourcesPath.indexOf('*') != -1) {
throw new IllegalArgumentException(
"virtualResourcesPath cannot contain the '*' character.");
}
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme(httpScheme);
uriBuilder.authority(domain);
uriBuilder.path(virtualResourcesPath);
Uri httpPrefix = null;
Uri httpsPrefix = null;
PathHandler handler = new PathHandler() {
@Override
public InputStream handle(Uri url) {
InputStream stream = protocolHandler.openResource(url);
String mimeType = null;
try {
mimeType = URLConnection.guessContentTypeFromStream(stream);
} catch (Exception ex) {
Log.e(TAG, "Unable to get mime type" + url);
}
return stream;
}
};
if (enableHttp) {
httpPrefix = uriBuilder.build();
register(Uri.withAppendedPath(httpPrefix, "**"), handler);
}
if (enableHttps) {
uriBuilder.scheme(httpsScheme);
httpsPrefix = uriBuilder.build();
register(Uri.withAppendedPath(httpsPrefix, "**"), handler);
}
return new AssetHostingDetails(httpPrefix, httpsPrefix);
}
/**
* Hosts the application's files on an http(s):// URL. Files from the basePath
* <code>basePath/...</code> will be available under
* <code>http(s)://{uuid}.androidplatform.net/...</code>.
*
* @param basePath the local path in the application's data folder which will be made
* available by the server (for example "/www").
*/
public void hostFiles(final String basePath) {
this.isAsset = false;
this.basePath = basePath;
createHostingDetails();
}
/**
* The KitKat WebView reads the InputStream on a separate threadpool. We can use that to
* parallelize loading.
*/
private static abstract class LazyInputStream extends InputStream {
protected final PathHandler handler;
private InputStream is = null;
public LazyInputStream(PathHandler handler) {
this.handler = handler;
}
private InputStream getInputStream() {
if (is == null) {
is = handle();
}
return is;
}
protected abstract InputStream handle();
@Override
public int available() throws IOException {
InputStream is = getInputStream();
return (is != null) ? is.available() : 0;
}
@Override
public int read() throws IOException {
InputStream is = getInputStream();
return (is != null) ? is.read() : -1;
}
@Override
public int read(byte b[]) throws IOException {
InputStream is = getInputStream();
return (is != null) ? is.read(b) : -1;
}
@Override
public int read(byte b[], int off, int len) throws IOException {
InputStream is = getInputStream();
return (is != null) ? is.read(b, off, len) : -1;
}
@Override
public long skip(long n) throws IOException {
InputStream is = getInputStream();
return (is != null) ? is.skip(n) : 0;
}
}
// For L and above.
private static class LollipopLazyInputStream extends LazyInputStream {
private Uri uri;
private InputStream is;
public LollipopLazyInputStream(PathHandler handler, Uri uri) {
super(handler);
this.uri = uri;
}
@Override
protected InputStream handle() {
return handler.handle(uri);
}
}
public String getBasePath(){
return this.basePath;
}
}
@@ -0,0 +1,27 @@
/*
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 <WebKit/WebKit.h>
@interface CDVWKProcessPoolFactory : NSObject
@property (nonatomic, retain) WKProcessPool* sharedPool;
+(instancetype) sharedFactory;
-(WKProcessPool*) sharedProcessPool;
@end
@@ -0,0 +1,49 @@
/*
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 <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
#import "CDVWKProcessPoolFactory.h"
static CDVWKProcessPoolFactory *factory = nil;
@implementation CDVWKProcessPoolFactory
+ (instancetype)sharedFactory
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
factory = [[CDVWKProcessPoolFactory alloc] init];
});
return factory;
}
- (instancetype)init
{
if (self = [super init]) {
_sharedPool = [[WKProcessPool alloc] init];
}
return self;
}
- (WKProcessPool*) sharedProcessPool {
return _sharedPool;
}
@end

Some files were not shown because too many files have changed in this diff Show More