ai_co_discuss 0.5.64 → 0.5.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/backend/server.py CHANGED
@@ -77,7 +77,7 @@ from .message_queue import drain as drain_queue, enqueue, enqueue_share, queue_a
77
77
  from .room_import import import_room, imported_attachment
78
78
  from .object_storage import (DOWNLOAD_SECONDS, OBJECT_MAX_BYTES, ObjectMissing, StorageUnavailable, configured_storage,
79
79
  object_storage_quota_mib, object_storage_retention_days, object_storage_threshold_mib,
80
- storage_http_error)
80
+ storage_http_error, storage_url)
81
81
  from .free_room import save_relay_receipt
82
82
  from .room_links import list_links
83
83
  from .free_room import insert_request, require_owner_or_host
@@ -2452,8 +2452,9 @@ DESTRUCTION_LIST_LIMIT = 20
2452
2452
  def destruction_cloud_objects(connection, room_id):
2453
2453
  """Snapshot the room's object keys before cascades remove their records."""
2454
2454
  # Older manual attachment cleanup could set cleared_at even if the provider failed.
2455
- rows = connection.execute(f"""SELECT id,object_name,size,stored_at FROM attachments
2456
- WHERE room_id=? AND storage='object' AND object_name IS NOT NULL
2455
+ rows = connection.execute(f"""SELECT id,object_name,size,
2456
+ CASE WHEN storage='object' THEN stored_at ELSE created_at END AS stored_at FROM attachments
2457
+ WHERE room_id=? AND (storage='object' AND object_name IS NOT NULL OR {PENDING_VIA_CLOUD_ATTACHMENT})
2457
2458
  UNION ALL
2458
2459
  SELECT id,object_name,size,stored_at FROM cloud_files
2459
2460
  WHERE room_id=? AND purpose!='keep' AND cleared_at IS NULL""", (room_id, room_id))
@@ -3531,7 +3532,7 @@ def query_attachments(connection, room_id, params, token=""):
3531
3532
  where += " AND (message_id IS NULL OR message_id<=?)"
3532
3533
  values.append(cutoff)
3533
3534
  if "submission_id" in params:
3534
- where += " AND submission_id=?"
3535
+ where += " AND submission_id=? AND NOT (message_id IS NULL AND cleared_at IS NOT NULL)"
3535
3536
  values.append(submission_value(params["submission_id"]))
3536
3537
  else:
3537
3538
  where += " AND message_id IS NOT NULL"
@@ -3550,7 +3551,7 @@ def query_attachments(connection, room_id, params, token=""):
3550
3551
  def get_attachment(connection, room_id, identifier, params=None, token="", content=False):
3551
3552
  """Resolve a file only within the explicitly selected room, and within the caller's reading boundary."""
3552
3553
  row = connection.execute("SELECT * FROM attachments WHERE room_id=? AND id=?", (room_id, identifier)).fetchone()
3553
- if not row:
3554
+ if not row or (row["message_id"] is None and row["cleared_at"]):
3554
3555
  raise LookupError(Text('附件不存在'))
3555
3556
  cutoff = attachment_cutoff(connection, room_id, params or {}, token, content)
3556
3557
  if cutoff is not None and row["message_id"] is not None and row["message_id"] > cutoff:
@@ -3961,13 +3962,20 @@ def store_attachment(connection, database, room_id, metadata, body, *, token, wr
3961
3962
  temporary = Path(staging) / "content"
3962
3963
  with temporary.open("xb", buffering=0) as target:
3963
3964
  stream_upload(source, target, length, digest, write_chunk=write_chunk)
3964
- with temporary.open("rb") as incoming:
3965
- content_type = attachment_content_type(incoming.read(max(128, SVG_SNIFF_BYTES)))
3966
- incoming.seek(0)
3967
- width, height = image_size(incoming) if content_type in SIZED_IMAGE_TYPES else (None, None)
3968
- info = {"size": length, "sha256": digest.hexdigest(), "content_type": content_type}
3965
+ properties = staged_attachment_properties(temporary)
3966
+ info = {"size": length, "sha256": digest.hexdigest(), "content_type": properties["content_type"]}
3969
3967
  authorize_attachment_upload(connection, room_id, token, metadata)
3970
- return save_staged_attachment(connection, database, room_id, metadata, (temporary, info, width, height))
3968
+ return save_staged_attachment(connection, database, room_id, metadata,
3969
+ (temporary, info, properties["width"], properties["height"]))
3970
+
3971
+
3972
+ def staged_attachment_properties(path):
3973
+ """Report the type and image dimensions from staged bytes, not the upload declaration."""
3974
+ with path.open("rb") as incoming:
3975
+ content_type = attachment_content_type(incoming.read(max(128, SVG_SNIFF_BYTES)))
3976
+ incoming.seek(0)
3977
+ width, height = image_size(incoming) if content_type in SIZED_IMAGE_TYPES else (None, None)
3978
+ return {"content_type": content_type, "width": width, "height": height}
3971
3979
 
3972
3980
 
3973
3981
  def save_staged_attachment(connection, database, room_id, metadata, staged):
@@ -3979,7 +3987,8 @@ def save_staged_attachment(connection, database, room_id, metadata, staged):
3979
3987
  previous = connection.execute("SELECT * FROM attachments WHERE room_id=? AND submission_id=?",
3980
3988
  (room_id, metadata["submission_id"])).fetchone()
3981
3989
  if previous:
3982
- if any(previous[key] != value for key, value in expected.items()):
3990
+ if (previous["cleared_at"] or previous["storage"] is not None
3991
+ or any(previous[key] != value for key, value in expected.items())):
3983
3992
  raise FileExistsError(Text('这个附件提交编号已被其他文件使用'))
3984
3993
  return {"attachment": attachment_view(connection, previous), "duplicate": True}
3985
3994
  prune_unsent_attachments(connection, database, room_id)
@@ -4014,12 +4023,18 @@ def object_upload_metadata(payload, actor):
4014
4023
 
4015
4024
  # Imported records have no object in this account. Pending uploads already reserve their full declared size.
4016
4025
  LIVE_CLOUD_ATTACHMENTS = "storage='object' AND object_name IS NOT NULL AND cleared_at IS NULL"
4026
+ PENDING_VIA_CLOUD_ATTACHMENT = "storage IS NULL AND object_scope='via_cloud' AND object_name IS NOT NULL"
4027
+
4028
+
4029
+ def pending_via_cloud_attachment(row):
4030
+ """The local file is settled, but the provider has not confirmed deletion of its temporary copy."""
4031
+ return row["storage"] is None and row["object_scope"] == "via_cloud" and row["object_name"] is not None
4017
4032
 
4018
4033
 
4019
4034
  def object_storage_used_bytes(connection):
4020
4035
  """Count all live objects and upload reservations in this account's database."""
4021
4036
  return connection.execute(f"""SELECT
4022
- (SELECT COALESCE(SUM(size),0) FROM attachments WHERE {LIVE_CLOUD_ATTACHMENTS}) +
4037
+ (SELECT COALESCE(SUM(size),0) FROM attachments WHERE {LIVE_CLOUD_ATTACHMENTS} OR {PENDING_VIA_CLOUD_ATTACHMENT}) +
4023
4038
  (SELECT COALESCE(SUM(size),0) FROM cloud_files WHERE cleared_at IS NULL) +
4024
4039
  (SELECT COALESCE(SUM(json_extract(object.value,'$.size')),0) FROM room_destructions AS d,
4025
4040
  json_each(d.items) AS item, json_each(item.value,'$.objects') AS object WHERE d.status='cleaning')""").fetchone()[0]
@@ -4044,23 +4059,27 @@ def object_storage_limits(connection, database, attachment_limit):
4044
4059
  }
4045
4060
 
4046
4061
 
4047
- def reserve_object_attachment(connection, database, room_id, metadata, *, allow_small=False, require_via_cloud=None):
4062
+ def reserve_object_attachment(connection, database, room_id, metadata, *, require_via_cloud, allow_small=False):
4048
4063
  """Reserve a room-owned path; only the same submission can recover the reservation."""
4049
4064
  begin_write(connection)
4050
4065
  previous = connection.execute("SELECT * FROM attachments WHERE room_id=? AND submission_id=?",
4051
4066
  (room_id, metadata["submission_id"])).fetchone()
4052
4067
  if previous:
4068
+ if previous["object_scope"] == "via_cloud":
4069
+ require_via_cloud()
4070
+ if previous["storage"] is None:
4071
+ if previous["cleared_at"] or any(previous[key] != metadata[key] for key in ("file_name", "actor", "size")):
4072
+ raise FileExistsError(Text("这个附件提交编号已被其他文件使用"))
4073
+ return dict(previous)
4053
4074
  if (previous["storage"] != "object" or not previous["object_name"] or previous["cleared_at"]
4054
4075
  or any(previous[key] != value for key, value in metadata.items())):
4055
4076
  raise FileExistsError(Text("这个附件提交编号已被其他文件使用"))
4056
- if previous["object_scope"] == "via_cloud" and require_via_cloud:
4057
- require_via_cloud()
4058
4077
  return dict(previous)
4059
4078
  threshold = object_storage_threshold_mib(database, attachment_limit_mib(database))
4060
4079
  is_small = metadata["size"] <= threshold * BYTES_PER_MIB
4061
4080
  if is_small and not allow_small:
4062
4081
  raise ValueError(Text("仅超过 {limit} MiB 的附件使用对象存储", limit=threshold))
4063
- if is_small and require_via_cloud:
4082
+ if is_small:
4064
4083
  require_via_cloud()
4065
4084
  require_cloud_quota(connection, database, metadata["size"])
4066
4085
  identifier = uuid.uuid4().hex
@@ -4179,6 +4198,38 @@ def verify_object_size(client, record):
4179
4198
  raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致"))
4180
4199
 
4181
4200
 
4201
+ def stage_cloud_attachment(client, record, temporary, *, write_chunk):
4202
+ """Stream a signed object download to private staging and verify its length."""
4203
+ digest = hashlib.sha256()
4204
+ name, size = record["object_name"], record["size"]
4205
+ try:
4206
+ verify_object_size(client, record)
4207
+ # Resource-center clients sign via download_request; S3 signs the same GET locally.
4208
+ url = client.download(name)["url"]
4209
+ if not storage_url(url, https_only=True):
4210
+ raise StorageUnavailable()
4211
+ target = urlsplit(url)
4212
+ route = (target.path or "/") + ("?" + target.query if target.query else "")
4213
+ with closing(HTTPSConnection(target.hostname, target.port, timeout=CLOUD_COPY_TIMEOUT_SECONDS)) as remote:
4214
+ remote.request("GET", route)
4215
+ with remote.getresponse() as incoming, temporary.open("xb", buffering=0) as destination:
4216
+ if incoming.status in (404, 410):
4217
+ raise FileExistsError(Text("对象存储尚未收到文件"))
4218
+ if incoming.status != 200:
4219
+ raise StorageUnavailable()
4220
+ try:
4221
+ stream_upload(incoming, destination, size, digest, write_chunk=write_chunk)
4222
+ except ValueError:
4223
+ raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致")) from None
4224
+ if incoming.read(1):
4225
+ raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致"))
4226
+ except FileExistsError:
4227
+ raise
4228
+ except (HTTPException, OSError, ValueError):
4229
+ raise StorageUnavailable() from None
4230
+ return {**staged_attachment_properties(temporary), "sha256": digest.hexdigest()}
4231
+
4232
+
4182
4233
  def require_temporary_file_fresh(expires_at, cleared_at=None):
4183
4234
  """Report expiry separately from a deletion that happened before the deadline."""
4184
4235
  if not expires_at:
@@ -4366,7 +4417,7 @@ def queued_attachment_ids(connection, room_id):
4366
4417
  def unsent_attachment_rows(connection, room_id):
4367
4418
  """Files uploaded in this room that no message took and no queued message is waiting to send."""
4368
4419
  queued = queued_attachment_ids(connection, room_id)
4369
- return [row for row in connection.execute("SELECT * FROM attachments WHERE room_id=? AND message_id IS NULL", (room_id,))
4420
+ return [row for row in connection.execute("SELECT * FROM attachments WHERE room_id=? AND message_id IS NULL AND cleared_at IS NULL", (room_id,))
4370
4421
  if row["id"] not in queued]
4371
4422
 
4372
4423
 
@@ -4408,10 +4459,36 @@ def delete_remote_attachments(database, rows):
4408
4459
  return sum(not delete_remote_attachment(database, row, client) for row in rows)
4409
4460
 
4410
4461
 
4462
+ def settle_via_cloud_attachment(connection, database, row, client):
4463
+ """Keep the cleanup key and quota until the provider confirms deletion."""
4464
+ if not delete_remote_attachment(database, row, client):
4465
+ return
4466
+ with connection:
4467
+ connection.execute(f"""UPDATE attachments SET object_name=NULL
4468
+ WHERE id=? AND room_id=? AND object_name=? AND {PENDING_VIA_CLOUD_ATTACHMENT}""",
4469
+ (row["id"], row["room_id"], row["object_name"]))
4470
+ connection.execute("""DELETE FROM attachments WHERE id=? AND room_id=? AND storage IS NULL
4471
+ AND object_scope='via_cloud' AND object_name IS NULL AND message_id IS NULL AND cleared_at IS NOT NULL""",
4472
+ (row["id"], row["room_id"]))
4473
+
4474
+
4475
+ def sweep_via_cloud_attachments(connection, database):
4476
+ """Retry temporary cloud copies left behind by an interrupted completion."""
4477
+ rows = connection.execute(f"SELECT id,room_id,object_name FROM attachments WHERE {PENDING_VIA_CLOUD_ATTACHMENT}").fetchall()
4478
+ if rows:
4479
+ client = configured_storage(database)
4480
+ for row in rows:
4481
+ settle_via_cloud_attachment(connection, database, row, client)
4482
+
4483
+
4411
4484
  def remove_attachment_files(connection, database, rows):
4412
- """Delete unsent uploads and their bytes; the caller commits."""
4485
+ """Delete unsent uploads and their bytes; retain an unsettled cloud cleanup key."""
4413
4486
  for row in rows:
4414
- connection.execute("DELETE FROM attachments WHERE id=? AND message_id IS NULL", (row["id"],))
4487
+ if pending_via_cloud_attachment(row):
4488
+ connection.execute("UPDATE attachments SET cleared_at=? WHERE id=? AND message_id IS NULL",
4489
+ (utc_iso_now(), row["id"]))
4490
+ else:
4491
+ connection.execute("DELETE FROM attachments WHERE id=? AND message_id IS NULL", (row["id"],))
4415
4492
  attachment_path(database, row).unlink(missing_ok=True)
4416
4493
  thumbnail_path(database, row).unlink(missing_ok=True)
4417
4494
 
@@ -4519,16 +4596,22 @@ def sweep_attachments(database, *, expire_objects=True):
4519
4596
  with closing(connect_db(database)) as connection:
4520
4597
  with connection:
4521
4598
  begin_write(connection)
4522
- rooms = connection.execute("SELECT DISTINCT room_id FROM attachments WHERE message_id IS NULL").fetchall()
4599
+ pending_expired = []
4600
+ rooms = connection.execute("SELECT DISTINCT room_id FROM attachments WHERE message_id IS NULL AND cleared_at IS NULL").fetchall()
4523
4601
  for room in rooms:
4524
4602
  for row in expired_unsent_attachments(connection, room[0]):
4525
4603
  if row["storage"] == "object" and row["object_name"] and not row["cleared_at"]:
4526
4604
  cloud_drafts.add(row["id"])
4605
+ elif pending_via_cloud_attachment(row):
4606
+ pending_expired.append(row)
4527
4607
  else:
4528
4608
  expired.add(row["id"])
4529
4609
  connection.executemany("DELETE FROM attachments WHERE id=? AND message_id IS NULL", ((key,) for key in expired))
4610
+ if pending_expired:
4611
+ remove_attachment_files(connection, database, pending_expired)
4530
4612
  sweep_unsent_object_attachments(connection, database, cloud_drafts)
4531
4613
  if expire_objects:
4614
+ sweep_via_cloud_attachments(connection, database)
4532
4615
  sweep_cloud_file_drafts(connection, database)
4533
4616
  sweep_cloud_transfers(connection, database)
4534
4617
  cloud_drive.sweep_trash(connection, database)
@@ -4539,7 +4622,8 @@ def sweep_attachments(database, *, expire_objects=True):
4539
4622
  # Uploads acquire this same write lock before creating their file. Hold it from the ID snapshot through unlink.
4540
4623
  with connection:
4541
4624
  begin_write(connection)
4542
- registered = {os.path.normcase(row[0]) for row in connection.execute("SELECT id FROM attachments")}
4625
+ registered = {os.path.normcase(row[0]) for row in connection.execute(
4626
+ "SELECT id FROM attachments WHERE NOT (message_id IS NULL AND cleared_at IS NOT NULL)")}
4543
4627
  registered.update("cloud-" + row[0] for row in connection.execute(
4544
4628
  "SELECT id FROM cloud_files WHERE thumbnail_type IS NOT NULL AND cleared_at IS NULL"))
4545
4629
  cutoff = time.time() - ORPHAN_ATTACHMENT_GRACE_SECONDS
@@ -4572,7 +4656,9 @@ def discard_attachment(connection, database, room_id, identifier, token):
4572
4656
  raise FileExistsError(Text('附件已随消息发出或正在排队,不能撤下'))
4573
4657
  remove_attachment_files(connection, database, [row])
4574
4658
  connection.commit()
4575
- if row["storage"] == "object" and row["object_name"]:
4659
+ if pending_via_cloud_attachment(row):
4660
+ settle_via_cloud_attachment(connection, database, row, configured_storage(database))
4661
+ elif row["storage"] == "object" and row["object_name"]:
4576
4662
  delete_remote_attachments(database, [row])
4577
4663
  return {"discarded": identifier}
4578
4664
 
@@ -4632,6 +4718,8 @@ def check_message_attachments(connection, room_id, actor, identifiers):
4632
4718
  attachment = get_attachment(connection, room_id, identifier)
4633
4719
  if attachment["actor"] != actor or attachment["message_id"] is not None:
4634
4720
  raise FileExistsError(Text('附件已用于其他消息,或不属于本次实际提交者'))
4721
+ if attachment["cleared_at"]:
4722
+ raise LookupError(Text("附件不存在"))
4635
4723
  if attachment.get("storage") == "object" and not attachment["stored"]:
4636
4724
  raise ValueError(Text("附件尚未完成上传"))
4637
4725
 
@@ -6689,7 +6777,9 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6689
6777
  return False
6690
6778
  self.close_connection = True
6691
6779
  # Sent directly, not through respond(): a refused caller leaves nothing in any room's event log.
6692
- message = Text("这个工作台只接受经入口的访问;本机管理员请从任务栏图标或桌面“共议”打开")
6780
+ parts = parsed.path.strip("/").split("/")
6781
+ message = (self.media_owner_required() if self.media_command_post(parts, method) or self.no_wake_post(parts, method, read=True)
6782
+ else Text("这个工作台只接受经入口的访问;本机管理员请从任务栏图标或桌面“共议”打开"))
6693
6783
  self.send_payload(403, "application/json", json.dumps(error_body(message), ensure_ascii=False).encode("utf-8"))
6694
6784
  return True
6695
6785
 
@@ -6729,6 +6819,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6729
6819
  def dispatch_routes(self, method, parsed, params, parts, text_mode):
6730
6820
  """Route one request and map validation, permission and lookup errors to their status codes."""
6731
6821
  open_database = self.request_database(method, parts)
6822
+ body_drained = False
6732
6823
  try:
6733
6824
  if self.headers.get("X-Discussion-Token") or self.headers.get(ACTING_MEMBER_HEADER) or guest_path(parts):
6734
6825
  with open_database() as guard_connection:
@@ -6748,7 +6839,11 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6748
6839
  guard_external_route(open_database, self.headers, parts)
6749
6840
  except PermissionError:
6750
6841
  # Read the unread body first, or the refusal can reach the gateway as a reset connection.
6751
- self.rfile.read(min(int(self.headers.get("Content-Length") or 0), MAX_BODY_BYTES))
6842
+ if self.no_wake_post(parts, method, read=True):
6843
+ raise self.media_owner_required() from None
6844
+ if not self.message_post_route(parts, method):
6845
+ self.rfile.read(min(int(self.headers.get("Content-Length") or 0), MAX_BODY_BYTES))
6846
+ body_drained = True
6752
6847
  self.close_connection = True
6753
6848
  raise
6754
6849
  self.bridged = self.relay_bridge(parts)
@@ -6784,6 +6879,9 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6784
6879
  except PermissionError as error:
6785
6880
  if getattr(error, "details", {}).get("code", "").startswith("guest_"):
6786
6881
  self.close_connection = True
6882
+ if self.media_command_post(parts, method) or self.no_wake_post(parts, method, read=not body_drained):
6883
+ self.close_connection = True
6884
+ error = self.media_owner_required()
6787
6885
  return self.respond(self.request_error(error, parts), 403)
6788
6886
  except (ValueError, TypeError) as error:
6789
6887
  return self.respond(self.plain_error(error) if text_mode else self.request_error(error, parts), 400,
@@ -6801,6 +6899,33 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6801
6899
  logging.exception("Request failed")
6802
6900
  return self.respond(error_body(Text("服务器内部错误")), 500)
6803
6901
 
6902
+ @staticmethod
6903
+ def media_owner_required():
6904
+ """Use one machine-readable refusal across media commands and silent publication."""
6905
+ return BoundaryError(Text("需要本房间的控制凭据;没有凭据只能阅读"), code="media_owner_required")
6906
+
6907
+ @staticmethod
6908
+ def media_command_post(parts, method):
6909
+ return method == "POST" and len(parts) == 3 and parts[:2] == ["api", "local"] and parts[2] in MEDIA_ROOM_COMMANDS
6910
+
6911
+ @staticmethod
6912
+ def message_post_route(parts, method):
6913
+ return method == "POST" and (
6914
+ len(parts) == 4 and parts[:2] == ["api", "rooms"] and parts[3] == "messages"
6915
+ or guest_path(parts) and parts[5:] == ["messages"])
6916
+
6917
+ def no_wake_post(self, parts, method, *, read=False):
6918
+ """Recognize a silent publish even when an earlier guest or member guard denied it."""
6919
+ if not self.message_post_route(parts, method):
6920
+ return False
6921
+ payload = self.payload_cache
6922
+ if payload is None and read:
6923
+ try:
6924
+ payload = self.read_payload()
6925
+ except ValueError:
6926
+ return False
6927
+ return bool(payload and payload.get("no_wake") is True)
6928
+
6804
6929
  @staticmethod
6805
6930
  def group_window_room(parts):
6806
6931
  """Recognize the room in JSON, text, and external room paths."""
@@ -7417,19 +7542,37 @@ class DiscussionHandler(BaseHTTPRequestHandler):
7417
7542
 
7418
7543
  def handle_local_media_command(self, command, site):
7419
7544
  """Pin media commands to the authenticated origin and keep provider calls in the runner."""
7420
- if self.read_only_request() or self.headers.get(ACTING_MEMBER_HEADER) or self.entry_member_request():
7545
+ if self.read_only_request() or self.headers.get(ACTING_MEMBER_HEADER):
7421
7546
  raise PermissionError(Text('需要管理员登录'))
7422
7547
  if self.headers.get_content_type() != "application/json":
7423
7548
  raise ValueError(Text('本机操作须使用 application/json'))
7424
7549
  payload = self.read_payload()
7425
7550
  if command in MEDIA_ROOM_COMMANDS:
7426
- payload.pop("access_file", None)
7427
- payload.pop("_moss_owner", None)
7551
+ if "access_file" in payload or "_moss_owner" in payload:
7552
+ raise self.media_owner_required()
7428
7553
  payload.update(site=site, entry="web")
7429
- if not payload.get("token") and not self.bridge_origin:
7554
+ header = self.headers.get("X-Discussion-Token", "")
7555
+ token = payload.get("token", "")
7556
+ if not isinstance(token, str):
7557
+ raise self.media_owner_required()
7558
+ token = token or header
7559
+ if self.bridge_origin:
7560
+ if not token or (header and header != token):
7561
+ raise self.media_owner_required()
7562
+ else:
7563
+ room_id = payload.get("room_id", "")
7564
+ if not isinstance(room_id, str) or not room_id:
7565
+ raise self.media_owner_required()
7430
7566
  with closing(connect_db(self.server.database)) as connection:
7431
- self.admin_as_owner(connection, payload.get("room_id", ""))
7432
- payload["token"] = self.headers.get("X-Discussion-Token", "")
7567
+ if header:
7568
+ require_owner(connection, room_id, header)
7569
+ if not token:
7570
+ self.admin_as_owner(connection, room_id)
7571
+ token = self.headers.get("X-Discussion-Token", "")
7572
+ require_owner(connection, room_id, token if isinstance(token, str) else "")
7573
+ payload["token"] = token
7574
+ elif self.entry_member_request():
7575
+ raise PermissionError(Text('需要管理员登录'))
7433
7576
  return self.run_local_command(command, payload, remote=bool(self.bridge_origin))
7434
7577
 
7435
7578
  def issue_media_ticket(self, payload):
@@ -8615,7 +8758,14 @@ class DiscussionHandler(BaseHTTPRequestHandler):
8615
8758
  elif method == "POST" and parts[3:] == ["limits"] and current_session(connection, room_id, active_only=True):
8616
8759
  pass
8617
8760
  elif method == "POST":
8618
- free_actor = authorize_free_write(connection, room_id, token, parts[3] if len(parts) > 3 else "", self.read_payload())
8761
+ payload = self.read_payload()
8762
+ if self.no_wake_post(parts, method):
8763
+ if self.headers.get(ACTING_MEMBER_HEADER) or "access_file" in payload:
8764
+ raise self.media_owner_required()
8765
+ if payload.get("token", "") != "":
8766
+ require_owner(connection, room_id, payload["token"] if isinstance(payload["token"], str) else "")
8767
+ require_owner(connection, room_id, token)
8768
+ free_actor = authorize_free_write(connection, room_id, token, parts[3] if len(parts) > 3 else "", payload)
8619
8769
  if (parts[3:] == ["backup"] and method == "GET") or (len(parts) == 4 and parts[3] in DIRECTORY_OPERATIONS and method == "POST"):
8620
8770
  self.require_entry_owner(connection, room_id, token)
8621
8771
  if parts[3:] == ["backup"] and method == "GET":
@@ -8691,8 +8841,6 @@ class DiscussionHandler(BaseHTTPRequestHandler):
8691
8841
  if method == "GET":
8692
8842
  return self.respond(query_messages(connection, room_id, params, token, search_database=self.server.database))
8693
8843
  payload = self.read_payload()
8694
- if payload.get("no_wake") is True and self.headers.get(ACTING_MEMBER_HEADER):
8695
- raise PermissionError(Text("需要本房间的控制凭据"))
8696
8844
  if free_actor == "用户":
8697
8845
  room = require_room(connection, room_id)
8698
8846
  if room["system_kind"] == moss_window_messages.GROUP_KIND:
@@ -9135,49 +9283,65 @@ class DiscussionHandler(BaseHTTPRequestHandler):
9135
9283
  raise PermissionError(Text("附件上传者须与凭据身份一致"))
9136
9284
  require_room(connection, room_id)
9137
9285
  database = self.server.database
9138
- threshold = object_storage_threshold_mib(database, attachment_limit_mib(database)) * BYTES_PER_MIB
9139
- via_cloud = payload.get("via_cloud") is True
9140
- allow_small = via_cloud and metadata["size"] <= threshold
9286
+ limit = attachment_limit_mib(database)
9287
+ threshold = object_storage_threshold_mib(database, limit) * BYTES_PER_MIB
9288
+ via_cloud = payload.get("via_cloud") is True and metadata["size"] <= threshold
9289
+ allow_small = via_cloud and metadata["size"] <= limit * BYTES_PER_MIB
9141
9290
  require_via_cloud = lambda: self.require_attachment_outbound_session(connection)
9142
- if allow_small:
9291
+ if via_cloud:
9143
9292
  require_via_cloud()
9144
- client = configured_storage(self.server.database)
9145
- if not client:
9293
+ client = configured_storage(database)
9294
+ if not client and not connection.execute("""SELECT 1 FROM attachments
9295
+ WHERE room_id=? AND submission_id=? AND object_scope='via_cloud' AND storage IS NULL""",
9296
+ (room_id, metadata["submission_id"])).fetchone():
9146
9297
  raise FileExistsError(Text("对象存储未配置"))
9147
9298
  record = reserve_object_attachment(connection, database, room_id, metadata,
9148
9299
  allow_small=allow_small, require_via_cloud=require_via_cloud)
9149
9300
  connection.commit()
9150
9301
  try:
9151
- upload = None if record["stored_at"] else client.upload(record["object_name"], record["size"], record["content_type"])
9302
+ upload = None if record["storage"] != "object" or record["stored_at"] else client.upload(
9303
+ record["object_name"], record["size"], record["content_type"])
9152
9304
  except StorageUnavailable as error:
9153
9305
  failure = storage_http_error(error)
9154
9306
  failure.details = {"code": "object_reserved", "attachment_id": record["id"]}
9155
9307
  raise failure from None
9156
9308
  return self.respond({"attachment": attachment_view(connection, record), "upload": upload})
9157
9309
 
9158
- def complete_object_upload(self, connection, room_id, identifier):
9159
- """Verify size with the resource center and mark exactly the reserved row as stored."""
9310
+ def object_upload_for_completion(self, connection, room_id, identifier):
9311
+ """Recheck uploader, trusted session and draft state under the write lock."""
9312
+ begin_write(connection)
9313
+ record = connection.execute("SELECT * FROM attachments WHERE room_id=? AND id=?", (room_id, identifier)).fetchone()
9314
+ if record is None or (record["storage"] != "object" and record["object_scope"] != "via_cloud"):
9315
+ raise LookupError(Text("附件不存在"))
9160
9316
  token = self.headers.get("X-Discussion-Token", "")
9161
- record = get_object_attachment(connection, room_id, identifier)
9162
9317
  actor = authorize_free_write(connection, room_id, token, "attachments", {"author": record["actor"]})
9163
9318
  if (actor if isinstance(actor, str) else actor["name"]) != record["actor"]:
9164
9319
  raise PermissionError(Text("只能确认自己上传的附件"))
9165
- if record["cleared_at"] or not record["object_name"]:
9320
+ if record["object_scope"] == "via_cloud":
9321
+ self.require_attachment_outbound_session(connection)
9322
+ if record["message_id"] is None and record["cleared_at"]:
9323
+ raise LookupError(Text("附件不存在"))
9324
+ if record["cleared_at"] or (record["storage"] == "object" and not record["object_name"]):
9166
9325
  raise AdminError(Text("文件已不在对象存储中"), 410)
9167
- if record["stored_at"]:
9326
+ return record
9327
+
9328
+ def complete_object_upload(self, connection, room_id, identifier):
9329
+ """Verify one reservation, returning a local receipt for a temporary cloud upload."""
9330
+ record = self.object_upload_for_completion(connection, room_id, identifier)
9331
+ via_cloud = record["object_scope"] == "via_cloud"
9332
+ if record["storage"] is None or (record["stored_at"] and not via_cloud):
9168
9333
  return self.respond({"attachment": attachment_view(connection, record)})
9169
9334
  connection.commit()
9170
9335
  client = configured_storage(self.server.database)
9171
9336
  if not client:
9172
9337
  raise AdminError(Text("对象存储暂不可用"), 503)
9338
+ if via_cloud:
9339
+ return self.complete_via_cloud_upload(connection, record, client)
9173
9340
  try:
9174
- size = client.file_size(record["object_name"])
9175
- except ObjectMissing:
9176
- raise FileExistsError(Text("对象存储尚未收到文件")) from None
9341
+ verify_object_size(client, record)
9177
9342
  except StorageUnavailable as error:
9178
9343
  raise storage_http_error(error) from None
9179
- if size != record["size"]:
9180
- raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致"))
9344
+ token = self.headers.get("X-Discussion-Token", "")
9181
9345
  authorize_free_write(connection, room_id, token, "attachments", {"author": record["actor"]})
9182
9346
  connection.execute("UPDATE attachments SET stored_at=? WHERE room_id=? AND id=? AND cleared_at IS NULL AND stored_at IS NULL",
9183
9347
  (utc_now(), room_id, identifier))
@@ -9185,6 +9349,56 @@ class DiscussionHandler(BaseHTTPRequestHandler):
9185
9349
  connection.commit()
9186
9350
  return self.respond({"attachment": attachment_view(connection, result)})
9187
9351
 
9352
+ def complete_via_cloud_upload(self, connection, record, client):
9353
+ """Stage an admitted local copy, then clean up its durable cloud reservation."""
9354
+ database = self.server.database
9355
+ size = record["size"]
9356
+ with self.attachment_upload_reservation(size, size > attachment_limit_mib(database) * BYTES_PER_MIB) as writer:
9357
+ if writer is None:
9358
+ raise AdminError(self.attachment_budget_error(), 413)
9359
+ updated = self.install_via_cloud_attachment(connection, record, client, writer)
9360
+ if updated is not None:
9361
+ try:
9362
+ generate_attachment_thumbnail(connection, database, updated)
9363
+ finally:
9364
+ settle_via_cloud_attachment(connection, database, record, client)
9365
+ return self.respond({"attachment": get_attachment(connection, record["room_id"], record["id"])})
9366
+
9367
+ def install_via_cloud_attachment(self, connection, record, client, write_chunk):
9368
+ """Stream outside the SQLite write lock, then publish only while the draft still matches."""
9369
+ database = self.server.database
9370
+ room_id, identifier = record["room_id"], record["id"]
9371
+ path = attachment_path(database, record)
9372
+ path.parent.mkdir(parents=True, exist_ok=True)
9373
+ with tempfile.TemporaryDirectory(dir=path.parent, prefix=".upload-") as directory:
9374
+ temporary = Path(directory) / "content"
9375
+ try:
9376
+ properties = stage_cloud_attachment(client, record, temporary, write_chunk=write_chunk)
9377
+ except (FileExistsError, StorageUnavailable) as error:
9378
+ # A concurrent completion can delete the remote object before this download reaches it.
9379
+ current = self.object_upload_for_completion(connection, room_id, identifier)
9380
+ if current["storage"] is None:
9381
+ return None
9382
+ if isinstance(error, StorageUnavailable):
9383
+ raise storage_http_error(error) from None
9384
+ raise
9385
+ current = self.object_upload_for_completion(connection, room_id, identifier)
9386
+ if current["storage"] is None:
9387
+ return None
9388
+ if current["object_name"] != record["object_name"] or current["size"] != record["size"]:
9389
+ raise FileExistsError(Text("这个附件提交编号已被其他文件使用"))
9390
+ temporary.replace(path)
9391
+ try:
9392
+ connection.execute("""UPDATE attachments SET storage=NULL, stored_at=NULL,
9393
+ sha256=:sha256, content_type=:content_type, width=:width, height=:height
9394
+ WHERE room_id=:room_id AND id=:id AND storage='object' AND cleared_at IS NULL""",
9395
+ {**properties, "room_id": room_id, "id": identifier})
9396
+ connection.commit()
9397
+ except Exception:
9398
+ path.unlink(missing_ok=True)
9399
+ raise
9400
+ return {**dict(current), **properties}
9401
+
9188
9402
  def import_attachment(self, connection, room_id, attachment_id):
9189
9403
  """Store the original bytes of an attachment recorded by an import; an existing file is kept."""
9190
9404
  if self.headers.get_content_type() == "application/json":
@@ -9493,6 +9707,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
9493
9707
 
9494
9708
  def handle_guest_projection(self, connection, parts, params, method):
9495
9709
  """Commit a guest write before notifying room subscribers."""
9710
+ if self.message_post_route(parts, method) and self.read_payload().get("no_wake") is True:
9711
+ raise self.media_owner_required()
9496
9712
  data = guest_projection(connection, parts, method, self.headers.get("X-Discussion-Token", ""), params, self.read_payload)
9497
9713
  connection.commit()
9498
9714
  if method == "POST":
@@ -51,9 +51,9 @@ Fast and Ultrafast show a lightning badge on expert cards, room member cards, an
51
51
  ## See context and usage limits
52
52
 
53
53
  - **Context.** It belongs to each member's own session. After each run, the room records how much of it is in use, shown as a thin progress bar with a percentage, fuller as more is used: grey normally, amber from 80% and red from 95% (software usually compacts before it is full) (rings only ever mean account limits, so a bar is always context): at the end of the member's status line in the right sidebar's speaking order, on the “Context” row at the end of each member card on **Members and settings**, and under the private chat's input box. It is not shown on a working card, since it is read only after a run ends. Click the bar to see the tokens used against the window size. When the window size is unknown the bar is a dashed line with no percentage and the details say “489K used, window size unknown”.
54
- - **Account usage limits.** How much is left in the 5-hour, 7-day or other windows and when each resets; a prepaid model API shows its balance. Limits belong to an account, so several members of one software show it once: the right end of the grey line under the message box shows the accounts above the display line, each account given two figures with the windows named once at the end (such as “Claude 65% / 33% Codex ∞ / 45% Gemini ∞ / 5% 5h / 7d”; a model group shows by its group name; ∞ where there is no such limit, — where nothing was read yet). Clicking it opens a table with one line per account: the subscription tier appears beside the account name (read automatically for Claude Code and Codex; for software that does not report its tier, such as Antigravity CLI, managers can click the configuration button at the end of the row to pick or clear a tier from the dropdown, synced across all rooms and paired devices and used in **Analytics → Subscription usage**); 5h and 7d show the percentage left and the reset time. The bar shortens as the limit is used, turns amber at 20% left, and keeps a red track at 0% alongside the red number. Managers can drag an account by its handle or move the dashed display line with the eye icon. You can also focus a handle or the display line and use the up and down arrow keys. The first three accounts are shown by default. Once saved, only the accounts above the line are shown, and you can move all of them below it. The selection and order apply to all rooms and paired devices. The send and new-line keys appear when you point at the send button. A member's line carries no limit figures and no warning when one runs low, only “Limit used up · back at 14:00” once used up. Phones hide that grey line, and on tablets or narrow windows the limits leave it too; instead a button sits beside the paper clip in the message box with a pair of rings for each account above the display line, in the same order (an account with only a balance gets none): the outer ring is 7 days and the inner ring 5 hours, with green arcs that shorten as usage rises, amber at 20% left, and a red track when used up, dashed where there is no such limit. A small dot appears when an account not shown runs low. If no accounts are selected or none has rings, a gauge icon still opens the full table. When creating a room or inviting a member, the front of the member card has a “Usage limits” row to help choose the software. A group with a 7-day window but no 5-hour one shows “5h no limit”.
54
+ - **Account usage limits.** How much is left in the 5-hour, 7-day or other windows and when each resets; a prepaid model API shows its balance. Limits belong to an account, so several members of one software show it once: the right end of the grey line under the message box shows the accounts above the display line, each account given two figures with the windows named once at the end (such as “Claude 65% / 33% Codex ∞ / 45% Gemini ∞ / 5% 5h / 7d”; a model group shows by its group name; ∞ where there is no such limit, — where nothing was read yet). Clicking it opens a table with one line per account: the subscription tier appears beside the account name (read automatically for Claude Code and Codex; for software that does not report its tier, such as Antigravity CLI, managers can click the configuration button at the end of the row to pick or clear a tier from the dropdown, synced across all rooms and paired devices and used in **Analytics → Subscription usage**); 5h and 7d show the percentage left and the reset time. The bar shortens as the limit is used, turns amber at 20% left, and stays an empty track at 0% while the red 0% carries the warning. Managers can drag an account by its handle or move the dashed display line with the eye icon. You can also focus a handle or the display line and use the up and down arrow keys. The first three accounts are shown by default. Once saved, only the accounts above the line are shown, and you can move all of them below it. The selection and order apply to all rooms and paired devices. The send and new-line keys appear when you point at the send button. A member's line carries no limit figures and no warning when one runs low, only “Limit used up · back at 14:00” once used up. Phones hide that grey line, and on tablets or narrow windows the limits leave it too; instead a button sits on the right of the message toolbar, just before the read-aloud button with a pair of rings for each account above the display line, in the same order (an account with only a balance gets none): the outer ring is 7 days and the inner ring 5 hours, with green arcs that shorten as usage rises, amber at 20% left, and a red track when used up, dashed where there is no such limit. A small dot appears when an account not shown runs low. If no accounts are selected or none has rings, a gauge icon still opens the full table. On phones the panel spans the screen from edge to edge. When creating a room or inviting a member, the front of the member card has a “Usage limits” row to help choose the software. A group with a 7-day window but no 5-hour one shows “5h no limit”.
55
55
  - **Token usage.** At the end of the answer card's “Process” row (or a “Usage” row of its own when there is none), the tokens that turn took are given; click it for the cache hit rate and the uncached input, cache reads, cache writes and output.
56
- - **Colours.** The bar and the limit rings are green while there is room, amber from 80% and red at 100%, since the next task would fail.
56
+ - **Colours.** The context bar is grey normally, amber from 80% used and red from 95%. For account limits, the table bar is grey and the mobile rings are green while there is room, amber at 20% left or less, and at 0% left the numeral and mobile ring track turn red (the table bar stays an empty track), since the next task would fail.
57
57
  - **Where the readings come from.** Limits are read only after a member finishes a turn, never on a timer in the background: Claude Code and Codex bring theirs back while they run, and Antigravity CLI and DeepSeek are read once after their member's turn (after a failed agy read, not again for 6 hours, because agy may open a sign-in page when the network drops). So a software not used for a while shows an older reading. When a Claude Code error says one model's own limit (such as Fable) is used up, the table gains a line for that model, shown as used up with the reset time the error gave, and it leaves by itself at that time; only members on that model show “Limit used up”. All of this comes from Claude Code's own error text, without reading its sign-in credentials, so that model's usage is not visible before it runs out. Claude Code does not report its context window; past 200K it is counted against 1M, otherwise only the tokens used are shown. Among model APIs, only DeepSeek's official address reports a balance; other APIs and app connections show no limits. The host can read the same values in the room state and use them when handing out work.
58
58
 
59
59
  ## Set the host, pause participation, invite back, or remove