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