Flask_SocketIO Not emitting custom events - flutter

I have a Flask_SocketIO app that supposed to implement a chat groups system.
The client thats interacting with it is a flutter app.
I wrote a test to see if the socketio events are working. it worked once, but than stopped.
the server is getting the client's emits but not emitting back to the client.
also, the connection related evets (connect, disconnect, error) seems to be fully working. the client's callbacks on these events are called.
My flutter test client:
void main() async {
setupLocator();
final api = locator<Api>();
final socketService = locator<SocketService>();
Message msg = Message(
msgId: null,
content: "Hello!",
senderId: 1,
senderName: 'tair',
sendtime: DateTime.now().toString(),
groupId: 1);
runApp(
MaterialApp(
home: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
RaisedButton(
child: Text("Disconnect"),
onPressed: () {
socketService.leave(1, 1);
}),
RaisedButton(
child: Text("Send"),
onPressed: () {
socketService.sendMessage(msg);
},
),
RaisedButton(
child: Text("Connect"),
onPressed: () {
socketService.connect(1, 1, (data) {
print('Data!');
print(data);
});
},
),
],
),
),
),
);
SharedPreferences.setMockInitialValues({});
await api.login('tair', '1234');
await socketService.getToken();
socketService.connect(1, 1, (data) {
print('Data!');
print(data);
});
Api: A class that's interacting with rest api. not related
SocketService: A class that's emitting and listening to events. im giving the connect() method
parameters in order to join a socketio room on the server side
locator: Dependency injecttion using pub package get_it. also not related
Here's the events on my Server:
#sock.on('join')
def join_group_room(data):
print(data)
token = data['token']
if token in user_token.keys():
group = Group.query.filter_by(id=int(data['groupId'])).first()
if group.temp_participants is None:
group.temp_participants = data['userId'] + ','
else:
group.temp_participants += data['userId'] + ','
db.session.commit()
join_room(data['groupId'])
#print(rooms())
else:
emit('error', 'Invalid token')
#sock.on('message')
def message_room(data):
print(data)
token = data['token']
if token in user_token.keys():
message = Message(content=data['message'], groupid=int(data['groupId']), username=user_token[token],
datetime=data['datetime'])
db.session.add(message)
db.session.commit()
participants = Group.query.filter_by(id=message.groupid).first().participants.split(",")
temp_participants = Group.query.filter_by(id=message.groupid).first().temp_participants.split(",")
for participant in participants:
if participant not in temp_participants:
pushbots.push_batch(platform=pushbots.PLATFORM_ANDROID,
alias=participant,
msg='A new message arrived', payload={'data': {'message': message.content,
'messageId': message.id,
'username': user_token[
token],
'datetime': message.datetime,
'groupId': message.groupid,
'userId': User.query.filter_by(
username=user_token[
token]).first().id}})
print("Emitting")
emit('message', {'message': message.content, 'messageId': message.id,
'username': user_token[token], 'datetime': message.datetime,
'groupId': message.groupid,
'userId': User.query.filter_by(username=user_token[token]).first().id},
room=message.groupid)
sock.sleep(0)
else:
emit('error', 'Invalid token')
#sock.on('leave')
def leave_group_room(data):
print(data)
token = data['token']
if token in user_token.keys():
group = Group.query.filter_by(id=int(data['groupId'])).first()
group.temp_participants = str(group.temp_participants.split(",").remove(data['userId'])).strip('[]')
db.session.commit()
leave_room(data['groupId'])
emit('error', 'Invalid token')
Im using eventlet as async_mode for the socketio app. i looked up online for solutions and many people said i should add the following line to the main script:
import eventlet
eventlet.monkey_patch()
Also, according to my partner on this project, the events are working fine on his machine
for further explaination, here is the link to my git repo, so you can watch the whole code: My git repo (its on integration/ClientServer branch)
Thanks for helping!

Apperantly, room names can be only strings, but the emit function wont throw an error if youll pass an int as the room parameter.

Related

How do i connect to csgo's community server?

So, I've been working on a bot and I've been stuck on this issue where my bot is not able to connect to the community server
Here is this code I've used:
const SteamUser = require('steam-user');
const steam = new SteamUser();
steam.logOn({
accountName: '',
password: ''
});
steam.on('loggedOn', () => {
console.log('We joinned steam');
steam.setPersona(SteamUser.EPersonaState.Online); // Makes steam online
steam.gamesPlayed(730); // Opens csgo
});
Is there any fixes?
I tried some fixing to the code using ChatGPT but I still get error
Here is the code provided by ChatGPT:
const { SteamClient } = require('steam-client');
const SteamUser = require('steam-user');
// Create a new Steam client and user objects
const client = new SteamClient();
const user = new SteamUser(client);
// Set your Steam username and password
const username = 'your_username';
const password = 'your_password';
// Authenticate with the Steam client
user.logOn({
accountName: username,
password: password
});
client.on('logOnResponse', () => {
console.log('Logged in to Steam!');
// Join a community server
client.joinCommunityServer('123.456.789.012', 27015);
console.log('Joined community server!');
// Disconnect from the server after 10 seconds
setTimeout(() => {
client.leaveCommunityServer();
console.log('Disconnected from community server.');
}, 10000);
});

