| 1 | |
| 2 | """Private FileChooser portal and host file ingress for one desktop session.""" |
| 3 | import ctypes as C |
| 4 | from ctypes.util import find_library |
| 5 | from http.server import BaseHTTPRequestHandler |
| 6 | import json |
| 7 | import os |
| 8 | from pathlib import Path |
| 9 | import re |
| 10 | import select |
| 11 | import shutil |
| 12 | import socketserver |
| 13 | import subprocess |
| 14 | import sys |
| 15 | import threading |
| 16 | import time |
| 17 | import uuid |
| 18 | from urllib.parse import parse_qs, unquote, urlsplit |
| 19 | |
| 20 | LIMIT = 2 * 1024 ** 3 |
| 21 | PORTAL = 'org.freedesktop.portal.FileChooser' |
| 22 | ROOT = '/org/freedesktop/portal/desktop' |
| 23 | |
| 24 | |
| 25 | def image_context(): |
| 26 | result = subprocess.run(['/usr/local/bin/cage-native-input', '--request'], |
| 27 | input=b'{"mode":"status"}\n', stdout=subprocess.PIPE, |
| 28 | stderr=subprocess.DEVNULL, check=True, timeout=4) |
| 29 | value = json.loads(result.stdout) |
| 30 | context = value.get('context', '') |
| 31 | if value.get('available') is not True or not re.fullmatch('[a-f0-9]{32}', context): |
| 32 | raise ValueError('图片接收位置尚未聚焦,请点击输入框后重试') |
| 33 | return context |
| 34 | |
| 35 | |
| 36 | class Broker: |
| 37 | def __init__(self, directory, deliver=lambda request, paths: None, downloads=None): |
| 38 | self.directory = Path(directory) |
| 39 | self.directory.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 40 | self.deliver = deliver |
| 41 | self.downloads = downloads |
| 42 | self.requests = {} |
| 43 | self.lock = threading.RLock() |
| 44 | |
| 45 | def start(self, kind='paste', multiple=True, **metadata): |
| 46 | if kind not in ('paste', 'drop', 'image', 'chooser', 'save', 'open'): |
| 47 | raise ValueError('文件传递方式无效') |
| 48 | if kind == 'image': |
| 49 | metadata['image_context'] = image_context() |
| 50 | multiple = False |
| 51 | with self.lock: |
| 52 | if len(self.requests) >= 32: |
| 53 | raise ValueError('请先完成已打开的文件窗口') |
| 54 | key = str(uuid.uuid4()) |
| 55 | self.requests[key] = dict(id=key, kind=kind, multiple=multiple, |
| 56 | files=[], busy=False, created=time.monotonic(), **metadata) |
| 57 | return {'id': key} |
| 58 | |
| 59 | def snapshot(self): |
| 60 | with self.lock: |
| 61 | for key, request in list(self.requests.items()): |
| 62 | if request['kind'] == 'open' and time.monotonic() - request['created'] > 60: |
| 63 | self.complete_open(key, '本机文件操作已超时,请重新打开') |
| 64 | return {'uploads': [dict(id=r['id'], multiple=r['multiple'], |
| 65 | title=r.get('title', ''), target='desktop', |
| 66 | directory=r.get('directory', False)) |
| 67 | for r in self.requests.values() if r['kind'] == 'chooser'], |
| 68 | 'downloads': self.downloads.snapshot() if self.downloads else [], |
| 69 | 'opens': [{'id': r['id']} for r in self.requests.values() |
| 70 | if r['kind'] == 'open' and not r['busy']]} |
| 71 | |
| 72 | def open_path(self, path, action='open', **metadata): |
| 73 | if action not in ('open', 'reveal') or not isinstance(path, str) or not path or '\x00' in path: |
| 74 | raise ValueError('文件打开请求无效') |
| 75 | if path.startswith('file:'): |
| 76 | uri = urlsplit(path) |
| 77 | if uri.scheme != 'file' or uri.netloc not in ('', 'localhost') or uri.query or uri.fragment: |
| 78 | raise ValueError('请选择本机项目中的文件') |
| 79 | path = unquote(uri.path, errors='strict') |
| 80 | if not Path(path).is_absolute(): |
| 81 | raise ValueError('文件打开请求需要绝对路径') |
| 82 | path = str(Path(path).resolve(strict=True)) |
| 83 | return self.start('open', False, path=path, action=action, **metadata) |
| 84 | |
| 85 | def claim_open(self, key): |
| 86 | with self.lock: |
| 87 | request = self.requests.get(key) |
| 88 | if not request or request['kind'] != 'open' or request['busy']: |
| 89 | return {'handled': True} |
| 90 | if time.monotonic() - request['created'] > 60: |
| 91 | self.complete_open(key, '本机文件操作已超时,请重新打开') |
| 92 | return {'handled': True} |
| 93 | request['busy'] = True |
| 94 | path = request['path'] |
| 95 | if self.downloads: |
| 96 | try: |
| 97 | path = self.downloads.host_visible_path(path) |
| 98 | except ValueError as error: |
| 99 | return {'error': str(error)} |
| 100 | return {'id': key, 'path': path, 'action': request['action']} |
| 101 | |
| 102 | def complete_open(self, key, error=''): |
| 103 | with self.lock: |
| 104 | request = self.requests.get(key) |
| 105 | if not request or request['kind'] != 'open': |
| 106 | return {'ok': True} |
| 107 | del self.requests[key] |
| 108 | if request.get('handle'): |
| 109 | self.deliver(request, None if error else []) |
| 110 | return {'ok': True} |
| 111 | |
| 112 | def get(self, key): |
| 113 | if key not in self.requests: |
| 114 | raise ValueError('上传窗口已关闭,请重新选择文件') |
| 115 | return self.requests[key] |
| 116 | |
| 117 | def receive(self, key, name, chunks): |
| 118 | if (not isinstance(name, str) or not name or len(name.encode()) > 255 |
| 119 | or name in ('.', '..') or re.search(r'[/\\\x00-\x1f]', name)): |
| 120 | raise ValueError('文件名无效') |
| 121 | with self.lock: |
| 122 | request = self.get(key) |
| 123 | if request.get('directory'): |
| 124 | raise ValueError('请选择项目文件夹') |
| 125 | if request['busy'] or len(request['files']) >= (100 if request['multiple'] else 1): |
| 126 | raise ValueError('请选择允许数量的文件') |
| 127 | request['busy'] = True |
| 128 | directory = self.directory / key / str(uuid.uuid4()) |
| 129 | accepted = False |
| 130 | try: |
| 131 | directory.mkdir(parents=True, mode=0o700) |
| 132 | path = directory / name |
| 133 | size = 0 |
| 134 | with path.open('xb') as output: |
| 135 | os.chmod(path, 0o600) |
| 136 | for chunk in chunks: |
| 137 | size += len(chunk) |
| 138 | if size > LIMIT: |
| 139 | raise ValueError('每个文件不能超过 2 GB') |
| 140 | with self.lock: |
| 141 | if self.requests.get(key) is not request: |
| 142 | raise ValueError('上传已取消') |
| 143 | output.write(chunk) |
| 144 | with self.lock: |
| 145 | if self.requests.get(key) is not request: |
| 146 | raise ValueError('上传已取消') |
| 147 | request['files'].append(str(path)) |
| 148 | accepted = True |
| 149 | return dict(ok=True, name=name, size=size) |
| 150 | finally: |
| 151 | with self.lock: |
| 152 | request['busy'] = False |
| 153 | if not accepted: |
| 154 | shutil.rmtree(directory, ignore_errors=True) |
| 155 | |
| 156 | def finish(self, key): |
| 157 | with self.lock: |
| 158 | request = self.get(key) |
| 159 | if request['kind'] == 'image' or request['busy'] or not request['files']: |
| 160 | raise ValueError('请先选择并传递文件') |
| 161 | request['busy'] = True |
| 162 | try: |
| 163 | self.deliver(request, request['files']) |
| 164 | with self.lock: |
| 165 | if self.requests.get(key) is not request: |
| 166 | raise ValueError('上传已取消') |
| 167 | del self.requests[key] |
| 168 | |
| 169 | return {'ok': True} |
| 170 | except Exception: |
| 171 | self.cancel(key) |
| 172 | raise |
| 173 | |
| 174 | def finish_image(self, key): |
| 175 | with self.lock: |
| 176 | request = self.get(key) |
| 177 | if request['kind'] != 'image' or request['busy'] or len(request['files']) != 1: |
| 178 | raise ValueError('图片没有完整收到') |
| 179 | request['busy'] = True |
| 180 | try: |
| 181 | if image_context() != request['image_context']: |
| 182 | raise ValueError('图片接收位置已变化,请重新粘贴') |
| 183 | paste_files(request['files'], expected_context=request['image_context']) |
| 184 | return {'ok': True} |
| 185 | finally: |
| 186 | self.cancel(key) |
| 187 | |
| 188 | def cancel(self, key, respond=True): |
| 189 | with self.lock: |
| 190 | request = self.requests.pop(key, None) |
| 191 | if request and respond and request['kind'] in ('chooser', 'save'): |
| 192 | self.deliver(request, None) |
| 193 | shutil.rmtree(self.directory / key, ignore_errors=True) |
| 194 | return {'ok': True} |
| 195 | |
| 196 | def choose_directory(self, key, path): |
| 197 | with self.lock: |
| 198 | request = self.get(key) |
| 199 | if request['kind'] != 'chooser' or not request.get('directory'): |
| 200 | raise ValueError('当前窗口没有请求文件夹') |
| 201 | if request['busy']: |
| 202 | raise ValueError('文件夹正在交给应用') |
| 203 | if not isinstance(path, str) or not Path(path).is_absolute() or not Path(path).is_dir(): |
| 204 | raise ValueError('项目文件夹尚未连接,请重新打开项目') |
| 205 | request['files'] = [path] |
| 206 | return self.finish(key) |
| 207 | |
| 208 | |
| 209 | class Handler(BaseHTTPRequestHandler): |
| 210 | protocol_version = 'HTTP/1.1' |
| 211 | |
| 212 | def log_message(self, *_args): |
| 213 | pass |
| 214 | |
| 215 | def chunks(self): |
| 216 | length = self.headers.get('Content-Length') |
| 217 | if self.headers.get('Transfer-Encoding', '').lower() == 'chunked': |
| 218 | while True: |
| 219 | line = self.rfile.readline(128) |
| 220 | if not line.endswith(b'\r\n'): |
| 221 | raise ValueError('文件传递中断') |
| 222 | size = int(line.split(b';', 1)[0], 16) |
| 223 | if size == 0: |
| 224 | if self.rfile.readline(128) != b'\r\n': |
| 225 | raise ValueError('文件传递格式无效') |
| 226 | return |
| 227 | if size < 0 or size > LIMIT: |
| 228 | raise ValueError('每个文件不能超过 2 GB') |
| 229 | while size: |
| 230 | data = self.rfile.read(min(65536, size)) |
| 231 | if not data: |
| 232 | raise ValueError('文件传递中断') |
| 233 | size -= len(data) |
| 234 | yield data |
| 235 | if self.rfile.read(2) != b'\r\n': |
| 236 | raise ValueError('文件传递格式无效') |
| 237 | elif length is not None: |
| 238 | remaining = int(length) |
| 239 | if remaining < 0 or remaining > LIMIT: |
| 240 | raise ValueError('每个文件不能超过 2 GB') |
| 241 | while remaining: |
| 242 | data = self.rfile.read(min(65536, remaining)) |
| 243 | if not data: |
| 244 | raise ValueError('文件传递中断') |
| 245 | remaining -= len(data) |
| 246 | yield data |
| 247 | else: |
| 248 | raise ValueError('缺少文件长度') |
| 249 | |
| 250 | def route(self): |
| 251 | route = urlsplit(self.path) |
| 252 | broker = self.server.broker |
| 253 | try: |
| 254 | if self.command == 'GET' and route.path == '/requests': |
| 255 | result = broker.snapshot() |
| 256 | elif self.command == 'POST' and route.path == '/upload': |
| 257 | query = parse_qs(route.query) |
| 258 | result = broker.receive(query.get('id', [''])[0], query.get('name', [''])[0], self.chunks()) |
| 259 | elif self.command == 'POST': |
| 260 | data = bytearray() |
| 261 | for chunk in self.chunks(): |
| 262 | data.extend(chunk) |
| 263 | if len(data) > 65536: |
| 264 | raise ValueError('文件请求过大') |
| 265 | value = json.loads(data or b'{}') |
| 266 | if route.path == '/start': |
| 267 | result = broker.start(value.get('kind', 'paste')) |
| 268 | elif route.path == '/finish': |
| 269 | result = broker.finish(value.get('id', '')) |
| 270 | elif route.path == '/finish-image': |
| 271 | result = broker.finish_image(value.get('id', '')) |
| 272 | elif route.path == '/cancel': |
| 273 | key = value.get('id', '') |
| 274 | if not re.fullmatch(r'[0-9a-f-]{36}', key): |
| 275 | raise ValueError('文件请求无效') |
| 276 | result = broker.cancel(key) |
| 277 | elif route.path == '/directory': |
| 278 | result = broker.choose_directory(value.get('id', ''), value.get('path', '')) |
| 279 | elif route.path == '/open': |
| 280 | result = broker.open_path(value.get('path', ''), value.get('action', 'open')) |
| 281 | elif route.path == '/open-claim': |
| 282 | result = broker.claim_open(value.get('id', '')) |
| 283 | elif route.path == '/open-complete': |
| 284 | result = broker.complete_open(value.get('id', ''), value.get('error', '')) |
| 285 | elif route.path == '/download-retry' and broker.downloads: |
| 286 | result = broker.downloads.retry(value.get('id', '')) |
| 287 | else: |
| 288 | raise ValueError('文件操作无效') |
| 289 | else: |
| 290 | raise ValueError('文件操作无效') |
| 291 | body, status = json.dumps(result).encode(), 200 |
| 292 | except Exception as error: |
| 293 | body, status = str(error).encode(), 400 |
| 294 | self.send_response(status) |
| 295 | self.send_header('Content-Type', 'application/json' if status == 200 else 'text/plain; charset=utf-8') |
| 296 | self.send_header('Content-Length', str(len(body))) |
| 297 | self.send_header('Connection', 'close') |
| 298 | self.end_headers() |
| 299 | self.wfile.write(body) |
| 300 | self.close_connection = True |
| 301 | |
| 302 | do_GET = route |
| 303 | do_POST = route |
| 304 | |
| 305 | |
| 306 | class FileServer(socketserver.ThreadingMixIn, socketserver.UnixStreamServer): |
| 307 | daemon_threads = True |
| 308 | |
| 309 | |
| 310 | def bind(lib, name, result, *args): |
| 311 | function = getattr(lib, name) |
| 312 | function.restype, function.argtypes = result, list(args) |
| 313 | return function |
| 314 | |
| 315 | |
| 316 | class Portal: |
| 317 | """GIO is already required by the desktop; no Python D-Bus package needed.""" |
| 318 | XML = '''<node><interface name="org.freedesktop.portal.FileChooser"> |
| 319 | <property name="version" type="u" access="read"/> |
| 320 | <method name="OpenFile"><arg type="s" direction="in"/><arg type="s" direction="in"/> |
| 321 | <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> |
| 322 | <method name="SaveFile"><arg type="s" direction="in"/><arg type="s" direction="in"/> |
| 323 | <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> |
| 324 | </interface><interface name="org.freedesktop.portal.OpenURI"> |
| 325 | <property name="version" type="u" access="read"/> |
| 326 | <method name="OpenDirectory"><arg type="s" direction="in"/><arg type="h" direction="in"/> |
| 327 | <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> |
| 328 | </interface><interface name="org.freedesktop.FileManager1"> |
| 329 | <method name="ShowItems"><arg type="as" direction="in"/><arg type="s" direction="in"/></method> |
| 330 | <method name="ShowFolders"><arg type="as" direction="in"/><arg type="s" direction="in"/></method> |
| 331 | </interface><interface name="org.freedesktop.portal.Request"> |
| 332 | <method name="Close"/><signal name="Response"><arg type="u"/><arg type="a{sv}"/></signal> |
| 333 | </interface></node>''' |
| 334 | |
| 335 | def __init__(self, broker): |
| 336 | self.broker, self.objects = broker, {} |
| 337 | self.glib = C.CDLL(find_library('glib-2.0') or 'libglib-2.0.so.0') |
| 338 | self.gio = C.CDLL(find_library('gio-2.0') or 'libgio-2.0.so.0') |
| 339 | p, s, u = C.c_void_p, C.c_char_p, C.c_uint |
| 340 | self.variant_parse = bind(self.glib, 'g_variant_parse', p, p, s, p, p, p) |
| 341 | self.variant_print = bind(self.glib, 'g_variant_print', p, p, C.c_int) |
| 342 | self.free = bind(self.glib, 'g_free', None, p) |
| 343 | self.child = bind(self.glib, 'g_variant_get_child_value', p, p, C.c_size_t) |
| 344 | self.string = bind(self.glib, 'g_variant_get_string', s, p, p) |
| 345 | self.boolean = bind(self.glib, 'g_variant_get_boolean', C.c_int, p) |
| 346 | self.lookup = bind(self.glib, 'g_variant_lookup_value', p, p, s, p) |
| 347 | self.unref = bind(self.glib, 'g_variant_unref', None, p) |
| 348 | self.new_string = bind(self.glib, 'g_variant_new_string', p, s) |
| 349 | self.new_path = bind(self.glib, 'g_variant_new_object_path', p, s) |
| 350 | self.new_uint = bind(self.glib, 'g_variant_new_uint32', p, u) |
| 351 | self.new_variant = bind(self.glib, 'g_variant_new_variant', p, p) |
| 352 | self.new_entry = bind(self.glib, 'g_variant_new_dict_entry', p, p, p) |
| 353 | self.new_tuple = bind(self.glib, 'g_variant_new_tuple', p, C.POINTER(p), C.c_size_t) |
| 354 | self.new_array = bind(self.glib, 'g_variant_new_array', p, p, C.POINTER(p), C.c_size_t) |
| 355 | self.type_new = bind(self.glib, 'g_variant_type_new', p, s) |
| 356 | self.type_free = bind(self.glib, 'g_variant_type_free', None, p) |
| 357 | self.connection = bind(self.gio, 'g_bus_get_sync', p, C.c_int, p, p)(2, None, None) |
| 358 | if not self.connection: |
| 359 | raise RuntimeError('桌面文件选择服务无法连接会话') |
| 360 | call = bind(self.gio, 'g_dbus_connection_call_sync', p, p, s, s, s, s, p, p, u, C.c_int, p, p) |
| 361 | name_reply = call(self.connection, b'org.freedesktop.DBus', b'/org/freedesktop/DBus', b'org.freedesktop.DBus', |
| 362 | b'RequestName', self.tuple(self.new_string(b'org.freedesktop.portal.Desktop'), self.new_uint(4)), |
| 363 | None, 0, 5000, None, None) |
| 364 | if not name_reply: |
| 365 | raise RuntimeError('桌面文件选择服务无法注册') |
| 366 | code = self.child(name_reply, 0) |
| 367 | code_value = bind(self.glib, 'g_variant_get_uint32', u, p)(code) |
| 368 | self.unref(code) |
| 369 | self.unref(name_reply) |
| 370 | if code_value != 1: |
| 371 | raise RuntimeError('已有其他桌面文件选择服务') |
| 372 | name_reply = call(self.connection, b'org.freedesktop.DBus', b'/org/freedesktop/DBus', b'org.freedesktop.DBus', |
| 373 | b'RequestName', self.tuple(self.new_string(b'org.freedesktop.FileManager1'), self.new_uint(4)), |
| 374 | None, 0, 5000, None, None) |
| 375 | if not name_reply: |
| 376 | raise RuntimeError('本机文件打开服务无法注册') |
| 377 | code = self.child(name_reply, 0) |
| 378 | code_value = bind(self.glib, 'g_variant_get_uint32', u, p)(code) |
| 379 | self.unref(code) |
| 380 | self.unref(name_reply) |
| 381 | if code_value != 1: |
| 382 | raise RuntimeError('已有其他文件管理服务') |
| 383 | self.reply = bind(self.gio, 'g_dbus_method_invocation_return_value', None, p, p) |
| 384 | self.error = bind(self.gio, 'g_dbus_method_invocation_return_dbus_error', None, p, s, s) |
| 385 | self.emit = bind(self.gio, 'g_dbus_connection_emit_signal', C.c_int, p, s, s, s, s, p, p) |
| 386 | self.unregister = bind(self.gio, 'g_dbus_connection_unregister_object', C.c_int, p, u) |
| 387 | self.register = bind(self.gio, 'g_dbus_connection_register_object', u, p, s, p, p, p, p, p) |
| 388 | self.node = bind(self.gio, 'g_dbus_node_info_new_for_xml', p, s, p)(self.XML.encode(), None) |
| 389 | self.interface = bind(self.gio, 'g_dbus_node_info_lookup_interface', p, p, s) |
| 390 | method_type = C.CFUNCTYPE(None, p, s, s, s, s, p, p, p) |
| 391 | property_type = C.CFUNCTYPE(p, p, s, s, s, s, p, p) |
| 392 | self.method_callback = method_type(self.method) |
| 393 | self.property_callback = property_type(lambda *_: self.new_uint(3)) |
| 394 | class VTable(C.Structure): |
| 395 | _fields_ = [('method', method_type), ('get', property_type), ('set', p), ('padding', p * 8)] |
| 396 | self.vtable = VTable(self.method_callback, self.property_callback, None) |
| 397 | if not self.register(self.connection, ROOT.encode(), self.interface(self.node, PORTAL.encode()), C.byref(self.vtable), None, None, None): |
| 398 | raise RuntimeError('桌面文件选择接口无法注册') |
| 399 | for object_path, interface in ((ROOT, 'org.freedesktop.portal.OpenURI'), |
| 400 | ('/org/freedesktop/FileManager1', 'org.freedesktop.FileManager1')): |
| 401 | if not self.register(self.connection, object_path.encode(), self.interface(self.node, interface.encode()), C.byref(self.vtable), None, None, None): |
| 402 | raise RuntimeError('本机文件打开接口无法注册') |
| 403 | self.loop = bind(self.glib, 'g_main_loop_new', p, p, C.c_int)(None, False) |
| 404 | |
| 405 | def tuple(self, *values): |
| 406 | return self.new_tuple((C.c_void_p * len(values))(*values), len(values)) |
| 407 | |
| 408 | def array(self, signature, values): |
| 409 | kind = self.type_new(signature.encode()) |
| 410 | try: |
| 411 | return self.new_array(kind, (C.c_void_p * len(values))(*values), len(values)) |
| 412 | finally: |
| 413 | self.type_free(kind) |
| 414 | |
| 415 | def option(self, options, name, default): |
| 416 | value = self.lookup(options, name.encode(), b'b' if isinstance(default, bool) else b's') |
| 417 | if not value: |
| 418 | return default |
| 419 | try: |
| 420 | return bool(self.boolean(value)) if isinstance(default, bool) else self.string(value, None).decode() |
| 421 | finally: |
| 422 | self.unref(value) |
| 423 | |
| 424 | def method(self, _connection, sender, path, _interface, method, parameters, invocation, _data): |
| 425 | try: |
| 426 | if method in (b'ShowItems', b'ShowFolders'): |
| 427 | uris = self.child(parameters, 0) |
| 428 | try: |
| 429 | count = bind(self.glib, 'g_variant_n_children', C.c_size_t, C.c_void_p)(uris) |
| 430 | if count > 32: |
| 431 | raise ValueError('一次最多打开 32 个位置') |
| 432 | for index in range(count): |
| 433 | uri = self.child(uris, index) |
| 434 | try: |
| 435 | self.broker.open_path(self.string(uri, None).decode(), 'reveal' if method == b'ShowItems' else 'open') |
| 436 | finally: |
| 437 | self.unref(uri) |
| 438 | finally: |
| 439 | self.unref(uris) |
| 440 | self.reply(invocation, self.tuple()) |
| 441 | return |
| 442 | if method == b'Close': |
| 443 | request = next((r for r in self.broker.requests.values() if r.get('handle') == path.decode() and r.get('sender') == sender.decode()), None) |
| 444 | if request: |
| 445 | self.broker.cancel(request['id'], respond=False) |
| 446 | self.remove(request) |
| 447 | self.reply(invocation, self.tuple()) |
| 448 | return |
| 449 | title, options = self.child(parameters, 1), self.child(parameters, 2) |
| 450 | try: |
| 451 | directory = self.option(options, 'directory', False) |
| 452 | token = self.option(options, 'handle_token', 'cage_' + uuid.uuid4().hex) |
| 453 | if not re.fullmatch(r'[A-Za-z0-9_]+', token): |
| 454 | raise ValueError('文件窗口标识无效') |
| 455 | handle = ROOT + '/request/' + sender.decode().lstrip(':').replace('.', '_') + '/' + token |
| 456 | if handle in self.objects: |
| 457 | raise ValueError('文件窗口已打开') |
| 458 | object_id = self.register(self.connection, handle.encode(), self.interface(self.node, b'org.freedesktop.portal.Request'), C.byref(self.vtable), None, None, None) |
| 459 | if not object_id: |
| 460 | raise ValueError('文件窗口无法打开') |
| 461 | self.objects[handle] = object_id |
| 462 | key = None |
| 463 | try: |
| 464 | saving = method == b'SaveFile' |
| 465 | if method == b'OpenDirectory': |
| 466 | |
| 467 | |
| 468 | message = bind(self.gio, 'g_dbus_method_invocation_get_message', C.c_void_p, C.c_void_p)(invocation) |
| 469 | descriptors = bind(self.gio, 'g_dbus_message_get_unix_fd_list', C.c_void_p, C.c_void_p)(message) |
| 470 | index = bind(self.glib, 'g_variant_get_handle', C.c_int, C.c_void_p)(title) |
| 471 | fd = bind(self.gio, 'g_unix_fd_list_get', C.c_int, C.c_void_p, C.c_int, C.c_void_p)(descriptors, index, None) if descriptors else -1 |
| 472 | if fd < 0: |
| 473 | raise ValueError('文件位置无法读取') |
| 474 | try: |
| 475 | key = self.broker.open_path(os.readlink('/proc/self/fd/' + str(fd)), 'reveal', |
| 476 | handle=handle, sender=sender.decode())['id'] |
| 477 | finally: |
| 478 | os.close(fd) |
| 479 | else: |
| 480 | key = self.broker.start('save' if saving else 'chooser', self.option(options, 'multiple', False) and not directory, |
| 481 | directory=directory, |
| 482 | handle=handle, sender=sender.decode(), title=self.string(title, None).decode())['id'] |
| 483 | if saving: |
| 484 | if not self.broker.downloads: |
| 485 | raise ValueError('下载服务不可用') |
| 486 | destination = self.broker.downloads.begin(self.option(options, 'current_name', 'download')) |
| 487 | except Exception: |
| 488 | self.unregister(self.connection, self.objects.pop(handle)) |
| 489 | if key: |
| 490 | self.broker.cancel(key, respond=False) |
| 491 | raise |
| 492 | self.reply(invocation, self.tuple(self.new_path(handle.encode()))) |
| 493 | if saving: |
| 494 | |
| 495 | |
| 496 | request = self.broker.get(key) |
| 497 | self.deliver(request, [destination]) |
| 498 | del self.broker.requests[key] |
| 499 | finally: |
| 500 | self.unref(title) |
| 501 | self.unref(options) |
| 502 | except Exception as error: |
| 503 | self.error(invocation, b'org.freedesktop.portal.Error.Failed', str(error).encode()) |
| 504 | |
| 505 | def remove(self, request): |
| 506 | object_id = self.objects.pop(request['handle'], None) |
| 507 | if object_id: |
| 508 | self.unregister(self.connection, object_id) |
| 509 | |
| 510 | def deliver(self, request, paths): |
| 511 | if request['kind'] not in ('chooser', 'save', 'open'): |
| 512 | paste_files(paths) |
| 513 | return |
| 514 | entries = [] |
| 515 | if paths is not None and request['kind'] != 'open': |
| 516 | uris = self.array('s', [self.new_string(Path(path).as_uri().encode()) for path in paths]) |
| 517 | entries.append(self.new_entry(self.new_string(b'uris'), self.new_variant(uris))) |
| 518 | response = self.tuple(self.new_uint(0 if paths is not None else (2 if request['kind'] == 'open' else 1)), self.array('{sv}', entries)) |
| 519 | if not self.emit(self.connection, request['sender'].encode(), request['handle'].encode(), |
| 520 | b'org.freedesktop.portal.Request', b'Response', response, None): |
| 521 | raise ValueError('原文件窗口已关闭') |
| 522 | self.remove(request) |
| 523 | |
| 524 | def run(self): |
| 525 | bind(self.glib, 'g_main_loop_run', None, C.c_void_p)(self.loop) |
| 526 | |
| 527 | |
| 528 | def paste_files(paths, expected_context=None): |
| 529 | process = subprocess.Popen([sys.executable, __file__, '--clipboard'], stdin=subprocess.PIPE, |
| 530 | stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) |
| 531 | value = paths if expected_context is None else dict(paths=paths, image_context=expected_context) |
| 532 | process.stdin.write(json.dumps(value).encode()) |
| 533 | process.stdin.close() |
| 534 | try: |
| 535 | ready, _, _ = select.select([process.stdout], [], [], 10) |
| 536 | if not ready or process.stdout.readline() != b'ok\n': |
| 537 | process.terminate() |
| 538 | process.wait(timeout=3) |
| 539 | raise ValueError('目标没有接收文件,请点击支持附件的输入框后重试') |
| 540 | finally: |
| 541 | process.stdout.close() |
| 542 | |
| 543 | |
| 544 | def clipboard(paths, expected_context=None): |
| 545 | gtk, gdk, glib = (C.CDLL(name) for name in ('libgtk-3.so.0', 'libgdk-3.so.0', 'libglib-2.0.so.0')) |
| 546 | p = C.c_void_p |
| 547 | if not bind(gtk, 'gtk_init_check', C.c_int, p, p)(None, None): |
| 548 | raise RuntimeError('display unavailable') |
| 549 | atom = bind(gdk, 'gdk_atom_intern_static_string', p, C.c_char_p) |
| 550 | set_data = bind(gtk, 'gtk_selection_data_set', None, p, p, C.c_int, p, C.c_int) |
| 551 | flush = bind(gdk, 'gdk_flush', None) |
| 552 | main = bind(gtk, 'gtk_main', None) |
| 553 | quit_main = bind(gtk, 'gtk_main_quit', None) |
| 554 | stop_type = C.CFUNCTYPE(C.c_int, p) |
| 555 | timeout = bind(glib, 'g_timeout_add', C.c_uint, C.c_uint, stop_type, p) |
| 556 | class Target(C.Structure): |
| 557 | _fields_ = [('target', C.c_char_p), ('flags', C.c_uint), ('info', C.c_uint)] |
| 558 | provide_type = C.CFUNCTYPE(None, p, p, C.c_uint, p) |
| 559 | clear_type = C.CFUNCTYPE(None, p, p) |
| 560 | if expected_context is not None: |
| 561 | if len(paths) != 1 or image_context() != expected_context: |
| 562 | raise ValueError('图片接收位置已变化,请重新粘贴') |
| 563 | with open(paths[0], 'rb') as image: |
| 564 | data = image.read(20 * 1024 * 1024 + 1) |
| 565 | if len(data) > 20 * 1024 * 1024 or not data.startswith(b'\x89PNG\r\n\x1a\n'): |
| 566 | raise ValueError('PNG 图片无效') |
| 567 | names, payloads = [b'image/png'], [data] |
| 568 | else: |
| 569 | names = [b'text/uri-list', b'x-special/gnome-copied-files'] |
| 570 | uris = [Path(path).as_uri() for path in paths] |
| 571 | payloads = [('\r\n'.join(uris) + '\r\n').encode(), ('copy\n' + '\n'.join(uris)).encode()] |
| 572 | buffers = [C.create_string_buffer(data) for data in payloads] |
| 573 | acknowledged = False |
| 574 | @stop_type |
| 575 | def stop(_): |
| 576 | quit_main() |
| 577 | return 0 |
| 578 | @provide_type |
| 579 | def provide(_clipboard, selection, info, _data): |
| 580 | nonlocal acknowledged |
| 581 | set_data(selection, atom(names[info]), 8, buffers[info], len(payloads[info])) |
| 582 | flush() |
| 583 | if not acknowledged: |
| 584 | print('ok', flush=True) |
| 585 | acknowledged = True |
| 586 | @clear_type |
| 587 | def clear(_clipboard, _data): |
| 588 | timeout(10000, stop, None) |
| 589 | targets = (Target * len(names))(*(Target(name, 0, index) for index, name in enumerate(names))) |
| 590 | get = bind(gtk, 'gtk_clipboard_get', p, p) |
| 591 | own = bind(gtk, 'gtk_clipboard_set_with_data', C.c_int, p, C.POINTER(Target), C.c_uint, provide_type, clear_type, p) |
| 592 | if not own(get(atom(b'CLIPBOARD')), targets, len(names), provide, clear, None): |
| 593 | raise RuntimeError('clipboard unavailable') |
| 594 | flush() |
| 595 | if expected_context is not None and image_context() != expected_context: |
| 596 | raise ValueError('图片接收位置已变化,请重新粘贴') |
| 597 | subprocess.run(['xdotool', 'key', '--clearmodifiers', 'ctrl+v'], check=True, |
| 598 | stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=3) |
| 599 | timeout(120000, stop, None) |
| 600 | main() |
| 601 | |
| 602 | |
| 603 | def main(): |
| 604 | if len(sys.argv) == 3 and sys.argv[1] == '--open': |
| 605 | import http.client |
| 606 | import socket |
| 607 | class Connection(http.client.HTTPConnection): |
| 608 | def connect(self): |
| 609 | self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 610 | self.sock.settimeout(self.timeout) |
| 611 | self.sock.connect('/run/cage-desktop/files.sock') |
| 612 | client = Connection('localhost', timeout=5) |
| 613 | try: |
| 614 | |
| 615 | |
| 616 | path = sys.argv[2] |
| 617 | if not path.startswith('file:'): |
| 618 | path = str(Path(path).resolve(strict=True)) |
| 619 | client.request('POST', '/open', json.dumps({'path': path}), {'Content-Type': 'application/json'}) |
| 620 | response = client.getresponse() |
| 621 | data = response.read() |
| 622 | if response.status != 200: |
| 623 | raise ValueError(data.decode()) |
| 624 | finally: |
| 625 | client.close() |
| 626 | return |
| 627 | if len(sys.argv) == 3 and sys.argv[1] == '--save-file': |
| 628 | |
| 629 | root = Path.home() / '.local/share/cage/attachments/files' |
| 630 | broker = Broker(root) |
| 631 | key = broker.start()['id'] |
| 632 | try: |
| 633 | def chunks(): |
| 634 | while data := sys.stdin.buffer.read(65536): |
| 635 | yield data |
| 636 | broker.receive(key, sys.argv[2], chunks()) |
| 637 | print(json.dumps({'ok': True, 'path': broker.get(key)['files'][0]})) |
| 638 | except BaseException: |
| 639 | broker.cancel(key) |
| 640 | raise |
| 641 | return |
| 642 | if sys.argv[1:] == ['--clipboard']: |
| 643 | value = json.load(sys.stdin) |
| 644 | if isinstance(value, dict): |
| 645 | clipboard(value['paths'], value['image_context']) |
| 646 | else: |
| 647 | clipboard(value) |
| 648 | return |
| 649 | runtime = Path(os.environ['XDG_RUNTIME_DIR']) |
| 650 | directory = runtime / 'uploads' |
| 651 | shutil.rmtree(directory, ignore_errors=True) |
| 652 | from importlib.machinery import SourceFileLoader |
| 653 | downloads = SourceFileLoader('cage_desktop_downloads', '/usr/local/lib/cage-desktop-downloads.py').load_module() |
| 654 | broker = Broker(directory, downloads=downloads.create_downloads()) |
| 655 | portal = Portal(broker) |
| 656 | broker.deliver = portal.deliver |
| 657 | socket = runtime / 'files.sock' |
| 658 | socket.unlink(missing_ok=True) |
| 659 | server = FileServer(str(socket), Handler) |
| 660 | os.chmod(socket, 0o600) |
| 661 | server.broker = broker |
| 662 | threading.Thread(target=server.serve_forever, daemon=True).start() |
| 663 | portal.run() |
| 664 | |
| 665 | |
| 666 | if __name__ == '__main__': |
| 667 | main() |