Skip to content

Synchronous Client

This page contains the API reference for the synchronous Seedr client.

seedrcc.client.Seedr

Bases: BaseClient

Synchronous client for interacting with the Seedr API.

Example
from seedrcc import Seedr, Token

# Load a previously saved token from a JSON string
token_string = '{"access_token": "...", "refresh_token": "..."}'
token = Token.from_json(token_string)

# Initialize the client and make a request
with Seedr(token=token) as client:
    settings = client.get_settings()
    print(f"Hello, {settings.account.username}")
Source code in seedrcc/client.py
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
class Seedr(BaseClient):
    """Synchronous client for interacting with the Seedr API.

    Example:
        ```python
        from seedrcc import Seedr, Token

        # Load a previously saved token from a JSON string
        token_string = '{"access_token": "...", "refresh_token": "..."}'
        token = Token.from_json(token_string)

        # Initialize the client and make a request
        with Seedr(token=token) as client:
            settings = client.get_settings()
            print(f"Hello, {settings.account.username}")
        ```
    """

    _client: httpx.Client
    _manages_client_lifecycle: bool

    def __init__(
        self,
        token: Token,
        on_token_refresh: Optional[Callable[[Token], None]] = None,
        httpx_client: Optional[httpx.Client] = None,
        timeout: float = 30.0,
        proxy: Optional[Dict[str, str]] = None,
        **httpx_kwargs: Any,
    ) -> None:
        """Initializes the synchronous client with an existing token.

        Args:
            token: An authenticated `Token` object.
            on_token_refresh: An optional callback function that is called with the new
                `Token` object when the session is refreshed.
            httpx_client: An optional, pre-configured `httpx.Client` instance.
            timeout: The timeout for network requests in seconds.
            proxy: An optional dictionary of proxy to use for requests.
            **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
                These are ignored if `httpx_client` is provided.
        """
        super().__init__(token, on_token_refresh)
        if httpx_client is not None:
            self._client = httpx_client
            self._manages_client_lifecycle = False
        else:
            httpx_kwargs.setdefault("timeout", timeout)
            httpx_kwargs.setdefault("proxy", proxy)
            self._client = httpx.Client(**httpx_kwargs)
            self._manages_client_lifecycle = True

    @property
    def token(self) -> Token:
        return super().token

    @staticmethod
    def get_device_code() -> models.DeviceCode:
        """
        Gets the device and user codes required for authorization.

        This is the first step in the device authentication flow.

        Returns:
            A `DeviceCode` object containing the codes needed for the next step.

        Example:
            ```python
            from seedrcc import Seedr

            codes = Seedr.get_device_code()
            print(f"Go to {codes.verification_url} and enter {codes.user_code}")
            ```
        """
        params = _request_models.GetDeviceCodeParams()
        with httpx.Client() as client:
            response = Seedr._make_http_request(client, "get", _constants.DEVICE_CODE_URL, params=params.to_dict())

            if not response.is_success:
                raise APIError("Failed to get device code.", response=response)

            try:
                response_data = response.json()
            except json.JSONDecodeError as e:
                raise APIError("Invalid JSON response from API.", response=None) from e
            return models.DeviceCode.from_dict(response_data)

    @classmethod
    def from_password(
        cls: Type["Seedr"],
        username: str,
        password: str,
        on_token_refresh: Optional[Callable[[Token], None]] = None,
        httpx_client: Optional[httpx.Client] = None,
        timeout: float = 30.0,
        proxy: Optional[Dict[str, str]] = None,
        **httpx_kwargs: Any,
    ) -> "Seedr":
        """
        Creates a new client by authenticating with a username and password.

        Args:
            username: The user's Seedr username (email).
            password: The user's Seedr password.
            on_token_refresh: A callback function that is called with the new
                Token object when the session is refreshed.
            httpx_client: An optional, pre-configured `httpx.Client` instance.
            timeout: The timeout for network requests in seconds.
            proxy: A dictionary of proxy to use for requests.
            **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
                These are ignored if `httpx_client` is provided.

        Returns:
            An initialized `Seedr` client instance.

        Example:
            ```python
            client = Seedr.from_password("your_email@example.com", "your_password")
            ```
        """

        def auth_callable(client: httpx.Client) -> Dict[str, Any]:
            """Prepare and execute the authentication request."""
            payload = _request_models.PasswordLoginPayload(username=username, password=password)
            return cls._authenticate_and_get_token_data(
                client,
                "post",
                _constants.TOKEN_URL,
                data=payload.to_dict(),
            )

        return cls._initialize_client(
            auth_callable,
            lambda r: {},
            on_token_refresh,
            httpx_client,
            timeout=timeout,
            proxy=proxy,
            **httpx_kwargs,
        )

    @classmethod
    def from_device_code(
        cls: Type["Seedr"],
        device_code: str,
        on_token_refresh: Optional[Callable[[Token], None]] = None,
        httpx_client: Optional[httpx.Client] = None,
        timeout: float = 30.0,
        proxy: Optional[Dict[str, str]] = None,
        **httpx_kwargs: Any,
    ) -> "Seedr":
        """
        Creates a new client by authorizing with a device code.

        This is the second step in the device authentication flow, after getting the
        codes from `Seedr.get_device_code()`.

        Args:
            device_code: The device code obtained from `get_device_code()`.
            on_token_refresh: A callback function that is called with the new
                Token object when the session is refreshed.
            httpx_client: An optional, pre-configured `httpx.Client` instance.
            timeout: The timeout for network requests in seconds.
            proxy: A dictionary of proxy to use for requests.
            **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
                These are ignored if `httpx_client` is provided.

        Returns:
            An initialized `Seedr` client instance.

        Example:
            ```python
            client = Seedr.from_device_code("your_device_code")
            ```
        """

        def auth_callable(client: httpx.Client) -> Dict[str, Any]:
            """Prepare and execute the device authorization request."""
            params = _request_models.DeviceCodeAuthParams(device_code=device_code)
            return cls._authenticate_and_get_token_data(
                client,
                "get",
                _constants.DEVICE_AUTHORIZE_URL,
                params=params.to_dict(),
            )

        return cls._initialize_client(
            auth_callable,
            lambda r: {"device_code": device_code},
            on_token_refresh,
            httpx_client,
            timeout=timeout,
            proxy=proxy,
            **httpx_kwargs,
        )

    @classmethod
    def from_refresh_token(
        cls: Type["Seedr"],
        refresh_token: str,
        on_token_refresh: Optional[Callable[[Token], None]] = None,
        httpx_client: Optional[httpx.Client] = None,
        timeout: float = 30.0,
        proxy: Optional[Dict[str, str]] = None,
        **httpx_kwargs: Any,
    ) -> "Seedr":
        """
        Creates a new client by using an existing refresh token.

        Args:
            refresh_token: A valid refresh token.
            on_token_refresh: A callback function that is called with the new
                Token object when the session is refreshed.
            httpx_client: An optional, pre-configured `httpx.Client` instance.
            timeout: The timeout for network requests in seconds.
            proxy: A dictionary of proxy to use for requests.
            **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
                These are ignored if `httpx_client` is provided.

        Returns:
            An initialized `Seedr` client instance.

        Example:
            ```python
            client = Seedr.from_refresh_token("your_refresh_token")
            ```
        """

        def auth_callable(client: httpx.Client) -> Dict[str, Any]:
            """Prepare and execute the token refresh request."""
            payload = _request_models.RefreshTokenPayload(refresh_token=refresh_token)
            return cls._authenticate_and_get_token_data(
                client,
                "post",
                _constants.TOKEN_URL,
                data=payload.to_dict(),
            )

        return cls._initialize_client(
            auth_callable,
            lambda r: {"refresh_token": refresh_token},
            on_token_refresh,
            httpx_client,
            timeout=timeout,
            proxy=proxy,
            **httpx_kwargs,
        )

    def refresh_token(self) -> models.RefreshTokenResult:
        """
        Manually refreshes the access token.

        This is useful if you want to proactively manage the token's lifecycle
        instead of waiting for an automatic refresh on an API call.

        Returns:
            The result of the token refresh operation.

        Example:
            ```python
            try:
                result = client.refresh_token()
                print(f"Token successfully refreshed. New token expires in {result.expires_in} seconds.")
            except AuthenticationError as e:
                print(f"Failed to refresh token: {e}")
            ```
        """
        return self._refresh_access_token()

    def get_settings(self) -> models.UserSettings:
        """
        Get the user settings.

        Returns:
            An object containing the user's account settings.

        Example:
            ```python
            settings = client.get_settings()
            print(settings.account.username)
            ```
        """
        response_data = self._api_request("get", "get_settings")
        return models.UserSettings.from_dict(response_data)

    def get_memory_bandwidth(self) -> models.MemoryBandwidth:
        """
        Get the memory and bandwidth usage.

        Returns:
            An object containing memory and bandwidth details.

        Example:
            ```python
            usage = client.get_memory_bandwidth()
            print(f"Space used: {usage.space_used}/{usage.space_max}")
            ```
        """
        response_data = self._api_request("get", "get_memory_bandwidth")
        return models.MemoryBandwidth.from_dict(response_data)

    def list_contents(self, folder_id: str = "0") -> models.ListContentsResult:
        """
        List the contents of a folder.

        Args:
            folder_id (str, optional): The folder id to list the contents of. Defaults to root folder.

        Returns:
            An object containing the contents of the folder.

        Example:
            ```python
            response = client.list_contents()
            print(response)
            ```
        """
        payload = _request_models.ListContentsPayload(content_id=folder_id)
        response_data = self._api_request("post", "list_contents", data=payload.to_dict())
        return models.ListContentsResult.from_dict(response_data)

    def add_torrent(
        self,
        magnet_link: Optional[str] = None,
        torrent_file: Optional[str] = None,
        wishlist_id: Optional[str] = None,
        folder_id: str = "0",
    ) -> models.AddTorrentResult:
        """
        Add a torrent to the seedr account for downloading.

        Args:
            magnet_link (str, optional): The magnet link of the torrent.
            torrent_file (str, optional): Remote or local path of the torrent file.
            wishlist_id (str, optional): The ID of a wishlist item to add.
            folder_id (str, optional): The folder ID to add the torrent to. Defaults to root ('-1').

        Returns:
            An object containing the result of the add torrent operation.

        Example:
            ```python
            # Add by magnet link
            result = client.add_torrent(magnet_link="magnet:?xt=urn:btih:...")
            print(result.title)

            # Add from a local .torrent file
            result = client.add_torrent(torrent_file="/path/to/your/file.torrent")
            print(result.title)
            ```
        """
        payload = _request_models.AddTorrentPayload(
            torrent_magnet=magnet_link,
            wishlist_id=wishlist_id,
            folder_id=folder_id,
        )
        files = {}
        if torrent_file:
            files = self._read_torrent_file(torrent_file)

        response_data = self._api_request("post", "add_torrent", data=payload.to_dict(), files=files)
        return models.AddTorrentResult.from_dict(response_data)

    def scan_page(self, url: str) -> models.ScanPageResult:
        """
        Scan a page for torrents and magnet links.

        Args:
            url (str): The URL of the page to scan.

        Returns:
            An object containing the list of torrents found on the page.

        Example:
            ```python
            result = client.scan_page(url='some_torrent_page_url')
            for torrent in result.torrents:
                print(torrent.title)
            ```
        """
        payload = _request_models.ScanPagePayload(url=url)
        response_data = self._api_request("post", "scan_page", data=payload.to_dict())
        return models.ScanPageResult.from_dict(response_data)

    def fetch_file(self, file_id: str) -> models.FetchFileResult:
        """
        Create a link of a file.

        Args:
            file_id (str): The file id to fetch. This is the `folder_file_id` from the `list_contents` method.

        Returns:
            An object containing the file details and download URL.

        Example:
            ```python
            result = client.fetch_file(file_id='12345')
            print(f"Download URL: {result.url}")
            ```
        """
        payload = _request_models.FetchFilePayload(folder_file_id=file_id)
        response_data = self._api_request("post", "fetch_file", data=payload.to_dict())
        return models.FetchFileResult.from_dict(response_data)

    def create_archive(self, folder_id: str) -> models.CreateArchiveResult:
        """
        Create an archive link of a folder.

        Args:
            folder_id (str): The folder id to create the archive of.

        Returns:
            An object containing the result of the archive creation.

        Example:
            ```python
            result = client.create_archive(folder_id='12345')
            print(f"Archive URL: {result.archive_url}")
            ```
        """
        payload = _request_models.CreateArchivePayload(folder_id=folder_id)
        response_data = self._api_request("post", "create_empty_archive", data=payload.to_dict())
        return models.CreateArchiveResult.from_dict(response_data)

    def search_files(self, query: str) -> models.Folder:
        """
        Search for files.

        Args:
            query (str): The query to search for.

        Returns:
            An object containing the search results.

        Example:
            ```python
            results = client.search_files(query='harry potter')
            for f in results.folders:
                print(f"Found folder: {f.name}")
            ```
        """
        payload = _request_models.SearchFilesPayload(search_query=query)
        response_data = self._api_request("post", "search_files", data=payload.to_dict())
        return models.Folder.from_dict(response_data)

    def add_folder(self, name: str) -> models.APIResult:
        """
        Add a folder.

        Args:
            name (str): Folder name to add.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            result = client.add_folder(name='New Folder')
            if result.result:
                print("Folder created successfully.")
            ```
        """
        payload = _request_models.AddFolderPayload(name=name)
        response_data = self._api_request("post", "add_folder", data=payload.to_dict())
        return models.APIResult.from_dict(response_data)

    def rename_file(self, file_id: str, rename_to: str) -> models.APIResult:
        """
        Rename a file.

        Args:
            file_id (str): The file id to rename.
            rename_to (str): The new name of the file.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            result = client.rename_file(file_id='12345', rename_to='newName')
            if result.result:
                print("File renamed successfully.")
            ```
        """
        payload = _request_models.RenameFilePayload(rename_to=rename_to, file_id=file_id)
        response_data = self._api_request("post", "rename", data=payload.to_dict())
        return models.APIResult.from_dict(response_data)

    def rename_folder(self, folder_id: str, rename_to: str) -> models.APIResult:
        """
        Rename a folder.

        Args:
            folder_id (str): The folder id to rename.
            rename_to (str): The new name of the folder.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            result = client.rename_folder(folder_id='12345', rename_to='newName')
            if result.result:
                print("Folder renamed successfully.")
            ```
        """
        payload = _request_models.RenameFolderPayload(rename_to=rename_to, folder_id=folder_id)
        response_data = self._api_request("post", "rename", data=payload.to_dict())
        return models.APIResult.from_dict(response_data)

    def delete_file(self, file_id: str) -> models.APIResult:
        """
        Delete a file.

        Args:
            file_id (str): The file id to delete.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            response = client.delete_file(file_id='12345')
            print(response)
            ```
        """
        return self._delete_api_item("file", file_id)

    def delete_folder(self, folder_id: str) -> models.APIResult:
        """
        Delete a folder.

        Args:
            folder_id (str): The folder id to delete.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            response = client.delete_folder(folder_id='12345')
            print(response)
            ```
        """
        return self._delete_api_item("folder", folder_id)

    def delete_torrent(self, torrent_id: str) -> models.APIResult:
        """
        Delete an active downloading torrent.

        Args:
            torrent_id (str): The torrent id to delete.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            response = client.delete_torrent(torrent_id='12345')
            print(response)
            ```
        """
        return self._delete_api_item("torrent", torrent_id)

    def delete_wishlist(self, wishlist_id: str) -> models.APIResult:
        """
        Delete an item from the wishlist.

        Args:
            wishlist_id (str): The wishlistId of item to delete.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            result = client.delete_wishlist(wishlist_id='12345')
            ```
        """
        payload = _request_models.RemoveWishlistPayload(id=wishlist_id)
        response_data = self._api_request("post", "remove_wishlist", data=payload.to_dict())
        return models.APIResult.from_dict(response_data)

    def get_devices(self) -> List[models.Device]:
        """
        Get the devices connected to the seedr account.

        Returns:
            A list of devices connected to the account.

        Example:
            ```python
            devices = client.get_devices()
            for device in devices:
                print(device.client_name)
            ```
        """
        response_data = self._api_request("get", "get_devices")
        devices_data = response_data.get("devices", [])
        return [models.Device.from_dict(d) for d in devices_data]

    def get_torrent_progress(self, progress_url: str) -> models.TorrentProgress:
        """
        Fetch and parse the progress data for an active torrent download.

        Args:
            progress_url (str): The progress URL from a `Torrent` object's `progress_url` field.

        Returns:
            A `TorrentProgress` object containing download stats.

        Example:
            ```python
            contents = client.list_contents()
            for torrent in contents.torrents:
                if torrent.progress_url:
                    progress = client.get_torrent_progress(torrent.progress_url)
                    print(f"{progress.title}: {progress.progress:.1f}%")
            ```
        """
        url = httpx.URL(progress_url).copy_remove_param("callback")
        response = self._make_http_request(self._client, "get", str(url))
        try:
            data = response.json()
        except json.JSONDecodeError as e:
            raise APIError("Invalid JSON response from progress URL.", response=response) from e
        return models.TorrentProgress.from_dict(data)

    def change_name(self, name: str, password: str) -> models.APIResult:
        """
        Change the name of the account.

        Args:
            name (str): The new name of the account.
            password (str): The password of the account.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            result = client.change_name(name='New Name', password='password')
            ```
        """
        payload = _request_models.ChangeNamePayload(fullname=name, password=password)
        response_data = self._api_request("post", "user_account_modify", data=payload.to_dict())
        return models.APIResult.from_dict(response_data)

    def change_password(self, old_password: str, new_password: str) -> models.APIResult:
        """
        Change the password of the account.

        Args:
            old_password (str): The old password of the account.
            new_password (str): The new password of the account.

        Returns:
            An object indicating the result of the operation.

        Example:
            ```python
            result = client.change_password(old_password='old', new_password='new')
            ```
        """
        payload = _request_models.ChangePasswordPayload(
            password=old_password,
            new_password=new_password,
            new_password_repeat=new_password,
        )
        response_data = self._api_request("post", "user_account_modify", data=payload.to_dict())
        return models.APIResult.from_dict(response_data)

    def _api_request(
        self, http_method: str, func: str, files: Optional[Dict[str, Any]] = None, **kwargs: Any
    ) -> Dict[str, Any]:
        """Handles the core logic for making authenticated API requests, including token refreshes."""
        url = kwargs.pop("url", _constants.RESOURCE_URL)
        params = kwargs.pop("params", {})
        if "access_token" not in params:
            params["access_token"] = self._token.access_token
        if func:
            params["func"] = func

        response = self._make_http_request(self._client, http_method, url, params=params, files=files, **kwargs)
        try:
            data = response.json()
        except json.JSONDecodeError as e:
            raise APIError("Invalid JSON response from API.", response=None) from e

        if isinstance(data, dict) and data.get("error") == "expired_token":
            self._refresh_access_token()
            params["access_token"] = self._token.access_token
            response = self._make_http_request(self._client, http_method, url, params=params, files=files, **kwargs)
            try:
                data = response.json()
            except json.JSONDecodeError as e:
                raise APIError("Invalid JSON response from API.", response=None) from e

        if response.is_client_error:
            if response.status_code == 401:
                raise AuthenticationError("Authentication failed.", response=response)
            raise APIError("API request failed.", response=response)

        if isinstance(data, dict) and data.get("result", True) is not True:
            raise APIError("API operation failed.", response=response)

        return data

    def _refresh_access_token(self) -> models.RefreshTokenResult:
        """Refreshes the access token using the refresh token or device code."""
        if self._token.refresh_token:
            payload = _request_models.RefreshTokenPayload(refresh_token=self._token.refresh_token)
            response = self._make_http_request(self._client, "post", _constants.TOKEN_URL, data=payload.to_dict())
        elif self._token.device_code:
            params = _request_models.DeviceCodeAuthParams(device_code=self._token.device_code)
            response = self._make_http_request(
                self._client, "get", _constants.DEVICE_AUTHORIZE_URL, params=params.to_dict()
            )
        else:
            raise AuthenticationError("No refresh token or device code available to refresh the session.")

        if not response.is_success:
            raise AuthenticationError("Failed to refresh token.", response=response)

        try:
            response_data = response.json()
        except json.JSONDecodeError as e:
            raise APIError("Invalid JSON response from API.", response=None) from e

        if "access_token" not in response_data:
            raise AuthenticationError(
                "Token refresh failed. The response did not contain a new access token.",
                response=response,
            )

        self._token = Token(
            access_token=response_data["access_token"],
            refresh_token=self._token.refresh_token,
            device_code=self._token.device_code,
        )
        if self._on_token_refresh:
            self._on_token_refresh(self._token)

        return models.RefreshTokenResult.from_dict(response_data)

    def _read_torrent_file(self, torrent_file: str) -> Dict[str, Any]:
        """Reads a torrent file from a local path or a remote URL into memory."""
        if torrent_file.startswith(("http://", "https://")):
            file_content = httpx.get(torrent_file).content
            return {"torrent_file": file_content}
        else:
            with open(torrent_file, "rb") as f:
                return {"torrent_file": f.read()}

    def _delete_api_item(self, item_type: Literal["file", "folder", "torrent"], item_id: str) -> models.APIResult:
        """Constructs and sends a request to delete a specific item (file, folder, etc.)."""
        payload = _request_models.DeleteItemPayload(item_type=item_type, item_id=item_id)
        response_data = self._api_request("post", "delete", data=payload.to_dict())
        return models.APIResult.from_dict(response_data)

    @classmethod
    def _initialize_client(
        cls: Type["Seedr"],
        auth_callable: Callable[[httpx.Client], Dict[str, Any]],
        token_callable: Callable[[Dict[str, Any]], Dict[str, Any]],
        on_token_refresh: Optional[Callable[[Token], None]],
        httpx_client: Optional[httpx.Client],
        timeout: float = 30.0,
        proxy: Optional[Dict[str, str]] = None,
        **httpx_kwargs: Any,
    ) -> "Seedr":
        """A factory helper that orchestrates the authentication process and constructs the client."""
        httpx_kwargs.setdefault("timeout", timeout)
        httpx_kwargs.setdefault("proxy", proxy)
        client = httpx_client or httpx.Client(**httpx_kwargs)
        success = False
        try:
            response_data = auth_callable(client)
            token_extras = token_callable(response_data)
            token = Token(
                access_token=response_data["access_token"],
                refresh_token=response_data.get("refresh_token"),
                **token_extras,
            )
            instance = cls(token, on_token_refresh=on_token_refresh, httpx_client=client, **httpx_kwargs)
            success = True
            return instance
        finally:
            if httpx_client is None and not success:
                client.close()

    @classmethod
    def _authenticate_and_get_token_data(
        cls: Type["Seedr"],
        client: httpx.Client,
        method: str,
        url: str,
        **httpx_kwargs: Any,
    ) -> Dict[str, Any]:
        """Handles the common logic for making an authentication request."""
        response = cls._make_http_request(client, method, url, **httpx_kwargs)

        if not response.is_success:
            raise AuthenticationError("Authentication failed.", response=response)

        try:
            data = response.json()
            if isinstance(data, dict) and data.get("error") in ["authorization_pending"]:
                raise AuthenticationError(
                    "Authentication failed.",
                    response=response,
                )
            return data
        except json.JSONDecodeError as e:
            raise APIError("Invalid JSON response from API.", response=None) from e

    @staticmethod
    def _make_http_request(
        client: httpx.Client,
        method: str,
        url: str,
        **kwargs: Any,
    ) -> httpx.Response:
        """Performs the raw HTTP request, handles network/server errors, and returns the response."""
        try:
            response = client.request(method, url, **kwargs)

            if response.is_server_error:
                raise ServerError(response=response)

            return response
        except httpx.RequestError as e:
            raise NetworkError(str(e)) from e

    def close(self) -> None:
        """Closes the underlying httpx client if it was created by this instance."""
        if self._manages_client_lifecycle:
            self._client.close()

    def __enter__(self) -> "Seedr":
        return self

    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        self.close()

