0
|
1 #!/usr/bin/python |
|
2 # -*- coding: utf-8 -*- |
|
3 |
|
4 """ |
|
5 gcp: Goffi's CoPier |
|
6 Copyright (C) 2010 Jérôme Poisson (goffi@goffi.org) |
|
7 |
|
8 This program is free software: you can redistribute it and/or modify |
|
9 it under the terms of the GNU General Public License as published by |
|
10 the Free Software Foundation, either version 3 of the License, or |
|
11 (at your option) any later version. |
|
12 |
|
13 This program is distributed in the hope that it will be useful, |
|
14 but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
16 GNU General Public License for more details. |
|
17 |
|
18 You should have received a copy of the GNU General Public License |
|
19 along with this program. If not, see <http://www.gnu.org/licenses/>. |
|
20 """ |
|
21 |
|
22 ### logging ### |
|
23 import logging |
|
24 from logging import debug, info, error, warning |
|
25 logging.basicConfig(level=logging.DEBUG, |
|
26 format='%(message)s') |
|
27 ### |
|
28 import sys |
|
29 import os,os.path |
|
30 from optparse import OptionParser #To be replaced by argparse ASAP |
1
|
31 import cPickle as pickle |
0
|
32 try: |
|
33 import gobject |
|
34 #DBus |
|
35 import dbus, dbus.glib |
|
36 import dbus.service |
|
37 import dbus.mainloop.glib |
|
38 except ImportError,e: |
|
39 error("Error during import") |
|
40 error("Please check dependecies:",e) |
|
41 exit(2) |
|
42 try: |
|
43 from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed |
|
44 pbar_available=True |
|
45 except ImportError, e: |
|
46 info ('ProgressBar not available, please download it at http://pypi.python.org/pypi/progressbar') |
|
47 info ('Progress bar deactivated\n--\n') |
|
48 pbar_available=False |
|
49 |
|
50 NAME = "gcp (Goffi's copier)" |
|
51 NAME_SHORT = "gcp" |
|
52 VERSION = '0.1' |
|
53 |
|
54 ABOUT = NAME+" v"+VERSION+""" (c) Jérôme Poisson (aka Goffi) 2010 |
|
55 |
|
56 --- |
|
57 """+NAME+""" Copyright (C) 2010 Jérôme Poisson |
|
58 This program comes with ABSOLUTELY NO WARRANTY; |
|
59 This is free software, and you are welcome to redistribute it |
|
60 under certain conditions. |
|
61 --- |
|
62 |
|
63 This software is an advanced file copier |
|
64 Get the latest version at http://www.goffi.org |
|
65 """ |
|
66 |
|
67 const_DBUS_INTERFACE = "org.goffi.gcp" |
|
68 const_DBUS_PATH = "/org/goffi/gcp" |
|
69 |
|
70 |
|
71 class DbusObject(dbus.service.Object): |
|
72 |
|
73 def __init__(self, gcp, bus, path): |
|
74 self._gcp = gcp |
|
75 dbus.service.Object.__init__(self, bus, path) |
|
76 debug("Init DbusObject...") |
|
77 self.cb={} |
|
78 |
|
79 @dbus.service.method(const_DBUS_INTERFACE, |
|
80 in_signature='', out_signature='s') |
|
81 def getVersion(self): |
|
82 """Get gcp version |
|
83 @return: version as string""" |
|
84 return VERSION |
|
85 |
|
86 @dbus.service.method(const_DBUS_INTERFACE, |
1
|
87 in_signature='ss', out_signature='bs') |
0
|
88 def addArgs(self, source_path, args): |
|
89 """Add arguments to gcp as if there were entered on its own command line |
1
|
90 @param source_path: current working dir to use as base for arguments, as given by os.getcwd() |
|
91 @param args: serialized (wich pickle) list of strings - without command name -, as given by sys.argv[1:]. |
|
92 @return: success (boolean) and error message if any (string)""" |
|
93 try: |
|
94 args = pickle.loads(str(args)) |
|
95 except TypeError, pickle.UnpicklingError: |
|
96 return (False, "INTERNAL ERROR: invalid arguments") |
0
|
97 return self._gcp.parseArguments(args, source_path) |
|
98 |
|
99 class GCP(): |
|
100 |
|
101 def __init__(self): |
|
102 try: |
|
103 sessions_bus = dbus.SessionBus() |
|
104 db_object = sessions_bus.get_object(const_DBUS_INTERFACE, |
|
105 const_DBUS_PATH) |
|
106 self.gcp_main = dbus.Interface(db_object, |
|
107 dbus_interface=const_DBUS_INTERFACE) |
|
108 self._main_instance = False |
|
109 |
|
110 except dbus.exceptions.DBusException,e: |
|
111 if e._dbus_error_name=='org.freedesktop.DBus.Error.ServiceUnknown': |
|
112 self.launchDbusMainInstance() |
|
113 debug ("gcp launched") |
|
114 self._main_instance = True |
|
115 else: |
|
116 raise e |
|
117 |
|
118 def launchDbusMainInstance(self): |
|
119 debug ("Init DBus...") |
|
120 session_bus = dbus.SessionBus() |
|
121 self.dbus_name = dbus.service.BusName(const_DBUS_INTERFACE, session_bus) |
|
122 self.dbus_object = DbusObject(self, session_bus, const_DBUS_PATH) |
|
123 |
|
124 self.copy_list = [] |
|
125 self.mounts = self.__getMountPoints() |
1
|
126 self.files_left = 0 |
|
127 self.bytes_left = 0 |
0
|
128 |
|
129 def getFsType(self, path): |
|
130 fs='' |
|
131 for mount in self.mounts: |
2
|
132 if path.startswith(mount) and len(self.mounts[mount])>=len(fs): |
0
|
133 fs = self.mounts[mount] |
|
134 return fs |
|
135 |
|
136 def __getMountPoints(self): |
|
137 """Parse /proc/mounts to get currently mounted devices""" |
|
138 #TODO: reparse when a new device is added/a device is removed |
1
|
139 #(check freedesktop mounting signals) |
0
|
140 ret = {} |
|
141 try: |
|
142 with open("/proc/mounts",'r') as mounts: |
|
143 for line in mounts.readlines(): |
|
144 fs_spec, fs_file, fs_vfstype, fs_mntops, fs_freq, fs_passno = line.split(' ') |
|
145 ret[fs_file] = fs_vfstype |
|
146 except: |
|
147 error ("Can't read mounts table") |
|
148 return ret |
|
149 |
1
|
150 def __appendToList(self, path, destpath, options): |
0
|
151 """Add a file to the copy list |
|
152 @param path: absolute path of file |
|
153 @param options: options as return by optparse""" |
1
|
154 debug ("Adding to copy list: %s ==> %s (%s)", path, destpath, self.getFsType(destpath)) |
|
155 try: |
|
156 self.bytes_left+=os.path.getsize(path) |
|
157 self.files_left+=1 |
|
158 self.copy_list.append((path, destpath, options)) |
|
159 print "total size:", float(self.bytes_left/1024/1024), "Mb (%i)" % self.files_left |
|
160 except OSError,e: |
|
161 error("Can't copy %(path)s: %(exception)s" % {'path':path, 'exception':e.strerror}) |
0
|
162 |
1
|
163 |
|
164 def __appendDirToList(self, dirpath, destpath, options): |
0
|
165 """Add recursively directory to the copy list |
|
166 @param path: absolute path of dir |
|
167 @param options: options as return by optparse""" |
|
168 try: |
|
169 for filename in os.listdir(dirpath): |
|
170 filepath = os.path.join(dirpath,filename) |
|
171 if os.path.isdir(filepath): |
1
|
172 full_destpath = os.path.join(destpath,filename) |
|
173 self.__appendDirToList(filepath, full_destpath, options) |
0
|
174 else: |
1
|
175 self.__appendToList(filepath, destpath, options) |
0
|
176 except OSError,e: |
|
177 error("Can't copy %(path)s: %(exception)s" % {'path':dirpath, 'exception':e.strerror}) |
|
178 |
|
179 def __checkArgs(self, options, source_path, args): |
|
180 """Check thats args are files, and add them to copy list""" |
1
|
181 assert(len (args)>=2) |
|
182 try: |
|
183 destpath = os.path.normpath(os.path.join(os.path.expanduser(source_path), args.pop())) |
|
184 except OSError,e: |
|
185 error ("Invalid destpath: %s",e) |
|
186 |
0
|
187 for path in args: |
1
|
188 abspath = os.path.normpath(os.path.join(os.path.expanduser(source_path), path)) |
0
|
189 if not os.path.exists(abspath): |
|
190 warning("The path given in arg doesn't exist or is not accessible: %s",abspath) |
|
191 else: |
|
192 if os.path.isdir(abspath): |
1
|
193 full_destpath = destpath if os.path.isabs(path) else os.path.normpath(os.path.join(destpath, path)) |
0
|
194 if not options.recursive: |
|
195 warning ('omitting directory "%s"' % abspath) |
|
196 else: |
1
|
197 self.__appendDirToList(abspath, full_destpath, options) |
0
|
198 else: |
1
|
199 self.__appendToList(abspath, destpath, options) |
0
|
200 |
|
201 |
|
202 def parseArguments(self, full_args=sys.argv[1:], source_path = os.getcwd()): |
1
|
203 """Parse arguments and add files to queue |
|
204 @param full_args: list of arguments strings (without program name) |
|
205 @param source_path: path from where the arguments come, ad given by os.getcwd() |
|
206 @return: a tuple (boolean, message) where the boolean is the success of the arguments |
|
207 validation, and message is the error message to print when necessary""" |
0
|
208 _usage=""" |
|
209 %prog [options] FILE1 [FILE2 ...] DEST |
|
210 |
|
211 %prog --help for options list |
|
212 """ |
1
|
213 for idx in range(len(full_args)): |
|
214 if isinstance(full_args[idx], unicode): |
|
215 #We don't want unicode as some filenames can be invalid unicode |
|
216 full_args[idx] = full_args[idx].encode('utf-8') |
|
217 |
0
|
218 parser = OptionParser(usage=_usage,version=ABOUT) |
|
219 |
|
220 parser.add_option("-r", "--recursive", action="store_true", default=False, |
|
221 help="copy directories recursively") |
|
222 |
1
|
223 parser.add_option("--no-unicode-fix", action="store_true", default=False, |
|
224 help="don't fixe name encoding errors") #TODO |
0
|
225 (options, args) = parser.parse_args(full_args) |
|
226 |
|
227 if not self._main_instance: |
1
|
228 info ("There is already one instance of %s running, pluging to it" % NAME_SHORT) |
|
229 #XXX: we have to serialize data as dbus only accept valid unicode, and filenames |
|
230 # can have invalid unicode. |
|
231 return self.gcp_main.addArgs(os.getcwd(),pickle.dumps(full_args)) |
0
|
232 else: |
1
|
233 if len(args) < 2: |
|
234 _error_msg = "Wrong number of arguments" |
|
235 return (False, _error_msg) |
0
|
236 debug("adding args to gcp: %s",args) |
|
237 self.__checkArgs(options, source_path, args) |
1
|
238 return (True,'') |
0
|
239 |
|
240 def go(self): |
1
|
241 """Launch main loop""" |
0
|
242 self.loop = gobject.MainLoop() |
|
243 try: |
|
244 self.loop.run() |
|
245 except KeyboardInterrupt: |
|
246 info("User interruption: good bye") |
|
247 |
|
248 |
|
249 if __name__ == "__main__": |
|
250 gcp = GCP() |
1
|
251 success,message = gcp.parseArguments() |
|
252 if not success: |
|
253 error(message) |
|
254 exit(1) |
0
|
255 if gcp._main_instance: |
|
256 gcp.go() |
|
257 |