Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 350
0.00% covered (danger)
0.00%
0 / 21
CRAP
0.00% covered (danger)
0.00%
0 / 1
ShortcutController
0.00% covered (danger)
0.00%
0 / 350
0.00% covered (danger)
0.00%
0 / 21
5852
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 index
0.00% covered (danger)
0.00%
0 / 41
0.00% covered (danger)
0.00%
0 / 1
72
 create
0.00% covered (danger)
0.00%
0 / 63
0.00% covered (danger)
0.00%
0 / 1
90
 update
0.00% covered (danger)
0.00%
0 / 86
0.00% covered (danger)
0.00%
0 / 1
156
 list
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 applyFilters
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 applyOrdering
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 applyPagination
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 details
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 delete
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 dispatchShortcutEvent
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 latest
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 duplicate
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 saveBrowserUsed
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 deleteShortcutVersion
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 rollbackToPreviousVersion
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
12
 getShorcutVersions
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 makeShareable
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 getShared
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
 mediaSize
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 deleteBulkFlycuts
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace App\Http\Controllers\v1;
4
5use App\Events\TrackingExtensionDeployEvent;
6use Illuminate\Support\Facades\Config;
7use Jenssegers\Agent\Agent;
8use Illuminate\Http\Request;
9use App\Http\Models\Shortcut;
10use App\Http\Models\Auth\User;
11use App\Http\Models\FlyCutUsage;
12use App\Traits\SubscriptionTrait;
13use Illuminate\Http\JsonResponse;
14use Illuminate\Support\Facades\DB;
15use Illuminate\Support\Facades\Log;
16use App\Http\Controllers\Controller;
17use App\Http\Models\ShortcutVersion;
18use App\Http\Models\ShortcutCategory;
19use Illuminate\Support\Facades\Cache;
20use App\Http\Models\Auth\BusinessUser;
21use App\Http\Models\ShortcutSharedLinks;
22use Illuminate\Support\Facades\Validator;
23use App\Http\Requests\ShortcutFormRequest;
24use App\Http\Requests\FlycutBulkDeleteRequest;
25use App\Http\Models\ShortcutSubCategoryLv1;
26use App\Http\Models\ShortcutSubCategoryLv2;
27use App\Http\Models\UserInfo;
28use App\Http\Services\StatisticsService;
29
30class ShortcutController extends Controller
31{
32    use SubscriptionTrait;
33
34    public function __construct(
35        protected StatisticsService $statisticsService,
36    ) {}
37
38    /**
39     * Get Shortcuts.
40     *
41     * @param Request $request
42     *
43     * @return JsonResponse
44     */
45    public function index(Request $request): JsonResponse
46    {
47        $query = $request->query('q');
48
49        if ($query === 'recently_used') {
50            $shortcuts = Shortcut::query()
51                ->whereNotNull('last_deployed_date')
52                ->orderByDesc('last_deployed_date')
53                ->limit(5)
54                ->get();
55
56            $user_id = $request->user()->getKey();
57            $user = User::find($user_id);
58            // Skip the code if $shortcuts already has 5 records
59            if ($shortcuts->count() === 5 || $user->recently_used_get_updated == true) {
60                return response()->json($shortcuts);
61            }
62
63            // If we this user still using the old way proceed using the old method and update the DB to use the new methond next time.
64
65            $records = FlyCutUsage::query()
66                ->select('shortcut_id', 'created_at')
67                ->where('user_id', $user_id)
68                ->orderBy('created_at', 'desc')
69                ->groupBy('shortcut_id')
70                ->limit(5)
71                ->get();
72
73            // Mark that we updated the user shortcuts get method.
74            if ($user) {
75                $user->recently_used_get_updated = true;
76                $user->save();
77            }
78
79            $shortcuts = [];
80            foreach ($records as $record) {
81                $shortcutId = $record->shortcut_id;
82                $shortcut = Shortcut::query()->where('_id', $shortcutId)->first();
83
84                if ($shortcut) {
85                    $formattedDate = $record->created_at->format('Y-m-d\TH:i:sP');
86                    $shortcut->last_deployed_date = $formattedDate;
87                    $shortcut->save();
88                    $shortcuts[] = $shortcut;
89                }
90            }
91        } elseif ($query === 'mostly_used') {
92            $shortcuts = Shortcut::query()
93                ->whereNotNull('flycutUsage_count')
94                ->orderBy('flycutUsage_count', 'desc')
95                ->limit(5)
96                ->get();
97        } else {
98            $shortcuts = Shortcut::query()
99                ->latest()
100                ->limit(5)
101                ->get();
102        }
103        return response()->json($shortcuts);
104    }
105
106    /**
107     * Creates a new shortcut
108     * @param ShortcutFormRequest $request
109     * @return JsonResponse
110     */
111    public function create(ShortcutFormRequest $request)
112    {
113        $data = $request->validated();
114        $user = $request->user();
115        $userId = $request->user()->getKey();
116        $data['user_id'] = $userId;
117        $data['version'] = 1;
118        $data['user_defined'] = true;
119        $isOnboarding = $data['onboarding'] ?? false;
120
121        $type = $request['type'];
122        $categoryId = $request['category_id'];
123
124        if (isset($type)) {
125            if ($type == 'sub_categories_lv2') {
126                $data['sub_categories_lv2_id'] = $categoryId;
127            } elseif ($type == 'sub_categories_lv1') {
128                $data['sub_categories_lv1_id'] = $categoryId;
129            } else {
130                $data['category_id'] = $categoryId;
131            }
132        }
133
134        $data['version_counts'] = 1;
135
136        $charactors_count = strlen(strip_tags($data['text']));
137        $words_count = str_word_count(strip_tags($data['text']));
138        $html_count = strlen(strip_tags($data['html']));
139
140        $data['charactors_count'] = $charactors_count;
141        $data['words_count'] = $words_count;
142        $data['html_count'] = $html_count;
143
144        $result = Shortcut::create($data);
145
146        $shortcutId = $result['_id'];
147
148        $mediaCount = $this->mediaSize($data['uploads']);
149
150        $browser_type = 'chrome';
151
152        if ($request->header('Browser-type')) {
153            $browser_type = strtolower($request->header('Browser-type'));
154        } elseif ($request->header('browser-type')) {
155            $browser_type = strtolower($request->header('browser-type'));
156        } elseif ($request->header('browser')) {
157            $browser_type = strtolower($request['browser']);
158        } elseif ($request['browser']) {
159            $browser_type = strtolower($request['browser']);
160        }
161
162        dispatch(function () use ($user, $userId, $charactors_count, $words_count, $html_count, $mediaCount, $data, $shortcutId, $isOnboarding, $result, $browser_type) {
163            // Create a flymessage version
164            $shortcutVersionHistory = new ShortcutVersion();
165            $statisticsData = [
166                'charactors_count' => $charactors_count,
167                'words_count' => $words_count,
168                'html_count' => $html_count,
169                'media_count' => $mediaCount,
170                'updated_at' => now(),
171            ];
172
173            $flymsg_details = array_merge($data, $statisticsData);
174            $versionHistoryData[1] = json_encode($flymsg_details, true);
175            $versionHistoryData['shortcut_id'] = $shortcutId;
176            $versionHistoryData['user_id'] = $userId;
177            $versionHistoryData['last_version_count'] = 1;
178            $versionHistoryData['current_version'] = 0;
179
180            $shortcutVersionHistory->fill($versionHistoryData);
181            $shortcutVersionHistory->push();
182
183            $this->dispatchShortcutEvent();
184
185            $this->saveBrowserUsed($userId);
186
187            if ($isOnboarding) {
188                $data = [
189                    'value' => $charactors_count,
190                    'shortcut_id' => $shortcutId,
191                    'executed_at' => config('romeo.frontend-base-url'),
192                    'tag' => 'total_char_by_a_FlyCut'
193                ];
194
195                event(new TrackingExtensionDeployEvent($user, $data, $result, $browser_type));
196            }
197        });
198
199        return response()->json($result);
200    }
201
202    public function update(ShortcutFormRequest $request, $shortcutId): JsonResponse
203    {
204        $data = $request->validated();
205        $userId = $request->user()->getKey();
206
207        $shortcutSearchArray = ['_id' => $shortcutId];
208        $searchArray = ['_id' => $request['category_id']];
209        $result = false;
210        $shortcut = Shortcut::find($shortcutId);
211
212        // Check if it's a category update or a Normal flycut update.
213        if (isset($request['category_level'])) {
214
215            if ($request['category_level'] == 0) {
216                $this->checkCategoriesCount($request);
217
218                $category = ShortcutCategory::where($searchArray)->first();
219                if ($category) {
220                    $object = Shortcut::find($shortcutId);
221                    $object->category_id = $request['category_id'];
222                    $object->sub_categories_lv1_id = null;
223                    $object->sub_categories_lv2_id = null;
224                    $object->version = $shortcut->version + 1;
225                    $object->save();
226                    $result = $object;
227                    $result['category_name'] = $category['name'];
228                }
229            }
230
231            if ($request['category_level'] == 1) {
232                $this->checkSubCategoriesCount($request);
233
234                $category = ShortcutSubCategoryLv1::where($searchArray)->first();
235                if ($category) {
236                    $object = Shortcut::find($shortcutId);
237                    $object->category_id = $category['category_id'];
238                    $object->sub_categories_lv1_id = $request['category_id'];
239                    $object->sub_categories_lv2_id = null;
240                    $object->version = $shortcut->version + 1;
241                    $object->save();
242                    $result = $object;
243                    $result['category_name'] = $category['name'];
244                }
245            }
246
247            if ($request['category_level'] == 2) {
248                $this->checkSubCategoriesCount($request);
249
250                $category = ShortcutSubCategoryLv2::where($searchArray)->first();
251                if ($category) {
252                    $object = Shortcut::find($shortcutId);
253                    $object->category_id = $category['category_id'];
254                    $object->sub_categories_lv1_id = $category['sub_categories_lv1_id'];
255                    $object->sub_categories_lv2_id = $request['category_id'];
256                    $object->version = $shortcut->version + 1;
257                    $object->save();
258                    $result = $object;
259                    $result['category_name'] = $category['name'];
260                }
261            }
262        } else {
263            $whereShortCutVersions = ['shortcut_id' => $shortcutId];
264            $versionData = ShortcutVersion::where($whereShortCutVersions)->first();
265
266            $data['version'] = $shortcut->version + 1;
267            $data['version_counts'] = (isset($shortcut->version_counts)) ? $shortcut->version_counts + 1 : 1;
268            $data['sub_categories_lv1'] = $request->get('sub_categories_lv1', '');
269            $data['sub_categories_lv2'] = $request->get('sub_categories_lv2', '');
270
271            $charactors_count = strlen(strip_tags($data['text']));
272            $words_count = str_word_count(strip_tags($data['text']));
273            $html_count = strlen(strip_tags($data['html']));
274
275            $data['charactors_count'] = $charactors_count;
276            $data['words_count'] = $words_count;
277            $data['html_count'] = $html_count;
278
279            $result = Shortcut::find($shortcutId);
280            try {
281                $result = $result->update($data);
282            } catch (\Throwable $th) {
283                Log::error('error', [
284                    'message' => $th->getMessage(),
285                    'file' => $th->getFile(),
286                    'line' => $th->getLine(),
287                ]);
288            }
289
290            // if (!empty($versionData)) {
291            //     $last_version_count = (isset($versionData->last_version_count)) ? $versionData->last_version_count + 1 : 1;
292
293            //     $statisticsData = array(
294            //         'charactors_count' => $charactors_count,
295            //         'words_count' => $words_count,
296            //         'html_count' => $html_count,
297            //         'media_count' => count($data['uploads']),
298            //         'updated_at' => now(),
299            //     );
300
301            //     $current_flycutData = array_merge($data, $statisticsData);
302            //     $current_flycutData = json_encode($current_flycutData, true);
303            //     $versionData = $versionData->toArray();
304            //     $versionData['last_version_count'] = $last_version_count;
305            //     if(!isset($versionData['current_version'])){
306            //         $versionData['current_version']=0;
307            //     }
308            //     $versionData['current_version'] = $versionData['current_version'] + 1;
309
310            //     array_push($versionData, $current_flycutData);
311
312            //     unset($versionData['_id']);
313            //     Log::info(['ShortcutVersion' => $versionData]);
314            //     $shortcut_versions = ShortcutVersion::where($whereShortCutVersions)->first();
315            //     try {
316            //         $shortcut_versions = $shortcut_versions->update($versionData);
317            //         Log::info(['ShortcutVersion' => $shortcut_versions]);
318            //     } catch (\Throwable $th) {
319            //         Log::error([
320            //             'message' => $th->getMessage(),
321            //             'file' => $th->getFile(),
322            //             'line' => $th->getLine(),
323            //         ]);
324            //     }
325            // } else {
326            $shortcutVersionHistory = new ShortcutVersion();
327            $statisticsData = array(
328                'charactors_count' => $charactors_count,
329                'words_count' => $words_count,
330                'html_count' => $html_count,
331                'media_count' => count($data['uploads']),
332            );
333            $flymsg_details = array_merge($data, $statisticsData);
334            $versionHistoryData[0] = json_encode($flymsg_details, true);
335            $versionHistoryData['shortcut_id'] = $shortcutId;
336            $versionHistoryData['user_id'] = $userId;
337            $versionHistoryData['last_version_count'] = 0;
338            if (isset($versionHistoryData['current_version'])) {
339                $versionHistoryData['current_version'] = $versionHistoryData['current_version'] + 1;
340            } else {
341                $versionHistoryData['current_version'] = 0;
342            }
343            $shortcutVersionHistory->fill($versionHistoryData);
344            $shortcutVersionHistory->push();
345            // }
346        }
347
348        $this->dispatchShortcutEvent();
349
350        $userId = $request->user()->getKey();
351        $this->saveBrowserUsed($userId);
352
353        if (isset($request['category_level'])) {
354            return response()->json($result);
355        } else {
356            return response()->json((bool) $result);
357        }
358    }
359
360    /**
361     * Filters a list of shortcuts by category id, shortcut and direction
362     * @param Request $request
363     * @return JsonResponse
364     */
365    // public function list(Request $request): JsonResponse
366    // {
367    //     try {
368    //         $limit = $request->get('limit');
369    //         $skip = $request->get('skip');
370    //         $orderBy = $request->get('order_by');
371
372    //         $result = Shortcut::when($request->anyFilled(['category_id', 'sub_categories_lv1_id', 'sub_categories_lv2_id']), function ($query) use ($request) {
373    //             $categoryId = $request->get('category_id');
374    //             $subCategoryLv1Id = $request->get('sub_categories_lv1_id');
375    //             $subCategoryLv2Id = $request->get('sub_categories_lv2_id');
376
377    //             if (filled($subCategoryLv2Id)) {
378    //                 return $query->where('sub_categories_lv2_id', $subCategoryLv2Id);
379    //             } else if (filled($subCategoryLv1Id)) {
380    //                 return $query->where('sub_categories_lv1_id', $subCategoryLv1Id);
381    //             } else if (filled($categoryId)) {
382    //                 return $query->where('category_id', $categoryId);
383    //             }
384    //         })->when($orderBy, function ($query, string $orderBy) {
385    //             $order = explode(",", $orderBy);
386    //             $query->orderBy($order[0], $order[1]);
387    //         }, function ($query) {
388    //             $query->latest();
389    //         })
390    //         ->when($skip, function ($query, $skip) {
391    //             $query->skip($skip);
392    //         })
393    //         ->when($limit, function ($query, $limit) {
394    //             $query->limit($limit);
395    //         })
396    //         ->get();
397
398    //         return response()->json($result);
399    //     } catch (\Throwable $th) {
400    //         Log::info([
401    //             'message' => $th->getMessage(),
402    //             'file' => $th->getFile(),
403    //             'line' => $th->getLine(),
404    //         ]);
405    //         return response()->json(["error" => "Something went wrong"]);
406    //     }
407    // }
408
409    public function list(Request $request): JsonResponse
410    {
411        try {
412            $query = Shortcut::where('user_id', $request->user()->id);
413
414            $this->applyFilters($query, $request);
415            $this->applyOrdering($query, $request->get('order_by'));
416            $this->applyPagination($query, $request->get('skip'), $request->get('limit'));
417
418            $result = $query->get();
419
420            return response()->json($result);
421        } catch (\Throwable $th) {
422            Log::error('error', [
423                'message' => $th->getMessage(),
424                'file' => $th->getFile(),
425                'line' => $th->getLine(),
426            ]);
427            return response()->json(["error" => "Something went wrong"], 500);
428        }
429    }
430
431    private function applyFilters($query, Request $request)
432    {
433        if ($request->filled('sub_categories_lv2_id')) {
434            $query->where('sub_categories_lv2_id', $request->get('sub_categories_lv2_id'));
435        } elseif ($request->filled('sub_categories_lv1_id')) {
436            $query->where('sub_categories_lv1_id', $request->get('sub_categories_lv1_id'));
437        } elseif ($request->filled('category_id')) {
438            $query->where('category_id', $request->get('category_id'));
439        }
440    }
441
442    private function applyOrdering($query, ?string $orderBy)
443    {
444        if ($orderBy) {
445            [$column, $direction] = explode(",", $orderBy);
446            $query->orderBy($column, $direction);
447        } else {
448            $query->latest();
449        }
450    }
451
452    private function applyPagination($query, ?int $skip, ?int $limit)
453    {
454        if ($skip !== null) {
455            $query->skip($skip);
456        }
457        if ($limit !== null) {
458            $query->limit($limit);
459        }
460    }
461
462    public function details(Request $request, $shortcutId)
463    {
464        $searchArray = ['_id' => $shortcutId];
465        $shortcut = Shortcut::with('category')->where($searchArray)->first();
466
467        //check if word counts and characters counts not found for the shortcut
468        if (!isset($shortcut->charactors_count) || ($shortcut->charactors_count == '')) {
469            $shortcut->charactors_count = strlen(strip_tags($shortcut->text));
470            $shortcut->words_count = str_word_count(strip_tags($shortcut->text));
471            $shortcut->html_count = strlen(strip_tags($shortcut->html));
472
473            $shortcut->save();
474        }
475
476        $shortcut['category_name'] = $shortcut->category->name;
477        unset($shortcut['category']);
478        $result = $shortcut;
479        return response()->json($result);
480    }
481
482    public function delete(Request $request, $shortcutId): JsonResponse
483    {
484        try {
485            ShortcutVersion::where('shortcut_id', $shortcutId)->delete();
486            $result = Shortcut::where('_id', $shortcutId)->delete();
487            $userId = $request->user()->getKey();
488
489            dispatch(function () use ($userId) {
490                $this->dispatchShortcutEvent();
491                Cache::forget('template_' . $userId);
492            });
493
494            return response()->json((bool)$result);
495        } catch (\Throwable $th) {
496            Log::error($th->getMessage());
497            return response()->json(false);
498        }
499    }
500
501    public function dispatchShortcutEvent()
502    {
503        $user = request()->user();
504        if ($user instanceof User) {
505            event(new \App\Events\User\ShortcutUpdated($user));
506        }
507        if ($user instanceof BusinessUser) {
508            event(new \App\Events\Business\ShortcutUpdated($user));
509        }
510    }
511
512    public function latest(Request $request): JsonResponse
513    {
514        $latest_shortcuts = Shortcut::with('category')->orderBy('created_at', 'desc')->paginate(20);
515
516        return response()->json($latest_shortcuts);
517    }
518
519    public function duplicate(Request $request, $id): JsonResponse
520    {
521        $flycut = Shortcut::findOrFail($id);
522
523        $new = $flycut->replicate(['created_at', 'updated_at', 'id']);
524        $new->shortcut = "{$flycut->shortcut} (Copy)";
525        $new->save();
526
527        return response()->json($new);
528    }
529
530    private function saveBrowserUsed($userId): void
531    {
532        $user = User::firstWhere('_id', $userId);
533        $userInfo = UserInfo::firstWhere('email', $user['email']);
534        $agent = new Agent();
535        $browser = $agent->browser();
536        $propertyValue = $browser;
537        if ($browser === 'Edge' || $browser === 'IE') {
538            $propertyValue = 'Edge';
539        }
540        $propertyValue = is_string($propertyValue) ? ucfirst($propertyValue) : '';
541        $userInfo->last_browser_used = $propertyValue;
542        $userInfo->save();
543    }
544
545    /**
546     * Function to delete the shortcut version
547     */
548    public function deleteShortcutVersion(Request $request, $shortcutId, $shortcut_version_index, $versionId = null): JsonResponse
549    {
550        //New
551        if (filled($versionId)) {
552            $result = ShortcutVersion::where('_id', $versionId)->delete();
553        } else {
554            //Old
555            $versionDataArray = [];
556
557            $whereShortCutVersions = ['shortcut_id' => $shortcutId];
558            $versionData = ShortcutVersion::where($whereShortCutVersions)->first();
559
560            if (!empty($versionData)) {
561                $versionDataArray = $versionData->toArray();
562
563                unset($versionDataArray['_id']);
564                unset($versionDataArray[$shortcut_version_index]);
565            }
566            $versionData->delete();
567
568            $versionData = new ShortcutVersion();
569            $versionData->fill($versionDataArray);
570            $result = $versionData->push();
571
572            $searchArray = ['_id' => $shortcutId];
573            $shortcut = Shortcut::where($searchArray)->first();
574            // $shortcut->version = $shortcut->version - 1;
575            $shortcut->decrement('version_counts');
576            $shortcut->save();
577        }
578
579        return response()->json((bool) $result);
580    }
581
582    /**
583     * Function to Roll back the previous added version to the current shortcut
584     */
585    public function rollbackToPreviousVersion(Request $request): JsonResponse
586    {
587        $validator = Validator::make($request->all(), [
588            'shortcutId' => ['required', 'exists:shortcut_versions,shortcut_id'],
589            'versionId' => ['required', 'exists:shortcut_versions,_id'],
590        ]);
591
592        if ($validator->fails()) {
593            return response()->json($validator->errors());
594        }
595
596        $shortcutVersion = ShortcutVersion::find($request->versionId);
597
598        $collection = collect($shortcutVersion->getAttributes());
599
600        $maxKey = $collection->filter(function ($value, $key) {
601            return is_int($key);
602        })->keys()->max();
603
604        $maxValue = $collection->get($maxKey);
605
606        $versionData = json_decode($maxValue);
607
608        $shortcut = Shortcut::find($request->shortcutId);
609
610        //Update Shortcut to current version data
611        $result = $shortcut->update([
612            'shortcut' => $versionData->shortcut,
613            'title' => $versionData->title,
614            'text' => $versionData->text,
615            'html' => $versionData->html,
616            'first_line' => $versionData->first_line,
617            'rollback_counts' => isset($shortcut->rollback_counts) ? $shortcut->rollback_counts + 1 : 1
618        ]);
619
620        //Update ShortcutVersion updated_at field so it can be picked on frontend as current version
621        $shortcutVersion->touch();
622
623        $this->dispatchShortcutEvent();
624
625        $userId = $request->user()->getKey();
626        $this->saveBrowserUsed($userId);
627
628        return response()->json((bool) $result);
629    }
630
631    /**
632     * getShortcutVersions function to get all shortcut versions list
633     * @param Request $request
634     * @param string $shortcutId main shortcut id
635     * @return JsonResponse
636     */
637    public function getShorcutVersions(Request $request, string $shortcutId): JsonResponse
638    {
639        $shortcutVersions = ShortcutVersion::where('shortcut_id', $shortcutId)->get();
640
641        return response()->json($shortcutVersions);
642    }
643
644    /**
645     * Make a Flycut  shareable function.
646     *
647     * @param  string  $shortcutId main shortcut id
648     * @return string  encyrpted key or empty string
649     */
650    public function makeShareable(Request $request, string $shortcutId): JsonResponse
651    {
652        $shortcutSearchArray = ['_id' => $shortcutId];
653        $result = Shortcut::where($shortcutSearchArray)->update(['shareable' => 1]);
654        // EncryptString using  to minimize the key.
655
656        $ShortcutSharedLinks = new ShortcutSharedLinks();
657        $ShortcutSharedLinks->shortcut_id = $shortcutId;
658        $ShortcutSharedLinks->save();
659
660        $this->dispatchShortcutEvent();
661
662        $userId = $request->user()->getKey();
663        $this->saveBrowserUsed($userId);
664
665        if ($result) {
666            return response()->json((string) $ShortcutSharedLinks->id);
667        } else {
668            return response()->json((bool) $result);
669        }
670    }
671
672    /**
673     * Get a Shared Flycut Details.
674     *
675     * @param  string  $shortcutId encrypted token
676     * @return JsonResponse  Shortcut
677     */
678    public function getShared(Request $request, $key): JsonResponse
679    {
680        $shortcutSearchArray = ['_id' => $key];
681        $shortcut_shared_links = DB::table('shortcut_shared_links')->where($shortcutSearchArray)->first();
682
683        $shortcutSearchArray = ['_id' => $shortcut_shared_links->shortcut_id];
684        $result = DB::table('shortcuts')->where($shortcutSearchArray)->first();
685        if ($result && isset($result->shareable) && (int) $result->shareable == 1) {
686            return response()->json(['status' => true, 'data' => $result]);
687        } else {
688            return response()->json(['status' => false, 'msg' => "This Flycut has been deleted or it's not shareable anymore"]);
689        }
690    }
691
692    private function mediaSize($uploads)
693    {
694        if (empty($uploads)) {
695            return 0;
696        }
697
698        $totalSum = collect($uploads)->sum(function ($item) {
699            return isset($item['size']) ? $item['size'] : 0;
700        });
701
702        //Default back to legacy mode of counting number of source paths.
703        if (empty($totalSum)) {
704            return count($uploads) ?? 0;
705        }
706
707        return $totalSum;
708    }
709
710    public function deleteBulkFlycuts(FlycutBulkDeleteRequest $request): JsonResponse
711    {
712        try {
713            $shortcut_ids = $request->shortcut_ids;
714            $userId = $request->user()->getKey();
715
716            if (!empty($shortcut_ids)) {
717                foreach ($shortcut_ids as $shortcut_id) {
718                    $versions = ShortcutVersion::where('shortcut_id', $shortcut_id);
719                    $versions->forceDelete();
720
721                    $result = Shortcut::where('_id', $shortcut_id)->delete();
722
723                    dispatch(function () use ($userId) {
724                        $this->dispatchShortcutEvent();
725                        Cache::forget('template_' . $userId);
726                    });
727                }
728            }
729
730            return response()->json((bool)$result);
731        } catch (\Throwable $th) {
732            Log::error($th->getMessage());
733            return response()->json(false);
734        }
735    }
736}