-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrop.py
More file actions
281 lines (231 loc) · 7.96 KB
/
brop.py
File metadata and controls
281 lines (231 loc) · 7.96 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
#!/usr/bin/env python3
"""
Brop (Browser-to-Phone) - Windows Version
Syncs URLs from Brave browser to Android phone via SSH/Termux
Uses PowerShell for window management and Python for logic
"""
import subprocess
import re
import sys
import logging
import time
from pathlib import Path
from datetime import datetime
from typing import List, Tuple
import argparse
# Configuration
SSH_PROFILE = "tmux" # SSH config profile name for phone
LOG_DIR = Path.home() / "AppData" / "Local" / "brop"
LOG_FILE = LOG_DIR / "brop.log"
BRAVE_SHORTCUT = "^+y" # Ctrl+Shift+Y
# Ensure log directory exists
LOG_DIR.mkdir(parents=True, exist_ok=True)
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s : %(levelname)s : %(message)s',
handlers=[
logging.FileHandler(LOG_FILE, encoding='utf-8'),
logging.StreamHandler()
]
)
def check_dependencies() -> bool:
"""Check if required commands are available."""
required = ['pwsh', 'ssh', 'yt-dlp']
missing = []
for cmd in required:
try:
subprocess.run(
[cmd, '--version'] if cmd != 'pwsh' else ['pwsh', '-Command', 'exit'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=5
)
except (subprocess.TimeoutExpired, FileNotFoundError):
missing.append(cmd)
if missing:
logging.error(f"Missing dependencies: {', '.join(missing)}")
return False
return True
def notify(title: str, message: str):
"""Send Windows notification."""
ps_script = f"""
Add-Type -AssemblyName Windows.UI
Add-Type -AssemblyName Windows.Data
$template = @"
<toast>
<visual>
<binding template="ToastText02">
<text id="1">{title}</text>
<text id="2">{message}</text>
</binding>
</visual>
</toast>
"@
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$xml.LoadXml($template)
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
$notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("Brop")
$notifier.Show($toast)
"""
try:
subprocess.run(
['pwsh', '-NoProfile', '-Command', ps_script],
capture_output=True,
timeout=5
)
except Exception as e:
logging.warning(f"Failed to send notification: {e}")
def focus_brave() -> bool:
"""Focus on Brave browser window."""
ps_script = """
$brave = Get-Process | Where-Object { $_.ProcessName -eq 'brave' -and $_.MainWindowTitle -ne '' } | Select-Object -First 1
if ($brave) {
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class Win32 {
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
}
"@
[Win32]::SetForegroundWindow($brave.MainWindowHandle)
Start-Sleep -Milliseconds 200
exit 0
}
exit 1
"""
try:
result = subprocess.run(
['pwsh', '-NoProfile', '-Command', ps_script],
capture_output=True,
timeout=5
)
return result.returncode == 0
except Exception as e:
logging.error(f"Failed to focus Brave: {e}")
return False
def get_clipboard() -> str:
"""Get text from Windows clipboard."""
ps_script = "Get-Clipboard -Raw"
try:
result = subprocess.run(
['pwsh', '-NoProfile', '-Command', ps_script],
capture_output=True,
text=True,
timeout=5
)
return result.stdout.strip()
except Exception as e:
logging.error(f"Failed to get clipboard: {e}")
return ""
def send_keys(keys: str):
"""Send keystrokes using PowerShell."""
ps_script = f"""
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.SendKeys]::SendWait('{keys}')
"""
try:
subprocess.run(
['pwsh', '-NoProfile', '-Command', ps_script],
capture_output=True,
timeout=5
)
except Exception as e:
logging.error(f"Failed to send keys: {e}")
def extract_url(text: str) -> str:
"""Extract URL from text."""
url_pattern = r'https?://[^\s<>"{}|\\^`\[\]]+'
match = re.search(url_pattern, text)
return match.group(0) if match else ""
def is_video_url(url: str) -> bool:
"""Check if URL is a video platform."""
video_domains = [
'youtube.com', 'youtu.be', 'vimeo.com', 'dailymotion.com',
'twitch.tv', 'tiktok.com', 'instagram.com', 'reddit.com'
]
return any(domain in url.lower() for domain in video_domains)
def send_to_phone(url: str) -> bool:
"""Send URL to phone via SSH."""
if not url:
logging.error("No URL to send")
return False
logging.info(f"Sending URL: {url}")
# Construct command
if is_video_url(url):
# For video URLs, download with yt-dlp
cmd = f"yt-dlp -f 'bestvideo[height<=720]+bestaudio/best[height<=720]' '{url}'"
else:
# For regular URLs, just echo (could be extended to download with wget/curl)
cmd = f"echo 'Received URL: {url}'"
# SSH to phone and execute
ssh_cmd = ['ssh', SSH_PROFILE, cmd]
try:
result = subprocess.run(
ssh_cmd,
capture_output=True,
text=True,
timeout=60
)
if result.returncode == 0:
logging.info("Successfully sent to phone")
notify("Brop Success", f"Sent URL to phone")
return True
else:
logging.error(f"SSH command failed: {result.stderr}")
notify("Brop Failed", "SSH command failed")
return False
except subprocess.TimeoutExpired:
logging.error("SSH command timed out")
notify("Brop Failed", "Connection timed out")
return False
except Exception as e:
logging.error(f"Failed to send to phone: {e}")
notify("Brop Failed", str(e))
return False
def main():
"""Main function."""
parser = argparse.ArgumentParser(description='Brop - Browser to Phone URL sync')
parser.add_argument('--check-deps', action='store_true', help='Check dependencies')
parser.add_argument('--url', type=str, help='URL to send directly')
args = parser.parse_args()
if args.check_deps:
if check_dependencies():
print("✓ All dependencies available")
return 0
else:
print("✗ Missing dependencies")
return 1
if args.url:
# Direct URL mode
success = send_to_phone(args.url)
return 0 if success else 1
# Normal mode: focus browser and copy URL
logging.info("Starting Brop sync...")
if not focus_brave():
logging.error("Could not find or focus Brave browser")
notify("Brop Failed", "Brave browser not found")
return 1
# Wait for window to focus
time.sleep(0.3)
# Send Ctrl+Shift+Y to copy URL
send_keys(BRAVE_SHORTCUT)
# Wait for clipboard
time.sleep(0.2)
# Get clipboard content
clipboard = get_clipboard()
if not clipboard:
logging.error("Clipboard is empty")
notify("Brop Failed", "No URL in clipboard")
return 1
# Extract URL
url = extract_url(clipboard)
if not url:
logging.error(f"No valid URL found in clipboard: {clipboard[:100]}")
notify("Brop Failed", "No valid URL found")
return 1
# Send to phone
success = send_to_phone(url)
return 0 if success else 1
if __name__ == "__main__":
sys.exit(main())