ai_co_discuss 0.5.64 → 0.5.66

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
@@ -155,6 +155,19 @@ MEDIA_GENERATION_TIMEOUT = 960
155
155
  MEDIA_GENERATION_COMMANDS = ("image-generate", "video-generate")
156
156
  MEDIA_ROOM_COMMANDS = MEDIA_GENERATION_COMMANDS + ("media-job",)
157
157
  MEDIA_COMMANDS = MEDIA_ROOM_COMMANDS + ("video-settings", "video-check")
158
+ MEDIA_META_CHOICES = {
159
+ "mode": {"image", "video"}, "action": {"generate", "edit"},
160
+ "quality": {"auto", "low", "medium", "high", "xhigh", "max"},
161
+ "output_format": {"png", "jpeg", "webp", "gif", "svg", "mp4"},
162
+ "background": {"auto", "opaque", "transparent"}, "complexity": {"low", "medium", "high"},
163
+ "moderation": {"auto", "low"}, "input_fidelity": {"low", "high"},
164
+ }
165
+ MEDIA_META_INTEGERS = {"n": (1, 10), "seconds": (1, 2**53 - 1), "frame_count": (2, 16), "frame_duration_ms": (20, 2000)}
166
+ MEDIA_META_MODEL = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/@-]{0,127}")
167
+ MEDIA_META_SIZE = re.compile(r"(?:auto|[1-9][0-9]{0,4}x[1-9][0-9]{0,4})")
168
+ MEDIA_META_SECRET = re.compile(
169
+ r"(?i)(?:sk[-_]|gsk_|gh[pousr]_|akia|aiza|eyJ[a-z0-9_-]*\.|data:)|[a-f0-9]{32,}|[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}"
170
+ )
158
171
  MACHINE_COMMAND_POLL_SECONDS = 0.5
159
172
  # Ordering and filing a channel only rearrange the shared directory, like folder edits, so they need no room credential.
160
173
  DIRECTORY_OPERATIONS = ("move", "folder", "detach")
@@ -319,6 +332,7 @@ MESSAGE_QUERY = """SELECT messages.*, COALESCE(details.kind,'opinion') AS kind,
319
332
  COALESCE(details.submitted_by, CASE WHEN messages.source IN ('cli','api','url','user')
320
333
  THEN messages.author ELSE '用户' END) AS submitted_by,
321
334
  COALESCE(summaries.text,'') AS summary, COALESCE(summaries.author,'') AS summary_by, timing.elapsed_seconds,
335
+ media.message_id AS no_wake_id, media.media_meta,
322
336
  answered.execution_id, answered.request_message_id, answered.layout_after, answered.layout_at, COALESCE(withdrawn.kind,'') AS withdrawn,
323
337
  CASE WHEN messages.author='用户' THEN (
324
338
  SELECT CASE WHEN COUNT(parent_id)=COUNT(*) AND MIN(parent_id)=MAX(parent_id) THEN MIN(parent_id) END
@@ -357,6 +371,7 @@ COALESCE(NULLIF(relay.member,''),(SELECT name FROM room_members WHERE room_id=re
357
371
  CASE WHEN relay.message_id IS NOT NULL THEN (SELECT m.name FROM member_requests q JOIN room_members m ON m.id=q.member_id
358
372
  WHERE q.message_id=messages.id ORDER BY q.id LIMIT 1) END AS relay_to
359
373
  FROM messages LEFT JOIN message_details AS details ON details.message_id=messages.id
374
+ LEFT JOIN message_no_wake AS media ON media.message_id=messages.id
360
375
  LEFT JOIN moss_channel_out AS outbound ON outbound.message_id=messages.id
361
376
  LEFT JOIN (SELECT message_id,target_room_id,host,target_message_id,queued_id,interrupted,state FROM room_relay_sends) AS sent
362
377
  ON sent.message_id=messages.id
@@ -818,8 +833,11 @@ def init_database(database, seed=True):
818
833
  moss_results.migrate_delegations(connection)
819
834
  connection.executescript(SCHEMA + cloud_shares.SCHEMA)
820
835
  connection.execute("""CREATE TABLE IF NOT EXISTS message_no_wake (
821
- message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE
836
+ message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
837
+ media_meta TEXT
822
838
  )""")
839
+ if "media_meta" not in {row[1] for row in connection.execute("PRAGMA table_info(message_no_wake)")}:
840
+ connection.execute("ALTER TABLE message_no_wake ADD COLUMN media_meta TEXT")
823
841
  migrate_guest_cancel_reasons(connection)
824
842
  if "redirect_message_id" not in {row[1] for row in connection.execute("PRAGMA table_info(dispatch_withdrawals)")}:
825
843
  connection.execute("ALTER TABLE dispatch_withdrawals ADD COLUMN redirect_message_id INTEGER REFERENCES messages(id) ON DELETE SET NULL")
@@ -2452,8 +2470,9 @@ DESTRUCTION_LIST_LIMIT = 20
2452
2470
  def destruction_cloud_objects(connection, room_id):
2453
2471
  """Snapshot the room's object keys before cascades remove their records."""
2454
2472
  # 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
2473
+ rows = connection.execute(f"""SELECT id,object_name,size,
2474
+ CASE WHEN storage='object' THEN stored_at ELSE created_at END AS stored_at FROM attachments
2475
+ WHERE room_id=? AND (storage='object' AND object_name IS NOT NULL OR {PENDING_VIA_CLOUD_ATTACHMENT})
2457
2476
  UNION ALL
2458
2477
  SELECT id,object_name,size,stored_at FROM cloud_files
2459
2478
  WHERE room_id=? AND purpose!='keep' AND cleared_at IS NULL""", (room_id, room_id))
