Completed
Push — dev5 ( 096a7b...37965d )
by Ron
09:47
created

LinkFilesController::saveFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 14
nc 1
nop 2
dl 0
loc 27
rs 9.7998
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers\FileLinks;
4
5
use App\Files;
6
use App\FileLinks;
7
use App\FileLinkFiles;
8
use App\CustomerFiles;
9
use Illuminate\Http\Request;
10
use Illuminate\Http\UploadedFile;
11
use Illuminate\Support\Facades\Log;
12
use App\Http\Controllers\Controller;
13
use Illuminate\Support\Facades\Auth;
14
use Illuminate\Support\Facades\Storage;
15
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
16
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
17
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
18
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
19
20
class LinkFilesController extends Controller
21
{
22
    //  Only authorized users have access
23
    public function __construct()
24
    {
25
        $this->middleware('auth');
26
    }
27
    
28
    //  Get the files for the link    
29
    public function getIndex($id, $dir)
30
    {
31
        $files = [];
32
        
33
        switch($dir)
34
        {
35
            //  For files that are available for a guest to download
36
            case 'down':
37
                $files = FileLinkFiles::where('link_id', $id)
38
                    ->where('upload', false)
39
                    ->join('files', 'file_link_files.file_id', '=', 'files.file_id')
40
                    ->get();
41
                break;
42
            //  For files that are uploaded by a guest
43
            case 'up':
44
                $files = Files::where('file_link_files.link_id', $id)
45
                    ->where('file_link_files.upload', true)
46
                    ->join('file_link_files', 'files.file_id', '=', 'file_link_files.file_id')
47
                    ->with('FileLinkNotes')
48
                    ->get();
49
                break;
50
        }
51
        
52
        //  Add the download link to the collection
53
        foreach($files as $file)
54
        {
55
            $file->url       = route('download', [$file->file_id, $file->file_name]);
56
            $file->timestamp = date('M d, Y', strtotime($file->created_at));
57
        }
58
        
59
        return response()->json($files);
60
    }
61
    
62
    //  Add a file to the link
63
    public function postIndex(Request $request, $linkID, $dir)
64
    {
65
        //  If the file exists, process it
66
        if(!empty($request->file))
67
        {
68
            $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
69
            
70
            //  Verify that the upload is valid and being processed
71
            if($receiver->isUploaded() === false)
72
            {
73
                throw new UploadMissingFileException();
74
            }
75
            
76
            //  Recieve and process the file
77
            $save = $receiver->receive();
78
            
79
            //  See if the uploade has finished
80
            if($save->isFinished())
81
            {
82
                $fileID = $this->saveFile($save->getFile(), $linkID);
0 ignored issues
show
Unused Code introduced by
The assignment to $fileID is dead and can be removed.
Loading history...
83
                
84
                return response()->json(['success' => true]);;
85
            }
86
        
87
            //  Get the current progress
88
            $handler = $save->handler();
89
90
            return response()->json([
91
                'done'   => $handler->getPercentageDone(),
92
                'status' => true
93
            ]);
94
        
95
        }
96
        
97
        return response()->json(['success' => false]);
98
    }
99
    
100
    //  Save the file and add it to the database
101
    private function saveFile(UploadedFile $file, $linkID)
102
    {
103
        $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$linkID;
104
        
105
        //  Clean the file and store it
106
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
107
        $file->storeAs($filePath, $fileName);
108
109
        //  Place file in Files table of DB
110
        $newFile = Files::create([
111
            'file_name' => $fileName,
112
            'file_link' => $filePath.DIRECTORY_SEPARATOR
113
        ]);
114
        $fileID = $newFile->file_id;
115
116
        //  Place the file in the file link files table of DB
117
        FileLinkFiles::create([
118
            'link_id'  => $linkID,
119
            'file_id'  => $fileID,
120
            'user_id'  => Auth::user()->user_id,
121
            'upload'   => 0
122
        ]);
123
124
        //  Log stored file
125
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
126
        
127
        return $fileID;
128
    }
129
    
130
    //  Move a file to the customer attached to the link
131
    public function moveFile(Request $request, $id)
132
    {
133
        $request->validate([
134
            'selected' => 'required',
135
            'file_id'  => 'required'
136
        ]);
137
        
138
        $linkData = FileLinks::find($id);
139
        
140
        $newPath = config('filesystems.paths.customers').DIRECTORY_SEPARATOR.$linkData->cust_id.DIRECTORY_SEPARATOR;
141
        $fileData = Files::find($request->file_id);
142
        
143
        //  Verify the file does not already exist in the customer data or file
144
        $dup = CustomerFiles::where('file_id', $request->file_id)->where('cust_id', $linkData->cust_id)->count();
145
        if($dup || Storage::exists($newPath.$fileData->file_name))
146
        {
147
            return response()->json(['success' => 'duplicate']);
148
        }
149
        
150
        //  Move the file to the customers file folder
151
        Storage::move($fileData->file_link.$fileData->file_name, $newPath.$fileData->file_name);
152
        
153
        //  Update file database
154
        $fileData->update([
155
            'file_link' => $newPath
156
        ]);
157
        
158
        //  Place file in customer database
159
        CustomerFiles::create([
160
            'file_id'      => $request->file_id,
161
            'file_type_id' => $request->selected,
162
            'cust_id'      => $linkData->cust_id,
163
            'user_id'      => Auth::user()->user_id,
164
            'name'         => $request->file_name
165
        ]);
166
        
167
        return response()->json(['success' => true]);
168
    }
169
    
170
    //  Delete a file attached to a link
171
    public function delFile($id)
172
    {
173
        $fileData = FileLinkFiles::find($id);
174
        $fileID   = $fileData->file_id;
175
        $fileData->delete();
176
        
177
        Files::deleteFile($fileID);
178
        
179
        return response()->json(['success' => true]);
180
    }
181
}
182