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
5
6
7
8
9
import os
from datetime import datetime
import locale
import shutil
from mimetypes import guess_type
from zipfile import ZipFile
Marcel's avatar
Marcel committed
10

11
12
13
14
15
16
17
18
19
20
21
22

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

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

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

murban's avatar
murban committed
69
    def get_file_list(self, path, deep, ext_filter=[], reverse=False):
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        dirlist = os.listdir(path)
        returnlist = []
        for elem in dirlist:
            fullPath = os.path.join(path, elem)
            locale.setlocale(locale.LC_ALL, '')
            stats = os.stat(path + ('' if path.endswith('/') else '/') + elem)
            size = stats.st_size
            size = locale.format("%d", size, grouping=True)
            mtime = stats.st_mtime
            mtime = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")
            if os.path.isdir(fullPath):
                if elem.startswith("."):
                    continue
                returnlist.append({'name': elem, 'type': 'folder', 'parent': path + '/', 'extension': '', 'mtime': mtime, 'size': size, "path": os.path.join(path, elem)})
                if deep:
murban's avatar
murban committed
85
                    returnlist.extend(self.get_file_list(fullPath, deep, ext_filter, reverse))
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
            else:
                if elem.startswith("."):
                    continue
                extension = elem.split(".")[-1]
                returnlist.append({'name': elem, 'type': 'file', 'parent': path + '/', 'extension': extension, 'mtime': mtime, 'size': size, "path": os.path.join(path, elem)})
        # apply filters
        filelist = []
        # delete "." in file extensions
        ext_filter = map(lambda ext: ext if not ext.startswith(".") else ext[1:], ext_filter)
        for elem in returnlist:
            if (elem["type"] == "folder"):
                filelist.append(elem)
                continue
            if not reverse:
                if str(elem["extension"]) not in ext_filter:
                    filelist.append(elem)
            else:
                if str(elem["extension"]) in ext_filter:
                    filelist.append(elem)
        return filelist

Marcel's avatar
Marcel committed
107
108
109
110
    def get_suggestions(self, path, length=1, append_hidden=True):
        suggestions = []
        source, filter = None, None
        # does the path exist?
Marcel's avatar
Marcel committed
111
        if os.path.exists(os.path.expanduser(os.path.expandvars(path))):
Marcel's avatar
Marcel committed
112
            # dir case
Marcel's avatar
Marcel committed
113
            if os.path.isdir(os.path.expanduser(os.path.expandvars(path))):
Marcel's avatar
Marcel committed
114
115
116
117
118
119
120
121
122
123
124
                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
125
            if os.path.isdir(os.path.expanduser(os.path.expandvars(head))):
Marcel's avatar
Marcel committed
126
127
128
129
130
131
132
                source = head
                filter = tail

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

Marcel's avatar
Marcel committed
133
        files = os.listdir(os.path.expanduser(os.path.expandvars(source)))
Marcel's avatar
Marcel committed
134
135
136
        # resort?
        if append_hidden:
            files = sorted(files, cmp=file_compare, key=str.lower)
137
        while (len(suggestions) < length or length == 0) and len(files):
Marcel's avatar
Marcel committed
138
139
140
141
            file = files.pop(0)
            if filter and not file.startswith(filter):
                continue
            suggestion = os.path.join(source, file)
Marcel's avatar
Marcel committed
142
            if not suggestion.endswith('/') and os.path.isdir(os.path.expanduser(os.path.expandvars(suggestion))):
Marcel's avatar
Marcel committed
143
144
145
146
                suggestion += '/'
            suggestions.append(suggestion)

        return suggestions
147

murban's avatar
murban committed
148
    def cut_slashs(self, path):
149
150
151
152
153
154
        path = path[1:] if path.startswith("/") else path
        if path == "":
            return path
        path = path[:-1] if path.endswith("/") else path
        return path

murban's avatar
murban committed
155
    def create_folder(self, path, name):
