TypeError: Cannot read property 'AwsCredentialsProvider' of undefined - amazon-web-services

Been trying to test out the aws-iot-device-sdk-v2 library for a bit. I am currently trying to test out the sample app provided by the AWS dev team. I am trying to test out the system incrementally. This is the code I have tested so far:
import { mqtt, auth, http, io, iot } from 'aws-iot-device-sdk-v2';
const client_bootstrap = new io.ClientBootstrap();
let config_builder = iot.AwsIotMqttConnectionConfigBuilder.new_with_websockets({
region: 'us-west-2',
credentials_provider: auth.AwsCredentialsProvider.newDefault(client_bootstrap)
});
config_builder.with_clean_session(false);
config_builder.with_endpoint('example.com');
config_builder.with_client_id(1);
const config = config_builder.build();
const client = new mqtt.MqttClient(client_bootstrap);
const connection = client.new_connection(config);
await connection.connect();
When running this on the AWS console, I am getting the following error:
TypeError: Cannot read property 'AwsCredentialsProvider' of undefined
Any idea what I'm doing wrong here?

Wasn't able to identify why I couldn't use AwsCredentialsProvider as expected but found a work-around. Instead, I was able to initialize the builder with const config_builder = iot.AwsIotMqttConnectionConfigBuilder.new_with_websockets();. Anyway, didn't figure out why I couldn't utilize AwsCredentialsProvider as expected. Might be something to look into if the dev team has time. đź‘Ť

I also encounter the same issue when running this example in browser and found the reason :
'aws-iot-device-sdk-v2' just import these 5 classes directly form aws-crt
https://github.com/aws/aws-iot-device-sdk-js-v2/blob/main/lib/index.ts
while in aws-crt, it's implementation for browser is in a sub folder ,
https://github.com/awslabs/aws-crt-nodejs/tree/main/lib/browserm, and it don't include 'auth' .
so if you run these example in browser, you need to import form aws-crt's subfolder, and skip 'auth':
import { mqtt, http, io, iot } from 'aws-crt/dist.browser/browser';

Related

I don't understand how my google action shows up on "Works with Google" search

I have followed below tutorial to build my own home action.
https://github.com/actions-on-google/smart-home-nodejs
I don't understand well on how this works. Let me explain you all about what I have understood so far and what I have done by now.
What I have DONE :
I built a conversational action (built with dialogflow's inline editor and intents) to change a data of the Firebase realtime database. (for instance, when I say "Turn the light on", then the Firebase data 'LED/OnOff' turns 0 to 1). Below is the code I have in my Dialogflow inline editor. (I have excluded the field including my project's credentials.)
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
admin.initializeApp();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to my agent!`);
}
function fallback(agent) {
agent.add(`I didn't understand`);
agent.add(`I'm sorry, can you try again?`);
}
function handle_heatOn(agent) {
const state = agent.parameters.heat_on;
console.log(state);
var heat = 0;
if (state == 1)
heat = 1;
return admin.database().ref('0/OnOff').update({
on : true
});
}
function handle_heatOff(agent) {
const state = agent.parameters.heat_on;
var heat = 0;
if (state == 0)
heat = 0;
return admin.database().ref('0/OnOff').update({
on : false
});
}
//some more functions, related to controlling 4 different devices (heater, cooler, exhaust fan, LED) - exempted
// Run the proper function handler based on the matched Dialogflow intent name
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('heat_on', handle_heatOn);
intentMap.set('heat_off', handle_heatOff);
intentMap.set('cool_on', handle_coolOn);
intentMap.set('cool_off', handle_coolOff);
intentMap.set('exha_on', handle_exhaOn);
intentMap.set('exha_off', handle_exhaOff);
intentMap.set('led_on', handle_ledOn);
intentMap.set('led_off', handle_ledOff);
// intentMap.set('your intent name here', yourFunctionHandler);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
Then I have deployed my action and Google has approved my action! It is now in production and can be searched in anyone's google account.
I have set up an OAuth 2.0 server. I'm really a beginner in developing, so I managed to use Auth0 to make the server. I have followed the below tutorial :
https://v3.jovo.tech/tutorials/google-action-account-linking-auth0
As a conclusion, when I invoke my conversational action in anyone's Google Assistant App, It will prompt the user to the authentication (login) screen (By Auth0). After the user inputs ID and Password, google assistant will link the user's account and launch my app.
However, my action is not shown on Google Home's "Works with Google" category. After trying to complete Brand Verification in Google Actions Console and linking one of my existent app on Google Play, I still don't know what to do or where to start from.
What I have understood so far :
Sorry for my shallow understanding in advance. I have understood that once my action is invoked by a user, it has to do account linking, which requires OAuth 2.0 server to exchange authentication token. If exchanging token has succeeded, the user's account is linked and he/she is able to use my action. The action will be launched after that.
I have searched the Internet and found some information such as Deep Linking and App Discovery, but I'm not sure this is the right keyword to start from.
I know I am really lacking in knowledge here. Please kindly at least hint where I should study and start.
What I want to understand and do :
I want to make my action, which is in production, show up on Google Home and Google Assistant App's "Works With Google" category without the prefix [test]. In other words, I want to let my app be searched just as the other company's apps. I understand that if you click on one of the apps of a company, your account will be linked and the company's action would be launched. Maybe I have to add some lines on Dialogflow's inline editor?? I know I might be silly, but I really appreciate your help. Thank you for reading my post.

