-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathadbclipboard.py
executable file
·244 lines (204 loc) · 8.83 KB
/
adbclipboard.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
import subprocess
import time
import re
import platform
import argparse
# Constants
CONNECTED_DEVICES_DELAY_DEFAULT = 5
NO_CONNECTED_DEVICE_DELAY_DEFAULT = 60
verbose = False
connectedDevicesDelay = CONNECTED_DEVICES_DELAY_DEFAULT
noConnectedDeviceDelay = NO_CONNECTED_DEVICE_DELAY_DEFAULT
def parseArgs():
parser = argparse.ArgumentParser(
description='Sync clipboard with connected Android devices.')
parser.add_argument('-v', '--verbose', action='store_true',
help='Output status on the console')
parser.add_argument('-c', '--connected-devices-delay', type=int,
help="Delay in seconds between each sync if there is" +
" at least one device connected." +
" Defaults to {0} seconds."
.format(CONNECTED_DEVICES_DELAY_DEFAULT))
parser.add_argument('-n', '--no-connected-device-delay', type=int,
help="Delay in seconds between each sync if there is" +
" no device connected. Defaults to {0} seconds."
.format(NO_CONNECTED_DEVICE_DELAY_DEFAULT))
args = parser.parse_args()
global verbose, connectedDevicesDelay, noConnectedDeviceDelay
if args.verbose is True:
verbose = True
if args.connected_devices_delay is not None:
connectedDevicesDelay = args.connected_devices_delay
if args.no_connected_device_delay is not None:
noConnectedDeviceDelay = args.connected_devices_delay
if verbose is True:
print("verbose: {0}".format(verbose))
print("connectedDevicesDelay: {0}".format(connectedDevicesDelay))
print("noConnectedDeviceDelay: {0}".format(noConnectedDeviceDelay))
print
def checkAdbDependency():
try:
process = subprocess.Popen(['adb'], stdout=subprocess.PIPE)
return True
except OSError as e:
print("adb not found. Please make sure Android SDK is installed" +
" and adb is available on your PATH.")
if verbose is True:
print("error: {0}".format(e))
return False
def getConnectedDeviceHashes():
adbProcess = subprocess.Popen(['adb', 'devices'], stdout=subprocess.PIPE)
adbDevicesOutput = adbProcess.communicate()[0]
adbDevicesOutputLines = adbDevicesOutput.splitlines()
# remove first line that contains a description
del adbDevicesOutputLines[0]
deviceHashes = []
for deviceLine in adbDevicesOutputLines:
if (len(deviceLine) > 0):
deviceHashes.append(deviceLine.split('\t')[0])
return deviceHashes
def urlEncode(unencodedString):
return urllib.quote_plus(unencodedString)
def writeToDevice(deviceHash, urlEncodedString):
adbProcess = subprocess.Popen(
['adb',
'-s', deviceHash,
'shell', 'am',
'broadcast',
'-n', 'ch.pete.adbclipboard/.WriteReceiver',
'-e', 'text', urlEncodedString],
stdout=subprocess.PIPE)
resultString = adbProcess.communicate()[0]
if verbose is True:
print("write device response from {0}:\n{1}".format(
deviceHash, resultString))
return parseResponse(resultString)
def readFromDevice(deviceHash):
adbProcess = subprocess.Popen(
['adb',
'-s', deviceHash,
'shell', 'am',
'broadcast',
'-n', 'ch.pete.adbclipboard/.ReadReceiver'],
stdout=subprocess.PIPE)
resultString = adbProcess.communicate()[0]
if verbose is True:
print("read device response from {0}:\n{1}"
.format(deviceHash, resultString))
return parseResponse(resultString)
class Response(object):
status = None
data = None
def parseResponse(resultString):
resultMatcher = re.compile("^.*\n.*result=([\-]{0,1}[0-9]*).*")
resultMatch = resultMatcher.match(resultString)
response = Response()
if resultMatch and resultMatch.groups > 0:
if len(resultMatch.group(1)) == 0:
print("error: " + resultMatch.group(1))
response.status = int(resultMatch.group(1))
if response.status == -1:
# re.DOTALL to match newline as well
dataMatcher = re.compile("^.*\n.*data=\"(.*)\"$", re.DOTALL)
dataMatch = dataMatcher.match(resultString)
if dataMatch and dataMatch.groups > 0:
response.data = dataMatch.group(1)
return response
def syncWithDevices(clipboardHandler):
previousClipboardString = None
while True:
deviceHashes = getConnectedDeviceHashes()
hasDeviceWithAdbClipboardInstalled = False
hasUpdateFromDevice = False
if (len(deviceHashes) == 0):
# no devices connected, sleep longer
print("No device connected, sleep for {0}s"
.format(noConnectedDeviceDelay))
previousClipboardString = None
time.sleep(noConnectedDeviceDelay)
else:
clipboardString = clipboardHandler.readClipboard()
if previousClipboardString != clipboardString:
previousClipboardString = clipboardString
if len(clipboardString) > 0:
urlEncodedString = urlEncode(clipboardString)
for deviceHash in deviceHashes:
response = writeToDevice(
deviceHash, urlEncodedString)
printedStatus = ""
if response.status is -1:
hasDeviceWithAdbClipboardInstalled = True
else:
printedStatus = " (failed)"
print("send to {0}: \"{1}\"{2}".format(
deviceHash, clipboardString, printedStatus))
else:
for deviceHash in deviceHashes:
response = readFromDevice(deviceHash)
if response.status == -1:
hasDeviceWithAdbClipboardInstalled = True
deviceClipboardText = response.data
if len(clipboardString) == 0 or \
deviceClipboardText != clipboardString:
print("recv from {0}: \"{1}\"".format(
deviceHash, deviceClipboardText))
if deviceClipboardText is not None:
if verbose is True:
print("write to clipboard: {0}".format(
deviceClipboardText))
clipboardHandler.writeClipboard(
deviceClipboardText)
hasUpdateFromDevice = True
break
if hasDeviceWithAdbClipboardInstalled is False:
print("No device with installed AdbClipboard, sleep for {0}s"
.format(noConnectedDeviceDelay))
previousClipboardString = None
time.sleep(noConnectedDeviceDelay)
elif hasUpdateFromDevice is False:
time.sleep(connectedDevicesDelay)
class ClipboardHandlerMac(object):
def checkDependencies(self):
# on Mac pbpaste is preinstalled
return True
def readClipboard(self):
process = subprocess.Popen(['pbpaste'], stdout=subprocess.PIPE)
clipboardText = process.communicate()[0]
return clipboardText
def writeClipboard(self, text):
process = subprocess.Popen(['pbcopy'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
process.communicate(input=text)
class ClipboardHandlerLinux(object):
def checkDependencies(self):
try:
process = subprocess.Popen(['xclip'], stdout=subprocess.PIPE)
return True
except OSError as e:
print("xclip not found." +
" Please install it with your package manager.")
print("e.g. sudo apt install xclip")
if verbose is True:
print("error: {0}".format(e))
return False
def readClipboard(self):
process = subprocess.Popen(['xclip'], stdout=subprocess.PIPE)
clipboardText = process.communicate()[0]
return clipboardText
def writeClipboard(self, text):
process = subprocess.Popen(['xclip', '-o'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
process.communicate(input=text)
if platform.system() == "Linux":
clipboardHandler = ClipboardHandlerLinux()
else:
clipboardHandler = ClipboardHandlerMac()
parseArgs()
if checkAdbDependency() is True:
if clipboardHandler.checkDependencies() is True:
syncWithDevices(clipboardHandler)