├── example
├── .watchmanconfig
├── .gitattributes
├── .babelrc
├── app.json
├── screenshot.png
├── android
│ ├── app
│ │ ├── src
│ │ │ └── main
│ │ │ │ ├── res
│ │ │ │ ├── values
│ │ │ │ │ ├── strings.xml
│ │ │ │ │ └── styles.xml
│ │ │ │ ├── mipmap-hdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── mipmap-mdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── mipmap-xhdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ └── mipmap-xxhdpi
│ │ │ │ │ └── ic_launcher.png
│ │ │ │ ├── java
│ │ │ │ └── com
│ │ │ │ │ └── dialogflowexample
│ │ │ │ │ ├── MainActivity.java
│ │ │ │ │ └── MainApplication.java
│ │ │ │ └── AndroidManifest.xml
│ │ ├── BUCK
│ │ ├── proguard-rules.pro
│ │ └── build.gradle
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── keystores
│ │ ├── debug.keystore.properties
│ │ └── BUCK
│ ├── settings.gradle
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradlew.bat
│ └── gradlew
├── ios
│ ├── DialogflowExample
│ │ ├── Images.xcassets
│ │ │ ├── Contents.json
│ │ │ └── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ ├── AppDelegate.h
│ │ ├── main.m
│ │ ├── AppDelegate.m
│ │ ├── Info.plist
│ │ └── Base.lproj
│ │ │ └── LaunchScreen.xib
│ ├── DialogflowExampleTests
│ │ ├── Info.plist
│ │ └── DialogflowExampleTests.m
│ ├── DialogflowExample-tvOSTests
│ │ └── Info.plist
│ ├── DialogflowExample-tvOS
│ │ └── Info.plist
│ └── DialogflowExample.xcodeproj
│ │ └── xcshareddata
│ │ └── xcschemes
│ │ ├── DialogflowExample.xcscheme
│ │ └── DialogflowExample-tvOS.xcscheme
├── .buckconfig
├── index.js
├── README.md
├── package.json
├── .gitignore
├── .flowconfig
├── App.android.js
└── App.ios.js
├── header_img.png
├── .npmignore
├── android
├── src
│ └── main
│ │ ├── res
│ │ ├── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ ├── mipmap-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── mipmap-xhdpi
│ │ │ └── ic_launcher.png
│ │ └── mipmap-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── de
│ │ └── innfactory
│ │ └── apiai
│ │ ├── RNApiAiPackage.java
│ │ └── RNApiAiModule.java
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── build.gradle
├── gradlew.bat
└── gradlew
├── .gitattributes
├── .buckconfig
├── .travis.yml
├── yarn.lock
├── __tests__
├── index.ios.js
└── index.android.js
├── ios
├── ApiAi
│ ├── ApiAi.h
│ └── ApiAi.m
└── ApiAi.xcodeproj
│ └── project.pbxproj
├── react-native-dialogflow.podspec
├── js
├── Errors.js
├── googleAuth
│ ├── GoogleAuth.js
│ └── postAsForm.js
├── ResetContextsRequest.js
├── Dialogflow.js
├── XhrRequest.js
├── RCTVoice.js
└── Dialogflow_V2.js
├── package.json
├── .gitignore
├── LICENSE
├── index.js
└── README.md
/example/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
--------------------------------------------------------------------------------
/example/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 |
--------------------------------------------------------------------------------
/header_img.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/header_img.png
--------------------------------------------------------------------------------
/example/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | "module:metro-react-native-babel-preset"
4 | ]
5 | }
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "DialogflowExample",
3 | "displayName": "DialogflowExample"
4 | }
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | node_modules/
2 | example/
3 | android/build/
4 | ios/lib/DerivedData/
5 | header_img.png
6 | travis.yml
--------------------------------------------------------------------------------
/example/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/example/screenshot.png
--------------------------------------------------------------------------------
/android/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | reactNativeApiAi
3 |
4 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | ios/* linguist-vendored=true
3 | android/* linguist-vendored=true
4 | example/* linguist-vendored=true
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | DialogflowExample
3 |
4 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/.buckconfig:
--------------------------------------------------------------------------------
1 |
2 | [android]
3 | target = Google Inc.:Google APIs:23
4 |
5 | [maven_repositories]
6 | central = https://repo1.maven.org/maven2
7 |
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/example/.buckconfig:
--------------------------------------------------------------------------------
1 |
2 | [android]
3 | target = Google Inc.:Google APIs:23
4 |
5 | [maven_repositories]
6 | central = https://repo1.maven.org/maven2
7 |
--------------------------------------------------------------------------------
/android/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/android/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/android/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/android/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/android/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/example/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import { AppRegistry } from 'react-native';
2 | import App from './App';
3 |
4 | AppRegistry.registerComponent('DialogflowExample', () => App);
5 |
--------------------------------------------------------------------------------
/android/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/android/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/keystores/debug.keystore.properties:
--------------------------------------------------------------------------------
1 | key.store=debug.keystore
2 | key.alias=androiddebugkey
3 | key.store.password=android
4 | key.alias.password=android
5 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: android
2 | sudo: required
3 | jdk: oraclejdk8
4 | before_script: cd android
5 | android:
6 | components:
7 | - build-tools-25.0.3
8 | - android-25
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/innFactory/react-native-dialogflow/HEAD/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/keystores/BUCK:
--------------------------------------------------------------------------------
1 | keystore(
2 | name = "debug",
3 | properties = "debug.keystore.properties",
4 | store = "debug.keystore",
5 | visibility = [
6 | "PUBLIC",
7 | ],
8 | )
9 |
--------------------------------------------------------------------------------
/android/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
6 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | zipStoreBase=GRADLE_USER_HOME
4 | zipStorePath=wrapper/dists
5 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
6 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | # Example App
2 |
3 | How to run:
4 | ```
5 | git clone https://github.com/innFactory/react-native-dialogflow.git
6 | cd react-native-dialogflow/example
7 | npm install
8 | react-native run-android
9 | ```
10 |
11 |
12 |
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/yarn.lock:
--------------------------------------------------------------------------------
1 | # THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
2 | # yarn lockfile v1
3 |
4 |
5 | jsrsasign@^8.0.12:
6 | version "8.0.12"
7 | resolved "https://registry.yarnpkg.com/jsrsasign/-/jsrsasign-8.0.12.tgz#22abb9656d34a30b9530436720835e89c2e5c316"
8 | integrity sha1-Iqu5ZW00owuVMENnIINeicLlwxY=
9 |
--------------------------------------------------------------------------------
/__tests__/index.ios.js:
--------------------------------------------------------------------------------
1 | import 'react-native';
2 | import React from 'react';
3 | import Index from '../index.ios.js';
4 |
5 | // Note: test renderer must be required after react-native.
6 | import renderer from 'react-test-renderer';
7 |
8 | it('renders correctly', () => {
9 | const tree = renderer.create(
10 |
11 | );
12 | });
13 |
--------------------------------------------------------------------------------
/__tests__/index.android.js:
--------------------------------------------------------------------------------
1 | import 'react-native';
2 | import React from 'react';
3 | import Index from '../index.android.js';
4 |
5 | // Note: test renderer must be required after react-native.
6 | import renderer from 'react-test-renderer';
7 |
8 | it('renders correctly', () => {
9 | const tree = renderer.create(
10 |
11 | );
12 | });
13 |
--------------------------------------------------------------------------------
/ios/ApiAi/ApiAi.h:
--------------------------------------------------------------------------------
1 |
2 |
3 | #import
4 | #if __has_include("RCTBridgeModule.h")
5 | #import "RCTBridgeModule.h"
6 | #else
7 | #import
8 | #endif
9 | #if __has_include("RCTLog.h")
10 | #import "RCTLog.h"
11 | #else
12 | #import
13 | #endif
14 |
15 |
16 | @interface ApiAi: NSObject
17 |
18 |
19 | @end
20 |
--------------------------------------------------------------------------------
/example/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'DialogflowExample'
2 | include ':react-native-dialogflow'
3 | project(':react-native-dialogflow').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-dialogflow/android')
4 | include ':react-native-voice'
5 | project(':react-native-voice').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-voice/android')
6 |
7 | include ':app'
8 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample/AppDelegate.h:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 |
10 | @interface AppDelegate : UIResponder
11 |
12 | @property (nonatomic, strong) UIWindow *window;
13 |
14 | @end
15 |
--------------------------------------------------------------------------------
/ios/ApiAi/ApiAi.m:
--------------------------------------------------------------------------------
1 |
2 |
3 | #import "ApiAi.h"
4 | #if __has_include("RCTBridge.h")
5 | #import "RCTBridge.h"
6 | #else
7 | #import
8 | #endif
9 |
10 | @implementation ApiAi
11 | RCT_EXPORT_MODULE();
12 |
13 | /*
14 | RCT_EXPORT_METHOD(setConfiguration:(NSString *)clientAccessToken languageTag:(NSString *)languageTag) {
15 |
16 | }
17 |
18 |
19 | RCT_EXPORT_METHOD(startListening) {
20 |
21 | }
22 | */
23 |
24 | @end
25 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample/main.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 |
10 | #import "AppDelegate.h"
11 |
12 | int main(int argc, char * argv[]) {
13 | @autoreleasepool {
14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/dialogflowexample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.dialogflowexample;
2 |
3 | import com.facebook.react.ReactActivity;
4 |
5 | public class MainActivity extends ReactActivity {
6 |
7 | /**
8 | * Returns the name of the main component registered from JavaScript.
9 | * This is used to schedule rendering of the component.
10 | */
11 | @Override
12 | protected String getMainComponentName() {
13 | return "DialogflowExample";
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "DialogflowExample",
3 | "version": "0.0.1",
4 | "private": true,
5 | "scripts": {
6 | "start": "node node_modules/react-native/local-cli/cli.js start",
7 | "test": "jest"
8 | },
9 | "dependencies": {
10 | "jsrsasign": "^8.0.12",
11 | "react": "16.6.0-alpha.8af6728",
12 | "react-native": "0.57.3",
13 | "react-native-dialogflow": "../"
14 | },
15 | "devDependencies": {
16 | "metro-react-native-babel-preset": "0.48.1"
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/react-native-dialogflow.podspec:
--------------------------------------------------------------------------------
1 | require 'json'
2 |
3 | package = JSON.parse(File.read(File.join(__dir__, 'package.json')))
4 |
5 | Pod::Spec.new do |spec|
6 | spec.name = package['name']
7 | spec.version = package['version']
8 | spec.author = package['author']
9 | spec.license = package['license']
10 | spec.homepage = package['repository']['url']
11 | spec.source = {
12 | :git => "#{package['repository']['url']}.git"
13 | }
14 | spec.summary = package['description']
15 | spec.source_files = 'ios/**/*.{h,m}'
16 | spec.platform = :ios, '8.0'
17 | spec.dependency 'React'
18 | end
19 |
--------------------------------------------------------------------------------
/js/Errors.js:
--------------------------------------------------------------------------------
1 | export class ApiAiBaseError extends Error {
2 | constructor(message) {
3 | super(message);
4 | this.message = message;
5 | this.stack = new Error().stack;
6 | }
7 | }
8 | export class ApiAiClientConfigurationError extends ApiAiBaseError {
9 | constructor(message) {
10 | super(message);
11 | this.name = "ApiAiClientConfigurationError";
12 | }
13 | }
14 | export class ApiAiRequestError extends ApiAiBaseError {
15 | constructor(message, code = null) {
16 | super(message);
17 | this.message = message;
18 | this.code = code;
19 | this.name = "ApiAiRequestError";
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/example/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:2.2.3'
9 |
10 | // NOTE: Do not place your application dependencies here; they belong
11 | // in the individual module build.gradle files
12 | }
13 | }
14 |
15 | allprojects {
16 | repositories {
17 | mavenLocal()
18 | jcenter()
19 | maven {
20 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
21 | url "$rootDir/../node_modules/react-native/android"
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-dialogflow",
3 | "description": "A React-Native Bridge for the Google Dialogflow SDK",
4 | "version": "3.2.2",
5 | "author": "Anton Spöck (https://github.com/spoeck)",
6 | "dependencies": {
7 | "jsrsasign": "^8.0.12"
8 | },
9 | "keywords": [
10 | "ai",
11 | "api",
12 | "api-ai",
13 | "api.ai",
14 | "apiai",
15 | "dialogflow",
16 | "google",
17 | "react-native",
18 | "speak",
19 | "text-recognition",
20 | "voice"
21 | ],
22 | "license": "MIT",
23 | "peerDependencies": {
24 | "react-native": ">=0.40.0",
25 | "react-native-voice": ">=0.2.6"
26 | },
27 | "repository": {
28 | "type": "git",
29 | "url": "https://github.com/innFactory/react-native-dialogflow"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/example/ios/DialogflowExampleTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample-tvOSTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/example/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | android.useDeprecatedNdk=true
21 |
--------------------------------------------------------------------------------
/example/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # Xcode
6 | #
7 | build/
8 | *.pbxuser
9 | !default.pbxuser
10 | *.mode1v3
11 | !default.mode1v3
12 | *.mode2v3
13 | !default.mode2v3
14 | *.perspectivev3
15 | !default.perspectivev3
16 | xcuserdata
17 | *.xccheckout
18 | *.moved-aside
19 | DerivedData
20 | *.hmap
21 | *.ipa
22 | *.xcuserstate
23 | project.xcworkspace
24 |
25 | # Android/IntelliJ
26 | #
27 | build/
28 | .idea
29 | .gradle
30 | local.properties
31 | *.iml
32 |
33 | # node.js
34 | #
35 | node_modules/
36 | npm-debug.log
37 | yarn-error.log
38 |
39 | # BUCK
40 | buck-out/
41 | \.buckd/
42 | *.keystore
43 |
44 | # fastlane
45 | #
46 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
47 | # screenshots whenever they are needed.
48 | # For more information about the recommended setup visit:
49 | # https://docs.fastlane.tools/best-practices/source-control/
50 |
51 | */fastlane/report.xml
52 | */fastlane/Preview.html
53 | */fastlane/screenshots
54 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | header_img.png
2 |
3 | # OSX
4 | #
5 | .DS_Store
6 |
7 | # Xcode
8 | #
9 | build/
10 | *.pbxuser
11 | !default.pbxuser
12 | *.mode1v3
13 | !default.mode1v3
14 | *.mode2v3
15 | !default.mode2v3
16 | *.perspectivev3
17 | !default.perspectivev3
18 | xcuserdata
19 | *.xccheckout
20 | *.moved-aside
21 | DerivedData
22 | *.hmap
23 | *.ipa
24 | *.xcuserstate
25 | project.xcworkspace
26 |
27 | # Android/IntelliJ
28 | #
29 | build/
30 | .idea
31 | .gradle
32 | local.properties
33 | *.iml
34 |
35 | # node.js
36 | #
37 | node_modules/
38 | npm-debug.log
39 | yarn-error.log
40 |
41 | # BUCK
42 | buck-out/
43 | \.buckd/
44 | *.keystore
45 |
46 | # fastlane
47 | #
48 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
49 | # screenshots whenever they are needed.
50 | # For more information about the recommended setup visit:
51 | # https://github.com/fastlane/fastlane/blob/master/fastlane/docs/Gitignore.md
52 |
53 | fastlane/report.xml
54 | fastlane/Preview.html
55 | fastlane/screenshots
56 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 innFactory
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 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
7 |
13 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/android/src/main/java/de/innfactory/apiai/RNApiAiPackage.java:
--------------------------------------------------------------------------------
1 | package de.innfactory.apiai;
2 |
3 |
4 | import com.facebook.react.ReactPackage;
5 | import com.facebook.react.bridge.JavaScriptModule;
6 | import com.facebook.react.bridge.NativeModule;
7 | import com.facebook.react.bridge.ReactApplicationContext;
8 | import com.facebook.react.uimanager.ViewManager;
9 |
10 | import java.lang.reflect.Array;
11 | import java.util.ArrayList;
12 | import java.util.Collections;
13 | import java.util.List;
14 |
15 |
16 | /**
17 | * Created by Anton Spöck on 2017-07-21
18 | **/
19 | public class RNApiAiPackage implements ReactPackage{
20 |
21 | public List> createJSModules() {
22 | return Collections.emptyList();
23 | }
24 |
25 | @Override
26 | public List createViewManagers(ReactApplicationContext reactContext) {
27 | return Collections.emptyList();
28 | }
29 |
30 |
31 | @Override
32 | public List createNativeModules(
33 | ReactApplicationContext reactContext) {
34 | List modules = new ArrayList<>();
35 |
36 | modules.add(new RNApiAiModule(reactContext));
37 |
38 | return modules;
39 | }
40 |
41 | }
--------------------------------------------------------------------------------
/example/ios/DialogflowExample/AppDelegate.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import "AppDelegate.h"
9 |
10 | #import
11 | #import
12 |
13 | @implementation AppDelegate
14 |
15 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
16 | {
17 | NSURL *jsCodeLocation;
18 |
19 | jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
20 |
21 | RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
22 | moduleName:@"DialogflowExample"
23 | initialProperties:nil
24 | launchOptions:launchOptions];
25 | rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
26 |
27 | self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
28 | UIViewController *rootViewController = [UIViewController new];
29 | rootViewController.view = rootView;
30 | self.window.rootViewController = rootViewController;
31 | [self.window makeKeyAndVisible];
32 | return YES;
33 | }
34 |
35 | @end
36 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/dialogflowexample/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.dialogflowexample;
2 |
3 | import android.app.Application;
4 |
5 | import com.facebook.react.ReactApplication;
6 | import de.innfactory.apiai.RNApiAiPackage;
7 | import com.wenkesj.voice.VoicePackage;
8 | import com.facebook.react.ReactNativeHost;
9 | import com.facebook.react.ReactPackage;
10 | import com.facebook.react.shell.MainReactPackage;
11 | import com.facebook.soloader.SoLoader;
12 |
13 | import java.util.Arrays;
14 | import java.util.List;
15 |
16 | public class MainApplication extends Application implements ReactApplication {
17 |
18 | private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
19 | @Override
20 | public boolean getUseDeveloperSupport() {
21 | return BuildConfig.DEBUG;
22 | }
23 |
24 | @Override
25 | protected List getPackages() {
26 | return Arrays.asList(
27 | new MainReactPackage(),
28 | new RNApiAiPackage(),
29 | new VoicePackage()
30 | );
31 | }
32 |
33 | @Override
34 | protected String getJSMainModuleName() {
35 | return "index";
36 | }
37 | };
38 |
39 | @Override
40 | public ReactNativeHost getReactNativeHost() {
41 | return mReactNativeHost;
42 | }
43 |
44 | @Override
45 | public void onCreate() {
46 | super.onCreate();
47 | SoLoader.init(this, /* native exopackage */ false);
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/example/.flowconfig:
--------------------------------------------------------------------------------
1 | [ignore]
2 | ; We fork some components by platform
3 | .*/*[.]android.js
4 |
5 | ; Ignore "BUCK" generated dirs
6 | /\.buckd/
7 |
8 | ; Ignore unexpected extra "@providesModule"
9 | .*/node_modules/.*/node_modules/fbjs/.*
10 |
11 | ; Ignore duplicate module providers
12 | ; For RN Apps installed via npm, "Libraries" folder is inside
13 | ; "node_modules/react-native" but in the source repo it is in the root
14 | .*/Libraries/react-native/React.js
15 |
16 | ; Ignore polyfills
17 | .*/Libraries/polyfills/.*
18 |
19 | ; Ignore metro
20 | .*/node_modules/metro/.*
21 |
22 | [include]
23 |
24 | [libs]
25 | node_modules/react-native/Libraries/react-native/react-native-interface.js
26 | node_modules/react-native/flow/
27 | node_modules/react-native/flow-github/
28 |
29 | [options]
30 | emoji=true
31 |
32 | module.system=haste
33 |
34 | munge_underscores=true
35 |
36 | module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub'
37 |
38 | module.file_ext=.js
39 | module.file_ext=.jsx
40 | module.file_ext=.json
41 | module.file_ext=.native.js
42 |
43 | suppress_type=$FlowIssue
44 | suppress_type=$FlowFixMe
45 | suppress_type=$FlowFixMeProps
46 | suppress_type=$FlowFixMeState
47 |
48 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)
49 | suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+
50 | suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy
51 | suppress_comment=\\(.\\|\n\\)*\\$FlowExpectedError
52 |
53 | [version]
54 | ^0.65.0
55 |
--------------------------------------------------------------------------------
/js/googleAuth/GoogleAuth.js:
--------------------------------------------------------------------------------
1 | var rs = require('jsrsasign');
2 | import postAsForm from './postAsForm';
3 |
4 |
5 | const encodeJWT = function (options) {
6 |
7 | if (!options) { throw new Error('options is required'); }
8 | if (!options.email) { throw new Error('options.email is required'); }
9 | if (!options.scopes) { throw new Error('options.scopes is required'); }
10 | if (!Array.isArray(options.scopes)) { throw new Error('options.scopes must be an array'); }
11 | if (options.scopes.length === 0) { throw new Error('options.scopes must contain at least one scope'); }
12 | if (!options.key) { throw new Error('options.key is required'); }
13 |
14 |
15 | var iat = Math.floor(new Date().getTime() / 1000),
16 | exp = iat + Math.floor((options.expiration || 60 * 60 * 1000) / 1000),
17 | claims = {
18 | iss: options.email,
19 | scope: options.scopes.join(' '),
20 | aud: 'https://accounts.google.com/o/oauth2/token',
21 | exp: exp,
22 | iat: iat,
23 | sub: null
24 | };
25 |
26 | if (options.delegationEmail) {
27 | claims.sub = options.delegationEmail;
28 | }
29 |
30 | // Sign JWT
31 | var sHeader = JSON.stringify({ alg: 'RS256', typ: 'JWT' });
32 | return rs.jws.JWS.sign("RS256", sHeader, JSON.stringify(claims), options.key);
33 | }
34 |
35 | const authenticate = async (email, key, scopes) => {
36 |
37 | const json = await postAsForm('https://accounts.google.com/o/oauth2/token',
38 | {
39 | grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
40 | assertion: encodeJWT({ email, key, scopes })
41 | });
42 |
43 | return JSON.parse(json).access_token;
44 | }
45 |
46 | export default authenticate;
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 |
4 | repositories {
5 | mavenLocal()
6 | mavenCentral()
7 |
8 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
9 | }
10 |
11 | buildscript {
12 | repositories {
13 | jcenter()
14 | }
15 | dependencies {
16 | classpath 'com.android.tools.build:gradle:2.2.3'
17 |
18 | // NOTE: Do not place your application dependencies here; they belong
19 | // in the individual module build.gradle files
20 | }
21 | }
22 |
23 |
24 | android {
25 | compileSdkVersion 25
26 | buildToolsVersion "25.0.3"
27 |
28 | defaultConfig {
29 | minSdkVersion 16
30 | targetSdkVersion 22
31 | versionCode 1
32 | versionName "1.0"
33 | }
34 | lintOptions {
35 | abortOnError false
36 | warning 'InvalidPackage'
37 | }
38 |
39 | packagingOptions {
40 | exclude 'META-INF/DEPENDENCIES.txt'
41 | exclude 'META-INF/LICENSE.txt'
42 | exclude 'META-INF/NOTICE.txt'
43 | exclude 'META-INF/NOTICE'
44 | exclude 'META-INF/LICENSE'
45 | exclude 'META-INF/DEPENDENCIES'
46 | exclude 'META-INF/notice.txt'
47 | exclude 'META-INF/license.txt'
48 | exclude 'META-INF/dependencies.txt'
49 | exclude 'META-INF/LGPL2.1'
50 | }
51 |
52 | }
53 |
54 |
55 |
56 |
57 | dependencies {
58 | compile "com.facebook.react:react-native:+"
59 | compile fileTree(dir: 'libs', include: ['*.jar'])
60 | compile 'com.android.support:appcompat-v7:23.2.1'
61 | compile 'ai.api:sdk:2.0.7@aar'
62 | compile 'com.google.code.gson:gson:2.3'
63 | compile 'commons-io:commons-io:2.4'
64 | compile('ai.api:libai:1.4.8') {
65 | exclude module: 'log4j-core'
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/js/ResetContextsRequest.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Created by toni on 30.08.2017.
3 | */
4 | import { ApiAiRequestError } from "./Errors";
5 | import XhrRequest from './XhrRequest';
6 | export const DEFAULT_BASE_URL = "https://api.api.ai/v1/";
7 |
8 |
9 | class ResetContextsRequest {
10 | constructor(accessToken, sessionId, contextName) {
11 |
12 | if (contextName != null) {
13 | this.uri = DEFAULT_BASE_URL + "contexts/" + contextName + "?sessionId=" + sessionId;
14 | } else {
15 | this.uri = DEFAULT_BASE_URL + "contexts?sessionId=" + sessionId;
16 | }
17 |
18 | this.headers = {
19 | Authorization: "Bearer " + accessToken,
20 | Accept: "application/json",
21 | };
22 | }
23 | static handleSuccess(xhr) {
24 | return Promise.resolve(JSON.parse(xhr.responseText));
25 | }
26 | static handleError(xhr) {
27 | let error = new ApiAiRequestError(null);
28 | try {
29 | const serverResponse = JSON.parse(xhr.responseText);
30 | if (serverResponse.status && serverResponse.status.errorDetails) {
31 | error = new ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code);
32 | }
33 | else {
34 | error = new ApiAiRequestError(xhr.statusText, xhr.status);
35 | }
36 | }
37 | catch (e) {
38 | error = new ApiAiRequestError(xhr.statusText, xhr.status);
39 | }
40 | return Promise.reject(error);
41 | }
42 | perform() {
43 | return XhrRequest.delete(this.uri, null, this.headers, {})
44 | .then(ResetContextsRequest.handleSuccess.bind(this))
45 | .catch(ResetContextsRequest.handleError.bind(this));
46 | }
47 | }
48 | export default ResetContextsRequest;
--------------------------------------------------------------------------------
/example/ios/DialogflowExample-tvOS/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)
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
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIRequiredDeviceCapabilities
28 |
29 | armv7
30 |
31 | UISupportedInterfaceOrientations
32 |
33 | UIInterfaceOrientationPortrait
34 | UIInterfaceOrientationLandscapeLeft
35 | UIInterfaceOrientationLandscapeRight
36 |
37 | UIViewControllerBasedStatusBarAppearance
38 |
39 | NSLocationWhenInUseUsageDescription
40 |
41 | NSAppTransportSecurity
42 |
43 |
44 | NSExceptionDomains
45 |
46 | localhost
47 |
48 | NSExceptionAllowsInsecureHTTPLoads
49 |
50 |
51 |
52 |
53 |
54 |
55 |
--------------------------------------------------------------------------------
/example/android/app/BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | lib_deps = []
12 |
13 | for jarfile in glob(['libs/*.jar']):
14 | name = 'jars__' + jarfile[jarfile.rindex('/') + 1: jarfile.rindex('.jar')]
15 | lib_deps.append(':' + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
21 | for aarfile in glob(['libs/*.aar']):
22 | name = 'aars__' + aarfile[aarfile.rindex('/') + 1: aarfile.rindex('.aar')]
23 | lib_deps.append(':' + name)
24 | android_prebuilt_aar(
25 | name = name,
26 | aar = aarfile,
27 | )
28 |
29 | android_library(
30 | name = "all-libs",
31 | exported_deps = lib_deps,
32 | )
33 |
34 | android_library(
35 | name = "app-code",
36 | srcs = glob([
37 | "src/main/java/**/*.java",
38 | ]),
39 | deps = [
40 | ":all-libs",
41 | ":build_config",
42 | ":res",
43 | ],
44 | )
45 |
46 | android_build_config(
47 | name = "build_config",
48 | package = "com.dialogflowexample",
49 | )
50 |
51 | android_resource(
52 | name = "res",
53 | package = "com.dialogflowexample",
54 | res = "src/main/res",
55 | )
56 |
57 | android_binary(
58 | name = "app",
59 | keystore = "//android/keystores:debug",
60 | manifest = "src/main/AndroidManifest.xml",
61 | package_type = "debug",
62 | deps = [
63 | ":app-code",
64 | ],
65 | )
66 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | DialogflowExample
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | 1.0
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | 1
25 | LSRequiresIPhoneOS
26 |
27 | NSLocationWhenInUseUsageDescription
28 |
29 | UILaunchStoryboardName
30 | LaunchScreen
31 | UIRequiredDeviceCapabilities
32 |
33 | armv7
34 |
35 | UISupportedInterfaceOrientations
36 |
37 | UIInterfaceOrientationPortrait
38 | UIInterfaceOrientationLandscapeLeft
39 | UIInterfaceOrientationLandscapeRight
40 |
41 | UIViewControllerBasedStatusBarAppearance
42 |
43 | NSLocationWhenInUseUsageDescription
44 |
45 | NSAppTransportSecurity
46 |
47 |
48 | NSAllowsArbitraryLoads
49 |
50 | NSExceptionDomains
51 |
52 | localhost
53 |
54 | NSExceptionAllowsInsecureHTTPLoads
55 |
56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExampleTests/DialogflowExampleTests.m:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2015-present, Facebook, Inc.
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | */
7 |
8 | #import
9 | #import
10 |
11 | #import
12 | #import
13 |
14 | #define TIMEOUT_SECONDS 600
15 | #define TEXT_TO_LOOK_FOR @"Welcome to React Native!"
16 |
17 | @interface DialogflowExampleTests : XCTestCase
18 |
19 | @end
20 |
21 | @implementation DialogflowExampleTests
22 |
23 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL(^)(UIView *view))test
24 | {
25 | if (test(view)) {
26 | return YES;
27 | }
28 | for (UIView *subview in [view subviews]) {
29 | if ([self findSubviewInView:subview matching:test]) {
30 | return YES;
31 | }
32 | }
33 | return NO;
34 | }
35 |
36 | - (void)testRendersWelcomeScreen
37 | {
38 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
39 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
40 | BOOL foundElement = NO;
41 |
42 | __block NSString *redboxError = nil;
43 | RCTSetLogFunction(^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
44 | if (level >= RCTLogLevelError) {
45 | redboxError = message;
46 | }
47 | });
48 |
49 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
50 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
51 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
52 |
53 | foundElement = [self findSubviewInView:vc.view matching:^BOOL(UIView *view) {
54 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
55 | return YES;
56 | }
57 | return NO;
58 | }];
59 | }
60 |
61 | RCTSetLogFunction(RCTDefaultLogFunction);
62 |
63 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
64 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
65 | }
66 |
67 |
68 | @end
69 |
--------------------------------------------------------------------------------
/js/googleAuth/postAsForm.js:
--------------------------------------------------------------------------------
1 | export default async function postAsForm(url, data) {
2 | var response;
3 | try {
4 |
5 | //array that holds the items that get added into the form
6 | var form = [];
7 |
8 | //special handling for object/array data, arrays will use "model" as the container ns
9 | addItemsToForm(form, typeof data == 'object' ? [] : [options.name || 'model'], data);
10 |
11 | //you'll need to await on response.text/blob/json etc
12 | var response = await fetch(url, {
13 | method: 'post',
14 | headers: {
15 | 'Accept': 'application/json, application/xml, text/play, text/html, *.*',
16 | 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
17 | },
18 | body: form.join('&')
19 | });
20 |
21 | //return plain text as-is, don't parse it here
22 | return await response.text();
23 | } catch (err) {
24 | //console.error("Error from server:", err && err.stack || err);
25 | err.response = response;
26 | throw err;
27 | }
28 | }
29 |
30 | function addItemsToForm(form, names, obj) {
31 | if (obj === undefined || obj === "" || obj === null) return addItemToForm(form, names, "");
32 |
33 | if (
34 | typeof obj == "string"
35 | || typeof obj == "number"
36 | || obj === true
37 | || obj === false
38 | ) return addItemToForm(form, names, obj);
39 |
40 | if (obj instanceof Date) return addItemToForm(form, names, obj.toJSON());
41 |
42 | // array or otherwise array-like
43 | if (obj instanceof Array) {
44 | return obj.forEach((v, i) => {
45 | names.push(`[${i}]`);
46 | addItemsToForm(form, names, v);
47 | names.pop();
48 | });
49 | }
50 |
51 | if (typeof obj === "object") {
52 | return Object.keys(obj).forEach((k) => {
53 | names.push(k);
54 | addItemsToForm(form, names, obj[k]);
55 | names.pop();
56 | });
57 | }
58 | }
59 |
60 | function addItemToForm(form, names, value) {
61 | var name = encodeURIComponent(names.join('.').replace(/\.\[/g, '['));
62 | value = encodeURIComponent(value.toString());
63 | form.push(`${name}=${value}`);
64 | }
65 |
--------------------------------------------------------------------------------
/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Disabling obfuscation is useful if you collect stack traces from production crashes
20 | # (unless you are using a system that supports de-obfuscate the stack traces).
21 | -dontobfuscate
22 |
23 | # React Native
24 |
25 | # Keep our interfaces so they can be used by other ProGuard rules.
26 | # See http://sourceforge.net/p/proguard/bugs/466/
27 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip
28 | -keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters
29 | -keep,allowobfuscation @interface com.facebook.common.internal.DoNotStrip
30 |
31 | # Do not strip any method/class that is annotated with @DoNotStrip
32 | -keep @com.facebook.proguard.annotations.DoNotStrip class *
33 | -keep @com.facebook.common.internal.DoNotStrip class *
34 | -keepclassmembers class * {
35 | @com.facebook.proguard.annotations.DoNotStrip *;
36 | @com.facebook.common.internal.DoNotStrip *;
37 | }
38 |
39 | -keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * {
40 | void set*(***);
41 | *** get*();
42 | }
43 |
44 | -keep class * extends com.facebook.react.bridge.JavaScriptModule { *; }
45 | -keep class * extends com.facebook.react.bridge.NativeModule { *; }
46 | -keepclassmembers,includedescriptorclasses class * { native ; }
47 | -keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; }
48 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; }
49 | -keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; }
50 |
51 | -dontwarn com.facebook.react.**
52 |
53 | # TextLayoutBuilder uses a non-public Android constructor within StaticLayout.
54 | # See libs/proxy/src/main/java/com/facebook/fbui/textlayoutbuilder/proxy for details.
55 | -dontwarn android.text.StaticLayout
56 |
57 | # okhttp
58 |
59 | -keepattributes Signature
60 | -keepattributes *Annotation*
61 | -keep class okhttp3.** { *; }
62 | -keep interface okhttp3.** { *; }
63 | -dontwarn okhttp3.**
64 |
65 | # okio
66 |
67 | -keep class sun.misc.Unsafe { *; }
68 | -dontwarn java.nio.file.*
69 | -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
70 | -dontwarn okio.**
71 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import { NativeAppEventEmitter } from 'react-native';
4 | import { Dialogflow } from './js/Dialogflow';
5 | import { Dialogflow_V2 } from './js/Dialogflow_V2';
6 | import Voice from './js/RCTVoice';
7 |
8 | /**
9 | * DIALOGFLOW V1
10 | */
11 | var dialogflow = new Dialogflow();
12 |
13 | dialogflow.setConfiguration = function (accessToken, languageTag) {
14 | dialogflow.accessToken = accessToken;
15 | dialogflow.languageTag = languageTag;
16 | dialogflow.sessionId = dialogflow.sessionId ? dialogflow.sessionId : dialogflow.guid();
17 |
18 | Voice.onSpeechStart = () => (c) => dialogflow.onListeningStarted(c);
19 | Voice.onSpeechEnd = () => (c) => dialogflow.onListeningFinished(c);
20 | }
21 |
22 | dialogflow.startListening = function (onResult, onError) {
23 |
24 | dialogflow.subscription = NativeAppEventEmitter.addListener(
25 | 'onSpeechResults',
26 | (result) => {
27 | if (result.value) {
28 | dialogflow.requestQuery(result.value[0], onResult, onError);
29 | }
30 |
31 | }
32 | );
33 |
34 | Voice.start(dialogflow.languageTag);
35 | }
36 |
37 | dialogflow.finishListening = function () {
38 | Voice.stop();
39 | }
40 |
41 | export default dialogflow;
42 |
43 |
44 | /**
45 | * DIALOGFLOW V2
46 | */
47 | var dialogflow2 = new Dialogflow_V2();
48 |
49 | dialogflow2.setConfiguration = async function (clientEmail, privateKey, languageTag, projectId) {
50 | dialogflow2.accessToken = await dialogflow2.generateAccessToken(clientEmail, privateKey);
51 | dialogflow2.languageTag = languageTag;
52 | dialogflow2.projectId = projectId;
53 | dialogflow2.sessionId = dialogflow2.sessionId ? dialogflow2.sessionId : dialogflow2.guid();
54 |
55 | // set listeners
56 | Voice.onSpeechStart = (c) => {
57 | dialogflow2.speechResult = null;
58 | if (dialogflow2.onListeningStarted) {
59 | dialogflow2.onListeningStarted(c);
60 | }
61 | }
62 |
63 | Voice.onSpeechEnd = (c) => {
64 |
65 | if (dialogflow2.speechResult) {
66 | dialogflow2.requestQuery(dialogflow2.speechResult[0], dialogflow2.onResult, dialogflow2.onError);
67 | }
68 |
69 | if (dialogflow2.onListeningFinished) {
70 | dialogflow2.onListeningFinished(c);
71 | }
72 | }
73 |
74 | Voice.onSpeechVolumeChanged = (c) => {
75 | if (dialogflow2.onAudioLevel) {
76 | dialogflow2.onAudioLevel(c);
77 | }
78 | }
79 |
80 | Voice.onSpeechResults = (result) => {
81 | if (result.value) {
82 | dialogflow2.speechResult = result.value;
83 | }
84 | }
85 | }
86 |
87 | dialogflow2.startListening = function (onResult, onError) {
88 | dialogflow2.onResult = onResult;
89 | dialogflow2.onError = onError;
90 |
91 | Voice.start(dialogflow2.languageTag);
92 | }
93 |
94 | dialogflow2.finishListening = function () {
95 | Voice.stop();
96 | }
97 |
98 | export { dialogflow2 as Dialogflow_V2 };
99 |
100 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample/Base.lproj/LaunchScreen.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
21 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/js/Dialogflow.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import { NativeModules, NativeAppEventEmitter } from 'react-native';
4 | import requestEvent from './ResetContextsRequest';
5 | import ResetContextsRequest from './ResetContextsRequest';
6 | export const DEFAULT_BASE_URL = "https://api.api.ai/v1/";
7 | export const DEFAULT_API_VERSION = "20150910";
8 |
9 | export class Dialogflow {
10 |
11 | onListeningStarted(callback) {
12 | callback();
13 | }
14 |
15 | onListeningCanceled(callback) {
16 | callback();
17 | }
18 |
19 | onListeningFinished(callback) {
20 | callback();
21 | }
22 |
23 | setContexts(contexts) {
24 | this.contexts = contexts;
25 | }
26 |
27 | setPermanentContexts(contexts) {
28 | // set lifespan to 1 if it's not set
29 | contexts.forEach((c, i, a) => {
30 | if (!c.lifespan) {
31 | a[i] = { ...c, lifespan: 1 };
32 | }
33 | });
34 |
35 | this.permanentContexts = contexts;
36 | }
37 |
38 | setEntities(entities) {
39 | this.entities = entities;
40 | }
41 |
42 | onAudioLevel(callback) {
43 |
44 | }
45 |
46 | requestEvent = async (eventName, eventData, onResult, onError) => {
47 |
48 | const data = {
49 | "event": {
50 | "name": eventName,
51 | "data": {
52 | ...eventData
53 | }
54 | },
55 | 'lang': this.languageTag,
56 | "sessionId": this.sessionId
57 | };
58 |
59 | fetch(DEFAULT_BASE_URL + "query?v=" + DEFAULT_API_VERSION, {
60 | method: "POST",
61 | headers: {
62 | 'Content-Type': 'application/json; charset=utf-8',
63 | 'Authorization': 'Bearer ' + this.accessToken,
64 | 'charset': "utf-8"
65 | },
66 | body: JSON.stringify(data)
67 | })
68 | .then(function (response) {
69 | var json = response.json().then(onResult)
70 | })
71 | .catch(onError);
72 | };
73 |
74 | requestQuery = async (query, onResult, onError) => {
75 |
76 | const data = {
77 | "contexts": this.mergeContexts(this.contexts, this.permanentContexts),
78 | "query": query,
79 | 'lang': this.languageTag,
80 | "sessionId": this.sessionId.toString()
81 | };
82 |
83 | this.contexts = null;
84 | this.entities = null;
85 |
86 | fetch(DEFAULT_BASE_URL + "query?v=" + DEFAULT_API_VERSION, {
87 | method: "POST",
88 | headers: {
89 | 'Content-Type': 'application/json; charset=utf-8',
90 | 'Authorization': 'Bearer ' + this.accessToken,
91 | 'charset': "utf-8"
92 | },
93 | body: JSON.stringify(data)
94 | })
95 | .then(function (response) {
96 | var json = response.json().then(onResult)
97 | })
98 | .catch(onError);
99 | };
100 |
101 | mergeContexts(context1, context2) {
102 | if (!context1) {
103 | return context2;
104 | } else if (!context2) {
105 | return context1;
106 | } else {
107 | return [...context1, ...context2];
108 | }
109 | }
110 |
111 | resetContexts(onResult, onError) {
112 | let request = new ResetContextsRequest(this.accessToken, this.sessionId, null);
113 | request.perform().then(res => onResult(res)).catch(err => onError(err));
114 | };
115 |
116 | /**
117 | * generates new random UUID
118 | * @returns {string}
119 | */
120 | guid() {
121 | const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
122 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" +
123 | s4() + "-" + s4() + s4() + s4();
124 | }
125 |
126 |
127 | LANG_CHINESE_CHINA = "zh-CN";
128 | LANG_CHINESE_HONGKONG = "zh-HK";
129 | LANG_CHINESE_TAIWAN = "zh-TW";
130 | LANG_DUTCH = "nl";
131 | LANG_ENGLISH = "en";
132 | LANG_ENGLISH_GB = "en-GB";
133 | LANG_ENGLISH_US = "en-US";
134 | LANG_FRENCH = "fr";
135 | LANG_GERMAN = "de";
136 | LANG_ITALIAN = "it";
137 | LANG_JAPANESE = "ja";
138 | LANG_KOREAN = "ko";
139 | LANG_PORTUGUESE = "pt";
140 | LANG_PORTUGUESE_BRAZIL = "pt-BR";
141 | LANG_RUSSIAN = "ru";
142 | LANG_SPANISH = "es";
143 | LANG_UKRAINIAN = "uk";
144 | }
145 |
146 |
--------------------------------------------------------------------------------
/js/XhrRequest.js:
--------------------------------------------------------------------------------
1 | /**
2 | * quick ts implementation of example from
3 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
4 | * with some minor improvements
5 | * @todo: test (?)
6 | * @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform
7 | */
8 | class XhrRequest {
9 | // Method that performs the ajax request
10 | static ajax(method, url, args = null, headers = null, options = {}) {
11 | // Creating a promise
12 | return new Promise((resolve, reject) => {
13 | // Instantiates the XMLHttpRequest
14 | const client = XhrRequest.createXMLHTTPObject();
15 | let uri = url;
16 | let payload = null;
17 | // Add given payload to get request
18 | if (args && (method === XhrRequest.Method.GET)) {
19 | uri += "?";
20 | let argcount = 0;
21 | for (const key in args) {
22 | if (args.hasOwnProperty(key)) {
23 | if (argcount++) {
24 | uri += "&";
25 | }
26 | uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]);
27 | }
28 | }
29 | }
30 | else if (args) {
31 | if (!headers) {
32 | headers = {};
33 | }
34 | headers["Content-Type"] = "application/json; charset=utf-8";
35 | payload = JSON.stringify(args);
36 | }
37 | for (const key in options) {
38 | if (key in client) {
39 | client[key] = options[key];
40 | }
41 | }
42 | // hack: method[method] is somewhat like .toString for enum Method
43 | // should be made in normal way
44 | client.open(XhrRequest.Method[method], uri, true);
45 | // Add given headers
46 | if (headers) {
47 | for (const key in headers) {
48 | if (headers.hasOwnProperty(key)) {
49 | client.setRequestHeader(key, headers[key]);
50 | }
51 | }
52 | }
53 | payload ? client.send(payload) : client.send();
54 | client.onload = () => {
55 | if (client.status >= 200 && client.status < 300) {
56 | // Performs the function "resolve" when this.status is equal to 2xx
57 | resolve(client);
58 | }
59 | else {
60 | // Performs the function "reject" when this.status is different than 2xx
61 | reject(client);
62 | }
63 | };
64 | client.onerror = () => {
65 | reject(client);
66 | };
67 | });
68 | }
69 | static get(url, payload = null, headers = null, options = {}) {
70 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options);
71 | }
72 | static post(url, payload = null, headers = null, options = {}) {
73 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options);
74 | }
75 | static put(url, payload = null, headers = null, options = {}) {
76 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options);
77 | }
78 | static delete(url, payload = null, headers = null, options = {}) {
79 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options);
80 | }
81 | static createXMLHTTPObject() {
82 | let xmlhttp = null;
83 | for (const i of XhrRequest.XMLHttpFactories) {
84 | try {
85 | xmlhttp = i();
86 | }
87 | catch (e) {
88 | continue;
89 | }
90 | break;
91 | }
92 | return xmlhttp;
93 | }
94 | }
95 | XhrRequest.XMLHttpFactories = [
96 | () => new XMLHttpRequest(),
97 | () => new window["ActiveXObject"]("Msxml2.XMLHTTP"),
98 | () => new window["ActiveXObject"]("Msxml3.XMLHTTP"),
99 | () => new window["ActiveXObject"]("Microsoft.XMLHTTP")
100 | ];
101 | (function (XhrRequest) {
102 | let Method;
103 | (function (Method) {
104 | Method[Method["GET"] = "GET"] = "GET";
105 | Method[Method["POST"] = "POST"] = "POST";
106 | Method[Method["PUT"] = "PUT"] = "PUT";
107 | Method[Method["DELETE"] = "DELETE"] = "DELETE";
108 | })(Method = XhrRequest.Method || (XhrRequest.Method = {}));
109 | })(XhrRequest || (XhrRequest = {}));
110 | export default XhrRequest;
111 |
--------------------------------------------------------------------------------
/example/App.android.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { AppRegistry, Button, StyleSheet, Text, View } from 'react-native';
3 | import Dialogflow, { Dialogflow_V2 } from "react-native-dialogflow";
4 |
5 |
6 | export default class App extends Component {
7 | constructor(props) {
8 | super(props);
9 |
10 | this.state = {
11 | result: "",
12 | listeningState: "not started",
13 | audioLevel: 0,
14 | };
15 |
16 |
17 | Dialogflow.setConfiguration(
18 | "3242_your_token_2344454", Dialogflow.LANG_GERMAN
19 | );
20 |
21 | Dialogflow_V2.setConfiguration(
22 | "reasdfsdfdf@asdf-76866.iam.gserviceaccount.com",
23 | '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADAN...1oqO\n-----END PRIVATE KEY-----\n',
24 | Dialogflow_V2.LANG_GERMAN,
25 | 'testv2-3b5ca'
26 | );
27 |
28 |
29 |
30 | const contexts = [{
31 | "name": "deals",
32 | "lifespan": 1,
33 | "parameters": {
34 | "name": "Sam"
35 | }
36 | }];
37 |
38 |
39 |
40 | Dialogflow.setContexts(contexts);
41 | Dialogflow_V2.setContexts(contexts);
42 |
43 |
44 | const permanentContexts = [{
45 | "name": "config",
46 | "parameters": {
47 | "access_token": "42 yo 42 tiny rick"
48 | }
49 | }];
50 |
51 |
52 | Dialogflow.setPermanentContexts(permanentContexts);
53 | Dialogflow_V2.setPermanentContexts(permanentContexts);
54 |
55 |
56 | const entities = [{
57 | "name": "shop",
58 | "extend": true,
59 | "entries": [
60 | {
61 | "value": "Media Markt",
62 | "synonyms": [
63 | "Media Markt",
64 | ]
65 | }
66 | ]
67 | }];
68 |
69 |
70 | Dialogflow.setEntities(entities);
71 | Dialogflow_V2.setEntities(entities);
72 | }
73 |
74 |
75 | render() {
76 | Dialogflow.requestEvent("WELCOME", null, r => console.log(r), e => console.log(e));
77 | Dialogflow_V2.requestEvent("WELCOME", null, r => console.log(r), e => console.log(e));
78 |
79 |
80 | return (
81 |
82 |
83 |
84 | {"Listening State: " + this.state.listeningState}
85 | {"Audio Level: " + this.state.audioLevel}
86 | {"Result: " + this.state.result}
87 |
88 |
89 |
143 |
144 | );
145 | }
146 | }
147 |
148 | const styles = StyleSheet.create({
149 | container: {
150 | flex: 1,
151 | backgroundColor: '#F5FCFF',
152 | },
153 |
154 | });
155 |
156 | AppRegistry.registerComponent('DialogflowExample', () => App);
--------------------------------------------------------------------------------
/js/RCTVoice.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | import React, {
3 | NativeModules,
4 | NativeEventEmitter,
5 | Platform,
6 | } from 'react-native';
7 |
8 | const { Voice } = NativeModules;
9 |
10 | // NativeEventEmitter is only availabe on React Native platforms, so this conditional is used to avoid import conflicts in the browser/server
11 | const voiceEmitter = Platform.OS !== "web" ? new NativeEventEmitter(Voice) : null;
12 |
13 | class RCTVoice {
14 | constructor() {
15 | this._loaded = false;
16 | this._listeners = null;
17 | this._events = {
18 | 'onSpeechStart': this._onSpeechStart.bind(this),
19 | 'onSpeechRecognized': this._onSpeechRecognized.bind(this),
20 | 'onSpeechEnd': this._onSpeechEnd.bind(this),
21 | 'onSpeechError': this._onSpeechError.bind(this),
22 | 'onSpeechResults': this._onSpeechResults.bind(this),
23 | 'onSpeechPartialResults': this._onSpeechPartialResults.bind(this),
24 | 'onSpeechVolumeChanged': this._onSpeechVolumeChanged.bind(this)
25 | };
26 | }
27 | removeAllListeners() {
28 | Voice.onSpeechStart = null;
29 | Voice.onSpeechRecognized = null;
30 | Voice.onSpeechEnd = null;
31 | Voice.onSpeechError = null;
32 | Voice.onSpeechResults = null;
33 | Voice.onSpeechPartialResults = null;
34 | Voice.onSpeechVolumeChanged = null;
35 | }
36 | destroy() {
37 | if (!this._loaded && !this._listeners) {
38 | return Promise.resolve();
39 | }
40 | return new Promise((resolve, reject) => {
41 | Voice.destroySpeech((error) => {
42 | if (error) {
43 | reject(new Error(error));
44 | } else {
45 | if (this._listeners) {
46 | this._listeners.map((listener, index) => listener.remove());
47 | this._listeners = null;
48 | }
49 | resolve();
50 | }
51 | });
52 | });
53 | }
54 | start(locale, options = {}) {
55 | if (!this._loaded && !this._listeners && voiceEmitter !== null) {
56 | this._listeners = Object.keys(this._events)
57 | .map((key, index) => voiceEmitter.addListener(key, this._events[key]));
58 | }
59 |
60 | return new Promise((resolve, reject) => {
61 | const callback = (error) => {
62 | if (error) {
63 | reject(new Error(error));
64 | } else {
65 | resolve();
66 | }
67 | };
68 | if (Platform.OS === 'android') {
69 | Voice.startSpeech(locale, Object.assign({
70 | EXTRA_LANGUAGE_MODEL: "LANGUAGE_MODEL_FREE_FORM",
71 | EXTRA_MAX_RESULTS: 5,
72 | EXTRA_PARTIAL_RESULTS: true,
73 | REQUEST_PERMISSIONS_AUTO: true,
74 | }, options), callback);
75 | } else {
76 | Voice.startSpeech(locale, callback);
77 | }
78 | });
79 | }
80 | stop() {
81 | if (!this._loaded && !this._listeners) {
82 | return Promise.resolve();
83 | }
84 | return new Promise((resolve, reject) => {
85 | Voice.stopSpeech((error) => {
86 | if (error) {
87 | reject(new Error(error));
88 | } else {
89 | resolve();
90 | }
91 | });
92 | });
93 | }
94 | cancel() {
95 | if (!this._loaded && !this._listeners) {
96 | return Promise.resolve();
97 | }
98 | return new Promise((resolve, reject) => {
99 | Voice.cancelSpeech((error) => {
100 | if (error) {
101 | reject(new Error(error));
102 | } else {
103 | resolve();
104 | }
105 | });
106 | });
107 | }
108 | isAvailable() {
109 | return new Promise((resolve, reject) => {
110 | Voice.isSpeechAvailable((isAvailable, error) => {
111 | if (error) {
112 | reject(new Error(error));
113 | } else {
114 | resolve(isAvailable);
115 | }
116 | });
117 | });
118 | }
119 | isRecognizing() {
120 | return new Promise((resolve, reject) => {
121 | Voice.isRecognizing(isRecognizing => resolve(isRecognizing));
122 | });
123 | }
124 | _onSpeechStart(e) {
125 | if (this.onSpeechStart) {
126 | this.onSpeechStart(e);
127 | }
128 | }
129 | _onSpeechRecognized(e) {
130 | if (this.onSpeechRecognized) {
131 | this.onSpeechRecognized(e);
132 | }
133 | }
134 | _onSpeechEnd(e) {
135 | if (this.onSpeechEnd) {
136 | this.onSpeechEnd(e);
137 | }
138 | }
139 | _onSpeechError(e) {
140 | if (this.onSpeechError) {
141 | this.onSpeechError(e);
142 | }
143 | }
144 | _onSpeechResults(e) {
145 | if (this.onSpeechResults) {
146 | this.onSpeechResults(e);
147 | }
148 | }
149 | _onSpeechPartialResults(e) {
150 | if (this.onSpeechPartialResults) {
151 | this.onSpeechPartialResults(e);
152 | }
153 | }
154 | _onSpeechVolumeChanged(e) {
155 | if (this.onSpeechVolumeChanged) {
156 | this.onSpeechVolumeChanged(e);
157 | }
158 | }
159 | }
160 |
161 | export default new RCTVoice();
--------------------------------------------------------------------------------
/example/ios/DialogflowExample.xcodeproj/xcshareddata/xcschemes/DialogflowExample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
29 |
35 |
36 |
37 |
43 |
49 |
50 |
51 |
52 |
53 |
58 |
59 |
61 |
67 |
68 |
69 |
70 |
71 |
77 |
78 |
79 |
80 |
81 |
82 |
92 |
94 |
100 |
101 |
102 |
103 |
104 |
105 |
111 |
113 |
119 |
120 |
121 |
122 |
124 |
125 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/example/ios/DialogflowExample.xcodeproj/xcshareddata/xcschemes/DialogflowExample-tvOS.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
29 |
35 |
36 |
37 |
43 |
49 |
50 |
51 |
52 |
53 |
58 |
59 |
61 |
67 |
68 |
69 |
70 |
71 |
77 |
78 |
79 |
80 |
81 |
82 |
92 |
94 |
100 |
101 |
102 |
103 |
104 |
105 |
111 |
113 |
119 |
120 |
121 |
122 |
124 |
125 |
128 |
129 |
130 |
--------------------------------------------------------------------------------
/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/js/Dialogflow_V2.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | import googleAuth from './googleAuth/GoogleAuth';
4 | import ResetContextsRequest from './ResetContextsRequest';
5 | export const DEFAULT_BASE_URL = "https://dialogflow.googleapis.com/v2beta1/projects/";
6 |
7 | export class Dialogflow_V2 {
8 |
9 | onListeningStarted(callback) {
10 | this.onListeningStarted = callback;
11 | }
12 |
13 | onListeningCanceled(callback) {
14 | this.onListeningCanceled = callback;
15 | }
16 |
17 | onListeningFinished(callback) {
18 | this.onListeningFinished = callback;
19 | }
20 |
21 | setContexts(contexts) {
22 | var array = contexts;
23 |
24 | array.forEach((c, i, a) => {
25 | a[i] = this.normalizeContext(c);
26 | })
27 |
28 | this.contexts = array;
29 | }
30 |
31 | setPermanentContexts(contexts) {
32 | // set lifespan to 1 if it's not set
33 | contexts.forEach((c, i, a) => {
34 | a[i] = this.normalizeContext(c);
35 |
36 | if (!c.lifespanCount) {
37 | a[i] = { ...c, lifespanCount: 1 };
38 | }
39 | });
40 |
41 | this.permanentContexts = contexts;
42 | }
43 |
44 | normalizeContext(context) {
45 | // rename property lifespan to lifespanCount
46 | if (context.lifespan) {
47 | context.lifespanCount = context.lifespan;
48 | delete context.lifespan;
49 | }
50 |
51 | // add context name path: projects//agent/sessions//contexts/
52 | // https://dialogflow.com/docs/reference/api-v2/rest/v2beta1/projects.agent.sessions.contexts#Context
53 | if (!context.name.startsWith("projects/")) {
54 | context.name = "projects/" + this.projectId + "/agent/sessions/" + this.sessionId + "/contexts/" + context.name;
55 | }
56 |
57 | return context;
58 | }
59 |
60 | /*
61 | setEntities(entities) {
62 | this.entities = entities;
63 | }
64 | */
65 |
66 | onAudioLevel(callback) {
67 |
68 | }
69 |
70 | requestEvent = async (eventName, eventParameters, onResult, onError) => {
71 |
72 | const data = {
73 | "queryParams": {
74 | "contexts": this.mergeContexts(this.contexts, this.permanentContexts),
75 | "sessionEntityTypes": []
76 | },
77 | "queryInput": {
78 | "event": {
79 | "name": eventName,
80 | "parameters": eventParameters,
81 | "languageCode": this.languageTag,
82 | },
83 | }
84 | }
85 |
86 | this.contexts = null;
87 | this.entities = null;
88 |
89 | fetch(DEFAULT_BASE_URL + this.projectId + "/agent/sessions/" + this.sessionId + ":detectIntent", {
90 | method: "POST",
91 | headers: {
92 | 'Content-Type': 'application/json; charset=utf-8',
93 | 'Authorization': 'Bearer ' + this.accessToken,
94 | 'charset': "utf-8"
95 | },
96 | body: JSON.stringify(data)
97 | })
98 | .then(function (response) {
99 | var json = response.json().then(onResult)
100 | })
101 | .catch(onError);
102 | };
103 |
104 |
105 | requestQuery = async (query, onResult, onError) => {
106 |
107 | const data = {
108 | "queryParams": {
109 | "contexts": this.mergeContexts(this.contexts, this.permanentContexts),
110 | "sessionEntityTypes": []
111 | },
112 | "queryInput": {
113 | "text": {
114 | "text": query,
115 | "languageCode": this.languageTag,
116 | },
117 | }
118 | }
119 |
120 | this.contexts = null;
121 | this.entities = null;
122 |
123 | fetch(DEFAULT_BASE_URL + this.projectId + "/agent/sessions/" + this.sessionId + ":detectIntent", {
124 | method: "POST",
125 | headers: {
126 | 'Content-Type': 'application/json; charset=utf-8',
127 | 'Authorization': 'Bearer ' + this.accessToken,
128 | 'charset': "utf-8"
129 | },
130 | body: JSON.stringify(data)
131 | })
132 | .then(function (response) {
133 | var json = response.json().then(onResult)
134 | })
135 | .catch(onError);
136 | };
137 |
138 |
139 | mergeContexts(context1, context2) {
140 | if (!context1) {
141 | return context2;
142 | } else if (!context2) {
143 | return context1;
144 | } else {
145 | return [...context1, ...context2];
146 | }
147 | }
148 |
149 | resetContexts(onResult, onError) {
150 | let request = new ResetContextsRequest(this.client.getAccessToken(), this.client.getSessionId(), null);
151 | request.perform().then(res => onResult(res)).catch(err => onError(err));
152 | };
153 |
154 | /**
155 | * generates new random UUID
156 | * @returns {string}
157 | */
158 | guid() {
159 | const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
160 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" +
161 | s4() + "-" + s4() + s4() + s4();
162 | }
163 |
164 | async generateAccessToken(clientEmail, privateKey) {
165 | let token;
166 | try {
167 | token = await googleAuth(clientEmail, privateKey, ['https://www.googleapis.com/auth/cloud-platform']);
168 | } catch (e) {
169 | console.error("react-native-dialogflow: Authentication Error: " + e);
170 | throw new Error("react-native-dialogflow: Authentication Error: " + e);
171 | } finally {
172 | return token;
173 | }
174 | }
175 |
176 |
177 | LANG_CHINESE_CHINA = "zh-CN";
178 | LANG_CHINESE_HONGKONG = "zh-HK";
179 | LANG_CHINESE_TAIWAN = "zh-TW";
180 | LANG_DUTCH = "nl";
181 | LANG_ENGLISH = "en";
182 | LANG_ENGLISH_GB = "en-GB";
183 | LANG_ENGLISH_US = "en-US";
184 | LANG_FRENCH = "fr";
185 | LANG_GERMAN = "de";
186 | LANG_ITALIAN = "it";
187 | LANG_JAPANESE = "ja";
188 | LANG_KOREAN = "ko";
189 | LANG_PORTUGUESE = "pt";
190 | LANG_PORTUGUESE_BRAZIL = "pt-BR";
191 | LANG_RUSSIAN = "ru";
192 | LANG_SPANISH = "es";
193 | LANG_UKRAINIAN = "uk";
194 | }
195 |
196 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | import com.android.build.OutputFile
4 |
5 | /**
6 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
7 | * and bundleReleaseJsAndAssets).
8 | * These basically call `react-native bundle` with the correct arguments during the Android build
9 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
10 | * bundle directly from the development server. Below you can see all the possible configurations
11 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
12 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
13 | *
14 | * project.ext.react = [
15 | * // the name of the generated asset file containing your JS bundle
16 | * bundleAssetName: "index.android.bundle",
17 | *
18 | * // the entry file for bundle generation
19 | * entryFile: "index.android.js",
20 | *
21 | * // whether to bundle JS and assets in debug mode
22 | * bundleInDebug: false,
23 | *
24 | * // whether to bundle JS and assets in release mode
25 | * bundleInRelease: true,
26 | *
27 | * // whether to bundle JS and assets in another build variant (if configured).
28 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
29 | * // The configuration property can be in the following formats
30 | * // 'bundleIn${productFlavor}${buildType}'
31 | * // 'bundleIn${buildType}'
32 | * // bundleInFreeDebug: true,
33 | * // bundleInPaidRelease: true,
34 | * // bundleInBeta: true,
35 | *
36 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
37 | * // for example: to disable dev mode in the staging build type (if configured)
38 | * devDisabledInStaging: true,
39 | * // The configuration property can be in the following formats
40 | * // 'devDisabledIn${productFlavor}${buildType}'
41 | * // 'devDisabledIn${buildType}'
42 | *
43 | * // the root of your project, i.e. where "package.json" lives
44 | * root: "../../",
45 | *
46 | * // where to put the JS bundle asset in debug mode
47 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
48 | *
49 | * // where to put the JS bundle asset in release mode
50 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
51 | *
52 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
53 | * // require('./image.png')), in debug mode
54 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
55 | *
56 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
57 | * // require('./image.png')), in release mode
58 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
59 | *
60 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
61 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
62 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
63 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
64 | * // for example, you might want to remove it from here.
65 | * inputExcludes: ["android/**", "ios/**"],
66 | *
67 | * // override which node gets called and with what additional arguments
68 | * nodeExecutableAndArgs: ["node"],
69 | *
70 | * // supply additional arguments to the packager
71 | * extraPackagerArgs: []
72 | * ]
73 | */
74 |
75 | project.ext.react = [
76 | entryFile: "index.js"
77 | ]
78 |
79 | apply from: "../../node_modules/react-native/react.gradle"
80 |
81 | /**
82 | * Set this to true to create two separate APKs instead of one:
83 | * - An APK that only works on ARM devices
84 | * - An APK that only works on x86 devices
85 | * The advantage is the size of the APK is reduced by about 4MB.
86 | * Upload all the APKs to the Play Store and people will download
87 | * the correct one based on the CPU architecture of their device.
88 | */
89 | def enableSeparateBuildPerCPUArchitecture = false
90 |
91 | /**
92 | * Run Proguard to shrink the Java bytecode in release builds.
93 | */
94 | def enableProguardInReleaseBuilds = false
95 |
96 | android {
97 | compileSdkVersion 23
98 | buildToolsVersion "23.0.1"
99 |
100 | defaultConfig {
101 | applicationId "com.dialogflowexample"
102 | minSdkVersion 16
103 | targetSdkVersion 22
104 | versionCode 1
105 | versionName "1.0"
106 | ndk {
107 | abiFilters "armeabi-v7a", "x86"
108 | }
109 | }
110 | splits {
111 | abi {
112 | reset()
113 | enable enableSeparateBuildPerCPUArchitecture
114 | universalApk false // If true, also generate a universal APK
115 | include "armeabi-v7a", "x86"
116 | }
117 | }
118 | buildTypes {
119 | release {
120 | minifyEnabled enableProguardInReleaseBuilds
121 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
122 | }
123 | }
124 | // applicationVariants are e.g. debug, release
125 | applicationVariants.all { variant ->
126 | variant.outputs.each { output ->
127 | // For each separate APK per architecture, set a unique version code as described here:
128 | // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
129 | def versionCodes = ["armeabi-v7a":1, "x86":2]
130 | def abi = output.getFilter(OutputFile.ABI)
131 | if (abi != null) { // null for the universal-debug, universal-release variants
132 | output.versionCodeOverride =
133 | versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
134 | }
135 | }
136 | }
137 | }
138 |
139 | dependencies {
140 | compile project(':react-native-dialogflow')
141 | compile project(':react-native-voice')
142 | compile fileTree(dir: "libs", include: ["*.jar"])
143 | compile "com.android.support:appcompat-v7:23.0.1"
144 | compile "com.facebook.react:react-native:+" // From node_modules
145 | }
146 |
147 | // Run this once to be able to run the application with BUCK
148 | // puts all compile dependencies into folder libs for BUCK to use
149 | task copyDownloadableDepsToLibs(type: Copy) {
150 | from configurations.compile
151 | into 'libs'
152 | }
153 |
--------------------------------------------------------------------------------
/example/App.ios.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { AppRegistry, Button, StyleSheet, Text, View } from 'react-native';
3 | import Dialogflow, { Dialogflow_V2 } from "react-native-dialogflow";
4 |
5 |
6 | export default class App extends Component {
7 | constructor(props) {
8 | super(props);
9 |
10 | this.state = {
11 | result: "",
12 | listeningState: "not started",
13 | audioLevel: 0,
14 | buttonText1: "Start Listening",
15 | buttonText2: "Start Listening V2",
16 | listening1: false,
17 | listening2: false
18 | };
19 |
20 |
21 | Dialogflow.setConfiguration(
22 | "3242_your_token_2344454", Dialogflow.LANG_GERMAN
23 | );
24 |
25 | Dialogflow_V2.setConfiguration(
26 | "react-access@laura-63528.iam.gserviceaccount.com",
27 | '-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDTQw/Lpj+nPiBQ\ncpecBK1SRSfUTqj5xnhbXhhI8q3NVrxkzBzkZivEBT5UlbtPFf1h0aaRM5twRz5J\nI8n6VlitXgZTpS06ls8z2nXc/2u9JbZIjY+ciZJN01FfATk8Mamply1mzN1XTCX8\nydDjYhqLfELwgZpI8cfWM+tiPK4tPcMCRF11u/rd8TDEy2Kf8W7lUhygv77gshu8\ndmCE1nS0ucA0H0Rhou4s7l485SWuqe4Dwar6Q6v7K4GqgnLcx2nwiQtuuefUXzzw\nWbt/5ExBjpGyDylZX0rUw80FfDSTrlWnb6B/wsf6J4FOt/yW+Zz4QuJF+KbYbG89\nVlNBYD7pAgMBAAECggEAYA6Zc4DrZ1k1qy53Ze6wefxMwFlltnA6EF0n0J9bTEa4\nUWKHbohQNQgnT6FnMe3vMFd5k4LyFaqnFO1rbGJvXqCmYsjzWDTzEIIv3iTa8X1g\ntPt8xXG97pn7YSW2xvpTyPMepyPWLlfG2/pNet4D8NE2xJFBPBKHSQuBZsDtd07O\nd2Bh06gP8+KhsQ7gjIVvBei3DoMAXCrw9RXfY2GdnNJtLgSd35FShpxP8Mn2+KSx\nHwJZVewkEH9YFhvqLb7GWV9330FJ5oqlq5HZiKGYpkXfYA01nD/s7GcRqYUb3ddR\noXlD7JsJZ8E2iowmG7Q865WKPH+ysBJ92d0aRsWgIwKBgQD2Bp4F23/x6AR4vdGY\nfn+5dGBG40zXFB534ydR1mgVrySYUQUf35ri3RDPObTjBQNOz1b+zOnB4AoimewN\nNQEUjiTt94sn2EZg3aOK86P5tILdKxAJxBlXAvVCUz+RpFotDqy7bckcOiSszSFq\nLjvC5qlj2z/DhpvHluESjHoYBwKBgQDb06WcNubPnJPCDSXW1VczYxtUdc2rvfX1\nhgvDlKUlzlii4Hqz1tYOcsJkskmcPZHm/5G2KXJhwaa1Mu0EnkTnitkLq+4hkUex\nHs7EiG1YficpLm5Mb++xUEM7t9PJwzME1pvsJWMWTVqkDghlw0Z4P5nC/X32+Ts5\nGh2AsZnVjwKBgDM9A5Iyub3W1X+UAN/ikJU+MILy+eDdVs8fJuQ7ZCgH9vYmAYw2\n1Jok8khGO28Ab0Ttl6+vW4u+Lj4wkmHZxSTTycspv/iHaXjpEBNzVJY/yvVm74sp\nJSHjAtNSZS3e7czufnj2j2jqjxLSEgB8KoQX5/VdBzWghjcWLD/hs9fnAoGBAMl/\nyplTteRuSP6iIKI5MlJXMRENXrZjTNZ+xb/EPFFYQOUj0TWR4uqhhNDaoCDISzor\n37vTaBZ1dMM5aAtIrC51lphdQ82fJtETRULfLyPjly/ncJE+Nb8ZrFdMHKUf+V8g\n/RHL/3TM+R3SAx6Mjcbhvab/x3wgXonsB0kVAsa/AoGAdmVqyBsVz4V0OBGMW/xt\nIpcpktwDzvDQHHE0trZJaF9CQnxUQzM6D/RqC6rDjMORAMaApx3jcOAJITwP9xXc\nS5r104LVYw0Whj+9JBPfmzTXdd2BzoCXDFQoeYwLtS69LoHSNjrQ5+nOU3cGquin\n40y3aAFL6WlPXIlE9M/7M2E=\n-----END PRIVATE KEY-----\n',
28 | Dialogflow_V2.LANG_GERMAN,
29 | 'laura-63528'
30 | );
31 |
32 |
33 |
34 | const contexts = [{
35 | "name": "deals",
36 | "lifespan": 1,
37 | "parameters": {
38 | "name": "Sam"
39 | }
40 | }];
41 |
42 |
43 |
44 | Dialogflow.setContexts(contexts);
45 | Dialogflow_V2.setContexts(contexts);
46 |
47 |
48 | const permanentContexts = [{
49 | "name": "config",
50 | "parameters": {
51 | "access_token": "42 yo 42 tiny rick"
52 | }
53 | }];
54 |
55 |
56 | Dialogflow.setPermanentContexts(permanentContexts);
57 | Dialogflow_V2.setPermanentContexts(permanentContexts);
58 |
59 |
60 | const entities = [{
61 | "name": "shop",
62 | "extend": true,
63 | "entries": [
64 | {
65 | "value": "Media Markt",
66 | "synonyms": [
67 | "Media Markt",
68 | ]
69 | }
70 | ]
71 | }];
72 |
73 |
74 | Dialogflow.setEntities(entities);
75 | // Dialogflow_V2.setEntities(entities);
76 | }
77 |
78 |
79 | render() {
80 | Dialogflow.requestEvent("WELCOME", null, r => console.log(r), e => console.log(e));
81 | Dialogflow_V2.requestEvent("WELCOME", null, r => console.log(r), e => console.log(e));
82 |
83 |
84 | return (
85 |
86 |
87 |
88 | {"Listening State: " + this.state.listeningState}
89 | {"Audio Level: " + this.state.audioLevel}
90 | {"Result: " + this.state.result}
91 |
92 |
93 | {
94 |
95 |
96 | if (this.state.listening1) {
97 | Dialogflow.finishListening();
98 | this.setState({ buttonText1: "Start Listening", listening1: false })
99 | } else {
100 | Dialogflow.startListening(result => {
101 | this.setState({ result: JSON.stringify(result) });
102 | }, error => {
103 | this.setState({ result: JSON.stringify(error) });
104 | });
105 | this.setState({ buttonText1: "Stop Listening", listening1: true })
106 | }
107 |
108 | // V1
109 | Dialogflow.onListeningStarted(() => {
110 | this.setState({ listeningState: "started" });
111 | });
112 |
113 | Dialogflow.onListeningCanceled(() => {
114 | this.setState({ listeningState: "canceled" });
115 | });
116 |
117 | Dialogflow.onListeningFinished(() => {
118 | this.setState({ listeningState: "finished" });
119 | });
120 |
121 | }} />
122 |
123 | {
124 | // V2
125 | if (this.state.listening2) {
126 | Dialogflow_V2.finishListening();
127 | this.setState({ buttonText2: "Start Listening V2", listening2: false })
128 | } else {
129 | Dialogflow_V2.startListening(result => {
130 | this.setState({ result: JSON.stringify(result) });
131 | }, error => {
132 | this.setState({ result: JSON.stringify(error) });
133 | });
134 | this.setState({ buttonText2: "Stop Listening V2", listening2: true })
135 | }
136 |
137 | Dialogflow_V2.onListeningStarted(() => {
138 | this.setState({ listeningState: "started" });
139 | });
140 |
141 | Dialogflow_V2.onListeningCanceled(() => {
142 | this.setState({ listeningState: "canceled" });
143 | });
144 |
145 | Dialogflow_V2.onListeningFinished(() => {
146 | this.setState({ listeningState: "finished" });
147 | });
148 |
149 | }} />
150 |
151 |
152 | );
153 | }
154 | }
155 |
156 | const styles = StyleSheet.create({
157 | container: {
158 | flex: 1,
159 | paddingTop: 20,
160 | backgroundColor: '#F5FCFF',
161 | },
162 |
163 | });
164 |
165 | AppRegistry.registerComponent('ApiAiExample', () => App);
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-native-dialogflow (react-native-api-ai)
2 |
3 | [](https://www.npmjs.com/package/react-native-dialogflow)
4 | [](https://www.npmjs.com/package/react-native-dialogflow)
5 | [](https://www.npmjs.com/package/react-native-dialogflow)
6 |
7 |
8 | A React-Native Bridge for the Google Dialogflow AI SDK.
9 |
10 |
11 |
12 | Support for iOS 10+ and Android!
13 |
14 | [Dialogflow](https://dialogflow.com/) is a powerful tool for building delightful and natural conversational experiences. You can build chat and speech bots and may intergrate it in a lot of platform like twitter, facebook, slack, or alexa.
15 |
16 | ## Install
17 |
18 | This package depends on react-native-voice, follow their readme to setup it.
19 |
20 | Add react-native-dialogflow and link it:
21 | ```
22 | npm install --save react-native-dialogflow react-native-voice
23 |
24 | react-native link react-native-dialogflow
25 | react-native link react-native-voice
26 |
27 | ```
28 |
29 | ### iOS: IMPORTANT xCode plist settings
30 |
31 | Also, you need open the React Native xCode project and add two new keys into `Info.plist`
32 | Just right click on `Info.plist` -> `Open As` -> `Source Code` and paste these strings somewhere into root `` tag
33 |
34 | ```xml
35 | NSSpeechRecognitionUsageDescription
36 | Your usage description here
37 | NSMicrophoneUsageDescription
38 | Your usage description here
39 | ```
40 |
41 | Application will crash if you don't do this.
42 |
43 | ## Usage
44 | Import Dialogflow:
45 | ```javascript
46 | import Dialogflow from "react-native-dialogflow";
47 | ```
48 | or for V2
49 | ```javascript
50 | import { Dialogflow_V2 } from "react-native-dialogflow"
51 | ```
52 |
53 | ### Configuration
54 | Set the `accessToken` and the language in your constructor:
55 | ```javascript
56 | constructor(props) {
57 | super(props);
58 |
59 | Dialogflow.setConfiguration(
60 | "4xxxxxxxe90xxxxxxxxc372", Dialogflow.LANG_GERMAN
61 | );
62 | }
63 |
64 | ```
65 |
66 | For V2 you can set the `client_email` and `private_key` of the credential json [auth setup](https://dialogflow.com/docs/reference/v2-auth-setup). In addition you have to set your projectId:
67 | ```javascript
68 | constructor(props) {
69 | super(props);
70 |
71 | Dialogflow_V2.setConfiguration(
72 | "your-dialogflow-project@asdf-76866.iam.gserviceaccount.com",
73 | '-----BEGIN PRIVATE KEY-----\nMIIEvgIBADAN...1oqO\n-----END PRIVATE KEY-----\n',
74 | Dialogflow_V2.LANG_GERMAN,
75 | 'testv2-3b5ca'
76 | );
77 | }
78 |
79 | ```
80 |
81 |
82 | ### Listening
83 | Start listening with integrated speech recognition:
84 | ```javascript
85 | {
86 | Dialogflow.startListening(result=>{
87 | console.log(result);
88 | }, error=>{
89 | console.log(error);
90 | });
91 | }}
92 | />
93 | ```
94 | In iOS only you have to call `finishListening()`. Android detects the end of your speech automatically. That's the reason why we didn't implement the finish method in Android.
95 | ```javascript
96 | // only for iOS
97 | Dialogflow.finishListening();
98 | // after this call your callbacks from the startListening will be executed.
99 | ```
100 |
101 | ### Text Request
102 | For using your own speech recognition:
103 | ```javascript
104 | {
105 | Dialogflow.requestQuery("Some text for your Dialogflow agent", result=>console.log(result), error=>console.log(error));
106 | }}
107 | />
108 | ```
109 |
110 | ### Request an Event
111 | For sending an [event](https://api.ai/docs/events) to Dialogflow _(Contexts and Entities have no effect!)_:
112 | ```javascript
113 | Dialogflow.requestEvent(
114 | "WELCOME",
115 | {param1: "yo mr. white!"},
116 | result=>{console.log(result);},
117 | error=>{console.log(error);}
118 | );
119 | ```
120 |
121 |
122 | ### Contexts
123 | Set [contexts](https://api.ai/docs/reference/agent/contexts) (will take affect on next startListening or queryRequest):
124 | ```javascript
125 | const contexts = [{
126 | name: "deals",
127 | lifespan: 1,
128 | parameters: {
129 | Shop: "Rewe"
130 | }
131 | }];
132 |
133 | Dialogflow.setContexts(contexts);
134 | ```
135 |
136 | Reset all (non-permantent) contexts for current session:
137 | ```javascript
138 | Dialogflow.resetContexts(result=>{
139 | console.log(result);
140 | }, error=>{
141 | console.log(error);
142 | });
143 | ```
144 |
145 | Set permanent contexts, which will be set automatically before every request. This is useful for e.g. access tokens in webhooks:
146 | ```javascript
147 | const permanentContexts = [{
148 | name: "Auth",
149 | // lifespan 1 is set automatically, but it's overrideable
150 | parameters: {
151 | AccessToken: "1234yo1234"
152 | }
153 | }];
154 |
155 | Dialogflow.setPermanentContexts(permanentContexts);
156 | ```
157 |
158 | ### Entities
159 | Set [UserEntities](https://api.ai/docs/reference/agent/userentities) (will take affect on next startListening or queryRequest):
160 | ```javascript
161 | const entities = [{
162 | "name":"shop",
163 | "extend":true,
164 | "entries":[
165 | {
166 | "value":"Media Markt",
167 | "synonyms":["Media Markt"]
168 | }
169 | ]
170 | }];
171 |
172 | Dialogflow.setEntities(entities);
173 | ```
174 |
175 |
176 | ### Listener for Android
177 | Only in Android we have four additional methods: `onListeningStarted`, `onListeningCanceled`, `onListeningFinished` and `onAudioLevel`. In iOS they will be never called:
178 | ```javascript
179 | {
180 |
181 | Dialogflow.onListeningStarted(()=>{
182 | console.log("listening started");
183 | });
184 |
185 | Dialogflow.onListeningCanceled(()=>{
186 | console.log("listening canceled");
187 | });
188 |
189 | Dialogflow.onListeningFinished(()=>{
190 | console.log("listening finished");
191 | });
192 |
193 | Dialogflow.onAudioLevel(level=>{
194 | console.log(level);
195 | });
196 |
197 |
198 | Dialogflow.startListening(result=>{
199 | console.log(result);
200 | }, error=>{
201 | console.log(error);
202 | });
203 | }}
204 | />
205 | ```
206 | Note: Make sure you are setting the callbacks before startListening every single time again. Don't set the callbacks in e.g. constructor or componentsDidMount if you are executing startListening more than one times.
207 |
208 |
209 | ## Supported Languages
210 | Set the language in your configuration:
211 | ```javascript
212 | Dialogflow.setConfiguration("4xxxxxxxe90xxxxxxxxc372", Dialogflow.LANG_GERMAN);
213 | ```
214 | * LANG_CHINESE_CHINA
215 | * LANG_CHINESE_HONGKONG
216 | * LANG_CHINESE_TAIWAN
217 | * LANG_DUTCH
218 | * LANG_ENGLISH
219 | * LANG_ENGLISH_GB
220 | * LANG_ENGLISH_US
221 | * LANG_FRENCH
222 | * LANG_GERMAN
223 | * LANG_ITALIAN
224 | * LANG_JAPANESE
225 | * LANG_KOREAN
226 | * LANG_PORTUGUESE
227 | * LANG_PORTUGUESE_BRAZIL
228 | * LANG_RUSSIAN
229 | * LANG_SPANISH
230 | * LANG_UKRAINIAN
231 |
232 | ## Methods
233 | | name | platform | param1 | param2 | param3 | param4 |
234 | | --------------------- | -------- | --------- | --------- | --------- | --------- |
235 | | `setConfiguration` (V1) | both | accessToken: String | languageTag: String |
236 | | `setConfiguration` (V2) | both | client_email: String | private_key: String | languageTag: String | projectId: String |
237 | | `startListening` | both | resultCallback: (result: object)=>{} | errorCallback: (error: object)=>{} | |
238 | | `finishListening` | ios | | | |
239 | | `requestQuery` | both | query: String | resultCallback: (result: object)=>{} | errorCallback: (error: object)=>{} |
240 | | `requestEvent` | both | eventName: String | eventData: Object | resultCallback: (result: object)=>{} | errorCallback: (error: object)=>{} |
241 | | `onListeningStarted` | both | callback: ()=>{} | | |
242 | | `onListeningCanceled` | none | callback: ()=>{} || |
243 | | `onListeningFinished` | both | callback: ()=>{} | | |
244 | | `onAudioLevel` | android | callback: (level: number)=>{} || |
245 | | `setContexts` | both | array || |
246 | | `resetContexts` | both | resultCallback: (result: object)=>{} | errorCallback: (error: object)=>{} | |
247 | | `setPermanentContexts`| both | array || |
248 | | `setEntities` (V1 only)| both | array || |
249 |
250 |
251 | ## Blogpost
252 |
253 | ### Deutsch
254 | [Sprachsteuerung mit Api.ai in einer React-Native App](https://innfactory.de/de/blog/34-software-engineering/65-sprachsteuerung-mit-api-ai-in-einer-react-native-app)
255 | ### English
256 |
257 | ## Contributors
258 |
259 | * [Anton Spöck](https://github.com/spoeck)
260 | * [Tobias Jonas](https://github.com/jona7o)
261 | * [Maximilian Grassl](https://github.com/innGrassl)
262 |
263 | Powered by [innFactory](https://innfactory.de/)
264 |
--------------------------------------------------------------------------------
/ios/ApiAi.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 46;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | DBCB5CDE1B46E62D005CB38B /* ApiAi.m in Sources */ = {isa = PBXBuildFile; fileRef = DBCB5CDD1B46E62D005CB38B /* ApiAi.m */; };
11 | /* End PBXBuildFile section */
12 |
13 | /* Begin PBXCopyFilesBuildPhase section */
14 | CDD7BF761B2D5125006FDA75 /* CopyFiles */ = {
15 | isa = PBXCopyFilesBuildPhase;
16 | buildActionMask = 2147483647;
17 | dstPath = "include/$(PRODUCT_NAME)";
18 | dstSubfolderSpec = 16;
19 | files = (
20 | );
21 | runOnlyForDeploymentPostprocessing = 0;
22 | };
23 | /* End PBXCopyFilesBuildPhase section */
24 |
25 | /* Begin PBXFileReference section */
26 | CDD7BF781B2D5125006FDA75 /* libApiAi.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libApiAi.a; sourceTree = BUILT_PRODUCTS_DIR; };
27 | DBCB5CDC1B46E62D005CB38B /* ApiAi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ApiAi.h; sourceTree = ""; };
28 | DBCB5CDD1B46E62D005CB38B /* ApiAi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ApiAi.m; sourceTree = ""; };
29 | /* End PBXFileReference section */
30 |
31 | /* Begin PBXFrameworksBuildPhase section */
32 | CDD7BF751B2D5125006FDA75 /* Frameworks */ = {
33 | isa = PBXFrameworksBuildPhase;
34 | buildActionMask = 2147483647;
35 | files = (
36 | );
37 | runOnlyForDeploymentPostprocessing = 0;
38 | };
39 | /* End PBXFrameworksBuildPhase section */
40 |
41 | /* Begin PBXGroup section */
42 | 56489C590F2D4EC58151DA97 /* Libraries */ = {
43 | isa = PBXGroup;
44 | children = (
45 | );
46 | name = Libraries;
47 | sourceTree = "";
48 | };
49 | CDD7BF6F1B2D5125006FDA75 = {
50 | isa = PBXGroup;
51 | children = (
52 | DBCB5CDB1B46E62D005CB38B /* ApiAi */,
53 | CDD7BF791B2D5125006FDA75 /* Products */,
54 | 56489C590F2D4EC58151DA97 /* Libraries */,
55 | FD3552E620D14EF000C53894 /* Recovered References */,
56 | );
57 | sourceTree = "";
58 | };
59 | CDD7BF791B2D5125006FDA75 /* Products */ = {
60 | isa = PBXGroup;
61 | children = (
62 | CDD7BF781B2D5125006FDA75 /* libApiAi.a */,
63 | );
64 | name = Products;
65 | sourceTree = "";
66 | };
67 | DBCB5CDB1B46E62D005CB38B /* ApiAi */ = {
68 | isa = PBXGroup;
69 | children = (
70 | DBCB5CDC1B46E62D005CB38B /* ApiAi.h */,
71 | DBCB5CDD1B46E62D005CB38B /* ApiAi.m */,
72 | );
73 | path = ApiAi;
74 | sourceTree = "";
75 | };
76 | FD3552E620D14EF000C53894 /* Recovered References */ = {
77 | isa = PBXGroup;
78 | children = (
79 | );
80 | name = "Recovered References";
81 | sourceTree = "";
82 | };
83 | /* End PBXGroup section */
84 |
85 | /* Begin PBXNativeTarget section */
86 | CDD7BF771B2D5125006FDA75 /* ApiAi */ = {
87 | isa = PBXNativeTarget;
88 | buildConfigurationList = CDD7BF8C1B2D5126006FDA75 /* Build configuration list for PBXNativeTarget "ApiAi" */;
89 | buildPhases = (
90 | CDD7BF741B2D5125006FDA75 /* Sources */,
91 | CDD7BF751B2D5125006FDA75 /* Frameworks */,
92 | CDD7BF761B2D5125006FDA75 /* CopyFiles */,
93 | );
94 | buildRules = (
95 | );
96 | dependencies = (
97 | );
98 | name = ApiAi;
99 | productName = RNI18n;
100 | productReference = CDD7BF781B2D5125006FDA75 /* libApiAi.a */;
101 | productType = "com.apple.product-type.library.static";
102 | };
103 | /* End PBXNativeTarget section */
104 |
105 | /* Begin PBXProject section */
106 | CDD7BF701B2D5125006FDA75 /* Project object */ = {
107 | isa = PBXProject;
108 | attributes = {
109 | LastUpgradeCheck = 630;
110 | ORGANIZATIONNAME = innFactory;
111 | TargetAttributes = {
112 | CDD7BF771B2D5125006FDA75 = {
113 | CreatedOnToolsVersion = 6.3.2;
114 | LastSwiftMigration = 830;
115 | };
116 | };
117 | };
118 | buildConfigurationList = CDD7BF731B2D5125006FDA75 /* Build configuration list for PBXProject "ApiAi" */;
119 | compatibilityVersion = "Xcode 3.2";
120 | developmentRegion = English;
121 | hasScannedForEncodings = 0;
122 | knownRegions = (
123 | en,
124 | );
125 | mainGroup = CDD7BF6F1B2D5125006FDA75;
126 | productRefGroup = CDD7BF791B2D5125006FDA75 /* Products */;
127 | projectDirPath = "";
128 | projectRoot = "";
129 | targets = (
130 | CDD7BF771B2D5125006FDA75 /* ApiAi */,
131 | );
132 | };
133 | /* End PBXProject section */
134 |
135 | /* Begin PBXSourcesBuildPhase section */
136 | CDD7BF741B2D5125006FDA75 /* Sources */ = {
137 | isa = PBXSourcesBuildPhase;
138 | buildActionMask = 2147483647;
139 | files = (
140 | DBCB5CDE1B46E62D005CB38B /* ApiAi.m in Sources */,
141 | );
142 | runOnlyForDeploymentPostprocessing = 0;
143 | };
144 | /* End PBXSourcesBuildPhase section */
145 |
146 | /* Begin XCBuildConfiguration section */
147 | CDD7BF8A1B2D5126006FDA75 /* Debug */ = {
148 | isa = XCBuildConfiguration;
149 | buildSettings = {
150 | ALWAYS_SEARCH_USER_PATHS = NO;
151 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
152 | CLANG_CXX_LIBRARY = "libc++";
153 | CLANG_ENABLE_MODULES = YES;
154 | CLANG_ENABLE_OBJC_ARC = YES;
155 | CLANG_WARN_BOOL_CONVERSION = YES;
156 | CLANG_WARN_CONSTANT_CONVERSION = YES;
157 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
158 | CLANG_WARN_EMPTY_BODY = YES;
159 | CLANG_WARN_ENUM_CONVERSION = YES;
160 | CLANG_WARN_INT_CONVERSION = YES;
161 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
162 | CLANG_WARN_UNREACHABLE_CODE = YES;
163 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
164 | COPY_PHASE_STRIP = NO;
165 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
166 | ENABLE_STRICT_OBJC_MSGSEND = YES;
167 | GCC_C_LANGUAGE_STANDARD = gnu99;
168 | GCC_DYNAMIC_NO_PIC = NO;
169 | GCC_NO_COMMON_BLOCKS = YES;
170 | GCC_OPTIMIZATION_LEVEL = 0;
171 | GCC_PREPROCESSOR_DEFINITIONS = (
172 | "DEBUG=1",
173 | "$(inherited)",
174 | );
175 | GCC_SYMBOLS_PRIVATE_EXTERN = NO;
176 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
177 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
178 | GCC_WARN_UNDECLARED_SELECTOR = YES;
179 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
180 | GCC_WARN_UNUSED_FUNCTION = YES;
181 | GCC_WARN_UNUSED_VARIABLE = YES;
182 | IPHONEOS_DEPLOYMENT_TARGET = 11.4;
183 | MTL_ENABLE_DEBUG_INFO = YES;
184 | ONLY_ACTIVE_ARCH = YES;
185 | SDKROOT = iphoneos;
186 | };
187 | name = Debug;
188 | };
189 | CDD7BF8B1B2D5126006FDA75 /* Release */ = {
190 | isa = XCBuildConfiguration;
191 | buildSettings = {
192 | ALWAYS_SEARCH_USER_PATHS = NO;
193 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
194 | CLANG_CXX_LIBRARY = "libc++";
195 | CLANG_ENABLE_MODULES = YES;
196 | CLANG_ENABLE_OBJC_ARC = YES;
197 | CLANG_WARN_BOOL_CONVERSION = YES;
198 | CLANG_WARN_CONSTANT_CONVERSION = YES;
199 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
200 | CLANG_WARN_EMPTY_BODY = YES;
201 | CLANG_WARN_ENUM_CONVERSION = YES;
202 | CLANG_WARN_INT_CONVERSION = YES;
203 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
204 | CLANG_WARN_UNREACHABLE_CODE = YES;
205 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
206 | COPY_PHASE_STRIP = NO;
207 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
208 | ENABLE_NS_ASSERTIONS = NO;
209 | ENABLE_STRICT_OBJC_MSGSEND = YES;
210 | GCC_C_LANGUAGE_STANDARD = gnu99;
211 | GCC_NO_COMMON_BLOCKS = YES;
212 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
213 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
214 | GCC_WARN_UNDECLARED_SELECTOR = YES;
215 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
216 | GCC_WARN_UNUSED_FUNCTION = YES;
217 | GCC_WARN_UNUSED_VARIABLE = YES;
218 | IPHONEOS_DEPLOYMENT_TARGET = 11.4;
219 | MTL_ENABLE_DEBUG_INFO = NO;
220 | SDKROOT = iphoneos;
221 | VALIDATE_PRODUCT = YES;
222 | };
223 | name = Release;
224 | };
225 | CDD7BF8D1B2D5126006FDA75 /* Debug */ = {
226 | isa = XCBuildConfiguration;
227 | buildSettings = {
228 | CLANG_ENABLE_MODULES = YES;
229 | HEADER_SEARCH_PATHS = (
230 | "$(inherited)",
231 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
232 | "$(SRCROOT)/node_modules/react-native/React/**",
233 | "$(SRCROOT)/../react-native/React/**",
234 | "$(SRCROOT)/ApiAI/**",
235 | );
236 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
237 | LIBRARY_SEARCH_PATHS = "$(inherited)";
238 | OTHER_LDFLAGS = "-ObjC";
239 | PRODUCT_NAME = ApiAi;
240 | SKIP_INSTALL = YES;
241 | SWIFT_OBJC_BRIDGING_HEADER = "ApiAi/ApiAi-Bridging-Header.h";
242 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
243 | SWIFT_VERSION = 3.0;
244 | };
245 | name = Debug;
246 | };
247 | CDD7BF8E1B2D5126006FDA75 /* Release */ = {
248 | isa = XCBuildConfiguration;
249 | buildSettings = {
250 | CLANG_ENABLE_MODULES = YES;
251 | HEADER_SEARCH_PATHS = (
252 | "$(inherited)",
253 | /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include,
254 | "$(SRCROOT)/node_modules/react-native/React/**",
255 | "$(SRCROOT)/../react-native/React/**",
256 | "$(SRCROOT)/ApiAI/**",
257 | );
258 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks";
259 | LIBRARY_SEARCH_PATHS = "$(inherited)";
260 | OTHER_LDFLAGS = "-ObjC";
261 | PRODUCT_NAME = ApiAi;
262 | SKIP_INSTALL = YES;
263 | SWIFT_OBJC_BRIDGING_HEADER = "ApiAi/ApiAi-Bridging-Header.h";
264 | SWIFT_VERSION = 3.0;
265 | };
266 | name = Release;
267 | };
268 | /* End XCBuildConfiguration section */
269 |
270 | /* Begin XCConfigurationList section */
271 | CDD7BF731B2D5125006FDA75 /* Build configuration list for PBXProject "ApiAi" */ = {
272 | isa = XCConfigurationList;
273 | buildConfigurations = (
274 | CDD7BF8A1B2D5126006FDA75 /* Debug */,
275 | CDD7BF8B1B2D5126006FDA75 /* Release */,
276 | );
277 | defaultConfigurationIsVisible = 0;
278 | defaultConfigurationName = Release;
279 | };
280 | CDD7BF8C1B2D5126006FDA75 /* Build configuration list for PBXNativeTarget "ApiAi" */ = {
281 | isa = XCConfigurationList;
282 | buildConfigurations = (
283 | CDD7BF8D1B2D5126006FDA75 /* Debug */,
284 | CDD7BF8E1B2D5126006FDA75 /* Release */,
285 | );
286 | defaultConfigurationIsVisible = 0;
287 | defaultConfigurationName = Release;
288 | };
289 | /* End XCConfigurationList section */
290 | };
291 | rootObject = CDD7BF701B2D5125006FDA75 /* Project object */;
292 | }
293 |
--------------------------------------------------------------------------------
/android/src/main/java/de/innfactory/apiai/RNApiAiModule.java:
--------------------------------------------------------------------------------
1 | package de.innfactory.apiai;
2 |
3 | import android.os.AsyncTask;
4 | import android.util.Log;
5 |
6 | import com.facebook.react.bridge.Callback;
7 | import com.facebook.react.bridge.ReactApplicationContext;
8 | import com.facebook.react.bridge.ReactContextBaseJavaModule;
9 | import com.facebook.react.bridge.ReactMethod;
10 | import com.google.gson.Gson;
11 | import com.google.gson.reflect.TypeToken;
12 | import com.facebook.react.bridge.Promise;
13 |
14 | import java.util.HashMap;
15 | import java.util.Map;
16 | import java.util.List;
17 |
18 | import ai.api.AIListener;
19 | import ai.api.AIServiceException;
20 | import ai.api.android.AIConfiguration;
21 | import ai.api.android.AIDataService;
22 | import ai.api.android.AIService;
23 | import ai.api.android.SessionIdStorage;
24 | import ai.api.model.AIError;
25 | import ai.api.model.AIRequest;
26 | import ai.api.model.AIResponse;
27 | import ai.api.model.Result;
28 | import ai.api.model.AIContext;
29 | import ai.api.model.Entity;
30 | import ai.api.model.EntityEntry;
31 | import ai.api.RequestExtras;
32 |
33 |
34 | /**
35 | * Created by Anton Spöck on 2017-07-21
36 | **/
37 | public class RNApiAiModule extends ReactContextBaseJavaModule implements AIListener {
38 |
39 | private static final String TAG = "ApiAi";
40 |
41 | private static final String LANG_CHINESE_CHINA = "LANG_CHINESE_CHINA";
42 | private static final String LANG_CHINESE_HONGKONG = "LANG_CHINESE_HONGKONG";
43 | private static final String LANG_CHINESE_TAIWAN = "LANG_CHINESE_TAIWAN";
44 | private static final String LANG_DUTCH = "LANG_DUTCH";
45 | private static final String LANG_ENGLISH = "LANG_ENGLISH";
46 | private static final String LANG_ENGLISH_GB = "LANG_ENGLISH_GB";
47 | private static final String LANG_ENGLISH_US = "LANG_ENGLISH_US";
48 | private static final String LANG_FRENCH = "LANG_FRENCH";
49 | private static final String LANG_GERMAN = "LANG_GERMAN";
50 | private static final String LANG_ITALIAN = "LANG_ITALIAN";
51 | private static final String LANG_JAPANESE = "LANG_JAPANESE";
52 | private static final String LANG_KOREAN = "LANG_KOREAN";
53 | private static final String LANG_PORTUGUESE = "LANG_PORTUGUESE";
54 | private static final String LANG_PORTUGUESE_BRAZIL = "LANG_PORTUGUESE_BRAZIL";
55 | private static final String LANG_RUSSIAN = "LANG_RUSSIAN";
56 | private static final String LANG_SPANISH = "LANG_SPANISH";
57 | private static final String LANG_UKRAINIAN = "LANG_UKRAINIAN";
58 |
59 |
60 | private AIService aiService;
61 | private AIConfiguration config = new AIConfiguration("",
62 | AIConfiguration.SupportedLanguages.DEFAULT,
63 | AIConfiguration.RecognitionEngine.System);
64 | private AIDataService aiDataService;
65 | private List contexts;
66 | private List permantentContexts;
67 | private List entities;
68 | private Callback onResultCallback;
69 | private Callback onErrorCallback;
70 | private Callback onListeningStartedCallback;
71 | private Callback onListeningCanceledCallback;
72 | private Callback onListeningFinishedCallback;
73 | private Callback onAudioLevelCallback;
74 |
75 | private String accessToken;
76 | private String languageTag;
77 |
78 |
79 | public RNApiAiModule(ReactApplicationContext reactContext) {
80 | super(reactContext);
81 | }
82 |
83 |
84 | @Override
85 | public String getName() {
86 | return "ApiAi";
87 | }
88 |
89 | @ReactMethod
90 | public void setConfiguration(String clientAccessToken, String languageTag) {
91 | this.accessToken = clientAccessToken;
92 | this.languageTag = languageTag;
93 | config = new AIConfiguration(clientAccessToken, AIConfiguration.SupportedLanguages.fromLanguageTag(languageTag), AIConfiguration.RecognitionEngine.System);
94 | }
95 |
96 | @ReactMethod
97 | public void getLanguage(Promise promise) {
98 | promise.resolve(languageTag);
99 | }
100 |
101 | @ReactMethod
102 | public void setContextsAsJson(String contextsAsJson) {
103 | Gson gson = new Gson();
104 | contexts = gson.fromJson(contextsAsJson, new TypeToken>() {
105 | }.getType());
106 | }
107 |
108 | @ReactMethod
109 | public void setPermanentContextsAsJson(String contextsAsJson) {
110 | Gson gson = new Gson();
111 | permantentContexts = gson.fromJson(contextsAsJson, new TypeToken>() {
112 | }.getType());
113 | }
114 |
115 |
116 | @ReactMethod
117 | public void setEntitiesAsJson(String userEntitiesAsJson) throws AIServiceException {
118 | Gson gson = new Gson();
119 | entities = gson.fromJson(userEntitiesAsJson, new TypeToken>() {
120 | }.getType());
121 | }
122 |
123 |
124 | @ReactMethod
125 | public void startListeningNative(Callback onResult, Callback onError) {//, Callback onListeningStarted, Callback onListeningCanceled, Callback onListeningFinished, Callback onAudioLevel) {
126 |
127 | onResultCallback = onResult;
128 | onErrorCallback = onError;
129 |
130 | getCurrentActivity().runOnUiThread(new Runnable() {
131 |
132 | public void run() {
133 |
134 | aiService = AIService.getService(getReactApplicationContext(), config);
135 | aiService.setListener(RNApiAiModule.this);
136 |
137 | // set contexts
138 | if (contexts != null || permantentContexts != null || entities != null) {
139 | RequestExtras requestExtras = new RequestExtras(mergeContexts(contexts, permantentContexts), entities);
140 | aiService.startListening(requestExtras);
141 | contexts = null;
142 | entities = null;
143 | } else {
144 |
145 | // start listening without context
146 | aiService.startListening();
147 | }
148 |
149 |
150 | }
151 | });
152 | }
153 |
154 |
155 | @ReactMethod
156 | public void stopListening() {
157 | getCurrentActivity().runOnUiThread(new Runnable() {
158 |
159 | public void run() {
160 |
161 | if (aiService != null) {
162 | aiService.stopListening();
163 | }
164 | }
165 | });
166 | }
167 |
168 |
169 | @ReactMethod
170 | public void cancel() {
171 | getCurrentActivity().runOnUiThread(new Runnable() {
172 |
173 | public void run() {
174 |
175 | if (aiService != null) {
176 | aiService.cancel();
177 | }
178 | }
179 | });
180 | }
181 |
182 |
183 | @Override
184 | public void onResult(AIResponse response) {
185 |
186 | if (onResultCallback != null) {
187 | Gson gson = new Gson();
188 | try {
189 | onResultCallback.invoke(gson.toJson(response));
190 | } catch (Exception e) {
191 | Log.e(TAG, e.getMessage(), e);
192 | }
193 | }
194 |
195 | }
196 |
197 | @Override
198 | public void onError(final AIError error) {
199 |
200 | if (onErrorCallback != null) {
201 | Gson gson = new Gson();
202 |
203 | try {
204 | onErrorCallback.invoke(gson.toJson(error));
205 | } catch (Exception e) {
206 | Log.e(TAG, e.getMessage(), e);
207 | }
208 | }
209 | }
210 |
211 | @ReactMethod
212 | public void onListeningStarted(Callback callback) {
213 | onListeningStartedCallback = callback;
214 | }
215 |
216 | @Override
217 | public void onListeningStarted() {
218 | if (onListeningStartedCallback != null) {
219 | try {
220 | onListeningStartedCallback.invoke();
221 | } catch (Exception e) {
222 | Log.e(TAG, e.getMessage(), e);
223 | }
224 | }
225 | }
226 |
227 | @ReactMethod
228 | public void onListeningCanceled(Callback callback) {
229 | onListeningCanceledCallback = callback;
230 | }
231 |
232 | @Override
233 | public void onListeningCanceled() {
234 | if (onListeningCanceledCallback != null) {
235 | try {
236 | onListeningCanceledCallback.invoke();
237 | } catch (Exception e) {
238 | Log.e(TAG, e.getMessage(), e);
239 | }
240 | }
241 | }
242 |
243 | @ReactMethod
244 | public void onListeningFinished(Callback callback) {
245 | onListeningFinishedCallback = callback;
246 | }
247 |
248 | @Override
249 | public void onListeningFinished() {
250 | if (onListeningFinishedCallback != null) {
251 | try {
252 | onListeningFinishedCallback.invoke();
253 | } catch (Exception e) {
254 | Log.e(TAG, e.getMessage(), e);
255 | }
256 | }
257 | }
258 |
259 |
260 | @ReactMethod
261 | public void onAudioLevel(Callback callback) {
262 | onAudioLevelCallback = callback;
263 | }
264 |
265 | @Override
266 | public void onAudioLevel(float level) {
267 | if (onAudioLevelCallback != null) {
268 | try {
269 | onAudioLevelCallback.invoke(level);
270 | } catch (Exception e) {
271 | Log.e(TAG, e.getMessage(), e);
272 | }
273 | }
274 |
275 | }
276 |
277 |
278 | @ReactMethod
279 | public void requestQueryNative(String query, Callback onResult, Callback onError) {
280 |
281 | onResultCallback = onResult;
282 | onErrorCallback = onError;
283 |
284 | if (aiDataService == null) {
285 | aiDataService = new AIDataService(getReactApplicationContext(), config);
286 | }
287 |
288 | final AIRequest aiRequest = new AIRequest();
289 | aiRequest.setQuery(query);
290 |
291 |
292 | new AsyncTask() {
293 | @Override
294 | protected AIResponse doInBackground(AIRequest... requests) {
295 | final AIRequest request = requests[0];
296 | try {
297 |
298 | AIResponse response = null;
299 |
300 | // set contexts
301 | if (contexts != null || permantentContexts != null || entities != null) {
302 | RequestExtras requestExtras = new RequestExtras(mergeContexts(contexts, permantentContexts), entities);
303 | response = aiDataService.request(aiRequest, requestExtras);
304 | contexts = null;
305 | entities = null;
306 | } else {
307 |
308 | // start request without context
309 | response = aiDataService.request(aiRequest);
310 | }
311 |
312 | return response;
313 | } catch (AIServiceException e) {
314 | Gson gson = new Gson();
315 | try {
316 | onErrorCallback.invoke(gson.toJson(e));
317 | } catch (Exception e1) {
318 | Log.e(TAG, e.getMessage(), e);
319 | }
320 | }
321 | return null;
322 | }
323 |
324 | @Override
325 | protected void onPostExecute(AIResponse aiResponse) {
326 | if (aiResponse != null) {
327 | onResult(aiResponse);
328 | }
329 | }
330 | }.execute(aiRequest);
331 | }
332 |
333 | @ReactMethod
334 | public void getAccessToken(Promise promise) {
335 | promise.resolve(accessToken);
336 | }
337 |
338 | @ReactMethod
339 | public void getSessionId(Promise promise) {
340 | promise.resolve(SessionIdStorage.getSessionId(getReactApplicationContext()));
341 | }
342 |
343 | private List mergeContexts(List contexts1, List contexts2) {
344 | if (contexts1 == null) {
345 | return contexts2;
346 | } else if (contexts2 == null) {
347 | return contexts1;
348 | } else {
349 | contexts1.addAll(contexts2);
350 | return contexts1;
351 | }
352 | }
353 |
354 | @Override
355 | public Map getConstants() {
356 | final Map constants = new HashMap<>();
357 | constants.put(LANG_CHINESE_CHINA, "zh-CN");
358 | constants.put(LANG_CHINESE_HONGKONG, "zh-HK");
359 | constants.put(LANG_CHINESE_TAIWAN, "zh-TW");
360 | constants.put(LANG_DUTCH, "nl");
361 | constants.put(LANG_ENGLISH, "en");
362 | constants.put(LANG_ENGLISH_GB, "en-GB");
363 | constants.put(LANG_ENGLISH_US, "en-US");
364 | constants.put(LANG_FRENCH, "fr");
365 | constants.put(LANG_GERMAN, "de");
366 | constants.put(LANG_ITALIAN, "it");
367 | constants.put(LANG_JAPANESE, "ja");
368 | constants.put(LANG_KOREAN, "ko");
369 | constants.put(LANG_PORTUGUESE, "pt");
370 | constants.put(LANG_PORTUGUESE_BRAZIL, "pt-BR");
371 | constants.put(LANG_RUSSIAN, "ru");
372 | constants.put(LANG_SPANISH, "es");
373 | constants.put(LANG_UKRAINIAN, "uk");
374 | return constants;
375 | }
376 |
377 |
378 | }
--------------------------------------------------------------------------------