filesystem.py 12.7 KB
Newer Older
Marcel's avatar
Marcel committed
1
# -*- coding: utf-8 -*-
2

Marcel's avatar
Marcel committed
3
# imports
4
import os
5
import re
6
7
8
9
10
from datetime import datetime
import locale
import shutil
from mimetypes import guess_type
from zipfile import ZipFile
11
import json
Gero Müller's avatar
Gero Müller committed
12
import stat
13
import base64
14

15
16
17
import logging
logger = logging.getLogger(__name__)

18
19
20
class FileSystem(object):

    FILE_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "ps", "eps", "pdf", "txt", "xml", "py", "c", "cpp", "root", "pxlio"]
Marcel's avatar
Marcel committed
21
22
23
24
25
    BROWSER_EXTENSIONS = ["png", "jpg", "jpeg", "bmp"]
    ADDITIONAL_MIMES = {
        "pxlio": "text/plain",
        "root" : "text/plain"
    }
26
27
28
29
30

    def __init__(self):
        # allowed extensions
        self.allowed_extensions = FileSystem.FILE_EXTENSIONS

31
    def setup(self, basedir=None):
Marcel's avatar
Marcel committed
32
33
        if basedir is None:
            basedir = self.expand('~/')
murban's avatar
murban committed
34
        if not os.path.isdir(basedir):
Marcel's avatar
Marcel committed
35
            raise Exception("Basedir '%s' does not exist!" % basedir)
murban's avatar
murban committed
36
37
        # the basedir
        self.basedir = os.path.join(basedir, ".vispa")
38
39
40
41
42
        if os.path.isdir(self.basedir):
            return "Basedir already exists"
        else: 
            os.makedirs(self.basedir, 0700)
            return "Basedir now exists"
43

murban's avatar
murban committed
44
    def get_mime_type(self, filepath):
Marcel's avatar
Marcel committed
45
        filepath = self.expand(filepath)
46
47
48
49
50
51
52
53
        mime, encoding = guess_type(filepath)
        if mime is not None:
            return mime
        ext = filepath.split(".")[-1]
        if ext is not None and ext != "" and ext.lower() in FileSystem.ADDITIONAL_MIMES.keys():
            return FileSystem.ADDITIONAL_MIMES[ext]
        return None

murban's avatar
murban committed
54
    def check_file_extension(self, path, extensions=[]):
Marcel's avatar
Marcel committed
55
        path = self.expand(path)
56
57
58
59
60
61
62
63
        if (len(extensions) == 0):
            return True
        for elem in extensions:
            elem = elem if elem.startswith(".") else "." + elem
            if path.lower().endswith(elem.lower()):
                return True
        return False

Marcel's avatar
Marcel committed
64
65
    def exists(self, path, type=None):
        # type may be 'f' or 'd'
Marcel's avatar
Marcel committed
66
        path = self.expand(path)
67
68
        # path exists physically?
        if not os.path.exists(path):
Marcel's avatar
Marcel committed
69
70
            return None
        # type correct?
71
72
73
74
75
76
77
        target_type = 'd' if os.path.isdir(path) else 'f'
        if not type:
            return target_type
        type = type.lower()
        if type not in ['f', 'd']:
            return None
        return target_type if target_type == type else None
78

Gero Müller's avatar
Gero Müller committed
79
80
81
    def get_file_list(self, path, deep=False,
                      filter=None, reverse=False,
                      hide_hidden=True, encode_json=True):
82
        filter = filter or []
83
        filelist = []
Marcel's avatar
Marcel committed
84
        path_expand = self.expand(path)
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        try:
            for elem in os.listdir(path_expand):
                # hide hidden files?
                if elem.startswith('.') and hide_hidden:
                    continue

                # excluded by filters?
                match = False
                for filter_elem in filter:
                    if re.search(filter_elem, elem):
                        match = True
                if match != reverse:
                    continue

                fullpath = os.path.join(path_expand, elem)

Gero Müller's avatar
Gero Müller committed
101
                stats = os.lstat(fullpath)
102
103
                size = stats.st_size
                mtime = stats.st_mtime
104

Gero Müller's avatar
Gero Müller committed
105
                if stat.S_ISDIR(stats.st_mode):
106
                    filelist.append({'name': elem, 'type': 'd', 'mtime': mtime, 'size': size})
107
108
109
                    if deep:
                        filelist.extend(self.get_file_list(fullpath, deep, filter, reverse))
                else:
110
                    filelist.append({'name': elem, 'type': 'f', 'mtime': mtime, 'size': size})
111
112
113
114
115
116
        except Exception, e:
            filelist.append({'warning': str(e)})

        # Determine the parent
        parentpath = path_expand[:-1] if path_expand.endswith(os.sep) and path_expand!=os.sep else path_expand
        parentpath = os.path.dirname(path_expand)
117
118
119
        data = {'filelist': filelist, 'parentpath': parentpath}
        if encode_json:
            return json.dumps(data)
120
121
        else:
            return data
122

123
    def get_suggestions(self, path, length=1, append_hidden=True, encode_json=True):