__init__(token, on_token_refresh=None, httpx_client=None, timeout=30.0, proxy=None, **httpx_kwargs)

Initializes the synchronous client with an existing token.

Parameters:

Name Type Description Default
token Token

An authenticated Token object.

required
on_token_refresh Optional[Callable[[Token], None]]

An optional callback function that is called with the new Token object when the session is refreshed.

None
httpx_client Optional[Client]

An optional, pre-configured httpx.Client instance.

None
timeout float

The timeout for network requests in seconds.

30.0
proxy Optional[Dict[str, str]]

An optional dictionary of proxy to use for requests.

None
**httpx_kwargs Any

Optional keyword arguments to pass to the httpx.Client constructor. These are ignored if httpx_client is provided.

{}
Source code in seedrcc/client.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def __init__(
    self,
    token: Token,
    on_token_refresh: Optional[Callable[[Token], None]] = None,
    httpx_client: Optional[httpx.Client] = None,
    timeout: float = 30.0,
    proxy: Optional[Dict[str, str]] = None,
    **httpx_kwargs: Any,
) -> None:
    """Initializes the synchronous client with an existing token.

    Args:
        token: An authenticated `Token` object.
        on_token_refresh: An optional callback function that is called with the new
            `Token` object when the session is refreshed.
        httpx_client: An optional, pre-configured `httpx.Client` instance.
        timeout: The timeout for network requests in seconds.
        proxy: An optional dictionary of proxy to use for requests.
        **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
            These are ignored if `httpx_client` is provided.
    """
    super().__init__(token, on_token_refresh)
    if httpx_client is not None:
        self._client = httpx_client
        self._manages_client_lifecycle = False
    else:
        httpx_kwargs.setdefault("timeout", timeout)
        httpx_kwargs.setdefault("proxy", proxy)
        self._client = httpx.Client(**httpx_kwargs)
        self._manages_client_lifecycle = True

