/
MessagesController.php
491 lines (449 loc) · 15.2 KB
/
MessagesController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
<?php
namespace Chatify\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Response;
use App\Models\ChMessage as Message;
use App\Models\ChFavorite as Favorite;
use Chatify\Facades\ChatifyMessenger as Chatify;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Request as FacadesRequest;
use Illuminate\Support\Str;
class MessagesController extends Controller
{
/**
* Authinticate the connection for pusher
*
* @param Request $request
* @return void
*/
public function pusherAuth(Request $request)
{
// Auth data
$authData = json_encode([
'user_id' => Auth::user()->id,
'user_info' => [
'name' => Auth::user()->name
]
]);
// check if user authorized
if (Auth::check()) {
return Chatify::pusherAuth(
$request['channel_name'],
$request['socket_id'],
$authData
);
}
// if not authorized
return new Response('Unauthorized', 401);
}
/**
* Returning the view of the app with the required data.
*
* @param int $id
* @return void
*/
public function index( $id = null)
{
$routeName= FacadesRequest::route()->getName();
$route = (in_array($routeName, ['user', config('chatify.routes.prefix')]))
? 'user'
: $routeName;
// prepare id
return view('Chatify::pages.app', [
'id' => ($id == null) ? 0 : $route . '_' . $id,
'route' => $route,
'messengerColor' => Auth::user()->messenger_color,
'dark_mode' => Auth::user()->dark_mode < 1 ? 'light' : 'dark',
]);
}
/**
* Fetch data by id for (user/group)
*
* @param Request $request
* @return collection
*/
public function idFetchData(Request $request)
{
// Favorite
$favorite = Chatify::inFavorite($request['id']);
// User data
if ($request['type'] == 'user') {
$fetch = User::where('id', $request['id'])->first();
}
// send the response
return Response::json([
'favorite' => $favorite,
'fetch' => $fetch,
'user_avatar' => asset('/storage/' . config('chatify.user_avatar.folder') . '/' . $fetch->avatar),
]);
}
/**
* This method to make a links for the attachments
* to be downloadable.
*
* @param string $fileName
* @return void
*/
public function download($fileName)
{
$path = storage_path() . '/app/public/' . config('chatify.attachments.folder') . '/' . $fileName;
if (file_exists($path)) {
return Response::download($path, $fileName);
} else {
return abort(404, "Sorry, File does not exist in our server or may have been deleted!");
}
}
/**
* Send a message to database
*
* @param Request $request
* @return JSON response
*/
public function send(Request $request)
{
// default variables
$error = (object)[
'status' => 0,
'message' => null
];
$attachment = null;
$attachment_title = null;
// if there is attachment [file]
if ($request->hasFile('file')) {
// allowed extensions
$allowed_images = Chatify::getAllowedImages();
$allowed_files = Chatify::getAllowedFiles();
$allowed = array_merge($allowed_images, $allowed_files);
$file = $request->file('file');
// if size less than 150MB
if ($file->getSize() < 150000000) {
if (in_array($file->getClientOriginalExtension(), $allowed)) {
// get attachment name
$attachment_title = $file->getClientOriginalName();
// upload attachment and store the new name
$attachment = Str::uuid() . "." . $file->getClientOriginalExtension();
$file->storeAs("public/" . config('chatify.attachments.folder'), $attachment);
} else {
$error->status = 1;
$error->message = "File extension not allowed!";
}
} else {
$error->status = 1;
$error->message = "File extension not allowed!";
}
}
if (!$error->status) {
// send to database
$messageID = mt_rand(9, 999999999) + time();
Chatify::newMessage([
'id' => $messageID,
'type' => $request['type'],
'from_id' => Auth::user()->id,
'to_id' => $request['id'],
'body' => htmlentities(trim($request['message']), ENT_QUOTES, 'UTF-8'),
'attachment' => ($attachment) ? json_encode((object)[
'new_name' => $attachment,
'old_name' => htmlentities(trim($attachment_title), ENT_QUOTES, 'UTF-8'),
]) : null,
]);
// fetch message to send it with the response
$messageData = Chatify::fetchMessage($messageID);
// send to user using pusher
Chatify::push('private-chatify', 'messaging', [
'from_id' => Auth::user()->id,
'to_id' => $request['id'],
'message' => Chatify::messageCard($messageData, 'default')
]);
}
// send the response
return Response::json([
'status' => '200',
'error' => $error,
'message' => Chatify::messageCard(@$messageData),
'tempID' => $request['temporaryMsgId'],
]);
}
/**
* fetch [user/group] messages from database
*
* @param Request $request
* @return JSON response
*/
public function fetch(Request $request)
{
// messages variable
$allMessages = null;
// fetch messages
$query = Chatify::fetchMessagesQuery($request['id'])->orderBy('created_at', 'asc');
$messages = $query->get();
// if there is a messages
if ($query->count() > 0) {
foreach ($messages as $message) {
$allMessages .= Chatify::messageCard(
Chatify::fetchMessage($message->id)
);
}
// send the response
return Response::json([
'count' => $query->count(),
'messages' => $allMessages,
]);
}
// send the response
return Response::json([
'count' => $query->count(),
'messages' => '<p class="message-hint center-el"><span>Say \'hi\' and start messaging</span></p>',
]);
}
/**
* Make messages as seen
*
* @param Request $request
* @return void
*/
public function seen(Request $request)
{
// make as seen
$seen = Chatify::makeSeen($request['id']);
// send the response
return Response::json([
'status' => $seen,
], 200);
}
/**
* Get contacts list
*
* @param Request $request
* @return JSON response
*/
public function getContacts(Request $request)
{
// get all users that received/sent message from/to [Auth user]
$users = Message::join('users', function ($join) {
$join->on('ch_messages.from_id', '=', 'users.id')
->orOn('ch_messages.to_id', '=', 'users.id');
})
->where(function ($q) {
$q->where('ch_messages.from_id', Auth::user()->id)
->orWhere('ch_messages.to_id', Auth::user()->id);
})
->orderBy('ch_messages.created_at', 'desc')
->get()
->unique('id');
$contacts = '<p class="message-hint center-el"><span>Your contact list is empty</span></p>';
$users = $users->where('id','!=',Auth::user()->id);
if ($users->count() > 0) {
// fetch contacts
$contacts = '';
foreach ($users as $user) {
if ($user->id != Auth::user()->id) {
// Get user data
$userCollection = User::where('id', $user->id)->first();
$contacts .= Chatify::getContactItem($request['messenger_id'], $userCollection);
}
}
}
// send the response
return Response::json([
'contacts' => $contacts,
], 200);
}
/**
* Update user's list item data
*
* @param Request $request
* @return JSON response
*/
public function updateContactItem(Request $request)
{
// Get user data
$userCollection = User::where('id', $request['user_id'])->first();
$contactItem = Chatify::getContactItem($request['messenger_id'], $userCollection);
// send the response
return Response::json([
'contactItem' => $contactItem,
], 200);
}
/**
* Put a user in the favorites list
*
* @param Request $request
* @return void
*/
public function favorite(Request $request)
{
// check action [star/unstar]
if (Chatify::inFavorite($request['user_id'])) {
// UnStar
Chatify::makeInFavorite($request['user_id'], 0);
$status = 0;
} else {
// Star
Chatify::makeInFavorite($request['user_id'], 1);
$status = 1;
}
// send the response
return Response::json([
'status' => @$status,
], 200);
}
/**
* Get favorites list
*
* @param Request $request
* @return void
*/
public function getFavorites(Request $request)
{
$favoritesList = null;
$favorites = Favorite::where('user_id', Auth::user()->id);
foreach ($favorites->get() as $favorite) {
// get user data
$user = User::where('id', $favorite->favorite_id)->first();
$favoritesList .= view('Chatify::layouts.favorite', [
'user' => $user,
]);
}
// send the response
return Response::json([
'count' => $favorites->count(),
'favorites' => $favorites->count() > 0
? $favoritesList
: 0,
], 200);
}
/**
* Search in messenger
*
* @param Request $request
* @return void
*/
public function search(Request $request)
{
$getRecords = null;
$input = trim(filter_var($request['input'], FILTER_SANITIZE_STRING));
$records = User::where('name', 'LIKE', "%{$input}%");
foreach ($records->get() as $record) {
$getRecords .= view('Chatify::layouts.listItem', [
'get' => 'search_item',
'type' => 'user',
'user' => $record,
])->render();
}
// send the response
return Response::json([
'records' => $records->count() > 0
? $getRecords
: '<p class="message-hint center-el"><span>Nothing to show.</span></p>',
'addData' => 'html'
], 200);
}
/**
* Get shared photos
*
* @param Request $request
* @return void
*/
public function sharedPhotos(Request $request)
{
$shared = Chatify::getSharedPhotos($request['user_id']);
$sharedPhotos = null;
// shared with its template
for ($i = 0; $i < count($shared); $i++) {
$sharedPhotos .= view('Chatify::layouts.listItem', [
'get' => 'sharedPhoto',
'image' => asset('storage/attachments/' . $shared[$i]),
])->render();
}
// send the response
return Response::json([
'shared' => count($shared) > 0 ? $sharedPhotos : '<p class="message-hint"><span>Nothing shared yet</span></p>',
], 200);
}
/**
* Delete conversation
*
* @param Request $request
* @return void
*/
public function deleteConversation(Request $request)
{
// delete
$delete = Chatify::deleteConversation($request['id']);
// send the response
return Response::json([
'deleted' => $delete ? 1 : 0,
], 200);
}
public function updateSettings(Request $request)
{
$msg = null;
$error = $success = 0;
// dark mode
if ($request['dark_mode']) {
$request['dark_mode'] == "dark"
? User::where('id', Auth::user()->id)->update(['dark_mode' => 1]) // Make Dark
: User::where('id', Auth::user()->id)->update(['dark_mode' => 0]); // Make Light
}
// If messenger color selected
if ($request['messengerColor']) {
$messenger_color = explode('-', trim(filter_var($request['messengerColor'], FILTER_SANITIZE_STRING)));
$messenger_color = Chatify::getMessengerColors()[$messenger_color[1]];
User::where('id', Auth::user()->id)
->update(['messenger_color' => $messenger_color]);
}
// if there is a [file]
if ($request->hasFile('avatar')) {
// allowed extensions
$allowed_images = Chatify::getAllowedImages();
$file = $request->file('avatar');
// if size less than 150MB
if ($file->getSize() < 150000000) {
if (in_array($file->getClientOriginalExtension(), $allowed_images)) {
// delete the older one
if (Auth::user()->avatar != config('chatify.user_avatar.default')) {
$path = storage_path('app/public/' . config('chatify.user_avatar.folder') . '/' . Auth::user()->avatar);
if (file_exists($path)) {
@unlink($path);
}
}
// upload
$avatar = Str::uuid() . "." . $file->getClientOriginalExtension();
$update = User::where('id', Auth::user()->id)->update(['avatar' => $avatar]);
$file->storeAs("public/" . config('chatify.user_avatar.folder'), $avatar);
$success = $update ? 1 : 0;
} else {
$msg = "File extension not allowed!";
$error = 1;
}
} else {
$msg = "File extension not allowed!";
$error = 1;
}
}
// send the response
return Response::json([
'status' => $success ? 1 : 0,
'error' => $error ? 1 : 0,
'message' => $error ? $msg : 0,
], 200);
}
/**
* Set user's active status
*
* @param Request $request
* @return void
*/
public function setActiveStatus(Request $request)
{
$update = $request['status'] > 0
? User::where('id', $request['user_id'])->update(['active_status' => 1])
: User::where('id', $request['user_id'])->update(['active_status' => 0]);
// send the response
return Response::json([
'status' => $update,
], 200);
}
}