forked from Tribler/tribler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosutils.py
261 lines (210 loc) · 7.64 KB
/
osutils.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
# Written by Arno Bakker, ABC authors
# see LICENSE.txt for license information
"""
OS-independent utility functions
get_home_dir() : Returns CSIDL_APPDATA i.e. App data directory on win32
get_picture_dir()
get_free_space(path)
"""
#
# Multiple methods for getting free diskspace
#
import sys
import os
import time
import binascii
import subprocess
import logging
logger = logging.getLogger(__name__)
def get_android_api_version():
"""
:return: integer Runtime API version or None.
"""
try:
from android import api_version
return api_version
except ImportError:
return None
def is_android():
"""
This functions checks whether Tribler is running on Android or not, using the Android runtime API version.
:return: boolean True if running on Android. False otherwise.
"""
return get_android_api_version() is not None
if sys.platform == "win32":
try:
from win32com.shell import shell, shellcon
def get_home_dir():
# http://www.mvps.org/access/api/api0054.htm
# CSIDL_PROFILE = &H28
# C:\Documents and Settings\username
return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_PROFILE)
def get_appstate_dir():
# http://www.mvps.org/access/api/api0054.htm
# CSIDL_APPDATA = &H1A
# C:\Documents and Settings\username\Application Data
return shell.SHGetSpecialFolderPath(0, shellcon.CSIDL_APPDATA)
def get_picture_dir():
# http://www.mvps.org/access/api/api0054.htm
# CSIDL_MYPICTURES = &H27
# C:\Documents and Settings\username\My Documents\My Pictures
return shell.SHGetSpecialFolderPath(0, 0x27)
def get_desktop_dir():
# http://www.mvps.org/access/api/api0054.htm
# CSIDL_DESKTOPDIRECTORY = &H10
# C:\Documents and Settings\username\Desktop
return shell.SHGetSpecialFolderPath(0, 0x10)
except ImportError:
def get_home_dir():
try:
# when there are special unicode characters in the username,
# the following will fail on python 2.4, 2.5, 2.x this will
# always succeed on python 3.x
return os.path.expanduser(u"~")
except Exception as unicode_error:
pass
# non-unicode home
home = os.path.expanduser("~")
head, tail = os.path.split(home)
dirs = os.listdir(head)
udirs = os.listdir(unicode(head))
# the character set may be different, but the string length is
# still the same
islen = lambda dir: len(dir) == len(tail)
dirs = filter(islen, dirs)
udirs = filter(islen, udirs)
if len(dirs) == 1 and len(udirs) == 1:
return os.path.join(head, udirs[0])
# remove all dirs that are equal in unicode and non-unicode. we
# know that we don't need these dirs because the initial
# expandusers would not have failed on them
for dir in dirs[:]:
if dir in udirs:
dirs.remove(dir)
udirs.remove(dir)
if len(dirs) == 1 and len(udirs) == 1:
return os.path.join(head, udirs[0])
# assume that the user has write access in her own
# directory. therefore we can filter out any non-writable
# directories
writable_udir = [udir for udir in udirs if os.access(udir, os.W_OK)]
if len(writable_udir) == 1:
return os.path.join(head, writable_udir[0])
# fallback: assume that the order of entries in dirs is the same
# as in udirs
for dir, udir in zip(dirs, udirs):
if dir == tail:
return os.path.join(head, udir)
# failure
raise unicode_error
def get_appstate_dir():
homedir = get_home_dir()
# 5 = XP, 6 = Vista
# [E1101] Module 'sys' has no 'getwindowsversion' member
# pylint: disable-msg=E1101
winversion = sys.getwindowsversion()
# pylint: enable-msg=E1101
if winversion[0] == 6:
appdir = os.path.join(homedir, u"AppData", u"Roaming")
else:
appdir = os.path.join(homedir, u"Application Data")
return appdir
def get_picture_dir():
return get_home_dir()
def get_desktop_dir():
home = get_home_dir()
return os.path.join(home, u"Desktop")
elif is_android():
def get_home_dir():
return os.path.realpath(os.environ['ANDROID_PRIVATE'])
def get_appstate_dir():
return os.path.join(get_home_dir(), '.Tribler')
def get_picture_dir():
return os.path.join(get_desktop_dir(), 'DCIM')
def get_desktop_dir():
return os.path.realpath(os.environ['EXTERNAL_STORAGE'])
else:
# linux or darwin (mac)
def get_home_dir():
return os.path.expanduser(u"~")
def get_appstate_dir():
return get_home_dir()
def get_picture_dir():
return get_desktop_dir()
def get_desktop_dir():
home = get_home_dir()
desktop = os.path.join(home, "Desktop")
if os.path.exists(desktop):
return desktop
else:
return home
def get_free_space(path):
if not os.path.exists(path):
return -1
if sys.platform == 'win32':
from win32file import GetDiskFreeSpaceEx
return GetDiskFreeSpaceEx(os.path.splitdrive(os.path.abspath(path))[0])[0]
else:
data = os.statvfs(path.encode("utf-8"))
return data.f_bavail * data.f_frsize
invalidwinfilenamechars = ''
for i in range(32):
invalidwinfilenamechars += chr(i)
invalidwinfilenamechars += '"*/:<>?\\|'
invalidlinuxfilenamechars = '/'
def fix_filebasename(name, unit=False, maxlen=255):
""" Check if str is a valid Windows file name (or unit name if unit is true)
* If the filename isn't valid: returns a corrected name
* If the filename is valid: returns the filename
"""
if unit and (len(name) != 2 or name[1] != ':'):
return 'c:'
if not name or name == '.' or name == '..':
return '_'
if unit:
name = name[0]
fixed = False
if len(name) > maxlen:
name = name[:maxlen]
fixed = True
fixedname = ''
spaces = 0
for c in name:
if sys.platform.startswith('win'):
invalidchars = invalidwinfilenamechars
else:
invalidchars = invalidlinuxfilenamechars
if c in invalidchars:
fixedname += '_'
fixed = True
else:
fixedname += c
if c == ' ':
spaces += 1
file_dir, basename = os.path.split(fixedname)
while file_dir != '':
fixedname = basename
file_dir, basename = os.path.split(fixedname)
fixed = True
if fixedname == '':
fixedname = '_'
fixed = True
if fixed:
return last_minute_filename_clean(fixedname)
elif spaces == len(name):
# contains only spaces
return '_'
else:
return last_minute_filename_clean(name)
def last_minute_filename_clean(name):
s = name.strip() # Arno: remove initial or ending space
if sys.platform == 'win32' and s.endswith('..'):
s = s[:-2]
return s
def startfile(filepath):
if sys.platform == 'darwin':
subprocess.call(('open', filepath))
elif sys.platform == 'linux2':
subprocess.call(('xdg-open', filepath))
elif hasattr(os, "startfile"):
os.startfile(filepath)