get_device_code() staticmethod

Gets the device and user codes required for authorization.

This is the first step in the device authentication flow.

Returns:

Type Description
DeviceCode

A DeviceCode object containing the codes needed for the next step.

Example
from seedrcc import Seedr

codes = Seedr.get_device_code()
print(f"Go to {codes.verification_url} and enter {codes.user_code}")
Source code in seedrcc/client.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@staticmethod
def get_device_code() -> models.DeviceCode:
    """
    Gets the device and user codes required for authorization.

    This is the first step in the device authentication flow.

    Returns:
        A `DeviceCode` object containing the codes needed for the next step.

    Example:
        ```python
        from seedrcc import Seedr

        codes = Seedr.get_device_code()
        print(f"Go to {codes.verification_url} and enter {codes.user_code}")
        ```
    """
    params = _request_models.GetDeviceCodeParams()
    with httpx.Client() as client:
        response = Seedr._make_http_request(client, "get", _constants.DEVICE_CODE_URL, params=params.to_dict())

        if not response.is_success:
            raise APIError("Failed to get device code.", response=response)

        try:
            response_data = response.json()
        except json.JSONDecodeError as e:
            raise APIError("Invalid JSON response from API.", response=None) from e
        return models.DeviceCode.from_dict(response_data)

from_password(username, password, on_token_refresh=None, httpx_client=None, timeout=30.0, proxy=None, **httpx_kwargs) classmethod