156
157
158
159
160
161
162
163
164
165
        # folder with the same name existent?
        fullpath = os.path.join(path, name)
        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
166
    def create_file(self, path, name):
167
168
169
170
171
172
173
174
175
176
177
        # file with the same name existent?
        fullpath = os.path.join(path, name)
        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
178
    def rename_folder(self, path, name):
179
180
181
182
183
184
185
186
187
188
189
190
        # file or folder
        if not os.path.isdir(path):
            raise Exception("Renaming file with folder function!")

        # folder with the same name existent?
        path = path if not path.endswith("/") else path[:-1]
        fullpath = os.path.join("/".join(path.split("/")[:-1]), name)
        if os.path.exists(fullpath):
            raise Exception("Name already in use!")

        os.renames(path, fullpath)

murban's avatar
murban committed
191
    def rename_file(self, path, name):
192
193
194
195
196
197
198
199
200
201
202
        # file or folder
        if os.path.isdir(path):
            raise Exception("Renaming folder with file function!")

        # file with the same name existent?
        fullpath = os.path.join("/".join(path.split("/")[:-1]), name)
        if os.path.exists(fullpath):
            raise Exception("Name already in use!")

        os.renames(path, fullpath)

murban's avatar
murban committed
203
204
    def remove(self, path):
        if isinstance(path, list):
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
            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]

        path = path if not path.endswith("/") else path[:-1]

        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
227
        path = path if path.startswith("/") else path
228
229
230
        for p in paths:
            if p is None or p == "":
                continue
murban's avatar
murban committed
231
            p = p if p.startswith(os.sep) else os.sep + path
232
233
234
235
236
237
238
239
240
241
242
243
244
245
            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(fullpp, ap)

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

        archive.close()

murban's avatar
murban committed
246
247
248
249
    def paste(self, path, target, cut):
        if isinstance(target, list):
            for p in target:
                self.paste(path, p, cut)
250
251
            return True

murban's avatar
murban committed
252
        fulltarget = os.path.join(path, target.split("/")[-1])
253
254
255
256

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

murban's avatar
murban committed
257
258
        if os.path.isdir(target):
            shutil.copytree(target, fulltarget)
259
            if cut:
murban's avatar
murban committed
260
                shutil.rmtree(target)
261
        else:
murban's avatar
murban committed
262
            shutil.copy2(target, path)
263
            if cut:
murban's avatar
murban committed
264
                os.remove(target)
265

murban's avatar
murban committed
266
    def save_file_content(self, path, content, force=True):
Marcel's avatar
Marcel committed
267
268
        path = os.path.expandvars(os.path.expanduser(path))
        # check if file already exists
murban's avatar
murban committed
269
        if os.path.exists(path) and not force:
Marcel's avatar
Marcel committed
270
271
272
            return False
        out = open(path, "wb")
        out.write(content)
273
        out.close()
Marcel's avatar
Marcel committed
274
        return True
275

murban's avatar
murban committed
276
    def get_file_content(self, path):
Marcel's avatar
Marcel committed
277
        path = os.path.expandvars(os.path.expanduser(path))
murban's avatar
murban committed
278
        f = open(path, "r")
279
280
        content = f.read()
        f.close()
Marcel's avatar
Marcel committed
281
        return content
282

Marcel's avatar
Marcel committed
283
284
285
286
    def get_mtime(self, path):
        path = os.path.expandvars(os.path.expanduser(path))
        return os.path.getmtime(path)

murban's avatar
murban committed
287
    def is_browser_file(self, path):
288
        extension = path.split(".")[-1]
murban's avatar
murban committed
289
        return extension in FileSystem.BROWSER_EXTENSIONS
290

murban's avatar
murban committed
291
    def handle_file_name_collision(self, name, path):
292
        # collision?
murban's avatar
murban committed
293
        files = os.listdir(path)
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
        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
329
        return self.handle_file_name_collision(newname, path)
Marcel's avatar
Marcel committed
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348


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