2380ed96993ccb91c63635e6f465892be6726781
[vuplus_dvbapp] / lib / python / Tools / Directories.py
1 # -*- coding: utf-8 -*-
2
3 from os import path as os_path, mkdir, rmdir, system, walk, stat as os_stat, listdir, readlink, makedirs, error as os_error, symlink, access, F_OK, R_OK, W_OK
4 from stat import S_IMODE
5 from re import compile
6
7 try:
8         from os import chmod
9         have_chmod = True
10 except:
11         have_chmod = False
12
13 try:
14         from os import utime
15         have_utime = True
16 except:
17         have_utime = False
18
19 SCOPE_TRANSPONDERDATA = 0
20 SCOPE_SYSETC = 1
21 SCOPE_FONTS = 2
22 SCOPE_SKIN = 3
23 SCOPE_SKIN_IMAGE = 4
24 SCOPE_USERETC = 5
25 SCOPE_CONFIG = 6
26 SCOPE_LANGUAGE = 7
27 SCOPE_HDD = 8
28 SCOPE_PLUGINS = 9
29 SCOPE_MEDIA = 10
30 SCOPE_PLAYLIST = 11
31 SCOPE_CURRENT_SKIN = 12
32 SCOPE_DEFAULTDIR = 13
33 SCOPE_DEFAULTPARTITION = 14
34 SCOPE_DEFAULTPARTITIONMOUNTDIR = 15
35 SCOPE_METADIR = 16
36
37 PATH_CREATE = 0
38 PATH_DONTCREATE = 1
39 PATH_FALLBACK = 2
40 defaultPaths = {
41                 SCOPE_TRANSPONDERDATA: ("/etc/", PATH_DONTCREATE),
42                 SCOPE_SYSETC: ("/etc/", PATH_DONTCREATE),
43                 SCOPE_FONTS: ("/usr/share/fonts/", PATH_DONTCREATE),
44                 SCOPE_CONFIG: ("/etc/enigma2/", PATH_CREATE),
45                 SCOPE_PLUGINS: ("/usr/lib/enigma2/python/Plugins/", PATH_CREATE),
46
47                 SCOPE_LANGUAGE: ("/usr/share/enigma2/po/", PATH_DONTCREATE),
48
49                 SCOPE_SKIN: ("/usr/share/enigma2/", PATH_DONTCREATE),
50                 SCOPE_SKIN_IMAGE: ("/usr/share/enigma2/", PATH_DONTCREATE),
51                 SCOPE_HDD: ("/hdd/movie/", PATH_DONTCREATE),
52                 SCOPE_MEDIA: ("/media/", PATH_DONTCREATE),
53                 SCOPE_PLAYLIST: ("/etc/enigma2/playlist/", PATH_CREATE),
54                 
55                 SCOPE_USERETC: ("", PATH_DONTCREATE), # user home directory
56                 
57                 SCOPE_DEFAULTDIR: ("/usr/share/enigma2/defaults/", PATH_CREATE),
58                 SCOPE_DEFAULTPARTITION: ("/dev/mtdblock/6", PATH_DONTCREATE),
59                 SCOPE_DEFAULTPARTITIONMOUNTDIR: ("/usr/share/enigma2/dealer", PATH_CREATE),
60                 SCOPE_METADIR: ("/usr/lib/enigma2/python/Plugins/meta", PATH_CREATE),
61         }
62
63 FILE_COPY = 0 # copy files from fallback dir to the basedir
64 FILE_MOVE = 1 # move files
65 PATH_COPY = 2 # copy the complete fallback dir to the basedir
66 PATH_MOVE = 3 # move the fallback dir to the basedir (can be used for changes in paths)
67 fallbackPaths = {
68                 SCOPE_CONFIG: [("/home/root/", FILE_MOVE),
69                                            ("/usr/share/enigma2/defaults/", FILE_COPY)],
70                 SCOPE_HDD: [("/hdd/movies", PATH_MOVE)]
71         }
72
73 def resolveFilename(scope, base = "", path_prefix = None):
74         if base[0:2] == "~/":
75                 # you can only use the ~/ if we have a prefix directory
76                 assert path_prefix is not None
77                 base = os_path.join(path_prefix, base[2:])
78
79         # don't resolve absolute paths
80         if base[0:1] == '/':
81                 return base
82
83         if scope == SCOPE_CURRENT_SKIN:
84                 from Components.config import config
85                 tmp = defaultPaths[SCOPE_SKIN]
86                 pos = config.skin.primary_skin.value.rfind('/')
87                 if pos != -1:
88                         path = tmp[0]+config.skin.primary_skin.value[:pos+1]
89                 else:
90                         path = tmp[0]
91         else:
92                 tmp = defaultPaths[scope]
93                 path = tmp[0]
94
95         flags = tmp[1]
96
97         if flags == PATH_CREATE:
98                 if not pathExists(path):
99                         mkdir(path)
100
101         fallbackPath = fallbackPaths.get(scope)
102
103         if fallbackPath and not fileExists(path + base):
104                 for x in fallbackPath:
105                         if x[1] == FILE_COPY:
106                                 if fileExists(x[0] + base):
107                                         system("cp " + x[0] + base + " " + path + base)
108                                         break
109                         elif x[1] == FILE_MOVE:
110                                 if fileExists(x[0] + base):
111                                         system("mv " + x[0] + base + " " + path + base)
112                                         break
113                         elif x[1] == PATH_COPY:
114                                 if pathExists(x[0]):
115                                         if not pathExists(defaultPaths[scope][0]):
116                                                 mkdir(path)
117                                         system("cp -a " + x[0] + "* " + path)
118                                         break
119                         elif x[1] == PATH_MOVE:
120                                 if pathExists(x[0]):
121                                         system("mv " + x[0] + " " + path)
122                                         break
123
124         # FIXME: we also have to handle DATADIR etc. here.
125         return path + base
126         # this is only the BASE - an extension must be added later.
127
128 def pathExists(path):
129         return os_path.exists(path)
130
131 def isMount(path):
132         return os_path.ismount(path)
133
134 def createDir(path, makeParents = False):
135         try:
136                 if makeParents:
137                         makedirs(path)
138                 else:
139                         mkdir(path)
140         except:
141                 ret = 0
142         else:
143                 ret = 1
144         return ret
145
146 def removeDir(path):
147         try:
148                 rmdir(path)
149         except:
150                 ret = 0
151         else:
152                 ret = 1
153         return ret
154
155 def fileExists(f, mode='r'):
156         if mode == 'r':
157                 acc_mode = R_OK
158         elif mode == 'w':
159                 acc_mode = W_OK
160         else:
161                 acc_mode = F_OK
162         return access(f, acc_mode)
163
164 def getRecordingFilename(basename, dirname = None):
165         # filter out non-allowed characters
166         non_allowed_characters = "/.\\:*?<>|\""
167         filename = ""
168         
169         basename = basename.replace('\xc2\x86', '').replace('\xc2\x87', '')
170         
171         for c in basename:
172                 if c in non_allowed_characters or ord(c) < 32:
173                         c = "_"
174                 filename += c
175
176         if dirname is not None:
177                 filename = ''.join((dirname, filename))
178
179         if len(filename) > 240:
180                 filename = filename[:240]
181
182         i = 0
183         while True:
184                 path = resolveFilename(SCOPE_HDD, filename)
185                 if i > 0:
186                         path += "_%03d" % i
187                 try:
188                         open(path + ".ts")
189                         i += 1
190                 except IOError:
191                         return path
192
193 # this is clearly a hack:
194 def InitFallbackFiles():
195         resolveFilename(SCOPE_CONFIG, "userbouquet.favourites.tv")
196         resolveFilename(SCOPE_CONFIG, "bouquets.tv")
197         resolveFilename(SCOPE_CONFIG, "userbouquet.favourites.radio")
198         resolveFilename(SCOPE_CONFIG, "bouquets.radio")
199
200 # returns a list of tuples containing pathname and filename matching the given pattern
201 # example-pattern: match all txt-files: ".*\.txt$"
202 def crawlDirectory(directory, pattern):
203         expression = compile(pattern)
204         list = []
205         for root, dirs, files in walk(directory):
206                 for file in files:
207                         if expression.match(file) is not None:
208                                 list.append((root, file))
209         return list
210
211 def copyfile(src, dst):
212         try:
213                 f1 = open(src, "rb")
214                 if os_path.isdir(dst):
215                         dst = os_path.join(dst, os_path.basename(src))
216                 f2 = open(dst, "w+b")
217                 while True:
218                         buf = f1.read(16*1024)
219                         if not buf:
220                                 break
221                         f2.write(buf)
222                 st = os_stat(src)
223                 mode = S_IMODE(st.st_mode)
224                 if have_chmod:
225                         chmod(dst, mode)
226                 if have_utime:
227                         utime(dst, (st.st_atime, st.st_mtime))
228         except:
229                 print "copy", src, "to", dst, "failed!"
230                 return -1
231         return 0
232
233 def copytree(src, dst, symlinks=False):
234         names = listdir(src)
235         if os_path.isdir(dst):
236                 dst = os_path.join(dst, os_path.basename(src))
237                 if not os_path.isdir(dst):
238                         mkdir(dst)
239         else:
240                 makedirs(dst)
241         for name in names:
242                 srcname = os_path.join(src, name)
243                 dstname = os_path.join(dst, name)
244                 try:
245                         if symlinks and os_path.islink(srcname):
246                                 linkto = readlink(srcname)
247                                 symlink(linkto, dstname)
248                         elif os_path.isdir(srcname):
249                                 copytree(srcname, dstname, symlinks)
250                         else:
251                                 copyfile(srcname, dstname)
252                 except:
253                         print "dont copy srcname (no file or link or folder)"
254         try:
255                 st = os_stat(src)
256                 mode = S_IMODE(st.st_mode)
257                 if have_chmod:
258                         chmod(dst, mode)
259                 if have_utime:
260                         utime(dst, (st.st_atime, st.st_mtime))
261         except:
262                 print "copy stats for", src, "failed!"