“The page has expired due to inactivity” appears when using a services methods - Laravel 5.5

According to other asked questions like this one, I did many doings to prevent this request expired message but there is no solution for my issue.
In the long run I recognized that the message appears when I call a service method inside a controller which run on form action!
Here is my codes samples with some descriptions:
My route:
Route::post('Material/{id}', 'MaterialController#updateMaterial')->name('updateMaterial');
Material Controller Constructor:
public function __construct(CustomService $srv)
{
$this->middleware('admin')->only(['updateMaterial']);
$this->srv= $srv;
}
srv is a protected attribute in MaterialController class.
updateMaterial Method:
public function updateMaterial($id,Request $request)
{
$this->validate($request, [...]);
$material = $this->srv->updateMaterial($request, $id);
if ($material)
return view('panel._materials.edit-material')
->with('material', $material)
->with('success', 1);
}
I also have a provider for CustomService with name CustomServiceProvider and here is the register method of the provider:
public function register()
{
$this->app->bind(CustomService::class,function($app){
return new CustomService();
});
}
and I registered it as a provider in config/app.php.
So when I return something before calling service updateMaterial method, it's OK. but when the method runs, the issue appears!
I don'n have any idea about!
Update:
And here is updateMaterial of CustomService:
public function updateMaterial($request, $id)
{
$material = Material::find($id);
if (!$material)
return false;
if ($request->has('unit'))
$material->unit = $request['unit'];
if ($request->has('price'))
$material->price = $request['price'];
if ($request->has('type'))
$material->type = $request['type'];
if ($request->has('is_active'))
$material->is_active = $request['is_active'];
$material->updated_at = Carbon::now();
$material->save();
return $material;
}
I also create a new project with Laravel 5.5.0 and without adding any complexity I just added a post route and call it in form action, but nothing changed!
This is just an issue for Windows users on Local Environment. I suffered a lot with this also when on Windows. Once you deploy to your production server, you won't have any issue at all.
It's important to note that this is not an issue with Laravel 5.5 version only. I first saw this issue in version 5.2.
I think a good fix for this would maybe be using something like Homestead or Vessel from Fideloper. Honestly I only suffered this problem when using Windows.

Parse on AWS Issues

I have recently migrated my Parse.com service over to AWS Elastic Beanstalk running the Parse Server project from Github. Everything seems to be working fine except when I try to perform a query in Cloud Code.
Whenever I try to run a Parse.Query command I get the following exception at runtime.
Uncaught internal server error. [ReferenceError: atom is not defined] ReferenceError: atom is not defined
at /usr/local/lib/node_modules/parse-server/lib/Adapters/Storage/Mongo/MongoTransform.js:559:78
at Array.map (native)
at transformConstraint (/usr/local/lib/node_modules/parse-server/lib/Adapters/Storage/Mongo/MongoTransform.js:556:29)
at transformQueryKeyValue (/usr/local/lib/node_modules/parse-server/lib/Adapters/Storage/Mongo/MongoTransform.js:193:7)
at transformWhere (/usr/local/lib/node_modules/parse-server/lib/Adapters/Storage/Mongo/MongoTransform.js:215:15)
at MongoStorageAdapter.find (/usr/local/lib/node_modules/parse-server/lib/Adapters/Storage/Mongo/MongoStorageAdapter.js:321:59)
at /usr/local/lib/node_modules/parse-server/lib/Controllers/DatabaseController.js:827:33
at run (/usr/local/lib/node_modules/parse-server/node_modules/babel-polyfill/node_modules/core-js/modules/es6.promise.js:89:22)
at /usr/local/lib/node_modules/parse-server/node_modules/babel-polyfill/node_modules/core-js/modules/es6.promise.js:102:28
at flush (/usr/local/lib/node_modules/parse-server/node_modules/babel-polyfill/node_modules/core-js/modules/_microtask.js:18:9)
Here is a sample of the Cloud Code I'm running. I must mention this code worked perfectly when hosted on Parse.com.
Parse.Cloud.define("getNumberOfUnreadMessages", function(request, response) {
var currentUser = request.params.user;
console.log("[getNumberOfUnreadMessages] Get User: " + JSON.stringify(currentUser));
var query = new Parse.Query("messages");
query.containedIn("toUser", [currentUser]);
query.equalTo("read", false);
query.find({
success: function(results) {
console.log('[getNumberOfUnreadMessages] Results: ' + results.length);
response.success(results.length);
},
error: function(e) {
response.error("[getNumberOfUnreadMessages] Error: " + JSON.stringify(e));
}
});
});
Any ideas what the problem could be?
Thanks!
So it turns out the issue has nothing todo with the server configuration. It was simply that I was trying to perform a Parse.Query.or function with a full object as apposed to a pointer to an object. Annoying that parse didn't give me a proper error, but in this case there is no bug.