How to solve Vercel 500 Internal Server Error?

I have created a project that uses MongoDB to store user info and Next-Auth to authenticate users. On local host this is all working seamlessly. Previously I had a couple errors with my next-auth config, but that seems to be working fine now on Vercel live site. Once the user logs in they are redirected to "my-project/suggestions". On this page I am using getServerSideProps to identify if there is a valid session token. If so, data is pulled from a local json file.
On the live site, when the user logs in, the page is redirected to "/suggestions", yet I am receiving an 500 Internal Server Error page. On the function logs I am getting this error message:
[GET] /_next/data/KpsnuV9k44lUAhQ-0rK-B/suggestions.json
10:10:57:12
2022-05-05T14:10:59.270Z 5b7a7375-045f-4518-864b-7968c3c9385f ERROR [Error: ENOENT: no such file or directory, open '/var/task/public/data/data.json'] {
errno: -2,
syscall: 'open',
path: '/var/task/public/data/data.json',
page: '/suggestions'
}
RequestId: 5b7a7375-045f-4518-864b-7968c3c9385f Error: Runtime exited with error: exit status 1
Runtime.ExitError
This is my first project using MongoDB and Next-Auth.. not so sure what the issue is in this case. In my .env.local file I only have these two variables:
NEXTAUTH_SECRET="MUNKNATION"
NEXTAUTH_URL=http://localhost:3000
How I am pulling the data on local host:
export const getServerSideProps = async (context) => {
const session = await getSession({ req: context.req });
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
} else {
let filePath = path.join(process.cwd(), "public", "data", "data.json");
let jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
const inProgressStatusData = data.productRequests.filter(
(item) => item.status == "in-progress"
);
const liveStatusData = data.productRequests.filter(
(item) => item.status == "live"
);
const plannedStatusData = data.productRequests.filter(
(item) => item.status == "planned"
);
let filterData = filteredData(data, "suggestion");
let feedbackData = {
suggestions: filterData,
progress: inProgressStatusData,
planned: plannedStatusData,
live: liveStatusData,
};
return {
props: { session, feedbackData },
};
}
};
Folder structure:
A simple solution to this problem would be to, inside of your getServerSideProps, instead of calling readFile use readFileSync as follows:
export const getServerSideProps = async (context) => {
...
const file = readFileSync(
join(process.cwd(), "public", "data", "data.json"),
"utf8"
);
const data = JSON.parse(fileData);
...
I have tested this solution with Vercel and it works correctly, in development and production mode.

graphql-flutter subscriptions in flutter connectivity issue

I am new to flutter development but I have good experience in nodejs and graphql. I am trying to consume the subscription widget of graphql-flutter and update the changes. but the connection is not being established. But I could use the query and Mutation widget and get the results. The examples provided by the graphql-flutter team is 2 years old and same with https://hasura.io/ documents. Can someone help me providing the latest examples or samples.
graphql-flutter:^5.0.0
If additional infos needed please comment below.
Thanks in advance
I made a class that I use with graphql but it'll be able to work with graphql-flutter but passing the client to
return GraphQLProvider(
client: Services().graphQL.client, // just how I have my services set up
child: MaterialApp(
title: 'Flutter Demo',
...
),
);
class:
class GraphQL {
static final HttpLink _httpLink = HttpLink(environment[envMode]!['server']);
static WebSocketLink _wsLink(String token) => WebSocketLink(
environment[envMode]!['webSocket'],
config: SocketClientConfig(
inactivityTimeout: const Duration(hours: 1),
initialPayload: {
'Authorization': 'Bearer $token',
},
),
);
Link _splitLink(String token) => Link.split(
(request) => request.isSubscription,
_wsLink(token),
_httpLink,
);
GraphQLClient client(String token) {
return GraphQLClient(
link: AuthLink(getToken: () async => 'Bearer $token')
.concat(_splitLink(token)),
cache: GraphQLCache(
store: HiveStore(),
),
);
}
Future<void> initHive() async {
return await initHiveForFlutter();
}
}
The environment and envMode come from a config file that has gets its data from an env file to keep manage env and secrets.

how to get token when sign up using graphql in flutter

hello i am trying to get the token value when user is signing up. i am running mutation query for signing up a new user but my problem is i don't know how to get the token when sign up is successful.
this is the api endpoint https://agro-e-commerce.herokuapp.com/graphql
and this is my mutation query in graphql playground
mutation{
signUp(data: {
full_name:"",
user_name:"",
email:"",
phone:"",
password:"",
division:"",
region:"",
address:""
}){
token}
}
here is my code in flutter
String query0 = """
mutation run(\$full_name: String!,\$user_name:String!,\$email:String!,
\$phone: String!,\$password: String!,\$division: String!,\$region:String!,\$address: String!){
signUp(data:{
full_name:\$full_name
user_name:\$user_name,
email:\$email,
phone:\$phone,
password:\$password,
division:\$division,
region:\$region,
address:\$address
}){
token
}
}
body: new Mutation(
builder: (RunMutation runMutation, QueryResult result) {
return FloatingActionButton(
child: new Icon(Icons.add),
onPressed: () {
runMutation({
'user_name': 'anikkoll',
'full_name': 'anikk karmokerkll',
'email': 'anikjkoy78749kl#gmail.com',
'phone': '0167605672879',
'password': 'password',
'division': 'barishal',
'region': 'barishal sadar',
'address': 'kawnia'
});
},
);
},
options: MutationOptions(document: query0),
onCompleted: (resultdata) {
print(resultdata);
}
i expected only token but i got this
{signUp: {token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjgzYTQzMzJhLTk2OWQtNDI3Mi05OWY3LTdiOWNjN2ZlNDhkOCIsImVtYWlsIjoiYW5pa2prb3k3bDg3NDlrbEBnbWFpbC5jb20iLCJ1c2VyX25hbWUiOiJhbmlra29vbGwiLCJyb2xlIjoiQ09OU1VNRVIiLCJpbWFnZSI6bnVsbCwiZnVsbF9uYW1lIjoiYW5pa2tsIGthcm1va2Vya2xsIiwicGhvbmUiOiIwMTU3NjA1NjcyODc5IiwiYWRkcmVzcyI6Imthd25pYSIsInJlZ2lvbiI6ImJhcmlzaGFsIHNhZGFyIiwiZGl2aXNpb24iOiJiYXJpc2hhbCIsImlhdCI6MTU2MzE3ODkxOSwiZXhwIjoxNTYzNzgzNzE5fQ.qCpES_c-dtk7nr-EXqTbTWjIdj4OMqB2HBsEwFXDMlc}}
In your query, you are requesting only the token. In return, you got your token.
This is the token you want now you just have to decode it.

Perform assertions on sweet alerts in protractor 6.0, angular 7 and sweet alert 2.0

After I register a user a sweet alert comes out saying whether i was successful or not. I am not able to assert the same using protractor.
I've tried the answers in the related older posts, searched for documentations, found none.
My spec is:
it('should go to login page, navigate to register page and register new user', async () => {
const loginButton = element(by.id('loginButton'));
await loginButton.click();
const registerUserButton = element(by.id('registerUserButton'));
await registerUserButton.click();
// register page
const name = element(by.id('usersName'));
const password = element(by.id('password'));
const confirmPassword = element(by.id('confirmPassword'));
const email = element(by.id('email'));
const number = element(by.id('number'));
const gender = element(by.id('gender'));
const submitButton = element(by.id('submitButton'));
// giving values to form data input fields
await name.sendKeys('testUser');
await password.sendKeys('testUser123');
await confirmPassword.sendKeys('testUser123');
await email.sendKeys(new Date().toDateString().split(' ').join('') + new Date().getTime() + '#gmail.com');
await number.sendKeys('9712312323');
await gender.sendKeys('male');
await submitButton.click();
// checking alert
const alertDialog = await browser.driver.switchTo().alert();
expect(await alertDialog.getText()).toEqual('Success!! You\'ve successfully registered');
});
the sweetalert code is :
Swal.fire({
type: 'success',
title: 'Success!! You\'ve successfully registered',
text: 'You\'re provided with 50 free loyalty points. Welcome to Star Hotel',
timer: 50000,
confirmButtonText: 'Cool'
});
Error:
- Failed: no such alert
(Session info: chrome=73.0.3683.86)
(Driver info: chromedriver=2.46.628402 (536cd7adbad73a3783fdc2cab92ab2ba7ec361e1),platform=Windows NT 10.0.17134 x86_64)
But the automation takes place fine and the user gets registered and an alert does pop out with the given successful message.
I didn't find any material regarding using locators for sweet alerts, but i am assuming at the core it is still javascript alert.