Marcel's avatar
Marcel committed
124
125
126
        suggestions = []
        source, filter = None, None
        # does the path exist?
Marcel's avatar
Marcel committed
127
128
        path_expanded = self.expand(path)
        if os.path.exists(path_expanded):
Marcel's avatar
Marcel committed
129
            # dir case
Marcel's avatar
Marcel committed
130
            if os.path.isdir(path_expanded):
Marcel's avatar
Marcel committed
131
132
133
134
135
136
137
138
139
140
141
                if path.endswith('/'):
                    source = path
                else:
                    suggestions.append(path + os.sep)
                    return suggestions
            # file case
            else:
                return suggestions
        else:
            # try to estimate source and filter
            head, tail = os.path.split(path)
Marcel's avatar
Marcel committed
142
            if os.path.isdir(os.path.expanduser(os.path.expandvars(head))):
Marcel's avatar
Marcel committed
143
144
145
146
147
148
149
                source = head
                filter = tail

        # return empty suggestions when source is not set
        if not source:
            return suggestions

Marcel's avatar
Marcel committed
150
        files = os.listdir(os.path.expanduser(os.path.expandvars(source)))
Marcel's avatar
Marcel committed
151
152
        # resort?
        if append_hidden:
153
            files = sorted(map(lambda f: str(f), files), cmp=file_compare, key=str.lower)
154
        while (len(suggestions) < length or length == 0) and len(files):
Marcel's avatar
Marcel committed
155
156
157
158
            file = files.pop(0)
            if filter and not file.startswith(filter):
                continue
            suggestion = os.path.join(source, file)
Marcel's avatar
Marcel committed
159
            if not suggestion.endswith('/') and os.path.isdir(os.path.expanduser(os.path.expandvars(suggestion))):
Marcel's avatar
Marcel committed
160
161
162
                suggestion += '/'
            suggestions.append(suggestion)

163
        return suggestions if not encode_json else json.dumps(suggestions)
164

murban's avatar
murban committed
165
    def cut_slashs(self, path):
Marcel's avatar
Marcel committed
166
        path = self.expand(path)
murban's avatar
murban committed
167
        path = path[1:] if path.startswith(os.sep) else path
168
169
        if path == "":
            return path
murban's avatar
murban committed
170
        path = path[:-1] if path.endswith(os.sep) else path
171
172
        return path

murban's avatar
murban committed
173
    def create_folder(self, path, name):
Marcel's avatar
Marcel committed
174
        path = self.expand(path)
175
        # folder with the same name existent?
176
        name = self.handle_file_name_collision(name, path)
Marcel's avatar
Marcel committed
177
        fullpath = os.path.join(path, name)
178
179
180
181
182
183
        try:
            os.mkdir(fullpath)
        except Exception as e:
            #raise Exception("You don't have the permission to create this folder!")
            raise Exception(str(e))

murban's avatar
murban committed
184
    def create_file(self, path, name):
Marcel's avatar
Marcel committed
185
        path = self.expand(path)
186
        # file with the same name existent?
187
        name = self.handle_file_name_collision(name, path)
Marcel's avatar
Marcel committed
188
        fullpath = os.path.join(path, name)
189
190
191
192
193
194
        try:
            f = file(fullpath, "w")
            f.close()
        except Exception as e:
            raise Exception(str(e))

195
196
197
198
199
200
201
202
203
204
    def rename(self, path, name, new_name, force=False):
        try:
            if force == False:
                new_name = self.handle_file_name_collision(new_name, path)
            name = os.path.join(path, name)
            new_name = os.path.join(path, new_name)
            os.renames(name, new_name)
            return
        except Exception, e:
            return str(e)
205

murban's avatar
murban committed
206
207
    def remove(self, path):
        if isinstance(path, list):
208
209
210
            for p in path:
                self.remove(p)
        else:
Marcel's avatar
Marcel committed
211
212
213
214
215
            path = self.expand(path)
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)
216
217

    def compress(self, path, paths, name):
Martin Urban's avatar
Martin Urban committed
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
        try:
            # paths has to be a list of strings
            paths = paths if isinstance(paths, (list, tuple)) else [paths]

            path = path if not path.endswith(os.sep) else path[:-1]

            name = name if name.endswith(".zip") else name + ".zip"
            name = self.handle_file_name_collision(name, path)

            fullpath = os.path.join(path, name)

            with ZipFile(fullpath, "w") as archive:
            # archive =  ZipFile(fullpath, "w")
                path = path if path.startswith(os.sep) else path
                for p in paths:
                    if p is None or p == "":
                        continue
                    p = p if p.startswith(os.sep) else os.sep + path
                    if os.path.isdir(p):
                        for elem in os.listdir(p):
                            fullp = os.path.join(p, elem)
                            if os.path.isdir(fullp):
                                paths.append(fullp)
                            else:
                                ap = fullp[len(path):] if fullp.startswith(path) else fullp
                                archive.write(fullp, ap)

                    ap = p[len(path):] if p.startswith(path) else p
                    archive.write(p, ap)
        # archive.close()
        except Exception, e:
            return str(e)