No headers in HAR response

I parse website 'http://ok.ru'. To get data from the post request I need to send a specific token that is generated by Javascript on the website and this token is contained in headers.
So I thought maybe one solution would be to open the website, let it generate token, grab headers and that's it.
One tool that can implement Java scripts is Selenium, however, to get headers I need to use brosermob-proxy (or equivalent). That is where I'm stuck.
There's no headers in response and I can't figure it out. Maybe someone who worked with browsermob can see what's wrong? I would also be glad to hear another solutions to my task. The code itself is below:
from browsermobproxy import Server
from selenium import webdriver
from ast import literal_eval
import json, os
os.chdir('C:/browsermob-proxy-2.1.0-beta-2/bin')
server = Server()
server.start()
proxy = server.create_proxy()
profile = webdriver.FirefoxProfile()
profile.set_proxy(proxy.selenium_proxy())
driver = webdriver.Firefox(firefox_profile=profile)
proxy.new_har('test')
driver.get('http://ok.ru')
driver.find_element_by_xpath('//input[#name="st.email"]').send_keys('****#****.com')
driver.find_element_by_xpath('//input[#name="st.password"]').send_keys('****')
driver.find_element_by_xpath(u'//input[contains(#value,"Log in")]').click()
result = literal_eval(json.dumps(proxy.har, ensure_ascii=False))
driver.close()
for entry in result['log']['entries']:
if len(entry['response']['headers']) > 0:
print entry['response']['headers']
The answer turned to be easy: just to add options to new_har:
proxy.new_har('test', options={'captureHeaders': True})
However, there is no token in headers, which is a new puzzle to me...

Trouble Getting Data from a Webservice using Qooxdoo

My capstone team has decided to use Qooxdoo as the front end for our project. We're developing apps for OpenFlow controllers using NOX, so we're using the NOX webservices framework. I'm having trouble getting data from the service; I know the service is running because if I go to the URL using Firefox the right data shows up. Here's the relevant portion of my code:
var req = new qx.io.remote.Request("http://localhost/ws.v1/hello/world",
"GET", "text/plain");
req.addListener("complete", function(e) {
this.debug(e.getContent());
});
var get = new qx.ui.form.Button("get");
get.addListener("execute", function() {
alert("The button has been pressed");
req.send();
}, this);
form.addButton(get);
In the firebug console I get this message after I click through the alert:
008402 qx.io.remote.Exchange: Unknown status code: 0 (4)
And if I press the Get button again I get this error:
027033 qx.io.remote.transport.XmlHttp[56]: Failed with exception: [Exception... "Component returned failure code: 0x80070057 (NS_ERROR_ILLEGAL_VALUE) [nsIXMLHttpRequest.open]" nsresult: "0x80070057 (NS_ERROR_ILLEGAL_VALUE)" location: "JS frame :: file:///home/user/qooxdoo-1.0-sdk/framework/source/class/qx/io/remote/transport/XmlHttp.js :: anonymous :: line 279" data: no]
I've also looked at the Twitter Client tutorial, however the "dataChange" event I set up in place of the "tweetsChanged" event never fired. Any help is appreciated, thank you.
This sound like a cross domain request issue. qx.io.remote.Request uses XHR for transporting the data which may not work in every case due to the browser restriction. Switching the crossDomain flag on the request to true will change from XHR to a dynamically inserted script tag doesn't have the cross domain restriction (but other restrictions).
req.setCrossDomain(true);
Maybe that solves your problem.
Additionally, you can take a look at the documentation of the remote package to get some further details on cross domain requests:
http://demo.qooxdoo.org/current/apiviewer/#qx.io.remote
Also take care not to use a request object twice. The only work once.