Creates a new client by authenticating with a username and password.

Parameters:

Name Type Description Default
username str

The user's Seedr username (email).

required
password str

The user's Seedr password.

required
on_token_refresh Optional[Callable[[Token], None]]

A callback function that is called with the new Token object when the session is refreshed.

None
httpx_client Optional[Client]

An optional, pre-configured httpx.Client instance.

None
timeout float

The timeout for network requests in seconds.

30.0
proxy Optional[Dict[str, str]]

A dictionary of proxy to use for requests.

None
**httpx_kwargs Any

Optional keyword arguments to pass to the httpx.Client constructor. These are ignored if httpx_client is provided.

{}

Returns:

Type Description
Seedr

An initialized Seedr client instance.

Example
client = Seedr.from_password("your_email@example.com", "your_password")
Source code in seedrcc/client.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
@classmethod
def from_password(
    cls: Type["Seedr"],
    username: str,
    password: str,
    on_token_refresh: Optional[Callable[[Token], None]] = None,
    httpx_client: Optional[httpx.Client] = None,
    timeout: float = 30.0,
    proxy: Optional[Dict[str, str]] = None,
    **httpx_kwargs: Any,
) -> "Seedr":
    """
    Creates a new client by authenticating with a username and password.

    Args:
        username: The user's Seedr username (email).
        password: The user's Seedr password.
        on_token_refresh: A callback function that is called with the new
            Token object when the session is refreshed.
        httpx_client: An optional, pre-configured `httpx.Client` instance.
        timeout: The timeout for network requests in seconds.
        proxy: A dictionary of proxy to use for requests.
        **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
            These are ignored if `httpx_client` is provided.

    Returns:
        An initialized `Seedr` client instance.

    Example:
        ```python
        client = Seedr.from_password("your_email@example.com", "your_password")
        ```
    """

    def auth_callable(client: httpx.Client) -> Dict[str, Any]:
        """Prepare and execute the authentication request."""
        payload = _request_models.PasswordLoginPayload(username=username, password=password)
        return cls._authenticate_and_get_token_data(
            client,
            "post",
            _constants.TOKEN_URL,
            data=payload.to_dict(),
        )

    return cls._initialize_client(
        auth_callable,
        lambda r: {},
        on_token_refresh,
        httpx_client,
        timeout=timeout,
        proxy=proxy,
        **httpx_kwargs,
    )

