-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathphone_cli.py
More file actions
297 lines (256 loc) · 9.34 KB
/
phone_cli.py
File metadata and controls
297 lines (256 loc) · 9.34 KB
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
#!/usr/bin/env python3
import click
import subprocess
import json
def run_adb_command(command):
try:
result = subprocess.run(command, shell=True, capture_output=True, text=True)
if result.returncode == 0:
return True, result.stdout
else:
return False, result.stderr
except Exception as e:
return False, str(e)
def get_total_count(content_uri, where=None):
"""Get total count of items for pagination
Args:
content_uri (str): Content provider URI to query
where (str, optional): SQL WHERE clause for filtering
Returns:
tuple: (success, count/error_message)
- If successful, returns (True, count)
- If failed, returns (False, error_message)
Example:
success, result = get_total_count('content://sms/inbox')
if success:
total_count = result
else:
error_msg = result
"""
command = f'adb shell content query --uri {content_uri} --projection count:count(*)'
if where:
command += f' --where "{where}"'
success, output = run_adb_command(command)
if not success:
return False, f"Failed to get count: {output}"
if not output or not output.strip():
return False, "Empty response from content query"
try:
count = int(output.strip().split('count=')[1])
return True, count
except (IndexError, ValueError) as e:
return False, f"Failed to parse count from output: {str(e)}"
@click.group()
def cli():
"""Phone MCP CLI tool for Android device control"""
pass
@cli.command()
@click.option('--account-name', '-n', default='你的账户名', help='Account name for the contact')
@click.option('--account-type', '-t', default='com.google', help='Account type (default: com.google)')
def create_contact(account_name, account_type):
"""Create a new raw contact with specified account details"""
command = (
f'adb shell content insert --uri content://com.android.contacts/raw_contacts '
f'--bind account_type:s:{account_type} '
f'--bind account_name:s:{account_name}'
)
success, output = run_adb_command(command)
result = {
'success': success,
'message': output
}
click.echo(json.dumps(result, ensure_ascii=False))
if not success:
exit(1)
@cli.command()
@click.option('--page', default=1, help='Page number (starts from 1)')
@click.option('--page-size', default=10, help='Number of items per page')
def get_contacts(page, page_size):
"""Get contacts with pagination support
Returns a JSON object containing:
- total_count: Total number of contacts
- total_pages: Total number of pages
- current_page: Current page number
- page_size: Number of items per page
- contacts: List of contacts in current page
"""
# Get total count
total_count = get_total_count('content://com.android.contacts/contacts')
total_pages = (total_count + page_size - 1) // page_size
# Validate page number
if page < 1:
page = 1
elif page > total_pages:
page = total_pages if total_pages > 0 else 1
# Calculate offset
offset = (page - 1) * page_size
command = (
f'adb shell content query --uri content://com.android.contacts/contacts '
f'--projection _id:display_name:has_phone_number '
f'--limit {page_size} --offset {offset}'
)
success, output = run_adb_command(command)
contacts = []
if success and output:
for line in output.strip().split('\n'):
if 'Row:' in line:
contact_data = line.split('Row:')[1].strip()
contacts.append(contact_data)
result = {
'success': success,
'total_count': total_count,
'total_pages': total_pages,
'current_page': page,
'page_size': page_size,
'contacts': contacts
}
click.echo(json.dumps(result, ensure_ascii=False))
if not success:
exit(1)
@cli.command()
@click.option('--page', default=1, help='Page number (starts from 1)')
@click.option('--page-size', default=10, help='Number of items per page')
def receive_text_messages(page, page_size):
"""Get received text messages with pagination support
Returns a JSON object containing:
- total_count: Total number of messages
- total_pages: Total number of pages
- current_page: Current page number
- page_size: Number of items per page
- messages: List of messages in current page
"""
# Get total count
total_count = get_total_count('content://sms/inbox')
total_pages = (total_count + page_size - 1) // page_size
# Validate page number
if page < 1:
page = 1
elif page > total_pages:
page = total_pages if total_pages > 0 else 1
# Calculate offset
offset = (page - 1) * page_size
command = (
f'adb shell content query --uri content://sms/inbox '
f'--projection _id:address:body:date:read '
f'--sort "date DESC" '
f'--limit {page_size} --offset {offset}'
)
success, output = run_adb_command(command)
messages = []
if success and output:
for line in output.strip().split('\n'):
if 'Row:' in line:
message_data = line.split('Row:')[1].strip()
messages.append(message_data)
result = {
'success': success,
'total_count': total_count,
'total_pages': total_pages,
'current_page': page,
'page_size': page_size,
'messages': messages
}
click.echo(json.dumps(result, ensure_ascii=False))
if not success:
exit(1)
@cli.command()
@click.option('--page', default=1, help='Page number (starts from 1)')
@click.option('--page-size', default=10, help='Number of items per page')
def get_sent_messages(page, page_size):
"""Get sent text messages with pagination support
Returns a JSON object containing:
- total_count: Total number of messages
- total_pages: Total number of pages
- current_page: Current page number
- page_size: Number of items per page
- messages: List of messages in current page
"""
# Get total count
total_count = get_total_count('content://sms/sent')
total_pages = (total_count + page_size - 1) // page_size
# Validate page number
if page < 1:
page = 1
elif page > total_pages:
page = total_pages if total_pages > 0 else 1
# Calculate offset
offset = (page - 1) * page_size
command = (
f'adb shell content query --uri content://sms/sent '
f'--projection _id:address:body:date '
f'--sort "date DESC" '
f'--limit {page_size} --offset {offset}'
)
success, output = run_adb_command(command)
messages = []
if success and output:
for line in output.strip().split('\n'):
if 'Row:' in line:
message_data = line.split('Row:')[1].strip()
messages.append(message_data)
result = {
'success': success,
'total_count': total_count,
'total_pages': total_pages,
'current_page': page,
'page_size': page_size,
'messages': messages
}
click.echo(json.dumps(result, ensure_ascii=False))
if not success:
exit(1)
@cli.command()
@click.option('--page', default=1, help='Page number (starts from 1)')
@click.option('--page-size', default=10, help='Number of items per page')
@click.option('--package-name', required=True, help='Package name of the app')
def get_app_shortcuts(page, page_size, package_name):
"""Get app shortcuts with pagination support
Returns a JSON object containing:
- total_count: Total number of shortcuts
- total_pages: Total number of pages
- current_page: Current page number
- page_size: Number of items per page
- shortcuts: List of shortcuts in current page
"""
# Get total count with package filter
where = f"package='{package_name}'"
total_count = get_total_count('content://com.android.launcher3.settings/favorites', where)
total_pages = (total_count + page_size - 1) // page_size
# Validate page number
if page < 1:
page = 1
elif page > total_pages:
page = total_pages if total_pages > 0 else 1
# Calculate offset
offset = (page - 1) * page_size
command = (
f'adb shell content query --uri content://com.android.launcher3.settings/favorites '
f'--projection _id:title:intent:itemType '
f'--where "{where}" '
f'--limit {page_size} --offset {offset}'
)
success, output = run_adb_command(command)
shortcuts = []
if success and output:
for line in output.strip().split('\n'):
if 'Row:' in line:
shortcut_data = line.split('Row:')[1].strip()
shortcuts.append(shortcut_data)
result = {
'success': success,
'total_count': total_count,
'total_pages': total_pages,
'current_page': page,
'page_size': page_size,
'shortcuts': shortcuts
}
click.echo(json.dumps(result, ensure_ascii=False))
if not success:
exit(1)
@cli.command()
def check():
"""Check device connection"""
success, output = run_adb_command('adb devices')
click.echo(output)
if __name__ == '__main__':
cli()