summaryrefslogtreecommitdiff
path: root/soundconverter/fileoperations.py
blob: 535cd01cf1ac58d0e5bb806aa83b7efbabff926c (plain)
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# SoundConverter - GNOME application for converting between audio formats.
# Copyright 2004 Lars Wirzenius
# Copyright 2005-2012 Gautier Portet
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
# USA

import os
import urllib
import urlparse
import gnomevfs

from utils import log
from error import show_error

use_gnomevfs = False

def unquote_filename(filename):
    return urllib.unquote(filename)


def beautify_uri(uri):
    return unquote_filename(uri).split('file://')[-1]


def vfs_walk(uri):
    """similar to os.path.walk, but with gnomevfs.

    uri -- the base folder uri.
    return a list of uri.

    """
    if str(uri)[-1] != '/':
        uri = uri.append_string('/')

    filelist = []

    try:
        dirlist = gnomevfs.open_directory(uri, gnomevfs.FILE_INFO_FOLLOW_LINKS)
        for file_info in dirlist:
            try:
                if file_info.name[0] == '.':
                    continue

                if file_info.type == gnomevfs.FILE_TYPE_DIRECTORY:
                    filelist.extend(
                        vfs_walk(uri.append_path(file_info.name)))

                if file_info.type == gnomevfs.FILE_TYPE_REGULAR:
                    filelist.append(str(uri.append_file_name(file_info.name)))
            except ValueError:
                # this can happen when you do not have sufficent
                # permissions to read file info.
                log("skipping: \'%s\'" % file_info.name)
    except:
        log("skipping: '%s\'" % uri)
        return filelist

    return filelist


def vfs_makedirs(path_to_create):
    """Similar to os.makedirs, but with gnomevfs."""

    uri = gnomevfs.URI(path_to_create)
    path = uri.path

    # start at root
    uri = uri.resolve_relative('/')

    for folder in path.split('/'):
        if not folder:
            continue
        uri = uri.append_string(folder.replace('%2f', '/'))
        try:
            gnomevfs.make_directory(uri, 0777)
        except gnomevfs.FileExistsError:
            pass
        except:
            return False
    return True


def vfs_unlink(filename):
    """Delete a gnomevfs file."""
    
    gnomevfs.unlink(gnomevfs.URI(filename))


def vfs_rename(original, newname):
    """Rename a gnomevfs file"""
    
    uri = gnomevfs.URI(newname)
    dirname = uri.parent
    if dirname and not gnomevfs.exists(dirname):
        log('Creating folder: \'%s\'' % dirname)
        if not vfs_makedirs(str(dirname)):
            show_error(_('Cannot create folder!'), unquote_filename(dirname.path))
            return 'cannot-create-folder'

    try:
        gnomevfs.xfer_uri(gnomevfs.URI(original), uri,
                          gnomevfs.XFER_REMOVESOURCE,
                          gnomevfs.XFER_ERROR_MODE_ABORT,
                          gnomevfs.XFER_OVERWRITE_MODE_ABORT
                         )
    except Exception as error:
        # TODO: maybe we need a special case here. If dest folder is unwritable. Just stop.
        # or an option to stop all processing.
        show_error(_('Error while renaming file!'), '%s: %s' % (beautify_uri(newname), error))
        return 'cannot-rename-file'


def vfs_exists(filename):
    try:
        return gnomevfs.exists(filename)
    except:
        return False


def filename_to_uri(filename):
    """Convert a filename to a valid uri.
    Filename can be a relative or absolute path, or an uri.
    """
    if '://' not in filename:
        # convert local filename to uri
        filename = urllib.pathname2url(os.path.abspath(filename))
    filename = str(gnomevfs.URI(filename))
    return filename


# GStreamer gnomevfssrc helpers

def vfs_encode_filename(filename):
    return filename_to_uri(filename)


def file_encode_filename(filename):
    return gnomevfs.get_local_path_from_uri(filename).replace(' ', '\ ')