@@ -2894,6 +2913,9 @@ def record_api_event(database, record):
2894
2913
  data["execution_id"] = execution_id
2895
2914
  redacted_texts = {}
2896
2915
  payload_to_log = record["payload"]
2916
+ if isinstance(payload_to_log, dict) and "media_request" in payload_to_log:
2917
+ # Audit records include rejected writes. Never record the raw display metadata there.
2918
+ payload_to_log = {key: value for key, value in payload_to_log.items() if key != "media_request"}
2897
2919
  if record["path"].startswith("/executions/") and isinstance(payload_to_log, dict):
2898
2920
  payload_to_log = {key: value for key, value in payload_to_log.items() if key != "diagnostics"}
2899
2921
  if isinstance(payload_to_log, dict) and "host_strategy" in payload_to_log:
@@ -3471,6 +3493,8 @@ def renumbered_expected(expected, payload, previous):
3471
3493
  def message_with_attachments(connection, row):
3472
3494
  """Attach the published file list to an original message."""
3473
3495
  message = dict(row)
3496
+ message.pop("no_wake_id", None)
3497
+ media_meta = message.pop("media_meta", None)
3474
3498
  chain, origin, speak = (message.pop(key, None) for key in ("relay_chain", "relay_origin", "relay_speak"))
3475
3499
  if origin:
3476
3500
  message["relay_speak"] = bool(speak)
@@ -3496,6 +3520,8 @@ def message_with_attachments(connection, row):
3496
3520
  if message["withdrawn"] == "retracted":
3497
3521
  # The owner retracted it before anyone handled it: only the page that retracted it keeps the text.
3498
3522
  return {**message, "text": "", "summary": "", "suggestions": [], "attachments": []}
3523
+ if media_meta:
3524
+ message["media_request"] = json.loads(media_meta)
3499
3525
  message["texts"] = load_texts(connection, "message", message["id"])
3500
3526
  template = message["texts"].get("trigger", {}).get("template")
3501
3527
  if template in (STEWARD_PROACTIVE_TEMPLATE, STEWARD_SESSION_TEMPLATE, "steward_scheduled"):
@@ -3531,7 +3557,7 @@ def query_attachments(connection, room_id, params, token=""):
3531
3557
  where += " AND (message_id IS NULL OR message_id<=?)"
3532
3558
  values.append(cutoff)
3533
3559
  if "submission_id" in params:
3534
- where += " AND submission_id=?"
3560
+ where += " AND submission_id=? AND NOT (message_id IS NULL AND cleared_at IS NOT NULL)"
3535
3561
  values.append(submission_value(params["submission_id"]))
3536
3562
  else:
3537
3563
  where += " AND message_id IS NOT NULL"
@@ -3550,7 +3576,7 @@ def query_attachments(connection, room_id, params, token=""):
3550
3576
  def get_attachment(connection, room_id, identifier, params=None, token="", content=False):
3551
3577
  """Resolve a file only within the explicitly selected room, and within the caller's reading boundary."""
3552
3578
  row = connection.execute("SELECT * FROM attachments WHERE room_id=? AND id=?", (room_id, identifier)).fetchone()
3553
- if not row:
3579
+ if not row or (row["message_id"] is None and row["cleared_at"]):
3554
3580
  raise LookupError(Text('附件不存在'))
3555
3581
  cutoff = attachment_cutoff(connection, room_id, params or {}, token, content)
3556
3582
  if cutoff is not None and row["message_id"] is not None and row["message_id"] > cutoff:
@@ -3961,13 +3987,20 @@ def store_attachment(connection, database, room_id, metadata, body, *, token, wr
3961
3987
  temporary = Path(staging) / "content"
3962
3988
  with temporary.open("xb", buffering=0) as target:
3963
3989
  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}
3990
+ properties = staged_attachment_properties(temporary)
3991
+ info = {"size": length, "sha256": digest.hexdigest(), "content_type": properties["content_type"]}
3969
3992
  authorize_attachment_upload(connection, room_id, token, metadata)
3970
- return save_staged_attachment(connection, database, room_id, metadata, (temporary, info, width, height))
3993
+ return save_staged_attachment(connection, database, room_id, metadata,
3994
+ (temporary, info, properties["width"], properties["height"]))
3995
+
3996
+
3997
+ def staged_attachment_properties(path):
3998
+ """Report the type and image dimensions from staged bytes, not the upload declaration."""
3999
+ with path.open("rb") as incoming:
4000
+ content_type = attachment_content_type(incoming.read(max(128, SVG_SNIFF_BYTES)))
4001
+ incoming.seek(0)
4002
+ width, height = image_size(incoming) if content_type in SIZED_IMAGE_TYPES else (None, None)
4003
+ return {"content_type": content_type, "width": width, "height": height}
3971
4004
 
3972
4005
 
3973
4006
  def save_staged_attachment(connection, database, room_id, metadata, staged):
@@ -3979,7 +4012,8 @@ def save_staged_attachment(connection, database, room_id, metadata, staged):
3979
4012
  previous = connection.execute("SELECT * FROM attachments WHERE room_id=? AND submission_id=?",
3980
4013
  (room_id, metadata["submission_id"])).fetchone()
3981
4014
  if previous:
3982
- if any(previous[key] != value for key, value in expected.items()):
4015
+ if (previous["cleared_at"] or previous["storage"] is not None
4016
+ or any(previous[key] != value for key, value in expected.items())):
3983
4017
  raise FileExistsError(Text('这个附件提交编号已被其他文件使用'))
3984
4018
  return {"attachment": attachment_view(connection, previous), "duplicate": True}
3985
4019
  prune_unsent_attachments(connection, database, room_id)
@@ -4014,12 +4048,18 @@ def object_upload_metadata(payload, actor):
4014
4048
 
