├── .npmignore ├── demo-angular ├── tsfmt.json ├── nsconfig.json ├── App_Resources │ ├── iOS │ │ ├── Assets.xcassets │ │ │ ├── Contents.json │ │ │ ├── AppIcon.appiconset │ │ │ │ ├── icon-20.png │ │ │ │ ├── icon-29.png │ │ │ │ ├── icon-40.png │ │ │ │ ├── icon-76.png │ │ │ │ ├── icon-1024.png │ │ │ │ ├── icon-20@2x.png │ │ │ │ ├── icon-20@3x.png │ │ │ │ ├── icon-29@2x.png │ │ │ │ ├── icon-29@3x.png │ │ │ │ ├── icon-40@2x.png │ │ │ │ ├── icon-40@3x.png │ │ │ │ ├── icon-60@2x.png │ │ │ │ ├── icon-60@3x.png │ │ │ │ ├── icon-76@2x.png │ │ │ │ ├── icon-83.5@2x.png │ │ │ │ └── Contents.json │ │ │ ├── LaunchScreen.Center.imageset │ │ │ │ ├── LaunchScreen-Center.png │ │ │ │ ├── LaunchScreen-Center@2x.png │ │ │ │ ├── LaunchScreen-Center@3x.png │ │ │ │ └── Contents.json │ │ │ └── LaunchScreen.AspectFill.imageset │ │ │ │ ├── LaunchScreen-AspectFill.png │ │ │ │ ├── LaunchScreen-AspectFill@2x.png │ │ │ │ ├── LaunchScreen-AspectFill@3x.png │ │ │ │ └── Contents.json │ │ ├── build.xcconfig │ │ ├── Info.plist │ │ └── LaunchScreen.storyboard │ └── Android │ │ ├── src │ │ └── main │ │ │ ├── res │ │ │ ├── values-v21 │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── drawable-hdpi │ │ │ │ ├── icon.png │ │ │ │ ├── logo.png │ │ │ │ └── background.png │ │ │ ├── drawable-ldpi │ │ │ │ ├── icon.png │ │ │ │ ├── logo.png │ │ │ │ └── background.png │ │ │ ├── drawable-mdpi │ │ │ │ ├── icon.png │ │ │ │ ├── logo.png │ │ │ │ └── background.png │ │ │ ├── drawable-xhdpi │ │ │ │ ├── icon.png │ │ │ │ ├── logo.png │ │ │ │ └── background.png │ │ │ ├── drawable-xxhdpi │ │ │ │ ├── icon.png │ │ │ │ ├── logo.png │ │ │ │ └── background.png │ │ │ ├── drawable-xxxhdpi │ │ │ │ ├── icon.png │ │ │ │ ├── logo.png │ │ │ │ └── background.png │ │ │ ├── values │ │ │ │ ├── colors.xml │ │ │ │ └── styles.xml │ │ │ ├── drawable-nodpi │ │ │ │ └── splash_screen.xml │ │ │ └── values-v29 │ │ │ │ └── styles.xml │ │ │ └── AndroidManifest.xml │ │ └── app.gradle ├── src │ ├── fonts │ │ ├── FontAwesome.otf │ │ └── fontawesome-webfont.ttf │ ├── package.json │ ├── app │ │ ├── app.component.html │ │ ├── app.component.ts │ │ ├── contacts │ │ │ ├── contacts-item.component.css │ │ │ ├── contacts.component.ts │ │ │ ├── contacts-item.component.ts │ │ │ └── contacts.provider.ts │ │ ├── app-routing.module.ts │ │ └── app.module.ts │ ├── main.ts │ └── app.css ├── tsconfig.tns.json ├── .editorconfig ├── angular.json ├── .gitignore ├── tsconfig.json ├── package.json ├── LICENSE └── webpack.config.js ├── platforms └── android │ └── AndroidManifest.xml ├── jsconfig.json ├── get-contacts-worker.js ├── .gitignore ├── LICENSE ├── package.json ├── constants.ios.js ├── index.js ├── contacts.ios.js ├── contacts.android.js ├── constants.android.js ├── README.md ├── contacts-helper.ios.js └── contacts-helper.android.js /.npmignore: -------------------------------------------------------------------------------- 1 | demo-angular 2 | *.map 3 | *.ts 4 | !*.d.ts 5 | tsconfig.json 6 | -------------------------------------------------------------------------------- /demo-angular/tsfmt.json: -------------------------------------------------------------------------------- 1 | { 2 | "indentSize": 4, 3 | "tabSize": 4 4 | } 5 | -------------------------------------------------------------------------------- /demo-angular/nsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "appResourcesPath": "App_Resources", 3 | "appPath": "src" 4 | } 5 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /demo-angular/src/fonts/FontAwesome.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/src/fonts/FontAwesome.otf -------------------------------------------------------------------------------- /demo-angular/src/fonts/fontawesome-webfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/src/fonts/fontawesome-webfont.ttf -------------------------------------------------------------------------------- /demo-angular/src/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "main.js", 3 | "android": { 4 | "v8Flags": "--expose_gc", 5 | "markingMode": "none" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/values-v21/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3d5afe 4 | -------------------------------------------------------------------------------- /demo-angular/tsconfig.tns.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig", 3 | "compilerOptions": { 4 | "module": "esNext", 5 | "moduleResolution": "node" 6 | } 7 | } -------------------------------------------------------------------------------- /demo-angular/src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-hdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-hdpi/icon.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-hdpi/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-hdpi/logo.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-ldpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-ldpi/icon.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-ldpi/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-ldpi/logo.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-mdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-mdpi/icon.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-mdpi/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-mdpi/logo.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xhdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xhdpi/icon.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xhdpi/logo.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xxhdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xxhdpi/icon.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xxhdpi/logo.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xxxhdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xxxhdpi/icon.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xxxhdpi/logo.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-hdpi/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-hdpi/background.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-ldpi/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-ldpi/background.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-mdpi/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-mdpi/background.png -------------------------------------------------------------------------------- /demo-angular/src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from "@angular/core"; 2 | 3 | @Component({ 4 | selector: "ns-app", 5 | templateUrl: "./app.component.html" 6 | }) 7 | export class AppComponent { } 8 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xhdpi/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xhdpi/background.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xxhdpi/background.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-20.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-29.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-29.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-40.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-76.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-76.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/Android/src/main/res/drawable-xxxhdpi/background.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-1024.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-20@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-20@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-20@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-20@3x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-29@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-29@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-29@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-29@3x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-40@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-40@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-40@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-40@3x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-60@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-60@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-60@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-60@3x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-76@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-76@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-83.5@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/icon-83.5@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.Center.imageset/LaunchScreen-Center.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.Center.imageset/LaunchScreen-Center.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.Center.imageset/LaunchScreen-Center@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.Center.imageset/LaunchScreen-Center@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.Center.imageset/LaunchScreen-Center@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.Center.imageset/LaunchScreen-Center@3x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.AspectFill.imageset/LaunchScreen-AspectFill.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.AspectFill.imageset/LaunchScreen-AspectFill.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.AspectFill.imageset/LaunchScreen-AspectFill@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.AspectFill.imageset/LaunchScreen-AspectFill@2x.png -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.AspectFill.imageset/LaunchScreen-AspectFill@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayastudios/nativescript-contacts-lite/HEAD/demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.AspectFill.imageset/LaunchScreen-AspectFill@3x.png -------------------------------------------------------------------------------- /demo-angular/.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | 9 | [*.json] 10 | indent_style = space 11 | indent_size = 2 12 | 13 | [*.ts] 14 | indent_style = space 15 | indent_size = 4 16 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #F5F5F5 4 | #757575 5 | #33B5E5 6 | #272734 7 | -------------------------------------------------------------------------------- /platforms/android/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs" 5 | }, 6 | "files": [ 7 | "index.js", 8 | "contacts.android.js", 9 | "contacts.ios.js", 10 | "get-contacts-worker.js", 11 | "contact-helper.android.js", 12 | "contact-helper.ios.js", 13 | "constants.android.js" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/drawable-nodpi/splash_screen.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /get-contacts-worker.js: -------------------------------------------------------------------------------- 1 | require('globals'); // necessary to bootstrap tns modules on the new thread 2 | let contacts = require("./contacts"); 3 | 4 | self.onmessage = (event) => { 5 | let result = contacts.getContactsFromBackend( 6 | event.data.fields, 7 | (event.data.searchTerm==='') ? undefined : event.data.searchTerm, 8 | event.data.debug, 9 | true // we are running in a web worker 10 | ); 11 | postMessage(result); 12 | } 13 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/values-v29/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 11 | 12 | -------------------------------------------------------------------------------- /demo-angular/angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "cli": { 6 | "defaultCollection": "@nativescript/schematics" 7 | }, 8 | "projects": { 9 | "hello-world": { 10 | "root": "", 11 | "sourceRoot": "src", 12 | "projectType": "application", 13 | "prefix": "ns" 14 | } 15 | }, 16 | "defaultProject": "hello-world" 17 | } 18 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/build.xcconfig: -------------------------------------------------------------------------------- 1 | // You can add custom settings here 2 | // for example you can uncomment the following line to force distribution code signing 3 | // CODE_SIGN_IDENTITY = iPhone Distribution 4 | // To build for device with Xcode 8 you need to specify your development team. More info: https://developer.apple.com/library/prerelease/content/releasenotes/DeveloperTools/RN-Xcode/Introduction.html 5 | // DEVELOPMENT_TEAM = YOUR_TEAM_ID; 6 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 7 | -------------------------------------------------------------------------------- /demo-angular/src/app/contacts/contacts-item.component.css: -------------------------------------------------------------------------------- 1 | .list-item { 2 | margin: 1 0 0 0; 3 | padding: 5; 4 | background-color: #f6f6f6; 5 | } 6 | 7 | .thumbnail { 8 | width: 50; 9 | height: 50; 10 | border-radius: 25; 11 | vertical-align: center; 12 | text-align: center; 13 | } 14 | 15 | .thumbnail-awesome { 16 | font-size: 50; 17 | color: #b7b7b7; 18 | vertical-align: center; 19 | text-align: center; 20 | } 21 | 22 | .contact-name { 23 | font-size: 18; 24 | color: black; 25 | margin-left: 5; 26 | vertical-align: center; 27 | } -------------------------------------------------------------------------------- /demo-angular/.gitignore: -------------------------------------------------------------------------------- 1 | # NativeScript 2 | hooks/ 3 | node_modules/ 4 | platforms/ 5 | 6 | # NativeScript Template 7 | *.js.map 8 | *.js 9 | !webpack.config.js 10 | 11 | # Logs 12 | logs 13 | *.log 14 | npm-debug.log* 15 | yarn-debug.log* 16 | yarn-error.log* 17 | 18 | # General 19 | .DS_Store 20 | .AppleDouble 21 | .LSOverride 22 | .idea 23 | .cloud 24 | .project 25 | tmp/ 26 | typings/ 27 | 28 | # Visual Studio Code 29 | .vscode/* 30 | !.vscode/settings.json 31 | !.vscode/tasks.json 32 | !.vscode/launch.json 33 | !.vscode/extensions.json 34 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.Center.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "LaunchScreen-Center.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "LaunchScreen-Center@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "LaunchScreen-Center@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/LaunchScreen.AspectFill.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "LaunchScreen-AspectFill.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "LaunchScreen-AspectFill@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "LaunchScreen-AspectFill@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Specifies intentionally untracked files to ignore when using Git 2 | # http://git-scm.com/docs/gitignore 3 | 4 | *~ 5 | *.sw[mnpcod] 6 | *.log 7 | *.tmp 8 | *.tmp.* 9 | *.bak 10 | log.txt 11 | *.sublime-project 12 | *.sublime-workspace 13 | .vscode/ 14 | npm-debug.log* 15 | 16 | .idea/ 17 | .sass-cache/ 18 | .tmp/ 19 | .versions/ 20 | demo*/app/**/*.js 21 | !demo*/app/assets/js/*.js 22 | demo*/app/**/*.js.map 23 | demo*/.nsbuildinfo 24 | coverage/ 25 | dist/ 26 | node_modules/ 27 | tmp/ 28 | temp/ 29 | lib/ 30 | hooks/ 31 | plugins/ 32 | plugins/android.json 33 | plugins/ios.json 34 | www/ 35 | $RECYCLE.BIN/ 36 | 37 | .DS_Store 38 | Thumbs.db 39 | UserInterfaceState.xcuserstate 40 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/app.gradle: -------------------------------------------------------------------------------- 1 | // Add your native dependencies here: 2 | 3 | // Uncomment to add recyclerview-v7 dependency 4 | //dependencies { 5 | // implementation 'com.android.support:recyclerview-v7:+' 6 | //} 7 | 8 | // If you want to add something to be applied before applying plugins' include.gradle files 9 | // e.g. project.ext.googlePlayServicesVersion = "15.0.1" 10 | // create a file named before-plugins.gradle in the current directory and place it there 11 | 12 | android { 13 | defaultConfig { 14 | minSdkVersion 17 15 | generatedDensities = [] 16 | } 17 | aaptOptions { 18 | additionalParameters "--no-version-vectors" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /demo-angular/src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from "@angular/core"; 2 | import { NativeScriptRouterModule } from "@nativescript/angular/router"; 3 | import { Routes } from "@angular/router"; 4 | 5 | // import { ContactsItemComponent } from "~/app/contacts/contacts-item.component"; 6 | import { ContactsComponent } from "~/app/contacts/contacts.component"; 7 | 8 | const routes: Routes = [ 9 | { path: "", redirectTo: "/contacts", pathMatch: "full" }, 10 | { path: "contacts", component: ContactsComponent }, 11 | ]; 12 | 13 | @NgModule({ 14 | imports: [NativeScriptRouterModule.forRoot(routes)], 15 | exports: [NativeScriptRouterModule] 16 | }) 17 | export class AppRoutingModule { } 18 | -------------------------------------------------------------------------------- /demo-angular/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es5", 5 | "experimentalDecorators": true, 6 | "emitDecoratorMetadata": true, 7 | "noEmitHelpers": true, 8 | "noEmitOnError": true, 9 | "skipLibCheck": true, 10 | "lib": [ 11 | "es6", 12 | "dom", 13 | "es2015.iterable" 14 | ], 15 | "baseUrl": ".", 16 | "paths": { 17 | "~/*": [ 18 | "src/*" 19 | ], 20 | "*": [ 21 | "./node_modules/*" 22 | ] 23 | } 24 | }, 25 | "exclude": [ 26 | "node_modules", 27 | "platforms" 28 | ] 29 | } -------------------------------------------------------------------------------- /demo-angular/src/main.ts: -------------------------------------------------------------------------------- 1 | // this import should be first in order to load some required settings (like globals and reflect-metadata) 2 | import { platformNativeScriptDynamic } from "@nativescript/angular/platform"; 3 | 4 | import { AppModule } from "./app/app.module"; 5 | 6 | // A traditional NativeScript application starts by initializing global objects, 7 | // setting up global CSS rules, creating, and navigating to the main page. 8 | // Angular applications need to take care of their own initialization: 9 | // modules, components, directives, routes, DI providers. 10 | // A NativeScript Angular app needs to make both paradigms work together, 11 | // so we provide a wrapper platform object, platformNativeScriptDynamic, 12 | // that sets up a NativeScript application and can bootstrap the Angular framework. 13 | platformNativeScriptDynamic().bootstrapModule(AppModule); 14 | -------------------------------------------------------------------------------- /demo-angular/src/app/contacts/contacts.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { ContactsProvider } from './contacts.provider'; 3 | 4 | @Component({ 5 | template: ` 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | `, 14 | styles: [` 15 | ListView { 16 | separator-color:transparent; 17 | height:100%; 18 | } 19 | `] 20 | }) 21 | export class ContactsComponent implements OnInit { 22 | constructor(public contacts:ContactsProvider) {} 23 | 24 | public ngOnInit() { 25 | this.contacts.cacheContacts(); 26 | } 27 | 28 | public onItemTap(contact_id) { 29 | this.contacts.getSingleContact(contact_id).then((contact) => { 30 | console.dir(contact); 31 | }); 32 | } 33 | } -------------------------------------------------------------------------------- /demo-angular/src/app/contacts/contacts-item.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'ContactsItem', 5 | template: ` 6 | 7 | 8 | 9 | 10 | 11 | `, 12 | styleUrls: ['./contacts-item.component.css' ] 13 | }) 14 | export class ContactsItemComponent implements OnInit { 15 | @Input() item:any = {}; 16 | @Input() index:number = undefined; 17 | @Output() tap = new EventEmitter(); 18 | 19 | constructor() {} 20 | 21 | public ngOnInit() { 22 | } 23 | 24 | public onItemTap(contact) { 25 | this.tap.emit(contact.contact_id); // allow parent to bind to tap 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /demo-angular/src/app.css: -------------------------------------------------------------------------------- 1 | /* 2 | In NativeScript, the app.css file is where you place CSS rules that 3 | you would like to apply to your entire application. Check out 4 | http://docs.nativescript.org/ui/styling for a full list of the CSS 5 | selectors and properties you can use to style UI components. 6 | 7 | /* 8 | In many cases you may want to use the NativeScript core theme instead 9 | of writing your own CSS rules. You can learn more about the 10 | NativeScript core theme at https://github.com/nativescript/theme 11 | The imported CSS rules must precede all other types of rules. 12 | */ 13 | @import "~@nativescript/theme/css/core.css"; 14 | @import "~@nativescript/theme/css/default.css"; 15 | 16 | /* Place any CSS rules you want to apply on both iOS and Android here. 17 | This is where the vast majority of your CSS code goes. */ 18 | 19 | /* 20 | The following CSS rule changes the font size of all Buttons that have the 21 | "-primary" class modifier. 22 | */ 23 | Button.-primary { 24 | font-size: 18; 25 | } 26 | 27 | .fa { 28 | font-family: 'FontAwesome', fontawesome-webfont; 29 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Jonathan Salomon 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nativescript-contacts-lite", 3 | "version": "0.2.7", 4 | "description": "NativeScript plugin providing pretty fast read-only access to the iOS and Android contact directory", 5 | "main": "index", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/abhayastudios/nativescript-contacts-lite.git" 9 | }, 10 | "keywords": [ 11 | "NativeScript", 12 | "Contacts", 13 | "Address Book", 14 | "Contact Directory" 15 | ], 16 | "author": { 17 | "name": "Jonathan Salomon", 18 | "email": "mail2joni@gmail.com" 19 | }, 20 | "license": "MIT", 21 | "bugs": { 22 | "url": "https://github.com/abhayastudios/nativescript-contacts-lite/issues" 23 | }, 24 | "homepage": "https://github.com/abhayastudios/nativescript-contacts-lite", 25 | "nativescript": { 26 | "platforms": { 27 | "ios": "2.4.0", 28 | "android": "2.4.0" 29 | }, 30 | "plugin": { 31 | "nan": "true", 32 | "pan": "true", 33 | "core3": "true", 34 | "webpack": "true", 35 | "wrapper": "false", 36 | "category": "Processing" 37 | }, 38 | "demong": "/demo-angular" 39 | }, 40 | "dependencies": { 41 | "nativescript-permissions": "^1.2.2" 42 | }, 43 | "devDependencies": {} 44 | } 45 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/values-v21/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 10 | 11 | 13 | 14 | 15 | 18 | 19 | 20 | 23 | 24 | 28 | -------------------------------------------------------------------------------- /demo-angular/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "nativescript": { 3 | "id": "org.nativescript.demoangular", 4 | "tns-android": { 5 | "version": "6.5.0" 6 | }, 7 | "tns-ios": { 8 | "version": "6.5.0" 9 | } 10 | }, 11 | "description": "NativeScript Application", 12 | "license": "SEE LICENSE IN ", 13 | "repository": "", 14 | "dependencies": { 15 | "@angular/animations": "~8.2.0", 16 | "@angular/common": "~8.2.0", 17 | "@angular/compiler": "~8.2.0", 18 | "@angular/core": "~8.2.0", 19 | "@angular/forms": "~8.2.0", 20 | "@angular/platform-browser": "~8.2.0", 21 | "@angular/platform-browser-dynamic": "~8.2.0", 22 | "@angular/router": "~8.2.0", 23 | "@nativescript/angular": "~8.21.0", 24 | "@nativescript/core": "~6.5.0", 25 | "@nativescript/theme": "~2.3.3", 26 | "nativescript-contacts-lite": "^0.2.7", 27 | "reflect-metadata": "~0.1.12", 28 | "rxjs": "^6.4.0", 29 | "zone.js": "~0.9.1" 30 | }, 31 | "devDependencies": { 32 | "@angular/compiler-cli": "~8.2.0", 33 | "@ngtools/webpack": "~8.2.0", 34 | "nativescript-dev-webpack": "~1.5.1", 35 | "nativescript-worker-loader": "^0.11.0", 36 | "typescript": "~3.5.3" 37 | }, 38 | "gitHead": "2250137db8c1e0bd0eb543e8e4563cb71480c00d", 39 | "readme": "NativeScript Application" 40 | } 41 | -------------------------------------------------------------------------------- /constants.ios.js: -------------------------------------------------------------------------------- 1 | var HOME_FAX = "_$!!$_"; 2 | var WORK_FAX = "_$!!$_"; 3 | var MAIN = "_$!
!$_"; 4 | 5 | exports.getGenericLabel = (nativeLabel) => { 6 | var genericLabel = nativeLabel; 7 | 8 | switch (nativeLabel) { 9 | case CNLabelHome: 10 | genericLabel = 'home'; 11 | break; 12 | case CNLabelWork: 13 | genericLabel = 'work'; 14 | break; 15 | case CNLabelOther: 16 | genericLabel = 'other'; 17 | break; 18 | }; 19 | 20 | return genericLabel; 21 | }; 22 | 23 | 24 | exports.getPhoneLabel = (nativeLabel) => { 25 | var phoneLabel = exports.getGenericLabel(nativeLabel); 26 | 27 | switch (nativeLabel) { 28 | case kABPersonPhoneMobileLabel: 29 | phoneLabel = "mobile"; 30 | break; 31 | case HOME_FAX: 32 | phoneLabel = 'fax_home'; 33 | break; 34 | case WORK_FAX: 35 | phoneLabel = 'fax_work'; 36 | break; 37 | case kABPersonPhonePagerLabel: 38 | phoneLabel = 'pager'; 39 | break; 40 | case MAIN: 41 | phoneLabel = 'main'; 42 | break; 43 | }; 44 | 45 | return phoneLabel; 46 | }; 47 | 48 | exports.getWebsiteLabel = (nativeLabel) => { 49 | var websiteLabel = exports.getGenericLabel(nativeLabel); 50 | 51 | switch (nativeLabel) { 52 | case CNLabelURLAddressHomePage: 53 | websiteLabel = "homepage"; 54 | break; 55 | }; 56 | 57 | return websiteLabel; 58 | }; 59 | -------------------------------------------------------------------------------- /demo-angular/src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core"; 2 | import { NativeScriptModule } from "@nativescript/angular/nativescript.module"; 3 | 4 | import { AppRoutingModule } from "./app-routing.module"; 5 | import { AppComponent } from "./app.component"; 6 | 7 | import { ContactsComponent } from "~/app/contacts/contacts.component"; 8 | import { ContactsItemComponent } from "~/app/contacts/contacts-item.component"; 9 | import { ContactsProvider } from "~/app/contacts/contacts.provider"; 10 | 11 | // Uncomment and add to NgModule imports if you need to use two-way binding 12 | // import { NativeScriptFormsModule } from "nativescript-angular/forms"; 13 | 14 | // Uncomment and add to NgModule imports if you need to use the HttpClient wrapper 15 | // import { NativeScriptHttpClientModule } from "nativescript-angular/http-client"; 16 | 17 | @NgModule({ 18 | bootstrap: [ 19 | AppComponent 20 | ], 21 | imports: [ 22 | NativeScriptModule, 23 | AppRoutingModule 24 | ], 25 | declarations: [ 26 | AppComponent, 27 | ContactsItemComponent, 28 | ContactsComponent, 29 | ], 30 | providers: [ 31 | ContactsProvider, 32 | ], 33 | schemas: [ 34 | NO_ERRORS_SCHEMA 35 | ] 36 | }) 37 | /* 38 | Pass your application module to the bootstrapModule function located in main.ts to start your app 39 | */ 40 | export class AppModule { } 41 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 12 | 13 | 14 | 15 | 16 | 17 | 23 | 24 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | ${PRODUCT_NAME} 9 | CFBundleExecutable 10 | ${EXECUTABLE_NAME} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1.0 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIRequiresFullScreen 28 | 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | UISupportedInterfaceOrientations~ipad 40 | 41 | UIInterfaceOrientationPortrait 42 | UIInterfaceOrientationPortraitUpsideDown 43 | UIInterfaceOrientationLandscapeLeft 44 | UIInterfaceOrientationLandscapeRight 45 | 46 | NSContactsUsageDescription 47 | This app needs access to your contacts 48 | 49 | 50 | -------------------------------------------------------------------------------- /demo-angular/src/app/contacts/contacts.provider.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import * as appSettings from "@nativescript/core/application-settings"; 3 | import { getContactsWorker, getContactById } from 'nativescript-contacts-lite'; 4 | 5 | @Injectable() 6 | export class ContactsProvider { 7 | public cachedContacts:Array = []; // array of objects containing shadow of entire phonebook 8 | 9 | constructor() {} 10 | 11 | /* 12 | creates a sorted cache of the phonebook through a web worker so UI won't get stuck and stores in app storage 13 | */ 14 | public cacheContacts() { 15 | return new Promise((resolve, reject) => { 16 | console.log('Start caching contacts'); 17 | 18 | /* get all contacts from phonebook */ 19 | 20 | let desiredFields:Array = ['display_name','thumbnail']; // fields to fetch from contacts 21 | 22 | console.time('getContactsWorker'); 23 | 24 | getContactsWorker(desiredFields).then((result) => { 25 | console.timeEnd('getContactsWorker'); 26 | console.log(`getContactsWorker: found ${result.length} items`); 27 | this.cachedContacts = result; 28 | resolve(); 29 | }) 30 | .catch((error) => { console.error(error); }); 31 | }); 32 | } 33 | 34 | public getSingleContact(contact_id) { 35 | return new Promise((resolve, reject) => { 36 | var timer = new Date().getTime(); 37 | 38 | let desiredFields:Array = ['address','display_name','email','name_details','nickname','note','organization','phone','photo','thumbnail','website']; // fields to fetch from contacts 39 | getContactById(contact_id,desiredFields).then((result) => { 40 | console.log(`getContactById complete in ${(new Date().getTime() - timer)} ms.`); 41 | resolve(result); 42 | }) 43 | .catch((error) => { console.error(error); }); 44 | }); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/Android/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 18 | 19 | 21 | 22 | 23 | 31 | 32 | 34 | 35 | 36 | 42 | 43 | 45 | 46 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | let contacts = require("./contacts"); 2 | let helper = require("./contacts-helper"); 3 | 4 | exports.getContactsWorker = (fields,searchTerm=undefined,debug=false) => { 5 | return new Promise((resolve, reject) => { 6 | helper.handlePermission().then(() => { 7 | 8 | let worker = {}; 9 | 10 | if (global.TNS_WEBPACK) { 11 | let Worker = require("nativescript-worker-loader!./get-contacts-worker.js"); 12 | worker = new Worker; 13 | } else { 14 | worker = new Worker('./get-contacts-worker.js'); // relative for caller script path 15 | } 16 | 17 | worker.postMessage({ 18 | "searchTerm": (searchTerm==='') ? undefined : searchTerm, 19 | "fields": fields, 20 | "debug": debug 21 | }); 22 | 23 | worker.onmessage = ((event) => { 24 | if (event.data.type == 'log') { console.log(event.data.message); } 25 | else if (event.data.type == 'dump') { console.dump(event.data.message); } 26 | else if (event.data.type == 'error') { reject(event.data); } 27 | else if (event.data.type == 'result') { 28 | worker.terminate(); 29 | resolve(event.data.message); 30 | } 31 | }); 32 | 33 | worker.onerror = ((e) => { reject(e); }); 34 | }, (e) => { reject(e); }); // end of handlePermission 35 | }); // end of promise 36 | }; 37 | 38 | exports.getContacts = (fields,searchTerm=undefined,debug=false) => { 39 | return new Promise((resolve, reject) => { 40 | helper.handlePermission().then(() => { 41 | let result = contacts.getContactsFromBackend( 42 | fields, 43 | (searchTerm==='') ? undefined : searchTerm, 44 | debug, 45 | false // we are not running in a web worker 46 | ); 47 | if (result.type=="error") { reject(result.message); } else { resolve(result.message); } 48 | }, (e) => { reject(e); }); // end of handlePermission 49 | }); // end of promise 50 | }; 51 | 52 | exports.getContactById = (contactId,fields,debug=false) => { 53 | return new Promise((resolve, reject) => { 54 | helper.handlePermission().then(() => { 55 | let result = contacts.getContactFromBackendById(contactId,fields,debug); 56 | if (result.type=="error") { reject(result.message); } else { resolve(result.message); } 57 | }, (e) => { reject(e); }); // end of handlePermission 58 | }); // end of promise 59 | } 60 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "20x20", 5 | "idiom" : "iphone", 6 | "filename" : "icon-20@2x.png", 7 | "scale" : "2x" 8 | }, 9 | { 10 | "size" : "20x20", 11 | "idiom" : "iphone", 12 | "filename" : "icon-20@3x.png", 13 | "scale" : "3x" 14 | }, 15 | { 16 | "size" : "29x29", 17 | "idiom" : "iphone", 18 | "filename" : "icon-29.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "29x29", 23 | "idiom" : "iphone", 24 | "filename" : "icon-29@2x.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "29x29", 29 | "idiom" : "iphone", 30 | "filename" : "icon-29@3x.png", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "size" : "40x40", 35 | "idiom" : "iphone", 36 | "filename" : "icon-40@2x.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "40x40", 41 | "idiom" : "iphone", 42 | "filename" : "icon-40@3x.png", 43 | "scale" : "3x" 44 | }, 45 | { 46 | "size" : "60x60", 47 | "idiom" : "iphone", 48 | "filename" : "icon-60@2x.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "60x60", 53 | "idiom" : "iphone", 54 | "filename" : "icon-60@3x.png", 55 | "scale" : "3x" 56 | }, 57 | { 58 | "size" : "20x20", 59 | "idiom" : "ipad", 60 | "filename" : "icon-20.png", 61 | "scale" : "1x" 62 | }, 63 | { 64 | "size" : "20x20", 65 | "idiom" : "ipad", 66 | "filename" : "icon-20@2x.png", 67 | "scale" : "2x" 68 | }, 69 | { 70 | "size" : "29x29", 71 | "idiom" : "ipad", 72 | "filename" : "icon-29.png", 73 | "scale" : "1x" 74 | }, 75 | { 76 | "size" : "29x29", 77 | "idiom" : "ipad", 78 | "filename" : "icon-29@2x.png", 79 | "scale" : "2x" 80 | }, 81 | { 82 | "size" : "40x40", 83 | "idiom" : "ipad", 84 | "filename" : "icon-40.png", 85 | "scale" : "1x" 86 | }, 87 | { 88 | "size" : "40x40", 89 | "idiom" : "ipad", 90 | "filename" : "icon-40@2x.png", 91 | "scale" : "2x" 92 | }, 93 | { 94 | "size" : "76x76", 95 | "idiom" : "ipad", 96 | "filename" : "icon-76.png", 97 | "scale" : "1x" 98 | }, 99 | { 100 | "size" : "76x76", 101 | "idiom" : "ipad", 102 | "filename" : "icon-76@2x.png", 103 | "scale" : "2x" 104 | }, 105 | { 106 | "size" : "83.5x83.5", 107 | "idiom" : "ipad", 108 | "filename" : "icon-83.5@2x.png", 109 | "scale" : "2x" 110 | }, 111 | { 112 | "size" : "1024x1024", 113 | "idiom" : "ios-marketing", 114 | "filename" : "icon-1024.png", 115 | "scale" : "1x" 116 | } 117 | ], 118 | "info" : { 119 | "version" : 1, 120 | "author" : "xcode" 121 | } 122 | } -------------------------------------------------------------------------------- /contacts.ios.js: -------------------------------------------------------------------------------- 1 | let helper = require("./contacts-helper"); 2 | 3 | /* 4 | if running inside a web worker, need to pass debug messages to main thread as workers do not have console access 5 | */ 6 | let console_log = (msg) => { postMessage({ type: 'log', message: msg }); } 7 | let console_dump = (msg) => { postMessage({ type: 'dump', message: msg }); } 8 | 9 | /* 10 | fields: desired fields to retrieve from phone storage backend 11 | searchTerm: search only for contacts whose display_name start with this term 12 | debug whether to print debug messages to the console 13 | worker: wether we are running inside a web worker 14 | */ 15 | exports.getContactsFromBackend = ((fields,searchTerm,debug,worker) => { 16 | try { 17 | 18 | /* variables used in ios backend query */ 19 | 20 | let contacts = []; // array containing contacts object to return 21 | let columnsToFetch = helper.getIOSQueryColumns(fields); // columns to return for each row 22 | 23 | var timer = new Date().getTime(); 24 | 25 | /* getting all contacts */ 26 | 27 | if (searchTerm===undefined) { 28 | var store = new CNContactStore(), 29 | error, 30 | fetch = CNContactFetchRequest.alloc().initWithKeysToFetch(columnsToFetch), 31 | nativeMutableArray = new NSMutableArray(); 32 | 33 | fetch.unifyResults = true; 34 | fetch.predicate = null; 35 | 36 | store.enumerateContactsWithFetchRequestErrorUsingBlock(fetch, error, (c,s) => { 37 | nativeMutableArray.addObject(c); 38 | 39 | //transform raw data into desired data structure */ 40 | contacts.push(helper.convertNativeCursorToContact(c,fields)); 41 | }); 42 | 43 | if (error && worker) { postMessage({ type: 'error', message: error }); } 44 | if (error && !worker) { return({ type: 'error', message: error }); } 45 | } 46 | 47 | /* getting contacts by searchTerm */ 48 | 49 | if (searchTerm) { 50 | var store = new CNContactStore(), 51 | error, 52 | foundContacts = store.unifiedContactsMatchingPredicateKeysToFetchError( 53 | CNContact.predicateForContactsMatchingName(searchTerm), 54 | columnsToFetch, error 55 | ); 56 | 57 | if (error && worker) { postMessage({ type: 'error', message: error }); } 58 | if (error && !worker) { return({ type: 'error', message: error }); } 59 | 60 | for (var i=0; i { 79 | try { 80 | 81 | /* variables used in ios backend query */ 82 | 83 | let contact = {}; // contact object to return 84 | let columnsToFetch = helper.getIOSQueryColumns(fields); // columns to return for each row 85 | 86 | var timer = new Date().getTime(); 87 | 88 | /* getting single contact by contact_id */ 89 | 90 | var store = new CNContactStore(), 91 | error, 92 | foundContact = store.unifiedContactWithIdentifierKeysToFetchError(contactId,columnsToFetch,error); 93 | 94 | if (error) { return({ type: 'error', message: error }); } 95 | 96 | //transform raw data into desired data structure */ 97 | contact = helper.convertNativeCursorToContact(foundContact,fields); 98 | 99 | if (debug) { console.log(`Processing data completed in ${(new Date().getTime() - timer)} ms!`); } 100 | 101 | return({ type: 'result', message: contact }); 102 | } catch (e) { return({ type: 'error', message: e }); } 103 | }); 104 | -------------------------------------------------------------------------------- /demo-angular/App_Resources/iOS/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /contacts.android.js: -------------------------------------------------------------------------------- 1 | let helper = require("./contacts-helper"); 2 | 3 | /* 4 | if running inside a web worker, need to pass debug messages to main thread as workers do not have console access 5 | */ 6 | let console_log = (msg) => { postMessage({ type: 'log', message: msg }); } 7 | let console_dump = (msg) => { postMessage({ type: 'dump', message: msg }); } 8 | 9 | /* 10 | fields: desired fields to retrieve from phone storage backend 11 | searchTerm: search only for contacts whose display_name start with this term 12 | debug whether to print debug messages to the console 13 | worker: wether we are running inside a web worker 14 | */ 15 | exports.getContactsFromBackend = ((fields,searchTerm,debug,worker) => { 16 | try { 17 | /* variables used in android backend query */ 18 | 19 | let content_uri = android.provider.ContactsContract.Data.CONTENT_URI, // The content URI of the words table 20 | columnsToFetch = helper.getAndroidQueryColumns(fields), // The columns to return for each row 21 | selectionClause = helper.getSelectionClause({ // Either null, or and SQL like WHERE clause 22 | fields: fields, 23 | searchTerm: searchTerm 24 | }), 25 | selectionArgs = helper.getSelectionArgs({ // Either null, or an array of string args for selection clause 26 | fields: fields, 27 | searchTerm: searchTerm 28 | }), 29 | sortOrder = null; // The sort order for the returned rows 30 | 31 | /* load raw data from android backend */ 32 | 33 | var timer = new Date().getTime(); 34 | let c = helper.getAndroidContext().getContentResolver().query(content_uri, columnsToFetch, selectionClause, selectionArgs, sortOrder); 35 | if (debug && worker) { console_log(`Querying storage backend completed in ${(new Date().getTime() - timer)} ms!`); } 36 | if (debug && !worker) { console.log(`Querying storage backend completed in ${(new Date().getTime() - timer)} ms!`); } 37 | 38 | /* 39 | transform raw data into desired data structure 40 | moveToNext() moves the row pointer to the next row in the cursor 41 | initial position is -1 and retrieving data at that position you will get an exception 42 | */ 43 | 44 | let contacts = []; // array containing contacts object to return 45 | var timer = new Date().getTime(); 46 | while (c.moveToNext()) { 47 | let contact_id = helper.getColumnValue(c,columnsToFetch.indexOf("contact_id")); 48 | // see if contact_id already exists in contacts to pass existing object for appending 49 | let existingContactObj = undefined; 50 | let existingContactIndex = contacts.findIndex((item,index) => { return item.contact_id === contact_id }); 51 | if (existingContactIndex > -1) { existingContactObj=contacts[existingContactIndex]; } 52 | 53 | let contact = helper.convertNativeCursorToContact(c,fields,columnsToFetch,existingContactObj); 54 | if (existingContactIndex > -1) { contacts[existingContactIndex] = contact; } 55 | else { contacts.push(contact); } 56 | } 57 | c.close(); 58 | 59 | if (debug && worker) { console_log(`Processing data completed in ${(new Date().getTime() - timer)} ms!`); } 60 | if (debug && !worker) { console.log(`Processing data completed in ${(new Date().getTime() - timer)} ms!`); } 61 | 62 | return({ type: 'result', message: contacts }); 63 | } catch (e) { return({ type: 'error', message: e }); } 64 | }); 65 | 66 | /* 67 | fields: desired fields to retrieve from phone storage backend 68 | searchTerm: search only for contacts whose display_name start with this term 69 | debug whether to print debug messages to the console 70 | worker: wether we are running inside a web worker 71 | */ 72 | exports.getContactFromBackendById = ((contactId,fields,debug) => { 73 | try { 74 | 75 | /* variables used in android backend query */ 76 | 77 | let content_uri = android.provider.ContactsContract.Data.CONTENT_URI, // The content URI of the words table 78 | columnsToFetch = helper.getAndroidQueryColumns(fields), // The columns to return for each row 79 | selectionClause = helper.getSelectionClause({ // Either null, or and SQL like WHERE clause 80 | fields: fields, 81 | contactId: contactId 82 | }), 83 | selectionArgs = helper.getSelectionArgs({ // Either null, or an array of string args for selection clause 84 | fields: fields, 85 | contactId: contactId 86 | }), 87 | sortOrder = null; // The sort order for the returned rows 88 | 89 | /* load raw data from android backend */ 90 | 91 | var timer = new Date().getTime(); 92 | let c = helper.getAndroidContext().getContentResolver().query(content_uri, columnsToFetch, selectionClause, selectionArgs, sortOrder); 93 | if (debug) { console.log(`Querying storage backend completed in ${(new Date().getTime() - timer)} ms!`); } 94 | 95 | /* 96 | transform raw data into desired data structure 97 | moveToNext() moves the row pointer to the next row in the cursor 98 | initial position is -1 and retrieving data at that position you will get an exception 99 | */ 100 | let contactObj = undefined; // contact object to return 101 | var timer = new Date().getTime(); 102 | while (c.moveToNext()) { 103 | let contact = helper.convertNativeCursorToContact(c,fields,columnsToFetch,contactObj); 104 | contactObj = contact; 105 | } 106 | c.close(); 107 | 108 | if (debug) { console.log(`Processing data completed in ${(new Date().getTime() - timer)} ms!`); } 109 | 110 | return({ type: 'result', message: contactObj }); 111 | } catch (e) { return({ type: 'error', message: e }); } 112 | }); 113 | -------------------------------------------------------------------------------- /constants.android.js: -------------------------------------------------------------------------------- 1 | exports.MIME_TYPES = { 2 | "name_details" : "vnd.android.cursor.item/name", 3 | "phone" : "vnd.android.cursor.item/phone_v2", 4 | "photo" : "vnd.android.cursor.item/photo", 5 | "thumbnail" : "vnd.android.cursor.item/photo", 6 | "organization" : "vnd.android.cursor.item/organization", 7 | "nickname" : "vnd.android.cursor.item/nickname", 8 | "note" : "vnd.android.cursor.item/note", 9 | "website" : "vnd.android.cursor.item/website", 10 | "email" : "vnd.android.cursor.item/email_v2", 11 | "address" : "vnd.android.cursor.item/postal-address_v2" 12 | } 13 | 14 | /* 15 | mapping of Android data types (needed for reverse lookup of "dataN" fields) 16 | */ 17 | DATA_TYPES = { 18 | "name_details" : { 19 | "family": android.provider.ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, 20 | "given": android.provider.ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, 21 | "middle": android.provider.ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, 22 | "prefix": android.provider.ContactsContract.CommonDataKinds.StructuredName.PREFIX, 23 | "suffix": android.provider.ContactsContract.CommonDataKinds.StructuredName.SUFFIX 24 | }, 25 | "phone": { 26 | //"_ID": android.provider.ContactsContract.CommonDataKinds.Phone._ID, 27 | "number": android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER, 28 | "type": android.provider.ContactsContract.CommonDataKinds.Phone.TYPE, 29 | "labels" : [] // define them dynamically later 30 | }, 31 | "email": { 32 | //"_ID": android.provider.ContactsContract.CommonDataKinds.Email._ID, 33 | "data": android.provider.ContactsContract.CommonDataKinds.Email.DATA, 34 | "type": android.provider.ContactsContract.CommonDataKinds.Email.TYPE, 35 | "labels" : [] // define them dynamically later 36 | }, 37 | "address": { 38 | //"_ID": android.provider.ContactsContract.CommonDataKinds.StructuredPostal._ID, 39 | "type": android.provider.ContactsContract.CommonDataKinds.Organization.TYPE, 40 | "formatted_address": android.provider.ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, 41 | "street": android.provider.ContactsContract.CommonDataKinds.StructuredPostal.STREET, 42 | "city": android.provider.ContactsContract.CommonDataKinds.StructuredPostal.CITY, 43 | "region": android.provider.ContactsContract.CommonDataKinds.StructuredPostal.REGION, 44 | "postcode": android.provider.ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, 45 | "country": android.provider.ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, 46 | "labels" : [] // define them dynamically later 47 | }, 48 | "organization": { 49 | //"_ID": android.provider.ContactsContract.CommonDataKinds.Organization._ID, 50 | "type": android.provider.ContactsContract.CommonDataKinds.Organization.TYPE, 51 | "department": android.provider.ContactsContract.CommonDataKinds.Organization.DEPARTMENT, 52 | "company": android.provider.ContactsContract.CommonDataKinds.Organization.COMPANY, 53 | "title": android.provider.ContactsContract.CommonDataKinds.Organization.TITLE, 54 | "labels" : [] // define them dynamically later 55 | }, 56 | "note": android.provider.ContactsContract.CommonDataKinds.Note.NOTE, 57 | "nickname": android.provider.ContactsContract.CommonDataKinds.Nickname.NAME, 58 | "website": { 59 | //"_ID": android.provider.ContactsContract.CommonDataKinds.Website._ID, 60 | "url": android.provider.ContactsContract.CommonDataKinds.Website.URL, 61 | "type": android.provider.ContactsContract.CommonDataKinds.Website.TYPE, 62 | "labels" : [] // define them dynamically later 63 | } 64 | } 65 | 66 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_ASSISTANT]='assistant'; 67 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_CALLBACK]='callback'; 68 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_CAR]='car'; 69 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_COMPANY_MAIN]='company_main'; 70 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_FAX_HOME]='fax_home'; 71 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_FAX_WORK]='fax_home'; 72 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_HOME]='home'; 73 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_ISDN]='isdn'; 74 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_MAIN]='main'; 75 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_MMS]='mms'; 76 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE]='mobile'; 77 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_OTHER]='other'; 78 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_OTHER_FAX]='other_fax'; 79 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_PAGER]='pager'; 80 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_WORK]='work'; 81 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_WORK_MOBILE]='work_mobile'; 82 | DATA_TYPES.phone.labels[android.provider.ContactsContract.CommonDataKinds.Phone.TYPE_WORK_PAGER]='work_pager'; 83 | DATA_TYPES.organization.labels[android.provider.ContactsContract.CommonDataKinds.Organization.TYPE_WORK]='work'; 84 | DATA_TYPES.organization.labels[android.provider.ContactsContract.CommonDataKinds.Organization.TYPE_OTHER]='other'; 85 | DATA_TYPES.website.labels[android.provider.ContactsContract.CommonDataKinds.Website.TYPE_BLOG]='blog'; 86 | DATA_TYPES.website.labels[android.provider.ContactsContract.CommonDataKinds.Website.TYPE_FTP]='ftp'; 87 | DATA_TYPES.website.labels[android.provider.ContactsContract.CommonDataKinds.Website.TYPE_HOME]='home'; 88 | DATA_TYPES.website.labels[android.provider.ContactsContract.CommonDataKinds.Website.TYPE_HOMEPAGE]='homepage'; 89 | DATA_TYPES.website.labels[android.provider.ContactsContract.CommonDataKinds.Website.TYPE_OTHER]='other'; 90 | DATA_TYPES.website.labels[android.provider.ContactsContract.CommonDataKinds.Website.TYPE_PROFILE]='profile'; 91 | DATA_TYPES.website.labels[android.provider.ContactsContract.CommonDataKinds.Website.TYPE_WORK]='work'; 92 | DATA_TYPES.address.labels[android.provider.ContactsContract.CommonDataKinds.StructuredPostal.TYPE_OTHER]='other'; 93 | DATA_TYPES.address.labels[android.provider.ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK]='work'; 94 | DATA_TYPES.address.labels[android.provider.ContactsContract.CommonDataKinds.StructuredPostal.TYPE_HOME]='home'; 95 | DATA_TYPES.email.labels[android.provider.ContactsContract.CommonDataKinds.Email.TYPE_HOME]='home'; 96 | DATA_TYPES.email.labels[android.provider.ContactsContract.CommonDataKinds.Email.TYPE_MOBILE]='mobile'; 97 | DATA_TYPES.email.labels[android.provider.ContactsContract.CommonDataKinds.Email.TYPE_OTHER]='other'; 98 | DATA_TYPES.email.labels[android.provider.ContactsContract.CommonDataKinds.Email.TYPE_WORK]='work'; 99 | 100 | exports.DATA_TYPES=DATA_TYPES; -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NativeScript Contacts Lite 2 | 3 | This nativescript-contacts-lite plugin provides pretty fast (but hey it's all relative) read-only access to the iOS and Android contact directory. By limiting the scope of the result set through the `desiredFields`, it is possible to obtain a JSON object containing the relevant data of the contact directory within a couple of hundred milliseconds. 4 | 5 | # Demo Application 6 | 7 | This repository contains a demo application in the `demo-angular` folder that uses this plugin to display a contact picker. The demo app can be a good starting point for your app and may be used for narrowing down issues whilst debugging. Just clone this repo and run `tns run ` in the `demo-angular` folder. 8 | 9 | # Installation 10 | 11 | Run `tns plugin add nativescript-contacts-lite` 12 | 13 | # Usage 14 | 15 | To use the contacts module you must first `require()` it. 16 | 17 | ```js 18 | var Contacts = require("nativescript-contacts-lite"); 19 | ``` 20 | 21 | ## Methods 22 | 23 | ### getContacts & getContactsWorker 24 | Both methods retrieve contacts and share the same interface. The difference is that the former runs in the main thread and the latter within a web worker. 25 | 26 | **Argument 1: desiredFields** 27 | An array containing the desired fields to fetch from phone's storage backend. Possible values are: 28 | ```js 29 | [ 30 | 'address', 31 | 'display_name', 32 | 'email', 33 | 'name_details', 34 | 'nickname', 35 | 'note', 36 | 'organization', 37 | 'phone', 38 | 'photo', 39 | 'thumbnail', 40 | 'website' 41 | ] 42 | ``` 43 | 44 | **Argument 2: searchTerm (optional)** 45 | A string with a search term to limit the result set to only contacts whose `display_name` contain the term. Defaults to fetching all relevant contacts if an empty search term is provided or none at all. 46 | 47 | **Argument 3: debug (optional)** 48 | Boolean (true/false) determining whether to pass debug messages to the console. Defaults to false. 49 | 50 | 51 | **Example using getContacts** 52 | ```js 53 | let desiredFields = ['display_name','phone']; 54 | let searchTerm = 'Jon'; 55 | 56 | console.log('Loading contacts...'); 57 | let timer = new Date().getTime(); 58 | 59 | Contacts.getContacts(desiredFields,searchTerm).then((result) => { 60 | console.log(`Loading contacts completed in ${(new Date().getTime() - timer)} ms.`); 61 | console.log(`Found ${result.length} contacts.`); 62 | console.dir(result); 63 | }, (e) => { console.dir(e); }); 64 | ``` 65 | 66 | **Example using getContactsWorker** 67 | ```js 68 | let desiredFields = ['display_name','phone','thumbnail','email','organization']; 69 | 70 | console.log('Loading contacts...'); 71 | let timer = new Date().getTime(); 72 | 73 | Contacts.getContactsWorker(desiredFields).then((result) => { 74 | console.log(`Loading contacts completed in ${(new Date().getTime() - timer)} ms.`); 75 | console.log(`Found ${result.length} contacts.`); 76 | console.dir(result); 77 | }, (e) => { console.dir(e); }); 78 | ``` 79 | 80 | 81 | ### getContactById 82 | Get contact details for a specific contact. 83 | 84 | **Argument 1: contactId** 85 | The identifier of the contact you wish to obtain details of (obtained through the getContacts(Worker) methods). 86 | 87 | **Argument 2: desiredFields** 88 | An array containing the desired fields to fetch from phone's storage backend. See `getContacts` method for possible values. 89 | 90 | **Argument 3: debug (optional)** 91 | Boolean (true/false) determining whether to pass debug messages to the console. Defaults to false. 92 | 93 | **Example** 94 | ```js 95 | let contact_id = contact.contact_id // get id from result of getContacts method 96 | 97 | let desiredFields = [ 98 | 'address', 99 | 'display_name', 100 | 'email', 101 | 'name_details', 102 | 'nickname', 103 | 'note', 104 | 'organization', 105 | 'phone', 106 | 'photo', 107 | 'thumbnail', 108 | 'website' 109 | ] 110 | 111 | Contacts.getContactById(contact_id,desiredFields).then((result) => { 112 | console.dir(result); 113 | }, (e) => { console.dir(e); }); 114 | ``` 115 | 116 | 117 | # Performance 118 | 119 | ## Considerations 120 | 121 | ### Running in main thread versus web worker 122 | The plugin provides both methods that run in either the main/UI thread or within a web worker. Although offloading the processing to a separate thread adds web worker initialization time, it guarantees that the main UI thread will continue to work smoothly. 123 | 124 | If you are implementing an autocomplete where on each key you are querying a smaller subset of the contacts, you will probably want to go with the non-worker variant to avoid web worker initialization time while the user is waiting. On the other hand, if you are reading the entire contact directory while initializing your app, you probably want this to happen in the background to avoid the UI getting stuck while processing. In the latter case you probably would want to use the web worker variant. 125 | 126 | ### Contact Picker Example 127 | Another way to speed up performance is possible in certain cases like when you are building a contact picker. In this case it is probably good enough to first provide a narrow array of desiredFields like `['display_name','thumbnail']` to `getContacts` to display the list. Only when the user selects a specific contact, you can obtain all details for a specific contact by supplying a wider array of desiredFields to `getContactById`. This example has been implemented in the demo app located in this repository. 128 | 129 | 130 | ## Benchmarks 131 | 132 | ### Android 133 | On a relatively old Samsung Galaxy S4 a list of ~600 contacts is returned somewhere between ~300ms up to ~2s depending on the desired fields and whether you run in the main thread or in a web worker. 134 | 135 | ### iOS 136 | Tests on an iPhone 7 plus with ~600 contacts returned in ~105ms when running `getContacts(['display_name', 'phone'])` (so non worker). This could use some more real iOS device data in different modes (e.g. more fields & web worker mode) if anyone has some. 137 | 138 | 139 | # Notes 140 | 141 | ## Bundling with Webpack 142 | This plugin is compatible with webpack bundling through the [nativescript-dev-webpack](https://github.com/NativeScript/nativescript-dev-webpack) plugin as of NativeScript 3.2. However, if you are using the web worker functions, we need to ensure that the web worker resources are included in the package. For this purpose, you should add the [nativescript-worker-loader](https://github.com/NativeScript/worker-loader) to your project: `npm i -D nativescript-worker-loader`. 143 | 144 | ## Photo & Thumbnail Images 145 | The plugin returns `photo` & `thumbnail` images as a base64 encoded string ready to be used as the source attribute of an image, e.g. `` 146 | 147 | ## Android Specifics 148 | 149 | ### Permissions 150 | This plugin uses the [nativescript-permissions](https://github.com/NathanaelA/nativescript-permissions) plugin by Nathanael Anderson for obtaining read-only permissions to the phone's contacts on Android 6 and above. 151 | 152 | ## iOS Specifics 153 | Since the plugin uses the Contact framework it is supported only on iOS 9.0 and above! 154 | 155 | ### Permissions 156 | As of iOS 10 it has become mandatory to add the `NSContactsUsageDescription` key to your application's `Info.plist` (see [Apple's developer documentation](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW14)). 157 | 158 | Therefore you should add something like this to your `~/app/App_Resources/iOS/Info.plist`: 159 | ``` 160 | NSContactsUsageDescription 161 | This application requires access to your contacts to function properly. 162 | ``` 163 | 164 | # Acknowledgements 165 | The iOS part of this plugin is based on code from the [nativescript-contacts](https://github.com/firescript/nativescript-contacts) plugin. 166 | -------------------------------------------------------------------------------- /contacts-helper.ios.js: -------------------------------------------------------------------------------- 1 | var constants = require("./constants"); 2 | var imageSource = require("@nativescript/core/image-source"); 3 | 4 | /* 5 | permissions handling is only relevant for Android, always resolve on iOS 6 | */ 7 | exports.handlePermission = (() => { 8 | return new Promise((resolve, reject) => { 9 | const status = CNAuthorizationStatus[CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts)]; 10 | 11 | if (status==="CNAuthorizationStatusAuthorized") { resolve(); } 12 | else if (status==="CNAuthorizationStatusNotDetermined") { 13 | requestPermission() 14 | .then(() => { resolve(); }) 15 | .catch((error) => { reject(error); }); 16 | } else { 17 | reject(`Unable to obtain permission to read contacts: ${status}`); 18 | } 19 | }); 20 | }); 21 | 22 | let requestPermission = (() => { 23 | return new Promise((resolve, reject) => { 24 | const contactStore = CNContactStore.new(); 25 | contactStore.requestAccessForEntityTypeCompletionHandler(CNEntityType.Contacts, () => { 26 | exports.handlePermission() 27 | .then(() => { resolve(); }) 28 | .catch((error) => { reject(error); }); 29 | }); 30 | }); 31 | }); 32 | 33 | let getiOSValue = function(key, contactData){ 34 | return contactData.isKeyAvailable(key) ? contactData[key] : null; 35 | }; 36 | 37 | /* 38 | Takes a native iOS contact row and converts to json object for new contact 39 | 40 | Arguments 41 | 1: contact - the cursor returned by iOS' data store 42 | 2: fields - those the user is interested in (skip irrelevant properties for speedup) 43 | */ 44 | exports.convertNativeCursorToContact = (c,fields) => { 45 | let contact = {}; // contact object to return if creatng a new record 46 | contact.contact_id = getiOSValue("identifier", c); 47 | 48 | /* display_name */ 49 | 50 | if (fields.indexOf("display_name") > -1) { 51 | contact.display_name = `${getiOSValue("givenName", c).trim()} ${getiOSValue("familyName", c).trim()}`.trim(); 52 | } 53 | 54 | /* name_details */ 55 | 56 | if (fields.indexOf("name_details") > -1) { 57 | var record = {}; 58 | record.family = getiOSValue("familyName", c); 59 | record.given = getiOSValue("givenName", c); 60 | record.middle = getiOSValue("middleName", c); 61 | record.prefix = getiOSValue("namePrefix", c); 62 | record.suffix = getiOSValue("nameSuffix", c); 63 | if (!contact.hasOwnProperty('name_details')) { contact.name_details = []; } 64 | contact.name_details.push(record); 65 | } 66 | 67 | /* phone */ 68 | 69 | if (fields.indexOf("phone") > -1) { 70 | if (!contact.hasOwnProperty('phone')) { contact.phone = []; } 71 | 72 | for (var i=0; i < c.phoneNumbers.count; i++) { 73 | var pdata = c.phoneNumbers[i]; 74 | contact.phone.push({ 75 | //id: pdata.identifier, 76 | type: constants.getPhoneLabel(pdata.label), 77 | number: pdata.value.stringValue 78 | }); 79 | } 80 | } 81 | 82 | /* photo */ 83 | 84 | if (fields.indexOf("photo") > -1) { 85 | contact.photo = null; 86 | if (c.imageDataAvailable) { 87 | var photo = imageSource.fromData(c.imageData); 88 | if (photo) { contact.photo = "data:image/png;base64,"+photo.toBase64String("png"); } 89 | } 90 | } 91 | 92 | /* thumbnail */ 93 | 94 | if (fields.indexOf("thumbnail") > -1) { 95 | contact.thumbnail = null; 96 | if (c.imageDataAvailable) { 97 | var thumb = imageSource.fromData(c.thumbnailImageData); 98 | if (thumb) { contact.thumbnail = "data:image/png;base64,"+thumb.toBase64String("png"); } 99 | } 100 | } 101 | 102 | /* organization */ 103 | 104 | if (fields.indexOf("organization") > -1) { 105 | var record = {} 106 | record.title = getiOSValue("jobTitle", c); 107 | record.department = getiOSValue("departmentName", c); 108 | record.company = getiOSValue("organizationName", c); 109 | if (!contact.hasOwnProperty('organization')) { contact.organization = []; } 110 | contact.organization.push(record); 111 | } 112 | 113 | /* nickname */ 114 | 115 | if (fields.indexOf("nickname") > -1) { 116 | var record = {}; 117 | record.name = getiOSValue("nickname", c); 118 | if (!contact.hasOwnProperty('nickname')) { contact.nickname = []; } 119 | contact.nickname.push(record); 120 | } 121 | 122 | /* note */ 123 | 124 | if (fields.indexOf("note") > -1) { 125 | var record = {}; 126 | var columnValue = getiOSValue("notes", c); 127 | if (columnValue!=null && columnValue!='') { record.note = columnValue; } else { record = null; } 128 | if (!contact.hasOwnProperty('note')) { contact.note = []; } 129 | if (record!=null) { contact.note.push(record); } 130 | } 131 | 132 | /* email */ 133 | 134 | if (fields.indexOf("email") > -1) { 135 | if (!contact.hasOwnProperty('email')) { contact.email = []; } 136 | 137 | for (var i=0; i < c.emailAddresses.count; i++) { 138 | var edata = c.emailAddresses[i]; 139 | contact.email.push({ 140 | type: constants.getGenericLabel(edata.label), 141 | address: edata.value 142 | }); 143 | } 144 | } 145 | 146 | /* website */ 147 | 148 | if (fields.indexOf("website") > -1) { 149 | if (!contact.hasOwnProperty('website')) { contact.website = []; } 150 | 151 | for (var i=0; i < c.urlAddresses.count; i++) { 152 | var urldata = c.urlAddresses[i]; 153 | contact.website.push({ 154 | type: constants.getWebsiteLabel(urldata.label), 155 | url: urldata.value 156 | }); 157 | } 158 | } 159 | 160 | /* address */ 161 | 162 | if (fields.indexOf("address") > -1) { 163 | if (!contact.hasOwnProperty('address')) { contact.address = []; } 164 | 165 | for (var i=0; i < c.postalAddresses.count; i++) { 166 | var postaldata = c.postalAddresses[i]; 167 | contact.address.push({ 168 | type: constants.getGenericLabel(postaldata.label), 169 | street: postaldata.value.street, 170 | city: postaldata.value.city, 171 | region: postaldata.value.state, 172 | postcode: postaldata.value.postalCode, 173 | country: postaldata.value.country, 174 | street: postaldata.value.street, 175 | formatted_address: null 176 | }); 177 | } 178 | } 179 | 180 | return contact; 181 | }; 182 | 183 | /* 184 | returns an array with names of columns to fetch from Android storage backend 185 | constants map to Android's "dataX" fields, e.g. 186 | android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER = "data1" 187 | see: https://developer.android.com/reference/android/provider/ContactsContract.Data.html 188 | */ 189 | exports.getIOSQueryColumns = (fields) => { 190 | let columnsToFetch = []; 191 | 192 | //columnsToFetch.push("contact_id","mimetype","account_name"); 193 | 194 | if (fields.indexOf('display_name') > -1) { columnsToFetch.push("givenName","familyName"); } 195 | if (fields.indexOf('name_details') > -1) { columnsToFetch.push("givenName","familyName","middleName","namePrefix","nameSuffix"); } 196 | if (fields.indexOf('phone') > -1) { columnsToFetch.push("phoneNumbers"); } 197 | if (fields.indexOf('email') > -1) { columnsToFetch.push("emailAddresses"); } 198 | if (fields.indexOf('address') > -1) { columnsToFetch.push("postalAddresses"); } 199 | if (fields.indexOf('nickname') > -1) { columnsToFetch.push("nickname"); } 200 | if (fields.indexOf('organization') > -1) { columnsToFetch.push("jobTitle", "departmentName", "organizationName"); } 201 | if (fields.indexOf('note') > -1) { columnsToFetch.push("notes"); } 202 | if (fields.indexOf('photo') > -1) { columnsToFetch.push(CNContactImageDataAvailableKey, CNContactImageDataKey); } 203 | if (fields.indexOf('thumbnail') > -1) { columnsToFetch.push(CNContactImageDataAvailableKey, CNContactThumbnailImageDataKey); } 204 | if (fields.indexOf('website') > -1) { columnsToFetch.push("urlAddresses"); } 205 | 206 | // filter out any nulls & duplicates 207 | return columnsToFetch.filter((item, index, self) => { return (item != null && index == self.indexOf(item)) }); 208 | } 209 | -------------------------------------------------------------------------------- /demo-angular/LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright (c) 2015-2019 Progress Software Corporation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /demo-angular/webpack.config.js: -------------------------------------------------------------------------------- 1 | const { join, relative, resolve, sep, dirname } = require("path"); 2 | 3 | const webpack = require("webpack"); 4 | const nsWebpack = require("nativescript-dev-webpack"); 5 | const nativescriptTarget = require("nativescript-dev-webpack/nativescript-target"); 6 | const { nsReplaceBootstrap } = require("nativescript-dev-webpack/transformers/ns-replace-bootstrap"); 7 | const { nsReplaceLazyLoader } = require("nativescript-dev-webpack/transformers/ns-replace-lazy-loader"); 8 | const { nsSupportHmrNg } = require("nativescript-dev-webpack/transformers/ns-support-hmr-ng"); 9 | const { getMainModulePath } = require("nativescript-dev-webpack/utils/ast-utils"); 10 | const { getNoEmitOnErrorFromTSConfig, getCompilerOptionsFromTSConfig } = require("nativescript-dev-webpack/utils/tsconfig-utils"); 11 | const CleanWebpackPlugin = require("clean-webpack-plugin"); 12 | const CopyWebpackPlugin = require("copy-webpack-plugin"); 13 | const { BundleAnalyzerPlugin } = require("webpack-bundle-analyzer"); 14 | const { NativeScriptWorkerPlugin } = require("nativescript-worker-loader/NativeScriptWorkerPlugin"); 15 | const TerserPlugin = require("terser-webpack-plugin"); 16 | const { getAngularCompilerPlugin } = require("nativescript-dev-webpack/plugins/NativeScriptAngularCompilerPlugin"); 17 | const hashSalt = Date.now().toString(); 18 | 19 | module.exports = env => { 20 | // Add your custom Activities, Services and other Android app components here. 21 | const appComponents = env.appComponents || []; 22 | appComponents.push(...[ 23 | "tns-core-modules/ui/frame", 24 | "tns-core-modules/ui/frame/activity", 25 | ]); 26 | 27 | const platform = env && (env.android && "android" || env.ios && "ios" || env.platform); 28 | if (!platform) { 29 | throw new Error("You need to provide a target platform!"); 30 | } 31 | 32 | const AngularCompilerPlugin = getAngularCompilerPlugin(platform); 33 | const projectRoot = __dirname; 34 | 35 | // Default destination inside platforms//... 36 | const dist = resolve(projectRoot, nsWebpack.getAppPath(platform, projectRoot)); 37 | 38 | const { 39 | // The 'appPath' and 'appResourcesPath' values are fetched from 40 | // the nsconfig.json configuration file. 41 | appPath = "src", 42 | appResourcesPath = "App_Resources", 43 | 44 | // You can provide the following flags when running 'tns run android|ios' 45 | aot, // --env.aot 46 | snapshot, // --env.snapshot, 47 | production, // --env.production 48 | uglify, // --env.uglify 49 | report, // --env.report 50 | sourceMap, // --env.sourceMap 51 | hiddenSourceMap, // --env.hiddenSourceMap 52 | hmr, // --env.hmr, 53 | unitTesting, // --env.unitTesting 54 | verbose, // --env.verbose 55 | snapshotInDocker, // --env.snapshotInDocker 56 | skipSnapshotTools, // --env.skipSnapshotTools 57 | compileSnapshot // --env.compileSnapshot 58 | } = env; 59 | 60 | const useLibs = compileSnapshot; 61 | const isAnySourceMapEnabled = !!sourceMap || !!hiddenSourceMap; 62 | const externals = nsWebpack.getConvertedExternals(env.externals); 63 | const appFullPath = resolve(projectRoot, appPath); 64 | const tsConfigName = "tsconfig.tns.json"; 65 | const tsConfigPath = join(__dirname, tsConfigName); 66 | const hasRootLevelScopedModules = nsWebpack.hasRootLevelScopedModules({ projectDir: projectRoot }); 67 | const hasRootLevelScopedAngular = nsWebpack.hasRootLevelScopedAngular({ projectDir: projectRoot }); 68 | let coreModulesPackageName = "tns-core-modules"; 69 | const alias = env.alias || {}; 70 | alias['~'] = appFullPath; 71 | 72 | const compilerOptions = getCompilerOptionsFromTSConfig(tsConfigPath); 73 | if (hasRootLevelScopedModules) { 74 | coreModulesPackageName = "@nativescript/core"; 75 | alias["tns-core-modules"] = coreModulesPackageName; 76 | nsWebpack.processTsPathsForScopedModules({ compilerOptions }); 77 | } 78 | 79 | if (hasRootLevelScopedAngular) { 80 | alias["nativescript-angular"] = "@nativescript/angular"; 81 | nsWebpack.processTsPathsForScopedAngular({ compilerOptions }); 82 | } 83 | 84 | const appResourcesFullPath = resolve(projectRoot, appResourcesPath); 85 | const entryModule = `${nsWebpack.getEntryModule(appFullPath, platform)}.ts`; 86 | const entryPath = `.${sep}${entryModule}`; 87 | const entries = env.entries || {}; 88 | entries.bundle = entryPath; 89 | 90 | const areCoreModulesExternal = Array.isArray(env.externals) && env.externals.some(e => e.indexOf("tns-core-modules") > -1); 91 | if (platform === "ios" && !areCoreModulesExternal) { 92 | entries["tns_modules/tns-core-modules/inspector_modules"] = "inspector_modules"; 93 | }; 94 | 95 | const ngCompilerTransformers = []; 96 | const additionalLazyModuleResources = []; 97 | if (aot) { 98 | ngCompilerTransformers.push(nsReplaceBootstrap); 99 | } 100 | 101 | if (hmr) { 102 | ngCompilerTransformers.push(nsSupportHmrNg); 103 | } 104 | 105 | // when "@angular/core" is external, it's not included in the bundles. In this way, it will be used 106 | // directly from node_modules and the Angular modules loader won't be able to resolve the lazy routes 107 | // fixes https://github.com/NativeScript/nativescript-cli/issues/4024 108 | if (env.externals && env.externals.indexOf("@angular/core") > -1) { 109 | const appModuleRelativePath = getMainModulePath(resolve(appFullPath, entryModule), tsConfigName); 110 | if (appModuleRelativePath) { 111 | const appModuleFolderPath = dirname(resolve(appFullPath, appModuleRelativePath)); 112 | // include the lazy loader inside app module 113 | ngCompilerTransformers.push(nsReplaceLazyLoader); 114 | // include the new lazy loader path in the allowed ones 115 | additionalLazyModuleResources.push(appModuleFolderPath); 116 | } 117 | } 118 | 119 | const ngCompilerPlugin = new AngularCompilerPlugin({ 120 | hostReplacementPaths: nsWebpack.getResolver([platform, "tns"]), 121 | platformTransformers: ngCompilerTransformers.map(t => t(() => ngCompilerPlugin, resolve(appFullPath, entryModule), projectRoot)), 122 | mainPath: join(appFullPath, entryModule), 123 | tsConfigPath, 124 | skipCodeGeneration: !aot, 125 | sourceMap: !!isAnySourceMapEnabled, 126 | additionalLazyModuleResources: additionalLazyModuleResources, 127 | compilerOptions: { paths: compilerOptions.paths } 128 | }); 129 | 130 | let sourceMapFilename = nsWebpack.getSourceMapFilename(hiddenSourceMap, __dirname, dist); 131 | 132 | const itemsToClean = [`${dist}/**/*`]; 133 | if (platform === "android") { 134 | itemsToClean.push(`${join(projectRoot, "platforms", "android", "app", "src", "main", "assets", "snapshots")}`); 135 | itemsToClean.push(`${join(projectRoot, "platforms", "android", "app", "build", "configurations", "nativescript-android-snapshot")}`); 136 | } 137 | 138 | const noEmitOnErrorFromTSConfig = getNoEmitOnErrorFromTSConfig(join(projectRoot, tsConfigName)); 139 | 140 | nsWebpack.processAppComponents(appComponents, platform); 141 | const config = { 142 | mode: production ? "production" : "development", 143 | context: appFullPath, 144 | externals, 145 | watchOptions: { 146 | ignored: [ 147 | appResourcesFullPath, 148 | // Don't watch hidden files 149 | "**/.*", 150 | ] 151 | }, 152 | target: nativescriptTarget, 153 | entry: entries, 154 | output: { 155 | pathinfo: false, 156 | path: dist, 157 | sourceMapFilename, 158 | libraryTarget: "commonjs2", 159 | filename: "[name].js", 160 | globalObject: "global", 161 | hashSalt 162 | }, 163 | resolve: { 164 | extensions: [".ts", ".js", ".scss", ".css"], 165 | // Resolve {N} system modules from tns-core-modules 166 | modules: [ 167 | resolve(__dirname, `node_modules/${coreModulesPackageName}`), 168 | resolve(__dirname, "node_modules"), 169 | `node_modules/${coreModulesPackageName}`, 170 | "node_modules", 171 | ], 172 | alias, 173 | symlinks: true 174 | }, 175 | resolveLoader: { 176 | symlinks: false 177 | }, 178 | node: { 179 | // Disable node shims that conflict with NativeScript 180 | "http": false, 181 | "timers": false, 182 | "setImmediate": false, 183 | "fs": "empty", 184 | "__dirname": false, 185 | }, 186 | devtool: hiddenSourceMap ? "hidden-source-map" : (sourceMap ? "inline-source-map" : "none"), 187 | optimization: { 188 | runtimeChunk: "single", 189 | noEmitOnErrors: noEmitOnErrorFromTSConfig, 190 | splitChunks: { 191 | cacheGroups: { 192 | vendor: { 193 | name: "vendor", 194 | chunks: "all", 195 | test: (module, chunks) => { 196 | const moduleName = module.nameForCondition ? module.nameForCondition() : ''; 197 | return /[\\/]node_modules[\\/]/.test(moduleName) || 198 | appComponents.some(comp => comp === moduleName); 199 | }, 200 | enforce: true, 201 | }, 202 | } 203 | }, 204 | minimize: !!uglify, 205 | minimizer: [ 206 | new TerserPlugin({ 207 | parallel: true, 208 | cache: true, 209 | sourceMap: isAnySourceMapEnabled, 210 | terserOptions: { 211 | output: { 212 | comments: false, 213 | semicolons: !isAnySourceMapEnabled 214 | }, 215 | compress: { 216 | // The Android SBG has problems parsing the output 217 | // when these options are enabled 218 | 'collapse_vars': platform !== "android", 219 | sequences: platform !== "android", 220 | } 221 | } 222 | }) 223 | ], 224 | }, 225 | module: { 226 | rules: [ 227 | { 228 | include: join(appFullPath, entryPath), 229 | use: [ 230 | // Require all Android app components 231 | platform === "android" && { 232 | loader: "nativescript-dev-webpack/android-app-components-loader", 233 | options: { modules: appComponents } 234 | }, 235 | 236 | { 237 | loader: "nativescript-dev-webpack/bundle-config-loader", 238 | options: { 239 | angular: true, 240 | loadCss: !snapshot, // load the application css if in debug mode 241 | unitTesting, 242 | appFullPath, 243 | projectRoot, 244 | ignoredFiles: nsWebpack.getUserDefinedEntries(entries, platform) 245 | } 246 | }, 247 | ].filter(loader => !!loader) 248 | }, 249 | 250 | { test: /\.html$|\.xml$/, use: "raw-loader" }, 251 | 252 | { 253 | test: /[\/|\\]app\.css$/, 254 | use: [ 255 | "nativescript-dev-webpack/style-hot-loader", 256 | { 257 | loader: "nativescript-dev-webpack/css2json-loader", 258 | options: { useForImports: true } 259 | } 260 | ] 261 | }, 262 | { 263 | test: /[\/|\\]app\.scss$/, 264 | use: [ 265 | "nativescript-dev-webpack/style-hot-loader", 266 | { 267 | loader: "nativescript-dev-webpack/css2json-loader", 268 | options: { useForImports: true } 269 | }, 270 | "sass-loader" 271 | ] 272 | }, 273 | 274 | // Angular components reference css files and their imports using raw-loader 275 | { test: /\.css$/, exclude: /[\/|\\]app\.css$/, use: "raw-loader" }, 276 | { test: /\.scss$/, exclude: /[\/|\\]app\.scss$/, use: ["raw-loader", "resolve-url-loader", "sass-loader"] }, 277 | 278 | { 279 | test: /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/, 280 | use: [ 281 | "nativescript-dev-webpack/moduleid-compat-loader", 282 | "nativescript-dev-webpack/lazy-ngmodule-hot-loader", 283 | "@ngtools/webpack", 284 | ] 285 | }, 286 | 287 | // Mark files inside `@angular/core` as using SystemJS style dynamic imports. 288 | // Removing this will cause deprecation warnings to appear. 289 | { 290 | test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/, 291 | parser: { system: true }, 292 | }, 293 | ], 294 | }, 295 | plugins: [ 296 | // Define useful constants like TNS_WEBPACK 297 | new webpack.DefinePlugin({ 298 | "global.TNS_WEBPACK": "true", 299 | "process": "global.process", 300 | }), 301 | // Remove all files from the out dir. 302 | new CleanWebpackPlugin(itemsToClean, { verbose: !!verbose }), 303 | // Copy assets to out dir. Add your own globs as needed. 304 | new CopyWebpackPlugin([ 305 | { from: { glob: "fonts/**" } }, 306 | { from: { glob: "**/*.jpg" } }, 307 | { from: { glob: "**/*.png" } }, 308 | ], { ignore: [`${relative(appPath, appResourcesFullPath)}/**`] }), 309 | new nsWebpack.GenerateNativeScriptEntryPointsPlugin("bundle"), 310 | // For instructions on how to set up workers with webpack 311 | // check out https://github.com/nativescript/worker-loader 312 | new NativeScriptWorkerPlugin(), 313 | ngCompilerPlugin, 314 | // Does IPC communication with the {N} CLI to notify events when running in watch mode. 315 | new nsWebpack.WatchStateLoggerPlugin(), 316 | ], 317 | }; 318 | 319 | if (report) { 320 | // Generate report files for bundles content 321 | config.plugins.push(new BundleAnalyzerPlugin({ 322 | analyzerMode: "static", 323 | openAnalyzer: false, 324 | generateStatsFile: true, 325 | reportFilename: resolve(projectRoot, "report", `report.html`), 326 | statsFilename: resolve(projectRoot, "report", `stats.json`), 327 | })); 328 | } 329 | 330 | if (snapshot) { 331 | config.plugins.push(new nsWebpack.NativeScriptSnapshotPlugin({ 332 | chunk: "vendor", 333 | angular: true, 334 | requireModules: [ 335 | "reflect-metadata", 336 | "@angular/platform-browser", 337 | "@angular/core", 338 | "@angular/common", 339 | "@angular/router", 340 | "nativescript-angular/platform-static", 341 | "nativescript-angular/router", 342 | ], 343 | projectRoot, 344 | webpackConfig: config, 345 | snapshotInDocker, 346 | skipSnapshotTools, 347 | useLibs 348 | })); 349 | } 350 | 351 | if (hmr) { 352 | config.plugins.push(new webpack.HotModuleReplacementPlugin()); 353 | } 354 | 355 | return config; 356 | }; 357 | -------------------------------------------------------------------------------- /contacts-helper.android.js: -------------------------------------------------------------------------------- 1 | var constants = require("./constants"); 2 | var Perms = require("nativescript-permissions"); 3 | var imageSource = require("@nativescript/core/image-source"); 4 | 5 | exports.handlePermission = (() => { 6 | return new Promise((resolve, reject) => { 7 | // check whether we already have permissions 8 | if (Perms.hasPermission(android.Manifest.permission.READ_CONTACTS)) { 9 | resolve(); 10 | } 11 | 12 | Perms.requestPermission( 13 | android.Manifest.permission.READ_CONTACTS, 14 | "This application requires read-only access to your contacts!" 15 | ).then(() => { 16 | resolve(); 17 | }).catch(() => { 18 | reject('Unable to obtain permission to read contacts!'); 19 | }); 20 | }); 21 | }); 22 | 23 | /* 24 | inside a web worker appModule.android.context does not work 25 | */ 26 | var getAndroidContext = () => { 27 | if (typeof appModule != "undefined" && appModule.hasOwnProperty('android') && appModule.android.hasOwnProperty('context')) { 28 | return (appModule.android.context); 29 | } 30 | 31 | var ctx = java.lang.Class.forName("android.app.AppGlobals").getMethod("getInitialApplication", null).invoke(null, null); 32 | if (ctx) { return ctx; } 33 | 34 | ctx = java.lang.Class.forName("android.app.ActivityThread").getMethod("currentApplication", null).invoke(null, null); 35 | return ctx; 36 | }; 37 | exports.getAndroidContext = getAndroidContext; 38 | 39 | /* 40 | returns value for column with index columnIndex 41 | helper function for convertNativeCursorToContact 42 | */ 43 | var getColumnValue = (cursor,columnIndex) => { 44 | var columnType = cursor.getType(columnIndex); 45 | switch (columnType) { 46 | case 0: // NULL 47 | return null; 48 | case 1: // Integer 49 | return cursor.getInt(columnIndex); 50 | case 2: // Float 51 | return cursor.getFloat(columnIndex); 52 | case 3: // String 53 | return cursor.getString(columnIndex); 54 | case 4: // Blob 55 | return cursor.getBlob(columnIndex); 56 | break; 57 | default: 58 | throw new Error('Contact - Unknown column type '+ columnType); 59 | } 60 | } 61 | exports.getColumnValue = getColumnValue; 62 | 63 | /* 64 | Takes a native cursor row and converts to json object for new contacts 65 | If contact already exists then merge relevant properties with the existing object 66 | 67 | Arguments 68 | 1: cursor - the cursor returned by Android's getContentResolver().query() 69 | 2: fields - those the user is interested in (skip irrelevant properties for speedup) 70 | 3: columnNames - since we already have those, no need to check them for every iteration 71 | 4: existingContact - either undefined or object for an existing record 72 | */ 73 | exports.convertNativeCursorToContact = (cursor,fields,columnNames,existingContact) => { 74 | let contact = {}; // contact object to return if creatng a new record 75 | if (existingContact) { contact = existingContact; } 76 | 77 | if (!existingContact) { 78 | contact.contact_id = getColumnValue(cursor,columnNames.indexOf("contact_id")); 79 | } 80 | 81 | /* display_name */ 82 | 83 | if (fields.indexOf("display_name") > -1 && !existingContact) { 84 | contact.display_name = getColumnValue(cursor,columnNames.indexOf("display_name")); 85 | } 86 | 87 | /* name_details */ 88 | 89 | if (fields.indexOf("name_details") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['name_details']) { 90 | var record = { "account_name" : getColumnValue(cursor,columnNames.indexOf("account_name")) } 91 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['name_details']['family'])); 92 | if (columnValue != null) { record.family = columnValue } 93 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['name_details']['given'])); 94 | if (columnValue != null) { record.given = columnValue } 95 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['name_details']['middle'])); 96 | if (columnValue != null) { record.middle = columnValue } 97 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['name_details']['prefix'])); 98 | if (columnValue != null) { record.prefix = columnValue } 99 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['name_details']['suffix'])); 100 | if (columnValue != null) { record.suffix = columnValue } 101 | if (!existingContact || !contact.hasOwnProperty('name_details')) { contact.name_details = []; } 102 | contact.name_details.push(record); 103 | } 104 | 105 | /* phone */ 106 | 107 | if (fields.indexOf("phone") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['phone']) { 108 | var record = { "account_name" : getColumnValue(cursor,columnNames.indexOf("account_name")) } 109 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['phone']['type'])); 110 | if (columnValue != null) { record.type = constants.DATA_TYPES['phone']['labels'][columnValue] || columnValue } 111 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['phone']['number'])); 112 | if (columnValue != null) { record.number = columnValue.trim() } 113 | if (!existingContact || !contact.hasOwnProperty('phone')) { contact.phone = []; } 114 | contact.phone.push(record); 115 | } 116 | 117 | /* photo */ 118 | 119 | if (fields.indexOf("photo") > -1 && !existingContact) { 120 | var image = null; 121 | var imageUri = getColumnValue(cursor,columnNames.indexOf("photo_uri")); 122 | if (imageUri!==null) { 123 | image = android.provider.MediaStore.Images.Media.getBitmap( 124 | getAndroidContext().getContentResolver(), 125 | android.net.Uri.parse(imageUri) 126 | ); 127 | contact.photo = "data:image/png;base64,"+imageSource.fromNativeSource(image).toBase64String("png"); 128 | } else { contact.photo = null; } 129 | } 130 | 131 | /* thumbnail */ 132 | 133 | if (fields.indexOf("thumbnail") > -1 && !existingContact) { 134 | var image = null; 135 | var imageUri = getColumnValue(cursor,columnNames.indexOf("photo_thumb_uri")); 136 | if (imageUri!==null) { 137 | image = android.provider.MediaStore.Images.Media.getBitmap( 138 | getAndroidContext().getContentResolver(), 139 | android.net.Uri.parse(imageUri) 140 | ); 141 | contact.thumbnail = "data:image/png;base64,"+imageSource.fromNativeSource(image).toBase64String("png"); 142 | } else { contact.thumbnail = null; } 143 | } 144 | 145 | /* organization */ 146 | 147 | if (fields.indexOf("organization") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['organization']) { 148 | var record = { "account_name" : getColumnValue(cursor,columnNames.indexOf("account_name")) } 149 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['organization']['type'])); 150 | if (columnValue != null) { record.type = constants.DATA_TYPES['organization']['labels'][columnValue] || columnValue } 151 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['organization']['department'])); 152 | if (columnValue != null) { record.department = columnValue } 153 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['organization']['company'])); 154 | if (columnValue != null) { record.company = columnValue } 155 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['organization']['title'])); 156 | if (columnValue != null) { record.title = columnValue } 157 | if (!existingContact || !contact.hasOwnProperty('organization')) { contact.organization = []; } 158 | contact.organization.push(record); 159 | } 160 | 161 | /* nickname */ 162 | 163 | if (fields.indexOf("nickname") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['nickname']) { 164 | var record = {}; 165 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['nickname'])); 166 | if (columnValue!=null && columnValue!='') { 167 | record.name = columnValue; 168 | record.account_name = getColumnValue(cursor,columnNames.indexOf("account_name")); 169 | } else { record = null; } 170 | if (!existingContact || !contact.hasOwnProperty('nickname')) { contact.nickname = []; } 171 | if (record!=null) { contact.nickname.push(record); } 172 | } 173 | 174 | /* note */ 175 | 176 | if (fields.indexOf("note") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['note']) { 177 | var record = {}; 178 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['note'])); 179 | if (columnValue!=null && columnValue!='') { 180 | record.note = columnValue; 181 | record.account_name = getColumnValue(cursor,columnNames.indexOf("account_name")); 182 | } else { record = null; } 183 | if (!existingContact || !contact.hasOwnProperty('note')) { contact.note = []; } 184 | if (record!=null) { contact.note.push(record); } 185 | } 186 | 187 | /* email */ 188 | 189 | if (fields.indexOf("email") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['email']) { 190 | var record = { "account_name" : getColumnValue(cursor,columnNames.indexOf("account_name")) } 191 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['email']['type'])); 192 | if (columnValue != null) { record.type = constants.DATA_TYPES['email']['labels'][columnValue] || columnValue } 193 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['email']['data'])); 194 | if (columnValue != null) { record.address = columnValue } 195 | if (!existingContact || !contact.hasOwnProperty('email')) { contact.email = []; } 196 | contact.email.push(record); 197 | } 198 | 199 | /* website */ 200 | 201 | if (fields.indexOf("website") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['website']) { 202 | var record = { "account_name" : getColumnValue(cursor,columnNames.indexOf("account_name")) } 203 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['website']['type'])); 204 | if (columnValue != null) { record.type = constants.DATA_TYPES['website']['labels'][columnValue] || columnValue } 205 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['website']['url'])); 206 | if (columnValue != null) { record.url = columnValue } 207 | if (!existingContact || !contact.hasOwnProperty('website')) { contact.website = []; } 208 | contact.website.push(record); 209 | } 210 | 211 | /* address */ 212 | 213 | if (fields.indexOf("address") > -1 && getColumnValue(cursor,columnNames.indexOf("mimetype")) == constants.MIME_TYPES['address']) { 214 | var record = { "account_name" : getColumnValue(cursor,columnNames.indexOf("account_name")) } 215 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['address']['type'])); 216 | if (columnValue != null) { record.type = constants.DATA_TYPES['address']['labels'][columnValue] || columnValue } 217 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['address']['formatted_address'])); 218 | if (columnValue != null) { record.formatted_address = columnValue } 219 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['address']['street'])); 220 | if (columnValue != null) { record.street = columnValue } 221 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['address']['city'])); 222 | if (columnValue != null) { record.city = columnValue } 223 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['address']['region'])); 224 | if (columnValue != null) { record.region = columnValue } 225 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['address']['postcode'])); 226 | if (columnValue != null) { record.postcode = columnValue } 227 | var columnValue = getColumnValue(cursor,columnNames.indexOf(constants.DATA_TYPES['address']['country'])); 228 | if (columnValue != null) { record.country = columnValue } 229 | if (!existingContact || !contact.hasOwnProperty('address')) { contact.address = []; } 230 | contact.address.push(record); 231 | } 232 | return contact; 233 | }; 234 | 235 | /* 236 | returns an array with names of columns to fetch from Android storage backend 237 | constants map to Android's "dataX" fields, e.g. 238 | android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER = "data1" 239 | see: https://developer.android.com/reference/android/provider/ContactsContract.Data.html 240 | */ 241 | exports.getAndroidQueryColumns = (fields) => { 242 | let columnsToFetch = []; 243 | 244 | columnsToFetch.push("contact_id","mimetype","account_name"); 245 | 246 | if (fields.indexOf("display_name") > -1) { 247 | columnsToFetch.push(android.provider.ContactsContract.ContactNameColumns.DISPLAY_NAME_PRIMARY); 248 | } 249 | 250 | if (fields.indexOf("name_details") > -1) { 251 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME); 252 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME); 253 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME); 254 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredName.PREFIX); 255 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredName.SUFFIX); 256 | } 257 | if (fields.indexOf("phone") > -1) { 258 | //columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Phone._ID); 259 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Phone.NUMBER); 260 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Phone.TYPE); 261 | } 262 | if (fields.indexOf("email") > -1) { 263 | //columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Email._ID); 264 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Email.DATA); 265 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Email.TYPE); 266 | } 267 | if (fields.indexOf("address") > -1) { 268 | //columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredPostal._ID); 269 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Organization.TYPE); 270 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS); 271 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredPostal.STREET); 272 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredPostal.CITY); 273 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredPostal.REGION); 274 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE); 275 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY); 276 | } 277 | if (fields.indexOf("organization") > -1) { 278 | //columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Organization._ID); 279 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Organization.TYPE); 280 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Organization.DEPARTMENT); 281 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Organization.COMPANY); 282 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Organization.TITLE); 283 | } 284 | if (fields.indexOf("note") > -1) { 285 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Note.NOTE); 286 | } 287 | if (fields.indexOf("nickname") > -1) { 288 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Nickname.NAME); 289 | } 290 | if (fields.indexOf("website") > -1) { 291 | //columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Website._ID); 292 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Website.URL); 293 | columnsToFetch.push(android.provider.ContactsContract.CommonDataKinds.Website.TYPE); 294 | } 295 | if (fields.indexOf("photo") > -1) { 296 | columnsToFetch.push("photo_uri"); 297 | } 298 | if (fields.indexOf("thumbnail") > -1) { 299 | columnsToFetch.push("photo_thumb_uri"); 300 | } 301 | 302 | // filter out any nulls & duplicates 303 | return columnsToFetch.filter((item, index, self) => { return (item != null && index == self.indexOf(item)) }); 304 | } 305 | 306 | 307 | 308 | /* 309 | returns an array with names of relevant metadata types to fetch from storage backend 310 | */ 311 | let getAndroidMimeTypes = (fields) => { 312 | let datatypes = []; 313 | 314 | if (fields.indexOf("name_details") > -1) { datatypes.push(constants.MIME_TYPES['name_details']); } 315 | if (fields.indexOf("phone") > -1) { datatypes.push(constants.MIME_TYPES['phone']); } 316 | if (fields.indexOf("photo") > -1) { 317 | // datatypes.push(constants.MIME_TYPES['photo']); // photo + thumb URI are obtained in getAndroidQueryColumns 318 | } 319 | if (fields.indexOf("organization") > -1) { datatypes.push(constants.MIME_TYPES['organization']); } 320 | if (fields.indexOf("nickname") > -1) { datatypes.push(constants.MIME_TYPES['nickname']); } 321 | if (fields.indexOf("note") > -1) { datatypes.push(constants.MIME_TYPES['note']); } 322 | if (fields.indexOf("website") > -1) { datatypes.push(constants.MIME_TYPES['website']); } 323 | if (fields.indexOf("email") > -1) { datatypes.push(constants.MIME_TYPES['email']); } 324 | if (fields.indexOf("address") > -1) { datatypes.push(constants.MIME_TYPES['address']); } 325 | 326 | return datatypes.filter((value) => { return value != null; }); // filter out any nulls 327 | } 328 | exports.getAndroidMimeTypes = getAndroidMimeTypes; 329 | 330 | /* 331 | returns an string with the selection clause, e.g. '(mimetype=? OR mimetype=?) AND searchTerm="Jon"' 332 | */ 333 | exports.getSelectionClause = ((options) => { 334 | let clause = '', clauseArray = [], fieldsArray = []; 335 | 336 | getAndroidMimeTypes(options.fields).forEach((mimetype) => { fieldsArray.push('mimetype=?','OR'); }); 337 | fieldsArray.pop(); 338 | if (fieldsArray.length >0) { clauseArray.push(`(${fieldsArray.join(' ')})`,'AND'); } 339 | 340 | if (options.hasOwnProperty('searchTerm') && options.searchTerm) { 341 | clauseArray.push(`${android.provider.ContactsContract.ContactNameColumns.DISPLAY_NAME_PRIMARY} LIKE ?`,'AND'); 342 | } 343 | 344 | if (options.hasOwnProperty('contactId') && options.contactId) { clauseArray.push('contact_id=?','AND'); } 345 | clauseArray.pop(); 346 | if (clauseArray.length >0) { clause = clauseArray.join(' '); } 347 | return(clause); 348 | }); 349 | 350 | /* 351 | returns an array of strings with the arguments for the selection clause, 352 | e.g. ['vnd.android.cursor.item/name','vnd.android.cursor.item/photo'] 353 | */ 354 | exports.getSelectionArgs = ((options) => { 355 | let argsArray = []; 356 | 357 | getAndroidMimeTypes(options.fields).forEach((mimetype) => { argsArray.push(mimetype); }); 358 | if (options.hasOwnProperty('searchTerm') && options.searchTerm) { argsArray.push(`%${options.searchTerm}%`); } 359 | if (options.hasOwnProperty('contactId') && options.contactId) { argsArray.push(`${options.contactId}`); } 360 | //if (options.hasOwnProperty('contactId') && options.contactId) { argsArray.push(options.contactId); } 361 | return(argsArray); 362 | }); 363 | --------------------------------------------------------------------------------