-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathelFinder.py
1502 lines (1264 loc) · 39.3 KB
/
elFinder.py
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# Connector for elFinder File Manager
# author Troex Nevelin <[email protected]>
import hashlib
import mimetypes
import os
import os.path
import re
import shutil
import time
from datetime import datetime
class connector():
"""Connector for elFinder"""
_options = {
'root': '',
'URL': '',
'rootAlias': 'Home',
'dotFiles': False,
'dirSize': True,
'fileMode': 0644,
'dirMode': 0755,
'imgLib': 'auto',
'tmbDir': '.tmb',
'tmbAtOnce': 5,
'tmbSize': 48,
'fileURL': True,
'uploadMaxSize': 256,
'uploadWriteChunk': 8192,
'uploadAllow': [],
'uploadDeny': [],
'uploadOrder': ['deny', 'allow'],
# 'aclObj': None, # TODO
# 'aclRole': 'user', # TODO
'defaults': {
'read': True,
'write': True,
'rm': True
},
'perms': {},
'archiveMimes': {},
'archivers': {
'create': {},
'extract': {}
},
'disabled': [],
'debug': False
}
_commands = {
'open': '__open',
'reload': '__reload',
'mkdir': '__mkdir',
'mkfile': '__mkfile',
'rename': '__rename',
'upload': '__upload',
'paste': '__paste',
'rm': '__rm',
'duplicate': '__duplicate',
'read': '__read',
'edit': '__edit',
'extract': '__extract',
'archive': '__archive',
'resize': '__resize',
'tmb': '__thumbnails',
'ping': '__ping'
}
_mimeType = {
# text
'txt': 'text/plain',
'conf': 'text/plain',
'ini': 'text/plain',
'php': 'text/x-php',
'html': 'text/html',
'htm': 'text/html',
'js' : 'text/javascript',
'css': 'text/css',
'rtf': 'text/rtf',
'rtfd': 'text/rtfd',
'py' : 'text/x-python',
'java': 'text/x-java-source',
'rb' : 'text/x-ruby',
'sh' : 'text/x-shellscript',
'pl' : 'text/x-perl',
'sql': 'text/x-sql',
# apps
'doc': 'application/msword',
'ogg': 'application/ogg',
'7z': 'application/x-7z-compressed',
# video
'ogm': 'appllication/ogm',
'mkv': 'video/x-matroska'
}
_time = 0
_request = {}
_response = {}
_errorData = {}
_form = {}
_im = None
_sp = None
_today = 0
_yesterday = 0
# public variables
httpAllowedParameters = ('cmd', 'target', 'targets[]', 'current', 'tree', 'name',
'content', 'src', 'dst', 'cut', 'init', 'type', 'width', 'height', 'upload[]')
# return variables
httpStatusCode = 0
httpHeader = {}
httpResponse = None
def __init__(self, opts):
for opt in opts:
self._options[opt] = opts.get(opt)
self._response['debug'] = {}
self._options['URL'] = self.__checkUtf8(self._options['URL'])
self._options['URL'] = self._options['URL'].rstrip('/')
self._options['root'] = self.__checkUtf8(self._options['root'])
self._options['root'] = self._options['root'].rstrip(os.sep)
self.__debug('URL', self._options['URL'])
self.__debug('root', self._options['root'])
for cmd in self._options['disabled']:
if cmd in self._commands:
del self._commands[cmd]
if self._options['tmbDir']:
self._options['tmbDir'] = os.path.join(self._options['root'], self._options['tmbDir'])
if not os.path.exists(self._options['tmbDir']):
self._options['tmbDir'] = False
def __reset(self):
"""Flush per request variables"""
self.httpStatusCode = 0
self.httpHeader = {}
self.httpResponse = None
self._request = {}
self._response = {}
self._errorData = {}
self._form = {}
self._time = time.time()
t = datetime.fromtimestamp(self._time)
self._today = time.mktime(datetime(t.year, t.month, t.day).timetuple())
self._yesterday = self._today - 86400
self._response['debug'] = {}
def run(self, httpRequest = []):
"""main function"""
self.__reset()
rootOk = True
if not os.path.exists(self._options['root']) or self._options['root'] == '':
rootOk = False
self._response['error'] = 'Invalid backend configuration'
elif not self.__isAllowed(self._options['root'], 'read'):
rootOk = False
self._response['error'] = 'Access denied'
for field in self.httpAllowedParameters:
if field in httpRequest:
self._request[field] = httpRequest[field]
if rootOk is True:
if 'cmd' in self._request:
if self._request['cmd'] in self._commands:
cmd = self._commands[self._request['cmd']]
func = getattr(self, '_' + self.__class__.__name__ + cmd, None)
if callable(func):
try:
func()
except Exception, e:
self._response['error'] = 'Command Failed'
self.__debug('exception', str(e))
else:
self._response['error'] = 'Unknown command'
else:
self.__open()
if 'init' in self._request:
self.__checkArchivers()
self._response['disabled'] = self._options['disabled']
if not self._options['fileURL']:
url = ''
else:
url = self._options['URL']
self._response['params'] = {
'dotFiles': self._options['dotFiles'],
'uplMaxSize': str(self._options['uploadMaxSize']) + 'M',
'archives': self._options['archivers']['create'].keys(),
'extract': self._options['archivers']['extract'].keys(),
'url': url
}
if self._errorData:
self._response['errorData'] = self._errorData
if self._options['debug']:
self.__debug('time', (time.time() - self._time))
else:
if 'debug' in self._response:
del self._response['debug']
if self.httpStatusCode < 100:
self.httpStatusCode = 200
if not 'Content-type' in self.httpHeader:
if ('cmd' in self._request and self._request['cmd'] == 'upload') or self._options['debug']:
self.httpHeader['Content-type'] = 'text/html'
else:
self.httpHeader['Content-type'] = 'application/json'
self.httpResponse = self._response
return self.httpStatusCode, self.httpHeader, self.httpResponse
def __open(self):
"""Open file or directory"""
# try to open file
if 'current' in self._request:
curDir = self.__findDir(self._request['current'], None)
curFile = self.__find(self._request['target'], curDir)
if not curDir or not curFile or os.path.isdir(curFile):
self.httpStatusCode = 404
self.httpHeader['Content-type'] = 'text/html'
self.httpResponse = 'File not found'
return
if not self.__isAllowed(curDir, 'read') or not self.__isAllowed(curFile, 'read'):
self.httpStatusCode = 403
self.httpHeader['Content-type'] = 'text/html'
self.httpResponse = 'Access denied'
return
if os.path.islink(curFile):
curFile = self.__readlink(curFile)
if not curFile or os.path.isdir(curFile):
self.httpStatusCode = 404
self.httpHeader['Content-type'] = 'text/html'
self.httpResponse = 'File not found'
return
if (
not self.__isAllowed(os.path.dirname(curFile), 'read')
or not self.__isAllowed(curFile, 'read')
):
self.httpStatusCode = 403
self.httpHeader['Content-type'] = 'text/html'
self.httpResponse = 'Access denied'
return
mime = self.__mimetype(curFile)
parts = mime.split('/', 2)
if parts[0] == 'image': disp = 'image'
elif parts[0] == 'text': disp = 'inline'
else: disp = 'attachments'
self.httpStatusCode = 200
self.httpHeader['Content-type'] = mime
self.httpHeader['Content-Disposition'] = disp + '; filename=' + os.path.basename(curFile)
self.httpHeader['Content-Location'] = curFile.replace(self._options['root'], '')
self.httpHeader['Content-Transfer-Encoding'] = 'binary'
self.httpHeader['Content-Length'] = str(os.lstat(curFile).st_size)
self.httpHeader['Connection'] = 'close'
self._response['file'] = open(curFile, 'r')
return
# try dir
else:
path = self._options['root']
if 'target' in self._request and self._request['target']:
target = self.__findDir(self._request['target'], None)
if not target:
self._response['error'] = 'Invalid parameters'
elif not self.__isAllowed(target, 'read'):
self._response['error'] = 'Access denied'
else:
path = target
self.__content(path, 'tree' in self._request)
pass
def __rename(self):
"""Rename file or dir"""
current = name = target = None
curDir = curName = newName = None
if 'name' in self._request and 'current' in self._request and 'target' in self._request:
name = self._request['name']
current = self._request['current']
target = self._request['target']
curDir = self.__findDir(current, None)
curName = self.__find(target, curDir)
newName = os.path.join(curDir, name)
if not curDir or not curName:
self._response['error'] = 'File not found'
elif not self.__isAllowed(curDir, 'write') and self.__isAllowed(curName, 'rm'):
self._response['error'] = 'Access denied'
elif not self.__checkName(name):
self._response['error'] = 'Invalid name'
elif os.path.exists(newName):
self._response['error'] = 'File or folder with the same name already exists'
else:
self.__rmTmb(curName)
try:
os.rename(curName, newName)
self._response['select'] = [self.__hash(newName)]
self.__content(curDir, os.path.isdir(newName))
except:
self._response['error'] = 'Unable to rename file'
def __mkdir(self):
"""Create new directory"""
current = None
path = None
newDir = None
if 'name' in self._request and 'current' in self._request:
name = self._request['name']
current = self._request['current']
path = self.__findDir(current, None)
newDir = os.path.join(path, name)
if not path:
self._response['error'] = 'Invalid parameters'
elif not self.__isAllowed(path, 'write'):
self._response['error'] = 'Access denied'
elif not self.__checkName(name):
self._response['error'] = 'Invalid name'
elif os.path.exists(newDir):
self._response['error'] = 'File or folder with the same name already exists'
else:
try:
os.mkdir(newDir, int(self._options['dirMode']))
self._response['select'] = [self.__hash(newDir)]
self.__content(path, True)
except:
self._response['error'] = 'Unable to create folder'
def __mkfile(self):
"""Create new file"""
name = current = None
curDir = newFile = None
if 'name' in self._request and 'current' in self._request:
name = self._request['name']
current = self._request['current']
curDir = self.__findDir(current, None)
newFile = os.path.join(curDir, name)
if not curDir or not name:
self._response['error'] = 'Invalid parameters'
elif not self.__isAllowed(curDir, 'write'):
self._response['error'] = 'Access denied'
elif not self.__checkName(name):
self._response['error'] = 'Invalid name'
elif os.path.exists(newFile):
self._response['error'] = 'File or folder with the same name already exists'
else:
try:
open(newFile, 'w').close()
self._response['select'] = [self.__hash(newFile)]
self.__content(curDir, False)
except:
self._response['error'] = 'Unable to create file'
def __rm(self):
"""Delete files and directories"""
current = rmList = None
curDir = rmFile = None
if 'current' in self._request and 'targets[]' in self._request:
current = self._request['current']
rmList = self._request['targets[]']
curDir = self.__findDir(current, None)
if not rmList or not curDir:
self._response['error'] = 'Invalid parameters'
return False
if not isinstance(rmList, list):
rmList = [rmList]
for rm in rmList:
rmFile = self.__find(rm, curDir)
if not rmFile: continue
self.__remove(rmFile)
# TODO if errorData not empty return error
self.__content(curDir, True)
def __upload(self):
"""Upload files"""
try: # Windows needs stdio set for binary mode.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
if 'current' in self._request:
curDir = self.__findDir(self._request['current'], None)
if not curDir:
self._response['error'] = 'Invalid parameters'
return
if not self.__isAllowed(curDir, 'write'):
self._response['error'] = 'Access denied'
return
if not 'upload[]' in self._request:
self._response['error'] = 'No file to upload'
return
upFiles = self._request['upload[]']
# invalid format
# must be dict('filename1': 'filedescriptor1', 'filename2': 'filedescriptor2', ...)
if not isinstance(upFiles, dict):
self._response['error'] = 'Invalid parameters'
return
self._response['select'] = []
total = 0
upSize = 0
maxSize = self._options['uploadMaxSize'] * 1024 * 1024
for name, data in upFiles.iteritems():
if name:
total += 1
name = os.path.basename(name)
if not self.__checkName(name):
self.__errorData(name, 'Invalid name')
else:
name = os.path.join(curDir, name)
try:
f = open(name, 'wb', self._options['uploadWriteChunk'])
for chunk in self.__fbuffer(data):
f.write(chunk)
f.close()
upSize += os.lstat(name).st_size
if self.__isUploadAllow(name):
os.chmod(name, self._options['fileMode'])
self._response['select'].append(self.__hash(name))
else:
self.__errorData(name, 'Not allowed file type')
try:
os.unlink(name)
except:
pass
except:
self.__errorData(name, 'Unable to save uploaded file')
if upSize > maxSize:
try:
os.unlink(name)
self.__errorData(name, 'File exceeds the maximum allowed filesize')
except:
pass
# TODO ?
self.__errorData(name, 'File was only partially uploaded')
break
if self._errorData:
if len(self._errorData) == total:
self._response['error'] = 'Unable to upload files'
else:
self._response['error'] = 'Some files was not uploaded'
self.__content(curDir, False)
return
def __paste(self):
"""Copy or cut files/directories"""
if 'current' in self._request and 'src' in self._request and 'dst' in self._request:
curDir = self.__findDir(self._request['current'], None)
src = self.__findDir(self._request['src'], None)
dst = self.__findDir(self._request['dst'], None)
if not curDir or not src or not dst or not 'targets[]' in self._request:
self._response['error'] = 'Invalid parameters'
return
files = self._request['targets[]']
if not isinstance(files, list):
files = [files]
cut = False
if 'cut' in self._request:
if self._request['cut'] == '1':
cut = True
if not self.__isAllowed(src, 'read') or not self.__isAllowed(dst, 'write'):
self._response['error'] = 'Access denied'
return
for fhash in files:
f = self.__find(fhash, src)
if not f:
self._response['error'] = 'File not found'
return
newDst = os.path.join(dst, os.path.basename(f))
if dst.find(f) == 0:
self._response['error'] = 'Unable to copy into itself'
return
if cut:
if not self.__isAllowed(f, 'rm'):
self._response['error'] = 'Move failed'
self._errorData(f, 'Access denied')
self.__content(curDir, True)
return
# TODO thumbs
if os.path.exists(newDst):
self._response['error'] = 'Unable to move files'
self._errorData(f, 'File or folder with the same name already exists')
self.__content(curDir, True)
return
try:
os.rename(f, newDst)
self.__rmTmb(f)
continue
except:
self._response['error'] = 'Unable to move files'
self._errorData(f, 'Unable to move')
self.__content(curDir, True)
return
else:
if not self.__copy(f, newDst):
self._response['error'] = 'Unable to copy files'
self.__content(curDir, True)
return
continue
self.__content(curDir, True)
else:
self._response['error'] = 'Invalid parameters'
return
def __duplicate(self):
"""Create copy of files/directories"""
if 'current' in self._request and 'target' in self._request:
curDir = self.__findDir(self._request['current'], None)
target = self.__find(self._request['target'], curDir)
if not curDir or not target:
self._response['error'] = 'Invalid parameters'
return
if not self.__isAllowed(target, 'read') or not self.__isAllowed(curDir, 'write'):
self._response['error'] = 'Access denied'
newName = self.__uniqueName(target)
if not self.__copy(target, newName):
self._response['error'] = 'Unable to create file copy'
return
self.__content(curDir, True)
return
def __resize(self):
"""Scale image size"""
if not (
'current' in self._request and 'target' in self._request
and 'width' in self._request and 'height' in self._request
):
self._response['error'] = 'Invalid parameters'
return
width = int(self._request['width'])
height = int(self._request['height'])
curDir = self.__findDir(self._request['current'], None)
curFile = self.__find(self._request['target'], curDir)
if width < 1 or height < 1 or not curDir or not curFile:
self._response['error'] = 'Invalid parameters'
return
if not self.__isAllowed(curFile, 'write'):
self._response['error'] = 'Access denied'
return
if not self.__mimetype(curFile).find('image') == 0:
self._response['error'] = 'File is not an image'
return
self.__debug('resize ' + curFile, str(width) + ':' + str(height))
self.__initImgLib()
try:
im = self._im.open(curFile)
imResized = im.resize((width, height), self._im.ANTIALIAS)
imResized.save(curFile)
except Exception, e:
self.__debug('resizeFailed_' + path, str(e))
self._response['error'] = 'Unable to resize image'
return
self._response['select'] = [self.__hash(curFile)]
self.__content(curDir, False)
return
def __thumbnails(self):
"""Create previews for images"""
if 'current' in self._request:
curDir = self.__findDir(self._request['current'], None)
if not curDir or curDir == self._options['tmbDir']:
return False
else:
return False
self.__initImgLib()
if self.__canCreateTmb():
if self._options['tmbAtOnce'] > 0:
tmbMax = self._options['tmbAtOnce']
else:
tmbMax = 5
self._response['current'] = self.__hash(curDir)
self._response['images'] = {}
i = 0
for f in os.listdir(curDir):
path = os.path.join(curDir, f)
fhash = self.__hash(path)
if self.__canCreateTmb(path) and self.__isAllowed(path, 'read'):
tmb = os.path.join(self._options['tmbDir'], fhash + '.png')
if not os.path.exists(tmb):
if self.__tmb(path, tmb):
self._response['images'].update({
fhash: self.__path2url(tmb)
})
i += 1
if i >= tmbMax:
self._response['tmb'] = True
break
else:
return False
return
def __content(self, path, tree):
"""CWD + CDC + maybe(TREE)"""
self.__cwd(path)
self.__cdc(path)
if tree:
self._response['tree'] = self.__tree(self._options['root'])
def __cwd(self, path):
"""Current Working Directory"""
name = os.path.basename(path)
if path == self._options['root']:
name = self._options['rootAlias']
root = True
else:
root = False
if self._options['rootAlias']:
basename = self._options['rootAlias']
else:
basename = os.path.basename(self._options['root'])
rel = basename + path[len(self._options['root']):]
self._response['cwd'] = {
'hash': self.__hash(path),
'name': self.__checkUtf8(name),
'mime': 'directory',
'rel': self.__checkUtf8(rel),
'size': 0,
'date': datetime.fromtimestamp(os.stat(path).st_mtime).strftime("%d %b %Y %H:%M"),
'read': True,
'write': self.__isAllowed(path, 'write'),
'rm': not root and self.__isAllowed(path, 'rm')
}
def __cdc(self, path):
"""Current Directory Content"""
files = []
dirs = []
for f in sorted(os.listdir(path)):
if not self.__isAccepted(f): continue
pf = os.path.join(path, f)
info = {}
info = self.__info(pf)
info['hash'] = self.__hash(pf)
if info['mime'] == 'directory':
dirs.append(info)
else:
files.append(info)
dirs.extend(files)
self._response['cdc'] = dirs
def __info(self, path):
mime = ''
filetype = 'file'
if os.path.isfile(path): filetype = 'file'
if os.path.isdir(path): filetype = 'dir'
if os.path.islink(path): filetype = 'link'
stat = os.lstat(path)
statDate = datetime.fromtimestamp(stat.st_mtime)
fdate = ''
if stat.st_mtime >= self._today:
fdate = 'Today ' + statDate.strftime("%H:%M")
elif stat.st_mtime >= self._yesterday and stat.st_mtime < self._today:
fdate = 'Yesterday ' + statDate.strftime("%H:%M")
else:
fdate = statDate.strftime("%d %b %Y %H:%M")
info = {
'name': self.__checkUtf8(os.path.basename(path)),
'hash': self.__hash(path),
'mime': 'directory' if filetype == 'dir' else self.__mimetype(path),
'date': fdate,
'size': self.__dirSize(path) if filetype == 'dir' else stat.st_size,
'read': self.__isAllowed(path, 'read'),
'write': self.__isAllowed(path, 'write'),
'rm': self.__isAllowed(path, 'rm')
}
if filetype == 'link':
lpath = self.__readlink(path)
if not lpath:
info['mime'] = 'symlink-broken'
return info
if os.path.isdir(lpath):
info['mime'] = 'directory'
else:
info['parent'] = self.__hash(os.path.dirname(lpath))
info['mime'] = self.__mimetype(lpath)
if self._options['rootAlias']:
basename = self._options['rootAlias']
else:
basename = os.path.basename(self._options['root'])
info['link'] = self.__hash(lpath)
info['linkTo'] = basename + lpath[len(self._options['root']):]
info['read'] = info['read'] and self.__isAllowed(lpath, 'read')
info['write'] = info['write'] and self.__isAllowed(lpath, 'write')
info['rm'] = self.__isAllowed(lpath, 'rm')
else:
lpath = False
if not info['mime'] == 'directory':
if self._options['fileURL'] and info['read'] is True:
if lpath:
info['url'] = self.__path2url(lpath)
else:
info['url'] = self.__path2url(path)
if info['mime'][0:5] == 'image':
if self.__canCreateTmb():
dim = self.__getImgSize(path)
if dim:
info['dim'] = dim
info['resize'] = True
# if we are in tmb dir, files are thumbs itself
if os.path.dirname(path) == self._options['tmbDir']:
info['tmb'] = self.__path2url(path)
return info
tmb = os.path.join(self._options['tmbDir'], info['hash'] + '.png')
if os.path.exists(tmb):
tmbUrl = self.__path2url(tmb)
info['tmb'] = tmbUrl
else:
self._response['tmb'] = True
return info
def __tree(self, path):
"""Return directory tree starting from path"""
if not os.path.isdir(path): return ''
if os.path.islink(path): return ''
if path == self._options['root'] and self._options['rootAlias']:
name = self._options['rootAlias']
else:
name = os.path.basename(path)
tree = {
'hash': self.__hash(path),
'name': self.__checkUtf8(name),
'read': self.__isAllowed(path, 'read'),
'write': self.__isAllowed(path, 'write'),
'dirs': []
}
if self.__isAllowed(path, 'read'):
for d in sorted(os.listdir(path)):
pd = os.path.join(path, d)
if os.path.isdir(pd) and not os.path.islink(pd) and self.__isAccepted(d):
tree['dirs'].append(self.__tree(pd))
return tree
def __uniqueName(self, path, copy = ' copy'):
"""Generate unique name for file copied file"""
curDir = os.path.dirname(path)
curName = os.path.basename(path)
lastDot = curName.rfind('.')
ext = newName = ''
if not os.path.isdir(path) and re.search(r'\..{3}\.(gz|bz|bz2)$', curName):
pos = -7
if curName[-1:] == '2':
pos -= 1
ext = curName[pos:]
oldName = curName[0:pos]
newName = oldName + copy
elif os.path.isdir(path) or lastDot <= 0:
oldName = curName
newName = oldName + copy
pass
else:
ext = curName[lastDot:]
oldName = curName[0:lastDot]
newName = oldName + copy
pos = 0
if oldName[-len(copy):] == copy:
newName = oldName
elif re.search(r'' + copy +'\s\d+$', oldName):
pos = oldName.rfind(copy) + len(copy)
newName = oldName[0:pos]
else:
newPath = os.path.join(curDir, newName + ext)
if not os.path.exists(newPath):
return newPath
# if we are here then copy already exists or making copy of copy
# we will make new indexed copy *black magic*
idx = 1
if pos > 0: idx = int(oldName[pos:])
while True:
idx += 1
newNameExt = newName + ' ' + str(idx) + ext
newPath = os.path.join(curDir, newNameExt)
if not os.path.exists(newPath):
return newPath
# if idx >= 1000: break # possible loop
return
def __remove(self, target):
"""Internal remove procedure"""
if not self.__isAllowed(target, 'rm'):
self.__errorData(target, 'Access denied')
if not os.path.isdir(target):
try:
os.unlink(target)
return True
except:
self.__errorData(target, 'Remove failed')
return False
else:
for i in os.listdir(target):
if self.__isAccepted(i):
self.__remove(os.path.join(target, i))
try:
os.rmdir(target)
return True
except:
self.__errorData(target, 'Remove failed')
return False
pass
def __copy(self, src, dst):
"""Internal copy procedure"""
dstDir = os.path.dirname(dst)
if not self.__isAllowed(src, 'read'):
self.__errorData(src, 'Access denied')
return False
if not self.__isAllowed(dstDir, 'write'):
self.__errorData(dstDir, 'Access denied')
return False
if os.path.exists(dst):
self.__errorData(dst, 'File or folder with the same name already exists')
return False
if not os.path.isdir(src):
try:
shutil.copyfile(src, dst)
shutil.copymode(src, dst)
return True
except:
self.__errorData(src, 'Unable to copy files')
return False
else:
try:
os.mkdir(dst)
shutil.copymode(src, dst)
except:
self.__errorData(src, 'Unable to copy files')
return False
for i in os.listdir(src):
newSrc = os.path.join(src, i)
newDst = os.path.join(dst, i)
if not self.__copy(newSrc, newDst):
self.__errorData(newSrc, 'Unable to copy files')
return False
return True
def __checkName(self, name):
"""Check for valid file/dir name"""
pattern = r'[\/\\\:\<\>]'
if re.search(pattern, name):
return False
return True
def __findDir(self, fhash, path):
"""Find directory by hash"""
fhash = str(fhash)
if not path:
path = self._options['root']
if fhash == self.__hash(path):
return path
if not os.path.isdir(path):
return None
for d in os.listdir(path):
pd = os.path.join(path, d)
if os.path.isdir(pd) and not os.path.islink(pd):
if fhash == self.__hash(pd):
return pd
else:
ret = self.__findDir(fhash, pd)
if ret:
return ret
return None
def __find(self, fhash, parent):
"""Find file/dir by hash"""
fhash = str(fhash)
if os.path.isdir(parent):
for i in os.listdir(parent):
path = os.path.join(parent, i)
if fhash == self.__hash(path):
return path
return None
def __read(self):
if 'current' in self._request and 'target' in self._request:
curDir = self.__findDir(self._request['current'], None)
curFile = self.__find(self._request['target'], curDir)
if curDir and curFile:
if self.__isAllowed(curFile, 'read'):
self._response['content'] = open(curFile, 'r').read()
else:
self._response['error'] = 'Access denied'
return
self._response['error'] = 'Invalid parameters'
return
def __edit(self):
"""Save content in file"""
error = ''
if 'current' in self._request and 'target' in self._request and 'content' in self._request:
curDir = self.__findDir(self._request['current'], None)
curFile = self.__find(self._request['target'], curDir)
error = curFile
if curFile and curDir:
if self.__isAllowed(curFile, 'write'):
try:
f = open(curFile, 'w+')
f.write(self._request['content'])
f.close()
self._response['target'] = self.__info(curFile)
except:
self._response['error'] = 'Unable to write to file'
else:
self._response['error'] = 'Access denied'
return