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/post.py at main · ericpberry/python-substack Expand file tree/ Copy pathpost.pyMore file actions 847 lines (708 loc) · 30 KB / Copy pathpost.pyFile metadata and controls847 lines (708 loc) · 30 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 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 """ Post Utilities """ import json import re from typing import Dict, List __all__ = ["Post", "parse_inline", "tokens_to_text_nodes"] from substack.exceptions import SectionNotExistsException def tokens_to_text_nodes(tokens: List[Dict]) -> List[Dict]: """Convert parse_inline() tokens to ProseMirror text nodes. parse_inline() returns {"content": "text", "marks": [...]}. ProseMirror expects {"type": "text", "text": "text", "marks": [...]}. """ nodes = [] for token in tokens: if not token or not token.get("content"): continue node = {"type": "text", "text": token["content"]} marks = token.get("marks") if marks: node["marks"] = marks nodes.append(node) return nodes def parse_inline(text: str) -> List[Dict]: """ Convert inline Markdown in a text string into a list of tokens for use in the post content. Supported formatting: - `code`: Text wrapped in backticks. - **Bold**: Text wrapped in double asterisks. - *Italic*: Text wrapped in single asterisks. - ***Bold+Italic***: Text wrapped in triple asterisks. - ~~Strikethrough~~: Text wrapped in double tildes. - [Links]: Text wrapped in square brackets followed by URL in parentheses. Args: text: Text string containing inline Markdown formatting. Returns: List of token dictionaries with content and marks. Example: >>> parse_inline("This is **bold** and this is [a link](https://example.com)") [{'content': 'This is '}, {'content': 'bold', 'marks': [{'type': 'strong'}]}, {'content': ' and this is '}, {'content': 'a link', 'marks': [{'type': 'link', 'attrs': {'href': 'https://example.com'}}]}] """ if not text: return [] tokens = [] # Pattern order matters: code > links > bold+italic > bold > italic > strikethrough code_pattern = r'`([^`]+)`' link_pattern = r'\[([^\]]+)\]\(([^)]+)\)' bold_italic_pattern = r'\*\*\*([^*]+)\*\*\*' bold_pattern = r'\*\*([^*]+)\*\*' italic_pattern = r'(?<!\*)\*([^*]+)\*(?!\*)' # Not preceded or followed by * strikethrough_pattern = r'~~([^~]+)~~' # Find all matches with their positions matches = [] # Inline code FIRST -- content inside backticks must not be parsed for other formatting for match in re.finditer(code_pattern, text): matches.append((match.start(), match.end(), "code", match.group(1), None)) # Links for match in re.finditer(link_pattern, text): # Skip if it's an image link (starts with ![) # But do NOT skip normal links at position 0. if match.start() == 0 or text[match.start()-1:match.start()+1] != "![": if not any(start <= match.start() < end for start, end, _, _, _ in matches): matches.append((match.start(), match.end(), "link", match.group(1), match.group(2))) # Bold+italic combo for match in re.finditer(bold_italic_pattern, text): if not any(start <= match.start() < end for start, end, _, _, _ in matches): matches.append((match.start(), match.end(), "bold_italic", match.group(1), None)) # Bold for match in re.finditer(bold_pattern, text): if not any(start <= match.start() < end for start, end, _, _, _ in matches): matches.append((match.start(), match.end(), "bold", match.group(1), None)) # Italic for match in re.finditer(italic_pattern, text): if not any(start <= match.start() < end for start, end, _, _, _ in matches): matches.append((match.start(), match.end(), "italic", match.group(1), None)) # Strikethrough for match in re.finditer(strikethrough_pattern, text): if not any(start <= match.start() < end for start, end, _, _, _ in matches): matches.append((match.start(), match.end(), "strikethrough", match.group(1), None)) # Sort matches by position matches.sort(key=lambda x: x[0]) # Build tokens last_pos = 0 for start, end, match_type, content, url in matches: # Add text before this match if start > last_pos: tokens.append({"content": text[last_pos:start]}) # Add the formatted content if match_type == "code": tokens.append({ "content": content, "marks": [{"type": "code"}] }) elif match_type == "link": tokens.append({ "content": content, "marks": [{"type": "link", "attrs": {"href": url}}] }) elif match_type == "bold_italic": tokens.append({ "content": content, "marks": [{"type": "strong"}, {"type": "em"}] }) elif match_type == "bold": tokens.append({ "content": content, "marks": [{"type": "strong"}] }) elif match_type == "italic": tokens.append({ "content": content, "marks": [{"type": "em"}] }) elif match_type == "strikethrough": tokens.append({ "content": content, "marks": [{"type": "strikethrough"}] }) last_pos = end # Add remaining text if last_pos < len(text): tokens.append({"content": text[last_pos:]}) # Filter out empty tokens tokens = [t for t in tokens if t.get("content")] return tokens class Post: """ Post utility class """ def __init__( self, title: str, subtitle: str, user_id, audience: str = None, write_comment_permissions: str = None, ): """ Args: title: subtitle: user_id: audience: possible values: everyone, only_paid, founding, only_free write_comment_permissions: none, only_paid, everyone (this field is a mess) """ self.draft_title = title self.draft_subtitle = subtitle self.draft_body = {"type": "doc", "content": []} self.draft_bylines = [{"id": int(user_id), "is_guest": False}] self.audience = audience if audience is not None else "everyone" self.draft_section_id = None self.section_chosen = True # TODO better understand the possible values and combinations with audience if write_comment_permissions is not None: self.write_comment_permissions = write_comment_permissions else: self.write_comment_permissions = self.audience def set_section(self, name: str, sections: list): """ Args: name: sections: Returns: """ section = [s for s in sections if s.get("name") == name] if len(section) != 1: raise SectionNotExistsException(name) section = section[0] self.draft_section_id = section.get("id") def add(self, item: Dict): """ Add item to draft body. Args: item: Returns: """ self.draft_body["content"] = self.draft_body.get("content", []) + [ {"type": item.get("type")} ] content = item.get("content") if item.get("type") == "captionedImage": self.captioned_image(**item) elif item.get("type") == "embeddedPublication": self.draft_body["content"][-1]["attrs"] = item.get("url") elif item.get("type") == "youtube2": self.youtube(item.get("src")) elif item.get("type") == "subscribeWidget": self.subscribe_with_caption(item.get("message")) elif item.get("type") == "codeBlock": self.code_block(item.get("content"), item.get("attrs", {})) else: if content is not None: self.add_complex_text(content) if item.get("type") == "heading": self.attrs(item.get("level", 1)) marks = item.get("marks") if marks is not None: self.marks(marks) return self def paragraph(self, content=None): """ Args: content: Returns: """ item = {"type": "paragraph"} if content is not None: item["content"] = content return self.add(item) def heading(self, content=None, level: int = 1): """ Args: content: level: Returns: """ item = {"type": "heading"} if content is not None: item["content"] = content item["level"] = level return self.add(item) def blockquote(self, content=None): """ Add a blockquote to the post. The blockquote wraps one or more paragraph nodes. Args: content: Text string or list of inline token dicts. When a plain string is provided it is wrapped in a single paragraph node. Returns: Self for method chaining. """ paragraphs: List[Dict] = [] if content is not None: if isinstance(content, str): tokens = parse_inline(content) text_nodes = [ {"type": "text", "text": t["content"]} for t in tokens if t ] if text_nodes: paragraphs.append({"type": "paragraph", "content": text_nodes}) elif isinstance(content, list): for item in content: if isinstance(item, dict) and item.get("type") == "paragraph": paragraphs.append(item) elif isinstance(item, dict): text_nodes = [{"type": "text", "text": item.get("content", "")}] paragraphs.append({"type": "paragraph", "content": text_nodes}) node: Dict = {"type": "blockquote"} if paragraphs: node["content"] = paragraphs self.draft_body["content"] = self.draft_body.get("content", []) + [node] return self def horizontal_rule(self): """ Returns: """ return self.add({"type": "horizontal_rule"}) def attrs(self, level): """ Args: level: Returns: """ content_attrs = self.draft_body["content"][-1].get("attrs", {}) content_attrs.update({"level": level}) self.draft_body["content"][-1]["attrs"] = content_attrs return self def captioned_image( self, src: str, fullscreen: bool = False, imageSize: str = "normal", height: int = 819, width: int = 1456, resizeWidth: int = 728, bytes: str = None, alt: str = None, title: str = None, type: str = None, href: str = None, belowTheFold: bool = False, internalRedirect: str = None, ): """ Add image to body. Args: bytes: alt: title: type: href: belowTheFold: internalRedirect: src: fullscreen: imageSize: height: width: resizeWidth: """ content = self.draft_body["content"][-1].get("content", []) content += [ { "type": "image2", "attrs": { "src": src, "fullscreen": fullscreen, "imageSize": imageSize, "height": height, "width": width, "resizeWidth": resizeWidth, "bytes": bytes, "alt": alt, "title": title, "type": type, "href": href, "belowTheFold": belowTheFold, "internalRedirect": internalRedirect, }, } ] self.draft_body["content"][-1]["content"] = content return self def text(self, value: str): """ Add text to the last paragraph. Args: value: Text to add to paragraph. Returns: """ content = self.draft_body["content"][-1].get("content", []) content += [{"type": "text", "text": value}] self.draft_body["content"][-1]["content"] = content return self def add_complex_text(self, text): """ Args: text: """ if isinstance(text, str): self.text(text) else: for chunk in text: if chunk: self.text(chunk.get("content")).marks(chunk.get("marks", [])) def marks(self, marks): """ Args: marks: Returns: """ content = self.draft_body["content"][-1].get("content", [])[-1] content_marks = content.get("marks", []) for mark in marks: new_mark = {"type": mark.get("type")} if mark.get("type") == "link": href = mark.get("href") or mark.get("attrs", {}).get("href") new_mark.update({"attrs": {"href": href}}) content_marks.append(new_mark) content["marks"] = content_marks return self def remove_last_paragraph(self): """Remove last paragraph""" del self.draft_body.get("content")[-1] def get_draft(self): """ Returns: """ out = vars(self) out["draft_body"] = json.dumps(out["draft_body"]) return out def subscribe_with_caption(self, message: str = None): """ Add subscribe widget with caption Args: message: Returns: """ if message is None: message = """Thanks for reading this newsletter! Subscribe for free to receive new posts and support my work.""" subscribe = self.draft_body["content"][-1] subscribe["attrs"] = { "url": "%%checkout_url%%", "text": "Subscribe", "language": "en", } subscribe["content"] = [ { "type": "ctaCaption", "content": [ { "type": "text", "text": message, } ], } ] return self def youtube(self, value: str): """ Add youtube video to post. Args: value: youtube url Returns: """ content_attrs = self.draft_body["content"][-1].get("attrs", {}) content_attrs.update({"videoId": value}) self.draft_body["content"][-1]["attrs"] = content_attrs return self def code_block(self, content, attrs=None): """ Add code block to post. Args: content: String containing code or list of text nodes attrs: Optional attributes like language Returns: """ if attrs is None: attrs = {} # Handle content - can be list of text nodes or a string if isinstance(content, str): # Convert string to list of text nodes code_content = [{"type": "text", "text": content}] elif isinstance(content, list): code_content = content else: code_content = [] # Set up the code block structure code_block = self.draft_body["content"][-1] code_block["content"] = code_content if attrs: code_block["attrs"] = attrs return self def from_markdown(self, markdown_content: str, api=None): """ Parse Markdown content and add it to the post. Supported Markdown features: - Headings: Lines starting with '#' characters (1-6 levels) - Images: Markdown image syntax  - Linked images: [](link_url) - images that are also links - Links: [text](url) - inline links in paragraphs - Code blocks: Fenced code blocks with ```language or ``` - Blockquotes: Lines starting with '>' (consecutive lines grouped) - Paragraphs: Regular text blocks - Bullet lists: Lines starting with '*' or '-' - Ordered lists: Lines starting with '1.', '2.', etc. - Horizontal rules: Lines with ---, ***, or ___ - Inline formatting: **bold**, *italic*, ***bold+italic***, `code`, ~~strikethrough~~ Args: markdown_content: Markdown string to parse and add to the post. api: Optional Api instance for uploading local images. If provided, local image paths will be uploaded via api.get_image(). Returns: Self for method chaining. Example: >>> post = Post("Title", "Subtitle", user_id) >>> post.from_markdown("# Heading\\n\\nThis is **bold** text with [a link](https://example.com).") """ lines = markdown_content.split("\n") blocks = [] current_block: List[str] = [] in_code_block = False code_block_language = None for line in lines: # Check for fenced code block start/end if line.strip().startswith("```"): if in_code_block: # End of code block if current_block: blocks.append({ "type": "code", "language": code_block_language, "content": "\n".join(current_block) }) current_block = [] in_code_block = False code_block_language = None else: # Start of code block if current_block: blocks.append({"type": "text", "content": "\n".join(current_block)}) current_block = [] # Extract language if specified language = line.strip()[3:].strip() code_block_language = language if language else None in_code_block = True continue if in_code_block: # Inside code block - collect lines as-is current_block.append(line) else: # Regular content if line.strip() == "": # Empty line - end current block if it has content if current_block: blocks.append({"type": "text", "content": "\n".join(current_block)}) current_block = [] else: current_block.append(line) # Add any remaining content if current_block: if in_code_block: blocks.append({ "type": "code", "language": code_block_language, "content": "\n".join(current_block) }) else: blocks.append({"type": "text", "content": "\n".join(current_block)}) # Process blocks for block in blocks: if block["type"] == "code": # Add code block code_content = block.get("content", "").strip() if code_content: # Substack uses "codeBlock" type code_attrs = {} if block.get("language"): code_attrs["language"] = block["language"] self.add({ "type": "codeBlock", "content": code_content, # Pass as string, code_block method will handle it "attrs": code_attrs }) else: # Process text block text_content = block.get("content", "").strip() if not text_content: continue # Check for horizontal rule: ---, ***, ___ if re.match(r'^(\*{3,}|-{3,}|_{3,})\s*$', text_content): self.horizontal_rule() continue # Process headings (lines starting with '#' characters) if text_content.startswith("#"): level = len(text_content) - len(text_content.lstrip("#")) heading_text = text_content.lstrip("#").strip() if heading_text: # Only add if there's actual text self.heading(content=heading_text, level=min(level, 6)) # Process images using Markdown image syntax:  # Also handle linked images: [](link_url) elif text_content.startswith("!") or (text_content.startswith("[") and "](link) linked_image_match = re.match(r'\[!\[([^\]]*)\]\(([^)]+)\)\]\(([^)]+)\)', text_content) if linked_image_match: # Linked image - create image with href alt_text = linked_image_match.group(1) image_url = linked_image_match.group(2) link_url = linked_image_match.group(3) # Adjust image URL if it starts with a slash image_url = image_url[1:] if image_url.startswith("/") else image_url # If api is provided and image_url is a local file, upload it if api is not None: try: image = api.get_image(image_url) image_url = image.get("url") except Exception: # If upload fails, use original URL pass self.add({ "type": "captionedImage", "src": image_url, "alt": alt_text, "href": link_url }) else: # Regular image:  match = re.match(r"!\[.*?\]\((.*?)\)", text_content) if match: image_url = match.group(1) # Adjust image URL if it starts with a slash image_url = image_url[1:] if image_url.startswith("/") else image_url # If api is provided and image_url is a local file, upload it if api is not None: try: image = api.get_image(image_url) image_url = image.get("url") except Exception: # If upload fails, use original URL pass self.add({"type": "captionedImage", "src": image_url}) # Process paragraphs, bullet lists, ordered lists, or blockquotes else: if "\n" in text_content: # Process each line, grouping consecutive bullets/ordered items # into list nodes and consecutive blockquote lines into a # single blockquote node. pending_bullets: List[List[Dict]] = [] pending_quotes: List[str] = [] pending_ordered: List[List[Dict]] = [] def flush_bullets(): if not pending_bullets: return list_items = [] for bullet_nodes in pending_bullets: list_items.append({ "type": "list_item", "content": [{"type": "paragraph", "content": bullet_nodes}], }) self.draft_body["content"].append( {"type": "bullet_list", "content": list_items} ) pending_bullets.clear() def flush_quotes(): if not pending_quotes: return paragraphs: List[Dict] = [] for quote_line in pending_quotes: tokens = parse_inline(quote_line) text_nodes = tokens_to_text_nodes(tokens) if text_nodes: paragraphs.append({"type": "paragraph", "content": text_nodes}) node: Dict = {"type": "blockquote"} if paragraphs: node["content"] = paragraphs self.draft_body["content"].append(node) pending_quotes.clear() def flush_ordered(): if not pending_ordered: return list_items = [] for item_nodes in pending_ordered: list_items.append({ "type": "list_item", "content": [{"type": "paragraph", "content": item_nodes}], }) self.draft_body["content"].append( {"type": "ordered_list", "content": list_items} ) pending_ordered.clear() for line in text_content.split("\n"): line = line.strip() if not line: flush_bullets() flush_ordered() flush_quotes() continue # Check for blockquote marker if line.startswith("> ") or line == ">": flush_bullets() flush_ordered() quote_text = line[2:] if line.startswith("> ") else "" pending_quotes.append(quote_text) continue # Check for ordered list marker ordered_match = re.match(r'^(\d+)\.\s+(.*)', line) if ordered_match: flush_bullets() flush_quotes() item_text = ordered_match.group(2).strip() tokens = parse_inline(item_text) text_nodes = tokens_to_text_nodes(tokens) if text_nodes: pending_ordered.append(text_nodes) continue # Check for bullet marker bullet_text = None if line.startswith("* "): bullet_text = line[2:].strip() elif line.startswith("- "): bullet_text = line[2:].strip() elif line.startswith("*") and not line.startswith("**"): bullet_text = line[1:].strip() if bullet_text is not None: flush_ordered() flush_quotes() tokens = parse_inline(bullet_text) text_nodes = tokens_to_text_nodes(tokens) if text_nodes: pending_bullets.append(text_nodes) else: flush_bullets() flush_ordered() flush_quotes() tokens = parse_inline(line) self.add({"type": "paragraph", "content": tokens}) flush_bullets() flush_ordered() flush_quotes() else: # Single line — blockquote, ordered list, or paragraph if text_content.startswith("> ") or text_content == ">": quote_text = text_content[2:] if text_content.startswith("> ") else "" tokens = parse_inline(quote_text) text_nodes = tokens_to_text_nodes(tokens) para = {"type": "paragraph", "content": text_nodes} if text_nodes else {"type": "paragraph"} self.draft_body["content"] = self.draft_body.get("content", []) + [ {"type": "blockquote", "content": [para]} ] elif re.match(r'^(\d+)\.\s+(.*)', text_content): ordered_match = re.match(r'^(\d+)\.\s+(.*)', text_content) item_text = ordered_match.group(2).strip() tokens = parse_inline(item_text) text_nodes = tokens_to_text_nodes(tokens) if text_nodes: list_item = { "type": "list_item", "content": [{"type": "paragraph", "content": text_nodes}], } self.draft_body["content"].append( {"type": "ordered_list", "content": [list_item]} ) else: tokens = parse_inline(text_content) self.add({"type": "paragraph", "content": tokens}) return self |
| 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. |