filesystem.py 11.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
Marcel's avatar
Marcel committed
13

14
15
16
17
18
19
20
21
22
23
24
25

class FileSystem(object):

    FILE_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "ps", "eps", "pdf", "txt", "xml", "py", "c", "cpp", "root", "pxlio"]
    BROWSER_EXTENSIONS = ["png", "jpg", "jpeg", "bmp", "pdf"]
    ADDITIONAL_MIMES = {"pxlio": "text/plain",
                        "root" : "text/plain"}

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

26
27
28
    def setup(self, basedir=None):
        if basedir==None:
            basedir = os.path.expanduser("~")
murban's avatar
murban committed
29
30
31
32
        if not os.path.isdir(basedir):
            raise Exception("Basedir ("+str(basedir)+") does not exist!")
        # the basedir
        self.basedir = os.path.join(basedir, ".vispa")
33
34
35
36
37
        if os.path.isdir(self.basedir):
            return "Basedir already exists"
        else: 
            os.makedirs(self.basedir, 0700)
            return "Basedir now exists"
38

murban's avatar
murban committed
39
    def get_mime_type(self, filepath):
40
41
42
43
44
45
46
47
        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
48
    def check_file_extension(self, path, extensions=[]):
49
50
51
52
53
54
55
56
        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
57
58
59
    def exists(self, path, type=None):
        # type may be 'f' or 'd'
        if path:
60
            path = os.path.expanduser(os.path.expandvars(path))
61
62
        # path exists physically?
        if not os.path.exists(path):
Marcel's avatar
Marcel committed
63
64
            return None
        # type correct?
65
66
67
68
69
70
71
        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
72

73
    def get_file_list(self, path, deep=False, filter=[], reverse=False, hide_hidden=True, encode_json=False):
74
        filelist = []
75
        path_expand = os.path.expanduser(os.path.expandvars(path))
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        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
92
                stats = os.stat(fullpath)
93
94
                size = stats.st_size
                mtime = stats.st_mtime
95

Gero Müller's avatar
Gero Müller committed
96
                if stat.S_ISDIR(stats.st_mode):
97
                    filelist.append({'name': elem, 'type': 'd', 'mtime': mtime, 'size': size})
98
99
100
                    if deep:
                        filelist.extend(self.get_file_list(fullpath, deep, filter, reverse))
                else:
101
                    filelist.append({'name': elem, 'type': 'f', 'mtime': mtime, 'size': size})
102
103
104
105
106
107
        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)
108
109
110
        data = {'filelist': filelist, 'parentpath': parentpath}
        if encode_json:
            return json.dumps(data)
111
112
        else:
            return data
113

114

115
    def get_suggestions(self, path, length=1, append_hidden=True, encode_json=False):
Marcel's avatar
Marcel committed
116
117
118
        suggestions = []
        source, filter = None, None
        # does the path exist?
Marcel's avatar
Marcel committed
119
        if os.path.exists(os.path.expanduser(os.path.expandvars(path))):
Marcel's avatar
Marcel committed
120
            # dir case
Marcel's avatar
Marcel committed
121
            if os.path.isdir(os.path.expanduser(os.path.expandvars(path))):
Marcel's avatar
Marcel committed
122
123
124
125
126
127
128
129
130
131
132
                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
133
            if os.path.isdir(os.path.expanduser(os.path.expandvars(head))):
Marcel's avatar
Marcel committed
134
135
136
137
138
139
140
                source = head
                filter = tail

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

Marcel's avatar
Marcel committed
141
        files = os.listdir(os.path.expanduser(os.path.expandvars(source)))
Marcel's avatar
Marcel committed
142
143
        # resort?
        if append_hidden:
144
            files = sorted(map(lambda f: str(f), files), cmp=file_compare, key=str.lower)
145
        while (len(suggestions) < length or length == 0) and len(files):
Marcel's avatar
Marcel committed
146
147
148
149
            file = files.pop(0)
            if filter and not file.startswith(filter):
                continue
            suggestion = os.path.join(source, file)
Marcel's avatar
Marcel committed
150
            if not suggestion.endswith('/') and os.path.isdir(os.path.expanduser(os.path.expandvars(suggestion))):
Marcel's avatar
Marcel committed
151
152
153
                suggestion += '/'
            suggestions.append(suggestion)

154
        return suggestions if not encode_json else json.dumps(suggestions)
155

murban's avatar
murban committed
156
    def cut_slashs(self, path):
murban's avatar
murban committed
157
        path = path[1:] if path.startswith(os.sep) else path
158
159
        if path == "":
            return path
murban's avatar
murban committed
160
        path = path[:-1] if path.endswith(os.sep) else path
161
162
        return path

murban's avatar
murban committed
163
    def create_folder(self, path, name):
164
        # folder with the same name existent?
165
        fullpath = os.path.expanduser(os.path.expandvars(os.path.join(path, name)))
166
167
168
169
170
171
172
173
        if os.path.isdir(fullpath):
            raise Exception("Name already in use!")
        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
