use laravel echo server in react native client - javascript

I want to use laravel echo server in react native app
but I think something is wrong that I don't know what is it
I get this error in my log
undefined is not an object (evaluating 'this.connector.channel')
channel
D:\react-native\taav\node_modules\laravel-echo\dist\echo.js:750:34
componentDidMount
it is my laravel
class updateStatus implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #return void
*/
public $activity;
public function __construct( Activity $a)
{
//
$this->activity=$a;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return ['channel'];
}
}
that I know my laravel server is correct because I can use correctly my socket in browser
and my react native code:
import React, {Component} from 'react';
import Echo from "laravel-echo"
import io from 'socket.io-client/dist/socket.io';
export default class Activities extends Component {
constructor(props) {
super(props)
this.btnadd = this.btnadd.bind(this)
this.SearchMethod = this.SearchMethod.bind(this)
this.socket = io('http://'.concat(server).concat(':6001'), {json: false})
}
componentDidMount() {
var echo = window.Echo = new Echo({
broadcaster: 'io',
host: 'http://'.concat(server).concat(':6001')
});
window.Echo.channel('channel')
.listen('updateStatus', (e) => {
// this.additem()
})
}

Try defining your broadcaster as 'socket.io' instead and that error should go away:
var echo = window.Echo = new Echo({
broadcaster: 'socket.io',
host: 'http://'.concat(server).concat(':6001')
});
Edit:
Looks like I'd also done some more magic with the echo library. From memory there was an issue getting the Echo library to pickup 'io' when it's imported here. What I ended up doing was copying the Echo code directly into my project and editing it to make it work. If you copy echo.js from /node_modules/laravel-echo/dist/echo.js into your own project and add this to the start of the file:
window.navigator.userAgent = 'react-native';
var io = require('socket.io-client');
and this to the end of the file:
export default Echo;
Then find the line of code that says
this.socket = io(this.options.host, {...this.options, ...{jsonp: false}});
and replace it with the following:
this.socket = io(this.options.host, this.options);
Then in your code above import Echo from this version in your project instead of from laravel-echo you'll hopefully have better luck. Sorry I didn't remember about that to start with!

Related

How can I use main.dart variable in my JS file?

I'm trying to create a calling app using flutter and I've created the backend using a node.js. This is how my main.dart file in flutter looks like:
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:flutter_dialpad/flutter_dialpad.dart';
import 'dart:js';
import 'package:js/js.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
body: SafeArea(
child:
DialPad(
enableDtmf: true,
outputMask: "(000) 000-0000",
backspaceButtonIconColor: Colors.red,
makeCall: (number){
print(number);
}
)
),
),
);
}
}
I want to use this "number" variable in my app.js file which looks like this:
const accountSid = '***';
const authToken = '***';
const client = require('twilio')(accountSid, authToken);
client.calls.create({
url: 'http://demo.twilio.com/docs/voice.xml',
to: '+10000000',
from: '+1000000',
}, function(err, call){
if (err) {
console.log(err);
} else {
console.log(call.sid);
}
})
I want to be able to use the "number" variable from my main.dart file in the "to" field in my app.js file. Please help me out...
What you need is a way to pass data between applications, and the easiest way for that would be through a REST API
You can use the HTTP module in NodeJS or a third-party package like Express and set up a POST Route to your NodeJS Server, where the number is sent as data.
Once the data is received on your server, you can call your Twilio function, and send a response back.
On Flutter, you can use the http package to make the API call.

Pusher: Callback function not executing with standalone Laravel (API) Vue.js(client) apps

