GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — python-substack/substack/api.py at main · ericpberry/python-substack Expand file tree/ Copy pathapi.pyMore file actions 806 lines (639 loc) · 24.4 KB / Copy pathapi.pyFile metadata and controls806 lines (639 loc) · 24.4 KB 1 2 3 4 5 6 7 8 9 10 11 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 """ API Wrapper """ import base64 import json import logging import os import time from datetime import datetime from urllib.parse import urljoin, unquote import requests from mutagen.mp3 import MP3 from substack.exceptions import SubstackAPIException, SubstackRequestException logger = logging.getLogger(__name__) __all__ = ["Api"] class Api: """ A python interface into the Substack API """ def __init__( self, email=None, password=None, cookies_path=None, base_url=None, publication_url=None, debug=False, cookies_string=None, ): """ To create an instance of the substack.Api class: >>> import substack >>> api = substack.Api(email="substack email", password="substack password") Args: email: password: cookies_path To re-use your session without logging in each time, you can save your cookies to a json file and then load them in the next session. Make sure to re-save your cookies, as they do update over time. cookies_string To re-use your session without logging in each time, you can provide cookies as a semicolon-separated string (e.g., "cookie1=value1; cookie2=value2"). This is useful when copying cookies from browser developer tools. base_url: The base URL to use to contact the Substack API. Defaults to https://substack.com/api/v1. """ self.base_url = base_url or "https://substack.com/api/v1" if debug: logging.basicConfig() logging.getLogger().setLevel(logging.DEBUG) self._session = requests.Session() # Load cookies from file if provided # Helps with Captcha errors by reusing cookies from "local" auth, then switching to running code in the cloud if cookies_path is not None: with open(cookies_path) as f: cookies = json.load(f) self._session.cookies.update(cookies) elif cookies_string is not None: cookies = self._parse_cookies_string(cookies_string) self._session.cookies.update(cookies) elif email is not None and password is not None: self.login(email, password) else: raise ValueError( "Must provide email and password, cookies_path, or cookies_string to authenticate." ) user_publication = None # if the user provided a publication url, then use that if publication_url: import re # Regular expression to extract subdomain name match = re.search(r"https://(.*).substack.com", publication_url.lower()) subdomain = match.group(1) if match else None user_publications = self.get_user_publications() # search through publications to find the publication with the matching subdomain for publication in user_publications: if publication["subdomain"] == subdomain: # set the current publication to the users publication user_publication = publication break else: # get the users primary publication user_publication = self.get_user_primary_publication() # set the current publication to the users primary publication self.change_publication(user_publication) @staticmethod def _parse_cookies_string(cookies_string: str) -> dict: """ Parse a semicolon-separated cookie string into a dictionary. Args: cookies_string: A semicolon-separated string of cookies (e.g., "cookie1=value1; cookie2=value2") Returns: A dictionary of cookie name-value pairs """ cookies = {} for cookie_pair in cookies_string.split(';'): cookie_pair = cookie_pair.strip() if not cookie_pair: continue if '=' in cookie_pair: key, value = cookie_pair.split('=', 1) key = key.strip() value = value.strip() # URL decode the value (e.g., s%3A becomes s:) value = unquote(value) cookies[key] = value return cookies def login(self, email, password) -> dict: """ Login to the substack account. Args: email: substack account email password: substack account password """ response = self._session.post( f"{self.base_url}/login", json={ "captcha_response": None, "email": email, "for_pub": "", "password": password, "redirect": "/", }, ) return Api._handle_response(response=response) def signin_for_pub(self, publication): """ Complete the signin process """ response = self._session.get( f"https://substack.com/sign-in?redirect=%2F&for_pub={publication['subdomain']}", ) try: output = Api._handle_response(response=response) except SubstackRequestException as ex: output = {} return output def change_publication(self, publication): """ Change the publication URL """ self.publication_url = urljoin(publication["publication_url"], "api/v1") # sign-in to the publication self.signin_for_pub(publication) def export_cookies(self, path: str = "cookies.json"): """ Export cookies to a json file. Args: path: path to the json file """ cookies = self._session.cookies.get_dict() with open(path, "w") as f: json.dump(cookies, f) @staticmethod def _handle_response(response: requests.Response): """ Internal helper for handling API responses from the Substack server. Raises the appropriate exceptions when necessary; otherwise, returns the response. """ if not (200 <= response.status_code < 300): raise SubstackAPIException(response.status_code, response.text) try: return response.json() except ValueError: raise SubstackRequestException("Invalid Response: %s" % response.text) def get_user_id(self): """ Returns: """ profile = self.get_user_profile() user_id = profile["id"] return user_id @staticmethod def get_publication_url(publication: dict) -> str: """ Gets the publication url Args: publication: """ custom_domain = publication.get("custom_domain", None) if not custom_domain and not publication.get('custom_domain_optional', None): publication_url = f"https://{publication['subdomain']}.substack.com" else: publication_url = f"https://{custom_domain}" return publication_url def get_user_primary_publication(self): """ Gets the users primary publication """ profile = self.get_user_profile() primary_publication = None # Try old API format first (backward compatibility) if "primaryPublication" in profile and profile["primaryPublication"] is not None: primary_publication = profile["primaryPublication"] else: # New API format: look for primary publication in publicationUsers publication_users = profile.get("publicationUsers") if publication_users is not None and len(publication_users) > 0: # Find the publication where is_primary is True for pub_user in publication_users: if pub_user.get("is_primary", False): primary_publication = pub_user.get("publication") if primary_publication: break # If no primary found, use the first publication if primary_publication is None: primary_publication = publication_users[0].get("publication") if primary_publication is None: raise SubstackRequestException( "Could not find primary publication in profile" ) primary_publication["publication_url"] = self.get_publication_url( primary_publication ) return primary_publication def get_user_publications(self): """ Gets the users publications """ profile = self.get_user_profile() # Loop through users "publicationUsers" list, and return a list # of dictionaries of "name", and "subdomain", and "id" user_publications = [] publication_users = profile.get("publicationUsers") if publication_users is None: # If publicationUsers is None, return empty list or try to construct from other fields # This maintains backward compatibility while handling new API format return user_publications for publication in publication_users: pub = publication.get("publication") if pub is not None: pub["publication_url"] = self.get_publication_url(pub) user_publications.append(pub) return user_publications def get_user_profile(self): """ Gets the users profile """ response = self._session.get(f"{self.base_url}/user/profile/self") return Api._handle_response(response=response) def get_user_settings(self): """ Get list of users. Returns: """ response = self._session.get(f"{self.base_url}/settings") return Api._handle_response(response=response) def get_publication_users(self): """ Get list of users. Returns: """ response = self._session.get(f"{self.publication_url}/publication/users") return Api._handle_response(response=response) def get_publication_subscriber_count(self): """ Get subscriber count. Returns: """ response = self._session.get( f"{self.publication_url}/publication_launch_checklist" ) return Api._handle_response(response=response)["subscriberCount"] def get_published_posts( self, offset=0, limit=25, order_by="post_date", order_direction="desc" ): """ Get list of published posts for the publication. """ response = self._session.get( f"{self.publication_url}/post_management/published", params={ "offset": offset, "limit": limit, "order_by": order_by, "order_direction": order_direction, }, ) return Api._handle_response(response=response) def get_posts(self) -> dict: """ Returns: """ response = self._session.get(f"{self.base_url}/reader/posts") return Api._handle_response(response=response) def get_drafts(self, filter=None, offset=None, limit=None): """ Args: filter: offset: limit: Returns: """ response = self._session.get( f"{self.publication_url}/drafts", params={"filter": filter, "offset": offset, "limit": limit}, ) return Api._handle_response(response=response) def get_draft(self, draft_id): """ Gets a draft given it's id. """ response = self._session.get(f"{self.publication_url}/drafts/{draft_id}") return Api._handle_response(response=response) def delete_draft(self, draft_id): """ Args: draft_id: Returns: """ response = self._session.delete(f"{self.publication_url}/drafts/{draft_id}") return Api._handle_response(response=response) def post_draft(self, body) -> dict: """ Args: body: Returns: """ response = self._session.post(f"{self.publication_url}/drafts", json=body) return Api._handle_response(response=response) def put_draft(self, draft, **kwargs) -> dict: """ Args: draft: **kwargs: Returns: """ response = self._session.put( f"{self.publication_url}/drafts/{draft}", json=kwargs, ) return Api._handle_response(response=response) def prepublish_draft(self, draft) -> dict: """ Args: draft: draft id Returns: """ response = self._session.get( f"{self.publication_url}/drafts/{draft}/prepublish" ) return Api._handle_response(response=response) def publish_draft( self, draft, send: bool = True, share_automatically: bool = False ) -> dict: """ Args: draft: draft id send: share_automatically: Returns: """ response = self._session.post( f"{self.publication_url}/drafts/{draft}/publish", json={"send": send, "share_automatically": share_automatically}, ) return Api._handle_response(response=response) def schedule_draft(self, draft, draft_datetime: datetime) -> dict: """ Args: draft: draft id draft_datetime: datetime to schedule the draft Returns: """ response = self._session.post( f"{self.publication_url}/drafts/{draft}/schedule", json={"post_date": draft_datetime.isoformat()}, ) return Api._handle_response(response=response) def unschedule_draft(self, draft) -> dict: """ Args: draft: draft id Returns: """ response = self._session.post( f"{self.publication_url}/drafts/{draft}/schedule", json={"post_date": None} ) return Api._handle_response(response=response) def get_image(self, image: str): """ This method generates a new substack link that contains the image. Args: image: filepath or original url of image. Returns: """ if os.path.exists(image): with open(image, "rb") as file: image = b"data:image/jpeg;base64," + base64.b64encode(file.read()) response = self._session.post( f"{self.publication_url}/image", data={"image": image}, ) return Api._handle_response(response=response) def upload_podcast_audio( self, file_path: str, draft_id: int, poll_timeout_seconds: float = 120, poll_interval_seconds: float = 3, ) -> dict: """ Upload an audio file for a podcast draft and wait until transcoding completes. Performs the full sequence: initiate upload, PUT raw bytes to the pre-signed S3 URL(s) returned by init, trigger transcode (which finalizes the multipart upload and starts the async transcode job), then poll the media object until its state is ``"transcoded"``. Duration is computed locally via mutagen and sent with the transcode call. Args: file_path: Local path to the audio file (typically an MP3). draft_id: ID of the podcast draft this upload is scoped to. Substack requires a ``post_id`` on the init call. poll_timeout_seconds: Maximum time to wait for transcoding to complete before raising. poll_interval_seconds: Delay between successive state polls. Returns: The final media object dict (``state == "transcoded"``). Its ``id`` field is the audio UUID to attach to a draft as ``draft_podcast_upload_id``. Raises: SubstackAPIException: on non-2xx from any Substack endpoint (init, transcode, or poll). SubstackRequestException: on S3 PUT failure or transcode timeout. """ path = os.fspath(file_path) file_size = os.path.getsize(path) file_name = os.path.basename(path) duration_seconds = MP3(path).info.length # 1. Initiate upload -- returns the media UUID, multipart upload id, # and one or more pre-signed S3 PUT URLs (today always 1 URL). init_response = self._session.post( f"{self.publication_url}/audio/upload", params={ "filetype": "audio/mpeg", "fileSize": file_size, "fileName": file_name, "post_id": draft_id, }, ) init_data = Api._handle_response(response=init_response) upload_id = init_data["mediaUpload"]["id"] multipart_upload_id = init_data["multipartUploadId"] upload_urls = init_data["multipartUploadUrls"] # 2. PUT bytes to each part URL. S3 returns no body; the ETag header # (including its surrounding double-quotes) is what we need. # This is the only HTTP call in the codebase that does not route # through _handle_response -- see docs/STYLE.md section 6. with open(path, "rb") as f: audio_bytes = f.read() etags = [] for url in upload_urls: s3_response = self._session.put(url, data=audio_bytes) if not s3_response.ok: body_preview = (s3_response.text or "")[:500] raise SubstackRequestException( f"S3 upload failed: {s3_response.status_code} {body_preview}" ) etags.append(s3_response.headers["ETag"]) # 3. Trigger transcode. Returns immediately with state "uploaded"; # actual transcoding happens asynchronously. Trust 2xx and proceed # to polling; the poll loop is the source of truth on transcode # completion. transcode_response = self._session.post( f"{self.publication_url}/audio/upload/{upload_id}/transcode", json={ "duration": duration_seconds, "multipart_upload_id": multipart_upload_id, "multipart_upload_etags": etags, }, ) Api._handle_response(response=transcode_response) # 4. Poll until state == "transcoded" (or raise on timeout). deadline = time.monotonic() + poll_timeout_seconds while True: poll_response = self._session.get( f"{self.publication_url}/audio/upload/{upload_id}" ) media = Api._handle_response(response=poll_response) if media.get("state") == "transcoded": return media if time.monotonic() >= deadline: raise SubstackRequestException( f"Audio transcode did not complete within " f"{poll_timeout_seconds}s (uuid={upload_id}, " f"last state={media.get('state')!r})" ) time.sleep(poll_interval_seconds) def add_tags_to_post(self, post_id: int, tag_names: list) -> dict: """ Add multiple tags to a post. Args: post_id: The ID of the post to tag. tag_names: A list of tag names to add. Returns: A dictionary with the results of applying all tags. """ results = [] for tag_name in tag_names: result = self.add_tag_to_post(post_id, tag_name) results.append(result) return {"tags_added": results} def get_publication_post_tags(self) -> list: """ Retrieve all post tags for the current publication. Returns: List of tag dicts as returned by Substack API. """ response = self._session.get(f"{self.publication_url}/publication/post-tag") return Api._handle_response(response=response) def add_tag_to_post(self, post_id: int, tag_name: str) -> dict: """ Add a tag to a post by first checking published tags and creating only if needed. Args: post_id: The ID of the post to tag. tag_name: The name of the tag to add. Returns: The response from applying the tag to the post. """ # Fetch existing publication tags first (avoid re-creating an already existing tag) existing_tags = self.get_publication_post_tags() or [] existing_tag = next( (tag for tag in existing_tags if tag.get("name") == tag_name), None, ) if existing_tag is not None: tag_id = existing_tag["id"] else: create_tag_response = self._session.post( f"{self.publication_url}/publication/post-tag", json={"name": tag_name}, ) tag_data = Api._handle_response(create_tag_response) tag_id = tag_data["id"] apply_tag_response = self._session.post( f"{self.publication_url}/post/{post_id}/tag/{tag_id}", ) return Api._handle_response(apply_tag_response) def get_categories(self): """ Retrieve list of all available categories. Returns: """ response = self._session.get(f"{self.base_url}/categories") return Api._handle_response(response=response) def get_category(self, category_id, category_type, page): """ Args: category_id: category_type: page: Returns: """ response = self._session.get( f"{self.base_url}/category/public/{category_id}/{category_type}", params={"page": page}, ) return Api._handle_response(response=response) def get_single_category(self, category_id, category_type, page=None, limit=None): """ Args: category_id: category_type: paid or all page: by default substack retrieves only the first 25 publications in the category. If this is left None, then all pages will be retrieved. The page size is 25 publications. limit: Returns: """ if page is not None: output = self.get_category(category_id, category_type, page) else: publications = [] page = 0 while True: page_output = self.get_category(category_id, category_type, page) publications.extend(page_output.get("publications", [])) if ( limit is not None and limit <= len(publications) ) or not page_output.get("more", False): publications = publications[:limit] break page += 1 output = { "publications": publications, "more": page_output.get("more", False), } return output def delete_all_drafts(self): """ Returns: """ response = None while True: drafts = self.get_drafts(filter="draft", limit=10, offset=0) if len(drafts) == 0: break for draft in drafts: response = self.delete_draft(draft.get("id")) return response def get_sections(self): """ Get a list of the sections of your publication. TODO: this is hacky but I cannot find another place where to get the sections. Returns: """ response = self._session.get( f"{self.publication_url}/subscriptions", ) content = Api._handle_response(response=response) sections = [ p.get("sections") for p in content.get("publications") if p.get("hostname") in self.publication_url ] return sections[0] def publication_embed(self, url): """ Args: url: Returns: """ return self.call("/publication/embed", "GET", url=url) def call(self, endpoint, method, **params): """ Args: endpoint: method: **params: Returns: """ response = self._session.request( method=method, url=f"{self.publication_url}/{endpoint}", params=params, ) return Api._handle_response(response=response) |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |