Ejemplo n.º 1
0
 /**
  * Display a listing of chats.
  *
  * @param int|null $lastChatId Last chat ID
  * @param int $size Response size
  * @return Response
  */
 public function getList($lastChatId = null, $size = 20)
 {
     $list = array();
     $ids = array();
     ChatMember::where('user_id', Auth::user()->id)->get()->each(function ($member) use(&$ids) {
         $ids[] = $member->chat_id;
     });
     if (count($ids) > 0) {
         $size = (int) $size > 0 ? (int) $size : 20;
         $unread = array();
         MessageUnread::whereRaw('user_id = ? and message_id not in (select b.message_id from messages_removed b where b.chat_id = chat_id)', array(Auth::user()->id))->get()->each(function ($message) use(&$unread) {
             $unread[] = $message->chat_id;
         });
         $query = 'select * from chats a where a.id in (' . implode(', ', $ids) . ') ' . (($lastChatId = (int) $lastChatId) > 0 ? 'and a.id < ' . $lastChatId . ' ' : '') . 'and (select count(b.id) from messages b where b.chat_id=a.id ' . 'and b.id not in (select c.message_id from messages_removed c where c.chat_id = a.id) ' . 'and b.id > coalesce((select d.message_id from chats_cleared d where d.user_id = ' . Auth::user()->id . ' and d.chat_id = a.id), 0)) > 0 ' . 'order by a.timestamp desc limit ' . $size;
         $result = DB::select($query);
         foreach ($result as $array) {
             $chat = new Chat((array) $array);
             $data = array('chat_id' => $chat->id, 'owner_id' => $chat->owner_id, 'topic' => $chat->topic, 'timestamp' => $chat->getTimestamp(), 'users' => $chat->getUsersArray());
             if (in_array($chat->id, $unread)) {
                 $data['unread'] = true;
             }
             if (!is_null($lastMessage = $chat->getLastMessage())) {
                 $data['last_message'] = $lastMessage->getAsArray();
             }
             $list[] = $data;
         }
     }
     return $this->respond($list);
 }