Im trying to convert some of my PHP functions to mongodb, but cant figure it out, could someone help me out?
PHP function applications:
function applications($gangId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `status`='avaliable' and `gangid`='$gangId'");
return ($applications ? $applications : false);
}
my attempt on function applications:
gangshema.methods.applications(thisid) {
// some sort of callback?
db.gang_applications.find({status:avaliable, gangid: thisid}, function(err, cursor) {
if (cursor != 0) {
console.log(cursor);
}
});
}
PHP function application_done
function application_done($applicationId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `id`='$applicationId'")->row();
return ($applications->status == 'avaliable' ? false : true);
}
my attempt on function application_done
gangshema.methods.application_done(applicationid) {
db.gang_applications.find({id:applicationid}, function(err,cursor) {
// return ($applications->status == 'avaliable' ? false : true);
});
}
but my main consern is a function called accept_applications. I have no clue on how to do this part, including calling other functions for their response.
function accept_application($userid,$applicationId) {
$box = 'failure';
if (empty($applicationId)) {
$message = "applicationId is empty";
} elseif ($this->application_done($applicationId)) {
$message = "Already registred!";
} else {
$application = $this->getApplication($applicationId);
$test = true;
if(!($test)) {
$message = "false test";
} else {
$this->db->query("UPDATE `gang_applications` SET `status`='accepted', `by`='$userid' where `id`='$applicationId'");
$this->gangs->add_member($application->userid,'gang','member',$application->gangid);
$message = "Accept!";
}
}
return $message;
}
Using this at the beginning of the Node.js script:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
First snippet:
function applications($gangId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `status`='avaliable' and `gangid`='$gangId'");
return ($applications ? $applications : false);
}
becomes:
var findApplications = function(db, gangId) {
var cursor = db.collection('gang_application').find({
"status": "available"
"gangId": gangId
});
var results = [];
cursor.each(function(err, doc) {
if (err) console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
results.push(doc);
}
});
return results;
};
Second snippet:
function application_done($applicationId) {
$applications = $this->db->query("SELECT * FROM `gang_applications` where `id`='$applicationId'")->row();
return ($applications->status == 'avaliable' ? false : true);
}
becomes:
function applications(gangId) {
db.gang_application
}
var applicationsDone = function(db, applicationId) {
var cursor = db.collection('gang_application').find({
"id": applicationId
});
var results = [];
cursor.each(function(err, doc) {
if (err) {
console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
results.push(doc.status);
}
});
return results;
};
Call both as follows:
MongoClient.connect(url, function(err, db) {
if (!db) {
console.log("Database did not connect.");
}
else {
findApplications(db, "102"); // Replace "102" with gangId
applicationsDone(db, "104"); // Replace "104" with applicationId
}
});
EDIT per comments, here's how to include a callback:
// Note extra `callback` parameter
var applicationsDone = function(db, applicationId, callback) {
var cursor = db.collection('gang_application').findOne({
"id": applicationId
});
cursor.each(function(err, doc) {
if (err) {
console.log("Error: " + err);
} else if (doc != null) {
console.log("Null document.");
} else {
return (doc.status == "available");
}
});
};
To call:
MongoClient.connect(url, function(err, db) {
if (!db) {
console.log("Database did not connect.");
}
else {
var callback = function(doc) { console.log(doc.status); };
applicationsDone(db, "104", callback);
}
});
EDIT Third snippet:
function accept_application($userid, $applicationId) {
$box = 'failure';
if (empty($applicationId)) {
$message = "applicationId is empty";
} elseif ($this->application_done($applicationId)) {
$message = "Already registred!";
} else {
$application = $this->getApplication($applicationId);
$test = true;
if(!($test)) {
$message = "false test";
} else {
$this->db->query("UPDATE `gang_applications` SET `status`='accepted', `by`='$userid' where `id`='$applicationId'");
$this->gangs->add_member($application->userid,'gang','member',$application->gangid);
$message = "Accept!";
}
}
return $message;
}
becomes this. Note some changes to the functions above to get this to work, such as returning an array of documents from applications, and using .findOne() for applicationDone():
function acceptApplication(userId, applicationId) {
if (!applicationId) return "No application ID";
if (applicationDone(db, applicationId)) return "Application already submitted.";
// Left out `if (!$test)`
db.gang_applications.update({
"id": applicationId,
"userId": userId
}, {
"status": "accepted"
}, upsert: false);
// $this->gangs->add_member($application->userid,'gang','member',$application->gangid);
return "Accepted!";
}
Related
I am working in flutter app that connect to the phpMyAdmin. I have to check the phone number if it's found in the database or not found and it's works and the result "found" or not return into the debug console successfully. My problem is how can i connect the flutter to the result from php? if it's found i want to print a message and if it not show another message.
this is the php :
<?php
include "config.php"; // call connection
$err= array();
$phone_login = $_POST["login_phone"];
try{
$stmt = $connect->prepare("SELECT * FROM profile WHERE phone = ?");
$stmt->execute(array($phone_login));
$count = $stmt->rowCount();
}catch(PDOException $e){
echo $e-> getMessage();}
if($count > 0){
echo json_encode(array("status" => "found"));
}else{
echo json_encode(array("status" => "not found"));
}
?>
and this is the function in login.dart:
const String linklogin = "$linkServerName/checkphone.php";
JsonAPI _tst = JsonAPI();
login() async {
var response = await _tst.postRequest(linklogin, {
"login_phone": mobileNumTF_login.text,
});
if (response['status'] == "found") {
print("found");
} else {
print("not found");
}
}
How can i do an action in flutter app if i received the found and not found?
You can use a FutureBuilder, pass the login() future and display a Text() widget as follows:
FutureBuilder<String>(
future: login(),
builder: (
BuildContext context,
AsyncSnapshot<String> snapshot,
) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return const Text('Error');
} else if (snapshot.hasData) {
return Text(
snapshot.data,
style: const TextStyle(color: Colors.cyan, fontSize: 36)
);
} else {
return const Text('Empty data');
}
} else {
return Text('State: ${snapshot.connectionState}');
}
},
),
if (response.statusCode == 200){
}else {
print("______##################################_______");
print(
'Request failed with status: ${response.statusCode}.');
print("______##################################_______");
}
i need to pass data with video that i wan upload but i don't know how to do that just like these data i need to pass it with the video to the php page
var data = {
"fileInput": videoFile.path,
"titleInput": titleController.text,
"descriptionInput": descriptionController.text,
"privacyInput": selectedCategorise.value,
"categoryInput": listcategory.map((e) => {e['name']}),
};
I know how to pass it on without a video like this function i pass the email and password
`signin() async {
var formdata = formstatesignin.currentState;
if (formdata.validate()) {
formdata.save();
var data = {"email": email.text, "password": password.text};
var url = "http://10.0.2.2/mobtech2/login.php";
var response = await http.post(url, body: data);
var responsebody = jsonDecode(response.body);
if (responsebody['status'] == "success") {
savePref(responsebody['username'], responsebody['email'],
responsebody['id']);
Navigator.of(context).pushNamed("homepage");
} else {
Navigator.of(context).pop();
}
} else {
print("Not vaild");
}
}`
this is the function that i wan pass data to it
`Future uploadVideo(File videoFile) async {
var uri = Uri.parse("http://10.0.2.2/videoTube/file_upload.php");
var request = new http.MultipartRequest("POST", uri);
var multipartFile =
await http.MultipartFile.fromPath("video", videoFile.path);
request.files.add(multipartFile);
http.StreamedResponse response = await request.send();
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
//final response = await http.post(uri, body: data);
if (response.statusCode == 200) {
print("Video uploaded");
} else {
print("Video upload failed");
}
}`
this code for class processing in php
`<?php
include "config.php";
if (!isset($_POST["video"])) {
echo "No video sent to page";
exit();
}
// 1) create file Uplaod Data
$videoUploadData = new VideoUploadData(
$_FILES["video"],
$_POST["titleInput"],
$_POST["descriptionInput"],
$_POST["privacyInput"],
$_POST["categoryInput"],
"REPLACE-THIS"
);
// 2) Process video data (upload)
$videoProcessor = new VideoProcessor($con);
$wasSuccessful = $videoProcessor->upload($videoUploadData);
?>`
this code for class VideoUploadData in php
`<?php
class VideoUploadData{
public $videoDataArray, $title, $description, $privacy, $category, $uploadedBy;
public function __construct($videoDataArray, $title, $description, $privacy, $category, $uploadedBy) {
$this->videoDataArray = $videoDataArray;
$this->title = $title;
$this->description = $description;
$this->privacy = $privacy;
$this->category = $category;
$this->uploadedBy = $uploadedBy;
}
}
?>`
this code for class VideoProcessor in php
`<?php
class VideoProcessor{
private $con;
private $sizeLimit = 500000000;
private $allowedTypes = array("mp4", "flv", "webm", "mkv", "vob", "ogv", "ogg", "avi", "wmv", "mov", "mpeg", "mpg");
public function __construct($con) {
$this->con = $con;
}
public function upload($videoUploadData) {
$targetDir = "uploads/videos/";
$videoData = $videoUploadData->videoDataArray;
$tempFilePath = $targetDir . uniqid() . basename($videoData["name"]);
$tempFilePath = str_replace(" ", "_", $tempFilePath);
$isValidData = $this->processData($videoData, $tempFilePath);
if (!$isValidData) {
return false;
}
if (move_uploaded_file($videoData["video"]["tmp_name"], $tempFilePath)) {
$finalFilePath = $targetDir . uniqid() . ".mp4";
if (!$this->insertVideoData($videoUploadData, $finalFilePath)) {
echo "Insert query failed";
return false;
}
}
}
private function processData($videoData, $filePath) {
$videoType = pathInfo($filePath, PATHINFO_EXTENSION);
if (!$this->isValidSize($videoData)) {
echo "File too large. Can't be more than" . $this->sizeLimit . " bytes";
return false;
}
else if (!$this->isValidType($videoType)) {
echo "Invalid file type";
return false;
}
else if ($this->hasError($videoData)) {
echo "Error code: " . $videoData["error"];
return false;
}
return true;
}
private function isValidSize($data) {
return $data["size"] <= $this->sizeLimit;
}
private function isValidType($type) {
$lowercased = strtolower($type);
return in_array($lowercased, $this->allowedTypes);
}
private function hasError($data) {
return $data["error"] != 0;
}
private function insertVideoData($uploadData, $filePath){}
}
?>`
yes you can upload a video with discription like name and title use dio package
this is an example i use to upload a video with some discription to my server backend use the MultipartFile
when you use the function _upload(video1) i pass the video as an argument but you can do it other way if you want i also set the progress indicator for the video upload progress.
// create listing,post and upload video to the server
void _upload(video1) async {
// get variables from shared preferences
token = await SharedPreferencesProvider.getUserToken();
userId = await SharedPreferencesProvider.getUserId();
// api to upload video
// Post a video to
var url = 'https://example.com/api/v1/video';
var video1Path;
if (video1 == null) {
return;
} else {
video1Path = await MultipartFile.fromFile(video1.path);
}
FormData data = FormData.fromMap({
"title": title,
"products": "1",
"description": description,
"category_id": categoryId,
"category_name": categoryName,
"longitude": _longitude,
"latitude": _latitude,
"video1": video1Path,
});
Dio dio = new Dio();
dio.options.headers["Authorization"] = "Bearer $token";
dio.post(url, data: data, onSendProgress: (int sent, int total) {
setState(() {
_isUploading = true;
// show a progress %
progressString ='uploading :' + ((sent / total) * 100).toStringAsFixed(0) + "%";
if ( ((sent / total) * 100).toStringAsFixed(0) == '100'){
progressString = 'Saving...';
}
//progressString = ((sent / total) * 100).toStringAsFixed(0) + "%";
});
}).then((response) async => {
setState(() {
progressString = DemoLocalizations.of(context).uploadCompleted;
}),
print(response),
//after successful product post we redirect to(Main page)
goHome()
})
.catchError((error) => print(error));
}
We are working on a car booking app to make it work with a PHP server. the mobile app is already using Signal R for real-time communication with a .NET server. we want to modify the code to connect to our PHP server.
My question is how can I connect this signal R code to communicate to a PHP server? How signal R will Work with a PHP server? Any solution for that?
Our primary aim is to make it work with signal R instead of switching to other solutions. Still, I would appreciate your recommendations.
Here is Java code that needs to communicate with PHP server
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Newtonsoft.Json;
using MyBuddyRide_APIs.Models;
using System;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using SortApp.ChatService;
using MyBuddyRide_APIs.Helper_Snippets;
using System.Data.Entity;
using MyBuddyRide_APIs.Enums;
using System.Collections.Generic;
namespace MyBuddyRide_APIs.ChatService
{
[HubName("brHub")]
public class PrivateChatHub : Hub
{
private MBRDbContext db = new MBRDbContext();
#region Internal Calls
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnReconnected()
{
return base.OnReconnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string connectionId = this.Context.ConnectionId;
User user = this.db.Users.Where(s => s.ConnectionId == connectionId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = null;
this.db.SaveChanges();
}
else
{
var driver = this.db.Driver.Where(s => s.ConnectionId == connectionId).FirstOrDefault();
if (driver != null)
{
//get all the active vehicles, if any vehicle is not in progress, set vehicles status offiline
var veh = db.Vechicles.Where(s => s.Status == DriverStatus.InProgress || s.Status == DriverStatus.OnLine).FirstOrDefault();
if (veh != null)
{
if (veh.Status == DriverStatus.OnLine)
{
veh.Status = DriverStatus.OffLine;
RemoveDriver(driver.DriverId);
}
}
driver.ConnectionId = null;
this.db.SaveChanges();
}
}
return base.OnDisconnected(stopCalled);
}
#endregion
#region Rider Calls
[HubMethodName("goOnlineUser")]
public string GoOnlineUser(int userId)
{
try
{
if (userId > 0)
{
string connectionId = this.Context.ConnectionId;
User user = this.db.Users.Where(s => s.UserId == userId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = connectionId;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("goOfflineRider")]
public string GoOfflineRider(long riderId, string token)
{
try
{
if (riderId > 0)
{
var user = this.db.Users.Where(s => s.UserId == riderId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = null;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("getNearbyDriver")]
public string GetNearbyDriver(long userId, string token)
{
try
{
if (userId > 0 && token != null)
{
var user = db.Users.Where(s => s.UserId == userId && s.Token == token).FirstOrDefault();
if (user != null)
{
//get all the online drivers's location
var locations = db.Driver.Where(s => !s.InRide && s.ConnectionId != null && s.Vehicles.Where(e => e.Status == DriverStatus.OnLine).FirstOrDefault() != null).Select(s => new DriverLocationUpdate
{
bearing = s.Bearing,
driverId = s.DriverId,
lat = s.Latitude,
lon = s.Longitude
}).ToList();
return JsonConvert.SerializeObject(new HubResponse()
{
data = locations
});
}
else
{
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid User"
});
}
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Driver Calls
[HubMethodName("goOnlineDriver")]
public string GoOnlineDriver(long driverId, int vehicleId = 0)
{
try
{
if (driverId > 0)
{
string connectionId = this.Context.ConnectionId;
var user = this.db.Driver.Where(s => s.DriverId == driverId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = connectionId;
db.Entry(user).State = EntityState.Modified;
if (vehicleId > 0)
{
//check if any vehicle was not in progress, then make it online
var veh = db.Vechicles.Where(s => s.VehicleId == vehicleId && s.Status != DriverStatus.InProgress).FirstOrDefault();
if (veh != null)
{
veh.Status = DriverStatus.OnLine;
}
}
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("updateLocation")]
public string UpdateDriverLocation(long driverId, int vehicleId, double latitude = 0.0, double longitude = 0.0, double bearing = 0.0)
{
try
{
if (driverId > 0 && vehicleId > 0)
{
var user = this.db.Driver.Where(s => s.DriverId == driverId && s.Vehicles.Where(x=>x.VehicleId == vehicleId).FirstOrDefault()!=null).FirstOrDefault();
if (user != null)
{
user.Latitude = latitude;
user.Longitude = longitude;
user.Bearing = bearing;
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
//notify all the users who are not in ride
NewDriverLocation(new DriverLocationUpdate
{
driverId = user.DriverId,
bearing = bearing,
lat = latitude,
lon = longitude
});
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("goOfflineDriver")]
public string GoOfflineDriver(long driverId, int vehicleId = 0)
{
try
{
if (driverId > 0)
{
var user = this.db.Driver.Where(s => s.DriverId == driverId).FirstOrDefault();
if (user != null)
{
user.ConnectionId = null;
db.Entry(user).State = EntityState.Modified;
if (vehicleId > 0)
{
//put the online vehicle offline
var veh = db.Vechicles.Where(s => s.VehicleId == vehicleId && s.Status == DriverStatus.OnLine).FirstOrDefault();
if (veh != null)
{
veh.Status = DriverStatus.OffLine;
RemoveDriver(driverId);
}
}
db.SaveChanges();
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Chat Calls
[HubMethodName("getAllChats")]
public string GetAllChats(int rideId)
{
try
{
var ride = db.Rides.Where(s => s.RideId == rideId).FirstOrDefault();
if (ride == null)
{
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "Unknows Ride!"
});
}
var resp = db.PrivateChats.AsNoTracking().Where(e => e.Ride.RideId == rideId).AsEnumerable().Select(s => new HubChatMessage
{
message = s.Message,
rideId = rideId,
datetime = s.Time.ToString("MM/dd/yyyy HH:mm"),
sender = s.Sender
}).ToList();
HubResponse hubResponse = new HubResponse
{
data = resp
};
return JsonConvert.SerializeObject(hubResponse);
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
[HubMethodName("sendMessage")]
public string SendMessage(int rideId, string sender, string message, string datetime)
{
try
{
var ride = db.Rides.Include("User").Include("Driver").Where(s => s.RideId == rideId).FirstOrDefault();
if (ride != null)
{
if (ride.User == null || ride.Driver == null)
{
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "Invalid Ride Session!"
});
}
//receiver
string connectionId = null;
if (sender == "rider")
{
connectionId = ride.Driver.ConnectionId;
}
else
{
connectionId = ride.User.ConnectionId;
}
var newMessage = new HubChatMessage
{
datetime = datetime,
message = message,
sender = sender,
rideId = rideId
};
var privateChatMessage = new PrivateChatMessage
{
Message = message,
Time = DateTime.ParseExact(datetime, "MM/dd/yyyy HH:mm", CultureInfo.InvariantCulture),
Sender = sender,
Ride = ride
};
db.PrivateChats.Add(privateChatMessage);
db.SaveChanges();
if (connectionId != null)
{
//call client side method.s
NewMessage(connectionId, newMessage);
}
else
{
if (sender != "rider")
{
//send push
SendPushNotifications push = new SendPushNotifications();
push.NotifyPerson(ride.User.UserId, message, "New Message", newMessage);
}
else
{
//send push
SendPushNotifications push = new SendPushNotifications();
push.NotifyDriver(ride.Driver.DriverId, message, "New Message", newMessage);
}
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
message = "message sent"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid message"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Ride Session
[HubMethodName("updateCaptainLocation")] //Captain's location who accepted the request will sync his location to rider
public string UpdateCaptainLocation(long rideId, double latitude = 0.0, double longitude = 0.0, double bearing = 0.0)
{
try
{
if (rideId > 0)
{
var userConnId = db.Rides.Where(s => s.RideId == rideId).Select(s => new
{
s.Driver.DriverId,
s.User.ConnectionId
}).FirstOrDefault();
if (userConnId != null)
{
if (userConnId.ConnectionId != null)
{
//notify rider
NewCaptianLocation(userConnId.ConnectionId, new DriverLocationUpdate
{
driverId = userConnId.DriverId,
bearing = bearing,
lat = latitude,
lon = longitude
});
}
return JsonConvert.SerializeObject(new HubResponse());
}
return JsonConvert.SerializeObject(new HubResponse()
{
status = false,
message = "unable to update status"
});
}
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = "invalid userId"
});
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return JsonConvert.SerializeObject((object)new HubResponse()
{
status = false,
message = ("some error occured!: " + ex.Message),
data = (object)ex.InnerException
});
}
}
#endregion
#region Client Side Invocations
private void NewMessage(string connectionId, HubChatMessage newMessage)
{
Clients.Client(connectionId).newMessage(JsonConvert.SerializeObject(newMessage));
}
//notify all the online users
private void NewDriverLocation(DriverLocationUpdate location)
{
var onlineUsers = db.Users.Where(s => s.ConnectionId != null && !s.InRide).Select(s => s.ConnectionId).ToList();
if (onlineUsers.Count > 0)
{
Clients.Clients(onlineUsers).newDriverLocation(JsonConvert.SerializeObject(location));
}
}
//notify the rider about his captian location.
private void NewCaptianLocation(string riderConnectionId, DriverLocationUpdate location)
{
Clients.Client(riderConnectionId).newCaptainLocation(JsonConvert.SerializeObject(location));
}
//notify users to remove driver from map as he's offline.
private void RemoveDriver(long driverId)
{
var onlineUsers = db.Users.Where(s => s.ConnectionId != null && !s.InRide).Select(s => s.ConnectionId).ToList();
if (onlineUsers.Count > 0)
{
Clients.Clients(onlineUsers).removeDriver(JsonConvert.SerializeObject(new
{
driverId = driverId
}
));
}
}
#endregion
#region Controller Helpers
/// <summary>
/// Helper function for Ride controller to remove the driver who have accepted the ride request
/// This pirtucular driver should not send his location to all users except the one who have requested him.
/// </summary>
/// <param name="driverId"></param>
/// <param name="onlineUsers"></param>
public static void RemoveDriverWhenInRide(long driverId,List<string> onlineUsers)
{
if (onlineUsers.Count > 0)
{
var hub = GlobalHost.ConnectionManager.GetHubContext<PrivateChatHub>();
hub.Clients.Clients(onlineUsers).removeDriver(JsonConvert.SerializeObject(new
{
driverId = driverId
}
));
}
}
#endregion
}
}
I use Yii2-advanced-app(2.0.15) and i need to do the logon operation with OTP.
With the cell number and password, everything is correct and the cookie is correct but when I use an opt, no value is created for the cookie.
My ajax code:
$("#m-sendCode__form-submit").click(function() {
$(this).attr('disabled','true');
let mobile = $('#mobile').val();
let csrfToken = $('meta[name="csrf-token"]').attr("content");
let rememberMe = $("#remember2").prop('checked');
// console.log(rememberMe);
$.ajax({
url: '/loginbysms',
method: 'POST',
data: {
_csrfFrontend: csrfToken,
phone: phone,
rememberMe: rememberMe
},
timeout: 6000
})
.done(function(data) {
let response = JSON.parse(data);
// console.log(data);
if (response.sent === 1){
$.ajax({
url: '/loginbysms',
method: 'POST',
data: {
_csrfFrontend: csrfToken,
verify: verify,
// rememberMe: rememberMe
},
})
.done(function(data) {
let s = JSON.parse(data);
if (s.status === 1){
window.location.href = '/';
}
});
}
})
.fail(function(error)){
console.log(error);
});
});
And my controller is:
public function actionLoginbysms()
{
$dataAjax = Yii::$app->request->post();
$session = Yii::$app->session;
if(isset($dataAjax)) {
if (isset($dataAjax['phone']) && !empty($dataAjax['phone'])) {
$phone = $dataAjax['phone'];
$user = User::findByPhone2($phone);
$sendSMS = new SendSMS();
if ($sendSMS->SendSMS($user->user_otp, $phone)) {
echo json_encode(['sent' => 1]);
exit;
} else {
echo json_encode(['sent' => 0]);
exit;
}
}
if(isset($dataAjax['verify]) && !empty($dataAjax['verfy'])){
$authorizedUser = User::findByOtp($session-
>get('user_phone'), $dataAjax['verify']);
if (isset($authorizedUser) && !empty($authorizedUser)) {
Yii::$app->user->login($authorizedUser, 3600 * 24 *
30)
echo json_encode(['status' => 1]);
exit;
}
}
}
}
When everything is true and the code is sent correctly by the user, the user enters the home page correctly but no value for the cookie is saved.
Please tell me the mistake.
The controller should be changed as follows:
public function actionLoginbysms()
{
$dataAjax = Yii::$app->request->post();
$session = Yii::$app->session;
if(Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
if (isset($dataAjax['phone']) && !empty($dataAjax['phone'])) {
$mobile = $dataAjax['phone'];
$user = User::findByPhone2($phone);
if ($user) {
unset($dataAjax['phone']);
$numbers = range(10000, 99999);
shuffle($numbers);
$session->set('user_phone', $phone);
if (isset($dataAjax['rememberMe']) && !empty($dataAjax['rememberMe'])
&& ($dataAjax['rememberMe'] == true)) {
$session->set('rememberMe', 'yes');
unset($dataAjax['rememberMe']);
}
$user->user_otp = $numbers[0];
$user->save();
try {
$sendSMS = new SendSMS();
$sendSMS->SendSMS($user->user_otp, $phone);
} catch (\Throwable $e) {
return [
'sent' => 0
];
}
return [
'sent' => 1
];
} else {
return ['user_not_found' => 1];
}
}
else if (isset($dataAjax['verify']) && !empty($dataAjax['verify'])) {
if ($session->isActive && $session->has('user_phone')) {
$authorizedUser = User::findByOtp($session->get('user_phone'), $dataAjax['verify']);
if (isset($authorizedUser) && !empty($authorizedUser)) {
unset($dataAjax['verify']);
$session->remove('user_phone');
$authorizedUser->user_otp = '';
$authorizedUser->save();
if(Yii::$app->user->login($authorizedUser, 3600 * 24 * 30)) {
return ['authenticationSuccess' => 1];
}
}
}
return ['authenticationSuccess' => 0];
}
}
}
As #rob006 said, we should not use exit.
With the help of Yii::#app->response->format = Response::FORMAT_JSON, everything works fine
I need to implement MinecraftQuery's class (https://github.com/xPaw/PHP-Minecraft-Query/blob/master/MinecraftQuery.class.php)
So far I have the PHP side working.
This resides in HomeController.
public function mcQuery($ip, $port)
{
$Query = new MinecraftQuery();
try
{
$host = $this->getHost($ip, $port);
$Query->Connect( $host["ip"], $host["port"] );
return $Query;
}
catch( MinecraftQueryException $e )
{
return false;
}
}
public function getHost($address, $port)
{
$result = dns_get_record("_minecraft._tcp.$address", DNS_SRV);
if ($result) {
$priority = 0;
$valid = 0;
foreach ($result as $v) {
$type = $v['type'];
$pri = $v['pri'];
$targetPort = $v['port'];
$target = $v['target'];
if ($type=="SRV") {
if ($valid==0 || $pri <= $priority) {
$address = $target;
$port = $targetPort;
$priority = $pri;
$valid = 1;
}
}
}
} else {
$address = gethostbyname($address.'.');
if(filter_var($address, FILTER_VALIDATE_IP) != $address) {
throw new \Exception("Not a valid ip address: " . $address . "\n");
}
}
return [ 'ip' => $address, 'port' => $port ];
}
}
This works - by itself anyways, but the next problem is actually returning the response to the route so I can use it via javascript
This is all I have...
Route::get('/servers', function(){
$ip = Input::get('ip');
$port = Input::get('port');
$home = App::make('HomeController');
$info = $home->mcQuery($ip, $port);
return $info
});
This returns an error, though. When I visit http://mysite.dev/servers?ip=lorem.someip.com&port=25564
I get...
The Response content must be a string or object implementing __toString(), "object" given.
However, doing a dd($info) instead returns...
object(MinecraftQuery)#130 (3) {
["Socket":"MinecraftQuery":private]=>
resource(48) of type (Unknown)
["Players":"MinecraftQuery":private]=>
NULL
["Info":"MinecraftQuery":private]=>
array(10) {
["HostName"]=>
string(37) "Some Name!"
["GameType"]=>
string(3) "SMP"
["Version"]=>
string(5) "1.7.9"
// ...
}
}
I've never seen an array with :private before and Im assuming that is apart of the problem. But this is the object I am trying to return.
Oh, and for the last bit, this is how I'm trying to get this data..
serversObj.each(function(index, el) {
// serverObj is like 4 divs
var serverIp = $(this).data('ip');
var serverPort = $(this).data('port');
var serverStatus = $(this).find('.status');
$.ajax({
url: '/servers',
type: 'GET',
data: {ip: serverIp, port: serverPort},
})
.done(function(data) {
console.log("success: \n" + data);
})
.fail(function(ex) {
console.log(ex);
return false;
});
});
But of course returns a 500 server error unless I do dd() in the route instead.
So how can I get the correct data to return?
You may try this:
return Response::json($info->GetInfo());
In the done method try:
done(function(data) {
var object = $.parseJSON(data);
console.log(object);
})
Looking at the class, it seems that you want the GetInfo() method. This example should work:
$Query = new MinecraftQuery();
$host = $this->getHost($ip, $port);
$Query->Connect( $host["ip"], $host["port"] );
var_dump($Query->GetInfo());