Please I need help with pusher integration in my Laravel & Vue js project. NOT SPA (i.e separate Apps (Laravel - API & Vuejs- frontend)
The goal is to establish a real-time chat between two users.
The whole cycle is working perfectly well but the pusher callback is not executing, therefore making the chat function limited to the app API level only. It is not real-time which is why I'm integrating pusher to handle that.
Please see the code snippets below, ready to provide more on request. I've spent days on this, still can't figure out what I'm doing wrong.
Thanks in anticipation.
CommentController
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$user = Auth::user();
$validator = Validator::make($request->all(), [
'bid_id' => 'required',
'message' => ['required', 'string'],
]);
if ($validator->fails()) {
return response()->json(["error" => $validator->errors()], 400);
}
try {
$comment = $user->comments()->create([
'bid_id' => $request->bid_id,
'message' => $request->message,
]);
// Fire the comment broadcast event
// event(new CommentEvent($comment));
broadcast(new CommentEvent($user, $comment->load('user')))->toOthers();
} catch (Exception $exception) {
Log::error("Error while creating Comment" . $exception->getMessage());
} finally {
return response()->json(['comment' => $comment], 201);
}
}
CommentEvent.php
<?php
namespace App\Events;
use App\Models\Comment;
use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CommentEvent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* #param $comment
*
* #return void
*/
public $user;
public $comment;
public function __construct(User $user, Comment $comment)
{
$this->user = $user;
$this->comment = $comment;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('comment-channel');
}
public function broadcastAs()
{
return 'CommentEvent';
}
}
Main.js
import Pusher from "pusher-js";
/* -------------------------------------------------------------------------- */
/* PUSHER CONFIG */
/* -------------------------------------------------------------------------- */
Pusher.logToConsole = true;
let pusher = new Pusher(process.env.VUE_APP_PUSHER_APP_KEY,{
cluster: process.env.VUE_APP_PUSHER_APP_CLUSTER,
encrypted: false,
});
Vue.prototype.$pusher = pusher;
App.vue
<script>
export default {
name: "App",
components: {},
created() {
let channel = this.$pusher.subscribe("comment-channel");
channel.bind("pusher:subscription_succeeded", function(members) {
console.log(members);
console.log("succesfully subscribed!");
});
channel.bind("CommentEvent", function(data) {
console.log(data);
this.$store.commit("ADD_COMMENT", data.comment);
});
},
methods: {
},
};
</script>
I've been able to resolve this using.
but I had to switch tech. The real-time chat system of my app is now driven by socket.io, Redis and a simple node js server wrapped within the API
I'll be willing to help with code snippets if you need me to.

Trouble running a background service in react native