250

251
    def paste(self, path, fullsrc, cut):
Marcel's avatar
Marcel committed
252
        # TODO
253
254
255
256
        path = self.expand(path)
        if isinstance(fullsrc, (list, tuple)):
            for p in fullsrc:
                p = self.expand(p)
murban's avatar
murban committed
257
                self.paste(path, p, cut)
258
259
            return True

260
261
262
263
264
265
        # fulltarget = os.path.join(path, fullsrc.split(os.sep)[-1])
        logger.error("")
        target = self.handle_file_name_collision(fullsrc.split(os.sep)[-1], path)
        fulltarget = os.path.join(path, target)
        logger.error(cut)
        logger.error("")
266

267
268
        if os.path.isdir(fullsrc):
            shutil.copytree(fullsrc, fulltarget)
269
            if cut:
270
                shutil.rmtree(fullsrc)
271
        else:
272
            shutil.copy2(fullsrc, fulltarget)
273
            if cut:
274
                os.remove(fullsrc)
275

Marcel's avatar
Marcel committed
276
    def save_file(self, path, content, binary=False, force=True):
277
278
279
        logger.info(path)
        logger.info("\n\n")
        return
Marcel's avatar
Marcel committed
280
        path = self.expand(path)
Marcel's avatar
Marcel committed
281
        # check if file already exists
murban's avatar
murban committed
282
        if os.path.exists(path) and not force:
Marcel's avatar
Marcel committed
283
            return False
Marcel's avatar
Marcel committed
284
        if binary:
285
286
287
288
289
            out = file(path, "wb")
        else:
            out = file(path, "w")
        logger.info("saved")
        logger.info("\n\n")
Marcel's avatar
Marcel committed
290
        out.write(content)
291
        out.close()
Marcel's avatar
Marcel committed
292
        return True
293

Gero Müller's avatar
Gero Müller committed
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    def save_file_content(self, filename, content,
                        path=None, force=True, append=False):
        #check write permissions
        #if not self.checkPermission(username, vPath, 'w'):
        #    return False, "Permission denied!"

        if path:
            filename = os.path.join(path, filename)
        filename = self.expand(filename)

        #check if file already exists
        if os.path.exists(filename) and not force:
            return False, "The file '%s' already exists!" % filename

        out = open(filename, "ab+" if append else "wb")
        out.write(content)
        out.close()

        return True, "File saved!"

murban's avatar
murban committed
314
    def get_file_content(self, path):
Marcel's avatar
Marcel committed
315
        path = self.expand(path)
Gero Müller's avatar
Gero Müller committed
316
        f = open(path, "rb")
317
318
        content = f.read()
        f.close()
Marcel's avatar
Marcel committed
319
        return content
320

Marcel's avatar
Marcel committed
321
    def get_mtime(self, path):
Marcel's avatar
Marcel committed
322
        path = self.expand(path)
Marcel's avatar
Marcel committed
323
324
        return os.path.getmtime(path)

murban's avatar
murban committed
325
    def is_browser_file(self, path):
Marcel's avatar
Marcel committed
326
        path = self.expand(path)
327
        extension = path.split(".")[-1]
328
        return extension.lower() in FileSystem.BROWSER_EXTENSIONS
329

murban's avatar
murban committed
330
    def handle_file_name_collision(self, name, path):
331
        # collision?
murban's avatar
murban committed
332
        files = os.listdir(path)
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
        if name not in files:
            return name

        # when this line is reached, there is a collision!

        # cut the file extension
        extension = name.split(".")[-1]
        prename = None
        if name == extension:
            extension = ""
            prename = name
        else:
            prename = name.split("." + extension)[0]

        # has the name already a counter at its end?
        hasCounter = False
        preprename = None
        counter = prename.split("_")[-1]

        if counter != prename:
            try:
                counter = int(counter)
                hasCounter = True
                preprename = "_".join(prename.split("_")[:-1])
            except:
                pass

        if hasCounter:
            # increment and try again
            counter += 1
            newname = "%s_%d%s" % (preprename, counter, "" if extension == "" else "." + extension)
        else:
            newname = "%s_1%s" % (prename, "" if extension == "" else "." + extension)

        # return
murban's avatar
murban committed
368
        return self.handle_file_name_collision(newname, path)
Marcel's avatar
Marcel committed
369

Marcel's avatar
Marcel committed
370
371
    def expand(self, path):
        return os.path.expanduser(os.path.expandvars(path))
Marcel's avatar
Marcel committed
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389

def string_compare(a, b):
    if a == b:
        return 0
    elif a > b:
        return 1
    else:
        return -1

def file_compare(a, b):
    if not a.startswith('.') and not b.startswith('.'):
        return string_compare(a, b)
    elif a.startswith('.') and b.startswith('.'):
        return string_compare(a, b)
    elif a.startswith('.') and not b.startswith('.'):
        return 1
    elif not a.startswith('.') and b.startswith('.'):
        return -1