-
Notifications
You must be signed in to change notification settings - Fork 0
/
couchmount.py
786 lines (706 loc) · 29.5 KB
/
couchmount.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
from sys import path
path.append('..')
from pydokan import Dokan
from pydokan.struct import DOKAN_OPTION_KEEP_ALIVE, DOKAN_OPTION_REMOVABLE,\
LPWSTR, WIN32_FIND_DATAW, PWIN32_FIND_DATAW, LPSTR
from pydokan.wrapper.file import AccessMode, ShareMode, CreationDisposition, \
FlagsAndAttributes
from pydokan.wrapper.dokan import DokanFileInfo
from pydokan.wrapper.security import SecurityInfo
from pydokan.win32con import ERROR_FILE_NOT_FOUND, FILE_ATTRIBUTE_DIRECTORY,\
ERROR_INVALID_HANDLE, FILE_CASE_SENSITIVE_SEARCH, FILE_UNICODE_ON_DISK,\
FILE_SUPPORTS_ENCRYPTION, FILE_SUPPORTS_REMOTE_STORAGE, \
FILE_ATTRIBUTE_NORMAL, ERROR_FILE_EXISTS, CREATE_NEW, ERROR_ALREADY_EXISTS,\
CREATE_ALWAYS, OPEN_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, FILE_ATTRIBUTE_HIDDEN, \
FILE_SUPPORTS_REPARSE_POINTS
from pydokan.utils import wrap, log, DateTimeConvertor, SizeConvert
from pydokan.debug import disable as disable_debug, force_breakpoint
from datetime import datetime
from threading import Thread, Lock
import traceback, logging, logging.handlers
from ctypes import memmove, string_at
from couchdb import Server
from replication import replicate_from_local_ids
import subprocess
import os
import json
import ctypes
DATABASE = "cozy-files"
server = Server("http://localhost:5984/")
database = server[DATABASE]
def _normalize_path_win_to_DB_lower(path):
res = database.view('device/all')
for device in res:
name = device.value['login'].lower()
if path is '\\':
return "/%s" %name
else:
return "/%s" %name + path.replace('\\', '/').lower()
def _normalize_path_DB_to_win_lower(path):
res = database.view('device/all')
for device in res:
login = device.value['login'].lower()
path = path.replace("/%s" %name, '\\')
return path.replace('/', '\\').lower()
def _path_split_lower(path):
'''
'''
res = database.view('device/all')
for device in res:
login = device.value['login'].lower()
if path is '\\':
path = "/%s" %login
else:
path = "/%s" %login + path.replace('\\', '/')
(folder_path, name) = os.path.split(path)
if folder_path[-1:] == '/':
folder_path = folder_path[:-(len(name)+1)]
return (folder_path.lower(), name.lower())
def _path_split(path):
'''
'''
res = database.view('device/all')
for device in res:
login = device.value['login']
if path is '\\':
path = "/%s" %login
else:
path = "/%s" %login + path.replace('\\', '/')
(folder_path, name) = os.path.split(path)
if folder_path[-1:] == '/':
folder_path = folder_path[:-(len(login)+1)]
return (folder_path, name)
class Couchmount(Dokan, Thread):
def __init__(self, app, mount_point, options, threads_count, version=600):
'''
Initialize Couchmount class
'''
self.app = app
Dokan.__init__(self, mount_point, options, threads_count, version)
Thread.__init__(self)
self.mount_code = 0
self.serial_number = 0x19831116
# Lock for decorator @log. Callback`s loging...
self.log_lock = Lock()
self.counter = 1
self.db = server[DATABASE]
self.currentFile = b''
self.read_current_file = {}
def run(self):
self.mount_code = 0
self.mount_code = self.main()
def log_exception(self):
'''
Log exception
'''
lines = traceback.format_exc().splitlines()
self.log_lock.acquire()
try:
log = self.app.log
for line in lines:
log.error(line)
finally:
self.log_lock.release()
@wrap(None, AccessMode, ShareMode, CreationDisposition, FlagsAndAttributes, DokanFileInfo)
@log('path', 'access', 'share_mode', 'disposition', 'flags', 'info')
def create_file(self, path, access, share_mode, disposition, flags, file_info):
'''
Create file if disposition flag is CREATE_NEW
path {string}: file path
access {AccessMode}: file permissions
share_mode {ShareMode}:
disposition {CreationDisposition}: Flags
file_info {Object}: file information
'''
def file_creation():
(file_path, name) = _path_split(path)
fileName, ext = os.path.splitext(name)
today = datetime.today()
new_binary = {"docType": "Binary"}
binary_id = self.db.create(new_binary)
self.db.put_attachment(self.db[binary_id], '', filename="file")
rev = self.db[binary_id]["_rev"]
if ext == ".txt" or ext == ".doc" or ext == ".pdf" or \
ext == ".ppt" or ext == ".odt" or ext == ".rtf":
file_class = "document"
elif ext == ".png" or ext == ".jpeg" or ext == ".jpg":
file_class = "image"
elif ext == ".mp3" or ext == ".wav":
file_class = "music"
elif ext == ".mp4" or ext == ".avi":
file_class = "video"
else:
file_class = "file"
newFile = {
"name": name,
"path": file_path,
"binary": {
"file": {
"id": binary_id,
"rev": rev
}
},
"size": 0,
"class": file_class,
"creationDate": today.strftime('%a %b %d %Y %H:%M:%S'),
"lastModification": today.strftime('%a %b %d %Y %H:%M:%S'),
"docType": "File"
}
self.db.create(newFile)
file_info.context = self.counter
file_info.is_directory = False
self.counter += 1
#replicate_from_local_ids([binary_id])
def replace_old_file(doc):
binary = self.db[doc['binary']['file']['id']]
self.db.delete(binary)
new_binary = {"docType": "Binary"}
binary_id = self.db.create(new_binary)
self.db.put_attachment(self.db[binary_id], '', filename="file")
rev = self.db[binary_id]["_rev"]
doc['size'] = 0
doc['binary']['file']['id'] = binary_id
doc['binary']['file']['rev'] = rev
self.db.save(doc)
(file_path, name) = _path_split_lower(path)
## Create file
if disposition == CreationDisposition(CREATE_NEW) or disposition == CreationDisposition(CREATE_ALWAYS) :
res = self.db.view('file/byFullPath', key=file_path+'/'+name)
if len(res) > 0 :
# File already exists
if disposition == CreationDisposition(CREATE_NEW):
# Return an error if disposition is CREATE_NEW
return -ERROR_ALREADY_EXISTS
else:
# Delete old file and create a new file if disposition is CREATE_ALWAYS
for doc in res:
replace_old_file(doc.value)
else:
# File doesn't exist
file_creation()
## Open file
else:
res = self.db.view('folder/byFullPath', key=file_path+'/'+name)
if len(res) > 0 or path == '\\':
file_info.is_directory = True
else:
res = self.db.view('file/byFullPath', key=file_path+'/'+name)
if len(res) > 0 :
file_info.is_directory = False
else:
return -ERROR_FILE_NOT_FOUND
return 0
disable_debug('create_file')
@wrap(None, DokanFileInfo)
@log('path', 'info')
def create_directory(self, path, file_info):
'''
Create new directory
path {string}: directory path
file_info {Object}: directory information
'''
(folder_path, name) = _path_split_lower(path)
# Check if folder already exists
res = self.db.view('folder/byFullPath', key=folder_path+'/'+name)
if len(res) > 0 :
return -ERROR_FILE_EXISTS
else:
res = self.db.view('file/byFullPath', key=folder_path+'/'+name)
if len(res) > 0 :
return -ERROR_FILE_EXISTS
else:
# Create folder
(folder_path, name) = _path_split(path)
self.db.create({
"name": name,
"path": folder_path,
"docType": "Folder"
})
return 0
disable_debug('create_directory')
@wrap(None, DokanFileInfo)
@log('path', 'info')
def open_directory(self, path, file_info):
'''
Open directory
path {string}: directory path
file_info {Object}: directory information
'''
folder_path = _normalize_path_win_to_DB_lower(path)
res = self.db.view('folder/byFullPath', key=folder_path)
if len(res) > 0 or path == '\\':
return 0
else:
return -ERROR_FILE_NOT_FOUND
disable_debug('open_directory')
@wrap(None, None, DokanFileInfo)
@log('path', 'buf', 'info')
def get_info(self, path, buffer, file_info):
'''
Get file or directory information
path {string}: directory path
buffer {buffer}: buffer to store file/directory information
file_info {Object}: directory information
'''
path = _normalize_path_win_to_DB_lower(path)
res = self.db.view('file/byFullPath', key=path)
if len(res) > 0:
# File
for doc in res:
if path.find('~') == -1:
# Standard file
buffer[0].dwFileAttributes = FILE_ATTRIBUTE_NORMAL
else:
# Temporary file
buffer[0].dwFileAttributes = FILE_ATTRIBUTE_HIDDEN
if 'size' in doc.value:
win_size = SizeConvert(doc.value['size']).convert()
else:
win_size = SizeConvert(1).convert()
buffer[0].nFileSizeHigh = win_size[0]
buffer[0].nFileSizeLow = win_size[1]
buffer[0].nNumberOfLinks = 1
win_index = SizeConvert(2).convert()
buffer[0].nFileIndexHigh = win_index[0]
buffer[0].nFileIndexLow = win_index[1]
lastModification = doc.value['lastModification'].split(' GMT')[0]
dt_converter = DateTimeConvertor(datetime.strptime(lastModification, '%a %b %d %Y %H:%M:%S'))
dc = dt_converter.convert()
if 'creationDate' in doc.value:
creationDate = doc.value['creationDate'].split(' GMT')[0]
dt_converter_creation = DateTimeConvertor(datetime.strptime(creationDate, '%a %b %d %Y %H:%M:%S'))
buffer[0].ftCreationTime = dt_converter_creation.convert()
else:
buffer[0].ftCreationTime = dc
buffer[0].ftLastAccessTime = dc
buffer[0].ftLastWriteTime = dc
else:
res = self.db.view('folder/byFullPath', key=path)
if len(res) > 0 or path is '\\':
# Folder
buffer[0].dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY
buffer[0].nFileSizeHigh = 0
buffer[0].nFileSizeLow = 0
buffer[0].nNumberOfLinks = 1
win_index = SizeConvert(1).convert()
buffer[0].nFileIndexHigh = win_index[0]
buffer[0].nFileIndexLow = win_index[1]
dt_converter = DateTimeConvertor(datetime.today())
dc = dt_converter.convert()
buffer[0].ftCreationTime = dc
buffer[0].ftLastAccessTime = dc
buffer[0].ftLastWriteTime = dc
else:
# Document doesn't exist
return -ERROR_FILE_NOT_FOUND
buffer[0].dwVolumeSerialNumber = self.serial_number
return 0
disable_debug('get_info')
@wrap(None, DokanFileInfo)
@log('path', 'info')
def cleanup(self, path, file_info):
path = _normalize_path_win_to_DB_lower(path)
'''
Clean file: Cleanup is invoked when the function CloseHandle in Windows
API is executed
path {string}: file/directory path
file_info {Object}: file/directory information
'''
if file_info.delete_on_close:
def delete_file(doc):
binary = self.db[doc['binary']['file']['id']]
self.db.delete(binary)
self.db.delete(self.db[doc['_id']])
res = self.db.view('file/byFullPath', key=path)
if len(res) > 0:
for doc in res:
doc = doc.value
delete_file(doc)
else:
return -ERROR_INVALID_HANDLE
file_info.context = 0
return 0
disable_debug('cleanup')
@wrap(None, DokanFileInfo)
@log('path', 'info')
def close(self, path, file_info):
'''
Close file
path {string}: file/directory path
file_info {Object}: file/directory information
'''
if file_info.context:
file_info.context = 0
return 0
else:
return 0
disable_debug('close')
@wrap(None, None, None, None, None, None, None, DokanFileInfo)
@log('name', 'name_size', 'serial', 'max_component_len', \
'fs_flags', 'fs_name', 'fs_name_size', 'info')
def get_volume_info(self, name_buff, name_size, sn, max_comonent_len, \
fs_flags, fs_name_buff, fs_name_size, file_info):
name = 'Digidisk'
fname = 'couchmontFS'
memmove(name_buff, LPWSTR(name), (len(name) + 1) * 2)
memmove(fs_name_buff, LPWSTR(fname), (len(fname) + 1) * 2)
sn[0] = self.serial_number
max_comonent_len[0] = 255000
flags = FILE_SUPPORTS_ENCRYPTION | FILE_UNICODE_ON_DISK | \
FILE_SUPPORTS_REMOTE_STORAGE | FILE_CASE_SENSITIVE_SEARCH
fs_flags[0] = flags
return 0
disable_debug('get_volume_info')
@wrap(None, None, None, DokanFileInfo)
@log('avail', 'total', 'free', 'info')
def get_free_space(self, free_bytes, total_bytes, total_free_bytes, file_info):
'''
TODOS
'''
free_bytes[0] = 1048576 - len('\\hello_world.txt')
total_bytes[0] = 1048576
total_free_bytes[0] = 1048576
return 0
disable_debug('get_free_space')
@wrap(None, None, None, DokanFileInfo)
@log('path', 'pattern', 'func', 'info')
def find_files_with_pattern(self, path, pattern, func, file_info):
'''
Find files with a specific pattern
path {string}: file/directory path
pattern {string}: parttern to find
func {function}: function to call with PWIN32_FIND_DATAW
file_info {Object}: file/directory information
'''
file_info_raw = file_info.raw()
new_path = _normalize_path_win_to_DB_lower(path)
# Files
res = self.db.view('file/byFolder', key=new_path)
for doc in res:
doc = doc.value
if self.name_in_expression(pattern, doc['name'], False):
if 'size' in doc:
win_size = SizeConvert(doc['size']).convert()
else:
win_size = SizeConvert(1).convert()
lastModification = doc['lastModification'].split(' GMT')[0]
dt_converter = DateTimeConvertor(datetime.strptime(lastModification, '%a %b %d %Y %H:%M:%S'))
dc = dt_converter.convert()
if 'creationDate' in doc:
creationDate = doc['creationDate'].split(' GMT')[0]
dt_converter_creation = DateTimeConvertor(datetime.strptime(creationDate, '%a %b %d %Y %H:%M:%S'))
dc_creation = dt_converter.convert()
else:
dc_creation = dc
if doc['name'].find('~') == -1:
info = WIN32_FIND_DATAW(
FILE_ATTRIBUTE_NORMAL, dc_creation, dc, dc,
win_size[0], win_size[1], 0, 0, doc['name'], ''
)
else:
info = WIN32_FIND_DATAW(
FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_TEMPORARY, dc_creation, dc, dc,
win_size[0], win_size[1], 0, 0, doc['name'], ''
)
func(PWIN32_FIND_DATAW(info), file_info_raw)
# Folders
res = self.db.view('folder/byFolder', key=new_path)
for doc in res:
doc = doc.value
if self.name_in_expression(pattern, doc['name'], False):
dc = DateTimeConvertor(datetime.today()).convert()
win_size = SizeConvert(1).convert()
info = WIN32_FIND_DATAW(
FILE_ATTRIBUTE_DIRECTORY, dc, dc, dc, win_size[0],
win_size[1], 0, 0, doc['name'], ''
)
func(PWIN32_FIND_DATAW(info), file_info_raw)
return 0
disable_debug('find_files_with_pattern')
@wrap(None, None, None, None, DokanFileInfo)
def set_time(self, path, creation, last_access, last_write, file_info):
return 0
disable_debug('set_time')
@wrap(None, None, DokanFileInfo)
def set_allocation_size(self, path, alloc, file_info):
return 0
disable_debug('set_allocation_size')
@wrap(None, None, None, None, None, DokanFileInfo)
def get_security_info(self, path, info, descr, length, needed_length, file_info):
return 0
disable_debug('get_security_info')
@wrap(None, None, None, None, DokanFileInfo)
def set_security_info(self, path, info, descr, length, file_info):
return 0
disable_debug('set_security_info')
@wrap(None, None, DokanFileInfo)
def set_attributes(self, path, attributes, file_info):
return 0
disable_debug('set_attributes')
@wrap(None, None, DokanFileInfo)
def set_end_of_file(self, path, length, file_info):
return 0
disable_debug('set_end_of_file')
@wrap(None, None, None, DokanFileInfo)
def lock_file(self, path, offset, length, file_info):
return 0
disable_debug('lock_file')
@wrap(None, None, None, DokanFileInfo)
def unlock_file(self, path, offset, length, file_info):
return 0
disable_debug('unlock_file')
@wrap(None, DokanFileInfo)
def flush(self, path, file_info):
return 0
disable_debug('flush')
@wrap(None, None, None, None, None, DokanFileInfo)
@log('path', 'buf', 'length', 'length', 'offset', 'info')
def read(self, path, buffer, length, buff_length, offset, file_info):
'''
Read file
path {string}: file/directory path
buffer {buffer}: buffer to store file content
length {integer}: max length to read
buff_length{LP_u_long}: pointer to buffer length
offser {integer}: file reading offset
file_info {Object}: file/directory information
'''
new_path = _normalize_path_win_to_DB_lower(path)
if file_info.context and new_path in self.read_current_file:
content = self.read_current_file[new_path]
else:
res = self.db.view('file/byFullPath', key=new_path)
if len(res) > 0:
for doc in res:
doc = doc.value
# Recover binary
try:
bin_id = doc['binary']['file']['id']
except Exception:
return -ERROR_INVALID_HANDLE
commande = ['curl', '-H', 'Content-Type: text/html',
'http://localhost:5984/cozy-files/%s/file' %bin_id]
process = subprocess.Popen(commande,
shell = True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
content, err = process.communicate()
# Save binary in read_current_file
self.read_current_file[new_path] = content
file_info.context = 1
else:
return -ERROR_INVALID_HANDLE
content_length = len(content)
if offset < content_length:
if offset + length > content_length:
length = content_length - offset
# Remove binary in read_current_file
del self.read_current_file[new_path]
else:
length = 0
memmove(buffer, content[offset:offset+length], length)
buff_length[0] = length
return 0
disable_debug('read')
@wrap(None, None, None , DokanFileInfo)
@log('path', 'path', 'bool', 'info')
def move(self, src, dst, replace, file_info):
'''
Move file or directory
src {string}: source file/directory path
dst {string}: destination file/directory path
replace {boolean}:
file_info {Object}: file/directory information
'''
def move_file(src, dst, doc):
(pathto, nameto) = _path_split(dst)
doc.update({"name":nameto, "path": pathto})
self.db.save(doc)
def move_folder(src, dst, doc):
pathfrom = _normalize_path_win_to_DB_lower(src)
(pathto, nameto) = _path_split(dst)
doc.update({"name":nameto, "path": pathto})
self.db.save(doc)
# Rename all subfiles
for res in self.db.view('file/byFolder', key=pathfrom):
filepathfrom = res.value['path'] + '/' + res.value['name']
filepathto = pathto + '/' + nameto + '/' + res.value['name']
move_file(filepathfrom, filepathto, res.value)
# Rename all subfolders
for res in self.db.view('folder/byFolder', key=pathfrom):
folderpathfrom = res.value['path'] + '/' + res.value['name']
folderpathto = pathto + '/' + nameto + '/' + res.value['name']
move_folder(folderpathfrom, folderpathto, res.value)
return 0
def move_doc():
pathfrom = _normalize_path_win_to_DB_lower(src)
res = self.db.view('file/byFullPath', key=pathfrom)
if len(res) > 0:
for doc in res:
doc = doc.value
move_file(src, dst, doc)
else:
res = self.db.view('folder/byFullPath', key=pathfrom)
if len(res) > 0:
for doc in res:
doc = doc.value
move_folder(src, dst, doc)
else:
return -ERROR_INVALID_HANDLE
(pathto, name) = _path_split_lower(dst)
res = self.db.view('folder/byFullPath', key=pathto+'/'+name)
if len(res) > 0:
if not replace:
return -ERROR_ALREADY_EXISTS
else:
for doc in res:
self.db.delete(doc.value['_id'])
move_doc()
return 0
else:
res = self.db.view('file/byFullPath', key=pathto+'/'+name)
if len(res) > 0:
if not replace:
return -ERROR_ALREADY_EXISTS
else:
for doc in res:
doc = doc.value
binary = self.db[doc['binary']['file']['id']]
self.db.delete(binary)
self.db.delete(self.db[doc['_id']])
move_doc()
return 0
else:
move_doc()
return 0
disable_debug('move')
@wrap(None, DokanFileInfo)
@log('path', 'info')
def delete_file(self, path, file_info):
'''
Delete file
path {string}: file path
file_info {Object}: file information
'''
path = _normalize_path_win_to_DB_lower(path)
res = self.db.view('file/byFullPath', key=path)
if len(res) > 0:
for doc in res:
doc = doc.value
binary = self.db[doc['binary']['file']['id']]
self.db.delete(binary)
self.db.delete(self.db[doc['_id']])
return 0
else:
return -ERROR_INVALID_HANDLE
disable_debug('delete_file')
@wrap(None, DokanFileInfo)
@log('path', 'info')
def delete_directory(self, path, file_info):
'''
Delete directory:
path {string}: directory path
file_info {Object}: directory information
'''
def delete_folder(folder):
self.db.delete(self.db[folder['_id']])
# Remove all subfiles
res = self.db.view('file/byFolder', key=path)
for sub_file in res:
delete_file(sub_file.value)
# Remove all subfolders
res = self.db.view('folder/byFolder', key=path)
for sub_folder in res:
delete_folder(sub_folder.value)
return 0
def delete_file(doc):
binary = self.db[doc['binary']['file']['id']]
self.db.delete(binary)
self.db.delete(self.db[doc['_id']])
path = _normalize_path_win_to_DB_lower(path)
res = self.db.view('folder/byFullPath', key=path)
if len(res) > 0:
for folder in res:
folder = folder.value
delete_folder(folder)
return 0
else:
return -ERROR_INVALID_HANDLE
disable_debug('delete_directory')
@wrap(None, None, None, None, None, DokanFileInfo)
@log('path', 'buf', 'length', 'written', 'offset', 'info')
def write(self, path, buffer, length, writen_length, offset, file_info):
'''
Write content in file
path {string}: file path
buffer {buffer}: content to write
length {integer}: content length to write
written_length {LP_u_long}: content length written
offset {integer}: file offset
file_info {Object}: file information
'''
new_path = _normalize_path_win_to_DB_lower(path)
res = self.db.view('file/byFullPath', key=new_path)
if len(res) > 0:
for doc in res:
# Recover binary
doc = doc.value
binary_id = doc["binary"]["file"]["id"]
buffer = string_at(buffer, length)
commande = ['curl', '-H', 'Content-Type: text/html',
'http://localhost:5984/cozy-files/%s/file' %binary_id]
process = subprocess.Popen(commande,
shell = True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
currentFile, err = process.communicate()
cmd = 'WMIC PROCESS get Caption,Commandline,Processid | grep %s' %file_info.process_id
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
microsoft = False
for line in proc.stdout:
line = str(line, encoding='utf8')
if not(line.find('Microsoft Office') is -1):
microsoft = True
if microsoft:
currentFile = currentFile[:offset] + buffer + currentFile[offset:]
else:
currentFile = currentFile[:offset] + buffer + currentFile[offset+length:]
self.db.put_attachment(self.db[binary_id],
currentFile,
filename = "file")
binary = self.db[binary_id]
doc['binary']['file']['rev'] = binary['_rev']
doc['size'] = len(currentFile)
today = datetime.today()
doc["lastModification"] = today.strftime('%a %b %d %Y %H:%M:%S')
self.db.save(doc)
writen_length[0] = length
replicate_from_local_ids([binary_id])
return 0
else:
return -ERROR_INVALID_HANDLE
disable_debug('write')
class App():
def __init__(self):
self.log = self.get_logger()
def get_logger(self):
logger = logging.getLogger('vdisk')
level = logging.DEBUG
logger.setLevel(level)
format = '[%(asctime)s] [%(thread)d] %(levelname)s: %(message)s'
formatter = logging.Formatter(format)
log_path = './logs/vdisk.log'
Handler = logging.handlers.TimedRotatingFileHandler
handler = Handler(log_path, when='D', interval=1, backupCount=5)
handler.setFormatter(formatter)
logger.addHandler(handler)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
return logger
def main():
app = App()
app.hwfs = Couchmount(app, 'H', DOKAN_OPTION_KEEP_ALIVE | DOKAN_OPTION_REMOVABLE, 5)
app.hwfs.start()
if __name__ == '__main__':
main()