from_device_code(device_code, on_token_refresh=None, httpx_client=None, timeout=30.0, proxy=None, **httpx_kwargs) classmethod

Creates a new client by authorizing with a device code.

This is the second step in the device authentication flow, after getting the codes from Seedr.get_device_code().

Parameters:

Name Type Description Default
device_code str

The device code obtained from get_device_code().

required
on_token_refresh Optional[Callable[[Token], None]]

A callback function that is called with the new Token object when the session is refreshed.

None
httpx_client Optional[Client]

An optional, pre-configured httpx.Client instance.

None
timeout float

The timeout for network requests in seconds.

30.0
proxy Optional[Dict[str, str]]

A dictionary of proxy to use for requests.

None
**httpx_kwargs Any

Optional keyword arguments to pass to the httpx.Client constructor. These are ignored if httpx_client is provided.

{}

Returns:

Type Description
Seedr

An initialized Seedr client instance.

Example
client = Seedr.from_device_code("your_device_code")
Source code in seedrcc/client.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
@classmethod
def from_device_code(
    cls: Type["Seedr"],
    device_code: str,
    on_token_refresh: Optional[Callable[[Token], None]] = None,
    httpx_client: Optional[httpx.Client] = None,
    timeout: float = 30.0,
    proxy: Optional[Dict[str, str]] = None,
    **httpx_kwargs: Any,
) -> "Seedr":
    """
    Creates a new client by authorizing with a device code.

    This is the second step in the device authentication flow, after getting the
    codes from `Seedr.get_device_code()`.

    Args:
        device_code: The device code obtained from `get_device_code()`.
        on_token_refresh: A callback function that is called with the new
            Token object when the session is refreshed.
        httpx_client: An optional, pre-configured `httpx.Client` instance.
        timeout: The timeout for network requests in seconds.
        proxy: A dictionary of proxy to use for requests.
        **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
            These are ignored if `httpx_client` is provided.

    Returns:
        An initialized `Seedr` client instance.

    Example:
        ```python
        client = Seedr.from_device_code("your_device_code")
        ```
    """

    def auth_callable(client: httpx.Client) -> Dict[str, Any]:
        """Prepare and execute the device authorization request."""
        params = _request_models.DeviceCodeAuthParams(device_code=device_code)
        return cls._authenticate_and_get_token_data(
            client,
            "get",
            _constants.DEVICE_AUTHORIZE_URL,
            params=params.to_dict(),
        )

    return cls._initialize_client(
        auth_callable,
        lambda r: {"device_code": device_code},
        on_token_refresh,
        httpx_client,
        timeout=timeout,
        proxy=proxy,
        **httpx_kwargs,
    )

from_refresh_token(refresh_token, on_token_refresh=None, httpx_client=None, timeout=30.0, proxy=None, **httpx_kwargs) classmethod

Creates a new client by using an existing refresh token.

Parameters:

Name Type Description Default
refresh_token str