4015
4049
  # Imported records have no object in this account. Pending uploads already reserve their full declared size.
4016
4050
  LIVE_CLOUD_ATTACHMENTS = "storage='object' AND object_name IS NOT NULL AND cleared_at IS NULL"
4051
+ PENDING_VIA_CLOUD_ATTACHMENT = "storage IS NULL AND object_scope='via_cloud' AND object_name IS NOT NULL"
4052
+
4053
+
4054
+ def pending_via_cloud_attachment(row):
4055
+ """The local file is settled, but the provider has not confirmed deletion of its temporary copy."""
4056
+ return row["storage"] is None and row["object_scope"] == "via_cloud" and row["object_name"] is not None
4017
4057
 
4018
4058
 
4019
4059
  def object_storage_used_bytes(connection):
4020
4060
  """Count all live objects and upload reservations in this account's database."""
4021
4061
  return connection.execute(f"""SELECT
4022
- (SELECT COALESCE(SUM(size),0) FROM attachments WHERE {LIVE_CLOUD_ATTACHMENTS}) +
4062
+ (SELECT COALESCE(SUM(size),0) FROM attachments WHERE {LIVE_CLOUD_ATTACHMENTS} OR {PENDING_VIA_CLOUD_ATTACHMENT}) +
4023
4063
  (SELECT COALESCE(SUM(size),0) FROM cloud_files WHERE cleared_at IS NULL) +
4024
4064
  (SELECT COALESCE(SUM(json_extract(object.value,'$.size')),0) FROM room_destructions AS d,
4025
4065
  json_each(d.items) AS item, json_each(item.value,'$.objects') AS object WHERE d.status='cleaning')""").fetchone()[0]
@@ -4044,23 +4084,27 @@ def object_storage_limits(connection, database, attachment_limit):
4044
4084
  }
4045
4085
 
4046
4086
 
4047
- def reserve_object_attachment(connection, database, room_id, metadata, *, allow_small=False, require_via_cloud=None):
4087
+ def reserve_object_attachment(connection, database, room_id, metadata, *, require_via_cloud, allow_small=False):
4048
4088
  """Reserve a room-owned path; only the same submission can recover the reservation."""
4049
4089
  begin_write(connection)
4050
4090
  previous = connection.execute("SELECT * FROM attachments WHERE room_id=? AND submission_id=?",
4051
4091
  (room_id, metadata["submission_id"])).fetchone()
4052
4092
  if previous:
4093
+ if previous["object_scope"] == "via_cloud":
4094
+ require_via_cloud()
4095
+ if previous["storage"] is None:
4096
+ if previous["cleared_at"] or any(previous[key] != metadata[key] for key in ("file_name", "actor", "size")):
4097
+ raise FileExistsError(Text("这个附件提交编号已被其他文件使用"))
4098
+ return dict(previous)
4053
4099
  if (previous["storage"] != "object" or not previous["object_name"] or previous["cleared_at"]
4054
4100
  or any(previous[key] != value for key, value in metadata.items())):
4055
4101
  raise FileExistsError(Text("这个附件提交编号已被其他文件使用"))
4056
- if previous["object_scope"] == "via_cloud" and require_via_cloud:
4057
- require_via_cloud()
4058
4102
  return dict(previous)
4059
4103
  threshold = object_storage_threshold_mib(database, attachment_limit_mib(database))
4060
4104
  is_small = metadata["size"] <= threshold * BYTES_PER_MIB
4061
4105
  if is_small and not allow_small:
4062
4106
  raise ValueError(Text("仅超过 {limit} MiB 的附件使用对象存储", limit=threshold))
4063
- if is_small and require_via_cloud:
4107
+ if is_small:
4064
4108
  require_via_cloud()
4065
4109
  require_cloud_quota(connection, database, metadata["size"])
4066
4110
  identifier = uuid.uuid4().hex
@@ -4179,6 +4223,38 @@ def verify_object_size(client, record):
4179
4223
  raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致"))
4180
4224
 
4181
4225
 
4226
+ def stage_cloud_attachment(client, record, temporary, *, write_chunk):
4227
+ """Stream a signed object download to private staging and verify its length."""
4228
+ digest = hashlib.sha256()
4229
+ name, size = record["object_name"], record["size"]
4230
+ try:
4231
+ verify_object_size(client, record)
4232
+ # Resource-center clients sign via download_request; S3 signs the same GET locally.
4233
+ url = client.download(name)["url"]
4234
+ if not storage_url(url, https_only=True):
4235
+ raise StorageUnavailable()
4236
+ target = urlsplit(url)
4237
+ route = (target.path or "/") + ("?" + target.query if target.query else "")
4238
+ with closing(HTTPSConnection(target.hostname, target.port, timeout=CLOUD_COPY_TIMEOUT_SECONDS)) as remote:
4239
+ remote.request("GET", route)
4240
+ with remote.getresponse() as incoming, temporary.open("xb", buffering=0) as destination:
4241
+ if incoming.status in (404, 410):
4242
+ raise FileExistsError(Text("对象存储尚未收到文件"))
4243
+ if incoming.status != 200:
4244
+ raise StorageUnavailable()
4245
+ try:
4246
+ stream_upload(incoming, destination, size, digest, write_chunk=write_chunk)
4247
+ except ValueError:
4248
+ raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致")) from None
4249
+ if incoming.read(1):
4250
+ raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致"))
4251
+ except FileExistsError:
4252
+ raise
4253
+ except (HTTPException, OSError, ValueError):
4254
+ raise StorageUnavailable() from None
4255
+ return {**staged_attachment_properties(temporary), "sha256": digest.hexdigest()}
4256
+
4257
+
4182
4258
  def require_temporary_file_fresh(expires_at, cleared_at=None):
