-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInitLocalFile.php
255 lines (217 loc) · 8.48 KB
/
InitLocalFile.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
<?php
namespace App\Console\Commands;
use App\Models\Category;
use App\Models\File;
use App\Models\FileCategory;
use App\Models\Link;
use App\Models\MimeType;
use App\Models\Person;
use App\Models\Type;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File as BaseFile;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\Finder\SplFileInfo as SymfonySplFileInfo;
use SplFileInfo;
class InitLocalFile extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:init-local-file
{folder? : Folder path to recover files}
{type? : File type}
{--disable-permanent-link : Disable permanent linking}
{--view : View the file}
{--recursive-folder : Recursive folder}
{--category : Add categories for each file}
{--only-extension= : Have only files of specified types}
{--categories= : Add more category for files (Separate by `|`)}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Initialize local files from a specified folder, with options for filtering file types, assigning categories, recursive search and preview.';
/**
* Execute the console command.
*/
public function handle()
{
if($this->argument('folder') && $this->argument('type')){
if(is_dir($this->argument('folder')) && is_readable($this->argument('folder'))){
$this->make(
$this->argument('folder'),
$this->argument('type'),
($this->option('categories')
? []
: explode('|', $this->option('categories'))
),
($this->option('only-extension')
? []
: explode('|', $this->option('only-extension'))
),
$this->argument('recursive-folder'),
);
}
else $this->error(" Unable to access {$this->argument('folder')} folder, please check if : \n\n - This folder exists. \n\n - You have read rights to this folder. ");
}
else{
foreach (self::getFolders() as $value) {
$this->make(
$value['folder'],
isset($value['type'])
? $value['type']
: self::class . '::autoDetectType'
,
isset($value['categories']) ? $value['categories'] : [],
isset($value['only-extension']) ? $value['only-extension'] : [],
isset($value['recursive-folder']) ? $value['recursive-folder'] : false
);
}
}
}
protected function make(array|string $dir, string|callable $type, array $categories = [], array $only_extensions = [], bool $recursive_folder = false){
$dirs = is_string($dir) ? [$dir] : $dir;
if($recursive_folder){
foreach ([...$dirs] as $folder_path) {
$dirs = array_merge($dirs, BaseFile::directories($folder_path));
}
}
$categories = array_map(fn ($arg) => Category::firstOrCreate(['name' => $arg]), $categories);
foreach ($dirs as $kk => $folder) {
// file_put_contents(__DIR__ . '/r/dirs.txt', $kk);
// if($kk < 1) continue;
if(is_dir($folder) && is_readable($folder)){
$absolute_folder_path = trim(trim($folder, '/'), '\\');
$files = BaseFile::files($absolute_folder_path);
$user = self::getUser();
foreach ($files as $key => $file) {
// file_put_contents(__DIR__ . '/r/dirs.txt', file_get_contents(__DIR__ . '/r/dirs.txt') . ', ' . $key);
// if($key < 66) continue;
// dump($key);
$ext = $file->getExtension();
if(count($only_extensions) > 0 && !is_numeric(array_search($ext, $only_extensions))) continue;
$absolute_file_path = $file->getPathname();
// $categories_ = array_map(fn ($arg) => Category::firstOrCreate(['name' => $arg]), $categories);
$categories_ = $categories;
if($this->option('view')){
switch (strtolower(PHP_OS_FAMILY)) {
case 'windows':
exec('explorer /select,"' . str_replace('"', '\\"', $absolute_file_path) . '"');
break;
case 'linux':
exec('nautilus --select "' . str_replace('"', '\\"', $absolute_file_path) . '" 2>/dev/null');
break;
case 'darwin':
exec('open -R "' . str_replace('"', '\\"', $absolute_file_path) . '"');
break;
}
$this->info("\n View this file : \"" . str_replace('"', '\\"', $absolute_file_path) . '"');
if(!$this->option('category')) $this->ask(__('Click to Entre to continue...'));
}
if($this->option('category')){
$input_categories = explode(',', $this->ask(__('Add categories')));
foreach ($input_categories as $cat_){
if(trim($cat_) != ''){
$categories_[] = Category::firstOrCreate(['name' => trim($cat_)]);
}
}
}
$mime = MimeType::firstOrCreate(['name' => BaseFile::mimeType($file->getRealPath())]);
$type = is_callable($type) ? $type(...['mime' => $mime, 'file' => $file, 'user' => $user]) : $type;
$type_ = Type::firstOrCreate(['name' => $type]);
$unique_keys = [
"type_id" => $type_->id,
"mime_type_id" => $mime->id,
"path" => $file->getRealPath(),
"size" => $file->getSize(),
"original_name" => $file->getBasename($ext == '' ? '' : ('.' . $ext)),
"extension" => $ext,
];
if(File::where($unique_keys)->exists()){
$this->warn("\n Already register - " . (count($dirs) > 1 ? "Dirs : [" . ($kk + 1) . "/" . count($dirs) . "] - " : '') . $file->getRealPath() . " [" . ($key + 1) . "/" . count($files) . "] - " . round((($key + 1) * 100) / count($files), 2) . '%');
continue;
}
$file_ = File::firstOrCreate([
"user_id" => $user->id,
"name" => $type_->name . '-' . uniqid() . random_int(0, 20000),
...$unique_keys
]);
if(!$this->option('disable-permanent-link')) {
Link::create([
'file_id' => $file_->id,
'key' => uniqid() . random_int(0, 20000),
]);
}
array_map(function($cat) use ($file_) { return FileCategory::create(['file_id' => $file_->id, 'category_id' => $cat->id]); }, $categories_);
$this->info("\n " . (count($dirs) > 1 ? "Dirs : [" . ($kk + 1) . "/" . count($dirs) . "] - " : '') . $file->getRealPath() . " [" . ($key + 1) . "/" . count($files) . "] - " . round((($key + 1) * 100) / count($files), 2) . '%');
}
}
else $this->error(" Unable to access $folder folder, please check if : \n\n - This folder exists. \n\n - You have read rights to this folder. ");
}
}
/**
* Get user
*
* @return User
*
*/
protected static function getUser() : User {
return (User::where('email', env('COMMAND_LOCAL_FILE_USER_EMAIL', 'johndoe@mail.com'))->get()->first() ?? User::where('username', env('COMMAND_LOCAL_FILE_USER_USERNAME', 'johndoe'))->get()->first()) ?? User::create([
'person_id' => Person::create([
"name" => env('COMMAND_LOCAL_FILE_USER_NAME', 'Doe'),
"firstname" => env('COMMAND_LOCAL_FILE_USER_FIRSTNAME', 'John'),
"lastname" => env('COMMAND_LOCAL_FILE_USER_LASTNAME', 'X'),
"sex" => env('COMMAND_LOCAL_FILE_USER_SEX', 'm'),
])->id,
'email' => env('COMMAND_LOCAL_FILE_USER_EMAIL', 'johndoe@mail.com'),
'username' => env('COMMAND_LOCAL_FILE_USER_USERNAME', 'johndoe'),
'password' => Hash::make(env('COMMAND_LOCAL_FILE_USER_PASSWORD', '12345678')),
'is' => "0",
// 'email_verified_at' => env('COMMAND_LOCAL_FILE_USER_EMAIL_VERIFIED', 1) == 1 ? now() : null,
]);
}
/**
* Get file type
*
* @param \App\Models\MimeType $mime
* @param \Symfony\Component\Finder\SplFileInfo|\SplFileInfo $file
* @param \App\Models\User $user
*
* @return string|null
*
*/
public static function autoDetectType(MimeType $mime, SymfonySplFileInfo|SplFileInfo $file, User $user){
return preg_match('/^' . preg_quote('application/vnd.openxmlformats-officedocument', '/') . '.*/', $mime->name) || $mime->name == 'application/msword' || $mime->name == 'application/pdf'
? 'document'
: (preg_match('/^' . preg_quote('font/', '/') . '.*/i', $mime->name)
? 'font'
: (preg_match('/^' . preg_quote('audio/', '/') . '.*/i', $mime->name)
? 'audio'
: (preg_match('/^' . preg_quote('image/', '/') . '.*/i', $mime->name)
? 'image'
: (preg_match('/^' . preg_quote('video/', '/') . '.*/i', $mime->name)
? 'video'
: (preg_match('/^' . preg_quote('text/', '/') . '.*/i', $mime->name)
? 'text'
: null
)
)
)
)
)
;
}
/**
* Get folders
*
* @return array<array<mixed>>
*
*/
protected static function getFolders(){
return is_array(config('app.file_init')) ? config('app.file_init') : [];
}
}