A valid refresh token.

required
on_token_refresh Optional[Callable[[Token], None]]

A callback function that is called with the new Token object when the session is refreshed.

None
httpx_client Optional[Client]

An optional, pre-configured httpx.Client instance.

None
timeout float

The timeout for network requests in seconds.

30.0
proxy Optional[Dict[str, str]]

A dictionary of proxy to use for requests.

None
**httpx_kwargs Any

Optional keyword arguments to pass to the httpx.Client constructor. These are ignored if httpx_client is provided.

{}

Returns:

Type Description
Seedr

An initialized Seedr client instance.

Example
client = Seedr.from_refresh_token("your_refresh_token")
Source code in seedrcc/client.py
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
@classmethod
def from_refresh_token(
    cls: Type["Seedr"],
    refresh_token: str,
    on_token_refresh: Optional[Callable[[Token], None]] = None,
    httpx_client: Optional[httpx.Client] = None,
    timeout: float = 30.0,
    proxy: Optional[Dict[str, str]] = None,
    **httpx_kwargs: Any,
) -> "Seedr":
    """
    Creates a new client by using an existing refresh token.

    Args:
        refresh_token: A valid refresh token.
        on_token_refresh: A callback function that is called with the new
            Token object when the session is refreshed.
        httpx_client: An optional, pre-configured `httpx.Client` instance.
        timeout: The timeout for network requests in seconds.
        proxy: A dictionary of proxy to use for requests.
        **httpx_kwargs: Optional keyword arguments to pass to the `httpx.Client` constructor.
            These are ignored if `httpx_client` is provided.

    Returns:
        An initialized `Seedr` client instance.

    Example:
        ```python
        client = Seedr.from_refresh_token("your_refresh_token")
        ```
    """

    def auth_callable(client: httpx.Client) -> Dict[str, Any]:
        """Prepare and execute the token refresh request."""
        payload = _request_models.RefreshTokenPayload(refresh_token=refresh_token)
        return cls._authenticate_and_get_token_data(
            client,
            "post",
            _constants.TOKEN_URL,
            data=payload.to_dict(),
        )

    return cls._initialize_client(
        auth_callable,
        lambda r: {"refresh_token": refresh_token},
        on_token_refresh,
        httpx_client,
        timeout=timeout,
        proxy=proxy,
        **httpx_kwargs,
    )

refresh_token()

Manually refreshes the access token.

This is useful if you want to proactively manage the token's lifecycle instead of waiting for an automatic refresh on an API call.

Returns:

Type Description
RefreshTokenResult

The result of the token refresh operation.

Example
try:
    result = client.refresh_token()
    print(f"Token successfully refreshed. New token expires in {result.expires_in} seconds.")
except AuthenticationError as e:
    print(f"Failed to refresh token: {e}")
Source code in seedrcc/client.py
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def refresh_token(self) -> models.RefreshTokenResult:
    """
    Manually refreshes the access token.

    This is useful if you want to proactively manage the token's lifecycle
    instead of waiting for an automatic refresh on an API call.

    Returns:
        The result of the token refresh operation.

    Example:
        ```python
        try:
            result = client.refresh_token()
            print(f"Token successfully refreshed. New token expires in {result.expires_in} seconds.")
        except AuthenticationError as e:
            print(f"Failed to refresh token: {e}")
        ```
    """
    return self._refresh_access_token()

get_settings()

Get the user settings.

Returns:

Type Description
UserSettings

An object containing the user's account settings.

Example
settings = client.get_settings()
print(settings.account.username)
Source code in seedrcc/client.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
def get_settings(self) -> models.UserSettings:
    """
    Get the user settings.

    Returns:
        An object containing the user's account settings.

    Example:
        ```python
        settings = client.get_settings()
        print(settings.account.username)
        ```
    """
    response_data = self._api_request("get", "get_settings")
    return models.UserSettings.from_dict(response_data)

get_memory_bandwidth()

Get the memory and bandwidth usage.

Returns:

Type Description
MemoryBandwidth

An object containing memory and bandwidth details.

Example
usage = client.get_memory_bandwidth()
print(f"Space used: {usage.space_used}/{usage.space_max}")
Source code in seedrcc/client.py
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def get_memory_bandwidth(self) -> models.MemoryBandwidth:
    """
    Get the memory and bandwidth usage.

    Returns:
        An object containing memory and bandwidth details.

    Example:
        ```python
        usage = client.get_memory_bandwidth()
        print(f"Space used: {usage.space_used}/{usage.space_max}")
        ```
    """
    response_data = self._api_request("get", "get_memory_bandwidth")
    return models.MemoryBandwidth.from_dict(response_data)

list_contents(folder_id='0')

List the contents of a folder.

Parameters:

Name Type Description Default
folder_id str

The folder id to list the contents of. Defaults to root folder.

'0'

Returns:

Type Description
ListContentsResult

An object containing the contents of the folder.

Example
response = client.list_contents()
print(response)
Source code in seedrcc/client.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def list_contents(self, folder_id: str = "0") -> models.ListContentsResult:
    """
    List the contents of a folder.

    Args:
        folder_id (str, optional): The folder id to list the contents of. Defaults to root folder.

    Returns:
        An object containing the contents of the folder.

    Example:
        ```python
        response = client.list_contents()
        print(response)
        ```
    """
    payload = _request_models.ListContentsPayload(content_id=folder_id)
    response_data = self._api_request("post", "list_contents", data=payload.to_dict())
    return models.ListContentsResult.from_dict(response_data)

add_torrent(magnet_link=None, torrent_file=None, wishlist_id=None, folder_id='0')

Add a torrent to the seedr account for downloading.

Parameters:

Name Type Description Default
magnet_link str

The magnet link of the torrent.

None
torrent_file str

Remote or local path of the torrent file.

None
wishlist_id str

The ID of a wishlist item to add.

None
folder_id str

The folder ID to add the torrent to. Defaults to root ('-1').

'0'

Returns:

Type Description
AddTorrentResult

An object containing the result of the add torrent operation.

Example
# Add by magnet link
result = client.add_torrent(magnet_link="magnet:?xt=urn:btih:...")
print(result.title)