This is my very first post here, so please don't blame me if I'm not as complete and clear as I have to be.
The issue
I am new to React native and I recently began to develop a react native app which could read my incoming SMS's aloud. I already achieved to retrieve the incoming messages and to read them aloud... But only if the app is the foreground.
So, could you please advise me some libraries or tutorials on the subject ?
I'm working on a Nokia 5 with Android 9.
I currently use the following libraries :
React-native-android-sms-listener to retrieve the incoming messages.
React-native-tts to read the content aloud.
What I already tried
I'm searching the Internet for more than a week now (includig Stack Overflow and this example question) and I can't find what I'm looking for. I already tried React-native-background-timer and React-native-background-job. But I couldn't never get a background timer working and React-native-background-job allows tasks to be executed every 15 minutes only (due to the Android limitations).
So I read many articles like this one explaining how to use Headless JS and other libraries until I found this codeburst tutorial today, explaining how to develop a background service to record audio calls. I tried to adapt it, but the background service never starts.
My code
I must tell you that I don't have any knowledge in Java, so the native code below may contain mistakes, even if it is based on tutorials and the React native documentation.
Currently, when the app is launched, the service IncomingSMSService is called. This service, developed following the Codeburst tutorial referenced above, relies on Headless JS and a JS function that listen to the incoming messages and then read them aloud thanks to React-native-tts.
Here is these two files :
IncomingSMSService.java
package com.ava.service;
import android.content.Intent;
import android.os.Bundle;
import com.facebook.react.HeadlessJsTaskService;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.jstasks.HeadlessJsTaskConfig;
public class IncomingSMSService extends HeadlessJsTaskService {
#Override
protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
return new HeadlessJsTaskConfig(
"HandleIncomingSMS",
Arguments.fromBundle(extras),
5000,
true
);
}
return null;
}
}
HandleIncomingSMS.js
import { AppRegistry } from 'react-native';
import SmsListener from 'react-native-android-sms-listener';
import Tts from 'react-native-tts';
const HandleIncomingSMS = async (taskData) => {
SmsListener.addListener(message => {
Tts.getInitStatus().then(() => {
Tts.speak(`New message from number ${message.originatingAddress} : ${message.body}`);
});
});
}
AppRegistry.registerHeadlessTask('HandleIncomingSMS', () => HandleIncomingSMS));
These pieces of code are called in a BroadcastReceiver here (IncomingSMSReceiver.java) :
package com.ava.receiver;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.ava.service.IncomingSMSService;
import com.facebook.react.HeadlessJsTaskService;
import java.util.List;
public final class IncomingSMSReceiver extends BroadcastReceiver {
#Override
public final void onReceive(Context context, Intent intent) {
if (!isAppOnForeground((context))) {
Intent service = new Intent(context, IncomingSMSService.class);
context.startService(service);
HeadlessJsTaskService.acquireWakeLockNow(context);
}
}
private boolean isAppOnForeground(Context context) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses =
activityManager.getRunningAppProcesses();
if (appProcesses == null) {
return false;
}
final String packageName = context.getPackageName();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance ==
ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
}
I also requested the good permissions in my AndroidManifest file, and I registered the service like so :
<service
android:name="com.ava.service.IncomingSMSService"
android:enabled="true"
android:label="IncomingSMSService"
/>
<receiver android:name="com.ava.receiver.IncomingSMSReceiver">
<intent-filter android:priority="0">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
What am I doing wrong ? I don't even see service in the Running services tab of the Android Developer options... Any ideas ?
Thanks in advance for your help.
UPDATE (01/06/2019)
After reading or watching several tutorials like this one or this video, I managed to get my app working in the foreground. It now displays a persistent notification.
BUT, I don't know how I can "link" my service and my Broadcsat Receiver to this notification (for now, the service is called only if the app is in foreground).
Here is my updated code :
// IncomingSMSService
package com.ava.service;
import android.graphics.Color;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.ContextWrapper;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import com.facebook.react.HeadlessJsTaskService;
import com.ava.MainActivity;
import com.ava.R;
public class IncomingSMSService extends Service {
private NotificationManager notifManager;
private String CHANNEL_ID = "47";
private int SERVICE_NOTIFICATION_ID = 47;
private Handler handler = new Handler();
private Runnable runnableCode = new Runnable() {
#Override
public void run() {
Context context = getApplicationContext();
Intent myIntent = new Intent(context, IncomingSMSEventService.class);
context.startService(myIntent);
HeadlessJsTaskService.acquireWakeLockNow(context);
handler.postDelayed(this, 2000);
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void createNotificationChannel() {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID, "General", notifManager.IMPORTANCE_HIGH);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.setShowBadge(true);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
getManager().createNotificationChannel(notificationChannel);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.handler.post(this.runnableCode);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Ava")
.setContentText("Listening for new messages...")
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(contentIntent)
.setOngoing(true)
.build();
startForeground(SERVICE_NOTIFICATION_ID, notification);
return START_NOT_STICKY;
}
private NotificationManager getManager() {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
return notifManager;
}
}
My headlessJS task :
// HandleIncomingSMS.js
import SmsListener from 'react-native-android-sms-listener';
import Tts from 'react-native-tts';
import Contacts from 'react-native-contacts';
import { text } from 'react-native-communications';
module.exports = async () => {
// To lower other applications' sounds
Tts.setDucking(true);
// Prevent the TTS engine from repeating messages multiple times
Tts.addEventListener('tts-finish', (event) => Tts.stop());
SmsListener.addListener(message => {
Contacts.getAll((err, contacts) => {
if (err) throw err;
const contactsLoop = () => {
contacts.forEach((contact, index, contacts) => {
// Search only for mobile numbers
if (contact.phoneNumbers[0].label === 'mobile') {
// Format the contact number to be compared with the message.oritignatingAddress variable
let contactNumber = contact.phoneNumbers[0].number.replace(/^00/, '+');
contactNumber = contactNumber.replace(/[\s-]/g, '');
// Phone numbers comparison
if (contactNumber === message.originatingAddress) {
if (contact.familyName !== null) {
Tts.speak(`Nouveau message de ${contact.givenName} ${contact.familyName} : ${message.body}`);
} else {
// If the contact doesn't have a known family name, just say his first name
Tts.speak(`Nouveau message de ${contact.givenName} : ${message.body}`);
}
} else if (contactNumber !== message.originatingAddress && index === contacts.length) {
// If the number isn't recognized and if the contacts have been all checked, just say the phone number
Tts.speak(`Nouveau message du numéro ${message.originatingAddress} : ${message.body}`);
}
}
});
}
contactsLoop();
// Redirect to the SMS app
text(message.originatingAddress, message = false);
});
});
}
I also added the good permissions in my AndroidManifest.xml file like the following :
...
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
...
I made some progress but I am still stuck, so if you have any idea, please share them ! Thank you !

Javascript ServiceStack Client serialization error

So I have a master/detail scenario between two views. The master page shows a list and after clicking on one of the items, I send a message via the EventAggregator in Aurelia to the child view with a deserialized dto (coming from the selected item of the master) as a payload of the message.
However when I then try to pass this item as a parameter of a subsequent request in the child (to get additional info) the payload object fails to serialize.
Master.ts:
import { JsonServiceClient } from "servicestack-client";
import {
ListPendingHoldingsFiles,
ListPendingHoldingsFilesResponse,
SendHoldings,
PositionFileInfo
} from "../holdingsManager.dtos";
import { inject, singleton } from "aurelia-framework";
import { Router } from "aurelia-router";
import { EventAggregator } from "aurelia-event-aggregator";
import { GetPendingPositionMessage } from "../common/GetPendingPositionMessage";
#singleton()
#inject(Router, EventAggregator)
export class Pending {
router: Router;
positions: PositionFileInfo[];
client: JsonServiceClient;
eventAgg: EventAggregator;
constructor(router, eventAggregator) {
this.router = router;
this.eventAgg = eventAggregator;
this.client = new JsonServiceClient('/');
var req = new ListPendingHoldingsFiles();
this.client.get(req).then((getHoldingsResponse) => {
this.positions = getHoldingsResponse.PositionFiles;
}).catch(e => {
console.log(e); // "oh, no!"
});
}
openHoldings(positionInfo) {
this.eventAgg.publish(new GetPendingPositionMessage(positionInfo));
this.router.navigate('#/holdings');
}
}
Child.ts:
import { JsonServiceClient } from "servicestack-client";
import { inject, singleton } from "aurelia-framework";
import { Router } from 'aurelia-router';
import { EventAggregator } from "aurelia-event-aggregator";
import { GetPendingPositionMessage } from "../common/GetPendingPositionMessage";
import {
GetPendingHoldingsFile,
GetPendingHoldingsFileResponse,
Position,
PositionFileInfo
} from "../holdingsManager.dtos";
#singleton()
#inject(Router, EventAggregator)
export class Holdings {
router: Router;
pendingPositionFileInfo: PositionFileInfo;
position: Position;
client: JsonServiceClient;
eventAgg: EventAggregator;
constructor(router, eventAggregator) {
this.router = router;
this.eventAgg = eventAggregator;
this.eventAgg.subscribe(GetPendingPositionMessage,
message => {
this.pendingPositionFileInfo = message.fileInfo;
});
}
activate(params, routeData) {
this.client = new JsonServiceClient('/');
var req = new GetPendingHoldingsFile();
req.PositionToRetrieve = this.pendingPositionFileInfo;
this.client.get(req).then((getHoldingsResponse) => {
this.position = getHoldingsResponse.PendingPosition;
}).catch(e => {
console.log(e); // "oh, no!"
});
}
}
So the error happens when the child activates and attempts to send the request 'GetPendingHoldingsFile'.
Failed to load resource: the server responded with a status of 500 (NullReferenceException)
I have verified that this.pendingPositionFileInfo in the child is not null or empty and that on the server side, the object is not being received (it is null). I am new to Aurelia and not very experienced with Javascript so I must be missing something, any advice would be appreciated.
Edit 1
This seems to be something wrong with how I'm interacting with ServiceStack. I'm using version 4.5.6 of serviceStack with servicestack-client#^0.0.17. I tried newing up a fresh copy of the dto (PositionFileInfo) and copying over all the values from the parent view just to be sure there wasn't some javascript type conversion weirdness happening that I'm not aware of, but even with a fresh dto the webservice still receives a null request.
Switching from 'client.get(...)' to 'client.post(...)' fixed the problem. Apparently trying to serialize the object over in the URL was not a good plan.

TypeError: Cannot read property 'firebase' of undefined in NativeScript app

I'm creating a mobile app by using NativeScript with AngularJS2 & TypeScript. For using Firebase as DB to store data.
For using firebase in NativeScript I'm suing the following library - https://github.com/EddyVerbruggen/nativescript-plugin-firebase
Here is my code -
import {Component} from "#angular/core";
import {User} from "./shared/user/user";
import {UserService} from "./shared/user/user.service";
import {HTTP_PROVIDERS} from "#angular/http";
var firebase = require("nativescript-plugin-firebase");
#Component({
selector: "my-app",
providers: [UserService, HTTP_PROVIDERS],
templateUrl: "pages/login/login.html",
styleUrls: ["pages/login/login-common.css", "pages/login/login.css"]
})
export class AppComponent {
user: User;
isLoggingIn = true;
constructor(private _userService: UserService) {
this.user = new User();
}
submit() {
if (this.isLoggingIn) {
this.login();
} else {
this.signUp();
}
}
login() {
// TODO: Define
console.log('Clicked on Login button');
firebase.init({
persist: true // Allow disk persistence. Default false.
}).then(
function (instance) {
console.log("firebase.init done");
},
function (error) {
console.log("firebase.init error: " + error);
}
);
}
signUp() {
this._userService.register(this.user);
}
toggleDisplay() {
this.isLoggingIn = !this.isLoggingIn;
}
}
Method "Login()" is getting invoked when a user clicks on "Sign in" button. I've pasted that firebase code for checking everything is fine with firebase or not.
But, whenever that "Login()" is invoked it's showing following error.
JS: Clicked on Login button
JS: Error in firebase.init: TypeError: Cannot read property 'firebase' of undefined
JS: firebase.init error: TypeError: Cannot read property 'firebase' of undefined
I can understand this error is showing because I'm not properly inserting that "firebase" dependency inside the class. But, as I'm new to TypeScript I can't able to understand.. how to do it.
Need some help
Edited -
Getting following error from VS Code when using import * as firebase from "nativescript-plugin-firebase"; rather than var firebase = require("nativescript-plugin-firebase");
import firebase = require("nativescript-plugin-firebase");
in reference.d.ts add /// <reference path="./node_modules/nativescript-plugin-firebase/firebase" /> (without extensions)
you should enable multiDex in your app.gradle and remove and rebuild the app
android {
defaultConfig {
applicationId "com.mysite.myproj"
generatedDensities = []
multiDexEnabled true
}
See This issue form more details

Categories

Resources