4183
4259
  """Report expiry separately from a deletion that happened before the deadline."""
4184
4260
  if not expires_at:
@@ -4366,7 +4442,7 @@ def queued_attachment_ids(connection, room_id):
4366
4442
  def unsent_attachment_rows(connection, room_id):
4367
4443
  """Files uploaded in this room that no message took and no queued message is waiting to send."""
4368
4444
  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,))
4445
+ 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
4446
  if row["id"] not in queued]
4371
4447
 
4372
4448
 
@@ -4408,10 +4484,36 @@ def delete_remote_attachments(database, rows):
4408
4484
  return sum(not delete_remote_attachment(database, row, client) for row in rows)
4409
4485
 
4410
4486
 
4487
+ def settle_via_cloud_attachment(connection, database, row, client):
4488
+ """Keep the cleanup key and quota until the provider confirms deletion."""
4489
+ if not delete_remote_attachment(database, row, client):
4490
+ return
4491
+ with connection:
4492
+ connection.execute(f"""UPDATE attachments SET object_name=NULL
4493
+ WHERE id=? AND room_id=? AND object_name=? AND {PENDING_VIA_CLOUD_ATTACHMENT}""",
4494
+ (row["id"], row["room_id"], row["object_name"]))
4495
+ connection.execute("""DELETE FROM attachments WHERE id=? AND room_id=? AND storage IS NULL
4496
+ AND object_scope='via_cloud' AND object_name IS NULL AND message_id IS NULL AND cleared_at IS NOT NULL""",
4497
+ (row["id"], row["room_id"]))
4498
+
4499
+
4500
+ def sweep_via_cloud_attachments(connection, database):
4501
+ """Retry temporary cloud copies left behind by an interrupted completion."""
4502
+ rows = connection.execute(f"SELECT id,room_id,object_name FROM attachments WHERE {PENDING_VIA_CLOUD_ATTACHMENT}").fetchall()
4503
+ if rows:
4504
+ client = configured_storage(database)
4505
+ for row in rows:
4506
+ settle_via_cloud_attachment(connection, database, row, client)
4507
+
4508
+
4411
4509
  def remove_attachment_files(connection, database, rows):
4412
- """Delete unsent uploads and their bytes; the caller commits."""
4510
+ """Delete unsent uploads and their bytes; retain an unsettled cloud cleanup key."""
4413
4511
  for row in rows:
4414
- connection.execute("DELETE FROM attachments WHERE id=? AND message_id IS NULL", (row["id"],))
4512
+ if pending_via_cloud_attachment(row):
4513
+ connection.execute("UPDATE attachments SET cleared_at=? WHERE id=? AND message_id IS NULL",
4514
+ (utc_iso_now(), row["id"]))
4515
+ else:
4516
+ connection.execute("DELETE FROM attachments WHERE id=? AND message_id IS NULL", (row["id"],))
4415
4517
  attachment_path(database, row).unlink(missing_ok=True)
4416
4518
  thumbnail_path(database, row).unlink(missing_ok=True)
4417
4519
 
@@ -4519,16 +4621,22 @@ def sweep_attachments(database, *, expire_objects=True):
4519
4621
  with closing(connect_db(database)) as connection:
4520
4622
  with connection:
4521
4623
  begin_write(connection)
4522
- rooms = connection.execute("SELECT DISTINCT room_id FROM attachments WHERE message_id IS NULL").fetchall()
4624
+ pending_expired = []
4625
+ rooms = connection.execute("SELECT DISTINCT room_id FROM attachments WHERE message_id IS NULL AND cleared_at IS NULL").fetchall()
4523
4626
  for room in rooms:
4524
4627
  for row in expired_unsent_attachments(connection, room[0]):
4525
4628
  if row["storage"] == "object" and row["object_name"] and not row["cleared_at"]:
4526
4629
  cloud_drafts.add(row["id"])
4630
+ elif pending_via_cloud_attachment(row):
4631
+ pending_expired.append(row)
4527
4632
  else:
4528
4633
  expired.add(row["id"])
4529
4634
  connection.executemany("DELETE FROM attachments WHERE id=? AND message_id IS NULL", ((key,) for key in expired))
4635
+ if pending_expired:
4636
+ remove_attachment_files(connection, database, pending_expired)
4530
4637
  sweep_unsent_object_attachments(connection, database, cloud_drafts)
4531
4638
  if expire_objects:
4639
+ sweep_via_cloud_attachments(connection, database)
4532
4640
  sweep_cloud_file_drafts(connection, database)
4533
4641
  sweep_cloud_transfers(connection, database)
4534
4642
  cloud_drive.sweep_trash(connection, database)
@@ -4539,7 +4647,8 @@ def sweep_attachments(database, *, expire_objects=True):
4539
4647
  # Uploads acquire this same write lock before creating their file. Hold it from the ID snapshot through unlink.
4540
4648
  with connection:
4541
4649
  begin_write(connection)
4542
- registered = {os.path.normcase(row[0]) for row in connection.execute("SELECT id FROM attachments")}
4650
+ registered = {os.path.normcase(row[0]) for row in connection.execute(
4651
+ "SELECT id FROM attachments WHERE NOT (message_id IS NULL AND cleared_at IS NOT NULL)")}
4543
4652
  registered.update("cloud-" + row[0] for row in connection.execute(
4544
4653
  "SELECT id FROM cloud_files WHERE thumbnail_type IS NOT NULL AND cleared_at IS NULL"))
4545
4654
  cutoff = time.time() - ORPHAN_ATTACHMENT_GRACE_SECONDS
@@ -4572,7 +4681,9 @@ def discard_attachment(connection, database, room_id, identifier, token):
4572
4681
  raise FileExistsError(Text('附件已随消息发出或正在排队,不能撤下'))