# Add from a local .torrent file
result = client.add_torrent(torrent_file="/path/to/your/file.torrent")
print(result.title)
Source code in seedrcc/client.py
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def add_torrent(
    self,
    magnet_link: Optional[str] = None,
    torrent_file: Optional[str] = None,
    wishlist_id: Optional[str] = None,
    folder_id: str = "0",
) -> models.AddTorrentResult:
    """
    Add a torrent to the seedr account for downloading.

    Args:
        magnet_link (str, optional): The magnet link of the torrent.
        torrent_file (str, optional): Remote or local path of the torrent file.
        wishlist_id (str, optional): The ID of a wishlist item to add.
        folder_id (str, optional): The folder ID to add the torrent to. Defaults to root ('-1').

    Returns:
        An object containing the result of the add torrent operation.

    Example:
        ```python
        # Add by magnet link
        result = client.add_torrent(magnet_link="magnet:?xt=urn:btih:...")
        print(result.title)

        # Add from a local .torrent file
        result = client.add_torrent(torrent_file="/path/to/your/file.torrent")
        print(result.title)
        ```
    """
    payload = _request_models.AddTorrentPayload(
        torrent_magnet=magnet_link,
        wishlist_id=wishlist_id,
        folder_id=folder_id,
    )
    files = {}
    if torrent_file:
        files = self._read_torrent_file(torrent_file)

    response_data = self._api_request("post", "add_torrent", data=payload.to_dict(), files=files)
    return models.AddTorrentResult.from_dict(response_data)

scan_page(url)

Scan a page for torrents and magnet links.

Parameters:

Name Type Description Default
url str

The URL of the page to scan.

required

Returns:

Type Description
ScanPageResult

An object containing the list of torrents found on the page.

Example
result = client.scan_page(url='some_torrent_page_url')
for torrent in result.torrents:
    print(torrent.title)
Source code in seedrcc/client.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def scan_page(self, url: str) -> models.ScanPageResult:
    """
    Scan a page for torrents and magnet links.

    Args:
        url (str): The URL of the page to scan.

    Returns:
        An object containing the list of torrents found on the page.

    Example:
        ```python
        result = client.scan_page(url='some_torrent_page_url')
        for torrent in result.torrents:
            print(torrent.title)
        ```
    """
    payload = _request_models.ScanPagePayload(url=url)
    response_data = self._api_request("post", "scan_page", data=payload.to_dict())
    return models.ScanPageResult.from_dict(response_data)

fetch_file(file_id)

Create a link of a file.

Parameters:

Name Type Description Default
file_id str

The file id to fetch. This is the folder_file_id from the list_contents method.

required

Returns:

Type Description
FetchFileResult

An object containing the file details and download URL.

Example
result = client.fetch_file(file_id='12345')
print(f"Download URL: {result.url}")
Source code in seedrcc/client.py
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def fetch_file(self, file_id: str) -> models.FetchFileResult:
    """
    Create a link of a file.

    Args:
        file_id (str): The file id to fetch. This is the `folder_file_id` from the `list_contents` method.

    Returns:
        An object containing the file details and download URL.

    Example:
        ```python
        result = client.fetch_file(file_id='12345')
        print(f"Download URL: {result.url}")
        ```
    """
    payload = _request_models.FetchFilePayload(folder_file_id=file_id)
    response_data = self._api_request("post", "fetch_file", data=payload.to_dict())
    return models.FetchFileResult.from_dict(response_data)

create_archive(folder_id)

Create an archive link of a folder.

Parameters:

Name Type Description Default
folder_id str

The folder id to create the archive of.

required

Returns:

Type Description
CreateArchiveResult

An object containing the result of the archive creation.

Example
result = client.create_archive(folder_id='12345')
print(f"Archive URL: {result.archive_url}")
Source code in seedrcc/client.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
def create_archive(self, folder_id: str) -> models.CreateArchiveResult:
    """
    Create an archive link of a folder.

    Args:
        folder_id (str): The folder id to create the archive of.

    Returns:
        An object containing the result of the archive creation.

    Example:
        ```python
        result = client.create_archive(folder_id='12345')
        print(f"Archive URL: {result.archive_url}")
        ```
    """
    payload = _request_models.CreateArchivePayload(folder_id=folder_id)
    response_data = self._api_request("post", "create_empty_archive", data=payload.to_dict())
    return models.CreateArchiveResult.from_dict(response_data)

search_files(query)

Search for files.

Parameters:

Name Type Description Default
query str

The query to search for.

required

Returns:

Type Description
Folder

An object containing the search results.

Example
results = client.search_files(query='harry potter')
for f in results.folders:
    print(f"Found folder: {f.name}")
Source code in seedrcc/client.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
def search_files(self, query: str) -> models.Folder:
    """
    Search for files.

    Args:
        query (str): The query to search for.

    Returns:
        An object containing the search results.

    Example:
        ```python
        results = client.search_files(query='harry potter')
        for f in results.folders:
            print(f"Found folder: {f.name}")
        ```
    """
    payload = _request_models.SearchFilesPayload(search_query=query)
    response_data = self._api_request("post", "search_files", data=payload.to_dict())
    return models.Folder.from_dict(response_data)

add_folder(name)

Add a folder.

Parameters:

Name Type Description Default
name str

Folder name to add.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
result = client.add_folder(name='New Folder')
if result.result:
    print("Folder created successfully.")
Source code in seedrcc/client.py
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
def add_folder(self, name: str) -> models.APIResult:
    """
    Add a folder.

    Args:
        name (str): Folder name to add.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        result = client.add_folder(name='New Folder')
        if result.result:
            print("Folder created successfully.")
        ```
    """
    payload = _request_models.AddFolderPayload(name=name)
    response_data = self._api_request("post", "add_folder", data=payload.to_dict())
    return models.APIResult.from_dict(response_data)

rename_file(file_id, rename_to)

Rename a file.

Parameters:

Name Type Description Default
file_id str

The file id to rename.

required
rename_to str

The new name of the file.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
result = client.rename_file(file_id='12345', rename_to='newName')
if result.result:
    print("File renamed successfully.")
Source code in seedrcc/client.py
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
def rename_file(self, file_id: str, rename_to: str) -> models.APIResult:
    """
    Rename a file.

    Args:
        file_id (str): The file id to rename.
        rename_to (str): The new name of the file.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        result = client.rename_file(file_id='12345', rename_to='newName')
        if result.result:
            print("File renamed successfully.")
        ```
    """
    payload = _request_models.RenameFilePayload(rename_to=rename_to, file_id=file_id)
    response_data = self._api_request("post", "rename", data=payload.to_dict())
    return models.APIResult.from_dict(response_data)

rename_folder(folder_id, rename_to)

Rename a folder.

Parameters:

Name Type Description Default
folder_id str

The folder id to rename.

required
rename_to str

The new name of the folder.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
result = client.rename_folder(folder_id='12345', rename_to='newName')
if result.result:
    print("Folder renamed successfully.")
