Webklex / laravel-imap

Laravel IMAP is an easy way to integrate both the native php-imap module and an extended custom imap protocol into your Laravel app.
https://www.php-imap.com
MIT License
641 stars 182 forks source link

How to use ->idle() method when trying to check for new messages through ajax request ? #420

Closed eXCom closed 3 years ago

eXCom commented 3 years ago

Im trying to check for new messages using ajax request. When im just trying to listen to new messages on backend only with php, everything works fine.

public function tracingNewMsg()
    {
        $client = MailIMAP::connection();
        $folder = $client->getFolderByPath('INBOX');
        $client->disconnect();
        $m = $folder->idle(function($message){
           $msg = $message->subject;
            dd($message->subject);
        },$timeout = 1200, $auto_reconnect = true);
    }

scr1

But if im trying to send ajax request from frontend to backend, my request is pending.

public function tracingNewMsg()
    {
        $client = MailIMAP::connection();
        $folder = $client->getFolderByPath('INBOX');
        $client->disconnect();
        $m = $folder->idle(function($message){
           $msg = $message->subject;
            return response()->json($msg);
        },$timeout = 1200, $auto_reconnect = true);
    }

scr2

I also tried

public function tracingNewMsg()
    {
        $client = MailIMAP::connection();
        $folder = $client->getFolderByPath('INBOX');
        $client->disconnect();
        return $folder->idle(function($message){
           $msg = $message->subject;
            return response()->json($msg);
        },$timeout = 1200, $auto_reconnect = true);
    }

Its the same, pending... Looks like ->idle() is just infinitely repeating itself, i would like to check for messages once and get a responce

Is there any way to achieve what im trying to do ?

Webklex commented 3 years ago

Hi @eXCom , many thanks for your question. The Folder::idle() command is exactly designed to do just this - idle and call the callback as soon as a new message arrives. Its not supposed to ever "finish"..

If you want to fetch new messages, you'll have to use the Folder::query() method - or implement a websocket and combine it with the idle method. Take a look at the implemented event / subscriber support https://www.php-imap.com/frameworks/laravel/events - they might help you as well :)

Best regards,

P.s.: if you have any questions regarding the core webklex/php-imap, please head over to the core repository https://github.com/Webklex/php-imap and create an new issue there.

eXCom commented 3 years ago

Thank you @Webklex very much for such a quick responce, i'll look into it!