forked from mountainstorm/MobileDevice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
afcmediadirectory.py
executable file
·380 lines (339 loc) · 11.2 KB
/
afcmediadirectory.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#!/usr/bin/python
# coding: utf-8
# Copyright (c) 2013 Mountainstorm
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from amdevice import *
from afc import *
class AFCMediaDirectory(AFC):
def __init__(self, amdevice):
s = amdevice.start_service(AMSVC_AFC)
if s is None:
raise RuntimeError(u'Unable to launch:', AMSVC_AFC)
AFC.__init__(self, s)
def transfer_application(self, path, progress=None):
u'''Transfers an application bundle to the device; into the
/PublicStaging directory
Arguments:
path -- the local path to the file to transfer
progress -- the callback to get notified of the transfer process
(defaults to none)
Error:
Raises RuntimeError on error
'''
# Technically you could use this on any AFC connection but it only makes
# sense to use it on the MediaDirectory - as it hard coded moves stuff
# to /PublicStaging.
def callback(cfdict, arg):
pass
cfpath = CFTypeFrom(path)
cb = AMDeviceNotificationCallback(callback)
if progress is not None:
cb = AMDeviceNotificationCallback(progress)
err = AMDeviceTransferApplication(self.s, cfpath, None, cb, None)
CFRelease(cfpath)
if err != MDERR_OK:
raise RuntimeError(u'Unable to transfer application')
def register_argparse_afc(cmdargs):
import argparse
import sys
import afcapplicationdirectory
import afccrashlogdirectory
import afcmediadirectory
import afcroot
import time
import posixpath
import pprint
def printdir(afc, path, recurse):
dirlist = []
rows = []
colmax = [0, 0, 0, 0]
print "afc: ", path
for name in afc.listdir(path):
isdir = u''
info = afc.lstat(posixpath.join(path, name))
if info.st_ifmt == stat.S_IFDIR:
isdir = u'/'
dirlist.append(posixpath.join(path, name))
types = {
stat.S_IFSOCK: u's',
stat.S_IFLNK: u'l',
stat.S_IFREG: u'-',
stat.S_IFBLK: u'b',
stat.S_IFDIR: u'd',
stat.S_IFCHR: u'c',
stat.S_IFIFO: u'p'
}
modtime = long(info.st_mtime)
if long(time.time()) - modtime > (60*60*24*365):
# only show year if its over a year old (ls style)
strtime = time.strftime(u'%d %b %Y', time.gmtime(modtime))
else:
strtime = time.strftime(u'%d %b %H:%M', time.gmtime(modtime))
islink = u''
if info.st_ifmt == stat.S_IFLNK:
islink = u' -> ' + afc.readlink(posixpath.join(path, name))
row = (
types[info.st_ifmt],
info.st_size,
strtime,
name + isdir + islink
)
rows.append(row)
for i in range(len(row)):
if len(row[i]) > colmax[i]:
colmax[i] = len(row[i])
for row in rows:
print(
row[0].ljust(colmax[0]) + u' ' +
row[1].rjust(colmax[1]) + u' ' +
row[2].ljust(colmax[2]) + u' ' +
row[3])
if recurse:
for name in dirlist:
print(u'\n' + name)
printdir(afc, name, recurse)
def get_afc(args, dev):
retval = None
if args.path.startswith(u'/var/mobile/Media'):
retval = afcmediadirectory.AFCMediaDirectory(dev)
args.path = args.path[len(u'/var/mobile/Media'):]
elif args.m:
retval = afcmediadirectory.AFCMediaDirectory(dev)
elif args.c:
retval = afccrashlogdirectory.AFCCrashLogDirectory(dev)
elif args.app is not None:
retval = afcapplicationdirectory.AFCApplicationDirectory(
dev,
args.app.decode(u'utf-8')
)
else:
retval = afcroot.AFCRoot(dev)
return retval
def cmd_ls(args, dev):
afc = get_afc(args, dev)
printdir(afc, args.path.decode(u'utf-8'), args.r)
afc.disconnect()
def cmd_mkdir(args, dev):
afc = get_afc(args, dev)
afc.mkdir(args.path)
afc.disconnect()
def cmd_rm(args, dev):
afc = get_afc(args, dev)
afc.remove(args.path)
afc.disconnect()
def cmd_rmdir(args, dev):
def del_logs(afc, path):
dir_list = []
info = afc.listdir(path)
for name in afc.listdir(path):
info = afc.lstat(posixpath.join(path, name))
if info.st_ifmt == stat.S_IFDIR:
dir_list.append(posixpath.join(path, name))
elif info.st_ifmt == stat.S_IFLNK:
pass # XXX handle symlinks e.g. LatestCrash*
else:
# 删除对应crash
afc.unlink(posixpath.join(path, name))
for names in dir_list:
del_logs(afc, names)
afc = get_afc(args, dev)
del_logs(afc, args.path)
afc.disconnect()
def cmd_ln(args, dev):
# XXX unable to make linking work?
afc = get_afc(args, dev)
# if we're using the default mediadirectory then adjust the link
if args.link.startswith(u'/var/mobile/Media'):
args.link = args.link[len(u'/var/mobile/Media'):]
if args.s:
afc.symlink(args.path, args.link)
else:
afc.link(args.path, args.link)
afc.disconnect()
def cmd_get(args, dev):
dest = args.dest
if dest[-1] == os.sep:
# trailing seperator so dest has same name as src
dest = posixpath.join(dest, posixpath.basename(args.path))
afc = get_afc(args, dev)
s = afc.open(args.path, u'r')
d = open(dest, u'w+')
d.write(s.readall())
d.close()
s.close()
afc.disconnect()
def cmd_put(args, dev):
if args.path[-1] == os.sep:
# trailing seperator so dest has same name as src
args.path = posixpath.join(args.path, posixpath.basename(args.src))
afc = get_afc(args, dev)
d = afc.open(args.path, u'w')
s = open(args.src, u'r')
d.write(s.read())
s.close()
d.close()
afc.disconnect()
def preview_file(afc, path):
s = afc.open(path, u'r')
d = s.readall()
s.close()
p = dict_from_plist_encoding(d)
if p is not None:
pprint.pprint(p)
else:
print(d)
# XXX add extra preview code for other common types
def cmd_view(args, dev):
afc = get_afc(args, dev)
path = args.path.decode(u'utf-8')
files = []
try:
# check for directory preview
for f in afc.listdir(path):
files.append(posixpath.join(path, f))
except OSError:
files = [path] # its not a directory
for f in files:
preview_file(afc, f)
afc.disconnect()
# afc command
afcparser = cmdargs.add_parser(
u'afc',
help=u'commands to manipulate files via afc'
)
afcgroup = afcparser.add_mutually_exclusive_group()
afcgroup.add_argument(
u'-a',
metavar=u'app',
dest=u'app',
help=u'reverse domain name of application; device paths become relative to app container'
)
afcgroup.add_argument(
u'-c',
action=u'store_true',
help=u'crashlogs; device paths become relative to crash log container'
)
afcgroup.add_argument(
u'-m',
action=u'store_true',
help=u'device paths become relative to /var/mobile/media (saves typing)'
)
afccmd = afcparser.add_subparsers()
# ls command
lscmd = afccmd.add_parser(
u'ls',
help=u'lists the contents of the directory'
)
lscmd.add_argument(
u'-r',
action=u'store_true',
help=u'if specified listing is recursive'
)
lscmd.add_argument(
u'path',
help=u'path on the device to list'
)
lscmd.set_defaults(func=cmd_ls)
# mkdir command
mkdircmd = afccmd.add_parser(
u'mkdir',
help=u'creates a directory'
)
mkdircmd.add_argument(
u'path',
help=u'path of the dir to create'
)
mkdircmd.set_defaults(func=cmd_mkdir)
# rmdir / rm
rmcmd = afccmd.add_parser(
u'rm',
help=u'remove file'
)
rmcmd.add_argument(
u'path',
help=u'the path to delete'
)
rmcmd.set_defaults(func=cmd_rm)
rmdircmd = afccmd.add_parser(
u'rmdir',
help=u'remove directory/file'
)
rmdircmd.add_argument(
u'path',
help=u'the path to delete'
)
rmdircmd.set_defaults(func=cmd_rmdir)
# ln
lncmd = afccmd.add_parser(
u'ln',
help=u'create a link (symbolic or hard)'
)
lncmd.add_argument(
u'path',
help=u'the pre-existing path to link to'
)
lncmd.add_argument(
u'link',
help=u'the path for the link'
)
lncmd.add_argument(
u'-s',
action=u'store_true',
help=u'create a symbolic link'
)
lncmd.set_defaults(func=cmd_ln)
# get
getcmd = afccmd.add_parser(
u'get',
help=u'retrieve a file from the device'
)
getcmd.add_argument(
u'path',
help=u'path on the device to retrieve'
)
getcmd.add_argument(
u'dest',
help=u'local path to write file to'
)
getcmd.set_defaults(func=cmd_get)
# put
putcmd = afccmd.add_parser(
u'put',
help=u'upload a file from the device'
)
putcmd.add_argument(
u'src',
help=u'local path to read file from'
)
putcmd.add_argument(
u'path',
help=u'path on the device to write'
)
putcmd.set_defaults(func=cmd_put)
# view
viewcmd = afccmd.add_parser(
u'view',
help=u'retrieve a file from the device and preview as txt'
)
viewcmd.add_argument(
u'path',
help=u'path on the device to retrieve'
)
viewcmd.set_defaults(func=cmd_view)