Monday, August 28, 2017

Using Google Translation API For Indian Language with PHP

Google translation API works good for Indian languages, if we type in proper language. For example, if you pass following in API. 

कैसे हो

Then it will translate properly to 

how are you

But if you pass it in english, like this.

"KAISE HO"

Then it will send the same text back but it only detects language. So it does not work properly. So what shall the possible solution for it. 

Here is how I worked out in one of my old project.

First I used Google input tools API to convert the input to regional language. 

So steps if First

KAISE HO is converted to

कैसे हो

and then pass it in translation API to convert it to English. Here is the code for the same.

$translatedText = "KAISE HO";
$detectedSourceLanguage = "hi";

$url ='https://www.google.com/inputtools/request?text='.urlencode($translatedText).'&ime=transliteration_en_'.urlencode($detectedSourceLanguage);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_PROXYPORT,3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
$response = curl_exec($ch);
$output = json_decode($response);
$resultText = '';

if($output[0] == 'SUCCESS'){
if(isset($output[1])){
if(isset($output[1][0])){
if(isset($output[1][0][1])){
$resultText = $output[1][0][1][0];
}
}
}
}

if($resultText != ''){
$url ='https://translation.googleapis.com/language/translate/v2';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"q=".urlencode($resultText)."&target=en&key=YOUR_API");

curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_PROXYPORT,3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
$response = curl_exec($ch);
$output = json_decode($response);
$resultText = $output->data->translations[0]->translatedText;
}

Hope this helps you in proper translation.

Friday, August 25, 2017

Laravel Dynamic Mail Configuration With Values From Database

In Laravel we have config folder, where we have different files like app.php and mail.php etc where we can configure settings. For example for sending mail from Laravel application, we have to configure mail.php file with configs like mail driver, mail user name etc. This will work good for static information. But what if you want to override and use your own settings from database at run time.

For example you have different mail configurations for each users and you want to set it when user is logged in. I this blog I am going to show you how you can do this in Laravel 5.x

For example you have mail_settings table where you are saving mails settings for each user. Now when user is logged in we have to get settings of logged in user and set it in config. This is how you can do that.

We know that all laravel controller extends the Controller. So what you can do is in constructor of Controller.php file, you can set the mail settings.

Here is how you can do this.
public function __construct()
{
$this->middleware(function ($request, $next) {
if(Auth::user()){
//So user is logged in.
if(Auth::user()->parent_id != null){
//Get the mail settings.
$settings = MailSettings::where('user_id',Auth::user()->parent_id)->first();

if(isset($settings)){
//settting up mail config for the logged in user.
config( ['mail' => ['from' => ['address' => $settings->from_email, 'name' => $settings->from_name], 'host'=>$settings->mail_host, 'port'=>$settings->mail_port, 'username'=>$settings->mail_username,  'password'=>$settings->mail_password, 'encryption'=>$settings->mail_encryption, 'driver'=>$settings->mail_driver]]);
}
}
}
return $next($request);
});

}

So as you can see we are getting mail settings from table for logged in user and setting up it in config. This way you can override anything in the default config and set it run time.

Monday, August 7, 2017

Integrating GetStream with Laravel using stream-laravel for Real Time Notifications

Hello,

After a long time I am publishing a blog post. I am sorry to all my readers for not publishing blog for longer time. In this blog I am going to explain how you can have real time notifications in your laravel application using GetStream.io.

I will not go in installation details as it's very well documented on their Github page. You can refer it here.

GetStream/steam-laravel

After you have installed it and configured service provider. First thing you have to do is create table for notifications. For that create migration add following code to it.

Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->index();
$table->string('name');
$table->string('message');
$table->string('link');
$table->timestamps();
});

Now create a model with name Notifications and add following code to it.


namespace App\Http\Models;

use App\User;
use Illuminate\Database\Eloquent\Model;

class Notifications extends Model
{
    //
    use \GetStream\StreamLaravel\Eloquent\ActivityTrait;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'notifications';

    protected $fillable = ['name', 'message','link'];
   
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'user_id' => 'int',
    ];
    /**
     * Get the user that owns the task.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    /**
     * Stream: Add extra activity data - task name, and user's display name:
     */
    public function activityExtraData()
    {
        return array('name'=>$this->name, 'message' => $this->message, 'link'=> $this->link);
    }
   /**
    * Stream: Change activity verb to 'created':
    */
    public function activityVerb()
    {
        return 'created';
    }

}


Now open your user model and add following code to it.

public function notifications()
    {
        return $this->hasMany(Notifications::class);
    }

So now we have notifications table setup and it's linked to user with hasMany relationship. Now next we will show how you can create notification.

$userObject->notifications()->create([
'name' => "NOTIFICATION_NAME",
'message' => 'NOTIFICATION_MESSAGE',
'link' => 'NOTIFICATION_LINK'           
]);

Here userObject is the object of user for whom you want to create notification. Now next we will show how to get all the notifications and show it user. For this we are going to use AngularJs. 

We are using client side library of GetStream.io you can download it from following link.


For this first of all we have to get token and that can be generated only from server side code. So create an API and call it from AngularJs controller. Here is the API code.

public function getStreamToken(){
$feed = \FeedManager::getUserFeed(Auth::user()->id);
$token = $feed->getToken();

return Response::json(array("success"=>true,"token"=>$token,"user_id"=>Auth::user()->id));
}

Now as soon as we get token, next you have to connect to client and get user feeds and register for push notifications. Here is the code for the same.

var client = stream.connect('YOUR_API_KEY', null, 'YOUR_APP_ID');
$scope.user = client.feed('user', $scope.user_id, $scope.token);

function successCallback() {
console.log('now listening to changes in realtime');
}

function failCallback(data) {
console.log(data);
}

$scope.user.subscribe($scope.gotNotification).then(successCallback, failCallback);    

$scope.user.get({limit:10, offset:$scope.offset}, $scope.gotUserActivities);

So above code will register you for the push notification and will get all your notifications. Now you have to display it using HTML and CSS as per your wish. 

For showing new notification, you can use below code in gotNotification function.

$.bootstrapGrowl(data.new[0].name + ' ' + data.new[0].message, { type: 'success' });

It will show nice pop up on screen.