4573
4682
  remove_attachment_files(connection, database, [row])
4574
4683
  connection.commit()
4575
- if row["storage"] == "object" and row["object_name"]:
4684
+ if pending_via_cloud_attachment(row):
4685
+ settle_via_cloud_attachment(connection, database, row, configured_storage(database))
4686
+ elif row["storage"] == "object" and row["object_name"]:
4576
4687
  delete_remote_attachments(database, [row])
4577
4688
  return {"discarded": identifier}
4578
4689
 
@@ -4632,6 +4743,8 @@ def check_message_attachments(connection, room_id, actor, identifiers):
4632
4743
  attachment = get_attachment(connection, room_id, identifier)
4633
4744
  if attachment["actor"] != actor or attachment["message_id"] is not None:
4634
4745
  raise FileExistsError(Text('附件已用于其他消息,或不属于本次实际提交者'))
4746
+ if attachment["cleared_at"]:
4747
+ raise LookupError(Text("附件不存在"))
4635
4748
  if attachment.get("storage") == "object" and not attachment["stored"]:
4636
4749
  raise ValueError(Text("附件尚未完成上传"))
4637
4750
 
@@ -4765,9 +4878,31 @@ def wake_group_window(connection, room_id, payload):
4765
4878
  return {"request_id": request_id, "message_id": message_id, "duplicate": False}
4766
4879
 
4767
4880
 
4881
+ def clean_media_request(raw):
4882
+ """Keep only bounded, flat display values, without copying arbitrary request fields."""
4883
+ if not isinstance(raw, dict):
4884
+ return None
4885
+ cleaned = {}
4886
+ for key, choices in MEDIA_META_CHOICES.items():
4887
+ value = raw.get(key)
4888
+ if isinstance(value, str) and value in choices:
4889
+ cleaned[key] = value
4890
+ for key, (minimum, maximum) in MEDIA_META_INTEGERS.items():
4891
+ value = raw.get(key)
4892
+ if type(value) is int and minimum <= value <= maximum:
4893
+ cleaned[key] = value
4894
+ for key, pattern in (("model", MEDIA_META_MODEL), ("size", MEDIA_META_SIZE)):
4895
+ value = raw.get(key)
4896
+ if isinstance(value, str) and len(value) <= 128 and pattern.fullmatch(value):
4897
+ if key != "model" or not MEDIA_META_SECRET.match(value):
4898
+ cleaned[key] = value
4899
+ return json.dumps(cleaned, separators=(",", ":"), sort_keys=True) if cleaned else None
4900
+
4901
+
4768
4902
  def append_free_message(connection, room, payload, actor):
4769
4903
  """Append a free-room message: the owner's creates requests, a member's completes its execution."""
4770
4904
  no_wake = payload.get("no_wake") is True
4905
+ media_meta = clean_media_request(payload.get("media_request")) if no_wake else None
4771
4906
  awaiting_user = awaiting_user_flag(payload, actor)
4772
4907
  silent = actor != "用户" and payload.get("execution_id") is not None and room.get("system_kind") == "steward_group"
4773
4908
  if payload.get("kind") == "moderation":
@@ -4798,13 +4933,13 @@ def append_free_message(connection, room, payload, actor):
4798
4933
  identifiers = attachment_ids(payload)
4799
4934
  previous = connection.execute(f"{MESSAGE_QUERY} WHERE room_id=? AND submission_id=?", (room_id, room_id, submission_id)).fetchone()
4800
4935
  if previous:
4936
+ same_media = no_wake == bool(previous["no_wake_id"]) and media_meta == previous["media_meta"]
4801
4937
  previous = message_with_attachments(connection, previous)
4802
4938
  if ((previous.get("relay_room") or None) != (payload.get("relay") or {}).get("room_id")
4803
4939
  or any(previous[key] != renumbered_expected(expected, payload, previous)[key] for key in ("author", "text", "reply_to", "kind", "submitted_by", "summary", "summary_by"))
4804
4940
  or [item["id"] for item in previous["attachments"]] != identifiers
4805
4941
  or silent != previous.get("silent", False)
4806
- or (actor == "用户" and no_wake != bool(connection.execute(
4807
- "SELECT 1 FROM message_no_wake WHERE message_id=?", (previous["id"],)).fetchone()))
4942
+ or (actor == "用户" and not same_media)
4808
4943
  or awaiting_user != bool(connection.execute("SELECT 1 FROM room_waits WHERE message_id=?", (previous["id"],)).fetchone())):
4809
4944
  raise FileExistsError(Text('这个提交编号已被另一条内容使用,请为新发言生成新编号'))
4810
4945
  check_review_retry(connection, room_id, previous["id"], payload)
@@ -4839,7 +4974,7 @@ def append_free_message(connection, room, payload, actor):
4839
4974
  connection.execute("INSERT INTO message_details (message_id,kind,submitted_by) VALUES (?,?,?)",
4840
4975
  (cursor.lastrowid, "chat", submitted_by))
4841
4976
  if no_wake:
4842
- connection.execute("INSERT INTO message_no_wake(message_id) VALUES(?)", (cursor.lastrowid,))
4977
+ connection.execute("INSERT INTO message_no_wake(message_id,media_meta) VALUES(?,?)", (cursor.lastrowid, media_meta))
4843
4978
  if silent:
4844
4979
  connection.execute("INSERT INTO moss_silent_answers(message_id) VALUES(?)", (cursor.lastrowid,))