174
    def create_file(self, path, name):
175
        # file with the same name existent?
176
        fullpath = os.path.expanduser(os.path.expandvars(os.path.join(path, name)))
177
178
179
180
181
182
183
184
185
        if os.path.exists(fullpath):
            raise Exception("Name already in use!")
        try:
            f = file(fullpath, "w")
            f.close()
        except Exception as e:
            raise Exception(str(e))
        

murban's avatar
murban committed
186
    def rename_folder(self, path, name):
187
188
189
190
191
        # file or folder
        if not os.path.isdir(path):
            raise Exception("Renaming file with folder function!")

        # folder with the same name existent?
murban's avatar
murban committed
192
193
        path = path if not path.endswith(os.sep) else path[:-1]
        fullpath = os.path.join(os.sep.join(path.split(os.sep)[:-1]), name)
194
195
196
197
198
        if os.path.exists(fullpath):
            raise Exception("Name already in use!")

        os.renames(path, fullpath)

murban's avatar
murban committed
199
    def rename_file(self, path, name):
200
201
202
203
204
        # file or folder
        if os.path.isdir(path):
            raise Exception("Renaming folder with file function!")

        # file with the same name existent?
murban's avatar
murban committed
205
        fullpath = os.path.join(os.sep.join(path.split(os.sep)[:-1]), name)
206
207
208
209
210
        if os.path.exists(fullpath):
            raise Exception("Name already in use!")

        os.renames(path, fullpath)

murban's avatar
murban committed
211
212
    def remove(self, path):
        if isinstance(path, list):
213
214
215
216
217
218
219
220
221
222
223
224
225
            for p in path:
                self.remove(p)
            return True

        if os.path.isdir(path):
            shutil.rmtree(path)
        else:
            os.remove(path)

    def compress(self, path, paths, name):
        # paths has to be a list of strings
        paths = paths if isinstance(paths, list) else [paths]

murban's avatar
murban committed
226
        path = path if not path.endswith(os.sep) else path[:-1]
227
228
229
230
231
232
233
234

        fullpath = os.path.join(path, "%s.zip" % name)

        if os.path.exists(fullpath):
            raise Exception("Name already in use!")

        archive = ZipFile(fullpath, "w")

murban's avatar
murban committed
235
        path = path if path.startswith(os.sep) else path
236
237
238
        for p in paths:
            if p is None or p == "":
                continue
murban's avatar
murban committed
239
            p = p if p.startswith(os.sep) else os.sep + path
240
241
242
243
244
245
246
            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
247
                        archive.write(fullp, ap)
248
249
250
251
252
253

            ap = p[len(path):] if p.startswith(path) else p
            archive.write(p, ap)

        archive.close()

murban's avatar
murban committed
254
255
256
257
    def paste(self, path, target, cut):
        if isinstance(target, list):
            for p in target:
                self.paste(path, p, cut)
258
259
            return True

murban's avatar
murban committed
260
        fulltarget = os.path.join(path, target.split(os.sep)[-1])
261
262
263
264

        if os.path.exists(fulltarget):
            raise Exception("Name already in use!")

murban's avatar
murban committed
265
266
        if os.path.isdir(target):
            shutil.copytree(target, fulltarget)
267
            if cut:
murban's avatar
murban committed
268
                shutil.rmtree(target)
269
        else:
murban's avatar
murban committed
270
            shutil.copy2(target, path)
271
            if cut:
murban's avatar
murban committed
272
                os.remove(target)
273

murban's avatar
murban committed
274
    def save_file_content(self, path, content, force=True):
Marcel's avatar
Marcel committed
275
276
        path = os.path.expandvars(os.path.expanduser(path))
        # check if file already exists
murban's avatar
murban committed
277
        if os.path.exists(path) and not force:
Marcel's avatar
Marcel committed
278
279
280
            return False
        out = open(path, "wb")
        out.write(content)
281
        out.close()
Marcel's avatar
Marcel committed
282
        return True
283

murban's avatar
murban committed
284
    def get_file_content(self, path):
Marcel's avatar
Marcel committed
285
        path = os.path.expandvars(os.path.expanduser(path))
murban's avatar
murban committed
286
        f = open(path, "r")
287
288
        content = f.read()
        f.close()
Marcel's avatar
Marcel committed
289
        return content
290

Marcel's avatar
Marcel committed
291
292
293
294
    def get_mtime(self, path):
        path = os.path.expandvars(os.path.expanduser(path))
        return os.path.getmtime(path)

murban's avatar
murban committed
295
    def is_browser_file(self, path):
296
        extension = path.split(".")[-1]
murban's avatar
murban committed
297
        return extension in FileSystem.BROWSER_EXTENSIONS
298

murban's avatar
murban committed
299
    def handle_file_name_collision(self, name, path):
300
        # collision?
murban's avatar
murban committed
301
        files = os.listdir(path)
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
        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
337
        return self.handle_file_name_collision(newname, path)
Marcel's avatar
Marcel committed
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356


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