nextcloud-client 0.211.0__py3-none-any.whl

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.
@@ -0,0 +1,930 @@
1
+ import logging
2
+ import re
3
+ from datetime import datetime, timezone
4
+ from typing import Any, Dict, List, Optional
5
+
6
+ from httpx2 import HTTPStatusError, RequestError
7
+
8
+ from .base import BaseNextcloudClient
9
+ from .models.deck import (
10
+ DeckACL,
11
+ DeckAttachment,
12
+ DeckBoard,
13
+ DeckCard,
14
+ DeckComment,
15
+ DeckConfig,
16
+ DeckLabel,
17
+ DeckSession,
18
+ DeckStack,
19
+ )
20
+ from .ocs import OCS_REQUEST_HEADERS
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ def _normalize_duedate(duedate: Optional[str]) -> Optional[str]:
26
+ """Convert an offset-aware due date to the UTC ``Z`` form Deck parses reliably.
27
+
28
+ Deck's PHP date handling is unreliable with non-UTC offsets, so an
29
+ offset-aware value is converted to the same instant in UTC. Naive and
30
+ unparseable strings are passed through untouched — this normalises, it does
31
+ not validate, and rejecting a format Deck might accept would be worse than
32
+ forwarding it.
33
+
34
+ Also used for ``startdate``, which Deck parses the same way.
35
+
36
+ An empty string maps to ``None`` so "clear the due date" is expressible;
37
+ previously it went on the wire as ``""``, where Deck's behaviour is undefined.
38
+
39
+ ``strftime`` rather than ``isoformat()``: the latter yields ``+00:00`` and
40
+ keeps microseconds, neither of which is what Deck stores.
41
+ """
42
+ if duedate is None:
43
+ return None
44
+ if not duedate.strip():
45
+ return None
46
+ try:
47
+ parsed = datetime.fromisoformat(duedate.replace("Z", "+00:00"))
48
+ except ValueError:
49
+ logger.debug("Passing through unparseable duedate %r unchanged", duedate)
50
+ return duedate
51
+ if parsed.tzinfo is None:
52
+ return duedate
53
+ return parsed.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
54
+
55
+
56
+ def _isoformat(value: Optional[datetime]) -> Optional[str]:
57
+ return value.isoformat() if value else None
58
+
59
+
60
+ def _normalize_color(color: Optional[str]) -> Optional[str]:
61
+ """Strip a leading ``#``: Deck stores card colors as bare hex (``FF0000``)
62
+ and its frontend prepends the ``#`` itself.
63
+
64
+ An empty string maps to ``None`` so "clear the color" stores NULL; Deck
65
+ 1.18.x would otherwise store ``""`` verbatim. Anything else must be 6-digit
66
+ hex: Deck does not validate card colors and would store ``"red"`` as-is.
67
+ """
68
+ if not color:
69
+ return None
70
+ bare = color.removeprefix("#")
71
+ if not re.fullmatch(r"[0-9A-Fa-f]{6}", bare):
72
+ raise ValueError(f"color must be 6-digit hex like 'FF0000', got {color!r}")
73
+ return bare
74
+
75
+
76
+ class DeckClient(BaseNextcloudClient):
77
+ """Client for Nextcloud Deck app operations."""
78
+
79
+ app_name = "deck"
80
+
81
+ # Own copy -- see the note in GroupsClient. Used by the /ocs/v2.php
82
+ # endpoints below (config, comments, sessions), NOT by the Deck REST API;
83
+ # see _get_deck_headers for why that one differs.
84
+ _OCS_HEADERS: dict[str, str] = dict(OCS_REQUEST_HEADERS)
85
+
86
+ def _get_deck_headers(
87
+ self, additional_headers: Optional[Dict[str, str]] = None
88
+ ) -> Dict[str, str]:
89
+ """Get standard headers required for Deck's own REST API.
90
+
91
+ Deliberately NOT ``_OCS_HEADERS``. These calls go to
92
+ ``/index.php/apps/deck/api/v1.0/...`` -- Deck's app REST API, not an
93
+ ``/ocs/v2.php`` route -- and they send ``Content-Type`` where the OCS
94
+ constant sends ``Accept``. That difference is left alone on purpose:
95
+ the endpoints work as-is, and swapping the header would be a
96
+ behaviour change riding along in a de-duplication pass. If it is ever
97
+ revisited, it is a change to Deck's REST calls only. ``OCS-APIRequest``
98
+ comes from the shared httpx2 client, as for every other call.
99
+ """
100
+ headers = {"Content-Type": "application/json"}
101
+ if additional_headers:
102
+ headers.update(additional_headers)
103
+ return headers
104
+
105
+ # Boards
106
+ async def get_boards(
107
+ self, details: bool = False, if_modified_since: Optional[str] = None
108
+ ) -> List[DeckBoard]:
109
+ additional_headers = {}
110
+ if if_modified_since:
111
+ additional_headers["If-Modified-Since"] = if_modified_since
112
+ headers = self._get_deck_headers(additional_headers)
113
+ params = {"details": "true"} if details else {}
114
+ response = await self._make_request(
115
+ "GET", "/apps/deck/api/v1.0/boards", headers=headers, params=params
116
+ )
117
+ return [DeckBoard(**board) for board in response.json()]
118
+
119
+ async def create_board(self, title: str, color: str) -> DeckBoard:
120
+ json_data = {"title": title, "color": color}
121
+ headers = self._get_deck_headers()
122
+ response = await self._make_request(
123
+ "POST", "/apps/deck/api/v1.0/boards", json=json_data, headers=headers
124
+ )
125
+ return DeckBoard(**response.json())
126
+
127
+ async def get_board(self, board_id: int) -> DeckBoard:
128
+ headers = self._get_deck_headers()
129
+ response = await self._make_request(
130
+ "GET", f"/apps/deck/api/v1.0/boards/{board_id}", headers=headers
131
+ )
132
+ return DeckBoard(**response.json())
133
+
134
+ async def update_board(
135
+ self,
136
+ board_id: int,
137
+ title: Optional[str] = None,
138
+ color: Optional[str] = None,
139
+ archived: Optional[bool] = None,
140
+ ) -> None:
141
+ json_data = {}
142
+ if title is not None:
143
+ json_data["title"] = title
144
+ if color is not None:
145
+ json_data["color"] = color
146
+ if archived is not None:
147
+ json_data["archived"] = archived
148
+ headers = self._get_deck_headers()
149
+ await self._make_request(
150
+ "PUT",
151
+ f"/apps/deck/api/v1.0/boards/{board_id}",
152
+ json=json_data,
153
+ headers=headers,
154
+ )
155
+
156
+ async def delete_board(self, board_id: int) -> None:
157
+ headers = self._get_deck_headers()
158
+ await self._make_request(
159
+ "DELETE", f"/apps/deck/api/v1.0/boards/{board_id}", headers=headers
160
+ )
161
+
162
+ async def undo_delete_board(self, board_id: int) -> None:
163
+ headers = self._get_deck_headers()
164
+ await self._make_request(
165
+ "POST",
166
+ f"/apps/deck/api/v1.0/boards/{board_id}/undo_delete",
167
+ headers=headers,
168
+ )
169
+
170
+ async def add_acl_rule(
171
+ self,
172
+ board_id: int,
173
+ type: int,
174
+ participant: str,
175
+ permission_edit: bool,
176
+ permission_share: bool,
177
+ permission_manage: bool,
178
+ ) -> DeckACL:
179
+ json_data = {
180
+ "type": type,
181
+ "participant": participant,
182
+ "permissionEdit": permission_edit,
183
+ "permissionShare": permission_share,
184
+ "permissionManage": permission_manage,
185
+ }
186
+ headers = self._get_deck_headers()
187
+ response = await self._make_request(
188
+ "POST",
189
+ f"/apps/deck/api/v1.0/boards/{board_id}/acl",
190
+ json=json_data,
191
+ headers=headers,
192
+ )
193
+ return DeckACL(**response.json())
194
+
195
+ async def update_acl_rule(
196
+ self,
197
+ board_id: int,
198
+ acl_id: int,
199
+ permission_edit: Optional[bool] = None,
200
+ permission_share: Optional[bool] = None,
201
+ permission_manage: Optional[bool] = None,
202
+ ) -> None:
203
+ json_data = {}
204
+ if permission_edit is not None:
205
+ json_data["permissionEdit"] = permission_edit
206
+ if permission_share is not None:
207
+ json_data["permissionShare"] = permission_share
208
+ if permission_manage is not None:
209
+ json_data["permissionManage"] = permission_manage
210
+ headers = self._get_deck_headers()
211
+ await self._make_request(
212
+ "PUT",
213
+ f"/apps/deck/api/v1.0/boards/{board_id}/acl/{acl_id}",
214
+ json=json_data,
215
+ headers=headers,
216
+ )
217
+
218
+ async def delete_acl_rule(self, board_id: int, acl_id: int) -> None:
219
+ headers = self._get_deck_headers()
220
+ await self._make_request(
221
+ "DELETE",
222
+ f"/apps/deck/api/v1.0/boards/{board_id}/acl/{acl_id}",
223
+ headers=headers,
224
+ )
225
+
226
+ async def clone_board(
227
+ self,
228
+ board_id: int,
229
+ with_cards: bool = False,
230
+ with_assignments: bool = False,
231
+ with_labels: bool = False,
232
+ with_due_date: bool = False,
233
+ move_cards_to_left_stack: bool = False,
234
+ restore_archived_cards: bool = False,
235
+ ) -> DeckBoard:
236
+ json_data = {
237
+ "withCards": with_cards,
238
+ "withAssignments": with_assignments,
239
+ "withLabels": with_labels,
240
+ "withDueDate": with_due_date,
241
+ "moveCardsToLeftStack": move_cards_to_left_stack,
242
+ "restoreArchivedCards": restore_archived_cards,
243
+ }
244
+ response = await self._make_request(
245
+ "POST", f"/apps/deck/api/v1.0/boards/{board_id}/clone", json=json_data
246
+ )
247
+ return DeckBoard(**response.json())
248
+
249
+ # Stacks
250
+ async def get_stacks(
251
+ self, board_id: int, if_modified_since: Optional[str] = None
252
+ ) -> List[DeckStack]:
253
+ additional_headers = {}
254
+ if if_modified_since:
255
+ additional_headers["If-Modified-Since"] = if_modified_since
256
+ headers = self._get_deck_headers(additional_headers)
257
+ response = await self._make_request(
258
+ "GET", f"/apps/deck/api/v1.0/boards/{board_id}/stacks", headers=headers
259
+ )
260
+ return [DeckStack(**stack) for stack in response.json()]
261
+
262
+ async def get_archived_stacks(self, board_id: int) -> List[DeckStack]:
263
+ response = await self._make_request(
264
+ "GET", f"/apps/deck/api/v1.0/boards/{board_id}/stacks/archived"
265
+ )
266
+ return [DeckStack(**stack) for stack in response.json()]
267
+
268
+ async def get_stack(self, board_id: int, stack_id: int) -> DeckStack:
269
+ response = await self._make_request(
270
+ "GET", f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}"
271
+ )
272
+ return DeckStack(**response.json())
273
+
274
+ async def create_stack(self, board_id: int, title: str, order: int) -> DeckStack:
275
+ json_data = {"title": title, "order": order}
276
+ headers = self._get_deck_headers()
277
+ response = await self._make_request(
278
+ "POST",
279
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks",
280
+ json=json_data,
281
+ headers=headers,
282
+ )
283
+ return DeckStack(**response.json())
284
+
285
+ async def update_stack(
286
+ self,
287
+ board_id: int,
288
+ stack_id: int,
289
+ title: Optional[str] = None,
290
+ order: Optional[int] = None,
291
+ ) -> None:
292
+ json_data = {}
293
+ if title is not None:
294
+ json_data["title"] = title
295
+ if order is not None:
296
+ json_data["order"] = order
297
+ headers = self._get_deck_headers()
298
+ await self._make_request(
299
+ "PUT",
300
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}",
301
+ json=json_data,
302
+ headers=headers,
303
+ )
304
+
305
+ async def delete_stack(self, board_id: int, stack_id: int) -> None:
306
+ await self._make_request(
307
+ "DELETE", f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}"
308
+ )
309
+
310
+ # Cards
311
+ async def get_card(self, board_id: int, stack_id: int, card_id: int) -> DeckCard:
312
+ headers = self._get_deck_headers()
313
+ # v1.1 (Deck >= 1.3.0), not v1.0, for the sake of ``attachments``: on
314
+ # v1.0 CardService::find strips every attachment that is not a legacy
315
+ # ``deck_file``, so a card whose files were attached from the Files app
316
+ # comes back with attachmentCount > 0 and an empty attachments array.
317
+ response = await self._make_request(
318
+ "GET",
319
+ f"/apps/deck/api/v1.1/boards/{board_id}/stacks/{stack_id}/cards/{card_id}",
320
+ headers=headers,
321
+ )
322
+ return DeckCard(**response.json())
323
+
324
+ async def create_card(
325
+ self,
326
+ board_id: int,
327
+ stack_id: int,
328
+ title: str,
329
+ type: str = "plain",
330
+ order: int = 999,
331
+ description: Optional[str] = None,
332
+ duedate: Optional[str] = None,
333
+ startdate: Optional[str] = None,
334
+ color: Optional[str] = None,
335
+ ) -> DeckCard:
336
+ json_data = {
337
+ "title": title,
338
+ "type": type,
339
+ "order": order,
340
+ }
341
+ if description is not None:
342
+ json_data["description"] = description
343
+ if duedate is not None:
344
+ json_data["duedate"] = _normalize_duedate(duedate)
345
+ if startdate is not None:
346
+ json_data["startdate"] = _normalize_duedate(startdate)
347
+ if color:
348
+ json_data["color"] = _normalize_color(color)
349
+ headers = self._get_deck_headers()
350
+ response = await self._make_request(
351
+ "POST",
352
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards",
353
+ json=json_data,
354
+ headers=headers,
355
+ )
356
+ return DeckCard(**response.json())
357
+
358
+ @staticmethod
359
+ def _card_update_payload(
360
+ current: DeckCard,
361
+ *,
362
+ title: Optional[str] = None,
363
+ description: Optional[str] = None,
364
+ type: Optional[str] = None,
365
+ owner: Optional[str] = None,
366
+ order: Optional[int] = None,
367
+ duedate: Optional[str] = None,
368
+ archived: Optional[bool] = None,
369
+ done: Optional[str] = None,
370
+ startdate: Optional[str] = None,
371
+ color: Optional[str] = None,
372
+ ) -> dict[str, Any]:
373
+ """Build the full-replacement body for a card update.
374
+
375
+ Deck's card PUT replaces the whole card, so every field the caller did
376
+ *not* supply has to be carried over from ``current``. ``order``,
377
+ ``duedate`` and ``archived`` were previously only sent when explicitly
378
+ passed, so a title-only update reset the card's order to 0 and cleared its
379
+ due date. ``move_card_to_board`` already sent order and duedate
380
+ unconditionally — the two payload builders simply disagreed.
381
+
382
+ Every fallback tests ``is not None``, never truthiness: ``order=0`` is a
383
+ legitimate first position and ``archived=False`` is meaningful, so
384
+ ``order or current.order`` would silently discard both.
385
+
386
+ ``done`` is deliberately not carried over. ``move_card_to_board``'s
387
+ docstring records that the internal route does not accept a ``done``
388
+ value, so the two routes genuinely differ here; preserving it blind could
389
+ re-stamp a done timestamp. Left as an explicit omission pending an
390
+ integration test that shows whether this route clears it.
391
+
392
+ ``startdate`` and ``color`` (Deck >= 1.18) are carried over like
393
+ ``duedate``: the 1.18.x ``CardService::update`` nulls both when the key
394
+ is omitted. Older Deck ignores both keys.
395
+ """
396
+ return {
397
+ # Title is required by the API
398
+ "title": title if title is not None else current.title,
399
+ # Type is required by the API
400
+ "type": type if type is not None else current.type,
401
+ # Owner is required by the API (model validator ensures it's a string)
402
+ "owner": owner if owner is not None else current.owner,
403
+ # Description must be sent to preserve it (PUT clears omitted fields)
404
+ "description": description
405
+ if description is not None
406
+ else (current.description or ""),
407
+ "order": order if order is not None else current.order,
408
+ "duedate": _normalize_duedate(
409
+ duedate if duedate is not None else _isoformat(current.duedate)
410
+ ),
411
+ "startdate": _normalize_duedate(
412
+ startdate if startdate is not None else _isoformat(current.startdate)
413
+ ),
414
+ "archived": archived if archived is not None else current.archived,
415
+ **({"done": done} if done is not None else {}),
416
+ # current.color is sent back as Deck stored it, unvalidated.
417
+ "color": _normalize_color(color) if color is not None else current.color,
418
+ }
419
+
420
+ async def update_card(
421
+ self,
422
+ board_id: int,
423
+ stack_id: int,
424
+ card_id: int,
425
+ title: Optional[str] = None,
426
+ description: Optional[str] = None,
427
+ type: Optional[str] = None,
428
+ owner: Optional[str] = None,
429
+ order: Optional[int] = None,
430
+ duedate: Optional[str] = None,
431
+ archived: Optional[bool] = None,
432
+ done: Optional[str] = None,
433
+ startdate: Optional[str] = None,
434
+ color: Optional[str] = None,
435
+ ) -> None:
436
+ # Deck PUT API is a full replacement - all required fields must be sent.
437
+ # Fetch current card to preserve values for fields not being updated.
438
+ current_card = await self.get_card(board_id, stack_id, card_id)
439
+
440
+ json_data = self._card_update_payload(
441
+ current_card,
442
+ title=title,
443
+ description=description,
444
+ type=type,
445
+ owner=owner,
446
+ order=order,
447
+ duedate=duedate,
448
+ archived=archived,
449
+ done=done,
450
+ startdate=startdate,
451
+ color=color,
452
+ )
453
+ headers = self._get_deck_headers()
454
+ await self._make_request(
455
+ "PUT",
456
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}",
457
+ json=json_data,
458
+ headers=headers,
459
+ )
460
+
461
+ async def delete_card(self, board_id: int, stack_id: int, card_id: int) -> None:
462
+ headers = self._get_deck_headers()
463
+ await self._make_request(
464
+ "DELETE",
465
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}",
466
+ headers=headers,
467
+ )
468
+
469
+ async def archive_card(self, board_id: int, stack_id: int, card_id: int) -> None:
470
+ await self._make_request(
471
+ "PUT",
472
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/archive",
473
+ )
474
+
475
+ async def unarchive_card(self, board_id: int, stack_id: int, card_id: int) -> None:
476
+ await self._make_request(
477
+ "PUT",
478
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/unarchive",
479
+ )
480
+
481
+ async def assign_label_to_card(
482
+ self, board_id: int, stack_id: int, card_id: int, label_id: int
483
+ ) -> None:
484
+ json_data = {"labelId": label_id}
485
+ await self._make_request(
486
+ "PUT",
487
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/assignLabel",
488
+ json=json_data,
489
+ )
490
+
491
+ async def remove_label_from_card(
492
+ self, board_id: int, stack_id: int, card_id: int, label_id: int
493
+ ) -> None:
494
+ json_data = {"labelId": label_id}
495
+ await self._make_request(
496
+ "PUT",
497
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/removeLabel",
498
+ json=json_data,
499
+ )
500
+
501
+ async def assign_user_to_card(
502
+ self, board_id: int, stack_id: int, card_id: int, user_id: str
503
+ ) -> None:
504
+ json_data = {"userId": user_id}
505
+ await self._make_request(
506
+ "PUT",
507
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/assignUser",
508
+ json=json_data,
509
+ )
510
+
511
+ async def unassign_user_from_card(
512
+ self, board_id: int, stack_id: int, card_id: int, user_id: str
513
+ ) -> None:
514
+ json_data = {"userId": user_id}
515
+ await self._make_request(
516
+ "PUT",
517
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/unassignUser",
518
+ json=json_data,
519
+ )
520
+
521
+ async def assign_dependent_card(
522
+ self, board_id: int, stack_id: int, card_id: int, dependent_card_id: int
523
+ ) -> DeckCard:
524
+ """Record that ``card_id`` depends on ``dependent_card_id``.
525
+
526
+ Mirrors Deck's "Add dependent card" card action. The dependency is
527
+ directional: it is stored on ``card_id`` and surfaces in that card's
528
+ ``dependentCards`` list. The caller needs read access to the dependent
529
+ card. Returns the updated (depending) card.
530
+ """
531
+ headers = self._get_deck_headers()
532
+ response = await self._make_request(
533
+ "POST",
534
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/dependentCards/{dependent_card_id}",
535
+ headers=headers,
536
+ )
537
+ return DeckCard(**response.json())
538
+
539
+ async def remove_dependent_card(
540
+ self, board_id: int, stack_id: int, card_id: int, dependent_card_id: int
541
+ ) -> DeckCard:
542
+ """Remove the dependency of ``card_id`` on ``dependent_card_id``.
543
+
544
+ Returns the updated (depending) card.
545
+ """
546
+ headers = self._get_deck_headers()
547
+ response = await self._make_request(
548
+ "DELETE",
549
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/dependentCards/{dependent_card_id}",
550
+ headers=headers,
551
+ )
552
+ return DeckCard(**response.json())
553
+
554
+ async def reorder_card(
555
+ self,
556
+ board_id: int,
557
+ stack_id: int,
558
+ card_id: int,
559
+ order: int,
560
+ target_stack_id: int,
561
+ ) -> None:
562
+ # Reorder is intentionally restricted to moves *within* a single board.
563
+ # Deck's reorder route (CardService::reorder) only reassigns stackId and
564
+ # does NOT remap board-scoped labels, so handing it a stack on another
565
+ # board silently orphans the card's labels (they keep the old boardId).
566
+ # Cross-board moves must go through move_card_to_board(), which uses the
567
+ # card-update route (CardService::update) and remaps labels by title.
568
+ # A same-stack reorder can't cross a board boundary, so skip the lookup.
569
+ if target_stack_id != stack_id:
570
+ board_stack_ids = {stack.id for stack in await self.get_stacks(board_id)}
571
+ if target_stack_id not in board_stack_ids:
572
+ raise ValueError(
573
+ f"target_stack_id {target_stack_id} is not a stack on board "
574
+ f"{board_id}; reorder_card only moves cards within a board. "
575
+ "Use move_card_to_board() to move a card to another board."
576
+ )
577
+
578
+ # Use the non-API route /cards/{cardId}/reorder which correctly reads
579
+ # stackId from the body. The API route /api/.../stacks/{stackId}/cards/...
580
+ # has a parameter conflict where URL stackId overrides body stackId.
581
+ # See: https://github.com/cbcoutinho/nextcloud-mcp-server/issues/469
582
+ json_data = {"order": order, "stackId": target_stack_id}
583
+ headers = self._get_deck_headers()
584
+ await self._make_request(
585
+ "PUT",
586
+ f"/apps/deck/cards/{card_id}/reorder",
587
+ json=json_data,
588
+ headers=headers,
589
+ )
590
+
591
+ async def move_card_to_board(
592
+ self,
593
+ source_board_id: int,
594
+ source_stack_id: int,
595
+ card_id: int,
596
+ target_board_id: int,
597
+ target_stack_id: int,
598
+ order: int = 0,
599
+ ) -> DeckCard:
600
+ """Move a card to a stack on a different (or the same) board.
601
+
602
+ Unlike :meth:`reorder_card`, this goes through the card-update route
603
+ (``CardService::update``). When the destination stack is on a different
604
+ board, Deck remaps the card's board-scoped labels by title — assigning
605
+ the same-titled label on the destination board, or cloning it there
606
+ when the user has board-manage permission — instead of leaving orphaned
607
+ labels behind. This mirrors Deck's native "Move/copy card" action. Card
608
+ identity (id, comments, attachments), ``archived`` state, the start and due
609
+ dates and ``assignedUsers`` are preserved — the move does not re-validate
610
+ assignees against the destination board, so an assigned user without
611
+ access to the target board stays assigned but may not be able to act on
612
+ the card.
613
+
614
+ The internal ``/apps/deck/cards/{cardId}`` route is used: it reads the
615
+ target ``stackId`` from the body (the board/stack-scoped API route
616
+ instead binds ``stackId`` from the URL — issue #469 — and 404s for a
617
+ card that isn't already on that board). The controller derives ``owner``
618
+ from the session user and does not accept a ``done`` value, so a "done"
619
+ card is re-marked done after the move; Deck stamps the current time
620
+ there, so the original done timestamp is not preserved (a limitation of
621
+ what this route exposes).
622
+
623
+ The done re-mark is best-effort: the move itself has already committed
624
+ by then, so if that follow-up fails the card is left on the target
625
+ board without its done state (logged as a warning) rather than raising
626
+ and implying the move failed.
627
+ """
628
+ # Validate the destination so target_board_id is load-bearing: the move
629
+ # itself is driven by stackId, so without this a stack on another board
630
+ # would relocate the card while the reported board is wrong.
631
+ target_stack_ids = {
632
+ stack.id for stack in await self.get_stacks(target_board_id)
633
+ }
634
+ if target_stack_id not in target_stack_ids:
635
+ raise ValueError(
636
+ f"target_stack_id {target_stack_id} is not a stack on target "
637
+ f"board {target_board_id}."
638
+ )
639
+
640
+ current = await self.get_card(source_board_id, source_stack_id, card_id)
641
+
642
+ json_data: dict[str, Any] = {
643
+ # The route placeholder is {cardId} but the controller reads the
644
+ # card id from the body, so it must be sent explicitly.
645
+ "id": card_id,
646
+ "title": current.title,
647
+ "type": current.type,
648
+ "stackId": target_stack_id,
649
+ "order": order,
650
+ "description": current.description or "",
651
+ # Sent explicitly as None when absent (update_card omits the key);
652
+ # both are equivalent here — the route reads duedate and there's
653
+ # nothing to clear on a card that never had one.
654
+ "duedate": _normalize_duedate(_isoformat(current.duedate)),
655
+ # Deck 1.18.x nulls startdate and color when the key is omitted.
656
+ "startdate": _normalize_duedate(_isoformat(current.startdate)),
657
+ "color": current.color,
658
+ # 0 keeps the card live (a positive value would soft-delete it)
659
+ "deletedAt": current.deletedAt or 0,
660
+ }
661
+ headers = self._get_deck_headers()
662
+ response = await self._make_request(
663
+ "PUT",
664
+ f"/apps/deck/cards/{card_id}",
665
+ json=json_data,
666
+ headers=headers,
667
+ )
668
+ moved = DeckCard(**response.json())
669
+
670
+ # This route clears `done`; restore the done *state* if the card had it
671
+ # (the timestamp is refreshed to now — see the docstring note). The move
672
+ # has already committed, so this is best-effort: on failure, warn with
673
+ # the card's new location rather than raising as if the move failed.
674
+ if current.done is not None:
675
+ try:
676
+ await self._make_request(
677
+ "PUT", f"/apps/deck/cards/{card_id}/done", headers=headers
678
+ )
679
+ moved = await self.get_card(target_board_id, target_stack_id, card_id)
680
+ except (HTTPStatusError, RequestError) as e:
681
+ logger.warning(
682
+ "Card %s moved to board %s stack %s but restoring done "
683
+ "state failed: %s",
684
+ card_id,
685
+ target_board_id,
686
+ target_stack_id,
687
+ e,
688
+ )
689
+
690
+ return moved
691
+
692
+ # Labels
693
+ async def get_label(self, board_id: int, label_id: int) -> DeckLabel:
694
+ headers = self._get_deck_headers()
695
+ response = await self._make_request(
696
+ "GET",
697
+ f"/apps/deck/api/v1.0/boards/{board_id}/labels/{label_id}",
698
+ headers=headers,
699
+ )
700
+ return DeckLabel(**response.json())
701
+
702
+ async def create_label(self, board_id: int, title: str, color: str) -> DeckLabel:
703
+ json_data = {"title": title, "color": color}
704
+ headers = self._get_deck_headers()
705
+ response = await self._make_request(
706
+ "POST",
707
+ f"/apps/deck/api/v1.0/boards/{board_id}/labels",
708
+ json=json_data,
709
+ headers=headers,
710
+ )
711
+ return DeckLabel(**response.json())
712
+
713
+ async def update_label(
714
+ self,
715
+ board_id: int,
716
+ label_id: int,
717
+ title: Optional[str] = None,
718
+ color: Optional[str] = None,
719
+ ) -> None:
720
+ json_data = {}
721
+ if title is not None:
722
+ json_data["title"] = title
723
+ if color is not None:
724
+ json_data["color"] = color
725
+ await self._make_request(
726
+ "PUT",
727
+ f"/apps/deck/api/v1.0/boards/{board_id}/labels/{label_id}",
728
+ json=json_data,
729
+ )
730
+
731
+ async def delete_label(self, board_id: int, label_id: int) -> None:
732
+ await self._make_request(
733
+ "DELETE", f"/apps/deck/api/v1.0/boards/{board_id}/labels/{label_id}"
734
+ )
735
+
736
+ # Attachments
737
+ async def get_attachments(
738
+ self, board_id: int, stack_id: int, card_id: int
739
+ ) -> List[DeckAttachment]:
740
+ # v1.1 for the same reason as get_card: v1.0 returns only deck_file.
741
+ response = await self._make_request(
742
+ "GET",
743
+ f"/apps/deck/api/v1.1/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/attachments",
744
+ )
745
+ return [DeckAttachment(**attachment) for attachment in response.json()]
746
+
747
+ async def get_attachment_file(
748
+ self,
749
+ board_id: int,
750
+ stack_id: int,
751
+ card_id: int,
752
+ attachment_id: int,
753
+ file_type: str = "deck_file",
754
+ ) -> Any:
755
+ # Every route that addresses one attachment by id resolves that id
756
+ # against ``type`` (server-side default deck_file), so a Files-share
757
+ # attachment is only found with type=file. Applies equally to
758
+ # update/delete/restore below.
759
+ # This endpoint returns the raw file, so we return the raw response content
760
+ response = await self._make_request(
761
+ "GET",
762
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/attachments/{attachment_id}",
763
+ params={"type": file_type},
764
+ )
765
+ return response.content
766
+
767
+ async def upload_attachment(
768
+ self,
769
+ board_id: int,
770
+ stack_id: int,
771
+ card_id: int,
772
+ file_data: bytes,
773
+ file_type: str = "file",
774
+ ) -> DeckAttachment:
775
+ # The API expects binary data directly, not JSON
776
+ headers = {"Content-Type": "application/octet-stream"}
777
+ params = {"type": file_type}
778
+ response = await self._make_request(
779
+ "POST",
780
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/attachments",
781
+ headers=headers,
782
+ params=params,
783
+ data=file_data,
784
+ )
785
+ return DeckAttachment(**response.json())
786
+
787
+ async def update_attachment(
788
+ self,
789
+ board_id: int,
790
+ stack_id: int,
791
+ card_id: int,
792
+ attachment_id: int,
793
+ file_data: bytes,
794
+ file_type: str = "deck_file",
795
+ ) -> DeckAttachment:
796
+ headers = {"Content-Type": "application/octet-stream"}
797
+ params = {"type": file_type}
798
+ response = await self._make_request(
799
+ "PUT",
800
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/attachments/{attachment_id}",
801
+ headers=headers,
802
+ params=params,
803
+ data=file_data,
804
+ )
805
+ return DeckAttachment(**response.json())
806
+
807
+ async def delete_attachment(
808
+ self,
809
+ board_id: int,
810
+ stack_id: int,
811
+ card_id: int,
812
+ attachment_id: int,
813
+ file_type: str = "deck_file",
814
+ ) -> None:
815
+ # See get_attachment_file on why ``type`` has to be sent.
816
+ await self._make_request(
817
+ "DELETE",
818
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/attachments/{attachment_id}",
819
+ params={"type": file_type},
820
+ )
821
+
822
+ async def restore_attachment(
823
+ self,
824
+ board_id: int,
825
+ stack_id: int,
826
+ card_id: int,
827
+ attachment_id: int,
828
+ file_type: str = "deck_file",
829
+ ) -> None:
830
+ await self._make_request(
831
+ "PUT",
832
+ f"/apps/deck/api/v1.0/boards/{board_id}/stacks/{stack_id}/cards/{card_id}/attachments/{attachment_id}/restore",
833
+ params={"type": file_type},
834
+ )
835
+
836
+ # OCS API Endpoints (Config, Comments, Sessions)
837
+ async def get_config(self) -> DeckConfig:
838
+ headers = self._OCS_HEADERS
839
+ response = await self._make_request(
840
+ "GET", "/ocs/v2.php/apps/deck/api/v1.0/config", headers=headers
841
+ )
842
+ return DeckConfig(**response.json()["ocs"]["data"])
843
+
844
+ async def set_config_value(
845
+ self, key: str, value: Any, board_id: Optional[int] = None
846
+ ) -> Any:
847
+ path = f"/ocs/v2.php/apps/deck/api/v1.0/config/{key}"
848
+ if board_id:
849
+ path = f"/ocs/v2.php/apps/deck/api/v1.0/config/board:{board_id}:{key}"
850
+ json_data = {"value": value}
851
+ response = await self._make_request(
852
+ "POST",
853
+ path,
854
+ json=json_data,
855
+ headers=self._OCS_HEADERS,
856
+ )
857
+ return response.json()["ocs"]["data"]
858
+
859
+ async def get_comments(
860
+ self, card_id: int, limit: int = 20, offset: int = 0
861
+ ) -> List[DeckComment]:
862
+ params = {"limit": limit, "offset": offset}
863
+ response = await self._make_request(
864
+ "GET",
865
+ f"/ocs/v2.php/apps/deck/api/v1.0/cards/{card_id}/comments",
866
+ params=params,
867
+ headers=self._OCS_HEADERS,
868
+ )
869
+ return [DeckComment(**comment) for comment in response.json()["ocs"]["data"]]
870
+
871
+ async def create_comment(
872
+ self, card_id: int, message: str, parent_id: Optional[int] = None
873
+ ) -> DeckComment:
874
+ json_data = {"message": message}
875
+ if parent_id is not None:
876
+ json_data["parentId"] = parent_id
877
+ response = await self._make_request(
878
+ "POST",
879
+ f"/ocs/v2.php/apps/deck/api/v1.0/cards/{card_id}/comments",
880
+ json=json_data,
881
+ headers=self._OCS_HEADERS,
882
+ )
883
+ return DeckComment(**response.json()["ocs"]["data"])
884
+
885
+ async def update_comment(
886
+ self, card_id: int, comment_id: int, message: str
887
+ ) -> DeckComment:
888
+ json_data = {"message": message}
889
+ response = await self._make_request(
890
+ "PUT",
891
+ f"/ocs/v2.php/apps/deck/api/v1.0/cards/{card_id}/comments/{comment_id}",
892
+ json=json_data,
893
+ headers=self._OCS_HEADERS,
894
+ )
895
+ return DeckComment(**response.json()["ocs"]["data"])
896
+
897
+ async def delete_comment(self, card_id: int, comment_id: int) -> None:
898
+ await self._make_request(
899
+ "DELETE",
900
+ f"/ocs/v2.php/apps/deck/api/v1.0/cards/{card_id}/comments/{comment_id}",
901
+ headers=self._OCS_HEADERS,
902
+ )
903
+
904
+ async def create_session(self, board_id: int) -> DeckSession:
905
+ json_data = {"boardId": board_id}
906
+ response = await self._make_request(
907
+ "PUT",
908
+ "/ocs/v2.php/apps/deck/api/v1.0/session/create",
909
+ json=json_data,
910
+ headers=self._OCS_HEADERS,
911
+ )
912
+ return DeckSession(**response.json()["ocs"]["data"])
913
+
914
+ async def sync_session(self, board_id: int, token: str) -> None:
915
+ json_data = {"boardId": board_id, "token": token}
916
+ await self._make_request(
917
+ "POST",
918
+ "/ocs/v2.php/apps/deck/api/v1.0/session/sync",
919
+ json=json_data,
920
+ headers=self._OCS_HEADERS,
921
+ )
922
+
923
+ async def close_session(self, board_id: int, token: str) -> None:
924
+ json_data = {"boardId": board_id, "token": token}
925
+ await self._make_request(
926
+ "POST",
927
+ "/ocs/v2.php/apps/deck/api/v1.0/session/close",
928
+ json=json_data,
929
+ headers=self._OCS_HEADERS,
930
+ )