4845
4980
  connection.execute("INSERT INTO message_summaries (message_id,text,author) VALUES (?,?,?)",
@@ -6689,7 +6824,9 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6689
6824
  return False
6690
6825
  self.close_connection = True
6691
6826
  # Sent directly, not through respond(): a refused caller leaves nothing in any room's event log.
6692
- message = Text("这个工作台只接受经入口的访问;本机管理员请从任务栏图标或桌面“共议”打开")
6827
+ parts = parsed.path.strip("/").split("/")
6828
+ message = (self.media_owner_required() if self.media_command_post(parts, method) or self.no_wake_post(parts, method, read=True)
6829
+ else Text("这个工作台只接受经入口的访问;本机管理员请从任务栏图标或桌面“共议”打开"))
6693
6830
  self.send_payload(403, "application/json", json.dumps(error_body(message), ensure_ascii=False).encode("utf-8"))
6694
6831
  return True
6695
6832
 
@@ -6729,6 +6866,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6729
6866
  def dispatch_routes(self, method, parsed, params, parts, text_mode):
6730
6867
  """Route one request and map validation, permission and lookup errors to their status codes."""
6731
6868
  open_database = self.request_database(method, parts)
6869
+ body_drained = False
6732
6870
  try:
6733
6871
  if self.headers.get("X-Discussion-Token") or self.headers.get(ACTING_MEMBER_HEADER) or guest_path(parts):
6734
6872
  with open_database() as guard_connection:
@@ -6748,7 +6886,11 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6748
6886
  guard_external_route(open_database, self.headers, parts)
6749
6887
  except PermissionError:
6750
6888
  # 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))
6889
+ if self.no_wake_post(parts, method, read=True):
6890
+ raise self.media_owner_required() from None
6891
+ if not self.message_post_route(parts, method):
6892
+ self.rfile.read(min(int(self.headers.get("Content-Length") or 0), MAX_BODY_BYTES))
6893
+ body_drained = True
6752
6894
  self.close_connection = True
6753
6895
  raise
6754
6896
  self.bridged = self.relay_bridge(parts)
@@ -6784,6 +6926,9 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6784
6926
  except PermissionError as error:
6785
6927
  if getattr(error, "details", {}).get("code", "").startswith("guest_"):
6786
6928
  self.close_connection = True
6929
+ if self.media_command_post(parts, method) or self.no_wake_post(parts, method, read=not body_drained):
6930
+ self.close_connection = True
6931
+ error = self.media_owner_required()
6787
6932
  return self.respond(self.request_error(error, parts), 403)
6788
6933
  except (ValueError, TypeError) as error:
6789
6934
  return self.respond(self.plain_error(error) if text_mode else self.request_error(error, parts), 400,
@@ -6801,6 +6946,33 @@ class DiscussionHandler(BaseHTTPRequestHandler):
6801
6946
  logging.exception("Request failed")
6802
6947
  return self.respond(error_body(Text("服务器内部错误")), 500)
6803
6948
 
6949
+ @staticmethod
6950
+ def media_owner_required():
6951
+ """Use one machine-readable refusal across media commands and silent publication."""
6952
+ return BoundaryError(Text("需要本房间的控制凭据;没有凭据只能阅读"), code="media_owner_required")
6953
+
6954
+ @staticmethod
6955
+ def media_command_post(parts, method):
6956
+ return method == "POST" and len(parts) == 3 and parts[:2] == ["api", "local"] and parts[2] in MEDIA_ROOM_COMMANDS
6957
+
6958
+ @staticmethod
6959
+ def message_post_route(parts, method):
6960
+ return method == "POST" and (
6961
+ len(parts) == 4 and parts[:2] == ["api", "rooms"] and parts[3] == "messages"
6962
+ or guest_path(parts) and parts[5:] == ["messages"])
6963
+
6964
+ def no_wake_post(self, parts, method, *, read=False):
6965
+ """Recognize a silent publish even when an earlier guest or member guard denied it."""
6966
+ if not self.message_post_route(parts, method):
6967
+ return False
6968
+ payload = self.payload_cache
6969
+ if payload is None and read:
6970
+ try:
6971
+ payload = self.read_payload()
6972
+ except ValueError:
6973
+ return False
6974
+ return bool(payload and payload.get("no_wake") is True)
6975
+
6804
6976
  @staticmethod
6805
6977
  def group_window_room(parts):
6806
6978
  """Recognize the room in JSON, text, and external room paths."""
@@ -7417,19 +7589,37 @@ class DiscussionHandler(BaseHTTPRequestHandler):
7417
7589
 
7418
7590
  def handle_local_media_command(self, command, site):
7419
7591
  """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():
7592
+ if self.read_only_request() or self.headers.get(ACTING_MEMBER_HEADER):
7421
7593
  raise PermissionError(Text('需要管理员登录'))
7422
7594
  if self.headers.get_content_type() != "application/json":
7423
7595
  raise ValueError(Text('本机操作须使用 application/json'))
7424
7596
  payload = self.read_payload()
7425
7597
  if command in MEDIA_ROOM_COMMANDS:
7426
- payload.pop("access_file", None)
7427
- payload.pop("_moss_owner", None)
7598
+ if "access_file" in payload or "_moss_owner" in payload:
7599
+ raise self.media_owner_required()
7428
7600
  payload.update(site=site, entry="web")
7429
- if not payload.get("token") and not self.bridge_origin:
7601
+ header = self.headers.get("X-Discussion-Token", "")
7602
+ token = payload.get("token", "")
7603
+ if not isinstance(token, str):
7604
+ raise self.media_owner_required()
7605
+ token = token or header
7606
+ if self.bridge_origin:
7607
+ if not token or (header and header != token):
7608
+ raise self.media_owner_required()
7609
+ else:
7610
+ room_id = payload.get("room_id", "")
7611
+ if not isinstance(room_id, str) or not room_id:
7612
+ raise self.media_owner_required()
7430
7613
  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", "")
7614
+ if header:
7615
+ require_owner(connection, room_id, header)
7616
+ if not token:
7617
+ self.admin_as_owner(connection, room_id)
7618
+ token = self.headers.get("X-Discussion-Token", "")
7619
+ require_owner(connection, room_id, token if isinstance(token, str) else "")
7620
+ payload["token"] = token
7621
+ elif self.entry_member_request():
7622
+ raise PermissionError(Text('需要管理员登录'))
7433
7623
  return self.run_local_command(command, payload, remote=bool(self.bridge_origin))
7434
7624
 
7435
7625
  def issue_media_ticket(self, payload):
@@ -8615,7 +8805,14 @@ class DiscussionHandler(BaseHTTPRequestHandler):
8615
8805
  elif method == "POST" and parts[3:] == ["limits"] and current_session(connection, room_id, active_only=True):
8616
8806
  pass
8617
8807
  elif method == "POST":
8618
- free_actor = authorize_free_write(connection, room_id, token, parts[3] if len(parts) > 3 else "", self.read_payload())
8808
+ payload = self.read_payload()
8809
+ if self.no_wake_post(parts, method):
8810
+ if self.headers.get(ACTING_MEMBER_HEADER) or "access_file" in payload:
8811
+ raise self.media_owner_required()
8812
+ if payload.get("token", "") != "":
8813
+ require_owner(connection, room_id, payload["token"] if isinstance(payload["token"], str) else "")
8814
+ require_owner(connection, room_id, token)
8815
+ free_actor = authorize_free_write(connection, room_id, token, parts[3] if len(parts) > 3 else "", payload)
8619
8816
  if (parts[3:] == ["backup"] and method == "GET") or (len(parts) == 4 and parts[3] in DIRECTORY_OPERATIONS and method == "POST"):
8620
8817
  self.require_entry_owner(connection, room_id, token)
8621
8818
  if parts[3:] == ["backup"] and method == "GET":
@@ -8691,8 +8888,6 @@ class DiscussionHandler(BaseHTTPRequestHandler):
8691
8888
  if method == "GET":
8692
8889
  return self.respond(query_messages(connection, room_id, params, token, search_database=self.server.database))
8693
8890
  payload = self.read_payload()
8694
- if payload.get("no_wake") is True and self.headers.get(ACTING_MEMBER_HEADER):
8695
- raise PermissionError(Text("需要本房间的控制凭据"))
8696
8891
  if free_actor == "用户":
8697
8892
  room = require_room(connection, room_id)
8698
8893
  if room["system_kind"] == moss_window_messages.GROUP_KIND:
@@ -9135,49 +9330,65 @@ class DiscussionHandler(BaseHTTPRequestHandler):
9135
9330
  raise PermissionError(Text("附件上传者须与凭据身份一致"))
9136
9331
  require_room(connection, room_id)
9137
9332
  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
9333
+ limit = attachment_limit_mib(database)
9334
+ threshold = object_storage_threshold_mib(database, limit) * BYTES_PER_MIB
9335
+ via_cloud = payload.get("via_cloud") is True and metadata["size"] <= threshold
9336
+ allow_small = via_cloud and metadata["size"] <= limit * BYTES_PER_MIB
9141
9337
  require_via_cloud = lambda: self.require_attachment_outbound_session(connection)
9142
- if allow_small:
9338
+ if via_cloud:
9143
9339
  require_via_cloud()
9144
- client = configured_storage(self.server.database)
9145
- if not client:
9340
+ client = configured_storage(database)
9341
+ if not client and not connection.execute("""SELECT 1 FROM attachments
9342
+ WHERE room_id=? AND submission_id=? AND object_scope='via_cloud' AND storage IS NULL""",
9343
+ (room_id, metadata["submission_id"])).fetchone():
9146
9344
  raise FileExistsError(Text("对象存储未配置"))
9147
9345
  record = reserve_object_attachment(connection, database, room_id, metadata,
9148
9346
  allow_small=allow_small, require_via_cloud=require_via_cloud)
9149
9347
  connection.commit()
9150
9348
  try:
9151
- upload = None if record["stored_at"] else client.upload(record["object_name"], record["size"], record["content_type"])
9349
+ upload = None if record["storage"] != "object" or record["stored_at"] else client.upload(
9350
+ record["object_name"], record["size"], record["content_type"])
9152
9351
  except StorageUnavailable as error:
9153
9352
  failure = storage_http_error(error)
9154
9353
  failure.details = {"code": "object_reserved", "attachment_id": record["id"]}
9155
9354
  raise failure from None
9156
9355
  return self.respond({"attachment": attachment_view(connection, record), "upload": upload})
9157
9356
 
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."""
9357
+ def object_upload_for_completion(self, connection, room_id, identifier):
9358
+ """Recheck uploader, trusted session and draft state under the write lock."""
9359
+ begin_write(connection)
9360
+ record = connection.execute("SELECT * FROM attachments WHERE room_id=? AND id=?", (room_id, identifier)).fetchone()
9361
+ if record is None or (record["storage"] != "object" and record["object_scope"] != "via_cloud"):
9362
+ raise LookupError(Text("附件不存在"))
9160
9363
  token = self.headers.get("X-Discussion-Token", "")
9161
- record = get_object_attachment(connection, room_id, identifier)
9162
9364
  actor = authorize_free_write(connection, room_id, token, "attachments", {"author": record["actor"]})
9163
9365
  if (actor if isinstance(actor, str) else actor["name"]) != record["actor"]:
9164
9366
  raise PermissionError(Text("只能确认自己上传的附件"))
9165
- if record["cleared_at"] or not record["object_name"]:
9367
+ if record["object_scope"] == "via_cloud":
9368
+ self.require_attachment_outbound_session(connection)
9369
+ if record["message_id"] is None and record["cleared_at"]:
9370
+ raise LookupError(Text("附件不存在"))
9371
+ if record["cleared_at"] or (record["storage"] == "object" and not record["object_name"]):
9166
9372
  raise AdminError(Text("文件已不在对象存储中"), 410)
9167
- if record["stored_at"]:
9373
+ return record
9374
+
9375
+ def complete_object_upload(self, connection, room_id, identifier):
9376
+ """Verify one reservation, returning a local receipt for a temporary cloud upload."""
9377
+ record = self.object_upload_for_completion(connection, room_id, identifier)
9378
+ via_cloud = record["object_scope"] == "via_cloud"
9379
+ if record["storage"] is None or (record["stored_at"] and not via_cloud):
9168
9380
  return self.respond({"attachment": attachment_view(connection, record)})
9169
9381
  connection.commit()
9170
9382
  client = configured_storage(self.server.database)
9171
9383
  if not client:
9172
9384
  raise AdminError(Text("对象存储暂不可用"), 503)
9385
+ if via_cloud:
9386
+ return self.complete_via_cloud_upload(connection, record, client)
9173
9387
  try:
9174
- size = client.file_size(record["object_name"])
9175
- except ObjectMissing:
9176
- raise FileExistsError(Text("对象存储尚未收到文件")) from None
9388
+ verify_object_size(client, record)
9177
9389
  except StorageUnavailable as error:
9178
9390
  raise storage_http_error(error) from None
9179
- if size != record["size"]:
9180
- raise FileExistsError(Text("对象存储中的文件大小与上传声明不一致"))
9391
+ token = self.headers.get("X-Discussion-Token", "")
9181
9392
  authorize_free_write(connection, room_id, token, "attachments", {"author": record["actor"]})
9182
9393
  connection.execute("UPDATE attachments SET stored_at=? WHERE room_id=? AND id=? AND cleared_at IS NULL AND stored_at IS NULL",
9183
9394
  (utc_now(), room_id, identifier))
@@ -9185,6 +9396,56 @@ class DiscussionHandler(BaseHTTPRequestHandler):
9185
9396
  connection.commit()
9186
9397
  return self.respond({"attachment": attachment_view(connection, result)})
9187
9398
 
9399
+ def complete_via_cloud_upload(self, connection, record, client):
9400
+ """Stage an admitted local copy, then clean up its durable cloud reservation."""
9401
+ database = self.server.database
9402
+ size = record["size"]
9403
+ with self.attachment_upload_reservation(size, size > attachment_limit_mib(database) * BYTES_PER_MIB) as writer:
9404
+ if writer is None:
9405
+ raise AdminError(self.attachment_budget_error(), 413)
9406
+ updated = self.install_via_cloud_attachment(connection, record, client, writer)
9407
+ if updated is not None:
9408
+ try:
9409
+ generate_attachment_thumbnail(connection, database, updated)
9410
+ finally:
9411
+ settle_via_cloud_attachment(connection, database, record, client)
9412
+ return self.respond({"attachment": get_attachment(connection, record["room_id"], record["id"])})
9413
+
9414
+ def install_via_cloud_attachment(self, connection, record, client, write_chunk):
9415
+ """Stream outside the SQLite write lock, then publish only while the draft still matches."""
9416
+ database = self.server.database
9417
+ room_id, identifier = record["room_id"], record["id"]
9418
+ path = attachment_path(database, record)
9419
+ path.parent.mkdir(parents=True, exist_ok=True)
9420
+ with tempfile.TemporaryDirectory(dir=path.parent, prefix=".upload-") as directory:
9421
+ temporary = Path(directory) / "content"
9422
+ try:
9423
+ properties = stage_cloud_attachment(client, record, temporary, write_chunk=write_chunk)
9424
+ except (FileExistsError, StorageUnavailable) as error:
9425
+ # A concurrent completion can delete the remote object before this download reaches it.
9426
+ current = self.object_upload_for_completion(connection, room_id, identifier)
9427
+ if current["storage"] is None:
9428
+ return None
9429
+ if isinstance(error, StorageUnavailable):
9430
+ raise storage_http_error(error) from None
9431
+ raise
9432
+ current = self.object_upload_for_completion(connection, room_id, identifier)
9433
+ if current["storage"] is None:
9434
+ return None
9435
+ if current["object_name"] != record["object_name"] or current["size"] != record["size"]:
9436
+ raise FileExistsError(Text("这个附件提交编号已被其他文件使用"))
9437
+ temporary.replace(path)
9438
+ try:
9439
+ connection.execute("""UPDATE attachments SET storage=NULL, stored_at=NULL,
9440
+ sha256=:sha256, content_type=:content_type, width=:width, height=:height
9441
+ WHERE room_id=:room_id AND id=:id AND storage='object' AND cleared_at IS NULL""",
9442
+ {**properties, "room_id": room_id, "id": identifier})
9443
+ connection.commit()
9444
+ except Exception:
9445
+ path.unlink(missing_ok=True)
9446
+ raise
9447
+ return {**dict(current), **properties}
9448
+
9188
9449
  def import_attachment(self, connection, room_id, attachment_id):
9189
9450
  """Store the original bytes of an attachment recorded by an import; an existing file is kept."""
9190
9451
  if self.headers.get_content_type() == "application/json":
@@ -9493,6 +9754,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
9493
9754
 
9494
9755
  def handle_guest_projection(self, connection, parts, params, method):
9495
9756
  """Commit a guest write before notifying room subscribers."""
9757
+ if self.message_post_route(parts, method) and self.read_payload().get("no_wake") is True:
9758
+ raise self.media_owner_required()
9496
9759
  data = guest_projection(connection, parts, method, self.headers.get("X-Discussion-Token", ""), params, self.read_payload)
9497
9760
  connection.commit()
9498
9761
  if method == "POST":