Source code in seedrcc/client.py
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
def rename_folder(self, folder_id: str, rename_to: str) -> models.APIResult:
    """
    Rename a folder.

    Args:
        folder_id (str): The folder id to rename.
        rename_to (str): The new name of the folder.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        result = client.rename_folder(folder_id='12345', rename_to='newName')
        if result.result:
            print("Folder renamed successfully.")
        ```
    """
    payload = _request_models.RenameFolderPayload(rename_to=rename_to, folder_id=folder_id)
    response_data = self._api_request("post", "rename", data=payload.to_dict())
    return models.APIResult.from_dict(response_data)

delete_file(file_id)

Delete a file.

Parameters:

Name Type Description Default
file_id str

The file id to delete.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
response = client.delete_file(file_id='12345')
print(response)
Source code in seedrcc/client.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def delete_file(self, file_id: str) -> models.APIResult:
    """
    Delete a file.

    Args:
        file_id (str): The file id to delete.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        response = client.delete_file(file_id='12345')
        print(response)
        ```
    """
    return self._delete_api_item("file", file_id)

delete_folder(folder_id)

Delete a folder.

Parameters:

Name Type Description Default
folder_id str

The folder id to delete.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
response = client.delete_folder(folder_id='12345')
print(response)
Source code in seedrcc/client.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def delete_folder(self, folder_id: str) -> models.APIResult:
    """
    Delete a folder.

    Args:
        folder_id (str): The folder id to delete.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        response = client.delete_folder(folder_id='12345')
        print(response)
        ```
    """
    return self._delete_api_item("folder", folder_id)

delete_torrent(torrent_id)

Delete an active downloading torrent.

Parameters:

Name Type Description Default
torrent_id str

The torrent id to delete.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
response = client.delete_torrent(torrent_id='12345')
print(response)
Source code in seedrcc/client.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def delete_torrent(self, torrent_id: str) -> models.APIResult:
    """
    Delete an active downloading torrent.

    Args:
        torrent_id (str): The torrent id to delete.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        response = client.delete_torrent(torrent_id='12345')
        print(response)
        ```
    """
    return self._delete_api_item("torrent", torrent_id)

delete_wishlist(wishlist_id)

Delete an item from the wishlist.

Parameters:

Name Type Description Default
wishlist_id str

The wishlistId of item to delete.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
result = client.delete_wishlist(wishlist_id='12345')
Source code in seedrcc/client.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def delete_wishlist(self, wishlist_id: str) -> models.APIResult:
    """
    Delete an item from the wishlist.

    Args:
        wishlist_id (str): The wishlistId of item to delete.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        result = client.delete_wishlist(wishlist_id='12345')
        ```
    """
    payload = _request_models.RemoveWishlistPayload(id=wishlist_id)
    response_data = self._api_request("post", "remove_wishlist", data=payload.to_dict())
    return models.APIResult.from_dict(response_data)

get_devices()

Get the devices connected to the seedr account.

Returns:

Type Description
List[Device]

A list of devices connected to the account.

Example
devices = client.get_devices()
for device in devices:
    print(device.client_name)
Source code in seedrcc/client.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def get_devices(self) -> List[models.Device]:
    """
    Get the devices connected to the seedr account.

    Returns:
        A list of devices connected to the account.

    Example:
        ```python
        devices = client.get_devices()
        for device in devices:
            print(device.client_name)
        ```
    """
    response_data = self._api_request("get", "get_devices")
    devices_data = response_data.get("devices", [])
    return [models.Device.from_dict(d) for d in devices_data]

get_torrent_progress(progress_url)

Fetch and parse the progress data for an active torrent download.

Parameters:

Name Type Description Default
progress_url str

The progress URL from a Torrent object's progress_url field.

required

Returns:

Type Description
TorrentProgress

A TorrentProgress object containing download stats.

Example
contents = client.list_contents()
for torrent in contents.torrents:
    if torrent.progress_url:
        progress = client.get_torrent_progress(torrent.progress_url)
        print(f"{progress.title}: {progress.progress:.1f}%")
Source code in seedrcc/client.py
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
def get_torrent_progress(self, progress_url: str) -> models.TorrentProgress:
    """
    Fetch and parse the progress data for an active torrent download.

    Args:
        progress_url (str): The progress URL from a `Torrent` object's `progress_url` field.

    Returns:
        A `TorrentProgress` object containing download stats.

    Example:
        ```python
        contents = client.list_contents()
        for torrent in contents.torrents:
            if torrent.progress_url:
                progress = client.get_torrent_progress(torrent.progress_url)
                print(f"{progress.title}: {progress.progress:.1f}%")
        ```
    """
    url = httpx.URL(progress_url).copy_remove_param("callback")
    response = self._make_http_request(self._client, "get", str(url))
    try:
        data = response.json()
    except json.JSONDecodeError as e:
        raise APIError("Invalid JSON response from progress URL.", response=response) from e
    return models.TorrentProgress.from_dict(data)

change_name(name, password)

Change the name of the account.

Parameters:

Name Type Description Default
name str

The new name of the account.

required
password str

The password of the account.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
result = client.change_name(name='New Name', password='password')
Source code in seedrcc/client.py
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def change_name(self, name: str, password: str) -> models.APIResult:
    """
    Change the name of the account.

    Args:
        name (str): The new name of the account.
        password (str): The password of the account.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        result = client.change_name(name='New Name', password='password')
        ```
    """
    payload = _request_models.ChangeNamePayload(fullname=name, password=password)
    response_data = self._api_request("post", "user_account_modify", data=payload.to_dict())
    return models.APIResult.from_dict(response_data)

change_password(old_password, new_password)

Change the password of the account.

Parameters:

Name Type Description Default
old_password str

The old password of the account.

required
new_password str

The new password of the account.

required

Returns:

Type Description
APIResult

An object indicating the result of the operation.

Example
result = client.change_password(old_password='old', new_password='new')
Source code in seedrcc/client.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def change_password(self, old_password: str, new_password: str) -> models.APIResult:
    """
    Change the password of the account.

    Args:
        old_password (str): The old password of the account.
        new_password (str): The new password of the account.

    Returns:
        An object indicating the result of the operation.

    Example:
        ```python
        result = client.change_password(old_password='old', new_password='new')
        ```
    """
    payload = _request_models.ChangePasswordPayload(
        password=old_password,
        new_password=new_password,
        new_password_repeat=new_password,
    )
    response_data = self._api_request("post", "user_account_modify", data=payload.to_dict())
    return models.APIResult.from_dict(response_data)

close()

Closes the underlying httpx client if it was created by this instance.

Source code in seedrcc/client.py
846
847
848
849
def close(self) -> None:
    """Closes the underlying httpx client if it was created by this instance."""
    if self._manages_client_lifecycle:
        self._client.close()